palbase 0.9.1 → 0.10.1
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/README.md +72 -1
- package/dist/ai/index.js +2 -2
- package/dist/backend/engine.js +2 -2
- package/dist/backend/env.js +1 -1
- package/dist/backend/index.js +5 -5
- package/dist/backend/stack.js +1 -1
- package/dist/backend/test.js +2 -2
- package/dist/chunks/{OV2D7HYG.js → 6N3E2XHZ.js} +1 -1
- package/dist/chunks/{CNUOWB6T.js → APTIATSC.js} +2 -2
- package/dist/chunks/{KUFTU2AJ.js → EUI3Y3LO.js} +3 -3
- package/dist/chunks/{4DDSGFFD.js → FHXGE2MX.js} +1 -1
- package/dist/chunks/{CJPHHWRE.js → INRWHOEW.js} +2 -2
- package/dist/chunks/{6RX5KVMR.js → IVJCGBYG.js} +2 -2
- package/dist/chunks/MFMA46HN.js +2 -0
- package/dist/chunks/{MALOKTVW.js → NBI5LPMS.js} +2 -2
- package/dist/chunks/{BKOIWNJP.js → NGS4ALOE.js} +1 -1
- package/dist/chunks/{WPE6J77U.js → PG7BO4MR.js} +1 -1
- package/dist/chunks/{5UI3Q5JO.js → QC2SDBJD.js} +2 -2
- package/dist/chunks/{2DWAHEYE.js → QD3SPM7D.js} +2 -2
- package/dist/chunks/{SE3MXMQD.js → QW3V2NBT.js} +2 -2
- package/dist/chunks/{ZRV54HT6.js → R4OLJRMH.js} +2 -2
- package/dist/chunks/{I56MGYTD.js → RO7ERCT3.js} +2 -2
- package/dist/chunks/{XGWTZGWR.js → RWGEPDRQ.js} +2 -2
- package/dist/chunks/{YSTCOQFT.js → UDAWSJMT.js} +2 -2
- package/dist/chunks/{2GF6TA4C.js → XYXBDSXW.js} +1 -1
- package/dist/chunks/{ZHHMA7V4.js → YQEM4H7U.js} +2 -2
- package/dist/chunks/{XSPSDUZA.js → Z4A62VQR.js} +2 -2
- package/dist/cli.js +124 -130
- package/dist/refuse/ai.js +1 -1
- package/dist/refuse/backend.js +1 -1
- package/dist/refuse/server.js +1 -1
- package/dist/server/index.js +2 -2
- package/dist/server/testing.js +2 -2
- package/dist/web/index.js +2 -2
- package/dist/web/message.js +2 -2
- package/dist/web/palbe.js +2 -2
- package/dist/web/paywall.js +2 -2
- package/dist/web/push-sw.js +1 -1
- package/dist/web/ssr.js +2 -2
- package/dist/web/vite.js +2 -2
- package/package.json +21 -2
- package/types/backend/src/decorators.d.ts +9 -6
- package/types/backend/src/errors.d.ts +1 -1
- package/types/backend/src/gateways.d.ts +1 -1
- package/types/backend/src/runtime.d.ts +5 -5
- package/types/backend/src/services.d.ts +2 -8
- package/types/backend/src/upload.d.ts +1 -1
- package/types/backend/src/webhooks.d.ts +2 -2
- package/types/server/src/testing.d.ts +0 -6
- package/types/web/src/backends.d.ts +2 -2
- package/dist/chunks/PUILCUFX.js +0 -2
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
1
|
+
/*! palbase 0.10.1 — Palbase SDK License (see LICENSE) */
|
|
2
2
|
var Rt=d=>[...new Uint8Array(d)].map(t=>t.toString(16).padStart(2,"0")).join(""),At=d=>`pw-font-${d}`;function ne(d){return(typeof d=="string"?/^asset:([0-9a-f-]{36})$/.exec(d):null)?.[1]}async function an(d,t={}){let a={},l=t.fetch??((c,p)=>globalThis.fetch(c,p));return await Promise.all(d.map(async c=>{try{if(!/^https:\/\//.test(c.url))return;let p=await l(c.url,{signal:t.signal,credentials:"omit"});if(!p.ok)return;let g=await p.arrayBuffer();if(g.byteLength!==c.bytes&&c.bytes>0||Rt(await globalThis.crypto.subtle.digest("SHA-256",g))!==c.sha256.toLowerCase())return;let w=_t(c.kind,new Uint8Array(g));if(w===void 0)return;let y=await Et(c,g,w,t);y&&(a[c.id]=y)}catch{}})),a}var C=(d,t,a=0)=>d.length>=a+t.length&&t.every((l,c)=>d[a+c]===l),W=d=>[...d].map(t=>t.charCodeAt(0));function _t(d,t){switch(d){case"image":return C(t,[137,80,78,71,13,10,26,10])?"image/png":C(t,[255,216,255])?"image/jpeg":C(t,W("RIFF"))&&C(t,W("WEBP"),8)?"image/webp":void 0;case"video":return C(t,W("ftyp"),4)?C(t,W("qt "),8)?"video/quicktime":"video/mp4":C(t,[26,69,223,163])?"video/webm":void 0;case"font":return C(t,W("wOF2"))?"font/woff2":C(t,W("wOFF"))?"font/woff":C(t,W("OTTO"))?"font/otf":C(t,[0,1,0,0])||C(t,W("true"))?"font/ttf":void 0;case"html":return C(t,[80,75,3,4])||C(t,[80,75,5,6])?"application/zip":void 0;default:return}}async function Et(d,t,a,l){switch(d.kind){case"image":case"video":return{kind:d.kind,url:URL.createObjectURL(new Blob([t],{type:a}))};case"font":{let c=At(d.id),p=globalThis.FontFace,g=l.fonts??globalThis.document?.fonts;if(!p||!g)return;let h=new p(c,t,{display:"block"});return await h.load(),g.add(h),{kind:"font",url:"",family:c}}case"html":{let c=await Lt(new Uint8Array(t)),p=Ot(c);return p===void 0?void 0:{kind:"html",url:"",html:p}}}}async function Lt(d){let t=new DataView(d.buffer,d.byteOffset,d.byteLength),a=-1;for(let h=d.length-22;h>=Math.max(0,d.length-22-65535);h--)if(t.getUint32(h,!0)===101010256){a=h;break}if(a<0)throw new Error("not a zip");let l=t.getUint16(a+10,!0),c=t.getUint32(a+16,!0),p=new Map,g=0;for(let h=0;h<l;h++){if(t.getUint32(c,!0)!==33639248)throw new Error("a broken zip");let w=t.getUint16(c+10,!0),y=t.getUint32(c+20,!0),m=t.getUint32(c+24,!0),v=t.getUint16(c+28,!0),_=t.getUint16(c+30,!0),P=t.getUint16(c+32,!0),R=t.getUint32(c+42,!0),x=new TextDecoder().decode(d.subarray(c+46,c+46+v));if(c+=46+v+_+P,x.endsWith("/"))continue;if(x.startsWith("/")||x.split("/").includes(".."))throw new Error("a path leaving the zip");if(g+=m,p.size>=200||g>20971520)throw new Error("a zip too large");let T=R+30+t.getUint16(R+26,!0)+t.getUint16(R+28,!0),O=d.subarray(T,T+y);if(w===0)p.set(x,O);else if(w===8)p.set(x,await Pt(O));else throw new Error("a zip entry compressed another way")}return p}async function Pt(d){let t=new Response(new Uint8Array(d)).body.pipeThrough(new DecompressionStream("deflate-raw"));return new Uint8Array(await new Response(t).arrayBuffer())}var Tt={html:"text/html",css:"text/css",js:"text/javascript",mjs:"text/javascript",json:"application/json",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",webp:"image/webp",gif:"image/gif",svg:"image/svg+xml",mp4:"video/mp4",webm:"video/webm",woff2:"font/woff2",woff:"font/woff",ttf:"font/ttf",otf:"font/otf"};function qe(d,t){let a=Tt[d.split(".").pop()?.toLowerCase()??""]??"application/octet-stream",l="";for(let c=0;c<t.length;c+=32768)l+=String.fromCharCode(...t.subarray(c,c+32768));return`data:${a};base64,${btoa(l)}`}var $t="default-src 'none'; img-src data:; media-src data:; font-src data:; style-src 'unsafe-inline' data:; script-src 'unsafe-inline' data:";function Ot(d){let t=d.get("index.html");if(!t)return;let a=new TextDecoder().decode(t),l=y=>new TextDecoder().decode(d.get(y)),c=y=>{let m=y.replace(/^\.\//,"").split(/[?#]/)[0];return d.has(m)?m:void 0},p=y=>y.replace(/url\(\s*(['"]?)([^'")]+)\1\s*\)/g,(m,v,_)=>{let P=c(_);return P?`url("${qe(P,d.get(P))}")`:m}),g=globalThis.DOMParser;if(!g)return;let h=new g().parseFromString(a,"text/html");for(let y of[...h.querySelectorAll('link[rel~="stylesheet"][href]')]){let m=c(y.getAttribute("href")),v=h.createElement("style");v.textContent=m?p(l(m)):"",y.replaceWith(v)}for(let y of[...h.querySelectorAll("style")])y.textContent=p(y.textContent??"");for(let y of[...h.querySelectorAll("[src], [href], [poster]")])for(let m of["src","href","poster"]){let v=y.getAttribute(m);if(v===null)continue;let _=c(v);_?y.setAttribute(m,qe(_,d.get(_))):/^(https?:)?\/\//i.test(v)&&y.removeAttribute(m)}for(let y of[...h.querySelectorAll("[style]")])y.setAttribute("style",p(y.getAttribute("style")??""));let w=h.createElement("meta");return w.setAttribute("http-equiv","Content-Security-Policy"),w.setAttribute("content",$t),h.head.prepend(w),`<!doctype html>${h.documentElement.outerHTML}`}var K=(d,t,a)=>`M${d-a} ${t}a${a} ${a} 0 1 0 ${2*a} 0a${a} ${a} 0 1 0 ${-2*a} 0`,de={ad_free:["M3 7h18v10H3z","M4 4l16 16"],bell:["M6 16v-5a6 6 0 0 1 12 0v5l2 2H4z","M10 21a2 2 0 0 0 4 0"],bolt:["M13 2L4 14h7l-1 8 9-12h-7z"],book:["M5 4h11a3 3 0 0 1 3 3v13H8a3 3 0 0 1-3-3z","M5 17a3 3 0 0 1 3-3h11"],chart:["M3 20h18","M6 20v-8","M11 20V5","M16 20v-6","M21 20V9"],chat:["M4 5h16v11H9l-5 4z"],check:["M5 12l5 5 9-10"],check_circle:[K(12,12,9),"M8 12l3 3 5-6"],clock:[K(12,12,9),"M12 7v5l3 2"],cloud:["M7 18a4 4 0 0 1-.5-7.97A6 6 0 0 1 18 9a4.5 4.5 0 0 1-.5 9z"],crown:["M3 8l4 4 5-7 5 7 4-4-2 11H5z"],download:["M12 4v11","M7 10l5 5 5-5","M4 20h16"],gift:["M3 9h18v4H3z","M5 13v8h14v-8","M12 9v12","M12 9C10 5 6 5 6 7.5S12 9 12 9zm0 0c2-4 6-4 6-1.5S12 9 12 9z"],globe:[K(12,12,9),"M3 12h18","M12 3a14 14 0 0 1 0 18a14 14 0 0 1 0-18z"],heart:["M12 20s-7-4.5-9-9a4.5 4.5 0 0 1 9-3 4.5 4.5 0 0 1 9 3c-2 4.5-9 9-9 9z"],infinity:["M7 9a3 3 0 1 0 0 6c3 0 7-6 10-6a3 3 0 1 1 0 6c-3 0-7-6-10-6z"],lock_open:["M5 11h14v10H5z","M8 11V7a4 4 0 0 1 7.5-2"],music:["M9 18V5l11-2v13",K(6,18,3),K(17,16,3)],people:[K(9,8,3.5),"M2 20a7 7 0 0 1 14 0","M16 4.5a3.5 3.5 0 0 1 0 7","M18 14a6 6 0 0 1 4 6"],person:[K(12,8,4),"M4 21a8 8 0 0 1 16 0"],photo:["M3 5h18v14H3z",K(8.5,9.5,1.5),"M3 17l5-5 4 4 3-3 6 6"],shield:["M12 3l8 3v6c0 5-3.5 8-8 9-4.5-1-8-4-8-9V6z"],sparkles:["M12 3l1.8 5.2L19 10l-5.2 1.8L12 17l-1.8-5.2L5 10l5.2-1.8z","M19 15l.8 2.2L22 18l-2.2.8L19 21l-.8-2.2L16 18l2.2-.8z"],star:["M12 3l2.8 5.7 6.2.9-4.5 4.4 1 6.2L12 17.3l-5.5 2.9 1-6.2L3 9.6l6.2-.9z"],video:["M3 6h12v12H3z","M15 10l6-3v10l-6-3z"],arrow_right:["M4 12h15","M13 6l6 6-6 6"],calendar:["M4 6h16v15H4z","M4 10h16","M8 3v5","M16 3v5"],close:["M6 6l12 12","M18 6L6 18"],lock:["M5 11h14v10H5z","M8 11V7a4 4 0 0 1 8 0v4"],play:["M7 4l13 8-13 8z"],quote:["M5 17c3 0 4-2 4-5V7H4v5h3","M15 17c3 0 4-2 4-5V7h-5v5h3"],trophy:["M7 4h10v5a5 5 0 0 1-10 0z","M7 6H4v2a3 3 0 0 0 3 3","M17 6h3v2a3 3 0 0 1-3 3","M12 14v4","M8 21h8","M9 18h6v3H9z"]};var Be="http://www.w3.org/2000/svg";function pe(d,t,a){let l=d.createElementNS(Be,"svg");l.setAttribute("viewBox","0 0 24 24"),l.setAttribute("width",String(a)),l.setAttribute("height",String(a)),l.setAttribute("fill","none"),l.setAttribute("stroke","currentColor"),l.setAttribute("stroke-width","2"),l.setAttribute("stroke-linecap","round"),l.setAttribute("stroke-linejoin","round"),l.setAttribute("aria-hidden","true"),l.setAttribute("focusable","false");for(let c of t){let p=d.createElementNS(Be,"path");p.setAttribute("d",c),l.append(p)}return l}var dn=2,pn=2,f=(d,t=!1)=>({kind:"value",value:"plain",def:d,required:t}),j=d=>({kind:"value",value:"color",def:d}),We=d=>({kind:"value",value:"spacing",def:d}),zt=d=>({kind:"value",value:"radius",def:d}),X=(d=!1)=>({kind:"text",required:d}),Me=(d,t=!1)=>({kind:"list",item:d,required:t}),se=(d,t=!1)=>({kind:"object",item:d,required:t}),Ke=(d=!1)=>({kind:"component",required:d}),Re={kind:"components"},Ge={stack:{axis:f("vertical"),spacing:We(0),align:f("center"),distribution:f("start"),scroll:f(!1),children:Re},text:{text:X(),spans:Me("span"),font:f(),size:f(),weight:f(),line_height:f(),letter_spacing:f(),color:{kind:"value",value:"textColor",def:"text"},align:f("center"),max_lines:f(),uppercase:f(!1)},image:{src:f(void 0,!0),fit:f("fit"),aspect:f(),mask:se("mask"),overlay:{kind:"value",value:"textColor"},alt:X(),decorative:f(!1)},icon:{name:f(void 0,!0),color:j("accent"),size:f(24)},video:{src:f(void 0,!0),poster:f(),autoplay:f(!0),loop:f(!0),mute:f(!0),controls:f(!1),fit:f("fill"),aspect:f(),alt:X()},button:{action:se("action",!0),content:Ke(!0)},purchase_button:{content:Ke(!0),package:f()},package:{product:f(void 0,!0),plan:f(void 0,!0),selected:f(!1),offer:f(),children:Re},tabs:{},switch:{},carousel:{pages:Re,peek:f(0),spacing:f(8),loop:f(!1),auto_advance_ms:f(),indicator:se("indicator"),height:f("")},countdown:{},timeline:{items:Me("timeline_item",!0),line_color:j("accent"),line_width:f(2),icon_color:j("on_accent"),color:j("text"),spacing:f(16)},features:{items:Me("feature",!0),icon_color:j("accent"),color:j("text"),spacing:f(12)},spacer:{size:We()},divider:{color:j("muted"),thickness:f(1)},custom_html:{src:f(void 0,!0),height:f("",!0)}},Ht={style:{padding:{kind:"edges"},margin:{kind:"edges"},width:f(""),height:f(""),max_width:f(),background:{kind:"fill"},border:se("border"),corners:{kind:"corners"},shadow:se("shadow"),opacity:f(1)},border:{width:f(),color:j("")},shadow:{color:j(""),radius:f(0),x:f(0),y:f(0)},linear:{type:f(""),angle:f(180),stops:f()},radial:{type:f(""),center_x:f(.5),center_y:f(.5),radius:f(.5),stops:f()},image_fill:{type:f(""),src:f(),fit:f("fill")},video_fill:{type:f(""),src:f(),poster:f(),loop:f(!0)},animation:{type:f(""),duration_ms:f(300),delay_ms:f(0),easing:f("ease_out")},action:{type:f(""),url:f(),sheet:f(),package:f()},mask:{shape:f(""),radius:zt(0),depth:f(16)},span:{text:X(!0),bold:f(!1),italic:f(!1),underline:f(!1),strikethrough:f(!1),color:j(""),link:f()},timeline_item:{icon:f(void 0,!0),title:X(!0),text:X(),color:j("")},feature:{icon:f(void 0,!0),text:X(!0)},indicator:{style:f("dots"),color:j("muted"),active_color:j("accent"),size:f(8),spacing:f(6)},typography:{font:f("system"),size:f(),weight:f(400),line_height:f(),letter_spacing:f(0),text_style:f("body")}},Xe=new Set(["package","purchase_button"]),Ct={action:{type:f(""),url:f(),link:f(),sheet:f(),placement:f(),name:f(),value:f(),offer:f(),dismiss:f(!0)},presentation:{type:f(""),position:f("bottom"),auto_dismiss_seconds:f(),dismissible:f(!0),backdrop:j("#00000080")}},jt={modal:["type","dismissible","backdrop"],fullscreen:["type"],banner:["type","position","auto_dismiss_seconds","dismissible"],card:["type"]},Ft={linear:"linear",radial:"radial",image:"image_fill",video:"video_fill"},Nt=["top","bottom","leading","trailing"],Dt=["top_leading","top_trailing","bottom_leading","bottom_trailing"],Jt=Object.keys(Ge),un=Jt.filter(d=>!Xe.has(d)),Ye=/\{\{\s*([^{}]*?)\s*\}\}/g,Q=(d,t)=>typeof d=="object"&&d!==null&&Object.hasOwn(d,t),M=d=>typeof d=="object"&&d!==null&&!Array.isArray(d)?d:{},I=d=>Array.isArray(d)?d:[],G=(d,t)=>d??t;function It(d){let t="";for(let a of new TextEncoder().encode(d)){let l=String.fromCharCode(a);t+=/^[A-Za-z0-9._~-]$/.test(l)?l:`%${a.toString(16).toUpperCase().padStart(2,"0")}`}return t}function Vt(d){let t=Math.floor(d/86400),a=Math.floor(d%86400/3600),l=Math.floor(d%3600/60),c=d%60,p=h=>String(h).padStart(2,"0");return{countdown:t>0?`${t}d ${p(a)}:${p(l)}:${p(c)}`:a>0?`${a}:${p(l)}:${p(c)}`:`${p(l)}:${p(c)}`,days:String(t),hours:p(a),minutes:p(l),seconds:p(c)}}function fn(d){let t=[],a=c=>{if(Array.isArray(c))return c.forEach(a);if(typeof c!="object"||c===null)return;let p=c;if(p.type==="package"&&typeof p.product=="string"&&typeof p.plan=="string"){let g=`${p.product}.${p.plan}`;t.includes(g)||t.push(g)}for(let g of Object.keys(p).sort())a(p[g])},l=d;for(let c of["header","root","footer"])a(l[c]);for(let c of Object.keys(M(l.sheets)).sort())a(M(M(l.sheets)[c]).root);return t}function Ut(d){let t=new Map,a=c=>{if(Array.isArray(c))return c.forEach(a);if(typeof c!="object"||c===null)return;let p=c;if(p.type==="package"&&typeof p.offer=="string"){let g=`${p.product}.${p.plan}`;t.has(g)||t.set(g,p.offer)}for(let g of Object.keys(p).sort())a(p[g])},l=d;for(let c of["header","root","footer","sheets"])a(l[c]);return t}function gn(d,t){return _e(d,t).tree}function _e(d,t){return new ue("paywall",d,t).resolve()}function hn(d,t){return Ee(d,t).tree}function Ee(d,t){let{variables:a,...l}=t;return new ue("message",d,{...l,packages:{"":{...a}}}).resolve()}var ue=class{kind;d;opts;lang;texts={};palette;typography={};radii;spacing;packages;offers;selected="";tab="";paths=new WeakMap;tabsShown={};switchesOn={};countdowns={};constructor(t,a,l){this.kind=t,this.d=a,this.opts=l,this.offers=Ut(a);let c={};for(let[y,m]of Object.entries(l.packages??{})){let v={...m};this.open(y)||(m.price!==void 0?v.offer_price=m.price:delete v.offer_price),c[y]=v}this.packages=c;let p=M(this.d.locales),g=String(this.d.default_locale??""),h=l.locale;Q(p,h)||(h=h.split("-")[0]??"",Q(p,h)||(h=g)),this.lang=h;for(let y of[g,h])for(let[m,v]of Object.entries(M(p[y])))typeof v=="string"&&(this.texts[m]=v);let w=M(this.d.theme);this.palette=M(M(w.colors)[l.appearance]);for(let[y,m]of Object.entries(M(w.typography))){let v={};for(let[_,P]of Object.entries(this.objectFields("typography"))){let R=G(M(m)[_],P.def);R!=null&&(v[_]=R)}this.typography[y]=v}this.radii=M(w.radii),this.spacing=M(w.spacing)}open(t){let a=this.offers.get(t);return a!==void 0&&(this.opts.offers??[]).includes(a)}fields(t){if(!(this.kind==="message"&&Xe.has(t)))return Ge[t]}objectFields(t){return(this.kind==="message"?Ct[t]:void 0)??Ht[t]??{}}resolve(){let[t,a]=this.initialState();this.tab=t,this.selected=this.kind==="paywall"?a:"";let l={theme:{colors:this.palette,typography:this.typography,radii:this.radii,spacing:this.spacing}};this.kind==="paywall"&&(l.selected=a);let c=this.d.presentation;if(typeof c=="object"&&c!==null){let g=this.item("presentation",M(c),void 0)??{},h=jt[String(M(c).type)]??[];for(let w of Object.keys(g))h.includes(w)||delete g[w];l.presentation=g}for(let g of["header","root","footer"]){let h=this.d[g];if(typeof h=="object"&&h!==null){let w=this.component(M(h),g,"",!1);w&&(l[g]=w)}}let p={};if(typeof this.d.sheets=="object"&&this.d.sheets!==null){let g={};for(let[h,w]of Object.entries(M(this.d.sheets))){let y=this.component(M(M(w).root),`sheets.${h}.root`,"",!1);y&&(g[h]=y);let m=this.text(M(w).title,this.packages[this.selected]);m!==null&&(p[h]=m)}l.sheets=g}return{tree:l,pathOf:g=>this.paths.get(g),tabs:this.tabsShown,switches:this.switchesOn,sheetTitles:p,countdowns:this.countdowns,language:this.lang}}switchOn(t,a){return this.opts.switches&&Object.hasOwn(this.opts.switches,a)?this.opts.switches[a]:this.opts.switch?this.opts.switch==="on":t.default===!0}tabShown(t,a){let c=I(t.tabs).map(M).map(g=>String(g.id)),p=this.opts.tabs?.[a];return p!==void 0&&c.includes(p)?p:this.opts.tab?this.opts.tab:typeof t.default=="string"&&t.default!==""?t.default:c[0]??""}initialState(){let t="",a="",l="",c="",p=(h,w)=>{if(Array.isArray(h)){h.forEach((m,v)=>p(m,`${w}[${v}]`));return}if(typeof h!="object"||h===null)return;let y=h;switch(y.type){case"package":{let m=`${y.product}.${y.plan}`;l===""&&(l=m),y.selected===!0&&a===""&&(a=m);break}case"switch":{let m=this.switchOn(y,w),v=m?y.on_package:y.off_package;typeof v=="string"&&c===""&&(c=v),p(m?y.on:y.off,`${w}.${m?"on":"off"}`);return}case"tabs":{let m=this.tabShown(y,w);t===""&&(t=m),I(y.tabs).forEach((v,_)=>{let P=M(v);P.id===m&&(typeof P.package=="string"&&c===""&&(c=P.package),p(P.content,`${w}.tabs[${_}].content`))});return}}for(let m of Object.keys(y).sort())m!=="sheets"&&p(y[m],w===""?m:`${w}.${m}`)};for(let h of["header","root","footer"])p(this.d[h],h);let g=this.opts.selected||c||a||l;return[t,g]}holds(t,a){let l=a||this.selected;for(let[c,p]of Object.entries(t))switch(c){case"selected_package":if(!I(p).includes(this.selected))return!1;break;case"intro_eligible":if((this.opts.eligible??[]).includes(l)!==p)return!1;break;case"offer_open":if(this.open(l)!==p)return!1;break;case"platform":if(!I(p).includes(this.opts.platform))return!1;break;case"locale":if(!I(p).includes(this.opts.locale)&&!I(p).includes(this.lang))return!1;break;case"appearance":if(p!==this.opts.appearance)return!1;break;case"tab":if(p!==this.tab)return!1;break}return!0}component(t,a,l,c){if(typeof t.visible=="object"&&t.visible!==null&&!this.holds(M(t.visible),l))return null;let p=String(t.type),g=l,h=c;p==="package"&&(g=`${t.product}.${t.plan}`,h=g===this.selected);let w={type:p};this.paths.set(w,a),Q(t,"id")&&(w.id=t.id);let y={...M(t.style)};h&&Object.assign(y,M(M(t.states).selected)),Object.keys(y).length>0&&(w.style=this.style(y)),typeof t.animation=="object"&&t.animation!==null&&(w.animation=this.defaults(M(t.animation),this.objectFields("animation")));let m=this.packages[g||this.selected];switch(p){case"tabs":return this.tabs(t,w,a,g);case"switch":return this.switchOf(t,w,a,g,h);case"countdown":return this.countdown(t,w,a,g,h);case"purchase_button":{let v=typeof t.package=="string"?t.package:this.selected;w.package=v,this.open(v)&&(w.offer=this.offers.get(v));let _=this.component(M(t.content),`${a}.content`,v,h);return _?(w.content=_,w):null}case"package":w.product=t.product,w.plan=t.plan,w.selected=h,typeof t.offer=="string"&&(this.opts.offers??[]).includes(t.offer)&&(w.offer=t.offer)}for(let[v,_]of Object.entries(this.fields(p)??{})){if(p==="package"&&(v==="product"||v==="plan"||v==="selected"||v==="offer"))continue;let P=t[v],R=Q(t,v);switch(_.kind){case"component":{if(!R)continue;let x=this.component(M(P),`${a}.${v}`,g,h);if(!x&&_.required)return null;x&&(w[v]=x);break}case"components":{let x=[];I(P).forEach((T,O)=>{let V=this.component(M(T),`${a}.${v}[${O}]`,g,h);V&&x.push(V)}),w[v]=x;break}case"text":{let x=this.text(P,m);if(x!==null)w[v]=x;else if(_.required||p==="text"&&v==="text"&&R)return null;break}case"list":{let x=[];for(let T of I(P)){let O=this.item(_.item,M(T),m);O&&x.push(O)}if(p==="text"&&x.length===0&&R)return null;R&&(w[v]=x);break}case"object":{if(R){let x=this.object(M(P),_.item,m);if(x===null&&_.required)return null;w[v]=x}else v==="indicator"&&(w[v]=this.object({},_.item,m));break}case"value":{let x=this.value(G(P,_.def),_);x!=null&&x!==""&&(w[v]=x);break}}}return p==="text"&&this.typeStyle(w),w}typeStyle(t){if(typeof t.size!="string"){t.size!==void 0&&t.size!==null&&(t.text_style="body");return}let a=this.typography[t.size];for(let l of["font","weight","line_height","letter_spacing","text_style"])!Q(t,l)&&a?.[l]!==void 0&&a?.[l]!==null&&(t[l]=a[l]);t.size=a?.size??null}tabs(t,a,l,c){let p=this.tabShown(t,l);this.tabsShown[l]=p;let g=[];return I(t.tabs).forEach((h,w)=>{let y=M(h),m=y.id===p,v=this.component(M(y.label),`${l}.tabs[${w}].label`,c,m);if(g.push({id:y.id,selected:m,label:v}),m){let _=this.component(M(y.content),`${l}.tabs[${w}].content`,c,!1);_&&(a.content=_)}}),a.tabs=g,typeof t.bar=="object"&&t.bar!==null&&(a.bar=this.style(M(t.bar))),a}switchOf(t,a,l,c,p){let g=this.switchOn(t,l);this.switchesOn[l]=g,a.on=g;let h=this.text(t.label,this.packages[c||this.selected]);h!==null&&(a.label=h),a.tint=this.color(String(G(t.tint,"accent")));let w=g?"on":"off",y=this.component(M(t[w]),`${l}.${w}`,c,p);return y&&(a.content=y),a}countdown(t,a,l,c,p){let g=M(t.target),h=this.opts.now??Date.now(),w;if(typeof g.after_open_seconds=="number"?w=Math.trunc(g.after_open_seconds)-(this.opts.openedSecondsAgo??0):w=Math.trunc((Date.parse(String(g.at))-h)/1e3),w>0){a.state="counting",a.remaining_seconds=w,this.countdowns[l]=w;let y=this.packages,m={};for(let[_,P]of Object.entries(y))m[_]={...P,...Vt(w)};this.packages=m;let v=this.component(M(t.counting),`${l}.counting`,c,p);return v&&(a.content=v),this.packages=y,a}if(a.state="ended",a.remaining_seconds=0,typeof t.ended=="object"&&t.ended!==null){let y=this.component(M(t.ended),`${l}.ended`,c,p);y&&(a.content=y)}return a}item(t,a,l){let c={};for(let[p,g]of Object.entries(this.objectFields(t))){let h=a[p];if(g.kind==="text"){let w=this.text(h,l);if(w!==null)c[p]=w;else if(g.required)return null}else{let w=g.def,y=this.value(G(h,w),g);y!=null&&(Q(a,p)||w!=null&&w!=="")&&(c[p]=y)}}return c}object(t,a,l){if(a==="style")return this.style(t);let c=this.item(a,t,l)??{};if(a==="action")for(let p of["url","link"]){if(typeof c[p]!="string")continue;let g=qt(c[p],l);if(g===null)return null;c[p]=g}return c}defaults(t,a){let l={};for(let[c,p]of Object.entries(a)){let g=G(t[c],p.def);g!=null&&g!==""&&(l[c]=g)}return l}style(t){let a={};for(let[l,c]of Object.entries(t)){let p=this.objectFields("style")[l];if(!p){a[l]=c;continue}switch(p.kind){case"edges":a[l]=this.sides(c,Nt,this.spacing);break;case"corners":a[l]=this.sides(c,Dt,this.radii);break;case"fill":a[l]=this.fill(c);break;case"object":{let g=M(c),h={};for(let[w,y]of Object.entries(this.objectFields(p.item))){let m=G(g[w],y.def);m!=null&&m!==""&&(h[w]=this.value(m,y))}a[l]=h;break}default:a[l]=c}}return a}sides(t,a,l){let c={};for(let p of a){let g=typeof t=="object"&&t!==null?G(M(t)[p],0):t;c[p]=Ae(g,l)}return c}fill(t){if(typeof t=="string")return{type:"color",color:this.color(t)};let a=M(t),l=this.defaults(a,this.objectFields(Ft[String(a.type)]??""));return Array.isArray(a.stops)&&(l.stops=a.stops.map(c=>({color:this.color(String(M(c).color)),at:M(c).at}))),l}value(t,a){if(a.kind!=="value")return t;switch(a.value){case"color":return typeof t=="string"&&t!==""?this.color(t):t;case"textColor":return typeof t=="string"?this.color(t):t==null?t:this.fill(t);case"spacing":return Ae(t,this.spacing);case"radius":return Ae(t,this.radii);default:return t}}color(t){let a=Object.hasOwn(this.palette,t)?this.palette[t]:void 0;return typeof a=="string"?a:t}text(t,a){let l;if(typeof t=="string")l=t;else if(typeof t=="object"&&t!==null&&!Array.isArray(t)){let p=t.t;l=typeof p=="string"&&Object.hasOwn(this.texts,p)?this.texts[p]:""}else return null;let c=!1;return l=l.replace(Ye,(p,g)=>{let h=a&&Object.hasOwn(a,g)?a[g]:void 0;return typeof h!="string"||h===""?(c=!0,""):h}),c||l.trim()===""?null:l}};function qt(d,t){let a=!1,l=d.replace(Ye,(c,p)=>{let g=t&&Object.hasOwn(t,p)?t[p]:void 0;return typeof g!="string"||g===""?(a=!0,""):It(g)});return a?null:l}function Ae(d,t){return typeof d=="string"?Object.hasOwn(t,d)?t[d]:null:d}var Bt={packages:"Choose a plan",close:"Close",restore:"Restore purchases",page:(d,t)=>`${d} of ${t}`},ee={system:'-apple-system, BlinkMacSystemFont, "SF Pro Text", system-ui, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif',rounded:'ui-rounded, "SF Pro Rounded", Nunito, "Varela Round", system-ui, -apple-system, sans-serif',serif:'ui-serif, "New York", "Iowan Old Style", Georgia, "Times New Roman", serif',mono:'ui-monospace, "SF Mono", Menlo, Consolas, "Liberation Mono", monospace'},Wt=1.35,Ze=20,Kt=new Set(["button","purchase_button","package","text"]),Gt=new Set(["ar","he","fa","ur","ps","yi","dv","ug","ku","sd"]),Qe={ease_out:"cubic-bezier(0.16, 1, 0.3, 1)",ease_in_out:"cubic-bezier(0.65, 0, 0.35, 1)",spring:"cubic-bezier(0.34, 1.56, 0.64, 1)"},Xt={start:"flex-start",center:"center",end:"flex-end",stretch:"stretch"},Yt={start:"flex-start",center:"center",end:"flex-end",space_between:"space-between",space_around:"space-around",space_evenly:"space-evenly"},Zt={stack:["children"],package:["children"],button:["content"],purchase_button:["content"],tabs:["tabs","content"],switch:["content"],carousel:["pages"],countdown:["content"]},Qt={package:["selected"],purchase_button:["package"],switch:["on"],countdown:["state","remaining_seconds"]},en=`
|
|
3
3
|
:host{display:block;height:100%}
|
|
4
4
|
.pw2{position:relative;box-sizing:border-box;display:flex;flex-direction:column;height:100%;overflow:hidden;font-family:${ee.system};font-size:1rem;line-height:1.3;-webkit-font-smoothing:antialiased;-webkit-text-size-adjust:100%;text-rendering:optimizeLegibility}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
2
|
-
import{a as D}from"./OV2D7HYG.js";import{a as A,b as P,c as R,d as x,e as O,f as j,g as M,h as C,i as L,j as U,k as K,l as N}from"./ZHHMA7V4.js";import{a as $,b as I}from"./I56MGYTD.js";import{b as S,d as w}from"./XGWTZGWR.js";var ae=/^pb_[a-z0-9]+_s/;function v(n){if(D())throw new TypeError("palbase/server runs on a server: its secret key never goes into a browser or a mobile app \u2014 apps use palbase/web (or the native SDKs) with the publishable key");if(typeof n.secretKey!="string"||!ae.test(n.secretKey))throw new TypeError("secretKey is the project secret key (pb_<ref>_s\u2026); a publishable key belongs in palbase/web");let e=I(w({baseUrl:n.url,credentials:{secretKey:n.secretKey},fetch:n.fetch,solveProofOfWork:n.solveProofOfWork??!1}),n.retry??$);return{ai:A.client(e),analytics:P.client(e),auth:R.client(e),cache:x.client(e),flags:O.client(e),machines:j.client(e),notify:M.client(e),purchases:C.client(e),realtime:L.client(e),secrets:U.client(e),storage:K.client(e),stores:N.client(e),transport:e,url:new URL(n.url).origin}}var f=class extends Error{code;constructor(e,t){super(t),this.name="WebhookSignatureError",this.code=e}},ue=300,de=/^[0-9]{1,12}$/,le=/^[0-9a-f]{64}$/,W=8,fe=/^whsec_[0-9A-Za-z]{32,}$/,he=1024*1024;async function B(n){if(typeof n.secret!="string"||!fe.test(n.secret))throw new TypeError("secret is the webhook endpoint secret (whsec_\u2026), not an API key");await F(n);let e;try{e=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(z(n.body)))}catch{throw new f("invalid_body","the signed body is not JSON")}if(!be(e))throw new f("invalid_body","the signed body is not a Palbase event (id, type, project_id, created_at, data)");return e}async function F(n){if(typeof n.secret!="string"||n.secret==="")throw new TypeError("secret is the key the request was signed with");let e=z(n.body),{t,v1:r}=H(n),s=await crypto.subtle.importKey("raw",new TextEncoder().encode(n.secret),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),o=new Uint8Array(await crypto.subtle.sign("HMAC",s,we(new TextEncoder().encode(`${t}.`),e))),a=!1;for(let u of r)me(o,ge(u))&&(a=!0);if(!a)throw new f("signature_mismatch","no v1 in Palbase-Signature is this body signed with this secret")}function H(n){let e=n.toleranceSeconds??ue;if(!Number.isFinite(e)||e<0)throw new TypeError(`toleranceSeconds is a number of seconds, 0 or more (got ${String(n.toleranceSeconds)})`);let t=(n.now??Date.now)();if(!Number.isFinite(t))throw new TypeError(`now() returns epoch milliseconds (got ${String(t)})`);let r=n.signature;if(typeof r!="string"||r.trim()==="")throw new f("missing_signature","the request carries no Palbase-Signature header");let s,o=[];for(let a of r.split(",")){let u=a.indexOf("=");if(u<=0)throw new f("malformed_signature","Palbase-Signature is t=<seconds>,v1=<hex>");let c=a.slice(0,u).trim(),i=a.slice(u+1).trim();if(c==="t"){if(s!==void 0||!de.test(i))throw new f("malformed_signature","Palbase-Signature carries one t, in unix seconds");s=i}else if(c==="v1"){if(!le.test(i))throw new f("malformed_signature","a v1 is 64 lowercase hex characters");if(o.length===W)throw new f("malformed_signature",`Palbase-Signature carries at most ${W} v1`);o.push(i)}}if(s===void 0||o.length===0)throw new f("malformed_signature","Palbase-Signature is t=<seconds>,v1=<hex>");if(Math.abs(t/1e3-Number(s))>e)throw new f("stale_timestamp",`the signature's time is more than ${e} s from now: an old delivery sent again is not taken`);return{t:s,v1:o}}async function pe(n,e,t={}){let r=await ye(n,t.maxBytes??he);return B({toleranceSeconds:t.toleranceSeconds,now:t.now,secret:e,signature:n.headers.get("palbase-signature"),body:r})}async function ye(n,e){let t=()=>new f("body_too_large",`the body is larger than ${e} bytes`),r=Number(n.headers.get("content-length")??"NaN");if(Number.isFinite(r)&&r>e)throw t();if(!n.body)return new Uint8Array(0);let s=n.body.getReader(),o=[],a=0;for(;;){let{done:i,value:l}=await s.read();if(i)break;if(a+=l.byteLength,a>e)throw await s.cancel().catch(()=>{}),t();o.push(l)}let u=new Uint8Array(a),c=0;for(let i of o)u.set(i,c),c+=i.byteLength;return u}function z(n){if(typeof n=="string")return new TextEncoder().encode(n);if(n instanceof Uint8Array)return n;if(n instanceof ArrayBuffer)return new Uint8Array(n);throw new TypeError("body is the raw request body (string or bytes): a parsed object is not what was signed \u2014 read the body before any JSON middleware")}function ge(n){let e=new Uint8Array(n.length/2);for(let t=0;t<e.length;t++)e[t]=parseInt(n.slice(t*2,t*2+2),16);return e}function me(n,e){if(n.byteLength!==e.byteLength)return!1;let t=0;for(let r=0;r<n.byteLength;r++)t|=n[r]^e[r];return t===0}function we(n,e){let t=new Uint8Array(n.byteLength+e.byteLength);return t.set(n,0),t.set(e,n.byteLength),t}function be(n){if(typeof n!="object"||n===null)return!1;let e=n;return typeof e.id=="string"&&typeof e.type=="string"&&typeof e.project_id=="string"&&typeof e.created_at=="string"&&"data"in e}var V=60,ke=60,Se=8*1024,ve=1e5;function E(n){let e=n instanceof Uint8Array?n:new Uint8Array(n),t="";for(let r of e)t+=String.fromCharCode(r);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function Y(n){let e=n.replace(/[\s=]+/g,"");if(!/^[A-Za-z0-9+/_-]*$/.test(e)||e.length%4===1)return;let t=atob(e.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(e.length/4)*4,"=")),r=new Uint8Array(t.length);for(let s=0;s<t.length;s++)r[s]=t.charCodeAt(s);return r}function J(n){let e=Y(n);if(e)try{let t=JSON.parse(new TextDecoder().decode(e));return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:void 0}catch{return}}var b=class{byKey=new Map;held=0;sweptAt=Number.NEGATIVE_INFINITY;max;constructor(e=ve){this.max=e}spend(e,t){if(t>=e.until)throw new d("proof","the DPoP proof is not taken: it was checked too long ago");let r=this.byKey.get(e.jkt);if(r){this.forgetOld(e.jkt,r,t);let s=r.get(e.jti);if(s!==void 0&&s>t)throw new d("proof","the DPoP proof is not taken: it was used before");s!==void 0&&r.delete(e.jti)&&this.held--}this.held>=this.max&&this.makeRoom(t),r=this.byKey.get(e.jkt),r||(r=new Map,this.byKey.set(e.jkt,r)),r.set(e.jti,e.until),this.held++}forgetOld(e,t,r){for(let[s,o]of t){if(o>r)break;t.delete(s),this.held--}t.size===0&&this.byKey.delete(e)}makeRoom(e){if(e-this.sweptAt>=1e3){this.sweptAt=e;for(let[r,s]of this.byKey){for(let[o,a]of s)a>e||(s.delete(o),this.held--);s.size===0&&this.byKey.delete(r)}this.held=0;for(let r of this.byKey.values())this.held+=r.size}if(this.held<this.max)return;let t=[...this.byKey].sort((r,s)=>s[1].size-r[1].size);for(let[r,s]of t){if(this.held<=this.max*.9)break;this.byKey.delete(r),this.held-=s.size}}};async function Ee(n,e){let t=`{"crv":"P-256","kty":"EC","x":"${n}","y":"${e}"}`;return E(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(t)))}function q(n){try{let e=new URL(n);return e.username!==""||e.password!==""?void 0:`${e.protocol}//${e.host}${e.pathname}`}catch{return}}async function G(n,e,t,r){let s=ie=>{throw new d("proof",`the DPoP proof is not taken: ${ie}`)},o=t.proof;if(!o)return s("there is none (a DPoP-bound token comes with a DPoP header)");if(o.length>Se)return s("it is too long");let a=o.split(".");if(a.length!==3)return s("it is not a JWS of three parts");let u=J(a[0]),c=J(a[1]);if(!u||!c)return s("its header or claims are not base64url JSON");if(u.typ!=="dpop+jwt")return s("its typ is not dpop+jwt");if(u.alg!=="ES256")return s(`it is signed with ${String(u.alg)}; only ES256 is taken`);let i=u.jwk;if(!i||typeof i!="object"||i.kty!=="EC"||i.crv!=="P-256"||typeof i.x!="string"||typeof i.y!="string")return s("its header carries no P-256 public key");if("d"in i)return s("its header carries a private key");if(await Ee(i.x,i.y)!==e)return s("it is signed by a key the token does not name");let l;try{l=await crypto.subtle.importKey("jwk",{kty:"EC",crv:"P-256",x:i.x,y:i.y,ext:!0},{name:"ECDSA",namedCurve:"P-256"},!1,["verify"])}catch{return s("its key is not a P-256 point")}let p=Y(a[2]);if(!p||!await crypto.subtle.verify({name:"ECDSA",hash:"SHA-256"},l,p,new TextEncoder().encode(`${a[0]}.${a[1]}`)).catch(()=>!1))return s("its signature does not verify");if(typeof c.htm!="string"||c.htm.toUpperCase()!==t.method.toUpperCase())return s(`it is for ${String(c.htm)}, not ${t.method}`);let h=typeof c.htu=="string"?q(c.htu):void 0,y=q(t.url);if(!h||!y||h!==y)return s(`it is for ${String(c.htu)}, not ${y??t.url}`);let re=r/1e3;if(typeof c.iat!="number"||Math.abs(c.iat-re)>V)return s("it was not made within a minute of now");let se=E(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(n)));if(c.ath!==se)return s("it is not for this token (ath)");if(typeof c.jti!="string"||c.jti===""||c.jti.length>256)return s("it has no jti (or one longer than 256)");let oe=E(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(c.jti)));return{jkt:e,jti:oe,until:(c.iat+V+ke)*1e3+1}}var d=class extends Error{reason;constructor(e,t){super(t),this.name="TokenError",this.reason=e}},g=class extends Error{constructor(e,t){super(e,t),this.name="AuthUnavailable"}},_e=new Set(["invalid_api_key","missing_api_key","secret_key_in_browser"]);function Te(n){return async e=>{let t=w({baseUrl:n.url,credentials:{secretKey:n.secretKey,accessToken:()=>e},fetch:n.fetch});try{return await t.send({op:"SessionStanding",method:"GET",path:"/auth/session/standing",auth:[["ApiKeyAuth","userJWT"]],answers:{204:"empty"}}),!0}catch(r){if(r instanceof S&&r.status===401&&!_e.has(r.code))return!1;throw new g("a session's standing could not be told",{cause:r})}}}var _={ES256:{kty:"EC",import:{name:"ECDSA",namedCurve:"P-256"},verify:{name:"ECDSA",hash:"SHA-256"}},PS256:{kty:"RSA",import:{name:"RSA-PSS",hash:"SHA-256"},verify:{name:"RSA-PSS",saltLength:32}}},X=60,Ae=16*1024,Pe=10*6e4,Re=5e4,Z=n=>typeof n=="string"&&Object.hasOwn(_,n),T=class{issuer;projectId;fetchImpl;now;maxKeyAgeMs;refetchIntervalMs;fetchTimeoutMs;standing;standingTtlMs;standingStaleMs;standings=new Map;asking=new Map;keys=new Map;keysUntil=0;lastFetch=Number.NEGATIVE_INFINITY;lastFailure=void 0;inflight=null;seenProofs=new b;constructor(e){let t=new URL(e.issuer);if(t.origin!==e.issuer.replace(/\/$/,""))throw new TypeError(`issuer is the project's origin (https://<ref>.<domain>), not ${e.issuer}`);if(typeof e.projectId!="string"||e.projectId==="")throw new TypeError("projectId is the project id the tokens carry");if(this.issuer=t.origin,this.projectId=e.projectId,this.fetchImpl=e.fetch??globalThis.fetch,this.now=e.now??Date.now,this.maxKeyAgeMs=e.maxKeyAgeMs??60*6e4,this.refetchIntervalMs=e.refetchIntervalMs??3e4,this.fetchTimeoutMs=e.fetchTimeoutMs??5e3,typeof e.standing!="function")throw new TypeError("standing is how the verifier asks whether a token's session stands");this.standing=e.standing,this.standingTtlMs=e.standingTtlMs??1e3,this.standingStaleMs=e.standingStaleMs??15e3}async verify(e,t){if(typeof e!="string"||e.length===0||e.length>Ae)throw new d("malformed","the token is not a JWT");let r=e.split(".");if(r.length!==3)throw new d("malformed","the token is not a JWS of three parts");let s=Q(r[0]),o=Q(r[1]);if(!s||!o)throw new d("malformed","the token header or claims are not base64url JSON");let a=s.alg;if(!Z(a))throw new d("algorithm",`the token is signed with ${String(a)}; only ES256 and PS256 are taken`);let u=s.kid;if(typeof u!="string"||u==="")throw new d("malformed","the token header names no kid");let c=await this.key(u);if(!c)throw new d("unknown_key",`no key ${u} in the project's key set`);if(c.alg!==a)throw new d("algorithm",`key ${u} is ${c.alg}, the token says ${a}`);let i=te(r[2]);if(!i)throw new d("malformed","the signature is not base64url");let l=new TextEncoder().encode(`${r[0]}.${r[1]}`);if(!await crypto.subtle.verify(_[c.alg].verify,c.key,i,l).catch(()=>!1))throw new d("signature","the signature does not verify");let m=this.check(o),h=o.cnf,y;if(h!==void 0){if(!t)throw new d("bound","the token is bound to a key (DPoP): it comes with the DPoP scheme and a proof, not as a Bearer");if(typeof h!="object"||h===null||typeof h.jkt!="string"||h.jkt==="")throw new d("bound","the token is bound to a key it does not name (cnf.jkt)");y=await G(e,h.jkt,t,this.now())}else if(t)throw new d("not_bound","the DPoP scheme came with a token bound to no key");if(!await this.stands(e,m.sessionId))throw new d("session_ended","the token's session has ended (signed out, revoked, or its user banned)");return y&&this.seenProofs.spend(y,this.now()),m}async verifyRequest(e){let t=e.headers instanceof Headers?e.headers:Oe(e.headers),r=t.get("authorization")??"";if(r==="")return null;let s=/^(bearer|dpop)\s+(\S+)$/i.exec(r);if(!s)throw new d("malformed","the Authorization header is not a Bearer or DPoP token");let o=s[1].toLowerCase()==="dpop",a=new URL(e.url,`http://${t.get("host")??"localhost"}`);return this.verify(s[2],o?{proof:t.get("dpop"),method:e.method,url:ee(t,a)}:void 0)}async stands(e,t){let r=this.now(),s=this.standings.get(t);if(s&&r<s.until)return s.live;let o=this.asking.get(t);o||(o=this.standing(e,t).finally(()=>this.asking.delete(t)),this.asking.set(t,o));let a;try{a=await o}catch(c){let i=this.standings.get(t),l=this.now();if(i&&l<i.at+this.standingStaleMs)return i.until=Math.min(l+this.standingTtlMs,i.at+this.standingStaleMs),i.live;throw new g("a session's standing cannot be read now",{cause:c})}let u=this.now();return this.standings.delete(t),this.standings.set(t,{live:a,at:u,until:u+this.standingTtlMs}),this.standings.size>Re&&this.standings.delete(this.standings.keys().next().value),a}check(e){if(e.iss!==this.issuer)throw new d("issuer",`the token was issued by ${String(e.iss)}, not this project`);if(!(Array.isArray(e.aud)?e.aud:[e.aud]).includes(this.issuer))throw new d("audience","the token is not meant for this project");if(e.project_id!==this.projectId)throw new d("project","the token names another project");let r=this.now()/1e3;if(typeof e.exp!="number"||e.exp+X<=r)throw new d("expired","the token has expired");if(e.nbf!==void 0&&(typeof e.nbf!="number"||e.nbf-X>r))throw new d("not_yet_valid","the token is not valid yet");if(typeof e.sub!="string"||e.sub===""||typeof e.auth_time!="number")throw new d("not_a_user","the token is not a user's");if(typeof e.session_id!="string"||e.session_id==="")throw new d("not_a_session","the token is no session's");let s=e.custom_claims;if(s!==void 0&&(typeof s!="object"||s===null||s.type!==void 0))throw new d("not_a_session","the token is a custom one (an exchange or an approval), not a session's");return{id:e.sub,email:typeof e.email=="string"?e.email:null,emailVerified:e.email_verified===!0,role:typeof e.role=="string"?e.role:null,sessionId:typeof e.session_id=="string"?e.session_id:null,claims:Object.freeze({...e})}}async key(e){let t=this.now();if(t>=this.keysUntil){let s=this.keys.size>0&&t<this.keysUntil+Pe;if(this.lastFailure!==void 0&&t-this.lastFetch<this.refetchIntervalMs){if(!s)throw new g("the project's key set cannot be read now",{cause:this.lastFailure})}else try{await this.refresh()}catch(o){if(!s)throw o}}let r=this.keys.get(e);return!r&&t-this.lastFetch>=this.refetchIntervalMs&&(await this.refresh(),r=this.keys.get(e)),r}refresh(){if(this.inflight)return this.inflight;let e=this.load().finally(()=>{this.inflight=null});return this.inflight=e,e}async load(){this.lastFetch=this.now();let e,t;try{if(t=await this.fetchImpl(`${this.issuer}/.well-known/jwks.json`,{redirect:"error",headers:{accept:"application/json"},signal:AbortSignal.timeout(this.fetchTimeoutMs)}),!t.ok)throw new Error(`the project's key set answered ${t.status}`);e=await t.json()}catch(o){throw this.lastFailure=o,new g("the project's key set cannot be read now",{cause:o})}this.lastFailure=void 0;let r=new Map;for(let o of Array.isArray(e.keys)?e.keys:[]){let a=o.alg;if(typeof o.kid!="string"||!Z(a))continue;let u=_[a];if(o.kty!==u.kty||o.use!==void 0&&o.use!=="sig")continue;let{d:c,...i}=o;try{r.set(o.kid,{alg:a,key:await crypto.subtle.importKey("jwk",i,u.import,!1,["verify"])})}catch{}}this.keys=r;let s=je(t.headers.get("cache-control"))??this.maxKeyAgeMs;this.keysUntil=this.now()+Math.min(Math.max(s,this.refetchIntervalMs),this.maxKeyAgeMs)}};function ee(n,e){let t=n.get("x-forwarded-proto")?.split(",")[0]?.trim().toLowerCase(),r=t==="https"||t==="http"?t:e.protocol.slice(0,-1),s=n.get("host")??e.host;return xe.test(s)?`${r}://${s}${e.pathname}`:""}var xe=/^(?:[a-z0-9-]+(?:\.[a-z0-9-]+)*|\[[0-9a-f:.]+\])(?::[0-9]{1,5})?$/i;function Oe(n){let e=new Headers;for(let[t,r]of Object.entries(n))if(r!==void 0)for(let s of Array.isArray(r)?r:[r])e.append(t,s);return e}function je(n){let e=/(?:^|,)\s*max-age=(\d+)/i.exec(n??"");return e?Number(e[1])*1e3:void 0}function te(n){if(!/^[A-Za-z0-9_-]*$/.test(n)||n.length%4===1)return null;let e=atob(n.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(n.length/4)*4,"=")),t=new Uint8Array(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return t}function Q(n){let e=te(n);if(!e)return null;try{let t=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(e));return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:null}catch{return null}}function Me(n,e,t=Date.now()){let r=Object.hasOwn(n.entitlements,e)?n.entitlements[e]:void 0;return r?.active?r.expires_at===null?!0:Date.parse(r.expires_at)>(typeof t=="number"?t:t.getTime()):!1}var k=class extends Error{receipt;constructor(e){super(`the reservation ${JSON.stringify(e.idempotency_key)} is ${e.status} already: its job is not run again (a new one is a new Idempotency-Key)`),this.name="ReservationSettled",this.receipt=e}};async function Ce(n,e,t,r){let{idempotencyKey:s,amount:o,ttlSeconds:a,metadata:u}=t;if(typeof s!="string"||s==="")throw new TypeError("idempotencyKey names the reservation for good: a retry with it is the same hold, never a second");let c={amount:o,...t.credits!==void 0?{credits:t.credits}:{limit:t.limit},...a!==void 0?{ttl_seconds:a}:{},...u!==void 0?{metadata:u}:{}},i=(await n.purchases.holdSpend({path:{customer_id:e},headers:{"Idempotency-Key":s},body:c})).data;if(i.status!=="held")throw new k(i);let l={customer_id:i.customer,spend_id:i.id},p;try{p=await r(i)}catch(m){throw await n.purchases.releaseSpend({path:l}).catch(()=>{}),m}return await n.purchases.commitSpend({path:l}),p}async function*Le(n){let e,t=new Set;do{let r=(await n(e)).data;yield r;let s=r.next_cursor??void 0;if(s!==void 0&&t.has(s))throw new Error(`the listing answered a cursor it had answered before (${s})`);s!==void 0&&t.add(s),e=s}while(e)}var Ue=/^[A-Za-z_][A-Za-z0-9_]{0,127}$/,Ke=/^(PALBASE_|NODE_|BUN_|NPM_|LD_|DYLD_|GIT_|SSH_)|^(PATH|HOME|SHELL|USER|TMPDIR|TMP|TEMP|PWD|IFS|ENV|BASH_ENV|SSL_CERT_FILE|SSL_CERT_DIR|CURL_CA_BUNDLE|REQUESTS_CA_BUNDLE|NO_PROXY|ALL_PROXY|HTTP_PROXY|HTTPS_PROXY|PG\w*)$/i;function ne(n){return!Ue.test(n)||Ke.test(n)||/_PROXY$/i.test(n)}var Ne=/^(PORT|PALBASE_(URL|PROJECT_ID|MACHINE|REPLICAS|SECRET_KEY|WEBHOOK_SECRET|PLATFORM_SECRET|CONTRACT_OUT|SECRETS|DB_[A-Z0-9_]+))$/;function $e(n){return Ne.test(n)}async function Ie(n={}){let e=n.env??process.env,t=e.PALBASE_SECRETS;if(t===void 0||t==="")return;if(t!=="development"&&t!=="production")throw new TypeError(`PALBASE_SECRETS is development or production, not ${t}`);let r=n.url??e.PALBASE_URL??"",s=n.secretKey??e.PALBASE_SECRET_KEY??"";if(r===""||s==="")throw new TypeError("PALBASE_SECRETS reads the project's Secrets with PALBASE_URL and PALBASE_SECRET_KEY: give both (palbase env:pull writes them)");let o=v({url:new URL(r).origin,secretKey:s,fetch:n.fetch}),{data:a}=await o.secrets.getEnvironmentValues({path:{environment:t}}),u=[],c=[],i=[];for(let[l,p]of Object.entries(a.values)){if(ne(l)){i.push(l);continue}if(e[l]!==void 0&&e[l]!==""){c.push(l);continue}e[l]=p,u.push(l)}return{set:t,loaded:u.sort(),kept:c.sort(),refused:i.sort()}}export{v as a,f as b,B as c,F as d,H as e,pe as f,d as g,g as h,Te as i,T as j,ee as k,Me as l,k as m,Ce as n,Le as o,ne as p,$e as q,Ie as r};
|
|
1
|
+
/*! palbase 0.10.1 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{a as D}from"./6N3E2XHZ.js";import{a as A,b as P,c as R,d as x,e as O,f as j,g as M,h as C,i as L,j as U,k as K,l as N}from"./YQEM4H7U.js";import{a as $,b as I}from"./RO7ERCT3.js";import{b as S,d as w}from"./RWGEPDRQ.js";var ae=/^pb_[a-z0-9]+_s/;function v(n){if(D())throw new TypeError("palbase/server runs on a server: its secret key never goes into a browser or a mobile app \u2014 apps use palbase/web (or the native SDKs) with the publishable key");if(typeof n.secretKey!="string"||!ae.test(n.secretKey))throw new TypeError("secretKey is the project secret key (pb_<ref>_s\u2026); a publishable key belongs in palbase/web");let e=I(w({baseUrl:n.url,credentials:{secretKey:n.secretKey},fetch:n.fetch,solveProofOfWork:n.solveProofOfWork??!1}),n.retry??$);return{ai:A.client(e),analytics:P.client(e),auth:R.client(e),cache:x.client(e),flags:O.client(e),machines:j.client(e),notify:M.client(e),purchases:C.client(e),realtime:L.client(e),secrets:U.client(e),storage:K.client(e),stores:N.client(e),transport:e,url:new URL(n.url).origin}}var f=class extends Error{code;constructor(e,t){super(t),this.name="WebhookSignatureError",this.code=e}},ue=300,de=/^[0-9]{1,12}$/,le=/^[0-9a-f]{64}$/,W=8,fe=/^whsec_[0-9A-Za-z]{32,}$/,he=1024*1024;async function B(n){if(typeof n.secret!="string"||!fe.test(n.secret))throw new TypeError("secret is the webhook endpoint secret (whsec_\u2026), not an API key");await F(n);let e;try{e=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(z(n.body)))}catch{throw new f("invalid_body","the signed body is not JSON")}if(!be(e))throw new f("invalid_body","the signed body is not a Palbase event (id, type, project_id, created_at, data)");return e}async function F(n){if(typeof n.secret!="string"||n.secret==="")throw new TypeError("secret is the key the request was signed with");let e=z(n.body),{t,v1:r}=H(n),s=await crypto.subtle.importKey("raw",new TextEncoder().encode(n.secret),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),o=new Uint8Array(await crypto.subtle.sign("HMAC",s,we(new TextEncoder().encode(`${t}.`),e))),a=!1;for(let u of r)me(o,ge(u))&&(a=!0);if(!a)throw new f("signature_mismatch","no v1 in Palbase-Signature is this body signed with this secret")}function H(n){let e=n.toleranceSeconds??ue;if(!Number.isFinite(e)||e<0)throw new TypeError(`toleranceSeconds is a number of seconds, 0 or more (got ${String(n.toleranceSeconds)})`);let t=(n.now??Date.now)();if(!Number.isFinite(t))throw new TypeError(`now() returns epoch milliseconds (got ${String(t)})`);let r=n.signature;if(typeof r!="string"||r.trim()==="")throw new f("missing_signature","the request carries no Palbase-Signature header");let s,o=[];for(let a of r.split(",")){let u=a.indexOf("=");if(u<=0)throw new f("malformed_signature","Palbase-Signature is t=<seconds>,v1=<hex>");let c=a.slice(0,u).trim(),i=a.slice(u+1).trim();if(c==="t"){if(s!==void 0||!de.test(i))throw new f("malformed_signature","Palbase-Signature carries one t, in unix seconds");s=i}else if(c==="v1"){if(!le.test(i))throw new f("malformed_signature","a v1 is 64 lowercase hex characters");if(o.length===W)throw new f("malformed_signature",`Palbase-Signature carries at most ${W} v1`);o.push(i)}}if(s===void 0||o.length===0)throw new f("malformed_signature","Palbase-Signature is t=<seconds>,v1=<hex>");if(Math.abs(t/1e3-Number(s))>e)throw new f("stale_timestamp",`the signature's time is more than ${e} s from now: an old delivery sent again is not taken`);return{t:s,v1:o}}async function pe(n,e,t={}){let r=await ye(n,t.maxBytes??he);return B({toleranceSeconds:t.toleranceSeconds,now:t.now,secret:e,signature:n.headers.get("palbase-signature"),body:r})}async function ye(n,e){let t=()=>new f("body_too_large",`the body is larger than ${e} bytes`),r=Number(n.headers.get("content-length")??"NaN");if(Number.isFinite(r)&&r>e)throw t();if(!n.body)return new Uint8Array(0);let s=n.body.getReader(),o=[],a=0;for(;;){let{done:i,value:l}=await s.read();if(i)break;if(a+=l.byteLength,a>e)throw await s.cancel().catch(()=>{}),t();o.push(l)}let u=new Uint8Array(a),c=0;for(let i of o)u.set(i,c),c+=i.byteLength;return u}function z(n){if(typeof n=="string")return new TextEncoder().encode(n);if(n instanceof Uint8Array)return n;if(n instanceof ArrayBuffer)return new Uint8Array(n);throw new TypeError("body is the raw request body (string or bytes): a parsed object is not what was signed \u2014 read the body before any JSON middleware")}function ge(n){let e=new Uint8Array(n.length/2);for(let t=0;t<e.length;t++)e[t]=parseInt(n.slice(t*2,t*2+2),16);return e}function me(n,e){if(n.byteLength!==e.byteLength)return!1;let t=0;for(let r=0;r<n.byteLength;r++)t|=n[r]^e[r];return t===0}function we(n,e){let t=new Uint8Array(n.byteLength+e.byteLength);return t.set(n,0),t.set(e,n.byteLength),t}function be(n){if(typeof n!="object"||n===null)return!1;let e=n;return typeof e.id=="string"&&typeof e.type=="string"&&typeof e.project_id=="string"&&typeof e.created_at=="string"&&"data"in e}var V=60,ke=60,Se=8*1024,ve=1e5;function E(n){let e=n instanceof Uint8Array?n:new Uint8Array(n),t="";for(let r of e)t+=String.fromCharCode(r);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function Y(n){let e=n.replace(/[\s=]+/g,"");if(!/^[A-Za-z0-9+/_-]*$/.test(e)||e.length%4===1)return;let t=atob(e.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(e.length/4)*4,"=")),r=new Uint8Array(t.length);for(let s=0;s<t.length;s++)r[s]=t.charCodeAt(s);return r}function J(n){let e=Y(n);if(e)try{let t=JSON.parse(new TextDecoder().decode(e));return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:void 0}catch{return}}var b=class{byKey=new Map;held=0;sweptAt=Number.NEGATIVE_INFINITY;max;constructor(e=ve){this.max=e}spend(e,t){if(t>=e.until)throw new d("proof","the DPoP proof is not taken: it was checked too long ago");let r=this.byKey.get(e.jkt);if(r){this.forgetOld(e.jkt,r,t);let s=r.get(e.jti);if(s!==void 0&&s>t)throw new d("proof","the DPoP proof is not taken: it was used before");s!==void 0&&r.delete(e.jti)&&this.held--}this.held>=this.max&&this.makeRoom(t),r=this.byKey.get(e.jkt),r||(r=new Map,this.byKey.set(e.jkt,r)),r.set(e.jti,e.until),this.held++}forgetOld(e,t,r){for(let[s,o]of t){if(o>r)break;t.delete(s),this.held--}t.size===0&&this.byKey.delete(e)}makeRoom(e){if(e-this.sweptAt>=1e3){this.sweptAt=e;for(let[r,s]of this.byKey){for(let[o,a]of s)a>e||(s.delete(o),this.held--);s.size===0&&this.byKey.delete(r)}this.held=0;for(let r of this.byKey.values())this.held+=r.size}if(this.held<this.max)return;let t=[...this.byKey].sort((r,s)=>s[1].size-r[1].size);for(let[r,s]of t){if(this.held<=this.max*.9)break;this.byKey.delete(r),this.held-=s.size}}};async function Ee(n,e){let t=`{"crv":"P-256","kty":"EC","x":"${n}","y":"${e}"}`;return E(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(t)))}function q(n){try{let e=new URL(n);return e.username!==""||e.password!==""?void 0:`${e.protocol}//${e.host}${e.pathname}`}catch{return}}async function G(n,e,t,r){let s=ie=>{throw new d("proof",`the DPoP proof is not taken: ${ie}`)},o=t.proof;if(!o)return s("there is none (a DPoP-bound token comes with a DPoP header)");if(o.length>Se)return s("it is too long");let a=o.split(".");if(a.length!==3)return s("it is not a JWS of three parts");let u=J(a[0]),c=J(a[1]);if(!u||!c)return s("its header or claims are not base64url JSON");if(u.typ!=="dpop+jwt")return s("its typ is not dpop+jwt");if(u.alg!=="ES256")return s(`it is signed with ${String(u.alg)}; only ES256 is taken`);let i=u.jwk;if(!i||typeof i!="object"||i.kty!=="EC"||i.crv!=="P-256"||typeof i.x!="string"||typeof i.y!="string")return s("its header carries no P-256 public key");if("d"in i)return s("its header carries a private key");if(await Ee(i.x,i.y)!==e)return s("it is signed by a key the token does not name");let l;try{l=await crypto.subtle.importKey("jwk",{kty:"EC",crv:"P-256",x:i.x,y:i.y,ext:!0},{name:"ECDSA",namedCurve:"P-256"},!1,["verify"])}catch{return s("its key is not a P-256 point")}let p=Y(a[2]);if(!p||!await crypto.subtle.verify({name:"ECDSA",hash:"SHA-256"},l,p,new TextEncoder().encode(`${a[0]}.${a[1]}`)).catch(()=>!1))return s("its signature does not verify");if(typeof c.htm!="string"||c.htm.toUpperCase()!==t.method.toUpperCase())return s(`it is for ${String(c.htm)}, not ${t.method}`);let h=typeof c.htu=="string"?q(c.htu):void 0,y=q(t.url);if(!h||!y||h!==y)return s(`it is for ${String(c.htu)}, not ${y??t.url}`);let re=r/1e3;if(typeof c.iat!="number"||Math.abs(c.iat-re)>V)return s("it was not made within a minute of now");let se=E(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(n)));if(c.ath!==se)return s("it is not for this token (ath)");if(typeof c.jti!="string"||c.jti===""||c.jti.length>256)return s("it has no jti (or one longer than 256)");let oe=E(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(c.jti)));return{jkt:e,jti:oe,until:(c.iat+V+ke)*1e3+1}}var d=class extends Error{reason;constructor(e,t){super(t),this.name="TokenError",this.reason=e}},g=class extends Error{constructor(e,t){super(e,t),this.name="AuthUnavailable"}},_e=new Set(["invalid_api_key","missing_api_key","secret_key_in_browser"]);function Te(n){return async e=>{let t=w({baseUrl:n.url,credentials:{secretKey:n.secretKey,accessToken:()=>e},fetch:n.fetch});try{return await t.send({op:"SessionStanding",method:"GET",path:"/auth/session/standing",auth:[["ApiKeyAuth","userJWT"]],answers:{204:"empty"}}),!0}catch(r){if(r instanceof S&&r.status===401&&!_e.has(r.code))return!1;throw new g("a session's standing could not be told",{cause:r})}}}var _={ES256:{kty:"EC",import:{name:"ECDSA",namedCurve:"P-256"},verify:{name:"ECDSA",hash:"SHA-256"}},PS256:{kty:"RSA",import:{name:"RSA-PSS",hash:"SHA-256"},verify:{name:"RSA-PSS",saltLength:32}}},X=60,Ae=16*1024,Pe=10*6e4,Re=5e4,Z=n=>typeof n=="string"&&Object.hasOwn(_,n),T=class{issuer;projectId;fetchImpl;now;maxKeyAgeMs;refetchIntervalMs;fetchTimeoutMs;standing;standingTtlMs;standingStaleMs;standings=new Map;asking=new Map;keys=new Map;keysUntil=0;lastFetch=Number.NEGATIVE_INFINITY;lastFailure=void 0;inflight=null;seenProofs=new b;constructor(e){let t=new URL(e.issuer);if(t.origin!==e.issuer.replace(/\/$/,""))throw new TypeError(`issuer is the project's origin (https://<ref>.<domain>), not ${e.issuer}`);if(typeof e.projectId!="string"||e.projectId==="")throw new TypeError("projectId is the project id the tokens carry");if(this.issuer=t.origin,this.projectId=e.projectId,this.fetchImpl=e.fetch??globalThis.fetch,this.now=e.now??Date.now,this.maxKeyAgeMs=e.maxKeyAgeMs??60*6e4,this.refetchIntervalMs=e.refetchIntervalMs??3e4,this.fetchTimeoutMs=e.fetchTimeoutMs??5e3,typeof e.standing!="function")throw new TypeError("standing is how the verifier asks whether a token's session stands");this.standing=e.standing,this.standingTtlMs=e.standingTtlMs??1e3,this.standingStaleMs=e.standingStaleMs??15e3}async verify(e,t){if(typeof e!="string"||e.length===0||e.length>Ae)throw new d("malformed","the token is not a JWT");let r=e.split(".");if(r.length!==3)throw new d("malformed","the token is not a JWS of three parts");let s=Q(r[0]),o=Q(r[1]);if(!s||!o)throw new d("malformed","the token header or claims are not base64url JSON");let a=s.alg;if(!Z(a))throw new d("algorithm",`the token is signed with ${String(a)}; only ES256 and PS256 are taken`);let u=s.kid;if(typeof u!="string"||u==="")throw new d("malformed","the token header names no kid");let c=await this.key(u);if(!c)throw new d("unknown_key",`no key ${u} in the project's key set`);if(c.alg!==a)throw new d("algorithm",`key ${u} is ${c.alg}, the token says ${a}`);let i=te(r[2]);if(!i)throw new d("malformed","the signature is not base64url");let l=new TextEncoder().encode(`${r[0]}.${r[1]}`);if(!await crypto.subtle.verify(_[c.alg].verify,c.key,i,l).catch(()=>!1))throw new d("signature","the signature does not verify");let m=this.check(o),h=o.cnf,y;if(h!==void 0){if(!t)throw new d("bound","the token is bound to a key (DPoP): it comes with the DPoP scheme and a proof, not as a Bearer");if(typeof h!="object"||h===null||typeof h.jkt!="string"||h.jkt==="")throw new d("bound","the token is bound to a key it does not name (cnf.jkt)");y=await G(e,h.jkt,t,this.now())}else if(t)throw new d("not_bound","the DPoP scheme came with a token bound to no key");if(!await this.stands(e,m.sessionId))throw new d("session_ended","the token's session has ended (signed out, revoked, or its user banned)");return y&&this.seenProofs.spend(y,this.now()),m}async verifyRequest(e){let t=e.headers instanceof Headers?e.headers:Oe(e.headers),r=t.get("authorization")??"";if(r==="")return null;let s=/^(bearer|dpop)\s+(\S+)$/i.exec(r);if(!s)throw new d("malformed","the Authorization header is not a Bearer or DPoP token");let o=s[1].toLowerCase()==="dpop",a=new URL(e.url,`http://${t.get("host")??"localhost"}`);return this.verify(s[2],o?{proof:t.get("dpop"),method:e.method,url:ee(t,a)}:void 0)}async stands(e,t){let r=this.now(),s=this.standings.get(t);if(s&&r<s.until)return s.live;let o=this.asking.get(t);o||(o=this.standing(e,t).finally(()=>this.asking.delete(t)),this.asking.set(t,o));let a;try{a=await o}catch(c){let i=this.standings.get(t),l=this.now();if(i&&l<i.at+this.standingStaleMs)return i.until=Math.min(l+this.standingTtlMs,i.at+this.standingStaleMs),i.live;throw new g("a session's standing cannot be read now",{cause:c})}let u=this.now();return this.standings.delete(t),this.standings.set(t,{live:a,at:u,until:u+this.standingTtlMs}),this.standings.size>Re&&this.standings.delete(this.standings.keys().next().value),a}check(e){if(e.iss!==this.issuer)throw new d("issuer",`the token was issued by ${String(e.iss)}, not this project`);if(!(Array.isArray(e.aud)?e.aud:[e.aud]).includes(this.issuer))throw new d("audience","the token is not meant for this project");if(e.project_id!==this.projectId)throw new d("project","the token names another project");let r=this.now()/1e3;if(typeof e.exp!="number"||e.exp+X<=r)throw new d("expired","the token has expired");if(e.nbf!==void 0&&(typeof e.nbf!="number"||e.nbf-X>r))throw new d("not_yet_valid","the token is not valid yet");if(typeof e.sub!="string"||e.sub===""||typeof e.auth_time!="number")throw new d("not_a_user","the token is not a user's");if(typeof e.session_id!="string"||e.session_id==="")throw new d("not_a_session","the token is no session's");let s=e.custom_claims;if(s!==void 0&&(typeof s!="object"||s===null||s.type!==void 0))throw new d("not_a_session","the token is a custom one (an exchange or an approval), not a session's");return{id:e.sub,email:typeof e.email=="string"?e.email:null,emailVerified:e.email_verified===!0,role:typeof e.role=="string"?e.role:null,sessionId:typeof e.session_id=="string"?e.session_id:null,claims:Object.freeze({...e})}}async key(e){let t=this.now();if(t>=this.keysUntil){let s=this.keys.size>0&&t<this.keysUntil+Pe;if(this.lastFailure!==void 0&&t-this.lastFetch<this.refetchIntervalMs){if(!s)throw new g("the project's key set cannot be read now",{cause:this.lastFailure})}else try{await this.refresh()}catch(o){if(!s)throw o}}let r=this.keys.get(e);return!r&&t-this.lastFetch>=this.refetchIntervalMs&&(await this.refresh(),r=this.keys.get(e)),r}refresh(){if(this.inflight)return this.inflight;let e=this.load().finally(()=>{this.inflight=null});return this.inflight=e,e}async load(){this.lastFetch=this.now();let e,t;try{if(t=await this.fetchImpl(`${this.issuer}/.well-known/jwks.json`,{redirect:"error",headers:{accept:"application/json"},signal:AbortSignal.timeout(this.fetchTimeoutMs)}),!t.ok)throw new Error(`the project's key set answered ${t.status}`);e=await t.json()}catch(o){throw this.lastFailure=o,new g("the project's key set cannot be read now",{cause:o})}this.lastFailure=void 0;let r=new Map;for(let o of Array.isArray(e.keys)?e.keys:[]){let a=o.alg;if(typeof o.kid!="string"||!Z(a))continue;let u=_[a];if(o.kty!==u.kty||o.use!==void 0&&o.use!=="sig")continue;let{d:c,...i}=o;try{r.set(o.kid,{alg:a,key:await crypto.subtle.importKey("jwk",i,u.import,!1,["verify"])})}catch{}}this.keys=r;let s=je(t.headers.get("cache-control"))??this.maxKeyAgeMs;this.keysUntil=this.now()+Math.min(Math.max(s,this.refetchIntervalMs),this.maxKeyAgeMs)}};function ee(n,e){let t=n.get("x-forwarded-proto")?.split(",")[0]?.trim().toLowerCase(),r=t==="https"||t==="http"?t:e.protocol.slice(0,-1),s=n.get("host")??e.host;return xe.test(s)?`${r}://${s}${e.pathname}`:""}var xe=/^(?:[a-z0-9-]+(?:\.[a-z0-9-]+)*|\[[0-9a-f:.]+\])(?::[0-9]{1,5})?$/i;function Oe(n){let e=new Headers;for(let[t,r]of Object.entries(n))if(r!==void 0)for(let s of Array.isArray(r)?r:[r])e.append(t,s);return e}function je(n){let e=/(?:^|,)\s*max-age=(\d+)/i.exec(n??"");return e?Number(e[1])*1e3:void 0}function te(n){if(!/^[A-Za-z0-9_-]*$/.test(n)||n.length%4===1)return null;let e=atob(n.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(n.length/4)*4,"=")),t=new Uint8Array(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return t}function Q(n){let e=te(n);if(!e)return null;try{let t=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(e));return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:null}catch{return null}}function Me(n,e,t=Date.now()){let r=Object.hasOwn(n.entitlements,e)?n.entitlements[e]:void 0;return r?.active?r.expires_at===null?!0:Date.parse(r.expires_at)>(typeof t=="number"?t:t.getTime()):!1}var k=class extends Error{receipt;constructor(e){super(`the reservation ${JSON.stringify(e.idempotency_key)} is ${e.status} already: its job is not run again (a new one is a new Idempotency-Key)`),this.name="ReservationSettled",this.receipt=e}};async function Ce(n,e,t,r){let{idempotencyKey:s,amount:o,ttlSeconds:a,metadata:u}=t;if(typeof s!="string"||s==="")throw new TypeError("idempotencyKey names the reservation for good: a retry with it is the same hold, never a second");let c={amount:o,...t.credits!==void 0?{credits:t.credits}:{limit:t.limit},...a!==void 0?{ttl_seconds:a}:{},...u!==void 0?{metadata:u}:{}},i=(await n.purchases.holdSpend({path:{customer_id:e},headers:{"Idempotency-Key":s},body:c})).data;if(i.status!=="held")throw new k(i);let l={customer_id:i.customer,spend_id:i.id},p;try{p=await r(i)}catch(m){throw await n.purchases.releaseSpend({path:l}).catch(()=>{}),m}return await n.purchases.commitSpend({path:l}),p}async function*Le(n){let e,t=new Set;do{let r=(await n(e)).data;yield r;let s=r.next_cursor??void 0;if(s!==void 0&&t.has(s))throw new Error(`the listing answered a cursor it had answered before (${s})`);s!==void 0&&t.add(s),e=s}while(e)}var Ue=/^[A-Za-z_][A-Za-z0-9_]{0,127}$/,Ke=/^(PALBASE_|NODE_|BUN_|NPM_|LD_|DYLD_|GIT_|SSH_)|^(PATH|HOME|SHELL|USER|TMPDIR|TMP|TEMP|PWD|IFS|ENV|BASH_ENV|SSL_CERT_FILE|SSL_CERT_DIR|CURL_CA_BUNDLE|REQUESTS_CA_BUNDLE|NO_PROXY|ALL_PROXY|HTTP_PROXY|HTTPS_PROXY|PG\w*)$/i;function ne(n){return!Ue.test(n)||Ke.test(n)||/_PROXY$/i.test(n)}var Ne=/^(PORT|PALBASE_(URL|PROJECT_ID|MACHINE|REPLICAS|SECRET_KEY|WEBHOOK_SECRET|PLATFORM_SECRET|CONTRACT_OUT|SECRETS|DB_[A-Z0-9_]+))$/;function $e(n){return Ne.test(n)}async function Ie(n={}){let e=n.env??process.env,t=e.PALBASE_SECRETS;if(t===void 0||t==="")return;if(t!=="development"&&t!=="production")throw new TypeError(`PALBASE_SECRETS is development or production, not ${t}`);let r=n.url??e.PALBASE_URL??"",s=n.secretKey??e.PALBASE_SECRET_KEY??"";if(r===""||s==="")throw new TypeError("PALBASE_SECRETS reads the project's Secrets with PALBASE_URL and PALBASE_SECRET_KEY: give both (palbase env:pull writes them)");let o=v({url:new URL(r).origin,secretKey:s,fetch:n.fetch}),{data:a}=await o.secrets.getEnvironmentValues({path:{environment:t}}),u=[],c=[],i=[];for(let[l,p]of Object.entries(a.values)){if(ne(l)){i.push(l);continue}if(e[l]!==void 0&&e[l]!==""){c.push(l);continue}e[l]=p,u.push(l)}return{set:t,loaded:u.sort(),kept:c.sort(),refused:i.sort()}}export{v as a,f as b,B as c,F as d,H as e,pe as f,d as g,g as h,Te as i,T as j,ee as k,Me as l,k as m,Ce as n,Le as o,ne as p,$e as q,Ie as r};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
2
|
-
import{a as d,b as u}from"./
|
|
1
|
+
/*! palbase 0.10.1 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{a as d,b as u}from"./RWGEPDRQ.js";var p={too_many_chats:()=>"this user is in as many chats as they may be (100): delete or leave one before starting another",too_many_endpoints:()=>"the project holds as many tool endpoints as it may (32): delete one (ai.endpoints.delete) before putting another",too_many_messages:t=>`this user has sent as many messages this minute as the project allows${t.retryAfter!==void 0?`: write again in ${t.retryAfter} s`:""}`,history_full:()=>"the project keeps as much chat history as it may: delete chats to write again",not_your_turn:()=>"this turn is another member's: only the member who started it (or the project's server) answers its tools and decides its approvals",not_a_member:()=>"the member the server acts as (as) is not in this chat: put them in it first (chats.members.put), or act as the server",goal_lapsed:()=>"the goal was set as a member who no longer stands where they stood then (out of the chat, or the chat no longer theirs alone): it is not resumed \u2014 clear it, or set another for the chat as it is now",goal_achieved:()=>"the goal is achieved: set a new one (chats.goal.set) to work on",turn_running:()=>"the chat's agent is at work on a turn: fork it once the turn has ended, or stop it first (chats.stop)",fork_too_large:()=>"what came before that message is more than a fork begins with (512 KiB): fork it before an earlier message",too_many_voices:t=>`this user has started as many voices this hour as the project allows (5)${t.retryAfter!==void 0?`: start again in ${t.retryAfter} s`:""}`,voice_active:()=>"another member's voice is live in this chat \u2014 one voice talks in a chat at a time: wait for it to end",not_your_voice:()=>"this voice is another member's: only its member \u2014 or the server as itself \u2014 reads, tells and closes it",voice_closed:()=>"the voice has ended: start a new one (chats.voice.start)",no_workspace:()=>"this chat works in no workspace, and files go into one: start the chat with a workspace, or send pictures as images",attachment_not_found:()=>"a picture or a file given is not one its writer may attach: a file of the project's storage \u2014 for a member, their own or a public bucket's",attachment_too_large:()=>"an attachment is past its bound: 5 MiB a picture, 15 MiB a file",attachment_changed:()=>"a file changed while it was being attached: send the message again",unsupported_image:()=>"a picture is not png, jpeg, webp or gif by its bytes: send it as a file",image_not_found:()=>"a picture given is not a file of the project's storage: upload it first (storage.from(bucket).upload(path, file)) and give that bucket and path",storage_unavailable:t=>`the project's storage did not answer when the model was to read a picture${t.retryAfter!==void 0?`: try again in ${t.retryAfter} s`:"; try again shortly"}`},g=new WeakSet;function c(t){if(!(t instanceof u)||g.has(t))return t;let r=p[t.code];if(!r)return t;let s=new u({op:t.op,status:t.status,code:t.code,message:`${r(t)} (${t.op}: ${t.status} ${t.code})`,requestId:t.requestId,retryAfter:t.retryAfter,body:t.body,cause:t});return g.add(s),s}function h(t){return t.catch(r=>{throw c(r)})}function _(t){if(typeof t!="object"||t===null)return;let r=t,s=r.data;if(typeof r.type!="string"||typeof s!="object"||s===null||Array.isArray(s))return;let e=d(s),i=typeof r.id=="number"&&Number.isSafeInteger(r.id)?r.id:0;switch(r.type){case"message":return typeof e.client_id=="string"?{type:"message",seq:i,message:e}:void 0;case"turn":{if(typeof e.response_id!="string"||typeof e.status!="string")return;let n={...e,type:"turn",seq:i};return n.waiting??=null,n.error??=null,n}case"text":{let n=e.offset;return typeof e.response_id!="string"||typeof n!="number"||!Number.isInteger(n)||n<0?void 0:{type:"text",response_id:e.response_id,offset:n,text:typeof e.text=="string"?e.text:""}}case"reset":{let n=e.offset;return typeof e.response_id!="string"||typeof n!="number"||!Number.isInteger(n)||n<0?void 0:{type:"reset",response_id:e.response_id,offset:n}}case"tool":{if(typeof e.call_id!="string"||typeof e.response_id!="string")return;let n=e.omitted_bytes;return{...e,type:"tool",seq:i,omittedBytes:typeof n=="number"&&Number.isSafeInteger(n)&&n>0?n:0,outputTruncated:e.output_truncated===!0}}case"agent":return typeof e.parent_response_id=="string"?{...e,type:"agent",seq:i}:void 0;case"thinking":{if(typeof e.response_id!="string")return;let n=typeof e.run_id=="string"?e.run_id:"";return e.unavailable===!0?{type:"thinking",seq:i,response_id:e.response_id,run_id:n,text:"",unavailable:!0,model:typeof e.model=="string"?e.model:"",reason:typeof e.reason=="string"?e.reason:""}:typeof e.text!="string"?void 0:{type:"thinking",seq:i,response_id:e.response_id,run_id:n,...typeof e.step_id=="string"&&e.step_id!==""?{step_id:e.step_id}:{},text:e.text}}case"goal":{if(typeof e.goal_id!="string"||typeof e.kind!="string")return;let{seq:n,...o}=e;return{...o,type:"goal",seq:i,...typeof n=="number"?{turn:n}:{}}}case"history":{if(!Array.isArray(e.items)||typeof e.part!="number"||!Number.isInteger(e.part)||e.part<0)return;let n=e.items.filter(a=>typeof a=="object"&&a!==null&&(a.role==="user"||a.role==="assistant")&&typeof a.text=="string"),o=e.forked_from;return{type:"history",forked_from:o&&typeof o.chat_id=="string"?o:null,part:e.part,parts:typeof e.parts=="number"?e.parts:e.part+1,items:n}}case"voice":return typeof e.voice_id!="string"||e.voice_id===""||typeof e.status!="string"?void 0:{...e,type:"voice",seq:i,user_id:typeof e.user_id=="string"?e.user_id:null};case"transcript":return typeof e.id!="string"||e.id===""||typeof e.text!="string"?void 0:{type:"transcript",seq:i,id:e.id,voice_id:typeof e.voice_id=="string"?e.voice_id:"",role:typeof e.role=="string"?e.role:"",user_id:typeof e.user_id=="string"?e.user_id:null,author_name:typeof e.author_name=="string"?e.author_name:"",text:e.text,final:e.final!==!1,created_at:typeof e.created_at=="string"?e.created_at:""};default:return}}function b(t){let r=0;for(let s=0;s<t.length;s++){let e=t.charCodeAt(s);e<128?r+=1:e<2048?r+=2:e>=55296&&e<=56319&&s+1<t.length&&(t.charCodeAt(s+1)&64512)===56320?(r+=4,s++):r+=3}return r}function l(t,r){if(r<=0)return 0;let s=0;for(let e=0;e<t.length;e++){let i=t.charCodeAt(e),n=3,o=1;if(i<128?n=1:i<2048?n=2:i>=55296&&i<=56319&&e+1<t.length&&(t.charCodeAt(e+1)&64512)===56320&&(n=4,o=2),s+=n,s>=r)return e+o;e+=o-1}return t.length}function v(t,r){return t.slice(l(t,r))}export{h as a,_ as b,b as c,l as d,v as e};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
/*! palbase 0.10.1 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{c as D,g as b,l as O,m as _,s as F}from"./FHXGE2MX.js";import{b as w}from"./RWGEPDRQ.js";var I=20,M=2048,S=256,j=/^[A-Za-z][A-Za-z0-9_.-]{0,39}$/,m=e=>new w({op:"GetPlacementPaywall",status:0,code:"invalid_attributes",message:e});function L(e){let n='"';for(let t=0;t<e.length;t++){let a=e.charCodeAt(t);a===34?n+='\\"':a===92?n+="\\\\":a>=32&&a<=126?n+=e[t]:n+=`\\u${a.toString(16).padStart(4,"0")}`}return`${n}"`}function T(e){let n=Object.keys(e??{}).sort((i,r)=>i<r?-1:i>r?1:0);if(n.length===0)return;if(n.length>I)throw m(`${n.length} attributes: at most ${I}`);let t=[];for(let i of n){if(!j.test(i))throw m(`the attribute ${JSON.stringify(i)}: a key is a letter, then letters, digits and _ . -, at most 40`);let r=e[i],s;if(typeof r=="string"){if(new TextEncoder().encode(r).length>S)throw m(`the attribute ${JSON.stringify(i)} is over ${S} bytes`);s=L(r)}else if(typeof r=="number"){if(!Number.isFinite(r))throw m(`the attribute ${JSON.stringify(i)} is no number`);s=String(Object.is(r,-0)?0:r)}else if(typeof r=="boolean")s=r?"true":"false";else throw m(`the attribute ${JSON.stringify(i)}: a value is a text, a number or a boolean`);t.push(`"${i}":${s}`)}let a=`{${t.join(",")}}`;if(a.length>M)throw m(`the attributes are ${a.length} bytes: at most ${M}`);return a}function x(e){let n=/^P(\d+)([DWMY])$/.exec(e??"");if(!n)return null;let t=Number(n[1]);if(!Number.isSafeInteger(t)||t<1)return null;switch(n[2]){case"D":return{count:t,unit:"day",months:t*12/365};case"W":return{count:t,unit:"week",months:t*12/52};case"M":return{count:t,unit:"month",months:t};default:return{count:t,unit:"year",months:t*12}}}function R(e){try{return new Intl.NumberFormat("en",{style:"currency",currency:e}).resolvedOptions().maximumFractionDigits??2}catch{return 2}}function $(e,n,t){let a=e/10**R(n);try{return new Intl.NumberFormat(t,{style:"currency",currency:n}).format(a)}catch{return`${a.toFixed(R(n))} ${n}`}}function X(e,n){try{let t=new Intl.NumberFormat(n,{style:"unit",unit:e.unit,unitDisplay:"long"});return e.count>1?t.format(e.count):t.formatToParts(1).filter(i=>i.type==="unit").map(i=>i.value).join("").trim()||t.format(1)}catch{return e.count>1?`${e.count} ${e.unit}s`:e.unit}}var K={en:e=>`${e} free`,tr:e=>`${e} \xFCcretsiz`,de:e=>`${e} kostenlos`,es:e=>`${e} gratis`,it:e=>`${e} gratis`,nl:e=>`${e} gratis`,pt:e=>`${e} gr\xE1tis`,sv:e=>`${e} gratis`,da:e=>`${e} gratis`,nb:e=>`${e} gratis`};function B(e,n){let t;try{t=new Intl.NumberFormat(n,{style:"unit",unit:e.unit,unitDisplay:"long"}).format(e.count)}catch{t=`${e.count} ${e.unit}${e.count>1?"s":""}`}let a=K[n.split("-")[0].toLowerCase()];return a?a(t):t}function H(e,n){try{return new Intl.NumberFormat(n,{style:"percent",maximumFractionDigits:0}).format(e)}catch{return`${Math.round(e*100)}%`}}function E(e,n){let t=new Map,a=new Map;for(let r of e){let s=x(r.period);if(!s)continue;let u=r.price.amount/s.months;t.set(r.key,u),a.set(r.price.currency,Math.max(a.get(r.price.currency)??0,u))}let i={};for(let r of e){let s={product_name:r.productName,price:$(r.price.amount,r.price.currency,n)},u=x(r.period);if(u){s.period=X(u,n),s.price_per_month=$(Math.round(t.get(r.key)),r.price.currency,n);let o=a.get(r.price.currency)??0,d=o>0?Math.floor((1-t.get(r.key)/o)*100)/100:0;d>=.01&&(s.savings=H(d,n))}let l=r.intro?.mode==="free_trial"?x(r.intro.duration):null;l&&(s.trial=B(l,n)),r.offer&&(s.offer_price=$(Math.floor((r.price.amount*(100-r.offer.percentOff)+50)/100),r.price.currency,n)),i[r.key]=s}return i}var V={version:"0.10.1"};var C=`palbase-js/${V.version}`;var k=class{placement;source;definition;assets;offerings;offers;shown;deps;exposed=!1;constructor(n,t,a,i,r,s,u={},l=[]){this.placement=n,this.source=t,this.definition=a,this.assets=u,this.offerings=i,this.offers=l,this.shown=r,this.deps=s}packages(n){return E(Y(this.offerings,O(this.definition),n,Z(this.definition,this.offers)),n)}render(n,t){let a=t.locale??globalThis.navigator?.language??this.definition.default_locale,i=t.appearance===void 0?q():void 0,r=this.packages(a),s=F(n,{definition:this.definition,locale:a,appearance:t.appearance??(i?.matches?"dark":"light"),platform:"web",packages:r,eligible:Object.entries(r).filter(([,o])=>o.trial).map(([o])=>o),offers:this.offers.filter(o=>o.web).map(o=>o.key),links:t.links,assets:this.assets},{onPurchase:async o=>{try{let d=await this.deps.checkout({product:o.product,plan:o.plan,successUrl:t.successUrl,cancelUrl:t.cancelUrl,...o.offer!==void 0?{offer:o.offer}:{}});t.onCheckout?t.onCheckout(d,o):globalThis.location.assign(d)}catch(d){if(!t.onError)throw d;t.onError(d,o)}},onClose:t.onClose,onLink:t.onLink,labels:t.labels}),u=o=>s.update({appearance:o.matches?"dark":"light"});i?.addEventListener?.("change",u),!this.exposed&&this.shown&&(this.exposed=!0,this.deps.expose(this));let l=s.destroy.bind(s);return s.destroy=()=>{i?.removeEventListener?.("change",u),l()},s}};function q(){try{return globalThis.matchMedia?.("(prefers-color-scheme: dark)")}catch{return}}function W(e,n){if(!e)return;let t=n.split("-")[0];return e[n]?.name??e[t]?.name??Object.values(e).find(a=>a.name)?.name}function Y(e,n,t,a=new Map){let i=[];for(let r of n){let[s,u]=r.split("."),l=e.products.find(f=>f.key===s),o=l?.channels.web,d=o?.plans.find(f=>f.key===u);if(!l||!o||!d)continue;let p=a.get(r),g=p?.discount?p.discount.percent:p?.trial?100:void 0;i.push({key:r,productName:W(o.locales,t)??l.key,price:{amount:d.price.amount,currency:d.price.currency},period:d.period,intro:d.intro,...g!==void 0?{offer:{percentOff:g}}:{}})}return i}function Z(e,n){let t=new Map;for(let[a,i]of _(e)){let r=n.find(s=>s.key===i);r?.web&&t.set(a,r)}return t}var G={en:{cta:"Continue",terms:"Terms",privacy:"Privacy"},tr:{cta:"Devam et",terms:"Ko\u015Fullar",privacy:"Gizlilik"},de:{cta:"Weiter",terms:"Bedingungen",privacy:"Datenschutz"},es:{cta:"Continuar",terms:"T\xE9rminos",privacy:"Privacidad"},fr:{cta:"Continuer",terms:"Conditions",privacy:"Confidentialit\xE9"},it:{cta:"Continua",terms:"Termini",privacy:"Privacy"},pt:{cta:"Continuar",terms:"Termos",privacy:"Privacidade"},nl:{cta:"Doorgaan",terms:"Voorwaarden",privacy:"Privacy"},ja:{cta:"\u7D9A\u3051\u308B",terms:"\u5229\u7528\u898F\u7D04",privacy:"\u30D7\u30E9\u30A4\u30D0\u30B7\u30FC"}},N=e=>({type:"button",action:{type:e},content:{type:"text",text:{t:e},size:"caption",color:"muted"}});function Q(e){let n=e.products.flatMap(t=>(t.channels.web?.plans??[]).map(a=>({product:t.key,plan:a.key}))).slice(0,6);return n.length===0?null:{schema:2,name:"Default",default_locale:"en",locales:G,theme:{colors:{light:{background:"#FFFFFF",surface:"#F2F2F7",text:"#111114",muted:"#6B6B70",accent:"#111114",on_accent:"#FFFFFF",stroke:"#E5E5EA"},dark:{background:"#000000",surface:"#1C1C1E",text:"#F5F5F7",muted:"#9A9AA0",accent:"#F5F5F7",on_accent:"#000000",stroke:"#2C2C2E"}},typography:{headline:{size:17,weight:600,text_style:"headline"},caption:{size:13,weight:400,text_style:"footnote"}},radii:{card:14},spacing:{sm:8,md:16,lg:24}},root:{type:"stack",spacing:"md",align:"stretch",style:{padding:"lg"},children:[{type:"stack",axis:"horizontal",children:[{type:"spacer"},{type:"button",action:{type:"close"},content:{type:"icon",name:"close",color:"muted",size:22}}]},{type:"spacer"},{type:"stack",spacing:"sm",align:"stretch",children:n.map(({product:t,plan:a})=>({type:"package",product:t,plan:a,style:{padding:"md",corners:"card",background:"surface",border:{width:1,color:"stroke"}},states:{selected:{border:{width:2,color:"accent"}}},children:[{type:"stack",axis:"horizontal",spacing:"sm",children:[{type:"stack",align:"start",spacing:2,children:[{type:"text",text:"{{product_name}}",size:"headline",align:"start"},{type:"text",text:"{{period}}",size:"caption",color:"muted",align:"start"}]},{type:"spacer"},{type:"text",text:"{{price}}",size:"headline"}]}]}))},{type:"purchase_button",style:{padding:"md",corners:"card",background:"accent"},content:{type:"text",text:{t:"cta"},size:"headline",color:"on_accent"}},{type:"stack",axis:"horizontal",spacing:"md",distribution:"center",children:[N("terms"),N("privacy")]}]}}}function h(){try{return globalThis.localStorage}catch{return}}function ee(e){try{let n=h()?.getItem(e);if(!n)return;let t=JSON.parse(n),a=t?.answer;return typeof a!="object"||a===null||typeof a.paywall_id!="string"||typeof a.version!="number"||typeof a.definition!="object"||a.definition===null||typeof a.offerings!="object"||a.definition.schema!==2?void 0:{etag:typeof t.etag=="string"?t.etag:void 0,answer:a}}catch{return}}function P(e,n){try{n?h()?.setItem(e,JSON.stringify(n)):h()?.removeItem(e)}catch{}}var z=()=>globalThis.crypto?.randomUUID?globalThis.crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,U;function te(e){let n=`palbase.installation.${e}`;try{let t=h()?.getItem(n);if(t&&/^[A-Za-z0-9._:-]{1,128}$/.test(t))return t;let a=z();if(h()?.setItem(n,a),h()?.getItem(n)===a)return a}catch{}return U??=z(),U}async function ye(e,n,t,a,i={}){let{signal:r,fetch:s}=i,u=T(i.attributes),l=`palbase.paywall.${n}.${t}`,o=te(n),p={checkout:a,expose:async c=>{if(c.shown)try{let v={paywall_id:c.shown.paywallId,version:c.shown.version,...c.shown.variant!==void 0?{variant:c.shown.variant}:{},...c.shown.ruleId!==void 0?{rule_id:c.shown.ruleId}:{}};await e.recordPaywallExposure({path:{placement:t},headers:{"X-Palbase-Installation":o},body:v})}catch{}}},g=async(c,v)=>new k(t,v,c.definition,c.offerings,{paywallId:c.paywall_id,version:c.version,...c.variant!==void 0?{variant:c.variant}:{},...c.rule_id!==void 0?{ruleId:c.rule_id}:{}},p,await D(c.assets??[],{signal:r,...s?{fetch:s}:{}}),c.offers??[]),f=ee(l),y;try{y=await e.getPlacementPaywall({path:{placement:t},query:{channel:"web"},headers:{"X-Palbase-Paywall-Schema":2,"X-Palbase-Installation":o,"X-Platform":"web","X-Palbase-SDK":C,...i.appVersion?{"X-Palbase-Client-Version":i.appVersion}:{},...i.app?{"X-Palbase-App":i.app}:{},...i.locale?{"Accept-Language":i.locale}:{},...u!==void 0?{"X-Palbase-Attributes":u}:{},...f?.etag?{"If-None-Match":f.etag}:{}},signal:r})}catch(c){if(c instanceof w&&c.status===404||c instanceof w&&c.status===400&&c.code.startsWith("invalid_"))return P(l,void 0),A(e,t,p,r);if(f&&!r?.aborted)return g(f.answer,"cache");throw c}return y.status===200?(P(l,{etag:y.headers.get("etag")??void 0,answer:y.data}),g(y.data,"server")):y.status===304&&f?g(f.answer,"server"):(P(l,void 0),A(e,t,p,r))}async function A(e,n,t,a){let i=(await e.getOfferings({query:{channel:"web"},signal:a})).data,r=Q(i);return r?new k(n,"default",r,i,void 0,t):null}export{T as a,x as b,$ as c,X as d,E as e,k as f,Q as g,ye as h};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
2
|
-
import{p as R,t as k,u as H}from"./
|
|
1
|
+
/*! palbase 0.10.1 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{p as R,t as k,u as H}from"./FHXGE2MX.js";var N=40,V=`
|
|
3
3
|
:host{display:contents}
|
|
4
4
|
.pm-modal,.pm-full{position:fixed;inset:0;width:100%;height:100%;max-width:none;max-height:none;margin:0;border:0;background:transparent;color:inherit;overflow:hidden;display:flex;flex-direction:column}
|
|
5
5
|
.pm-modal::backdrop,.pm-full::backdrop{background:transparent}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
1
|
+
/*! palbase 0.10.1 — Palbase SDK License (see LICENSE) */
|
|
2
2
|
import{lstat as j,mkdir as F,readdir as M,readFile as N,rename as J,rm as T,writeFile as v}from"node:fs/promises";import{join as E}from"node:path";var o="palbase/strings",f="_meta.json",p=3,y=2,$=r=>typeof r=="object"&&r!==null&&!Array.isArray(r);function m(r){try{return Intl.getCanonicalLocales(r)[0]}catch{return}}function b(r,n){try{return JSON.parse(r)}catch(t){throw new Error(`${n} is not JSON: ${t.message}`)}}async function x(r){let n=E(r,o);try{if(!(await j(n)).isDirectory())throw new Error(`${o} is not a directory: the strings live in a directory of their own`)}catch(e){if(e.code==="ENOENT")return;throw e}let t=new Map;for(let e of await M(n,{withFileTypes:!0}))if(!(e.name.startsWith(".")||!e.name.endsWith(".json"))){if(!e.isFile())throw new Error(`${o}/${e.name} is not a regular file`);t.set(e.name,await N(E(n,e.name),"utf8"))}return t.size===0?void 0:t}async function R(r,n=[p,y]){let t=await x(r);if(t===void 0)return;let e=t.get(f);if(e===void 0)throw new Error(`${o}/${f} is missing: it names the source language, and without it the language files are not a table`);let u=b(e,`${o}/${f}`);if(!$(u))throw new Error(`${o}/${f}: not a JSON object`);let s=u.version;if(s===y&&!n.includes(y))throw new Error(`${o}/${f}: version 2 is the earlier format ({"value", "state"} for each sentence) \u2014 run \`npx palbase strings\` once, and it writes the table as version ${p}`);if(typeof s!="number"||!n.includes(s))throw new Error(`${o}/${f}: version ${JSON.stringify(s)} is not one this reads (${n.join(" or ")})`);let a=u.source;if(typeof a!="string"||m(a)!==a)throw new Error(`${o}/${f}: source ${JSON.stringify(a)} is not a language tag as it is written (${m(String(a))??"en, en-US, zh-Hans"})`);let S=new Map;for(let w of[...t.keys()].sort()){if(w===f)continue;let i=w.slice(0,-5),g=`${o}/${w}`,d=m(i);if(d===void 0)throw new Error(`${g}: ${JSON.stringify(i)} is not a language tag`);if(d!==i)throw new Error(`${g}: the language is written ${d} \u2014 name the file ${d}.json`);if(i===a)throw new Error(`${g}: ${i} is the source language \u2014 its text is the key itself, and it has no file`);if(i==="und"||i==="root"||i.startsWith("x-"))throw new Error(`${g}: ${i} is no language a request names \u2014 name the file for one (en, de, pt-BR)`);let O=b(t.get(w),g);if(!$(O))throw new Error(`${g}: not a JSON object of "sentence": "translation"`);let h=new Map;for(let[l,c]of Object.entries(O))if(s===p){if(typeof c!="string")throw new Error(`${g}: the translation of ${JSON.stringify(l)} is not a string`);h.set(l,c)}else if(typeof c=="string")h.set(l,c);else{if(!$(c)||typeof c.value!="string")throw new Error(`${g}: key ${JSON.stringify(l)} is not {"value": string, "state": string}`);h.set(l,c.state==="missing"?"":c.value)}S.set(i,h)}return{format:s,source:a,languages:S}}async function A(r){let n=await R(r,[p]);if(n===void 0)return;let t={};Object.setPrototypeOf(t,null);for(let[e,u]of n.languages)for(let[s,a]of u)Object.hasOwn(t,s)||(t[s]={},Object.setPrototypeOf(t[s],null)),t[s][e]=a;return{source:n.source,locales:[n.source,...n.languages.keys()],strings:t}}export{A as a};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
1
|
+
/*! palbase 0.10.1 — Palbase SDK License (see LICENSE) */
|
|
2
2
|
var u="X-PoW-Challenge-ID",c="X-PoW-Nonce";function m(e){if(typeof e!="object"||e===null)return null;let t=e;if(t.error!=="pow_required"||typeof t.challenge!="object"||t.challenge===null)return null;let{id:n,prefix:r,difficulty:o}=t.challenge;return typeof n!="string"||typeof r!="string"||typeof o!="number"||!Number.isInteger(o)||o<0?null:{id:n,prefix:r,difficulty:o}}function d(e){return 8*2**e}var s;async function l(){if(s)return s;let e=globalThis;if(e.process?.versions?.node!==void 0||e.process?.versions?.bun!==void 0)try{let r=(await import("node:crypto")).createHash;if(typeof r=="function")return s=o=>new Uint8Array(r("sha256").update(o).digest()),s}catch{}let t=new TextEncoder;return s=async n=>new Uint8Array(await crypto.subtle.digest("SHA-256",t.encode(n))),s}function p(e){let t=0;for(let n of e){if(n===0){t+=8;continue}return t+Math.clz32(n)-24}return t}var w=4096,g=typeof globalThis.setImmediate=="function"?()=>new Promise(e=>globalThis.setImmediate(e)):()=>new Promise(e=>setTimeout(e,0));async function y(e,t={}){if(e.difficulty>24)throw new Error(`proof-of-work: difficulty ${e.difficulty} is above auth's ceiling of 24`);let n=await l(),r=d(e.difficulty),o=Date.now()+(t.timeLimitMs??12e4);for(let i=0;i<r;i++){if(i%w===0&&i>0){if(await g(),t.signal?.aborted)throw t.signal.reason??new DOMException("proof-of-work aborted","AbortError");if(Date.now()>o)throw new Error(`proof-of-work: gave up on difficulty ${e.difficulty} after ${i} attempts`)}let f=n(e.prefix+i),a=f instanceof Uint8Array?f:await f;if(p(a)>=e.difficulty)return{[u]:e.id,[c]:String(i)}}throw new Error(`proof-of-work: no nonce for difficulty ${e.difficulty} within ${r} attempts`)}export{m as a,y as b};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
2
|
-
import"./
|
|
1
|
+
/*! palbase 0.10.1 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import"./XYXBDSXW.js";import{pathToFileURL as i}from"node:url";import{z as c}from"zod";async function f(e){let n=new Map,t=new Map;for(let r of e){let a=`${r.className}.${r.method}`,o=t.get(r.className);if(o!==void 0&&o!==r.file)throw new Error(`two controllers are named ${r.className} (${o}, ${r.file}): the contract tells routes apart by their class's name \u2014 rename one`);t.set(r.className,r.file),n.set(a,{returns:await u(r),throws:r.throws})}return r=>n.get(`${r.controller.name}.${r.fn}`)}async function u(e){let n=`${e.file} \u2014 ${e.className}.${e.method}`;switch(e.returns.kind){case"void":return{kind:"void"};case"raw":return{kind:"raw"};case"schema":{let r=(await import(i(e.returns.file).href))[e.returns.exportName];if(!s(r))throw new Error(`${n}: its return type names ${e.returns.exportName}, which ${e.returns.file} exports as no schema (a zod, valibot or arktype schema)`);return{kind:"json",schema:r,array:e.returns.array}}case"expression":{let t=new Function("z",`return (${e.returns.expression});`)(c);if(!s(t))throw new Error(`${n}: the schema made of its return type is not one`);return{kind:"json",schema:t,array:!1}}}}function s(e){return typeof e=="object"&&e!==null&&typeof e["~standard"]?.validate=="function"}export{f as routeContracts};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
2
|
-
import{e as Re,g as Ae,h as Oe}from"./ZRV54HT6.js";import{h as Ce}from"./PUILCUFX.js";import{a as Ee}from"./MALOKTVW.js";import{r as xe,t as Pe,u as Te}from"./4DDSGFFD.js";import{b as V,c as K,e as Se,g as j,h as _e}from"./ZHHMA7V4.js";import{a as Ie,b as F}from"./I56MGYTD.js";import{b as I,d as U}from"./XGWTZGWR.js";function ht(n){let e=n,t=e?.body,s=t&&typeof t=="object"?t.reason:void 0;return s==="user_deleted"?"userDeleted":s==="user_banned"?"userBanned":e?.code==="session_expired"||e?.code==="token_expired"?"expired":"revoked"}var T=class extends Error{code="session_changed";constructor(e){super(e),this.name="SessionChangedError"}};function Me(){let n=null;return{load:()=>n,save:e=>{n=e},clear:()=>{n=null},shared:!1}}function Ne(n){let e=null,t=!0,s=()=>{try{return globalThis.localStorage}catch{return}};return{shared:!0,load(){try{let i=s()?.getItem(n);return i==null?t?null:e:JSON.parse(i)}catch{return e}},save(i){e=i;try{let r=s();if(!r)throw new Error("no storage");r.setItem(n,JSON.stringify(i)),t=!0}catch{t=!1}},clear(){e=null,t=!0;try{s()?.removeItem(n)}catch{}},watch(i){let r=globalThis;if(typeof r.addEventListener!="function")return()=>{};let a=o=>{(o.key===n||o.key===null)&&i()};return r.addEventListener("storage",a),()=>r.removeEventListener?.("storage",a)}}}function fe(n){try{let e=n.split(".")[1]??"",t=atob(e.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(e.length/4)*4,"=")),s=JSON.parse(t).sub;return typeof s=="string"?s:""}catch{return""}}var pt=6e4,ft=15e3;function gt(n,e,t){let s=n?globalThis.navigator?.locks:void 0;return s?s.request(e,t):t()}var W=class{current=null;loaded;inflight=null;endReason=null;listeners=new Set;store;refresher;isRejected;now;lockName;refreshTimeoutMs;mode;constructor(e,t,s,i={}){this.store=e,this.refresher=t,this.isRejected=s,this.now=i.now??Date.now,this.lockName=i.lockName??"palbase.session.refresh",this.refreshTimeoutMs=i.refreshTimeoutMs??ft,this.mode=i.refresh??"behind",this.loaded=Promise.resolve(e.load()).then(r=>{this.current=r}),e.watch?.(()=>{this.reconcile()})}async session(){return await this.loaded,this.current}snapshot(){return this.current}onChange(e){return this.listeners.add(e),()=>this.listeners.delete(e)}async set(e,t,s){await this.loaded;let i=t==="TOKEN_REFRESHED"?this.current:null,r={accessToken:e.access_token,refreshToken:e.refresh_token,expiresAt:this.now()+e.expires_in*1e3,userId:s?.id??i?.userId??fe(e.access_token),user:s??i?.user};return this.current=r,await this.store.save(r),this.emit(t,r),r}async setUser(e,t){await this.loaded,!(!this.current||!t||this.current.userId!==t.userId)&&(this.current={...this.current,user:e},await this.store.save(this.current),this.emit("USER_UPDATED",this.current))}async clear(e,t){await this.loaded;let s=this.current;this.current=null,this.inflight=null;let i=await this.store.load();(!i||!s||i.userId===s.userId)&&await this.store.clear(),s&&(e==="SESSION_EXPIRED"&&(this.endReason=t??"revoked"),this.emit(e,null))}async accessToken(){await this.loaded;let e=this.current;if(!e)return;let t=e.expiresAt-this.now();if(t>pt)return e.accessToken;if(this.mode==="never")return t>0?e.accessToken:void 0;if(t>0&&this.mode==="behind")return this.refresh().catch(()=>{}),e.accessToken;if(t>0)try{return(await this.refresh()).accessToken}catch(s){if(this.current===e)return e.accessToken;throw s}return(await this.refresh()).accessToken}refresh(){if(this.mode==="never")return Promise.reject(new Error("this client does not renew its session (refresh: 'never'): where the session cannot be written back, the request's middleware renews it"));if(this.inflight)return this.inflight;let e=gt(this.store.shared===!0,this.lockName,async()=>{await this.loaded;let t=this.current;if(!t)throw new T("no session to refresh");let s=await this.adoptStored(t);if(s)return s;try{let i=await this.withTimeout(this.refresher(t.refreshToken));if(this.current?.refreshToken!==t.refreshToken)throw new T("the session changed while it was refreshed");return await this.set(i,"TOKEN_REFRESHED")}catch(i){throw this.isRejected(i)&&this.current?.refreshToken===t.refreshToken&&await this.clear("SESSION_EXPIRED",ht(i)),i}});return this.inflight=e,e.finally(()=>{this.inflight===e&&(this.inflight=null)}).catch(()=>{}),e}async adoptStored(e){let t=await this.store.load();if(!t)throw this.current=null,this.emit("SIGNED_OUT",null),new T("signed out in another tab");if(t.userId!==e.userId)throw this.current=t,this.emit("SIGNED_OUT",null),this.emit("SIGNED_IN",t),new T("another user signed in in another tab");if(t.refreshToken!==e.refreshToken&&t.expiresAt>=e.expiresAt)return this.current=t,this.emit("TOKEN_REFRESHED",t),t}async reconcile(){await this.loaded;let e=this.current,t=await this.store.load();if(!e){t&&(this.current=t,this.emit("SIGNED_IN",t));return}await this.adoptStored(e).catch(()=>{})}withTimeout(e){let t,s=new Promise((i,r)=>{t=setTimeout(()=>r(new Error(`the refresh did not answer within ${this.refreshTimeoutMs/1e3} s`)),this.refreshTimeoutMs)});return Promise.race([e,s]).finally(()=>clearTimeout(t))}emit(e,t){(e==="SIGNED_IN"||e==="SIGNED_OUT")&&(this.endReason=null);for(let s of this.listeners)try{s(e,t)}catch{}}};var ge=class{state="closed";refusal;logSeq;joinRef=null;listeners=new Map;closers=new Set;joinWaiters=[];name;socket;constructor(e,t,s={}){this.name=e,this.socket=t,this.logSeq=s.after}get topic(){return`realtime:${this.name}`}join(){if(this.state==="joined")return Promise.resolve();let e=new Promise((t,s)=>this.joinWaiters.push({resolve:t,reject:s}));return this.state!=="joining"&&this.socket.join(this),e}leave(){this.socket.leave(this)}push(e,t){return this.socket.request(this,e,t)}on(e,t){let s=this.listeners.get(e);return s||this.listeners.set(e,s=new Set),s.add(t),()=>s.delete(t)}onClosed(e){return this.closers.add(e),()=>this.closers.delete(e)}deliver(e,t){e==="broadcast"&&typeof t.seq=="number"&&(this.logSeq=t.seq);for(let s of this.listeners.get(e)??[])try{s(t)}catch{}}settled(e,t){e&&typeof t.log_seq=="number"&&(this.logSeq=t.log_seq),this.state=e?"joined":"refused",this.refusal=e?void 0:t;let s=this.joinWaiters.splice(0);for(let i of s)e?i.resolve():i.reject(new Error(`join ${this.name} refused: ${JSON.stringify(t)}`))}closed(e){this.state="closed",this.joinRef=null;let t=this.joinWaiters.splice(0);for(let s of t)s.reject(new Error(`join ${this.name}: ${e}`));for(let s of[...this.closers])try{s()}catch{}}},B=class{ws=null;opening=null;ref=0;channels=new Map;replies=new Map;heartbeat=null;heartbeatRef=null;reconnectTimer=null;attempts=0;closedByUs=!1;reconnects=0;opts;constructor(e){this.opts=e}channel(e,t){let s=this.channels.get(e);return s||this.channels.set(e,s=new ge(e,this,t)),s}disconnect(){this.closedByUs=!0,this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=null,this.stopHeartbeat();let e=this.ws;this.ws=null,this.opening=null,e?.close(1e3);for(let[,t]of this.replies)t("error",{reason:"socket closed"});this.replies.clear();for(let t of this.channels.values())t.closed("the socket was closed")}async tokenChanged(){if(!this.ws||this.ws.readyState!==1)return;let e=await this.opts.accessToken();if(e)for(let t of this.channels.values())t.state==="joined"&&this.push(t.joinRef,t.topic,"access_token",{access_token:e})}join(e){e.state="joining",this.open().then(()=>this.sendJoin(e)).catch(t=>e.settled(!1,{reason:t instanceof Error?t.message:String(t)}))}leave(e){e.state==="joined"&&this.ws?.readyState===1&&this.push(e.joinRef,e.topic,"phx_leave",{}),e.state="closed",this.channels.delete(e.name)}async request(e,t,s){let i=this.ws;if(this.channels.get(e.name)!==e||e.state!=="joined"||i?.readyState!==1)return{status:"error",response:{reason:"not joined"}};let r=this.nextRef(),a=JSON.stringify([e.joinRef,r,e.topic,t,s]),o=this.awaitReply(r);return i.send(a),o}open(){if(this.ws?.readyState===1)return Promise.resolve();if(this.opening)return this.opening;this.closedByUs=!1;let e=this.opts.webSocket??globalThis.WebSocket,t=`${this.opts.baseUrl.replace(/^http/,"ws")}/realtime/v1/websocket?vsn=2.0.0&apikey=${encodeURIComponent(this.opts.publishableKey)}`,s=new Promise((i,r)=>{let a=new e(t);this.ws=a,a.onopen=()=>{this.attempts=0,this.startHeartbeat(),i()},a.onmessage=o=>this.receive(String(o.data)),a.onerror=()=>r(new Error("the realtime socket could not be opened")),a.onclose=()=>this.dropped(a)});return this.opening=s,s.finally(()=>{this.opening===s&&(this.opening=null)}).catch(()=>{}),s}dropped(e){if(this.ws!==e)return;this.ws=null,this.stopHeartbeat();for(let[,i]of this.replies)i("error",{reason:"socket closed"});this.replies.clear();for(let i of this.channels.values())i.state==="joined"&&(i.state="joining");if(this.closedByUs||![...this.channels.values()].some(i=>i.state==="joining"))return;let t=this.opts.backoff??[500,1e3,2e3,5e3,1e4,3e4],s=t[Math.min(this.attempts,t.length-1)]*(.8+Math.random()*.4);this.attempts++,this.reconnectTimer=J(setTimeout(()=>{this.reconnectTimer=null,this.reconnects++;let i=[...this.channels.values()].filter(r=>r.state==="joining");this.open().then(()=>Promise.all(i.map(r=>this.sendJoin(r)))).catch(()=>{})},s))}async sendJoin(e){let t=await this.opts.accessToken(),s=this.nextRef();e.joinRef=s;let i=this.awaitReply(s),r={broadcast:{self:!1}};e.logSeq!==void 0&&(r.log={after:e.logSeq}),this.push(s,e.topic,"phx_join",{access_token:t,config:r},s);let{status:a,response:o}=await i;if(this.channels.get(e.name)!==e||e.state!=="joining"){a==="ok"&&this.ws?.readyState===1&&this.push(s,e.topic,"phx_leave",{});return}e.settled(a==="ok",o)}awaitReply(e){return new Promise(t=>{let s=J(setTimeout(()=>{this.replies.delete(e),t({status:"timeout",response:{reason:"no reply"}})},this.opts.replyTimeoutMs??1e4));this.replies.set(e,(i,r)=>{clearTimeout(s),this.replies.delete(e),t({status:i,response:r})})})}receive(e){let t;try{t=JSON.parse(e)}catch{return}if(!Array.isArray(t)||t.length!==5||typeof t[2]!="string"||typeof t[3]!="string")return;let[,s,i,r,a]=t,o=typeof a=="object"&&a!==null?a:{};if(r==="phx_reply"&&typeof s=="string"){if(s===this.heartbeatRef){this.heartbeatRef=null;return}this.replies.get(s)?.(String(o.status),o.response??{});return}let c=[...this.channels.values()].find(l=>l.topic===i);if(c){if(r==="phx_close"){c.state="closed";return}if(r==="phx_error"){c.state="joining",J(setTimeout(()=>this.channels.get(c.name)===c&&c.state==="joining"&&this.ws?.readyState===1&&void this.sendJoin(c),1e3));return}c.deliver(r,o)}}push(e,t,s,i,r=this.nextRef()){this.ws?.send(JSON.stringify([e,r,t,s,i]))}nextRef(){return String(++this.ref)}startHeartbeat(){this.stopHeartbeat(),this.heartbeat=J(setInterval(()=>{if(this.heartbeatRef!==null){this.heartbeatRef=null,this.ws?.close(4e3);return}this.heartbeatRef=this.nextRef(),this.push(null,"phoenix","heartbeat",{},this.heartbeatRef)},this.opts.heartbeatMs??25e3))}stopHeartbeat(){this.heartbeat&&clearInterval(this.heartbeat),this.heartbeat=null,this.heartbeatRef=null}};function J(n){return n.unref?.(),n}var A="X-Palbase-Installation-Secret",z="X-Palbase-Installation",De=new WeakMap;function O(n){return De.get(n)}var Ue=new WeakSet;function Ke(n){return Ue.has(n)}var yt=/^[A-Za-z0-9_-]{43}$/,X=class{id;constructor(e){let t=`palbase.installation.secret.${e}`,s;try{let i=Le()?.getItem(t);i&&yt.test(i)&&(s=i)}catch{}if(!s){Ue.add(this),s=je(crypto.getRandomValues(new Uint8Array(32)));try{Le()?.setItem(t,s)}catch{}}De.set(this,s),this.id=mt(s)}};function mt(n){return je(wt(new TextEncoder().encode(n)).subarray(0,16))}function Le(){try{return globalThis.localStorage}catch{return}}function je(n){let e="";for(let t of n)e+=String.fromCharCode(t);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}var vt=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),E=(n,e)=>n>>>e|n<<32-e;function wt(n){let e=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),t=new Uint8Array(Math.ceil((n.length+9)/64)*64);t.set(n),t[n.length]=128;let s=new DataView(t.buffer);s.setUint32(t.length-8,Math.floor(n.length/536870912)),s.setUint32(t.length-4,n.length*8>>>0);let i=new Uint32Array(64);for(let o=0;o<t.length;o+=64){for(let g=0;g<16;g++)i[g]=s.getUint32(o+g*4);for(let g=16;g<64;g++){let m=E(i[g-15],7)^E(i[g-15],18)^i[g-15]>>>3,k=E(i[g-2],17)^E(i[g-2],19)^i[g-2]>>>10;i[g]=i[g-16]+m+i[g-7]+k|0}let[c,l,d,y,f,b,S,u]=e;for(let g=0;g<64;g++){let m=u+(E(f,6)^E(f,11)^E(f,25))+(f&b^~f&S)+vt[g]+i[g]|0,k=(E(c,2)^E(c,13)^E(c,22))+(c&l^c&d^l&d)|0;u=S,S=b,b=f,f=y+m|0,y=d,d=l,l=c,c=m+k|0}e[0]+=c,e[1]+=l,e[2]+=d,e[3]+=y,e[4]+=f,e[5]+=b,e[6]+=S,e[7]+=u}let r=new Uint8Array(32),a=new DataView(r.buffer);for(let o=0;o<8;o++)a.setUint32(o*4,e[o]);return r}var kt=30*6e4,$e=1e3,St=100,_t=60*1024,Y=()=>globalThis.crypto?.randomUUID?globalThis.crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;function D(){try{return globalThis.localStorage}catch{return}}var Q=class{api;closingApi;perfApi;closingPerfApi;flushMs;flushAt;now;anonKey;sessionKey;onceKey;events=[];samples=[];timer;memoryAnon;memorySession;memoryOnce;appVersion;stopAuto;session;consent;identifyPending=!1;listeners=new Set;people={set:e=>this.person({set:e}),setOnce:e=>this.person({set_once:e}),unset:e=>this.person({unset:[...e]}),add:e=>this.person({add:e})};constructor(e,t,s,i,r,a,o={}){this.session=s,this.consent=i;let c={send:d=>e.send(this.granted("analytics")?{...d,headers:{...d.headers,[z]:r.id}}:d)};this.api=V.client(c);let l={send:d=>(this.granted("analytics")?e:t).send(d)};this.perfApi=V.client(l),this.closingApi=V.client({send:d=>c.send({...d,keepalive:!0})}),this.closingPerfApi=V.client({send:d=>l.send({...d,keepalive:!0})}),this.flushMs=o.flushMs??5e3,this.flushAt=o.flushAt??20,this.now=o.now??Date.now,this.anonKey=`palbase.analytics.anonymous.${a}`,this.sessionKey=`palbase.analytics.session.${a}`,this.onceKey=`palbase.analytics.once.${a}`,s.onChange(d=>{d==="SIGNED_IN"?(this.identifyPending=!0,this.soon()):d==="SIGNED_OUT"&&(this.identifyPending=!1,this.reset())}),i.onChange((d,y)=>{y!=="granted"&&(d==="analytics"?(this.events=[],this.identifyPending=!1,this.samples=this.samples.map(ye),this.reset()):d==="performance"&&(this.samples=[]))})}capture(e,t){for(let i of this.listeners)i(e,t);if(!this.granted("analytics"))return;let s=this.now();this.hold({event:e,distinct_id:this.distinctId(),properties:t,timestamp:s,session_id:this.sessionId(s),...this.appVersion?{app_version:this.appVersion}:{}})}captureOnce(e,t,s){if(!this.granted("analytics"))return;let i=this.sessionId(this.now()),r=this.readOnce(),a=r?.session===i?r.keys:[];a.includes(e)||(this.writeOnce({session:i,keys:[...a,e].slice(-500)}),this.capture(t,s))}readOnce(){try{let e=D()?.getItem(this.onceKey);if(e)return JSON.parse(e)}catch{}return this.memoryOnce}writeOnce(e){this.memoryOnce=e;try{D()?.setItem(this.onceKey,JSON.stringify(e))}catch{}}onEvent(e){return this.listeners.add(e),()=>this.listeners.delete(e)}page(e={}){let t=globalThis.location,s=globalThis.document,i=e.url??(t?`${t.origin}${$(t.pathname)}`:"");if(!i)return;let r=e.referrer??Rt(s?.referrer);this.capture("$pageview",{...e.properties,url:i,...e.title??s?.title?{title:e.title??s?.title}:{},...r?{referrer:r}:{}})}async identify(e){this.identifyPending=!1;let t=this.session.snapshot()?.userId;!t||!this.granted("analytics")||(await this.flush(),await this.sendIdentify(this.api,t,e))}async sendIdentify(e,t,s){try{await e.identify({body:{distinct_id:t,anonymous_id:this.anonymousId(),traits:s,timestamp:this.now(),sent_at:this.now()}})}catch{}}reset(){this.memoryAnon=void 0,this.memorySession=void 0,this.memoryOnce=void 0;try{D()?.removeItem(this.anonKey),D()?.removeItem(this.sessionKey),D()?.removeItem(this.onceKey)}catch{}}async flush(e=!1){this.timer&&clearTimeout(this.timer),this.timer=void 0,this.granted("analytics")||(this.events=[]),this.granted("performance")?this.granted("analytics")||(this.samples=this.samples.map(ye)):this.samples=[];let t=e?this.closingApi:this.api,s=e?this.closingPerfApi:this.perfApi,i=this.now(),r=this.session.snapshot()?.userId;for(this.identifyPending&&r&&this.granted("analytics")&&(this.identifyPending=!1,await this.sendIdentify(t,r));this.events.length>0;){let a=this.take(this.events,e);try{await t.batch({body:{events:a.map(o=>({...o,sent_at:i}))}})}catch{}}for(;this.samples.length>0;){let a=this.take(this.samples,e);try{await s.sendPerf({body:{items:a}})}catch{}}}start(e={}){this.stopAuto?.(),this.appVersion=e.appVersion;let t=globalThis;if(typeof t.addEventListener!="function"||typeof globalThis.document>"u")return()=>{};let s=[];e.pageViews!==!1&&s.push(this.watchPages(t)),e.webVitals!==!1&&s.push(Pt((a,o)=>this.sample("web_vital",a,o))),e.network!==!1&&s.push(this.watchFetch(t));let i=()=>{document.visibilityState==="hidden"&&this.flush(!0)},r=()=>{this.flush(!0)};return document.addEventListener("visibilitychange",i),t.addEventListener("pagehide",r),s.push(()=>{document.removeEventListener("visibilitychange",i),t.removeEventListener("pagehide",r)}),this.stopAuto=()=>{for(let a of s.splice(0))a();this.stopAuto=void 0},this.stopAuto}granted(e){return this.consent.state(e)==="granted"}async person(e){if(!this.granted("analytics"))return;let t=this.session.snapshot()?.userId,s=this.now();try{await this.api.setPersonProperties({body:{...e,...t?{}:{distinct_id:this.anonymousId()},timestamp:s,sent_at:s}})}catch{}}hold(e){this.events.length>=$e&&this.events.shift(),this.events.push(e),this.soon()}sample(e,t,s,i={}){if(!this.granted("performance"))return;this.samples.length>=$e&&this.samples.shift();let r={row_id:Y(),trace_type:e,name:t,value:Math.max(0,s),timestamp:this.now(),...i};this.samples.push(this.granted("analytics")?{...r,distinct_id:this.distinctId()}:ye(r)),this.soon()}soon(){if(this.events.length+this.samples.length>=this.flushAt){this.flush();return}this.timer||(this.timer=setTimeout(()=>{this.flush()},this.flushMs),this.timer.unref?.())}take(e,t){let s=e.splice(0,St);if(!t)return s;for(;s.length>1&&JSON.stringify(s).length>_t;)e.unshift(s.pop());return s}distinctId(){return this.session.snapshot()?.userId??this.anonymousId()}anonymousId(){let e=D();try{let t=e?.getItem(this.anonKey);if(t)return t;let s=`anon_${Y()}`;if(e?.setItem(this.anonKey,s),e?.getItem(this.anonKey)===s)return s}catch{}return this.memoryAnon??=`anon_${Y()}`,this.memoryAnon}sessionId(e){let t=D(),s=this.memorySession;try{let r=t?.getItem(this.sessionKey);r&&(s=JSON.parse(r))}catch{}let i=s&&e-s.last<kt?{id:s.id,last:e}:{id:`ses_${Y()}`,last:e};this.memorySession=i;try{t?.setItem(this.sessionKey,JSON.stringify(i))}catch{}return i.id}watchPages(e){let t="",s=()=>{let o=`${e.location.origin}${e.location.pathname}`;if(o===t)return;t=o;let c=`${e.location.origin}${$(e.location.pathname)}`;setTimeout(()=>this.page({url:c}),0)},i=e.history,r=i.pushState.bind(i),a=i.replaceState.bind(i);return i.pushState=(...o)=>{r(...o),s()},i.replaceState=(...o)=>{a(...o),s()},e.addEventListener("popstate",s),s(),()=>{i.pushState=r,i.replaceState=a,e.removeEventListener("popstate",s)}}watchFetch(e){let t=e.fetch;if(typeof t!="function")return()=>{};let s=async(i,r)=>{let a=performance.now(),o=i instanceof Request?i:void 0,c=(r?.method??o?.method??"GET").toUpperCase(),l;try{l=new URL(o?.url??String(i),e.location.href)}catch{l=void 0}let d=!!l&&l.pathname.startsWith("/analytics/")||Tt(r?.headers??o?.headers);try{let y=await t(i,r);return l&&!d&&this.sample("network",`${c} ${l.origin}${$(l.pathname)}`,performance.now()-a,{attrs:{status:String(y.status)},...y.headers.get("x-request-id")?{request_id:y.headers.get("x-request-id")}:{}}),y}catch(y){throw l&&!d&&this.sample("network",`${c} ${l.origin}${$(l.pathname)}`,performance.now()-a,{attrs:{status:"0"}}),y}};return e.fetch=s,()=>{e.fetch===s&&(e.fetch=t)}}};function ye(n){let{distinct_id:e,request_id:t,...s}=n;return s}var It=n=>n.entryType==="layout-shift"&&"value"in n&&"hadRecentInput"in n,xt=n=>n.entryType==="event"||n.entryType==="first-input";function Z(n,e){if(!(typeof PerformanceObserver>"u"))try{let t=new PerformanceObserver(s=>e(s.getEntries()));return t.observe({type:n,buffered:!0}),t}catch{return}}function Pt(n){if(typeof document>"u"||typeof performance>"u"||typeof performance.getEntriesByType!="function")return()=>{};let e=0,t=0,s=0,i=[Z("largest-contentful-paint",l=>{for(let d of l)e=Math.max(e,d.startTime)}),Z("layout-shift",l=>{for(let d of l)It(d)&&!d.hadRecentInput&&(t+=d.value)}),Z("event",l=>{for(let d of l)xt(d)&&(s=Math.max(s,d.duration))}),Z("paint",l=>{for(let d of l)d.name==="first-contentful-paint"&&n("FCP",d.startTime)})],r=performance.getEntriesByType("navigation")[0];r&&r.responseStart>0&&n("TTFB",r.responseStart);let a=!1,o=()=>{a||(a=!0,e>0&&n("LCP",e),n("CLS",t),s>0&&n("INP",s))},c=()=>{document.visibilityState==="hidden"&&o()};return document.addEventListener("visibilitychange",c),()=>{o(),document.removeEventListener("visibilitychange",c);for(let l of i)l?.disconnect()}}function Tt(n){if(!n)return!1;try{return new Headers(n).has("next-router-prefetch")}catch{return!1}}var Et=/^[a-z][a-z0-9_-]{0,31}$/;function $(n){return n.split("/").map(e=>{if(e==="")return e;let t=e.split(";",1)[0],s=t.toLowerCase();return Et.test(s)&&(s.match(/\d/g)?.length??0)<=2&&t.slice(1)===s.slice(1)&&s.split(/[-_]/).every(r=>r.length<=16)?s:":id"}).join("/")}function Rt(n){if(!n)return"";try{let e=new URL(n);return`${e.origin}${$(e.pathname)}`}catch{return $(n.split(/[?#]/,1)[0]??"")}}var Ye=/^custom\.[a-z0-9_]{1,48}$/,At=/^[a-z][a-z0-9_]{0,63}$/,qe=n=>At.test(n)||Ye.test(n),Ot=50,Ve=[5e3,3e4,12e4,6e5],Ct=100,te=class{userApi;deviceApi;session;socket;ref;installation;start;textVersion;customKeys;storeKey;now;kept;listeners=new Set;engaged=!1;platformKeys;watch;sending;sendAgain=!1;retryTimer;retries=0;readFor;stale=!1;lastW=0;lastChosen=0;gpc=globalThis.navigator?.globalPrivacyControl===!0;constructor(e){let t=e.options??{};for(let[c,l]of Object.entries(t.start??{})){if(!qe(c))throw new TypeError(`consent.start: ${JSON.stringify(c)} is not a consent key (a platform key, or custom.<name>)`);if(l!=="granted"&&l!=="denied")throw new TypeError(`consent.start.${c} is granted or denied`)}for(let c of t.customKeys??[])if(!Ye.test(c))throw new TypeError(`consent.customKeys: ${JSON.stringify(c)} is not custom.<name> (a-z, 0-9 and _, 48 at most)`);if(t.textVersion!==void 0&&(t.textVersion===""||t.textVersion.length>64))throw new TypeError("consent.textVersion: 1 to 64 characters");this.userApi=e.userApi,this.deviceApi=e.deviceApi,this.session=e.session,this.socket=e.socket,this.ref=e.ref,this.installation=e.installation,this.start={...t.start},this.textVersion=t.textVersion,this.customKeys=[...t.customKeys??[]],this.storeKey=`palbase.consent.${e.origin}.${e.installation.id}`,this.now=e.now??Date.now;let s=this.load(),i=()=>Ke(this.installation)?{}:{unknown:{on:!0,w:this.stamp()}},r={whose:null,install:this.installation.id,choices:{},unsent:[]};typeof s!="object"?this.kept={...r,...s==="unreadable"?{unknown:{on:!0,w:this.stamp()}}:i()}:s.whose==null&&s.install!==void 0&&s.install!==this.installation.id?this.kept={...r,unsent:s.unsent.filter(c=>c.user!==null),...s.keys?{keys:s.keys}:{},...i()}:this.kept=s,e.session.onChange((c,l)=>{this.engaged&&(c==="SIGNED_IN"&&l?this.signedIn(l):(c==="SIGNED_OUT"||c==="SESSION_EXPIRED")&&this.signedOut())});let a=globalThis;typeof a.addEventListener=="function"&&(a.addEventListener("storage",c=>{(c.key===this.storeKey||c.key===null)&&this.reload()}),a.addEventListener("online",()=>{this.engaged&&this.send()}));let o=this.kept;(e.options!==void 0||s!=="empty"&&(o.unknown?.on||o.unsent.length>0||o.link!==void 0||Object.keys(o.choices).length>0))&&this.engage()}async keys(){return this.engage(),[...(await this.platform()).map(t=>({key:t.key,category:t.category,title:{...t.title},description:{...t.description},ads:t.ads})),...this.customKeys.map(t=>({key:t,category:"custom",title:{},description:{},ads:!1}))]}state(e){if(_(this.kept)!==this.holder()||this.gpcRefuses(e))return"denied";let t=Ge(this.kept,e);return t&&t.state!=="unset"?t.state:this.kept.unknown?.on?"denied":this.start[e]}owesRead(){return this.stale||this.kept.unknown?.on===!0||_(this.kept)!==this.holder()||Object.values(this.kept.choices).some(e=>e.provisional)}holder(){let e=this.session.snapshot()?.userId;return e?`user:${e}`:`device:${this.installation.id}`}lastDeniedAt(e){let t=this.kept.choices[e]?.last_denied_at;return t?new Date(t):void 0}set(e,t){this.setMany({[e]:t})}setMany(e){let t=Object.entries(e);for(let[a,o]of t){if(!qe(a))throw new TypeError(`${JSON.stringify(a)} is not a consent key (a platform key, or custom.<name>)`);if(o!=="granted"&&o!=="denied")throw new TypeError(`${a}: a choice is granted or denied`)}if(t.length===0)return;this.engage();let s=this.chosenAt(),i=this.session.snapshot()?.userId??null,r=this.states();for(let[a,o]of t)this.queue({key:a,state:o,source:"app",chosen_at:s,user:i,...this.textVersion!==void 0?{text_version:this.textVersion}:{}});this.commit(r),this.send()}onChange(e){return this.listeners.add(e),()=>this.listeners.delete(e)}async region(){this.engage();let e=await this.subject();if(this.readFor!==e)try{await this.read(e)}catch(t){if(!this.kept.region)throw t}return this.kept.region}async needsAsking(e){this.engage();let t=await this.subject();this.readFor!==t&&await this.read(t).catch(()=>{});let s=e??(await this.keys()).map(c=>c.key),i=await this.platform().catch(()=>this.kept.keys??[]),r=new Set(i.filter(c=>c.ads).map(c=>c.key)),a=this.kept.region?.jurisdiction==="us",o=new Date(this.now());return o.setUTCMonth(o.getUTCMonth()-12),s.filter(c=>{let l=this.kept.choices[c];return a&&r.has(c)&&l?.last_denied_at!==void 0&&Date.parse(l.last_denied_at)>o.getTime()?!1:!l||l.state==="unset"?!0:this.textVersion!==void 0&&l.source==="app"&&l.text_version!==this.textVersion})}engage(){this.engaged||(this.engaged=!0,this.session.session().then(e=>{e&&!this.watch&&this.follow(e),this.send(),this.refuseByGpc()}))}async subject(){return(await this.session.session())?.userId??null}secret(){return{[A]:O(this.installation)}}platform(){return this.platformKeys??=this.deviceApi.listConsentKeys().then(e=>(this.kept={...this.kept,keys:e.data.keys},this.commit(),e.data.keys),e=>{if(this.platformKeys=void 0,this.kept.keys)return this.kept.keys;throw e}),this.platformKeys}async read(e){let s=(await(e===null?this.deviceApi:this.userApi(e)).getConsents({query:{installation_id:this.installation.id},headers:this.secret()})).data;this.adopt(s,e)}adopt(e,t,s=[]){if(this.kept={...this.kept,region:e.region},(this.session.snapshot()?.userId??null)!==t){this.commit();return}let i=this.states(),r={};for(let u of e.choices)r[u.key]={state:u.state,source:u.source,chosen_at:u.chosen_at,...u.text_version!==void 0?{text_version:u.text_version}:{},...u.last_denied_at!==void 0?{last_denied_at:u.last_denied_at}:{}};let a=s.filter(u=>r[u.key]?.state!==u.state||Date.parse(r[u.key]?.chosen_at??"")!==Date.parse(u.chosen_at)).map(u=>C(u.key,u)),c=_(this.kept)===(t===null?`device:${this.installation.id}`:`user:${t}`)?Object.entries(this.kept.choices).filter(([,u])=>u.provisional).map(([u,g])=>C(u,g)):[];if(a.length+c.length>0&&(this.kept={...this.kept,void:M([...this.kept.void??[],...a,...c])}),t===null&&this.kept.resetAt!==void 0)for(let[u,g]of Object.entries(r))Date.parse(g.chosen_at)<this.kept.resetAt&&delete r[u];let l=new Set(Object.entries(r).map(([u,g])=>C(u,g))),d=(this.kept.void??[]).filter(u=>l.has(u));d.length>0&&(this.kept={...this.kept,unvoid:M([...this.kept.unvoid??[],...d])});let y=Ze(this.kept),f;if(_(this.kept)!==(t===null?`device:${this.installation.id}`:`user:${t}`))f=r;else{f={};for(let u of[...new Set([...Object.keys(this.kept.choices),...Object.keys(r)])].sort()){let g=this.kept.choices[u],m=g&&!g.provisional&&!y.has(C(u,g))?g:void 0,k=r[u],R=k&&(!m||Date.parse(k.chosen_at)>=Date.parse(m.chosen_at))?k:m;R&&(f[u]=R)}}for(let u of this.kept.unsent){if(u.user!==null&&u.user!==t||u.user===null&&u.device!==void 0&&u.device!==this.installation.id||u.user===null&&t!==null)continue;let g=f[u.key];g&&Date.parse(g.chosen_at)>Date.parse(u.chosen_at)||(f[u.key]=Fe(u,g))}let{install:b,...S}=this.kept;this.kept={...S,whose:t,...t===null?{install:this.installation.id}:{},choices:f,unknown:{on:!1,w:this.stamp()}},this.readFor=t,this.stale=!1,this.commit(i),this.refuseByGpc()}async refused(e,t,s){let i=t===e&&_(this.kept)===(t===null?`device:${this.installation.id}`:`user:${t}`),r=M([...this.kept.void??[],...s.map(c=>C(c.key,c))]);if(!i){this.kept={...this.kept,void:r},this.commit();return}let a=this.states(),o={...this.kept.choices};for(let c of s){if(this.kept.unsent.some(d=>d.key===c.key&&(d.user===null||d.user===e)&&Date.parse(d.chosen_at)>Date.parse(c.chosen_at)))continue;let l=o[c.key];o[c.key]={state:"denied",source:"app",chosen_at:c.chosen_at,...l?.last_denied_at!==void 0?{last_denied_at:l.last_denied_at}:{},provisional:!0}}this.kept={...this.kept,choices:o,void:r},this.commit(a);try{await this.read(e)}catch{this.stale=!0}}queue(e){let t=e.user===null?{...e,device:this.installation.id}:e,s=_(this.kept)===(t.user===null?`device:${this.installation.id}`:`user:${t.user}`);this.kept={...this.kept,unsent:Qe([...this.kept.unsent,t]),...s?{choices:{...this.kept.choices,[t.key]:Fe(t,this.kept.choices[t.key])}}:{}}}send(){if(this.sendAgain=!0,this.sending)return;let e=(async()=>{for(;this.sendAgain;)this.sendAgain=!1,await this.sendUnsent()||(this.sendAgain=!1)})();this.sending=e,e.finally(()=>{this.sending===e&&(this.sending=void 0)})}async sendUnsent(){this.retryTimer&&clearTimeout(this.retryTimer),this.retryTimer=void 0;let e=null;try{e=await this.subject();let t=await this.sendOf(null,e);if(e!==null&&(this.kept.link===e||t)){let s;try{s=(await this.userApi(e).linkConsents({headers:this.secret(),body:{installation_id:this.installation.id}})).data}catch(i){if(!Be(i))throw i}if(this.kept.link===e){let{link:i,...r}=this.kept;this.kept=r,this.commit()}if(s)this.adopt(s,e);else{let i=this.states();this.kept={...this.kept,unknown:{on:!0,w:this.stamp()}},this.commit(i)}}if(e!==null&&await this.sendOf(e,e),this.owesRead()&&(await this.read(e),this.owesRead()))throw new Error("the choices are not read yet");return this.retries=0,!0}catch(t){return t instanceof T&&(this.session.snapshot()?.userId??null)!==e?(this.sendAgain=!0,!0):(this.retryLater(),!1)}}async sendOf(e,t){let s=!1;for(;;){let i=this.nextGroup(e);if(i.length===0)return s;let r=i[0],a=e===null?this.deviceApi:this.userApi(e),o;try{o=(await a.chooseConsents({headers:this.secret(),body:{installation_id:this.installation.id,...r.source==="gpc"?{source:"gpc"}:{},...r.text_version!==void 0?{text_version:r.text_version}:{},choices:i.map(c=>({key:c.key,state:c.state,chosen_at:c.chosen_at}))}})).data}catch(c){if(!Be(c))throw c;if(i.length>1){this.kept={...this.kept,unsent:this.kept.unsent.map(l=>i.some(d=>Je(d,l))?{...l,alone:!0}:l)},this.commit();continue}}this.kept={...this.kept,unsent:this.kept.unsent.filter(c=>!i.some(l=>Je(l,c))),done:M([...this.kept.done??[],...i.map(se)])},this.commit(),o?(s=!0,e===t&&this.adopt(o,e,i)):await this.refused(t,e,i)}}nextGroup(e){let t=this.kept.unsent.filter(a=>a.user===e&&(e!==null||(a.device??this.installation.id)===this.installation.id)),s=t[0];if(!s)return[];let i=[],r=new Set;if(s.alone)return[s];for(let a of t)if(!r.has(a.key)&&(r.add(a.key),!(a.alone||a.source!==s.source||a.text_version!==s.text_version)&&(i.push(a),i.length===Ot)))break;return i}retryLater(){if(this.retryTimer)return;let e=Ve[Math.min(this.retries,Ve.length-1)];this.retries++,this.retryTimer=setTimeout(()=>{this.retryTimer=void 0,this.send()},e),this.retryTimer.unref?.()}signedIn(e){this.readFor=void 0,this.kept={...this.kept,link:e.userId},this.commit(),this.follow(e),this.send()}signedOut(){this.unfollow(),this.readFor=void 0;let e=this.states(),t=this.chosenAt(),s=new Set([...Object.entries(this.kept.choices).filter(([,o])=>o.state!=="unset").map(([o])=>o),...this.kept.unsent.filter(o=>o.user===null&&(o.device??this.installation.id)===this.installation.id).map(o=>o.key),...Object.keys(this.start),...this.customKeys,...(this.kept.keys??[]).map(o=>o.key)]),i={};for(let[o,c]of Object.entries(this.kept.choices))i[o]={state:"unset",source:"app",chosen_at:t,...c.last_denied_at!==void 0?{last_denied_at:c.last_denied_at}:{}};let r=o=>o.user===null&&(o.device??this.installation.id)===this.installation.id,a=this.kept.unsent.filter(r);this.kept={whose:null,install:this.installation.id,resetAt:Date.parse(t),choices:i,unsent:this.kept.unsent.filter(o=>!r(o)),...this.kept.void?{void:this.kept.void}:{},...this.kept.unvoid?{unvoid:this.kept.unvoid}:{},done:M([...this.kept.done??[],...a.map(se)]),...this.kept.region?{region:this.kept.region}:{},...this.kept.keys?{keys:this.kept.keys}:{},...this.kept.gpc?{gpc:this.kept.gpc}:{},...this.kept.unknown?{unknown:this.kept.unknown}:{}};for(let o of s)this.queue({key:o,state:"unset",source:"app",chosen_at:t,user:null});this.commit(e),this.send(),this.refuseByGpc()}follow(e){this.unfollow();let t=this.socket.channel(`consents:${this.ref}:${e.userId}`),s={userId:e.userId,channel:t,off:()=>{},version:-1},i=[t.on("broadcast",r=>{r.event==="changed"&&this.changed(s,me(r.payload))}),t.on("state_snapshot",r=>this.held(s,me(ze(r.entries)))),t.on("state_diff",r=>this.held(s,me(ze(r.set))))];s.off=()=>i.forEach(r=>r()),this.watch=s,t.join().catch(()=>{})}unfollow(){let e=this.watch;e&&(this.watch=void 0,e.off(),e.channel.leave())}held(e,t){t!==void 0&&this.changed(e,t)}changed(e,t){if(this.watch===e){if(t!==void 0){if(t<=e.version)return;e.version=t}this.read(e.userId).catch(()=>{this.watch===e&&(this.stale=!0,this.retryLater())})}}gpcRefuses(e){if(!this.gpc||!(this.kept.keys??[]).some(r=>r.key===e&&r.ads))return!1;let t=Ge(this.kept,e);if(t?.state==="denied")return!1;let s=this.kept.gpc?.[_(this.kept)],i=s!==void 0&&(this.kept.whose!=null||s>=(this.kept.resetAt??0));return!(t?.state==="granted"&&t.source==="app"&&i&&Date.parse(t.chosen_at)>s)}async refuseByGpc(){if(!this.gpc||_(this.kept)!==this.holder())return;let e;try{e=await this.platform()}catch{return}if(_(this.kept)!==this.holder())return;let t=this.session.snapshot()?.userId??null,s=e.filter(a=>a.ads&&this.gpcRefuses(a.key)&&!this.kept.unsent.some(o=>o.key===a.key&&o.source==="gpc"&&o.user===t));if(s.length===0)return;let i=this.chosenAt(),r=this.states();for(let a of s)this.queue({key:a.key,state:"denied",source:"gpc",chosen_at:i,user:t});this.kept={...this.kept,gpc:{...this.kept.gpc,[_(this.kept)]:Date.parse(i)}},this.commit(r),this.send()}states(){let e=new Map;for(let t of[...Object.keys(this.start),...Object.keys(this.kept.choices)])e.set(t,this.state(t));return e}tell(e){let t=this.states();for(let s of new Set([...e.keys(),...t.keys()])){let i=t.get(s);if(e.get(s)!==i)for(let r of[...this.listeners])try{r(s,i)}catch{}}}load(){let e;try{e=Xe()?.getItem(this.storeKey)}catch{return"unreadable"}if(e==null)return"empty";try{let t=JSON.parse(e);if(Dt(t))return t}catch{}return"unreadable"}reload(){let e=this.load();if(typeof e!="object"){this.write();return}let t=this.states();this.kept=He(e,this.kept,"theirs",this.holder()),_(e)===_(this.kept)&&We(this.kept)!==We(e)&&this.write(),this.tell(t);let s=this.session.snapshot()?.userId??null;this.engaged&&this.kept.unsent.some(i=>i.user!==null&&i.user===s||i.user===null&&(i.device??this.installation.id)===this.installation.id)&&this.retryLater(),this.engaged&&this.refuseByGpc()}commit(e=this.states()){let t=this.load();typeof t=="object"&&(this.kept=He(t,this.kept,"ours",this.holder())),this.write(),this.tell(e)}write(){try{Xe()?.setItem(this.storeKey,JSON.stringify(this.kept))}catch{}}chosenAt(){return this.lastChosen=Math.max(this.now(),this.lastChosen+1),new Date(this.lastChosen).toISOString()}stamp(){let e=this.kept,t=e?Math.max(0,e.unknown?.w??0):0;return this.lastW=Math.max(this.now(),this.lastW+1,t+1),this.lastW}};function Fe(n,e){let t=n.state==="denied"?n.chosen_at:e?.last_denied_at;return{state:n.state,source:n.source,chosen_at:n.chosen_at,...n.text_version!==void 0?{text_version:n.text_version}:{},...t!==void 0?{last_denied_at:t}:{}}}function C(n,e){return`${n}|${e.provisional?"provisional":e.state}|${Date.parse(e.chosen_at)}`}function Ze(n){let e=new Set(n.unvoid??[]);return new Set((n.void??[]).filter(t=>!e.has(t)))}var ee={denied:2,unset:1,granted:0};function Mt(n,e,t,s){let i=e&&!s.has(C(n,e))?e:void 0,r=t&&!s.has(C(n,t))?t:void 0;if(!i||!r)return i??r;let a=Date.parse(i.chosen_at),o=Date.parse(r.chosen_at);return a!==o?a>o?i:r:ee[i.state]!==ee[r.state]?ee[i.state]>ee[r.state]?i:r:i.provisional?r:i}function Nt(n,e){return!n||!e?n??e:e.w>n.w||e.w===n.w&&e.on?e:n}function He(n,e,t,s){let i=M([...n.void??[],...e.void??[]]),r=M([...n.unvoid??[],...e.unvoid??[]]),a=Ze({void:i,unvoid:r}),o={},c,l={...n.gpc};for(let[m,k]of Object.entries(e.gpc??{}))l[m]=Math.max(l[m]??0,k);let d;if(_(n)===_(e)){c=e;for(let m of[...new Set([...Object.keys(n.choices),...Object.keys(e.choices)])].sort()){let k=Mt(m,n.choices[m],e.choices[m],a);k&&(o[m]=k)}d=Nt(n.unknown,e.unknown)}else{c=_(e)===s?e:_(n)===s?n:t==="ours"?e:n;for(let[m,k]of Object.entries(c.choices))a.has(C(m,k))||(o[m]=k);d=c.unknown}let y=M([...n.done??[],...e.done??[]]),f=Qe([...n.unsent,...e.unsent]).filter(m=>!y.includes(se(m))),b=t==="ours"?e:n,S=t==="ours"?n:e,u=b.region??S.region,g=b.keys??S.keys;return{whose:c.whose??null,...c.whose==null&&c.install!==void 0?{install:c.install}:{},...c.whose==null&&(n.resetAt!==void 0||e.resetAt!==void 0)&&_(n)===_(e)?{resetAt:Math.max(n.resetAt??0,e.resetAt??0)}:c.whose==null&&c.resetAt!==void 0?{resetAt:c.resetAt}:{},choices:o,unsent:f,...y.length>0?{done:y}:{},...i.length>0?{void:i}:{},...r.length>0?{unvoid:r}:{},...b.link!==void 0?{link:b.link}:{},...u?{region:u}:{},...Object.keys(l).length>0?{gpc:l}:{},...g?{keys:g}:{},...d?{unknown:d}:{}}}function se(n){return`${n.user??`device:${n.device??""}`}|${n.key}|${n.state}|${n.source}|${n.chosen_at}`}function Ge(n,e){let t=n.choices[e];if(!t||n.whose!=null||n.resetAt===void 0||Date.parse(t.chosen_at)>=n.resetAt)return t}function _(n){return n.whose!=null?`user:${n.whose}`:`device:${n.install??""}`}function M(n){return[...new Set(n)].slice(-Ct)}function We(n){return JSON.stringify(n,(e,t)=>typeof t=="object"&&t!==null&&!Array.isArray(t)?Object.fromEntries(Object.entries(t).sort(([s],[i])=>s.localeCompare(i))):t)}function Qe(n){let e=new Map;for(let t of n){let s=se(t),i=e.get(s);e.set(s,i?i.alone||!t.alone?i:{...i,alone:!0}:t)}return[...e.values()].sort((t,s)=>Date.parse(t.chosen_at)-Date.parse(s.chosen_at))}var Lt=new Set(["granted","denied","unset"]);function Dt(n){if(typeof n!="object"||n===null)return!1;let e=n;if(typeof e.choices!="object"||e.choices===null||Array.isArray(e.choices)||!Array.isArray(e.unsent))return!1;let t=(o,c)=>{if(typeof o!="object"||o===null)return!1;let l=o;return Lt.has(l.state)&&typeof l.chosen_at=="string"&&(!c||typeof l.key=="string")},s=o=>o===void 0||typeof o=="object"&&o!==null&&typeof o.on=="boolean"&&typeof o.w=="number",i=n,r=o=>o===void 0||Array.isArray(o)&&o.every(c=>typeof c=="string"),a=i.whose===void 0||i.whose===null||typeof i.whose=="string";return Object.values(e.choices).every(o=>t(o,!1))&&e.unsent.every(o=>t(o,!0))&&(i.gpc===void 0||typeof i.gpc=="object"&&i.gpc!==null&&Object.values(i.gpc).every(o=>typeof o=="number"))&&s(i.unknown)&&r(i.done)&&r(i.void)&&r(i.unvoid)&&a}function Je(n,e){return n.key===e.key&&n.user===e.user&&n.state===e.state&&n.source===e.source&&n.chosen_at===e.chosen_at}function Be(n){return n instanceof I&&n.status>=400&&n.status<500&&n.status!==401&&n.status!==408&&n.status!==429}function Xe(){try{return globalThis.localStorage}catch{return}}function ze(n){let e=typeof n=="object"&&n!==null?n.version:void 0;return typeof e=="object"&&e!==null?e.v:void 0}function me(n){let e=typeof n=="object"&&n!==null?n.version:void 0;return typeof e=="number"&&Number.isFinite(e)?e:void 0}var Ut=`
|
|
1
|
+
/*! palbase 0.10.1 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{e as Re,g as Ae,h as Oe}from"./R4OLJRMH.js";import{h as Ce}from"./MFMA46HN.js";import{a as Ee}from"./NBI5LPMS.js";import{r as xe,t as Pe,u as Te}from"./FHXGE2MX.js";import{b as V,c as K,e as Se,g as j,h as _e}from"./YQEM4H7U.js";import{a as Ie,b as F}from"./RO7ERCT3.js";import{b as I,d as U}from"./RWGEPDRQ.js";function ht(n){let e=n,t=e?.body,s=t&&typeof t=="object"?t.reason:void 0;return s==="user_deleted"?"userDeleted":s==="user_banned"?"userBanned":e?.code==="session_expired"||e?.code==="token_expired"?"expired":"revoked"}var T=class extends Error{code="session_changed";constructor(e){super(e),this.name="SessionChangedError"}};function Me(){let n=null;return{load:()=>n,save:e=>{n=e},clear:()=>{n=null},shared:!1}}function Ne(n){let e=null,t=!0,s=()=>{try{return globalThis.localStorage}catch{return}};return{shared:!0,load(){try{let i=s()?.getItem(n);return i==null?t?null:e:JSON.parse(i)}catch{return e}},save(i){e=i;try{let r=s();if(!r)throw new Error("no storage");r.setItem(n,JSON.stringify(i)),t=!0}catch{t=!1}},clear(){e=null,t=!0;try{s()?.removeItem(n)}catch{}},watch(i){let r=globalThis;if(typeof r.addEventListener!="function")return()=>{};let a=o=>{(o.key===n||o.key===null)&&i()};return r.addEventListener("storage",a),()=>r.removeEventListener?.("storage",a)}}}function fe(n){try{let e=n.split(".")[1]??"",t=atob(e.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(e.length/4)*4,"=")),s=JSON.parse(t).sub;return typeof s=="string"?s:""}catch{return""}}var pt=6e4,ft=15e3;function gt(n,e,t){let s=n?globalThis.navigator?.locks:void 0;return s?s.request(e,t):t()}var W=class{current=null;loaded;inflight=null;endReason=null;listeners=new Set;store;refresher;isRejected;now;lockName;refreshTimeoutMs;mode;constructor(e,t,s,i={}){this.store=e,this.refresher=t,this.isRejected=s,this.now=i.now??Date.now,this.lockName=i.lockName??"palbase.session.refresh",this.refreshTimeoutMs=i.refreshTimeoutMs??ft,this.mode=i.refresh??"behind",this.loaded=Promise.resolve(e.load()).then(r=>{this.current=r}),e.watch?.(()=>{this.reconcile()})}async session(){return await this.loaded,this.current}snapshot(){return this.current}onChange(e){return this.listeners.add(e),()=>this.listeners.delete(e)}async set(e,t,s){await this.loaded;let i=t==="TOKEN_REFRESHED"?this.current:null,r={accessToken:e.access_token,refreshToken:e.refresh_token,expiresAt:this.now()+e.expires_in*1e3,userId:s?.id??i?.userId??fe(e.access_token),user:s??i?.user};return this.current=r,await this.store.save(r),this.emit(t,r),r}async setUser(e,t){await this.loaded,!(!this.current||!t||this.current.userId!==t.userId)&&(this.current={...this.current,user:e},await this.store.save(this.current),this.emit("USER_UPDATED",this.current))}async clear(e,t){await this.loaded;let s=this.current;this.current=null,this.inflight=null;let i=await this.store.load();(!i||!s||i.userId===s.userId)&&await this.store.clear(),s&&(e==="SESSION_EXPIRED"&&(this.endReason=t??"revoked"),this.emit(e,null))}async accessToken(){await this.loaded;let e=this.current;if(!e)return;let t=e.expiresAt-this.now();if(t>pt)return e.accessToken;if(this.mode==="never")return t>0?e.accessToken:void 0;if(t>0&&this.mode==="behind")return this.refresh().catch(()=>{}),e.accessToken;if(t>0)try{return(await this.refresh()).accessToken}catch(s){if(this.current===e)return e.accessToken;throw s}return(await this.refresh()).accessToken}refresh(){if(this.mode==="never")return Promise.reject(new Error("this client does not renew its session (refresh: 'never'): where the session cannot be written back, the request's middleware renews it"));if(this.inflight)return this.inflight;let e=gt(this.store.shared===!0,this.lockName,async()=>{await this.loaded;let t=this.current;if(!t)throw new T("no session to refresh");let s=await this.adoptStored(t);if(s)return s;try{let i=await this.withTimeout(this.refresher(t.refreshToken));if(this.current?.refreshToken!==t.refreshToken)throw new T("the session changed while it was refreshed");return await this.set(i,"TOKEN_REFRESHED")}catch(i){throw this.isRejected(i)&&this.current?.refreshToken===t.refreshToken&&await this.clear("SESSION_EXPIRED",ht(i)),i}});return this.inflight=e,e.finally(()=>{this.inflight===e&&(this.inflight=null)}).catch(()=>{}),e}async adoptStored(e){let t=await this.store.load();if(!t)throw this.current=null,this.emit("SIGNED_OUT",null),new T("signed out in another tab");if(t.userId!==e.userId)throw this.current=t,this.emit("SIGNED_OUT",null),this.emit("SIGNED_IN",t),new T("another user signed in in another tab");if(t.refreshToken!==e.refreshToken&&t.expiresAt>=e.expiresAt)return this.current=t,this.emit("TOKEN_REFRESHED",t),t}async reconcile(){await this.loaded;let e=this.current,t=await this.store.load();if(!e){t&&(this.current=t,this.emit("SIGNED_IN",t));return}await this.adoptStored(e).catch(()=>{})}withTimeout(e){let t,s=new Promise((i,r)=>{t=setTimeout(()=>r(new Error(`the refresh did not answer within ${this.refreshTimeoutMs/1e3} s`)),this.refreshTimeoutMs)});return Promise.race([e,s]).finally(()=>clearTimeout(t))}emit(e,t){(e==="SIGNED_IN"||e==="SIGNED_OUT")&&(this.endReason=null);for(let s of this.listeners)try{s(e,t)}catch{}}};var ge=class{state="closed";refusal;logSeq;joinRef=null;listeners=new Map;closers=new Set;joinWaiters=[];name;socket;constructor(e,t,s={}){this.name=e,this.socket=t,this.logSeq=s.after}get topic(){return`realtime:${this.name}`}join(){if(this.state==="joined")return Promise.resolve();let e=new Promise((t,s)=>this.joinWaiters.push({resolve:t,reject:s}));return this.state!=="joining"&&this.socket.join(this),e}leave(){this.socket.leave(this)}push(e,t){return this.socket.request(this,e,t)}on(e,t){let s=this.listeners.get(e);return s||this.listeners.set(e,s=new Set),s.add(t),()=>s.delete(t)}onClosed(e){return this.closers.add(e),()=>this.closers.delete(e)}deliver(e,t){e==="broadcast"&&typeof t.seq=="number"&&(this.logSeq=t.seq);for(let s of this.listeners.get(e)??[])try{s(t)}catch{}}settled(e,t){e&&typeof t.log_seq=="number"&&(this.logSeq=t.log_seq),this.state=e?"joined":"refused",this.refusal=e?void 0:t;let s=this.joinWaiters.splice(0);for(let i of s)e?i.resolve():i.reject(new Error(`join ${this.name} refused: ${JSON.stringify(t)}`))}closed(e){this.state="closed",this.joinRef=null;let t=this.joinWaiters.splice(0);for(let s of t)s.reject(new Error(`join ${this.name}: ${e}`));for(let s of[...this.closers])try{s()}catch{}}},B=class{ws=null;opening=null;ref=0;channels=new Map;replies=new Map;heartbeat=null;heartbeatRef=null;reconnectTimer=null;attempts=0;closedByUs=!1;reconnects=0;opts;constructor(e){this.opts=e}channel(e,t){let s=this.channels.get(e);return s||this.channels.set(e,s=new ge(e,this,t)),s}disconnect(){this.closedByUs=!0,this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=null,this.stopHeartbeat();let e=this.ws;this.ws=null,this.opening=null,e?.close(1e3);for(let[,t]of this.replies)t("error",{reason:"socket closed"});this.replies.clear();for(let t of this.channels.values())t.closed("the socket was closed")}async tokenChanged(){if(!this.ws||this.ws.readyState!==1)return;let e=await this.opts.accessToken();if(e)for(let t of this.channels.values())t.state==="joined"&&this.push(t.joinRef,t.topic,"access_token",{access_token:e})}join(e){e.state="joining",this.open().then(()=>this.sendJoin(e)).catch(t=>e.settled(!1,{reason:t instanceof Error?t.message:String(t)}))}leave(e){e.state==="joined"&&this.ws?.readyState===1&&this.push(e.joinRef,e.topic,"phx_leave",{}),e.state="closed",this.channels.delete(e.name)}async request(e,t,s){let i=this.ws;if(this.channels.get(e.name)!==e||e.state!=="joined"||i?.readyState!==1)return{status:"error",response:{reason:"not joined"}};let r=this.nextRef(),a=JSON.stringify([e.joinRef,r,e.topic,t,s]),o=this.awaitReply(r);return i.send(a),o}open(){if(this.ws?.readyState===1)return Promise.resolve();if(this.opening)return this.opening;this.closedByUs=!1;let e=this.opts.webSocket??globalThis.WebSocket,t=`${this.opts.baseUrl.replace(/^http/,"ws")}/realtime/v1/websocket?vsn=2.0.0&apikey=${encodeURIComponent(this.opts.publishableKey)}`,s=new Promise((i,r)=>{let a=new e(t);this.ws=a,a.onopen=()=>{this.attempts=0,this.startHeartbeat(),i()},a.onmessage=o=>this.receive(String(o.data)),a.onerror=()=>r(new Error("the realtime socket could not be opened")),a.onclose=()=>this.dropped(a)});return this.opening=s,s.finally(()=>{this.opening===s&&(this.opening=null)}).catch(()=>{}),s}dropped(e){if(this.ws!==e)return;this.ws=null,this.stopHeartbeat();for(let[,i]of this.replies)i("error",{reason:"socket closed"});this.replies.clear();for(let i of this.channels.values())i.state==="joined"&&(i.state="joining");if(this.closedByUs||![...this.channels.values()].some(i=>i.state==="joining"))return;let t=this.opts.backoff??[500,1e3,2e3,5e3,1e4,3e4],s=t[Math.min(this.attempts,t.length-1)]*(.8+Math.random()*.4);this.attempts++,this.reconnectTimer=J(setTimeout(()=>{this.reconnectTimer=null,this.reconnects++;let i=[...this.channels.values()].filter(r=>r.state==="joining");this.open().then(()=>Promise.all(i.map(r=>this.sendJoin(r)))).catch(()=>{})},s))}async sendJoin(e){let t=await this.opts.accessToken(),s=this.nextRef();e.joinRef=s;let i=this.awaitReply(s),r={broadcast:{self:!1}};e.logSeq!==void 0&&(r.log={after:e.logSeq}),this.push(s,e.topic,"phx_join",{access_token:t,config:r},s);let{status:a,response:o}=await i;if(this.channels.get(e.name)!==e||e.state!=="joining"){a==="ok"&&this.ws?.readyState===1&&this.push(s,e.topic,"phx_leave",{});return}e.settled(a==="ok",o)}awaitReply(e){return new Promise(t=>{let s=J(setTimeout(()=>{this.replies.delete(e),t({status:"timeout",response:{reason:"no reply"}})},this.opts.replyTimeoutMs??1e4));this.replies.set(e,(i,r)=>{clearTimeout(s),this.replies.delete(e),t({status:i,response:r})})})}receive(e){let t;try{t=JSON.parse(e)}catch{return}if(!Array.isArray(t)||t.length!==5||typeof t[2]!="string"||typeof t[3]!="string")return;let[,s,i,r,a]=t,o=typeof a=="object"&&a!==null?a:{};if(r==="phx_reply"&&typeof s=="string"){if(s===this.heartbeatRef){this.heartbeatRef=null;return}this.replies.get(s)?.(String(o.status),o.response??{});return}let c=[...this.channels.values()].find(l=>l.topic===i);if(c){if(r==="phx_close"){c.state="closed";return}if(r==="phx_error"){c.state="joining",J(setTimeout(()=>this.channels.get(c.name)===c&&c.state==="joining"&&this.ws?.readyState===1&&void this.sendJoin(c),1e3));return}c.deliver(r,o)}}push(e,t,s,i,r=this.nextRef()){this.ws?.send(JSON.stringify([e,r,t,s,i]))}nextRef(){return String(++this.ref)}startHeartbeat(){this.stopHeartbeat(),this.heartbeat=J(setInterval(()=>{if(this.heartbeatRef!==null){this.heartbeatRef=null,this.ws?.close(4e3);return}this.heartbeatRef=this.nextRef(),this.push(null,"phoenix","heartbeat",{},this.heartbeatRef)},this.opts.heartbeatMs??25e3))}stopHeartbeat(){this.heartbeat&&clearInterval(this.heartbeat),this.heartbeat=null,this.heartbeatRef=null}};function J(n){return n.unref?.(),n}var A="X-Palbase-Installation-Secret",z="X-Palbase-Installation",De=new WeakMap;function O(n){return De.get(n)}var Ue=new WeakSet;function Ke(n){return Ue.has(n)}var yt=/^[A-Za-z0-9_-]{43}$/,X=class{id;constructor(e){let t=`palbase.installation.secret.${e}`,s;try{let i=Le()?.getItem(t);i&&yt.test(i)&&(s=i)}catch{}if(!s){Ue.add(this),s=je(crypto.getRandomValues(new Uint8Array(32)));try{Le()?.setItem(t,s)}catch{}}De.set(this,s),this.id=mt(s)}};function mt(n){return je(wt(new TextEncoder().encode(n)).subarray(0,16))}function Le(){try{return globalThis.localStorage}catch{return}}function je(n){let e="";for(let t of n)e+=String.fromCharCode(t);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}var vt=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),E=(n,e)=>n>>>e|n<<32-e;function wt(n){let e=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),t=new Uint8Array(Math.ceil((n.length+9)/64)*64);t.set(n),t[n.length]=128;let s=new DataView(t.buffer);s.setUint32(t.length-8,Math.floor(n.length/536870912)),s.setUint32(t.length-4,n.length*8>>>0);let i=new Uint32Array(64);for(let o=0;o<t.length;o+=64){for(let g=0;g<16;g++)i[g]=s.getUint32(o+g*4);for(let g=16;g<64;g++){let m=E(i[g-15],7)^E(i[g-15],18)^i[g-15]>>>3,k=E(i[g-2],17)^E(i[g-2],19)^i[g-2]>>>10;i[g]=i[g-16]+m+i[g-7]+k|0}let[c,l,d,y,f,b,S,u]=e;for(let g=0;g<64;g++){let m=u+(E(f,6)^E(f,11)^E(f,25))+(f&b^~f&S)+vt[g]+i[g]|0,k=(E(c,2)^E(c,13)^E(c,22))+(c&l^c&d^l&d)|0;u=S,S=b,b=f,f=y+m|0,y=d,d=l,l=c,c=m+k|0}e[0]+=c,e[1]+=l,e[2]+=d,e[3]+=y,e[4]+=f,e[5]+=b,e[6]+=S,e[7]+=u}let r=new Uint8Array(32),a=new DataView(r.buffer);for(let o=0;o<8;o++)a.setUint32(o*4,e[o]);return r}var kt=30*6e4,$e=1e3,St=100,_t=60*1024,Y=()=>globalThis.crypto?.randomUUID?globalThis.crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;function D(){try{return globalThis.localStorage}catch{return}}var Q=class{api;closingApi;perfApi;closingPerfApi;flushMs;flushAt;now;anonKey;sessionKey;onceKey;events=[];samples=[];timer;memoryAnon;memorySession;memoryOnce;appVersion;stopAuto;session;consent;identifyPending=!1;listeners=new Set;people={set:e=>this.person({set:e}),setOnce:e=>this.person({set_once:e}),unset:e=>this.person({unset:[...e]}),add:e=>this.person({add:e})};constructor(e,t,s,i,r,a,o={}){this.session=s,this.consent=i;let c={send:d=>e.send(this.granted("analytics")?{...d,headers:{...d.headers,[z]:r.id}}:d)};this.api=V.client(c);let l={send:d=>(this.granted("analytics")?e:t).send(d)};this.perfApi=V.client(l),this.closingApi=V.client({send:d=>c.send({...d,keepalive:!0})}),this.closingPerfApi=V.client({send:d=>l.send({...d,keepalive:!0})}),this.flushMs=o.flushMs??5e3,this.flushAt=o.flushAt??20,this.now=o.now??Date.now,this.anonKey=`palbase.analytics.anonymous.${a}`,this.sessionKey=`palbase.analytics.session.${a}`,this.onceKey=`palbase.analytics.once.${a}`,s.onChange(d=>{d==="SIGNED_IN"?(this.identifyPending=!0,this.soon()):d==="SIGNED_OUT"&&(this.identifyPending=!1,this.reset())}),i.onChange((d,y)=>{y!=="granted"&&(d==="analytics"?(this.events=[],this.identifyPending=!1,this.samples=this.samples.map(ye),this.reset()):d==="performance"&&(this.samples=[]))})}capture(e,t){for(let i of this.listeners)i(e,t);if(!this.granted("analytics"))return;let s=this.now();this.hold({event:e,distinct_id:this.distinctId(),properties:t,timestamp:s,session_id:this.sessionId(s),...this.appVersion?{app_version:this.appVersion}:{}})}captureOnce(e,t,s){if(!this.granted("analytics"))return;let i=this.sessionId(this.now()),r=this.readOnce(),a=r?.session===i?r.keys:[];a.includes(e)||(this.writeOnce({session:i,keys:[...a,e].slice(-500)}),this.capture(t,s))}readOnce(){try{let e=D()?.getItem(this.onceKey);if(e)return JSON.parse(e)}catch{}return this.memoryOnce}writeOnce(e){this.memoryOnce=e;try{D()?.setItem(this.onceKey,JSON.stringify(e))}catch{}}onEvent(e){return this.listeners.add(e),()=>this.listeners.delete(e)}page(e={}){let t=globalThis.location,s=globalThis.document,i=e.url??(t?`${t.origin}${$(t.pathname)}`:"");if(!i)return;let r=e.referrer??Rt(s?.referrer);this.capture("$pageview",{...e.properties,url:i,...e.title??s?.title?{title:e.title??s?.title}:{},...r?{referrer:r}:{}})}async identify(e){this.identifyPending=!1;let t=this.session.snapshot()?.userId;!t||!this.granted("analytics")||(await this.flush(),await this.sendIdentify(this.api,t,e))}async sendIdentify(e,t,s){try{await e.identify({body:{distinct_id:t,anonymous_id:this.anonymousId(),traits:s,timestamp:this.now(),sent_at:this.now()}})}catch{}}reset(){this.memoryAnon=void 0,this.memorySession=void 0,this.memoryOnce=void 0;try{D()?.removeItem(this.anonKey),D()?.removeItem(this.sessionKey),D()?.removeItem(this.onceKey)}catch{}}async flush(e=!1){this.timer&&clearTimeout(this.timer),this.timer=void 0,this.granted("analytics")||(this.events=[]),this.granted("performance")?this.granted("analytics")||(this.samples=this.samples.map(ye)):this.samples=[];let t=e?this.closingApi:this.api,s=e?this.closingPerfApi:this.perfApi,i=this.now(),r=this.session.snapshot()?.userId;for(this.identifyPending&&r&&this.granted("analytics")&&(this.identifyPending=!1,await this.sendIdentify(t,r));this.events.length>0;){let a=this.take(this.events,e);try{await t.batch({body:{events:a.map(o=>({...o,sent_at:i}))}})}catch{}}for(;this.samples.length>0;){let a=this.take(this.samples,e);try{await s.sendPerf({body:{items:a}})}catch{}}}start(e={}){this.stopAuto?.(),this.appVersion=e.appVersion;let t=globalThis;if(typeof t.addEventListener!="function"||typeof globalThis.document>"u")return()=>{};let s=[];e.pageViews!==!1&&s.push(this.watchPages(t)),e.webVitals!==!1&&s.push(Pt((a,o)=>this.sample("web_vital",a,o))),e.network!==!1&&s.push(this.watchFetch(t));let i=()=>{document.visibilityState==="hidden"&&this.flush(!0)},r=()=>{this.flush(!0)};return document.addEventListener("visibilitychange",i),t.addEventListener("pagehide",r),s.push(()=>{document.removeEventListener("visibilitychange",i),t.removeEventListener("pagehide",r)}),this.stopAuto=()=>{for(let a of s.splice(0))a();this.stopAuto=void 0},this.stopAuto}granted(e){return this.consent.state(e)==="granted"}async person(e){if(!this.granted("analytics"))return;let t=this.session.snapshot()?.userId,s=this.now();try{await this.api.setPersonProperties({body:{...e,...t?{}:{distinct_id:this.anonymousId()},timestamp:s,sent_at:s}})}catch{}}hold(e){this.events.length>=$e&&this.events.shift(),this.events.push(e),this.soon()}sample(e,t,s,i={}){if(!this.granted("performance"))return;this.samples.length>=$e&&this.samples.shift();let r={row_id:Y(),trace_type:e,name:t,value:Math.max(0,s),timestamp:this.now(),...i};this.samples.push(this.granted("analytics")?{...r,distinct_id:this.distinctId()}:ye(r)),this.soon()}soon(){if(this.events.length+this.samples.length>=this.flushAt){this.flush();return}this.timer||(this.timer=setTimeout(()=>{this.flush()},this.flushMs),this.timer.unref?.())}take(e,t){let s=e.splice(0,St);if(!t)return s;for(;s.length>1&&JSON.stringify(s).length>_t;)e.unshift(s.pop());return s}distinctId(){return this.session.snapshot()?.userId??this.anonymousId()}anonymousId(){let e=D();try{let t=e?.getItem(this.anonKey);if(t)return t;let s=`anon_${Y()}`;if(e?.setItem(this.anonKey,s),e?.getItem(this.anonKey)===s)return s}catch{}return this.memoryAnon??=`anon_${Y()}`,this.memoryAnon}sessionId(e){let t=D(),s=this.memorySession;try{let r=t?.getItem(this.sessionKey);r&&(s=JSON.parse(r))}catch{}let i=s&&e-s.last<kt?{id:s.id,last:e}:{id:`ses_${Y()}`,last:e};this.memorySession=i;try{t?.setItem(this.sessionKey,JSON.stringify(i))}catch{}return i.id}watchPages(e){let t="",s=()=>{let o=`${e.location.origin}${e.location.pathname}`;if(o===t)return;t=o;let c=`${e.location.origin}${$(e.location.pathname)}`;setTimeout(()=>this.page({url:c}),0)},i=e.history,r=i.pushState.bind(i),a=i.replaceState.bind(i);return i.pushState=(...o)=>{r(...o),s()},i.replaceState=(...o)=>{a(...o),s()},e.addEventListener("popstate",s),s(),()=>{i.pushState=r,i.replaceState=a,e.removeEventListener("popstate",s)}}watchFetch(e){let t=e.fetch;if(typeof t!="function")return()=>{};let s=async(i,r)=>{let a=performance.now(),o=i instanceof Request?i:void 0,c=(r?.method??o?.method??"GET").toUpperCase(),l;try{l=new URL(o?.url??String(i),e.location.href)}catch{l=void 0}let d=!!l&&l.pathname.startsWith("/analytics/")||Tt(r?.headers??o?.headers);try{let y=await t(i,r);return l&&!d&&this.sample("network",`${c} ${l.origin}${$(l.pathname)}`,performance.now()-a,{attrs:{status:String(y.status)},...y.headers.get("x-request-id")?{request_id:y.headers.get("x-request-id")}:{}}),y}catch(y){throw l&&!d&&this.sample("network",`${c} ${l.origin}${$(l.pathname)}`,performance.now()-a,{attrs:{status:"0"}}),y}};return e.fetch=s,()=>{e.fetch===s&&(e.fetch=t)}}};function ye(n){let{distinct_id:e,request_id:t,...s}=n;return s}var It=n=>n.entryType==="layout-shift"&&"value"in n&&"hadRecentInput"in n,xt=n=>n.entryType==="event"||n.entryType==="first-input";function Z(n,e){if(!(typeof PerformanceObserver>"u"))try{let t=new PerformanceObserver(s=>e(s.getEntries()));return t.observe({type:n,buffered:!0}),t}catch{return}}function Pt(n){if(typeof document>"u"||typeof performance>"u"||typeof performance.getEntriesByType!="function")return()=>{};let e=0,t=0,s=0,i=[Z("largest-contentful-paint",l=>{for(let d of l)e=Math.max(e,d.startTime)}),Z("layout-shift",l=>{for(let d of l)It(d)&&!d.hadRecentInput&&(t+=d.value)}),Z("event",l=>{for(let d of l)xt(d)&&(s=Math.max(s,d.duration))}),Z("paint",l=>{for(let d of l)d.name==="first-contentful-paint"&&n("FCP",d.startTime)})],r=performance.getEntriesByType("navigation")[0];r&&r.responseStart>0&&n("TTFB",r.responseStart);let a=!1,o=()=>{a||(a=!0,e>0&&n("LCP",e),n("CLS",t),s>0&&n("INP",s))},c=()=>{document.visibilityState==="hidden"&&o()};return document.addEventListener("visibilitychange",c),()=>{o(),document.removeEventListener("visibilitychange",c);for(let l of i)l?.disconnect()}}function Tt(n){if(!n)return!1;try{return new Headers(n).has("next-router-prefetch")}catch{return!1}}var Et=/^[a-z][a-z0-9_-]{0,31}$/;function $(n){return n.split("/").map(e=>{if(e==="")return e;let t=e.split(";",1)[0],s=t.toLowerCase();return Et.test(s)&&(s.match(/\d/g)?.length??0)<=2&&t.slice(1)===s.slice(1)&&s.split(/[-_]/).every(r=>r.length<=16)?s:":id"}).join("/")}function Rt(n){if(!n)return"";try{let e=new URL(n);return`${e.origin}${$(e.pathname)}`}catch{return $(n.split(/[?#]/,1)[0]??"")}}var Ye=/^custom\.[a-z0-9_]{1,48}$/,At=/^[a-z][a-z0-9_]{0,63}$/,qe=n=>At.test(n)||Ye.test(n),Ot=50,Ve=[5e3,3e4,12e4,6e5],Ct=100,te=class{userApi;deviceApi;session;socket;ref;installation;start;textVersion;customKeys;storeKey;now;kept;listeners=new Set;engaged=!1;platformKeys;watch;sending;sendAgain=!1;retryTimer;retries=0;readFor;stale=!1;lastW=0;lastChosen=0;gpc=globalThis.navigator?.globalPrivacyControl===!0;constructor(e){let t=e.options??{};for(let[c,l]of Object.entries(t.start??{})){if(!qe(c))throw new TypeError(`consent.start: ${JSON.stringify(c)} is not a consent key (a platform key, or custom.<name>)`);if(l!=="granted"&&l!=="denied")throw new TypeError(`consent.start.${c} is granted or denied`)}for(let c of t.customKeys??[])if(!Ye.test(c))throw new TypeError(`consent.customKeys: ${JSON.stringify(c)} is not custom.<name> (a-z, 0-9 and _, 48 at most)`);if(t.textVersion!==void 0&&(t.textVersion===""||t.textVersion.length>64))throw new TypeError("consent.textVersion: 1 to 64 characters");this.userApi=e.userApi,this.deviceApi=e.deviceApi,this.session=e.session,this.socket=e.socket,this.ref=e.ref,this.installation=e.installation,this.start={...t.start},this.textVersion=t.textVersion,this.customKeys=[...t.customKeys??[]],this.storeKey=`palbase.consent.${e.origin}.${e.installation.id}`,this.now=e.now??Date.now;let s=this.load(),i=()=>Ke(this.installation)?{}:{unknown:{on:!0,w:this.stamp()}},r={whose:null,install:this.installation.id,choices:{},unsent:[]};typeof s!="object"?this.kept={...r,...s==="unreadable"?{unknown:{on:!0,w:this.stamp()}}:i()}:s.whose==null&&s.install!==void 0&&s.install!==this.installation.id?this.kept={...r,unsent:s.unsent.filter(c=>c.user!==null),...s.keys?{keys:s.keys}:{},...i()}:this.kept=s,e.session.onChange((c,l)=>{this.engaged&&(c==="SIGNED_IN"&&l?this.signedIn(l):(c==="SIGNED_OUT"||c==="SESSION_EXPIRED")&&this.signedOut())});let a=globalThis;typeof a.addEventListener=="function"&&(a.addEventListener("storage",c=>{(c.key===this.storeKey||c.key===null)&&this.reload()}),a.addEventListener("online",()=>{this.engaged&&this.send()}));let o=this.kept;(e.options!==void 0||s!=="empty"&&(o.unknown?.on||o.unsent.length>0||o.link!==void 0||Object.keys(o.choices).length>0))&&this.engage()}async keys(){return this.engage(),[...(await this.platform()).map(t=>({key:t.key,category:t.category,title:{...t.title},description:{...t.description},ads:t.ads})),...this.customKeys.map(t=>({key:t,category:"custom",title:{},description:{},ads:!1}))]}state(e){if(_(this.kept)!==this.holder()||this.gpcRefuses(e))return"denied";let t=Ge(this.kept,e);return t&&t.state!=="unset"?t.state:this.kept.unknown?.on?"denied":this.start[e]}owesRead(){return this.stale||this.kept.unknown?.on===!0||_(this.kept)!==this.holder()||Object.values(this.kept.choices).some(e=>e.provisional)}holder(){let e=this.session.snapshot()?.userId;return e?`user:${e}`:`device:${this.installation.id}`}lastDeniedAt(e){let t=this.kept.choices[e]?.last_denied_at;return t?new Date(t):void 0}set(e,t){this.setMany({[e]:t})}setMany(e){let t=Object.entries(e);for(let[a,o]of t){if(!qe(a))throw new TypeError(`${JSON.stringify(a)} is not a consent key (a platform key, or custom.<name>)`);if(o!=="granted"&&o!=="denied")throw new TypeError(`${a}: a choice is granted or denied`)}if(t.length===0)return;this.engage();let s=this.chosenAt(),i=this.session.snapshot()?.userId??null,r=this.states();for(let[a,o]of t)this.queue({key:a,state:o,source:"app",chosen_at:s,user:i,...this.textVersion!==void 0?{text_version:this.textVersion}:{}});this.commit(r),this.send()}onChange(e){return this.listeners.add(e),()=>this.listeners.delete(e)}async region(){this.engage();let e=await this.subject();if(this.readFor!==e)try{await this.read(e)}catch(t){if(!this.kept.region)throw t}return this.kept.region}async needsAsking(e){this.engage();let t=await this.subject();this.readFor!==t&&await this.read(t).catch(()=>{});let s=e??(await this.keys()).map(c=>c.key),i=await this.platform().catch(()=>this.kept.keys??[]),r=new Set(i.filter(c=>c.ads).map(c=>c.key)),a=this.kept.region?.jurisdiction==="us",o=new Date(this.now());return o.setUTCMonth(o.getUTCMonth()-12),s.filter(c=>{let l=this.kept.choices[c];return a&&r.has(c)&&l?.last_denied_at!==void 0&&Date.parse(l.last_denied_at)>o.getTime()?!1:!l||l.state==="unset"?!0:this.textVersion!==void 0&&l.source==="app"&&l.text_version!==this.textVersion})}engage(){this.engaged||(this.engaged=!0,this.session.session().then(e=>{e&&!this.watch&&this.follow(e),this.send(),this.refuseByGpc()}))}async subject(){return(await this.session.session())?.userId??null}secret(){return{[A]:O(this.installation)}}platform(){return this.platformKeys??=this.deviceApi.listConsentKeys().then(e=>(this.kept={...this.kept,keys:e.data.keys},this.commit(),e.data.keys),e=>{if(this.platformKeys=void 0,this.kept.keys)return this.kept.keys;throw e}),this.platformKeys}async read(e){let s=(await(e===null?this.deviceApi:this.userApi(e)).getConsents({query:{installation_id:this.installation.id},headers:this.secret()})).data;this.adopt(s,e)}adopt(e,t,s=[]){if(this.kept={...this.kept,region:e.region},(this.session.snapshot()?.userId??null)!==t){this.commit();return}let i=this.states(),r={};for(let u of e.choices)r[u.key]={state:u.state,source:u.source,chosen_at:u.chosen_at,...u.text_version!==void 0?{text_version:u.text_version}:{},...u.last_denied_at!==void 0?{last_denied_at:u.last_denied_at}:{}};let a=s.filter(u=>r[u.key]?.state!==u.state||Date.parse(r[u.key]?.chosen_at??"")!==Date.parse(u.chosen_at)).map(u=>C(u.key,u)),c=_(this.kept)===(t===null?`device:${this.installation.id}`:`user:${t}`)?Object.entries(this.kept.choices).filter(([,u])=>u.provisional).map(([u,g])=>C(u,g)):[];if(a.length+c.length>0&&(this.kept={...this.kept,void:M([...this.kept.void??[],...a,...c])}),t===null&&this.kept.resetAt!==void 0)for(let[u,g]of Object.entries(r))Date.parse(g.chosen_at)<this.kept.resetAt&&delete r[u];let l=new Set(Object.entries(r).map(([u,g])=>C(u,g))),d=(this.kept.void??[]).filter(u=>l.has(u));d.length>0&&(this.kept={...this.kept,unvoid:M([...this.kept.unvoid??[],...d])});let y=Ze(this.kept),f;if(_(this.kept)!==(t===null?`device:${this.installation.id}`:`user:${t}`))f=r;else{f={};for(let u of[...new Set([...Object.keys(this.kept.choices),...Object.keys(r)])].sort()){let g=this.kept.choices[u],m=g&&!g.provisional&&!y.has(C(u,g))?g:void 0,k=r[u],R=k&&(!m||Date.parse(k.chosen_at)>=Date.parse(m.chosen_at))?k:m;R&&(f[u]=R)}}for(let u of this.kept.unsent){if(u.user!==null&&u.user!==t||u.user===null&&u.device!==void 0&&u.device!==this.installation.id||u.user===null&&t!==null)continue;let g=f[u.key];g&&Date.parse(g.chosen_at)>Date.parse(u.chosen_at)||(f[u.key]=Fe(u,g))}let{install:b,...S}=this.kept;this.kept={...S,whose:t,...t===null?{install:this.installation.id}:{},choices:f,unknown:{on:!1,w:this.stamp()}},this.readFor=t,this.stale=!1,this.commit(i),this.refuseByGpc()}async refused(e,t,s){let i=t===e&&_(this.kept)===(t===null?`device:${this.installation.id}`:`user:${t}`),r=M([...this.kept.void??[],...s.map(c=>C(c.key,c))]);if(!i){this.kept={...this.kept,void:r},this.commit();return}let a=this.states(),o={...this.kept.choices};for(let c of s){if(this.kept.unsent.some(d=>d.key===c.key&&(d.user===null||d.user===e)&&Date.parse(d.chosen_at)>Date.parse(c.chosen_at)))continue;let l=o[c.key];o[c.key]={state:"denied",source:"app",chosen_at:c.chosen_at,...l?.last_denied_at!==void 0?{last_denied_at:l.last_denied_at}:{},provisional:!0}}this.kept={...this.kept,choices:o,void:r},this.commit(a);try{await this.read(e)}catch{this.stale=!0}}queue(e){let t=e.user===null?{...e,device:this.installation.id}:e,s=_(this.kept)===(t.user===null?`device:${this.installation.id}`:`user:${t.user}`);this.kept={...this.kept,unsent:Qe([...this.kept.unsent,t]),...s?{choices:{...this.kept.choices,[t.key]:Fe(t,this.kept.choices[t.key])}}:{}}}send(){if(this.sendAgain=!0,this.sending)return;let e=(async()=>{for(;this.sendAgain;)this.sendAgain=!1,await this.sendUnsent()||(this.sendAgain=!1)})();this.sending=e,e.finally(()=>{this.sending===e&&(this.sending=void 0)})}async sendUnsent(){this.retryTimer&&clearTimeout(this.retryTimer),this.retryTimer=void 0;let e=null;try{e=await this.subject();let t=await this.sendOf(null,e);if(e!==null&&(this.kept.link===e||t)){let s;try{s=(await this.userApi(e).linkConsents({headers:this.secret(),body:{installation_id:this.installation.id}})).data}catch(i){if(!Be(i))throw i}if(this.kept.link===e){let{link:i,...r}=this.kept;this.kept=r,this.commit()}if(s)this.adopt(s,e);else{let i=this.states();this.kept={...this.kept,unknown:{on:!0,w:this.stamp()}},this.commit(i)}}if(e!==null&&await this.sendOf(e,e),this.owesRead()&&(await this.read(e),this.owesRead()))throw new Error("the choices are not read yet");return this.retries=0,!0}catch(t){return t instanceof T&&(this.session.snapshot()?.userId??null)!==e?(this.sendAgain=!0,!0):(this.retryLater(),!1)}}async sendOf(e,t){let s=!1;for(;;){let i=this.nextGroup(e);if(i.length===0)return s;let r=i[0],a=e===null?this.deviceApi:this.userApi(e),o;try{o=(await a.chooseConsents({headers:this.secret(),body:{installation_id:this.installation.id,...r.source==="gpc"?{source:"gpc"}:{},...r.text_version!==void 0?{text_version:r.text_version}:{},choices:i.map(c=>({key:c.key,state:c.state,chosen_at:c.chosen_at}))}})).data}catch(c){if(!Be(c))throw c;if(i.length>1){this.kept={...this.kept,unsent:this.kept.unsent.map(l=>i.some(d=>Je(d,l))?{...l,alone:!0}:l)},this.commit();continue}}this.kept={...this.kept,unsent:this.kept.unsent.filter(c=>!i.some(l=>Je(l,c))),done:M([...this.kept.done??[],...i.map(se)])},this.commit(),o?(s=!0,e===t&&this.adopt(o,e,i)):await this.refused(t,e,i)}}nextGroup(e){let t=this.kept.unsent.filter(a=>a.user===e&&(e!==null||(a.device??this.installation.id)===this.installation.id)),s=t[0];if(!s)return[];let i=[],r=new Set;if(s.alone)return[s];for(let a of t)if(!r.has(a.key)&&(r.add(a.key),!(a.alone||a.source!==s.source||a.text_version!==s.text_version)&&(i.push(a),i.length===Ot)))break;return i}retryLater(){if(this.retryTimer)return;let e=Ve[Math.min(this.retries,Ve.length-1)];this.retries++,this.retryTimer=setTimeout(()=>{this.retryTimer=void 0,this.send()},e),this.retryTimer.unref?.()}signedIn(e){this.readFor=void 0,this.kept={...this.kept,link:e.userId},this.commit(),this.follow(e),this.send()}signedOut(){this.unfollow(),this.readFor=void 0;let e=this.states(),t=this.chosenAt(),s=new Set([...Object.entries(this.kept.choices).filter(([,o])=>o.state!=="unset").map(([o])=>o),...this.kept.unsent.filter(o=>o.user===null&&(o.device??this.installation.id)===this.installation.id).map(o=>o.key),...Object.keys(this.start),...this.customKeys,...(this.kept.keys??[]).map(o=>o.key)]),i={};for(let[o,c]of Object.entries(this.kept.choices))i[o]={state:"unset",source:"app",chosen_at:t,...c.last_denied_at!==void 0?{last_denied_at:c.last_denied_at}:{}};let r=o=>o.user===null&&(o.device??this.installation.id)===this.installation.id,a=this.kept.unsent.filter(r);this.kept={whose:null,install:this.installation.id,resetAt:Date.parse(t),choices:i,unsent:this.kept.unsent.filter(o=>!r(o)),...this.kept.void?{void:this.kept.void}:{},...this.kept.unvoid?{unvoid:this.kept.unvoid}:{},done:M([...this.kept.done??[],...a.map(se)]),...this.kept.region?{region:this.kept.region}:{},...this.kept.keys?{keys:this.kept.keys}:{},...this.kept.gpc?{gpc:this.kept.gpc}:{},...this.kept.unknown?{unknown:this.kept.unknown}:{}};for(let o of s)this.queue({key:o,state:"unset",source:"app",chosen_at:t,user:null});this.commit(e),this.send(),this.refuseByGpc()}follow(e){this.unfollow();let t=this.socket.channel(`consents:${this.ref}:${e.userId}`),s={userId:e.userId,channel:t,off:()=>{},version:-1},i=[t.on("broadcast",r=>{r.event==="changed"&&this.changed(s,me(r.payload))}),t.on("state_snapshot",r=>this.held(s,me(ze(r.entries)))),t.on("state_diff",r=>this.held(s,me(ze(r.set))))];s.off=()=>i.forEach(r=>r()),this.watch=s,t.join().catch(()=>{})}unfollow(){let e=this.watch;e&&(this.watch=void 0,e.off(),e.channel.leave())}held(e,t){t!==void 0&&this.changed(e,t)}changed(e,t){if(this.watch===e){if(t!==void 0){if(t<=e.version)return;e.version=t}this.read(e.userId).catch(()=>{this.watch===e&&(this.stale=!0,this.retryLater())})}}gpcRefuses(e){if(!this.gpc||!(this.kept.keys??[]).some(r=>r.key===e&&r.ads))return!1;let t=Ge(this.kept,e);if(t?.state==="denied")return!1;let s=this.kept.gpc?.[_(this.kept)],i=s!==void 0&&(this.kept.whose!=null||s>=(this.kept.resetAt??0));return!(t?.state==="granted"&&t.source==="app"&&i&&Date.parse(t.chosen_at)>s)}async refuseByGpc(){if(!this.gpc||_(this.kept)!==this.holder())return;let e;try{e=await this.platform()}catch{return}if(_(this.kept)!==this.holder())return;let t=this.session.snapshot()?.userId??null,s=e.filter(a=>a.ads&&this.gpcRefuses(a.key)&&!this.kept.unsent.some(o=>o.key===a.key&&o.source==="gpc"&&o.user===t));if(s.length===0)return;let i=this.chosenAt(),r=this.states();for(let a of s)this.queue({key:a.key,state:"denied",source:"gpc",chosen_at:i,user:t});this.kept={...this.kept,gpc:{...this.kept.gpc,[_(this.kept)]:Date.parse(i)}},this.commit(r),this.send()}states(){let e=new Map;for(let t of[...Object.keys(this.start),...Object.keys(this.kept.choices)])e.set(t,this.state(t));return e}tell(e){let t=this.states();for(let s of new Set([...e.keys(),...t.keys()])){let i=t.get(s);if(e.get(s)!==i)for(let r of[...this.listeners])try{r(s,i)}catch{}}}load(){let e;try{e=Xe()?.getItem(this.storeKey)}catch{return"unreadable"}if(e==null)return"empty";try{let t=JSON.parse(e);if(Dt(t))return t}catch{}return"unreadable"}reload(){let e=this.load();if(typeof e!="object"){this.write();return}let t=this.states();this.kept=He(e,this.kept,"theirs",this.holder()),_(e)===_(this.kept)&&We(this.kept)!==We(e)&&this.write(),this.tell(t);let s=this.session.snapshot()?.userId??null;this.engaged&&this.kept.unsent.some(i=>i.user!==null&&i.user===s||i.user===null&&(i.device??this.installation.id)===this.installation.id)&&this.retryLater(),this.engaged&&this.refuseByGpc()}commit(e=this.states()){let t=this.load();typeof t=="object"&&(this.kept=He(t,this.kept,"ours",this.holder())),this.write(),this.tell(e)}write(){try{Xe()?.setItem(this.storeKey,JSON.stringify(this.kept))}catch{}}chosenAt(){return this.lastChosen=Math.max(this.now(),this.lastChosen+1),new Date(this.lastChosen).toISOString()}stamp(){let e=this.kept,t=e?Math.max(0,e.unknown?.w??0):0;return this.lastW=Math.max(this.now(),this.lastW+1,t+1),this.lastW}};function Fe(n,e){let t=n.state==="denied"?n.chosen_at:e?.last_denied_at;return{state:n.state,source:n.source,chosen_at:n.chosen_at,...n.text_version!==void 0?{text_version:n.text_version}:{},...t!==void 0?{last_denied_at:t}:{}}}function C(n,e){return`${n}|${e.provisional?"provisional":e.state}|${Date.parse(e.chosen_at)}`}function Ze(n){let e=new Set(n.unvoid??[]);return new Set((n.void??[]).filter(t=>!e.has(t)))}var ee={denied:2,unset:1,granted:0};function Mt(n,e,t,s){let i=e&&!s.has(C(n,e))?e:void 0,r=t&&!s.has(C(n,t))?t:void 0;if(!i||!r)return i??r;let a=Date.parse(i.chosen_at),o=Date.parse(r.chosen_at);return a!==o?a>o?i:r:ee[i.state]!==ee[r.state]?ee[i.state]>ee[r.state]?i:r:i.provisional?r:i}function Nt(n,e){return!n||!e?n??e:e.w>n.w||e.w===n.w&&e.on?e:n}function He(n,e,t,s){let i=M([...n.void??[],...e.void??[]]),r=M([...n.unvoid??[],...e.unvoid??[]]),a=Ze({void:i,unvoid:r}),o={},c,l={...n.gpc};for(let[m,k]of Object.entries(e.gpc??{}))l[m]=Math.max(l[m]??0,k);let d;if(_(n)===_(e)){c=e;for(let m of[...new Set([...Object.keys(n.choices),...Object.keys(e.choices)])].sort()){let k=Mt(m,n.choices[m],e.choices[m],a);k&&(o[m]=k)}d=Nt(n.unknown,e.unknown)}else{c=_(e)===s?e:_(n)===s?n:t==="ours"?e:n;for(let[m,k]of Object.entries(c.choices))a.has(C(m,k))||(o[m]=k);d=c.unknown}let y=M([...n.done??[],...e.done??[]]),f=Qe([...n.unsent,...e.unsent]).filter(m=>!y.includes(se(m))),b=t==="ours"?e:n,S=t==="ours"?n:e,u=b.region??S.region,g=b.keys??S.keys;return{whose:c.whose??null,...c.whose==null&&c.install!==void 0?{install:c.install}:{},...c.whose==null&&(n.resetAt!==void 0||e.resetAt!==void 0)&&_(n)===_(e)?{resetAt:Math.max(n.resetAt??0,e.resetAt??0)}:c.whose==null&&c.resetAt!==void 0?{resetAt:c.resetAt}:{},choices:o,unsent:f,...y.length>0?{done:y}:{},...i.length>0?{void:i}:{},...r.length>0?{unvoid:r}:{},...b.link!==void 0?{link:b.link}:{},...u?{region:u}:{},...Object.keys(l).length>0?{gpc:l}:{},...g?{keys:g}:{},...d?{unknown:d}:{}}}function se(n){return`${n.user??`device:${n.device??""}`}|${n.key}|${n.state}|${n.source}|${n.chosen_at}`}function Ge(n,e){let t=n.choices[e];if(!t||n.whose!=null||n.resetAt===void 0||Date.parse(t.chosen_at)>=n.resetAt)return t}function _(n){return n.whose!=null?`user:${n.whose}`:`device:${n.install??""}`}function M(n){return[...new Set(n)].slice(-Ct)}function We(n){return JSON.stringify(n,(e,t)=>typeof t=="object"&&t!==null&&!Array.isArray(t)?Object.fromEntries(Object.entries(t).sort(([s],[i])=>s.localeCompare(i))):t)}function Qe(n){let e=new Map;for(let t of n){let s=se(t),i=e.get(s);e.set(s,i?i.alone||!t.alone?i:{...i,alone:!0}:t)}return[...e.values()].sort((t,s)=>Date.parse(t.chosen_at)-Date.parse(s.chosen_at))}var Lt=new Set(["granted","denied","unset"]);function Dt(n){if(typeof n!="object"||n===null)return!1;let e=n;if(typeof e.choices!="object"||e.choices===null||Array.isArray(e.choices)||!Array.isArray(e.unsent))return!1;let t=(o,c)=>{if(typeof o!="object"||o===null)return!1;let l=o;return Lt.has(l.state)&&typeof l.chosen_at=="string"&&(!c||typeof l.key=="string")},s=o=>o===void 0||typeof o=="object"&&o!==null&&typeof o.on=="boolean"&&typeof o.w=="number",i=n,r=o=>o===void 0||Array.isArray(o)&&o.every(c=>typeof c=="string"),a=i.whose===void 0||i.whose===null||typeof i.whose=="string";return Object.values(e.choices).every(o=>t(o,!1))&&e.unsent.every(o=>t(o,!0))&&(i.gpc===void 0||typeof i.gpc=="object"&&i.gpc!==null&&Object.values(i.gpc).every(o=>typeof o=="number"))&&s(i.unknown)&&r(i.done)&&r(i.void)&&r(i.unvoid)&&a}function Je(n,e){return n.key===e.key&&n.user===e.user&&n.state===e.state&&n.source===e.source&&n.chosen_at===e.chosen_at}function Be(n){return n instanceof I&&n.status>=400&&n.status<500&&n.status!==401&&n.status!==408&&n.status!==429}function Xe(){try{return globalThis.localStorage}catch{return}}function ze(n){let e=typeof n=="object"&&n!==null?n.version:void 0;return typeof e=="object"&&e!==null?e.v:void 0}function me(n){let e=typeof n=="object"&&n!==null?n.version:void 0;return typeof e=="number"&&Number.isFinite(e)?e:void 0}var Ut=`
|
|
3
3
|
:host{display:block;color-scheme:light dark;font:15px/1.4 system-ui,-apple-system,"Segoe UI",Roboto,sans-serif}
|
|
4
4
|
.list{display:flex;flex-direction:column;gap:8px;margin:0;padding:0;list-style:none}
|
|
5
5
|
.item{position:relative;display:flex;gap:12px;align-items:flex-start;padding:12px 40px 12px 12px;border-radius:12px;background:var(--bg);color:var(--fg);cursor:pointer;outline:none}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
2
|
-
import{a as L,c as me,d as he,e as ye}from"./
|
|
1
|
+
/*! palbase 0.10.1 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{a as L,c as me,d as he,e as ye}from"./IVJCGBYG.js";import{a as we}from"./6N3E2XHZ.js";import{a as ue}from"./YQEM4H7U.js";import{a as pe,b as ge,c as fe}from"./RO7ERCT3.js";import{b as I,d as le}from"./RWGEPDRQ.js";async function*be(e,t={}){let o=e.getReader(),a=new TextDecoder,i="",u="",l=[],m,s=()=>{o.cancel().catch(()=>{})};t.signal?.addEventListener("abort",s,{once:!0});try{if(t.signal?.aborted)return;for(;;){let{done:n,value:r}=await o.read();if(n||t.signal?.aborted)return;t.onBytes?.(),i+=a.decode(r,{stream:!0});for(let d=i.indexOf(`
|
|
3
3
|
`);d>=0;d=i.indexOf(`
|
|
4
4
|
`)){let p=i.slice(0,i[d-1]==="\r"?d-1:d);i=i.slice(d+1),p===""?(u!==""&&(yield m===void 0?{event:u,data:l.join(`
|
|
5
5
|
`)}:{event:u,data:l.join(`
|