palbase 0.29.0 → 0.30.0

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.
Files changed (48) hide show
  1. package/dist/ai/index.js +2 -2
  2. package/dist/backend/engine.js +2 -2
  3. package/dist/backend/env.js +1 -1
  4. package/dist/backend/index.js +3 -3
  5. package/dist/backend/stack.js +1 -1
  6. package/dist/backend/test.js +2 -2
  7. package/dist/chunks/{62XTQSVZ.js → 2HCODUCC.js} +2 -2
  8. package/dist/chunks/{66PTYGSE.js → 425EWENK.js} +2 -2
  9. package/dist/chunks/{C2SU644S.js → 5CGZD6ER.js} +2 -2
  10. package/dist/chunks/{AMWYOTRD.js → 5KRLND5G.js} +2 -2
  11. package/dist/chunks/{OAVOR7X5.js → AGYCOKIU.js} +1 -1
  12. package/dist/chunks/{KN6YJGWP.js → AU2V6M6Q.js} +2 -2
  13. package/dist/chunks/{OCZ5XVNP.js → CVO4TDIH.js} +1 -1
  14. package/dist/chunks/{OLRLJB7H.js → DF4GUELY.js} +1 -1
  15. package/dist/chunks/{GV63GJ4D.js → DGN5C3D4.js} +2 -2
  16. package/dist/chunks/{IYJRPKS2.js → DTMKEMIF.js} +2 -2
  17. package/dist/chunks/{4Q5QXL7S.js → FYJRLZWD.js} +1 -1
  18. package/dist/chunks/{GJPGCOTW.js → GT4Z7F3E.js} +2 -2
  19. package/dist/chunks/{3NB2Z2MF.js → K5N4GOSB.js} +1 -1
  20. package/dist/chunks/{MKLUERPB.js → KGH6GRJH.js} +2 -2
  21. package/dist/chunks/{EWMPKYBN.js → KVYTS3P2.js} +1 -1
  22. package/dist/chunks/{VCUKXTAR.js → LZN5JQDI.js} +2 -2
  23. package/dist/chunks/{HC2AGD3N.js → MN7PDXRL.js} +2 -2
  24. package/dist/chunks/{IQ6QJDM4.js → PN5NJVJ6.js} +2 -2
  25. package/dist/chunks/{WNEUGMU4.js → RYYYVFUC.js} +1 -1
  26. package/dist/chunks/{ZVRYGPBA.js → SLQWIFCV.js} +2 -2
  27. package/dist/chunks/{IOU6E244.js → VVHRNZRS.js} +2 -2
  28. package/dist/chunks/{A6CGX34F.js → WUUXHETU.js} +2 -2
  29. package/dist/chunks/{I5IDPWDM.js → Y5OIT4QP.js} +2 -2
  30. package/dist/cli.js +121 -121
  31. package/dist/cloud/index.js +2 -2
  32. package/dist/refuse/ai.js +1 -1
  33. package/dist/refuse/backend.js +1 -1
  34. package/dist/refuse/cloud.js +1 -1
  35. package/dist/refuse/server.js +1 -1
  36. package/dist/server/index.js +2 -2
  37. package/dist/server/testing.js +2 -2
  38. package/dist/web/calls-ui.js +2 -2
  39. package/dist/web/index.js +2 -2
  40. package/dist/web/message.js +2 -2
  41. package/dist/web/palbe.js +2 -2
  42. package/dist/web/paywall.js +2 -2
  43. package/dist/web/push-sw.js +1 -1
  44. package/dist/web/ssr.js +2 -2
  45. package/dist/web/vite.js +2 -2
  46. package/package.json +2 -2
  47. package/types/cloud/src/generated/project.d.ts +1 -1
  48. package/types/internal/src/modules/machines.d.ts +33 -4
@@ -1,2 +1,2 @@
1
- /*! palbase 0.29.0 — Palbase SDK License (see LICENSE) */
2
- import{a as se}from"./EWMPKYBN.js";import{b as R}from"./4Q5QXL7S.js";import{a as U,b as C,c as L,d as $,e as N,f as I,h as F,i as D,j as W,k as B,l as H,m as q,n as z,o as V}from"./C2SU644S.js";import{a as m,c as G,d as X,e as Z,f as Q,h as ee,i as te,j as A,k as ne,l as re,o as P}from"./OLRLJB7H.js";import{a as J,b as Y}from"./62XTQSVZ.js";import{b as T,d as v}from"./KN6YJGWP.js";var f=class extends Error{status=400;code;data;constructor(e,t,r={}){super(t),this.name="TransitRefusal",this.code=e,this.data=r}},Te=6e4,Ae=1e3;function x(n){return/^t[1-9][0-9]{0,5}$/.test(n)?Number(n.slice(1)):0}var k=class{keys=new Map;retired=new Set;order=[];project;timer;fetchedAt=0;heldFrom=0;fetching;opts;now;sleep;constructor(e){this.opts=e,this.now=e.now??Date.now,this.sleep=e.sleep??(t=>new Promise(r=>setTimeout(r,t)))}get loaded(){return this.project!==void 0}get projectId(){if(this.project===void 0)throw new Error("the project's transit keys are not loaded: await palbase.transit.load() at startup");return this.project}current(){return this.order[0]}async load(e){await this.refresh(e),this.timer===void 0&&(this.timer=setInterval(()=>{this.refresh().catch(()=>{})},Te),this.timer.unref?.())}close(){clearInterval(this.timer),this.timer=void 0}refresh(e){return this.fetching??=(async()=>{let t=this.now();try{let r=await this.opts.fetch(e),s=new Map;for(let i of r.keys){let o=X(i.key);s.set(i.id,{privateKey:o,publicKey:this.keys.get(i.id)?.publicKey??await Z(o)})}this.keys=s,this.order=r.keys.map(i=>i.id),this.retired=new Set(r.retired),this.project=r.project,this.fetchedAt=this.now(),this.heldFrom=t}finally{this.fetching=void 0}})(),this.fetching}newest(){return Math.max(0,...this.order.map(x),...[...this.retired].map(x))}async key(e){let t=this.now();for(;x(e)>this.newest()&&this.heldFrom<t;){let i=this.fetchedAt+Ae-this.now();if(i>0){await this.sleep(i);continue}await this.refresh()}let r=this.keys.get(e),s=this.current();if(this.retired.has(e))throw new f("encryption_key_retired",`the request is sealed to ${e}, retired: fetch the project's keys again`,{current:s});if(r===void 0)throw new f("encryption_key_unknown",`the request is sealed to ${e}, which the project has not made`,{current:s});return r}async request(e){if(e.header===void 0||e.header===null||e.header==="")throw new f("encryption_required",`this route carries encrypted fields: the request names its key in ${m}`,{field:m,current:this.current()});let t;try{t=ee(e.header).kid}catch{throw new f("encryption_unopenable",`${m} is not one`,{field:m})}let r=await this.key(t),s;try{s=Q(this.projectId,e.method,e.path,e.params??[])}catch{throw new f("encryption_unopenable","the request's path holds a value no key is sealed for",{field:m})}try{return new S(t,await te(e.header,r.privateKey,r.publicKey,s))}catch(i){throw i instanceof G?new f("encryption_unopenable","the request's key does not open: sealed for another project, route or path, or changed",{field:m}):i}}},S=class{kid;key;constructor(e,t){this.kid=e,this.key=t}async open(e,t,r){return P(e,t,r,async(s,i)=>{if(!ne(i))throw new f("encryption_required",`${s} is an encrypted field: it came plain`,{field:s});try{return await re(this.key,s,i)}catch{throw new f("encryption_unopenable",`${s} does not open: changed, moved from another field, or another request's`,{field:s})}})}async seal(e,t){return P(e,"/response",t,(r,s)=>A(this.key,r,s))}sealField(e,t){return A(this.key,e,t)}};var Pe=/^pb_[a-z0-9]+_s/;function O(n){if(se())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"||!Pe.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=Y(v({baseUrl:n.url,credentials:{secretKey:n.secretKey},fetch:n.fetch,solveProofOfWork:n.solveProofOfWork??!1}),n.retry??J),t=q.client(e);return{ai:U.client(e),analytics:C.client(e),auth:L.client(e),cache:$.client(e),calls:N.client(e),fields:new R({fetch:async r=>(await t.getFieldKeys({signal:r})).data}),flags:I.client(e),machines:F.client(e),messaging:D.client(e),notify:W.client(e),purchases:B.client(e),realtime:H.client(e),secrets:t,storage:z.client(e),stores:V.client(e),transit:new k({fetch:async r=>(await t.getTransitKeys({signal:r})).data}),transport:e,url:new URL(n.url).origin}}var h=class extends Error{code;constructor(e,t){super(t),this.name="WebhookSignatureError",this.code=e}},xe=300,Oe=/^[0-9]{1,12}$/,je=/^[0-9a-f]{64}$/,ie=8,Me=/^whsec_[0-9A-Za-z]{32,}$/,Ke=1024*1024;async function oe(n){if(typeof n.secret!="string"||!Me.test(n.secret))throw new TypeError("secret is the webhook endpoint secret (whsec_\u2026), not an API key");await ae(n);let e;try{e=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(de(n.body)))}catch{throw new h("invalid_body","the signed body is not JSON")}if(!Ie(e))throw new h("invalid_body","the signed body is not a Palbase event (id, type, project_id, created_at, data)");return e}async function ae(n){if(typeof n.secret!="string"||n.secret==="")throw new TypeError("secret is the key the request was signed with");let e=de(n.body),{t,v1:r}=ce(n),s=await crypto.subtle.importKey("raw",new TextEncoder().encode(n.secret),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),i=new Uint8Array(await crypto.subtle.sign("HMAC",s,Ne(new TextEncoder().encode(`${t}.`),e))),o=!1;for(let d of r)$e(i,Le(d))&&(o=!0);if(!o)throw new h("signature_mismatch","no v1 in Palbase-Signature is this body signed with this secret")}function ce(n){let e=n.toleranceSeconds??xe;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 h("missing_signature","the request carries no Palbase-Signature header");let s,i=[];for(let o of r.split(",")){let d=o.indexOf("=");if(d<=0)throw new h("malformed_signature","Palbase-Signature is t=<seconds>,v1=<hex>");let c=o.slice(0,d).trim(),a=o.slice(d+1).trim();if(c==="t"){if(s!==void 0||!Oe.test(a))throw new h("malformed_signature","Palbase-Signature carries one t, in unix seconds");s=a}else if(c==="v1"){if(!je.test(a))throw new h("malformed_signature","a v1 is 64 lowercase hex characters");if(i.length===ie)throw new h("malformed_signature",`Palbase-Signature carries at most ${ie} v1`);i.push(a)}}if(s===void 0||i.length===0)throw new h("malformed_signature","Palbase-Signature is t=<seconds>,v1=<hex>");if(Math.abs(t/1e3-Number(s))>e)throw new h("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:i}}async function Ue(n,e,t={}){let r=await Ce(n,t.maxBytes??Ke);return oe({toleranceSeconds:t.toleranceSeconds,now:t.now,secret:e,signature:n.headers.get("palbase-signature"),body:r})}async function Ce(n,e){let t=()=>new h("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(),i=[],o=0;for(;;){let{done:a,value:l}=await s.read();if(a)break;if(o+=l.byteLength,o>e)throw await s.cancel().catch(()=>{}),t();i.push(l)}let d=new Uint8Array(o),c=0;for(let a of i)d.set(a,c),c+=a.byteLength;return d}function de(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 Le(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 $e(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 Ne(n,e){let t=new Uint8Array(n.byteLength+e.byteLength);return t.set(n,0),t.set(e,n.byteLength),t}function Ie(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 ue=60,Fe=60,De=8*1024,We=1e5;function j(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 fe(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 le(n){let e=fe(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 E=class{byKey=new Map;held=0;sweptAt=Number.NEGATIVE_INFINITY;max;constructor(e=We){this.max=e}spend(e,t){if(t>=e.until)throw new u("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 u("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,i]of t){if(i>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[i,o]of s)o>e||(s.delete(i),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 Be(n,e){let t=`{"crv":"P-256","kty":"EC","x":"${n}","y":"${e}"}`;return j(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(t)))}function he(n){try{let e=new URL(n);return e.username!==""||e.password!==""?void 0:`${e.protocol}//${e.host}${e.pathname}`}catch{return}}async function pe(n,e,t,r){let s=_e=>{throw new u("proof",`the DPoP proof is not taken: ${_e}`)},i=t.proof;if(!i)return s("there is none (a DPoP-bound token comes with a DPoP header)");if(i.length>De)return s("it is too long");let o=i.split(".");if(o.length!==3)return s("it is not a JWS of three parts");let d=le(o[0]),c=le(o[1]);if(!d||!c)return s("its header or claims are not base64url JSON");if(d.typ!=="dpop+jwt")return s("its typ is not dpop+jwt");if(d.alg!=="ES256")return s(`it is signed with ${String(d.alg)}; only ES256 is taken`);let a=d.jwk;if(!a||typeof a!="object"||a.kty!=="EC"||a.crv!=="P-256"||typeof a.x!="string"||typeof a.y!="string")return s("its header carries no P-256 public key");if("d"in a)return s("its header carries a private key");if(await Be(a.x,a.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:a.x,y:a.y,ext:!0},{name:"ECDSA",namedCurve:"P-256"},!1,["verify"])}catch{return s("its key is not a P-256 point")}let y=fe(o[2]);if(!y||!await crypto.subtle.verify({name:"ECDSA",hash:"SHA-256"},l,y,new TextEncoder().encode(`${o[0]}.${o[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 p=typeof c.htu=="string"?he(c.htu):void 0,g=he(t.url);if(!p||!g||p!==g)return s(`it is for ${String(c.htu)}, not ${g??t.url}`);let ve=r/1e3;if(typeof c.iat!="number"||Math.abs(c.iat-ve)>ue)return s("it was not made within a minute of now");let Se=j(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 Ee=j(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(c.jti)));return{jkt:e,jti:Ee,until:(c.iat+ue+Fe)*1e3+1}}var u=class extends Error{reason;constructor(e,t){super(t),this.name="TokenError",this.reason=e}},w=class extends Error{constructor(e,t){super(e,t),this.name="AuthUnavailable"}},He=new Set(["invalid_api_key","missing_api_key","secret_key_in_browser"]);function qe(n){return async e=>{let t=v({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 T&&r.status===401&&!He.has(r.code))return!1;throw new w("a session's standing could not be told",{cause:r})}}}var M={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}}},ye=60,ze=16*1024,Ve=10*6e4,Je=5e4,ge=n=>typeof n=="string"&&Object.hasOwn(M,n),K=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 E;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>ze)throw new u("malformed","the token is not a JWT");let r=e.split(".");if(r.length!==3)throw new u("malformed","the token is not a JWS of three parts");let s=me(r[0]),i=me(r[1]);if(!s||!i)throw new u("malformed","the token header or claims are not base64url JSON");let o=s.alg;if(!ge(o))throw new u("algorithm",`the token is signed with ${String(o)}; only ES256 and PS256 are taken`);let d=s.kid;if(typeof d!="string"||d==="")throw new u("malformed","the token header names no kid");let c=await this.key(d);if(!c)throw new u("unknown_key",`no key ${d} in the project's key set`);if(c.alg!==o)throw new u("algorithm",`key ${d} is ${c.alg}, the token says ${o}`);let a=be(r[2]);if(!a)throw new u("malformed","the signature is not base64url");let l=new TextEncoder().encode(`${r[0]}.${r[1]}`);if(!await crypto.subtle.verify(M[c.alg].verify,c.key,a,l).catch(()=>!1))throw new u("signature","the signature does not verify");let b=this.check(i),p=i.cnf,g;if(p!==void 0){if(!t)throw new u("bound","the token is bound to a key (DPoP): it comes with the DPoP scheme and a proof, not as a Bearer");if(typeof p!="object"||p===null||typeof p.jkt!="string"||p.jkt==="")throw new u("bound","the token is bound to a key it does not name (cnf.jkt)");g=await pe(e,p.jkt,t,this.now())}else if(t)throw new u("not_bound","the DPoP scheme came with a token bound to no key");if(!await this.stands(e,b.sessionId))throw new u("session_ended","the token's session has ended (signed out, revoked, or its user banned)");return g&&this.seenProofs.spend(g,this.now()),b}async verifyRequest(e){let t=e.headers instanceof Headers?e.headers:Ge(e.headers),r=t.get("authorization")??"";if(r==="")return null;let s=/^(bearer|dpop)\s+(\S+)$/i.exec(r);if(!s)throw new u("malformed","the Authorization header is not a Bearer or DPoP token");let i=s[1].toLowerCase()==="dpop",o=new URL(e.url,`http://${t.get("host")??"localhost"}`);return this.verify(s[2],i?{proof:t.get("dpop"),method:e.method,url:we(t,o)}:void 0)}async stands(e,t){let r=this.now(),s=this.standings.get(t);if(s&&r<s.until)return s.live;let i=this.asking.get(t);i||(i=this.standing(e,t).finally(()=>this.asking.delete(t)),this.asking.set(t,i));let o;try{o=await i}catch(c){let a=this.standings.get(t),l=this.now();if(a&&l<a.at+this.standingStaleMs)return a.until=Math.min(l+this.standingTtlMs,a.at+this.standingStaleMs),a.live;throw new w("a session's standing cannot be read now",{cause:c})}let d=this.now();return this.standings.delete(t),this.standings.set(t,{live:o,at:d,until:d+this.standingTtlMs}),this.standings.size>Je&&this.standings.delete(this.standings.keys().next().value),o}check(e){if(e.iss!==this.issuer)throw new u("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 u("audience","the token is not meant for this project");if(e.project_id!==this.projectId)throw new u("project","the token names another project");let r=this.now()/1e3;if(typeof e.exp!="number"||e.exp+ye<=r)throw new u("expired","the token has expired");if(e.nbf!==void 0&&(typeof e.nbf!="number"||e.nbf-ye>r))throw new u("not_yet_valid","the token is not valid yet");if(typeof e.sub!="string"||e.sub===""||typeof e.auth_time!="number")throw new u("not_a_user","the token is not a user's");if(typeof e.session_id!="string"||e.session_id==="")throw new u("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 u("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+Ve;if(this.lastFailure!==void 0&&t-this.lastFetch<this.refetchIntervalMs){if(!s)throw new w("the project's key set cannot be read now",{cause:this.lastFailure})}else try{await this.refresh()}catch(i){if(!s)throw i}}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(i){throw this.lastFailure=i,new w("the project's key set cannot be read now",{cause:i})}this.lastFailure=void 0;let r=new Map;for(let i of Array.isArray(e.keys)?e.keys:[]){let o=i.alg;if(typeof i.kid!="string"||!ge(o))continue;let d=M[o];if(i.kty!==d.kty||i.use!==void 0&&i.use!=="sig")continue;let{d:c,...a}=i;try{r.set(i.kid,{alg:o,key:await crypto.subtle.importKey("jwk",a,d.import,!1,["verify"])})}catch{}}this.keys=r;let s=Xe(t.headers.get("cache-control"))??this.maxKeyAgeMs;this.keysUntil=this.now()+Math.min(Math.max(s,this.refetchIntervalMs),this.maxKeyAgeMs)}};function we(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 Ye.test(s)?`${r}://${s}${e.pathname}`:""}var Ye=/^(?:[a-z0-9-]+(?:\.[a-z0-9-]+)*|\[[0-9a-f:.]+\])(?::[0-9]{1,5})?$/i;function Ge(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 Xe(n){let e=/(?:^|,)\s*max-age=(\d+)/i.exec(n??"");return e?Number(e[1])*1e3:void 0}function be(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 me(n){let e=be(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 Ze(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 _=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 Qe(n,e,t,r){let{idempotencyKey:s,amount:i,ttlSeconds:o,metadata:d}=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:i,...t.credits!==void 0?{credits:t.credits}:{limit:t.limit},...o!==void 0?{ttl_seconds:o}:{},...d!==void 0?{metadata:d}:{}},a=(await n.purchases.holdSpend({path:{customer_id:e},headers:{"Idempotency-Key":s},body:c})).data;if(a.status!=="held")throw new _(a);let l={customer_id:a.customer,spend_id:a.id},y;try{y=await r(a)}catch(b){throw await n.purchases.releaseSpend({path:l}).catch(()=>{}),b}return await n.purchases.commitSpend({path:l}),y}async function*et(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 tt=/^[A-Za-z_][A-Za-z0-9_]{0,127}$/,nt=/^(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 ke(n){return!tt.test(n)||nt.test(n)||/_PROXY$/i.test(n)}var rt=/^(PORT|PALBASE_(URL|PROJECT_ID|MACHINE|REPLICAS|SECRET_KEY|WEBHOOK_SECRET|PLATFORM_SECRET|CONTRACT_OUT|SECRETS|DB_[A-Z0-9_]+))$/;function st(n){return rt.test(n)}async function it(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 i=O({url:new URL(r).origin,secretKey:s,fetch:n.fetch}),{data:o}=await i.secrets.getEnvironmentValues({path:{environment:t}}),d=[],c=[],a=[];for(let[l,y]of Object.entries(o.values)){if(ke(l)){a.push(l);continue}if(e[l]!==void 0&&e[l]!==""){c.push(l);continue}e[l]=y,d.push(l)}return{set:t,loaded:d.sort(),kept:c.sort(),refused:a.sort()}}export{f as a,k as b,S as c,O as d,h as e,oe as f,ae as g,ce as h,Ue as i,u as j,w as k,qe as l,K as m,we as n,Ze as o,_ as p,Qe as q,et as r,ke as s,st as t,it as u};
1
+ /*! palbase 0.30.0 — Palbase SDK License (see LICENSE) */
2
+ import{a as se}from"./KVYTS3P2.js";import{b as R}from"./FYJRLZWD.js";import{a as U,b as C,c as L,d as $,e as N,f as I,h as F,i as D,j as W,k as B,l as H,m as q,n as z,o as V}from"./5CGZD6ER.js";import{a as m,c as G,d as X,e as Z,f as Q,h as ee,i as te,j as A,k as ne,l as re,o as P}from"./DF4GUELY.js";import{a as J,b as Y}from"./2HCODUCC.js";import{b as T,d as v}from"./AU2V6M6Q.js";var f=class extends Error{status=400;code;data;constructor(e,t,r={}){super(t),this.name="TransitRefusal",this.code=e,this.data=r}},Te=6e4,Ae=1e3;function x(n){return/^t[1-9][0-9]{0,5}$/.test(n)?Number(n.slice(1)):0}var k=class{keys=new Map;retired=new Set;order=[];project;timer;fetchedAt=0;heldFrom=0;fetching;opts;now;sleep;constructor(e){this.opts=e,this.now=e.now??Date.now,this.sleep=e.sleep??(t=>new Promise(r=>setTimeout(r,t)))}get loaded(){return this.project!==void 0}get projectId(){if(this.project===void 0)throw new Error("the project's transit keys are not loaded: await palbase.transit.load() at startup");return this.project}current(){return this.order[0]}async load(e){await this.refresh(e),this.timer===void 0&&(this.timer=setInterval(()=>{this.refresh().catch(()=>{})},Te),this.timer.unref?.())}close(){clearInterval(this.timer),this.timer=void 0}refresh(e){return this.fetching??=(async()=>{let t=this.now();try{let r=await this.opts.fetch(e),s=new Map;for(let i of r.keys){let o=X(i.key);s.set(i.id,{privateKey:o,publicKey:this.keys.get(i.id)?.publicKey??await Z(o)})}this.keys=s,this.order=r.keys.map(i=>i.id),this.retired=new Set(r.retired),this.project=r.project,this.fetchedAt=this.now(),this.heldFrom=t}finally{this.fetching=void 0}})(),this.fetching}newest(){return Math.max(0,...this.order.map(x),...[...this.retired].map(x))}async key(e){let t=this.now();for(;x(e)>this.newest()&&this.heldFrom<t;){let i=this.fetchedAt+Ae-this.now();if(i>0){await this.sleep(i);continue}await this.refresh()}let r=this.keys.get(e),s=this.current();if(this.retired.has(e))throw new f("encryption_key_retired",`the request is sealed to ${e}, retired: fetch the project's keys again`,{current:s});if(r===void 0)throw new f("encryption_key_unknown",`the request is sealed to ${e}, which the project has not made`,{current:s});return r}async request(e){if(e.header===void 0||e.header===null||e.header==="")throw new f("encryption_required",`this route carries encrypted fields: the request names its key in ${m}`,{field:m,current:this.current()});let t;try{t=ee(e.header).kid}catch{throw new f("encryption_unopenable",`${m} is not one`,{field:m})}let r=await this.key(t),s;try{s=Q(this.projectId,e.method,e.path,e.params??[])}catch{throw new f("encryption_unopenable","the request's path holds a value no key is sealed for",{field:m})}try{return new S(t,await te(e.header,r.privateKey,r.publicKey,s))}catch(i){throw i instanceof G?new f("encryption_unopenable","the request's key does not open: sealed for another project, route or path, or changed",{field:m}):i}}},S=class{kid;key;constructor(e,t){this.kid=e,this.key=t}async open(e,t,r){return P(e,t,r,async(s,i)=>{if(!ne(i))throw new f("encryption_required",`${s} is an encrypted field: it came plain`,{field:s});try{return await re(this.key,s,i)}catch{throw new f("encryption_unopenable",`${s} does not open: changed, moved from another field, or another request's`,{field:s})}})}async seal(e,t){return P(e,"/response",t,(r,s)=>A(this.key,r,s))}sealField(e,t){return A(this.key,e,t)}};var Pe=/^pb_[a-z0-9]+_s/;function O(n){if(se())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"||!Pe.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=Y(v({baseUrl:n.url,credentials:{secretKey:n.secretKey},fetch:n.fetch,solveProofOfWork:n.solveProofOfWork??!1}),n.retry??J),t=q.client(e);return{ai:U.client(e),analytics:C.client(e),auth:L.client(e),cache:$.client(e),calls:N.client(e),fields:new R({fetch:async r=>(await t.getFieldKeys({signal:r})).data}),flags:I.client(e),machines:F.client(e),messaging:D.client(e),notify:W.client(e),purchases:B.client(e),realtime:H.client(e),secrets:t,storage:z.client(e),stores:V.client(e),transit:new k({fetch:async r=>(await t.getTransitKeys({signal:r})).data}),transport:e,url:new URL(n.url).origin}}var h=class extends Error{code;constructor(e,t){super(t),this.name="WebhookSignatureError",this.code=e}},xe=300,Oe=/^[0-9]{1,12}$/,je=/^[0-9a-f]{64}$/,ie=8,Me=/^whsec_[0-9A-Za-z]{32,}$/,Ke=1024*1024;async function oe(n){if(typeof n.secret!="string"||!Me.test(n.secret))throw new TypeError("secret is the webhook endpoint secret (whsec_\u2026), not an API key");await ae(n);let e;try{e=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(de(n.body)))}catch{throw new h("invalid_body","the signed body is not JSON")}if(!Ie(e))throw new h("invalid_body","the signed body is not a Palbase event (id, type, project_id, created_at, data)");return e}async function ae(n){if(typeof n.secret!="string"||n.secret==="")throw new TypeError("secret is the key the request was signed with");let e=de(n.body),{t,v1:r}=ce(n),s=await crypto.subtle.importKey("raw",new TextEncoder().encode(n.secret),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),i=new Uint8Array(await crypto.subtle.sign("HMAC",s,Ne(new TextEncoder().encode(`${t}.`),e))),o=!1;for(let d of r)$e(i,Le(d))&&(o=!0);if(!o)throw new h("signature_mismatch","no v1 in Palbase-Signature is this body signed with this secret")}function ce(n){let e=n.toleranceSeconds??xe;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 h("missing_signature","the request carries no Palbase-Signature header");let s,i=[];for(let o of r.split(",")){let d=o.indexOf("=");if(d<=0)throw new h("malformed_signature","Palbase-Signature is t=<seconds>,v1=<hex>");let c=o.slice(0,d).trim(),a=o.slice(d+1).trim();if(c==="t"){if(s!==void 0||!Oe.test(a))throw new h("malformed_signature","Palbase-Signature carries one t, in unix seconds");s=a}else if(c==="v1"){if(!je.test(a))throw new h("malformed_signature","a v1 is 64 lowercase hex characters");if(i.length===ie)throw new h("malformed_signature",`Palbase-Signature carries at most ${ie} v1`);i.push(a)}}if(s===void 0||i.length===0)throw new h("malformed_signature","Palbase-Signature is t=<seconds>,v1=<hex>");if(Math.abs(t/1e3-Number(s))>e)throw new h("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:i}}async function Ue(n,e,t={}){let r=await Ce(n,t.maxBytes??Ke);return oe({toleranceSeconds:t.toleranceSeconds,now:t.now,secret:e,signature:n.headers.get("palbase-signature"),body:r})}async function Ce(n,e){let t=()=>new h("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(),i=[],o=0;for(;;){let{done:a,value:l}=await s.read();if(a)break;if(o+=l.byteLength,o>e)throw await s.cancel().catch(()=>{}),t();i.push(l)}let d=new Uint8Array(o),c=0;for(let a of i)d.set(a,c),c+=a.byteLength;return d}function de(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 Le(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 $e(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 Ne(n,e){let t=new Uint8Array(n.byteLength+e.byteLength);return t.set(n,0),t.set(e,n.byteLength),t}function Ie(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 ue=60,Fe=60,De=8*1024,We=1e5;function j(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 fe(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 le(n){let e=fe(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 E=class{byKey=new Map;held=0;sweptAt=Number.NEGATIVE_INFINITY;max;constructor(e=We){this.max=e}spend(e,t){if(t>=e.until)throw new u("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 u("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,i]of t){if(i>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[i,o]of s)o>e||(s.delete(i),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 Be(n,e){let t=`{"crv":"P-256","kty":"EC","x":"${n}","y":"${e}"}`;return j(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(t)))}function he(n){try{let e=new URL(n);return e.username!==""||e.password!==""?void 0:`${e.protocol}//${e.host}${e.pathname}`}catch{return}}async function pe(n,e,t,r){let s=_e=>{throw new u("proof",`the DPoP proof is not taken: ${_e}`)},i=t.proof;if(!i)return s("there is none (a DPoP-bound token comes with a DPoP header)");if(i.length>De)return s("it is too long");let o=i.split(".");if(o.length!==3)return s("it is not a JWS of three parts");let d=le(o[0]),c=le(o[1]);if(!d||!c)return s("its header or claims are not base64url JSON");if(d.typ!=="dpop+jwt")return s("its typ is not dpop+jwt");if(d.alg!=="ES256")return s(`it is signed with ${String(d.alg)}; only ES256 is taken`);let a=d.jwk;if(!a||typeof a!="object"||a.kty!=="EC"||a.crv!=="P-256"||typeof a.x!="string"||typeof a.y!="string")return s("its header carries no P-256 public key");if("d"in a)return s("its header carries a private key");if(await Be(a.x,a.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:a.x,y:a.y,ext:!0},{name:"ECDSA",namedCurve:"P-256"},!1,["verify"])}catch{return s("its key is not a P-256 point")}let y=fe(o[2]);if(!y||!await crypto.subtle.verify({name:"ECDSA",hash:"SHA-256"},l,y,new TextEncoder().encode(`${o[0]}.${o[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 p=typeof c.htu=="string"?he(c.htu):void 0,g=he(t.url);if(!p||!g||p!==g)return s(`it is for ${String(c.htu)}, not ${g??t.url}`);let ve=r/1e3;if(typeof c.iat!="number"||Math.abs(c.iat-ve)>ue)return s("it was not made within a minute of now");let Se=j(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 Ee=j(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(c.jti)));return{jkt:e,jti:Ee,until:(c.iat+ue+Fe)*1e3+1}}var u=class extends Error{reason;constructor(e,t){super(t),this.name="TokenError",this.reason=e}},w=class extends Error{constructor(e,t){super(e,t),this.name="AuthUnavailable"}},He=new Set(["invalid_api_key","missing_api_key","secret_key_in_browser"]);function qe(n){return async e=>{let t=v({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 T&&r.status===401&&!He.has(r.code))return!1;throw new w("a session's standing could not be told",{cause:r})}}}var M={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}}},ye=60,ze=16*1024,Ve=10*6e4,Je=5e4,ge=n=>typeof n=="string"&&Object.hasOwn(M,n),K=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 E;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>ze)throw new u("malformed","the token is not a JWT");let r=e.split(".");if(r.length!==3)throw new u("malformed","the token is not a JWS of three parts");let s=me(r[0]),i=me(r[1]);if(!s||!i)throw new u("malformed","the token header or claims are not base64url JSON");let o=s.alg;if(!ge(o))throw new u("algorithm",`the token is signed with ${String(o)}; only ES256 and PS256 are taken`);let d=s.kid;if(typeof d!="string"||d==="")throw new u("malformed","the token header names no kid");let c=await this.key(d);if(!c)throw new u("unknown_key",`no key ${d} in the project's key set`);if(c.alg!==o)throw new u("algorithm",`key ${d} is ${c.alg}, the token says ${o}`);let a=be(r[2]);if(!a)throw new u("malformed","the signature is not base64url");let l=new TextEncoder().encode(`${r[0]}.${r[1]}`);if(!await crypto.subtle.verify(M[c.alg].verify,c.key,a,l).catch(()=>!1))throw new u("signature","the signature does not verify");let b=this.check(i),p=i.cnf,g;if(p!==void 0){if(!t)throw new u("bound","the token is bound to a key (DPoP): it comes with the DPoP scheme and a proof, not as a Bearer");if(typeof p!="object"||p===null||typeof p.jkt!="string"||p.jkt==="")throw new u("bound","the token is bound to a key it does not name (cnf.jkt)");g=await pe(e,p.jkt,t,this.now())}else if(t)throw new u("not_bound","the DPoP scheme came with a token bound to no key");if(!await this.stands(e,b.sessionId))throw new u("session_ended","the token's session has ended (signed out, revoked, or its user banned)");return g&&this.seenProofs.spend(g,this.now()),b}async verifyRequest(e){let t=e.headers instanceof Headers?e.headers:Ge(e.headers),r=t.get("authorization")??"";if(r==="")return null;let s=/^(bearer|dpop)\s+(\S+)$/i.exec(r);if(!s)throw new u("malformed","the Authorization header is not a Bearer or DPoP token");let i=s[1].toLowerCase()==="dpop",o=new URL(e.url,`http://${t.get("host")??"localhost"}`);return this.verify(s[2],i?{proof:t.get("dpop"),method:e.method,url:we(t,o)}:void 0)}async stands(e,t){let r=this.now(),s=this.standings.get(t);if(s&&r<s.until)return s.live;let i=this.asking.get(t);i||(i=this.standing(e,t).finally(()=>this.asking.delete(t)),this.asking.set(t,i));let o;try{o=await i}catch(c){let a=this.standings.get(t),l=this.now();if(a&&l<a.at+this.standingStaleMs)return a.until=Math.min(l+this.standingTtlMs,a.at+this.standingStaleMs),a.live;throw new w("a session's standing cannot be read now",{cause:c})}let d=this.now();return this.standings.delete(t),this.standings.set(t,{live:o,at:d,until:d+this.standingTtlMs}),this.standings.size>Je&&this.standings.delete(this.standings.keys().next().value),o}check(e){if(e.iss!==this.issuer)throw new u("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 u("audience","the token is not meant for this project");if(e.project_id!==this.projectId)throw new u("project","the token names another project");let r=this.now()/1e3;if(typeof e.exp!="number"||e.exp+ye<=r)throw new u("expired","the token has expired");if(e.nbf!==void 0&&(typeof e.nbf!="number"||e.nbf-ye>r))throw new u("not_yet_valid","the token is not valid yet");if(typeof e.sub!="string"||e.sub===""||typeof e.auth_time!="number")throw new u("not_a_user","the token is not a user's");if(typeof e.session_id!="string"||e.session_id==="")throw new u("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 u("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+Ve;if(this.lastFailure!==void 0&&t-this.lastFetch<this.refetchIntervalMs){if(!s)throw new w("the project's key set cannot be read now",{cause:this.lastFailure})}else try{await this.refresh()}catch(i){if(!s)throw i}}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(i){throw this.lastFailure=i,new w("the project's key set cannot be read now",{cause:i})}this.lastFailure=void 0;let r=new Map;for(let i of Array.isArray(e.keys)?e.keys:[]){let o=i.alg;if(typeof i.kid!="string"||!ge(o))continue;let d=M[o];if(i.kty!==d.kty||i.use!==void 0&&i.use!=="sig")continue;let{d:c,...a}=i;try{r.set(i.kid,{alg:o,key:await crypto.subtle.importKey("jwk",a,d.import,!1,["verify"])})}catch{}}this.keys=r;let s=Xe(t.headers.get("cache-control"))??this.maxKeyAgeMs;this.keysUntil=this.now()+Math.min(Math.max(s,this.refetchIntervalMs),this.maxKeyAgeMs)}};function we(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 Ye.test(s)?`${r}://${s}${e.pathname}`:""}var Ye=/^(?:[a-z0-9-]+(?:\.[a-z0-9-]+)*|\[[0-9a-f:.]+\])(?::[0-9]{1,5})?$/i;function Ge(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 Xe(n){let e=/(?:^|,)\s*max-age=(\d+)/i.exec(n??"");return e?Number(e[1])*1e3:void 0}function be(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 me(n){let e=be(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 Ze(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 _=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 Qe(n,e,t,r){let{idempotencyKey:s,amount:i,ttlSeconds:o,metadata:d}=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:i,...t.credits!==void 0?{credits:t.credits}:{limit:t.limit},...o!==void 0?{ttl_seconds:o}:{},...d!==void 0?{metadata:d}:{}},a=(await n.purchases.holdSpend({path:{customer_id:e},headers:{"Idempotency-Key":s},body:c})).data;if(a.status!=="held")throw new _(a);let l={customer_id:a.customer,spend_id:a.id},y;try{y=await r(a)}catch(b){throw await n.purchases.releaseSpend({path:l}).catch(()=>{}),b}return await n.purchases.commitSpend({path:l}),y}async function*et(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 tt=/^[A-Za-z_][A-Za-z0-9_]{0,127}$/,nt=/^(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 ke(n){return!tt.test(n)||nt.test(n)||/_PROXY$/i.test(n)}var rt=/^(PORT|PALBASE_(URL|PROJECT_ID|MACHINE|REPLICAS|SECRET_KEY|WEBHOOK_SECRET|PLATFORM_SECRET|CONTRACT_OUT|SECRETS|DB_[A-Z0-9_]+))$/;function st(n){return rt.test(n)}async function it(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 i=O({url:new URL(r).origin,secretKey:s,fetch:n.fetch}),{data:o}=await i.secrets.getEnvironmentValues({path:{environment:t}}),d=[],c=[],a=[];for(let[l,y]of Object.entries(o.values)){if(ke(l)){a.push(l);continue}if(e[l]!==void 0&&e[l]!==""){c.push(l);continue}e[l]=y,d.push(l)}return{set:t,loaded:d.sort(),kept:c.sort(),refused:a.sort()}}export{f as a,k as b,S as c,O as d,h as e,oe as f,ae as g,ce as h,Ue as i,u as j,w as k,qe as l,K as m,we as n,Ze as o,_ as p,Qe as q,et as r,ke as s,st as t,it as u};
@@ -1,5 +1,5 @@
1
- /*! palbase 0.29.0 — Palbase SDK License (see LICENSE) */
2
- import{e as Ze,g as et,h as tt}from"./IYJRPKS2.js";import{h as st}from"./AMWYOTRD.js";import{a as Qe}from"./IQ6QJDM4.js";import{r as ze,t as Xe,u as Ye}from"./WNEUGMU4.js";import{b as G,c as K,e as Ge,f as He,i as Pe,j as $,k as Be}from"./C2SU644S.js";import{a as Je,b as H}from"./62XTQSVZ.js";import{b as k,d as j}from"./KN6YJGWP.js";function Yt(r){let e=r,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 it(){let r=null;return{load:()=>r,save:e=>{r=e},clear:()=>{r=null},shared:!1}}function nt(r){let e=null,t=!0,s=()=>{try{return globalThis.localStorage}catch{return}};return{shared:!0,load(){try{let i=s()?.getItem(r);return i==null?t?null:e:JSON.parse(i)}catch{return e}},save(i){e=i;try{let n=s();if(!n)throw new Error("no storage");n.setItem(r,JSON.stringify(i)),t=!0}catch{t=!1}},clear(){e=null,t=!0;try{s()?.removeItem(r)}catch{}},watch(i){let n=globalThis;if(typeof n.addEventListener!="function")return()=>{};let o=a=>{(a.key===r||a.key===null)&&i()};return n.addEventListener("storage",o),()=>n.removeEventListener?.("storage",o)}}}function xe(r){try{let e=r.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 Qt=6e4,Zt=15e3;function es(r,e,t){let s=r?globalThis.navigator?.locks:void 0;return s?s.request(e,t):t()}var B=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??Zt,this.mode=i.refresh??"behind",this.loaded=Promise.resolve(e.load()).then(n=>{this.current=n}),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,n={accessToken:e.access_token,refreshToken:e.refresh_token,expiresAt:this.now()+e.expires_in*1e3,userId:s?.id??i?.userId??xe(e.access_token),user:s??i?.user};return this.current=n,await this.store.save(n),this.emit(t,n),n}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>Qt)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=es(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",Yt(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,n)=>{t=setTimeout(()=>n(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 Te=class{state="closed";refusal;logSeq;joinRef=null;listeners=new Map;closers=new Set;joiners=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)}onJoined(e){return this.joiners.add(e),()=>this.joiners.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)}`));if(e)for(let i of[...this.joiners])try{i()}catch{}}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{}}},z=class{ws=null;opening=null;ref=0;channels=new Map;lastJoin=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 Te(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");this.lastJoin.clear()}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",{}),this.lastJoin.get(e.name)===e&&this.lastJoin.delete(e.name)),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 n=this.nextRef(),o=JSON.stringify([e.joinRef,n,e.topic,t,s]),a=this.awaitReply(n);return i.send(o),a}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,n)=>{let o=new e(t);this.ws=o,o.onopen=()=>{this.attempts=0,this.startHeartbeat(),i()},o.onmessage=a=>this.receive(String(a.data)),o.onerror=()=>n(new Error("the realtime socket could not be opened")),o.onclose=()=>this.dropped(o)});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(n=>n.state==="joining");this.open().then(()=>Promise.all(i.map(n=>this.sendJoin(n)))).catch(()=>{})},s))}async sendJoin(e){let t=await this.opts.accessToken();if(this.channels.get(e.name)!==e||e.state!=="joining")return;let s=this.nextRef();e.joinRef=s;let i=this.awaitReply(s),n={broadcast:{self:!1}};e.logSeq!==void 0&&(n.log={after:e.logSeq}),this.lastJoin.set(e.name,e),this.push(s,e.topic,"phx_join",{access_token:t,config:n},s);let{status:o,response:a}=await i;if(this.channels.get(e.name)!==e||e.state!=="joining"){this.lastJoin.get(e.name)===e&&(this.lastJoin.delete(e.name),o==="ok"&&this.ws?.readyState===1&&this.push(s,e.topic,"phx_leave",{}));return}e.settled(o==="ok",a)}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,n)=>{clearTimeout(s),this.replies.delete(e),t({status:i,response:n})})})}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,n,o]=t,a=typeof o=="object"&&o!==null?o:{};if(n==="phx_reply"&&typeof s=="string"){if(s===this.heartbeatRef){this.heartbeatRef=null;return}this.replies.get(s)?.(String(a.status),a.response??{});return}let d=[...this.channels.values()].find(l=>l.topic===i);if(d){if(n==="phx_close"){d.state="closed";return}if(n==="phx_error"){d.state="joining",J(setTimeout(()=>this.channels.get(d.name)===d&&d.state==="joining"&&this.ws?.readyState===1&&void this.sendJoin(d),1e3));return}d.deliver(n,a)}}push(e,t,s,i,n=this.nextRef()){this.ws?.send(JSON.stringify([e,n,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(r){return r.unref?.(),r}var E="X-Palbase-Installation-Secret",Y="X-Palbase-Installation",at=new WeakMap;function O(r){return at.get(r)}var ot=new WeakSet;function dt(r){return ot.has(r)}var ts=/^[A-Za-z0-9_-]{43}$/,X=class{id;constructor(e){let t=`palbase.installation.secret.${e}`,s;try{let i=rt()?.getItem(t);i&&ts.test(i)&&(s=i)}catch{}if(!s){ot.add(this),s=lt(crypto.getRandomValues(new Uint8Array(32)));try{rt()?.setItem(t,s)}catch{}}at.set(this,s),this.id=ss(s)}};function ss(r){return lt(ns(new TextEncoder().encode(r)).subarray(0,16))}function rt(){try{return globalThis.localStorage}catch{return}}function lt(r){let e="";for(let t of r)e+=String.fromCharCode(t);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}var is=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]),R=(r,e)=>r>>>e|r<<32-e;function ns(r){let e=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),t=new Uint8Array(Math.ceil((r.length+9)/64)*64);t.set(r),t[r.length]=128;let s=new DataView(t.buffer);s.setUint32(t.length-8,Math.floor(r.length/536870912)),s.setUint32(t.length-4,r.length*8>>>0);let i=new Uint32Array(64);for(let a=0;a<t.length;a+=64){for(let p=0;p<16;p++)i[p]=s.getUint32(a+p*4);for(let p=16;p<64;p++){let y=R(i[p-15],7)^R(i[p-15],18)^i[p-15]>>>3,P=R(i[p-2],17)^R(i[p-2],19)^i[p-2]>>>10;i[p]=i[p-16]+y+i[p-7]+P|0}let[d,l,c,f,g,S,m,h]=e;for(let p=0;p<64;p++){let y=h+(R(g,6)^R(g,11)^R(g,25))+(g&S^~g&m)+is[p]+i[p]|0,P=(R(d,2)^R(d,13)^R(d,22))+(d&l^d&c^l&c)|0;h=m,m=S,S=g,g=f+y|0,f=c,c=l,l=d,d=y+P|0}e[0]+=d,e[1]+=l,e[2]+=c,e[3]+=f,e[4]+=g,e[5]+=S,e[6]+=m,e[7]+=h}let n=new Uint8Array(32),o=new DataView(n.buffer);for(let a=0;a<8;a++)o.setUint32(a*4,e[a]);return n}var as=30*6e4,ct=1e3,os=100,ds=60*1024,Q=()=>globalThis.crypto?.randomUUID?globalThis.crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;function U(){try{return globalThis.localStorage}catch{return}}var ee=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,n,o,a={}){this.session=s,this.consent=i;let d={send:c=>e.send(this.granted("analytics")?{...c,headers:{...c.headers,[Y]:n.id}}:c)};this.api=G.client(d);let l={send:c=>(this.granted("analytics")?e:t).send(c)};this.perfApi=G.client(l),this.closingApi=G.client({send:c=>d.send({...c,keepalive:!0})}),this.closingPerfApi=G.client({send:c=>l.send({...c,keepalive:!0})}),this.flushMs=a.flushMs??5e3,this.flushAt=a.flushAt??20,this.now=a.now??Date.now,this.anonKey=`palbase.analytics.anonymous.${o}`,this.sessionKey=`palbase.analytics.session.${o}`,this.onceKey=`palbase.analytics.once.${o}`,s.onChange(c=>{c==="SIGNED_IN"?(this.identifyPending=!0,this.soon()):c==="SIGNED_OUT"&&(this.identifyPending=!1,this.reset())}),i.onChange((c,f)=>{f!=="granted"&&(c==="analytics"?(this.events=[],this.identifyPending=!1,this.samples=this.samples.map(Ce),this.reset()):c==="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()),n=this.readOnce(),o=n?.session===i?n.keys:[];o.includes(e)||(this.writeOnce({session:i,keys:[...o,e].slice(-500)}),this.capture(t,s))}readOnce(){try{let e=U()?.getItem(this.onceKey);if(e)return JSON.parse(e)}catch{}return this.memoryOnce}writeOnce(e){this.memoryOnce=e;try{U()?.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}${V(t.pathname)}`:"");if(!i)return;let n=e.referrer??fs(s?.referrer);this.capture("$pageview",{...e.properties,url:i,...e.title??s?.title?{title:e.title??s?.title}:{},...n?{referrer:n}:{}})}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{U()?.removeItem(this.anonKey),U()?.removeItem(this.sessionKey),U()?.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(Ce)):this.samples=[];let t=e?this.closingApi:this.api,s=e?this.closingPerfApi:this.perfApi,i=this.now(),n=this.session.snapshot()?.userId;for(this.identifyPending&&n&&this.granted("analytics")&&(this.identifyPending=!1,await this.sendIdentify(t,n));this.events.length>0;){let o=this.take(this.events,e);try{await t.batch({body:{events:o.map(a=>({...a,sent_at:i}))}})}catch{}}for(;this.samples.length>0;){let o=this.take(this.samples,e);try{await s.sendPerf({body:{items:o}})}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(hs((o,a)=>this.sample("web_vital",o,a))),e.network!==!1&&s.push(this.watchFetch(t));let i=()=>{document.visibilityState==="hidden"&&this.flush(!0)},n=()=>{this.flush(!0)};return document.addEventListener("visibilitychange",i),t.addEventListener("pagehide",n),s.push(()=>{document.removeEventListener("visibilitychange",i),t.removeEventListener("pagehide",n)}),this.stopAuto=()=>{for(let o of s.splice(0))o();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>=ct&&this.events.shift(),this.events.push(e),this.soon()}sample(e,t,s,i={}){if(!this.granted("performance"))return;this.samples.length>=ct&&this.samples.shift();let n={row_id:Q(),trace_type:e,name:t,value:Math.max(0,s),timestamp:this.now(),...i};this.samples.push(this.granted("analytics")?{...n,distinct_id:this.distinctId()}:Ce(n)),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,os);if(!t)return s;for(;s.length>1&&JSON.stringify(s).length>ds;)e.unshift(s.pop());return s}distinctId(){return this.session.snapshot()?.userId??this.anonymousId()}anonymousId(){let e=U();try{let t=e?.getItem(this.anonKey);if(t)return t;let s=`anon_${Q()}`;if(e?.setItem(this.anonKey,s),e?.getItem(this.anonKey)===s)return s}catch{}return this.memoryAnon??=`anon_${Q()}`,this.memoryAnon}sessionId(e){let t=U(),s=this.memorySession;try{let n=t?.getItem(this.sessionKey);n&&(s=JSON.parse(n))}catch{}let i=s&&e-s.last<as?{id:s.id,last:e}:{id:`ses_${Q()}`,last:e};this.memorySession=i;try{t?.setItem(this.sessionKey,JSON.stringify(i))}catch{}return i.id}watchPages(e){let t="",s=()=>{let a=`${e.location.origin}${e.location.pathname}`;if(a===t)return;t=a;let d=`${e.location.origin}${V(e.location.pathname)}`;setTimeout(()=>this.page({url:d}),0)},i=e.history,n=i.pushState.bind(i),o=i.replaceState.bind(i);return i.pushState=(...a)=>{n(...a),s()},i.replaceState=(...a)=>{o(...a),s()},e.addEventListener("popstate",s),s(),()=>{i.pushState=n,i.replaceState=o,e.removeEventListener("popstate",s)}}watchFetch(e){let t=e.fetch;if(typeof t!="function")return()=>{};let s=async(i,n)=>{let o=performance.now(),a=i instanceof Request?i:void 0,d=(n?.method??a?.method??"GET").toUpperCase(),l;try{l=new URL(a?.url??String(i),e.location.href)}catch{l=void 0}let c=!!l&&l.pathname.startsWith("/analytics/")||us(n?.headers??a?.headers);try{let f=await t(i,n);return l&&!c&&this.sample("network",`${d} ${l.origin}${V(l.pathname)}`,performance.now()-o,{attrs:{status:String(f.status)},...f.headers.get("x-request-id")?{request_id:f.headers.get("x-request-id")}:{}}),f}catch(f){throw l&&!c&&this.sample("network",`${d} ${l.origin}${V(l.pathname)}`,performance.now()-o,{attrs:{status:"0"}}),f}};return e.fetch=s,()=>{e.fetch===s&&(e.fetch=t)}}};function Ce(r){let{distinct_id:e,request_id:t,...s}=r;return s}var ls=r=>r.entryType==="layout-shift"&&"value"in r&&"hadRecentInput"in r,cs=r=>r.entryType==="event"||r.entryType==="first-input";function Z(r,e){if(!(typeof PerformanceObserver>"u"))try{let t=new PerformanceObserver(s=>e(s.getEntries()));return t.observe({type:r,buffered:!0}),t}catch{return}}function hs(r){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 c of l)e=Math.max(e,c.startTime)}),Z("layout-shift",l=>{for(let c of l)ls(c)&&!c.hadRecentInput&&(t+=c.value)}),Z("event",l=>{for(let c of l)cs(c)&&(s=Math.max(s,c.duration))}),Z("paint",l=>{for(let c of l)c.name==="first-contentful-paint"&&r("FCP",c.startTime)})],n=performance.getEntriesByType("navigation")[0];n&&n.responseStart>0&&r("TTFB",n.responseStart);let o=!1,a=()=>{o||(o=!0,e>0&&r("LCP",e),r("CLS",t),s>0&&r("INP",s))},d=()=>{document.visibilityState==="hidden"&&a()};return document.addEventListener("visibilitychange",d),()=>{a(),document.removeEventListener("visibilitychange",d);for(let l of i)l?.disconnect()}}function us(r){if(!r)return!1;try{return new Headers(r).has("next-router-prefetch")}catch{return!1}}var ps=/^[a-z][a-z0-9_-]{0,31}$/;function V(r){return r.split("/").map(e=>{if(e==="")return e;let t=e.split(";",1)[0],s=t.toLowerCase();return ps.test(s)&&(s.match(/\d/g)?.length??0)<=2&&t.slice(1)===s.slice(1)&&s.split(/[-_]/).every(n=>n.length<=16)?s:":id"}).join("/")}function fs(r){if(!r)return"";try{let e=new URL(r);return`${e.origin}${V(e.pathname)}`}catch{return V(r.split(/[?#]/,1)[0]??"")}}var kt=/^custom\.[a-z0-9_]{1,48}$/,gs=/^[a-z][a-z0-9_]{0,63}$/,ht=r=>gs.test(r)||kt.test(r),ms=50,ut=[5e3,3e4,12e4,6e5],vs=100,se=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[d,l]of Object.entries(t.start??{})){if(!ht(d))throw new TypeError(`consent.start: ${JSON.stringify(d)} is not a consent key (a platform key, or custom.<name>)`);if(l!=="granted"&&l!=="denied")throw new TypeError(`consent.start.${d} is granted or denied`)}for(let d of t.customKeys??[])if(!kt.test(d))throw new TypeError(`consent.customKeys: ${JSON.stringify(d)} 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=()=>dt(this.installation)?{}:{unknown:{on:!0,w:this.stamp()}},n={whose:null,install:this.installation.id,choices:{},unsent:[]};typeof s!="object"?this.kept={...n,...s==="unreadable"?{unknown:{on:!0,w:this.stamp()}}:i()}:s.whose==null&&s.install!==void 0&&s.install!==this.installation.id?this.kept={...n,unsent:s.unsent.filter(d=>d.user!==null),...s.keys?{keys:s.keys}:{},...i()}:this.kept=s,e.session.onChange((d,l)=>{this.engaged&&(d==="SIGNED_IN"&&l?this.signedIn(l):(d==="SIGNED_OUT"||d==="SESSION_EXPIRED")&&this.signedOut())});let o=globalThis;typeof o.addEventListener=="function"&&(o.addEventListener("storage",d=>{(d.key===this.storeKey||d.key===null)&&this.reload()}),o.addEventListener("online",()=>{this.engaged&&this.send()}));let a=this.kept;(e.options!==void 0||s!=="empty"&&(a.unknown?.on||a.unsent.length>0||a.link!==void 0||Object.keys(a.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(x(this.kept)!==this.holder()||this.gpcRefuses(e))return"denied";let t=gt(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||x(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[o,a]of t){if(!ht(o))throw new TypeError(`${JSON.stringify(o)} is not a consent key (a platform key, or custom.<name>)`);if(a!=="granted"&&a!=="denied")throw new TypeError(`${o}: a choice is granted or denied`)}if(t.length===0)return;this.engage();let s=this.chosenAt(),i=this.session.snapshot()?.userId??null,n=this.states();for(let[o,a]of t)this.queue({key:o,state:a,source:"app",chosen_at:s,user:i,...this.textVersion!==void 0?{text_version:this.textVersion}:{}});this.commit(n),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(d=>d.key),i=await this.platform().catch(()=>this.kept.keys??[]),n=new Set(i.filter(d=>d.ads).map(d=>d.key)),o=this.kept.region?.jurisdiction==="us",a=new Date(this.now());return a.setUTCMonth(a.getUTCMonth()-12),s.filter(d=>{let l=this.kept.choices[d];return o&&n.has(d)&&l?.last_denied_at!==void 0&&Date.parse(l.last_denied_at)>a.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{[E]: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(),n={};for(let h of e.choices)n[h.key]={state:h.state,source:h.source,chosen_at:h.chosen_at,...h.text_version!==void 0?{text_version:h.text_version}:{},...h.last_denied_at!==void 0?{last_denied_at:h.last_denied_at}:{}};let o=s.filter(h=>n[h.key]?.state!==h.state||Date.parse(n[h.key]?.chosen_at??"")!==Date.parse(h.chosen_at)).map(h=>A(h.key,h)),d=x(this.kept)===(t===null?`device:${this.installation.id}`:`user:${t}`)?Object.entries(this.kept.choices).filter(([,h])=>h.provisional).map(([h,p])=>A(h,p)):[];if(o.length+d.length>0&&(this.kept={...this.kept,void:D([...this.kept.void??[],...o,...d])}),t===null&&this.kept.resetAt!==void 0)for(let[h,p]of Object.entries(n))Date.parse(p.chosen_at)<this.kept.resetAt&&delete n[h];let l=new Set(Object.entries(n).map(([h,p])=>A(h,p))),c=(this.kept.void??[]).filter(h=>l.has(h));c.length>0&&(this.kept={...this.kept,unvoid:D([...this.kept.unvoid??[],...c])});let f=St(this.kept),g;if(x(this.kept)!==(t===null?`device:${this.installation.id}`:`user:${t}`))g=n;else{g={};for(let h of[...new Set([...Object.keys(this.kept.choices),...Object.keys(n)])].sort()){let p=this.kept.choices[h],y=p&&!p.provisional&&!f.has(A(h,p))?p:void 0,P=n[h],I=P&&(!y||Date.parse(P.chosen_at)>=Date.parse(y.chosen_at))?P:y;I&&(g[h]=I)}}for(let h of this.kept.unsent){if(h.user!==null&&h.user!==t||h.user===null&&h.device!==void 0&&h.device!==this.installation.id||h.user===null&&t!==null)continue;let p=g[h.key];p&&Date.parse(p.chosen_at)>Date.parse(h.chosen_at)||(g[h.key]=pt(h,p))}let{install:S,...m}=this.kept;this.kept={...m,whose:t,...t===null?{install:this.installation.id}:{},choices:g,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&&x(this.kept)===(t===null?`device:${this.installation.id}`:`user:${t}`),n=D([...this.kept.void??[],...s.map(d=>A(d.key,d))]);if(!i){this.kept={...this.kept,void:n},this.commit();return}let o=this.states(),a={...this.kept.choices};for(let d of s){if(this.kept.unsent.some(c=>c.key===d.key&&(c.user===null||c.user===e)&&Date.parse(c.chosen_at)>Date.parse(d.chosen_at)))continue;let l=a[d.key];a[d.key]={state:"denied",source:"app",chosen_at:d.chosen_at,...l?.last_denied_at!==void 0?{last_denied_at:l.last_denied_at}:{},provisional:!0}}this.kept={...this.kept,choices:a,void:n},this.commit(o);try{await this.read(e)}catch{this.stale=!0}}queue(e){let t=e.user===null?{...e,device:this.installation.id}:e,s=x(this.kept)===(t.user===null?`device:${this.installation.id}`:`user:${t.user}`);this.kept={...this.kept,unsent:_t([...this.kept.unsent,t]),...s?{choices:{...this.kept.choices,[t.key]:pt(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=this.session.snapshot()?.userId??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(!yt(i))throw i}if(this.kept.link===e){let{link:i,...n}=this.kept;this.kept=n,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{return(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 n=i[0],o=e===null?this.deviceApi:this.userApi(e),a;try{a=(await o.chooseConsents({headers:this.secret(),body:{installation_id:this.installation.id,...n.source==="gpc"?{source:"gpc"}:{},...n.text_version!==void 0?{text_version:n.text_version}:{},choices:i.map(d=>({key:d.key,state:d.state,chosen_at:d.chosen_at}))}})).data}catch(d){if(!yt(d))throw d;if(i.length>1){this.kept={...this.kept,unsent:this.kept.unsent.map(l=>i.some(c=>vt(c,l))?{...l,alone:!0}:l)},this.commit();continue}}this.kept={...this.kept,unsent:this.kept.unsent.filter(d=>!i.some(l=>vt(l,d))),done:D([...this.kept.done??[],...i.map(ie)])},this.commit(),a?(s=!0,e===t&&this.adopt(a,e,i)):await this.refused(t,e,i)}}nextGroup(e){let t=this.kept.unsent.filter(o=>o.user===e&&(e!==null||(o.device??this.installation.id)===this.installation.id)),s=t[0];if(!s)return[];let i=[],n=new Set;if(s.alone)return[s];for(let o of t)if(!n.has(o.key)&&(n.add(o.key),!(o.alone||o.source!==s.source||o.text_version!==s.text_version)&&(i.push(o),i.length===ms)))break;return i}retryLater(){if(this.retryTimer)return;let e=ut[Math.min(this.retries,ut.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(([,a])=>a.state!=="unset").map(([a])=>a),...this.kept.unsent.filter(a=>a.user===null&&(a.device??this.installation.id)===this.installation.id).map(a=>a.key),...Object.keys(this.start),...this.customKeys,...(this.kept.keys??[]).map(a=>a.key)]),i={};for(let[a,d]of Object.entries(this.kept.choices))i[a]={state:"unset",source:"app",chosen_at:t,...d.last_denied_at!==void 0?{last_denied_at:d.last_denied_at}:{}};let n=a=>a.user===null&&(a.device??this.installation.id)===this.installation.id,o=this.kept.unsent.filter(n);this.kept={whose:null,install:this.installation.id,resetAt:Date.parse(t),choices:i,unsent:this.kept.unsent.filter(a=>!n(a)),...this.kept.void?{void:this.kept.void}:{},...this.kept.unvoid?{unvoid:this.kept.unvoid}:{},done:D([...this.kept.done??[],...o.map(ie)]),...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 a of s)this.queue({key:a,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",n=>{n.event==="changed"&&this.changed(s,Me(n.payload))}),t.on("state_snapshot",n=>this.held(s,Me(bt(n.entries)))),t.on("state_diff",n=>this.held(s,Me(bt(n.set))))];s.off=()=>i.forEach(n=>n()),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(n=>n.key===e&&n.ads))return!1;let t=gt(this.kept,e);if(t?.state==="denied")return!1;let s=this.kept.gpc?.[x(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||x(this.kept)!==this.holder())return;let e;try{e=await this.platform()}catch{return}if(x(this.kept)!==this.holder())return;let t=this.session.snapshot()?.userId??null,s=e.filter(o=>o.ads&&this.gpcRefuses(o.key)&&!this.kept.unsent.some(a=>a.key===o.key&&a.source==="gpc"&&a.user===t));if(s.length===0)return;let i=this.chosenAt(),n=this.states();for(let o of s)this.queue({key:o.key,state:"denied",source:"gpc",chosen_at:i,user:t});this.kept={...this.kept,gpc:{...this.kept.gpc,[x(this.kept)]:Date.parse(i)}},this.commit(n),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 n of[...this.listeners])try{n(s,i)}catch{}}}load(){let e;try{e=wt()?.getItem(this.storeKey)}catch{return"unreadable"}if(e==null)return"empty";try{let t=JSON.parse(e);if(ks(t))return t}catch{}return"unreadable"}reload(){let e=this.load();if(typeof e!="object"){this.write();return}let t=this.states();this.kept=ft(e,this.kept,"theirs",this.holder()),x(e)===x(this.kept)&&mt(this.kept)!==mt(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=ft(t,this.kept,"ours",this.holder())),this.write(),this.tell(e)}write(){try{wt()?.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 pt(r,e){let t=r.state==="denied"?r.chosen_at:e?.last_denied_at;return{state:r.state,source:r.source,chosen_at:r.chosen_at,...r.text_version!==void 0?{text_version:r.text_version}:{},...t!==void 0?{last_denied_at:t}:{}}}function A(r,e){return`${r}|${e.provisional?"provisional":e.state}|${Date.parse(e.chosen_at)}`}function St(r){let e=new Set(r.unvoid??[]);return new Set((r.void??[]).filter(t=>!e.has(t)))}var te={denied:2,unset:1,granted:0};function ys(r,e,t,s){let i=e&&!s.has(A(r,e))?e:void 0,n=t&&!s.has(A(r,t))?t:void 0;if(!i||!n)return i??n;let o=Date.parse(i.chosen_at),a=Date.parse(n.chosen_at);return o!==a?o>a?i:n:te[i.state]!==te[n.state]?te[i.state]>te[n.state]?i:n:i.provisional?n:i}function ws(r,e){return!r||!e?r??e:e.w>r.w||e.w===r.w&&e.on?e:r}function ft(r,e,t,s){let i=D([...r.void??[],...e.void??[]]),n=D([...r.unvoid??[],...e.unvoid??[]]),o=St({void:i,unvoid:n}),a={},d,l={...r.gpc};for(let[y,P]of Object.entries(e.gpc??{}))l[y]=Math.max(l[y]??0,P);let c;if(x(r)===x(e)){d=e;for(let y of[...new Set([...Object.keys(r.choices),...Object.keys(e.choices)])].sort()){let P=ys(y,r.choices[y],e.choices[y],o);P&&(a[y]=P)}c=ws(r.unknown,e.unknown)}else{d=x(e)===s?e:x(r)===s?r:t==="ours"?e:r;for(let[y,P]of Object.entries(d.choices))o.has(A(y,P))||(a[y]=P);c=d.unknown}let f=D([...r.done??[],...e.done??[]]),g=_t([...r.unsent,...e.unsent]).filter(y=>!f.includes(ie(y))),S=t==="ours"?e:r,m=t==="ours"?r:e,h=S.region??m.region,p=S.keys??m.keys;return{whose:d.whose??null,...d.whose==null&&d.install!==void 0?{install:d.install}:{},...d.whose==null&&(r.resetAt!==void 0||e.resetAt!==void 0)&&x(r)===x(e)?{resetAt:Math.max(r.resetAt??0,e.resetAt??0)}:d.whose==null&&d.resetAt!==void 0?{resetAt:d.resetAt}:{},choices:a,unsent:g,...f.length>0?{done:f}:{},...i.length>0?{void:i}:{},...n.length>0?{unvoid:n}:{},...S.link!==void 0?{link:S.link}:{},...h?{region:h}:{},...Object.keys(l).length>0?{gpc:l}:{},...p?{keys:p}:{},...c?{unknown:c}:{}}}function ie(r){return`${r.user??`device:${r.device??""}`}|${r.key}|${r.state}|${r.source}|${r.chosen_at}`}function gt(r,e){let t=r.choices[e];if(!t||r.whose!=null||r.resetAt===void 0||Date.parse(t.chosen_at)>=r.resetAt)return t}function x(r){return r.whose!=null?`user:${r.whose}`:`device:${r.install??""}`}function D(r){return[...new Set(r)].slice(-vs)}function mt(r){return JSON.stringify(r,(e,t)=>typeof t=="object"&&t!==null&&!Array.isArray(t)?Object.fromEntries(Object.entries(t).sort(([s],[i])=>s.localeCompare(i))):t)}function _t(r){let e=new Map;for(let t of r){let s=ie(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 bs=new Set(["granted","denied","unset"]);function ks(r){if(typeof r!="object"||r===null)return!1;let e=r;if(typeof e.choices!="object"||e.choices===null||Array.isArray(e.choices)||!Array.isArray(e.unsent))return!1;let t=(a,d)=>{if(typeof a!="object"||a===null)return!1;let l=a;return bs.has(l.state)&&typeof l.chosen_at=="string"&&(!d||typeof l.key=="string")},s=a=>a===void 0||typeof a=="object"&&a!==null&&typeof a.on=="boolean"&&typeof a.w=="number",i=r,n=a=>a===void 0||Array.isArray(a)&&a.every(d=>typeof d=="string"),o=i.whose===void 0||i.whose===null||typeof i.whose=="string";return Object.values(e.choices).every(a=>t(a,!1))&&e.unsent.every(a=>t(a,!0))&&(i.gpc===void 0||typeof i.gpc=="object"&&i.gpc!==null&&Object.values(i.gpc).every(a=>typeof a=="number"))&&s(i.unknown)&&n(i.done)&&n(i.void)&&n(i.unvoid)&&o}function vt(r,e){return r.key===e.key&&r.user===e.user&&r.state===e.state&&r.source===e.source&&r.chosen_at===e.chosen_at}function yt(r){return r instanceof k&&r.status>=400&&r.status<500&&r.status!==401&&r.status!==408&&r.status!==429}function wt(){try{return globalThis.localStorage}catch{return}}function bt(r){let e=typeof r=="object"&&r!==null?r.version:void 0;return typeof e=="object"&&e!==null?e.v:void 0}function Me(r){let e=typeof r=="object"&&r!==null?r.version:void 0;return typeof e=="number"&&Number.isFinite(e)?e:void 0}var Ss=`
1
+ /*! palbase 0.30.0 — Palbase SDK License (see LICENSE) */
2
+ import{e as Ze,g as et,h as tt}from"./DTMKEMIF.js";import{h as st}from"./5KRLND5G.js";import{a as Qe}from"./PN5NJVJ6.js";import{r as ze,t as Xe,u as Ye}from"./RYYYVFUC.js";import{b as G,c as K,e as Ge,f as He,i as Pe,j as $,k as Be}from"./5CGZD6ER.js";import{a as Je,b as H}from"./2HCODUCC.js";import{b as k,d as j}from"./AU2V6M6Q.js";function Yt(r){let e=r,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 it(){let r=null;return{load:()=>r,save:e=>{r=e},clear:()=>{r=null},shared:!1}}function nt(r){let e=null,t=!0,s=()=>{try{return globalThis.localStorage}catch{return}};return{shared:!0,load(){try{let i=s()?.getItem(r);return i==null?t?null:e:JSON.parse(i)}catch{return e}},save(i){e=i;try{let n=s();if(!n)throw new Error("no storage");n.setItem(r,JSON.stringify(i)),t=!0}catch{t=!1}},clear(){e=null,t=!0;try{s()?.removeItem(r)}catch{}},watch(i){let n=globalThis;if(typeof n.addEventListener!="function")return()=>{};let o=a=>{(a.key===r||a.key===null)&&i()};return n.addEventListener("storage",o),()=>n.removeEventListener?.("storage",o)}}}function xe(r){try{let e=r.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 Qt=6e4,Zt=15e3;function es(r,e,t){let s=r?globalThis.navigator?.locks:void 0;return s?s.request(e,t):t()}var B=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??Zt,this.mode=i.refresh??"behind",this.loaded=Promise.resolve(e.load()).then(n=>{this.current=n}),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,n={accessToken:e.access_token,refreshToken:e.refresh_token,expiresAt:this.now()+e.expires_in*1e3,userId:s?.id??i?.userId??xe(e.access_token),user:s??i?.user};return this.current=n,await this.store.save(n),this.emit(t,n),n}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>Qt)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=es(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",Yt(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,n)=>{t=setTimeout(()=>n(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 Te=class{state="closed";refusal;logSeq;joinRef=null;listeners=new Map;closers=new Set;joiners=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)}onJoined(e){return this.joiners.add(e),()=>this.joiners.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)}`));if(e)for(let i of[...this.joiners])try{i()}catch{}}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{}}},z=class{ws=null;opening=null;ref=0;channels=new Map;lastJoin=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 Te(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");this.lastJoin.clear()}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",{}),this.lastJoin.get(e.name)===e&&this.lastJoin.delete(e.name)),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 n=this.nextRef(),o=JSON.stringify([e.joinRef,n,e.topic,t,s]),a=this.awaitReply(n);return i.send(o),a}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,n)=>{let o=new e(t);this.ws=o,o.onopen=()=>{this.attempts=0,this.startHeartbeat(),i()},o.onmessage=a=>this.receive(String(a.data)),o.onerror=()=>n(new Error("the realtime socket could not be opened")),o.onclose=()=>this.dropped(o)});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(n=>n.state==="joining");this.open().then(()=>Promise.all(i.map(n=>this.sendJoin(n)))).catch(()=>{})},s))}async sendJoin(e){let t=await this.opts.accessToken();if(this.channels.get(e.name)!==e||e.state!=="joining")return;let s=this.nextRef();e.joinRef=s;let i=this.awaitReply(s),n={broadcast:{self:!1}};e.logSeq!==void 0&&(n.log={after:e.logSeq}),this.lastJoin.set(e.name,e),this.push(s,e.topic,"phx_join",{access_token:t,config:n},s);let{status:o,response:a}=await i;if(this.channels.get(e.name)!==e||e.state!=="joining"){this.lastJoin.get(e.name)===e&&(this.lastJoin.delete(e.name),o==="ok"&&this.ws?.readyState===1&&this.push(s,e.topic,"phx_leave",{}));return}e.settled(o==="ok",a)}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,n)=>{clearTimeout(s),this.replies.delete(e),t({status:i,response:n})})})}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,n,o]=t,a=typeof o=="object"&&o!==null?o:{};if(n==="phx_reply"&&typeof s=="string"){if(s===this.heartbeatRef){this.heartbeatRef=null;return}this.replies.get(s)?.(String(a.status),a.response??{});return}let d=[...this.channels.values()].find(l=>l.topic===i);if(d){if(n==="phx_close"){d.state="closed";return}if(n==="phx_error"){d.state="joining",J(setTimeout(()=>this.channels.get(d.name)===d&&d.state==="joining"&&this.ws?.readyState===1&&void this.sendJoin(d),1e3));return}d.deliver(n,a)}}push(e,t,s,i,n=this.nextRef()){this.ws?.send(JSON.stringify([e,n,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(r){return r.unref?.(),r}var E="X-Palbase-Installation-Secret",Y="X-Palbase-Installation",at=new WeakMap;function O(r){return at.get(r)}var ot=new WeakSet;function dt(r){return ot.has(r)}var ts=/^[A-Za-z0-9_-]{43}$/,X=class{id;constructor(e){let t=`palbase.installation.secret.${e}`,s;try{let i=rt()?.getItem(t);i&&ts.test(i)&&(s=i)}catch{}if(!s){ot.add(this),s=lt(crypto.getRandomValues(new Uint8Array(32)));try{rt()?.setItem(t,s)}catch{}}at.set(this,s),this.id=ss(s)}};function ss(r){return lt(ns(new TextEncoder().encode(r)).subarray(0,16))}function rt(){try{return globalThis.localStorage}catch{return}}function lt(r){let e="";for(let t of r)e+=String.fromCharCode(t);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}var is=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]),R=(r,e)=>r>>>e|r<<32-e;function ns(r){let e=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),t=new Uint8Array(Math.ceil((r.length+9)/64)*64);t.set(r),t[r.length]=128;let s=new DataView(t.buffer);s.setUint32(t.length-8,Math.floor(r.length/536870912)),s.setUint32(t.length-4,r.length*8>>>0);let i=new Uint32Array(64);for(let a=0;a<t.length;a+=64){for(let p=0;p<16;p++)i[p]=s.getUint32(a+p*4);for(let p=16;p<64;p++){let y=R(i[p-15],7)^R(i[p-15],18)^i[p-15]>>>3,P=R(i[p-2],17)^R(i[p-2],19)^i[p-2]>>>10;i[p]=i[p-16]+y+i[p-7]+P|0}let[d,l,c,f,g,S,m,h]=e;for(let p=0;p<64;p++){let y=h+(R(g,6)^R(g,11)^R(g,25))+(g&S^~g&m)+is[p]+i[p]|0,P=(R(d,2)^R(d,13)^R(d,22))+(d&l^d&c^l&c)|0;h=m,m=S,S=g,g=f+y|0,f=c,c=l,l=d,d=y+P|0}e[0]+=d,e[1]+=l,e[2]+=c,e[3]+=f,e[4]+=g,e[5]+=S,e[6]+=m,e[7]+=h}let n=new Uint8Array(32),o=new DataView(n.buffer);for(let a=0;a<8;a++)o.setUint32(a*4,e[a]);return n}var as=30*6e4,ct=1e3,os=100,ds=60*1024,Q=()=>globalThis.crypto?.randomUUID?globalThis.crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;function U(){try{return globalThis.localStorage}catch{return}}var ee=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,n,o,a={}){this.session=s,this.consent=i;let d={send:c=>e.send(this.granted("analytics")?{...c,headers:{...c.headers,[Y]:n.id}}:c)};this.api=G.client(d);let l={send:c=>(this.granted("analytics")?e:t).send(c)};this.perfApi=G.client(l),this.closingApi=G.client({send:c=>d.send({...c,keepalive:!0})}),this.closingPerfApi=G.client({send:c=>l.send({...c,keepalive:!0})}),this.flushMs=a.flushMs??5e3,this.flushAt=a.flushAt??20,this.now=a.now??Date.now,this.anonKey=`palbase.analytics.anonymous.${o}`,this.sessionKey=`palbase.analytics.session.${o}`,this.onceKey=`palbase.analytics.once.${o}`,s.onChange(c=>{c==="SIGNED_IN"?(this.identifyPending=!0,this.soon()):c==="SIGNED_OUT"&&(this.identifyPending=!1,this.reset())}),i.onChange((c,f)=>{f!=="granted"&&(c==="analytics"?(this.events=[],this.identifyPending=!1,this.samples=this.samples.map(Ce),this.reset()):c==="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()),n=this.readOnce(),o=n?.session===i?n.keys:[];o.includes(e)||(this.writeOnce({session:i,keys:[...o,e].slice(-500)}),this.capture(t,s))}readOnce(){try{let e=U()?.getItem(this.onceKey);if(e)return JSON.parse(e)}catch{}return this.memoryOnce}writeOnce(e){this.memoryOnce=e;try{U()?.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}${V(t.pathname)}`:"");if(!i)return;let n=e.referrer??fs(s?.referrer);this.capture("$pageview",{...e.properties,url:i,...e.title??s?.title?{title:e.title??s?.title}:{},...n?{referrer:n}:{}})}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{U()?.removeItem(this.anonKey),U()?.removeItem(this.sessionKey),U()?.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(Ce)):this.samples=[];let t=e?this.closingApi:this.api,s=e?this.closingPerfApi:this.perfApi,i=this.now(),n=this.session.snapshot()?.userId;for(this.identifyPending&&n&&this.granted("analytics")&&(this.identifyPending=!1,await this.sendIdentify(t,n));this.events.length>0;){let o=this.take(this.events,e);try{await t.batch({body:{events:o.map(a=>({...a,sent_at:i}))}})}catch{}}for(;this.samples.length>0;){let o=this.take(this.samples,e);try{await s.sendPerf({body:{items:o}})}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(hs((o,a)=>this.sample("web_vital",o,a))),e.network!==!1&&s.push(this.watchFetch(t));let i=()=>{document.visibilityState==="hidden"&&this.flush(!0)},n=()=>{this.flush(!0)};return document.addEventListener("visibilitychange",i),t.addEventListener("pagehide",n),s.push(()=>{document.removeEventListener("visibilitychange",i),t.removeEventListener("pagehide",n)}),this.stopAuto=()=>{for(let o of s.splice(0))o();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>=ct&&this.events.shift(),this.events.push(e),this.soon()}sample(e,t,s,i={}){if(!this.granted("performance"))return;this.samples.length>=ct&&this.samples.shift();let n={row_id:Q(),trace_type:e,name:t,value:Math.max(0,s),timestamp:this.now(),...i};this.samples.push(this.granted("analytics")?{...n,distinct_id:this.distinctId()}:Ce(n)),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,os);if(!t)return s;for(;s.length>1&&JSON.stringify(s).length>ds;)e.unshift(s.pop());return s}distinctId(){return this.session.snapshot()?.userId??this.anonymousId()}anonymousId(){let e=U();try{let t=e?.getItem(this.anonKey);if(t)return t;let s=`anon_${Q()}`;if(e?.setItem(this.anonKey,s),e?.getItem(this.anonKey)===s)return s}catch{}return this.memoryAnon??=`anon_${Q()}`,this.memoryAnon}sessionId(e){let t=U(),s=this.memorySession;try{let n=t?.getItem(this.sessionKey);n&&(s=JSON.parse(n))}catch{}let i=s&&e-s.last<as?{id:s.id,last:e}:{id:`ses_${Q()}`,last:e};this.memorySession=i;try{t?.setItem(this.sessionKey,JSON.stringify(i))}catch{}return i.id}watchPages(e){let t="",s=()=>{let a=`${e.location.origin}${e.location.pathname}`;if(a===t)return;t=a;let d=`${e.location.origin}${V(e.location.pathname)}`;setTimeout(()=>this.page({url:d}),0)},i=e.history,n=i.pushState.bind(i),o=i.replaceState.bind(i);return i.pushState=(...a)=>{n(...a),s()},i.replaceState=(...a)=>{o(...a),s()},e.addEventListener("popstate",s),s(),()=>{i.pushState=n,i.replaceState=o,e.removeEventListener("popstate",s)}}watchFetch(e){let t=e.fetch;if(typeof t!="function")return()=>{};let s=async(i,n)=>{let o=performance.now(),a=i instanceof Request?i:void 0,d=(n?.method??a?.method??"GET").toUpperCase(),l;try{l=new URL(a?.url??String(i),e.location.href)}catch{l=void 0}let c=!!l&&l.pathname.startsWith("/analytics/")||us(n?.headers??a?.headers);try{let f=await t(i,n);return l&&!c&&this.sample("network",`${d} ${l.origin}${V(l.pathname)}`,performance.now()-o,{attrs:{status:String(f.status)},...f.headers.get("x-request-id")?{request_id:f.headers.get("x-request-id")}:{}}),f}catch(f){throw l&&!c&&this.sample("network",`${d} ${l.origin}${V(l.pathname)}`,performance.now()-o,{attrs:{status:"0"}}),f}};return e.fetch=s,()=>{e.fetch===s&&(e.fetch=t)}}};function Ce(r){let{distinct_id:e,request_id:t,...s}=r;return s}var ls=r=>r.entryType==="layout-shift"&&"value"in r&&"hadRecentInput"in r,cs=r=>r.entryType==="event"||r.entryType==="first-input";function Z(r,e){if(!(typeof PerformanceObserver>"u"))try{let t=new PerformanceObserver(s=>e(s.getEntries()));return t.observe({type:r,buffered:!0}),t}catch{return}}function hs(r){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 c of l)e=Math.max(e,c.startTime)}),Z("layout-shift",l=>{for(let c of l)ls(c)&&!c.hadRecentInput&&(t+=c.value)}),Z("event",l=>{for(let c of l)cs(c)&&(s=Math.max(s,c.duration))}),Z("paint",l=>{for(let c of l)c.name==="first-contentful-paint"&&r("FCP",c.startTime)})],n=performance.getEntriesByType("navigation")[0];n&&n.responseStart>0&&r("TTFB",n.responseStart);let o=!1,a=()=>{o||(o=!0,e>0&&r("LCP",e),r("CLS",t),s>0&&r("INP",s))},d=()=>{document.visibilityState==="hidden"&&a()};return document.addEventListener("visibilitychange",d),()=>{a(),document.removeEventListener("visibilitychange",d);for(let l of i)l?.disconnect()}}function us(r){if(!r)return!1;try{return new Headers(r).has("next-router-prefetch")}catch{return!1}}var ps=/^[a-z][a-z0-9_-]{0,31}$/;function V(r){return r.split("/").map(e=>{if(e==="")return e;let t=e.split(";",1)[0],s=t.toLowerCase();return ps.test(s)&&(s.match(/\d/g)?.length??0)<=2&&t.slice(1)===s.slice(1)&&s.split(/[-_]/).every(n=>n.length<=16)?s:":id"}).join("/")}function fs(r){if(!r)return"";try{let e=new URL(r);return`${e.origin}${V(e.pathname)}`}catch{return V(r.split(/[?#]/,1)[0]??"")}}var kt=/^custom\.[a-z0-9_]{1,48}$/,gs=/^[a-z][a-z0-9_]{0,63}$/,ht=r=>gs.test(r)||kt.test(r),ms=50,ut=[5e3,3e4,12e4,6e5],vs=100,se=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[d,l]of Object.entries(t.start??{})){if(!ht(d))throw new TypeError(`consent.start: ${JSON.stringify(d)} is not a consent key (a platform key, or custom.<name>)`);if(l!=="granted"&&l!=="denied")throw new TypeError(`consent.start.${d} is granted or denied`)}for(let d of t.customKeys??[])if(!kt.test(d))throw new TypeError(`consent.customKeys: ${JSON.stringify(d)} 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=()=>dt(this.installation)?{}:{unknown:{on:!0,w:this.stamp()}},n={whose:null,install:this.installation.id,choices:{},unsent:[]};typeof s!="object"?this.kept={...n,...s==="unreadable"?{unknown:{on:!0,w:this.stamp()}}:i()}:s.whose==null&&s.install!==void 0&&s.install!==this.installation.id?this.kept={...n,unsent:s.unsent.filter(d=>d.user!==null),...s.keys?{keys:s.keys}:{},...i()}:this.kept=s,e.session.onChange((d,l)=>{this.engaged&&(d==="SIGNED_IN"&&l?this.signedIn(l):(d==="SIGNED_OUT"||d==="SESSION_EXPIRED")&&this.signedOut())});let o=globalThis;typeof o.addEventListener=="function"&&(o.addEventListener("storage",d=>{(d.key===this.storeKey||d.key===null)&&this.reload()}),o.addEventListener("online",()=>{this.engaged&&this.send()}));let a=this.kept;(e.options!==void 0||s!=="empty"&&(a.unknown?.on||a.unsent.length>0||a.link!==void 0||Object.keys(a.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(x(this.kept)!==this.holder()||this.gpcRefuses(e))return"denied";let t=gt(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||x(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[o,a]of t){if(!ht(o))throw new TypeError(`${JSON.stringify(o)} is not a consent key (a platform key, or custom.<name>)`);if(a!=="granted"&&a!=="denied")throw new TypeError(`${o}: a choice is granted or denied`)}if(t.length===0)return;this.engage();let s=this.chosenAt(),i=this.session.snapshot()?.userId??null,n=this.states();for(let[o,a]of t)this.queue({key:o,state:a,source:"app",chosen_at:s,user:i,...this.textVersion!==void 0?{text_version:this.textVersion}:{}});this.commit(n),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(d=>d.key),i=await this.platform().catch(()=>this.kept.keys??[]),n=new Set(i.filter(d=>d.ads).map(d=>d.key)),o=this.kept.region?.jurisdiction==="us",a=new Date(this.now());return a.setUTCMonth(a.getUTCMonth()-12),s.filter(d=>{let l=this.kept.choices[d];return o&&n.has(d)&&l?.last_denied_at!==void 0&&Date.parse(l.last_denied_at)>a.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{[E]: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(),n={};for(let h of e.choices)n[h.key]={state:h.state,source:h.source,chosen_at:h.chosen_at,...h.text_version!==void 0?{text_version:h.text_version}:{},...h.last_denied_at!==void 0?{last_denied_at:h.last_denied_at}:{}};let o=s.filter(h=>n[h.key]?.state!==h.state||Date.parse(n[h.key]?.chosen_at??"")!==Date.parse(h.chosen_at)).map(h=>A(h.key,h)),d=x(this.kept)===(t===null?`device:${this.installation.id}`:`user:${t}`)?Object.entries(this.kept.choices).filter(([,h])=>h.provisional).map(([h,p])=>A(h,p)):[];if(o.length+d.length>0&&(this.kept={...this.kept,void:D([...this.kept.void??[],...o,...d])}),t===null&&this.kept.resetAt!==void 0)for(let[h,p]of Object.entries(n))Date.parse(p.chosen_at)<this.kept.resetAt&&delete n[h];let l=new Set(Object.entries(n).map(([h,p])=>A(h,p))),c=(this.kept.void??[]).filter(h=>l.has(h));c.length>0&&(this.kept={...this.kept,unvoid:D([...this.kept.unvoid??[],...c])});let f=St(this.kept),g;if(x(this.kept)!==(t===null?`device:${this.installation.id}`:`user:${t}`))g=n;else{g={};for(let h of[...new Set([...Object.keys(this.kept.choices),...Object.keys(n)])].sort()){let p=this.kept.choices[h],y=p&&!p.provisional&&!f.has(A(h,p))?p:void 0,P=n[h],I=P&&(!y||Date.parse(P.chosen_at)>=Date.parse(y.chosen_at))?P:y;I&&(g[h]=I)}}for(let h of this.kept.unsent){if(h.user!==null&&h.user!==t||h.user===null&&h.device!==void 0&&h.device!==this.installation.id||h.user===null&&t!==null)continue;let p=g[h.key];p&&Date.parse(p.chosen_at)>Date.parse(h.chosen_at)||(g[h.key]=pt(h,p))}let{install:S,...m}=this.kept;this.kept={...m,whose:t,...t===null?{install:this.installation.id}:{},choices:g,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&&x(this.kept)===(t===null?`device:${this.installation.id}`:`user:${t}`),n=D([...this.kept.void??[],...s.map(d=>A(d.key,d))]);if(!i){this.kept={...this.kept,void:n},this.commit();return}let o=this.states(),a={...this.kept.choices};for(let d of s){if(this.kept.unsent.some(c=>c.key===d.key&&(c.user===null||c.user===e)&&Date.parse(c.chosen_at)>Date.parse(d.chosen_at)))continue;let l=a[d.key];a[d.key]={state:"denied",source:"app",chosen_at:d.chosen_at,...l?.last_denied_at!==void 0?{last_denied_at:l.last_denied_at}:{},provisional:!0}}this.kept={...this.kept,choices:a,void:n},this.commit(o);try{await this.read(e)}catch{this.stale=!0}}queue(e){let t=e.user===null?{...e,device:this.installation.id}:e,s=x(this.kept)===(t.user===null?`device:${this.installation.id}`:`user:${t.user}`);this.kept={...this.kept,unsent:_t([...this.kept.unsent,t]),...s?{choices:{...this.kept.choices,[t.key]:pt(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=this.session.snapshot()?.userId??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(!yt(i))throw i}if(this.kept.link===e){let{link:i,...n}=this.kept;this.kept=n,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{return(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 n=i[0],o=e===null?this.deviceApi:this.userApi(e),a;try{a=(await o.chooseConsents({headers:this.secret(),body:{installation_id:this.installation.id,...n.source==="gpc"?{source:"gpc"}:{},...n.text_version!==void 0?{text_version:n.text_version}:{},choices:i.map(d=>({key:d.key,state:d.state,chosen_at:d.chosen_at}))}})).data}catch(d){if(!yt(d))throw d;if(i.length>1){this.kept={...this.kept,unsent:this.kept.unsent.map(l=>i.some(c=>vt(c,l))?{...l,alone:!0}:l)},this.commit();continue}}this.kept={...this.kept,unsent:this.kept.unsent.filter(d=>!i.some(l=>vt(l,d))),done:D([...this.kept.done??[],...i.map(ie)])},this.commit(),a?(s=!0,e===t&&this.adopt(a,e,i)):await this.refused(t,e,i)}}nextGroup(e){let t=this.kept.unsent.filter(o=>o.user===e&&(e!==null||(o.device??this.installation.id)===this.installation.id)),s=t[0];if(!s)return[];let i=[],n=new Set;if(s.alone)return[s];for(let o of t)if(!n.has(o.key)&&(n.add(o.key),!(o.alone||o.source!==s.source||o.text_version!==s.text_version)&&(i.push(o),i.length===ms)))break;return i}retryLater(){if(this.retryTimer)return;let e=ut[Math.min(this.retries,ut.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(([,a])=>a.state!=="unset").map(([a])=>a),...this.kept.unsent.filter(a=>a.user===null&&(a.device??this.installation.id)===this.installation.id).map(a=>a.key),...Object.keys(this.start),...this.customKeys,...(this.kept.keys??[]).map(a=>a.key)]),i={};for(let[a,d]of Object.entries(this.kept.choices))i[a]={state:"unset",source:"app",chosen_at:t,...d.last_denied_at!==void 0?{last_denied_at:d.last_denied_at}:{}};let n=a=>a.user===null&&(a.device??this.installation.id)===this.installation.id,o=this.kept.unsent.filter(n);this.kept={whose:null,install:this.installation.id,resetAt:Date.parse(t),choices:i,unsent:this.kept.unsent.filter(a=>!n(a)),...this.kept.void?{void:this.kept.void}:{},...this.kept.unvoid?{unvoid:this.kept.unvoid}:{},done:D([...this.kept.done??[],...o.map(ie)]),...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 a of s)this.queue({key:a,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",n=>{n.event==="changed"&&this.changed(s,Me(n.payload))}),t.on("state_snapshot",n=>this.held(s,Me(bt(n.entries)))),t.on("state_diff",n=>this.held(s,Me(bt(n.set))))];s.off=()=>i.forEach(n=>n()),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(n=>n.key===e&&n.ads))return!1;let t=gt(this.kept,e);if(t?.state==="denied")return!1;let s=this.kept.gpc?.[x(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||x(this.kept)!==this.holder())return;let e;try{e=await this.platform()}catch{return}if(x(this.kept)!==this.holder())return;let t=this.session.snapshot()?.userId??null,s=e.filter(o=>o.ads&&this.gpcRefuses(o.key)&&!this.kept.unsent.some(a=>a.key===o.key&&a.source==="gpc"&&a.user===t));if(s.length===0)return;let i=this.chosenAt(),n=this.states();for(let o of s)this.queue({key:o.key,state:"denied",source:"gpc",chosen_at:i,user:t});this.kept={...this.kept,gpc:{...this.kept.gpc,[x(this.kept)]:Date.parse(i)}},this.commit(n),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 n of[...this.listeners])try{n(s,i)}catch{}}}load(){let e;try{e=wt()?.getItem(this.storeKey)}catch{return"unreadable"}if(e==null)return"empty";try{let t=JSON.parse(e);if(ks(t))return t}catch{}return"unreadable"}reload(){let e=this.load();if(typeof e!="object"){this.write();return}let t=this.states();this.kept=ft(e,this.kept,"theirs",this.holder()),x(e)===x(this.kept)&&mt(this.kept)!==mt(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=ft(t,this.kept,"ours",this.holder())),this.write(),this.tell(e)}write(){try{wt()?.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 pt(r,e){let t=r.state==="denied"?r.chosen_at:e?.last_denied_at;return{state:r.state,source:r.source,chosen_at:r.chosen_at,...r.text_version!==void 0?{text_version:r.text_version}:{},...t!==void 0?{last_denied_at:t}:{}}}function A(r,e){return`${r}|${e.provisional?"provisional":e.state}|${Date.parse(e.chosen_at)}`}function St(r){let e=new Set(r.unvoid??[]);return new Set((r.void??[]).filter(t=>!e.has(t)))}var te={denied:2,unset:1,granted:0};function ys(r,e,t,s){let i=e&&!s.has(A(r,e))?e:void 0,n=t&&!s.has(A(r,t))?t:void 0;if(!i||!n)return i??n;let o=Date.parse(i.chosen_at),a=Date.parse(n.chosen_at);return o!==a?o>a?i:n:te[i.state]!==te[n.state]?te[i.state]>te[n.state]?i:n:i.provisional?n:i}function ws(r,e){return!r||!e?r??e:e.w>r.w||e.w===r.w&&e.on?e:r}function ft(r,e,t,s){let i=D([...r.void??[],...e.void??[]]),n=D([...r.unvoid??[],...e.unvoid??[]]),o=St({void:i,unvoid:n}),a={},d,l={...r.gpc};for(let[y,P]of Object.entries(e.gpc??{}))l[y]=Math.max(l[y]??0,P);let c;if(x(r)===x(e)){d=e;for(let y of[...new Set([...Object.keys(r.choices),...Object.keys(e.choices)])].sort()){let P=ys(y,r.choices[y],e.choices[y],o);P&&(a[y]=P)}c=ws(r.unknown,e.unknown)}else{d=x(e)===s?e:x(r)===s?r:t==="ours"?e:r;for(let[y,P]of Object.entries(d.choices))o.has(A(y,P))||(a[y]=P);c=d.unknown}let f=D([...r.done??[],...e.done??[]]),g=_t([...r.unsent,...e.unsent]).filter(y=>!f.includes(ie(y))),S=t==="ours"?e:r,m=t==="ours"?r:e,h=S.region??m.region,p=S.keys??m.keys;return{whose:d.whose??null,...d.whose==null&&d.install!==void 0?{install:d.install}:{},...d.whose==null&&(r.resetAt!==void 0||e.resetAt!==void 0)&&x(r)===x(e)?{resetAt:Math.max(r.resetAt??0,e.resetAt??0)}:d.whose==null&&d.resetAt!==void 0?{resetAt:d.resetAt}:{},choices:a,unsent:g,...f.length>0?{done:f}:{},...i.length>0?{void:i}:{},...n.length>0?{unvoid:n}:{},...S.link!==void 0?{link:S.link}:{},...h?{region:h}:{},...Object.keys(l).length>0?{gpc:l}:{},...p?{keys:p}:{},...c?{unknown:c}:{}}}function ie(r){return`${r.user??`device:${r.device??""}`}|${r.key}|${r.state}|${r.source}|${r.chosen_at}`}function gt(r,e){let t=r.choices[e];if(!t||r.whose!=null||r.resetAt===void 0||Date.parse(t.chosen_at)>=r.resetAt)return t}function x(r){return r.whose!=null?`user:${r.whose}`:`device:${r.install??""}`}function D(r){return[...new Set(r)].slice(-vs)}function mt(r){return JSON.stringify(r,(e,t)=>typeof t=="object"&&t!==null&&!Array.isArray(t)?Object.fromEntries(Object.entries(t).sort(([s],[i])=>s.localeCompare(i))):t)}function _t(r){let e=new Map;for(let t of r){let s=ie(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 bs=new Set(["granted","denied","unset"]);function ks(r){if(typeof r!="object"||r===null)return!1;let e=r;if(typeof e.choices!="object"||e.choices===null||Array.isArray(e.choices)||!Array.isArray(e.unsent))return!1;let t=(a,d)=>{if(typeof a!="object"||a===null)return!1;let l=a;return bs.has(l.state)&&typeof l.chosen_at=="string"&&(!d||typeof l.key=="string")},s=a=>a===void 0||typeof a=="object"&&a!==null&&typeof a.on=="boolean"&&typeof a.w=="number",i=r,n=a=>a===void 0||Array.isArray(a)&&a.every(d=>typeof d=="string"),o=i.whose===void 0||i.whose===null||typeof i.whose=="string";return Object.values(e.choices).every(a=>t(a,!1))&&e.unsent.every(a=>t(a,!0))&&(i.gpc===void 0||typeof i.gpc=="object"&&i.gpc!==null&&Object.values(i.gpc).every(a=>typeof a=="number"))&&s(i.unknown)&&n(i.done)&&n(i.void)&&n(i.unvoid)&&o}function vt(r,e){return r.key===e.key&&r.user===e.user&&r.state===e.state&&r.source===e.source&&r.chosen_at===e.chosen_at}function yt(r){return r instanceof k&&r.status>=400&&r.status<500&&r.status!==401&&r.status!==408&&r.status!==429}function wt(){try{return globalThis.localStorage}catch{return}}function bt(r){let e=typeof r=="object"&&r!==null?r.version:void 0;return typeof e=="object"&&e!==null?e.v:void 0}function Me(r){let e=typeof r=="object"&&r!==null?r.version:void 0;return typeof e=="number"&&Number.isFinite(e)?e:void 0}var Ss=`
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}