palbase 0.18.2 → 0.18.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) 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/{DTILUE3A.js → 23DG57SE.js} +2 -2
  8. package/dist/chunks/{JWBOJ4DZ.js → 7J76IQQO.js} +2 -2
  9. package/dist/chunks/{QEBQ452U.js → 7YJBMLWX.js} +1 -1
  10. package/dist/chunks/{XQANDC54.js → AUNIMWDN.js} +2 -2
  11. package/dist/chunks/{TNSIU2CJ.js → C6NH2WOZ.js} +2 -2
  12. package/dist/chunks/{PQU3TAPP.js → CHBI7BTE.js} +2 -2
  13. package/dist/chunks/{X6FNTEXY.js → CSVO2J45.js} +1 -1
  14. package/dist/chunks/{NWFZYTV4.js → EBPOLJ27.js} +1 -1
  15. package/dist/chunks/{ZFJ7245R.js → EBXQXYJO.js} +2 -2
  16. package/dist/chunks/{BZD6DTRS.js → EIPZPXE2.js} +1 -1
  17. package/dist/chunks/{RFF725G4.js → F4KVCLHJ.js} +2 -2
  18. package/dist/chunks/{PPIZUQG5.js → HMFOOFQZ.js} +2 -2
  19. package/dist/chunks/{6O7HI5DJ.js → JRY3AOWY.js} +2 -2
  20. package/dist/chunks/{2MCXKESR.js → Q25DFC2R.js} +1 -1
  21. package/dist/chunks/R4E3KDUH.js +22 -0
  22. package/dist/chunks/{J3SSWIXW.js → RKYEUHF2.js} +2 -2
  23. package/dist/chunks/{FWE2RQ74.js → RLGT4XP5.js} +2 -2
  24. package/dist/chunks/{JK6Y5742.js → SZIFR2QY.js} +2 -2
  25. package/dist/chunks/{J3GVOUKS.js → V75RWXKF.js} +2 -2
  26. package/dist/chunks/{TAFRNPVE.js → WFE6Y3B7.js} +2 -2
  27. package/dist/chunks/{34GIR5XI.js → XYBDQRUX.js} +1 -1
  28. package/dist/chunks/{FYEDISVZ.js → YGFXUINB.js} +1 -1
  29. package/dist/chunks/{KPB7BB3F.js → YOSU5KRY.js} +2 -2
  30. package/dist/cli.js +141 -141
  31. package/dist/refuse/ai.js +1 -1
  32. package/dist/refuse/backend.js +1 -1
  33. package/dist/refuse/server.js +1 -1
  34. package/dist/server/index.js +2 -2
  35. package/dist/server/testing.js +2 -2
  36. package/dist/web/index.js +2 -2
  37. package/dist/web/message.js +2 -2
  38. package/dist/web/palbe.js +2 -2
  39. package/dist/web/paywall.js +2 -2
  40. package/dist/web/push-sw.js +1 -1
  41. package/dist/web/ssr.js +2 -2
  42. package/dist/web/vite.js +2 -2
  43. package/package.json +2 -2
  44. package/types/internal/src/messaging/engine.d.ts +8 -0
  45. package/types/internal/src/messaging/store.d.ts +13 -0
  46. package/dist/chunks/N7TLZR3V.js +0 -22
@@ -1,2 +1,2 @@
1
- /*! palbase 0.18.2 — Palbase SDK License (see LICENSE) */
1
+ /*! palbase 0.18.3 — Palbase SDK License (see LICENSE) */
2
2
  import{lstat as j,mkdir as F,readdir as M,readFile as N,rename as J,rm as T,writeFile as v}from"node:fs/promises";import{join as E}from"node:path";var o="palbase/strings",f="_meta.json",p=3,y=2,$=r=>typeof r=="object"&&r!==null&&!Array.isArray(r);function m(r){try{return Intl.getCanonicalLocales(r)[0]}catch{return}}function b(r,n){try{return JSON.parse(r)}catch(t){throw new Error(`${n} is not JSON: ${t.message}`)}}async function x(r){let n=E(r,o);try{if(!(await j(n)).isDirectory())throw new Error(`${o} is not a directory: the strings live in a directory of their own`)}catch(e){if(e.code==="ENOENT")return;throw e}let t=new Map;for(let e of await M(n,{withFileTypes:!0}))if(!(e.name.startsWith(".")||!e.name.endsWith(".json"))){if(!e.isFile())throw new Error(`${o}/${e.name} is not a regular file`);t.set(e.name,await N(E(n,e.name),"utf8"))}return t.size===0?void 0:t}async function R(r,n=[p,y]){let t=await x(r);if(t===void 0)return;let e=t.get(f);if(e===void 0)throw new Error(`${o}/${f} is missing: it names the source language, and without it the language files are not a table`);let u=b(e,`${o}/${f}`);if(!$(u))throw new Error(`${o}/${f}: not a JSON object`);let s=u.version;if(s===y&&!n.includes(y))throw new Error(`${o}/${f}: version 2 is the earlier format ({"value", "state"} for each sentence) \u2014 run \`npx palbase strings\` once, and it writes the table as version ${p}`);if(typeof s!="number"||!n.includes(s))throw new Error(`${o}/${f}: version ${JSON.stringify(s)} is not one this reads (${n.join(" or ")})`);let a=u.source;if(typeof a!="string"||m(a)!==a)throw new Error(`${o}/${f}: source ${JSON.stringify(a)} is not a language tag as it is written (${m(String(a))??"en, en-US, zh-Hans"})`);let S=new Map;for(let w of[...t.keys()].sort()){if(w===f)continue;let i=w.slice(0,-5),g=`${o}/${w}`,d=m(i);if(d===void 0)throw new Error(`${g}: ${JSON.stringify(i)} is not a language tag`);if(d!==i)throw new Error(`${g}: the language is written ${d} \u2014 name the file ${d}.json`);if(i===a)throw new Error(`${g}: ${i} is the source language \u2014 its text is the key itself, and it has no file`);if(i==="und"||i==="root"||i.startsWith("x-"))throw new Error(`${g}: ${i} is no language a request names \u2014 name the file for one (en, de, pt-BR)`);let O=b(t.get(w),g);if(!$(O))throw new Error(`${g}: not a JSON object of "sentence": "translation"`);let h=new Map;for(let[l,c]of Object.entries(O))if(s===p){if(typeof c!="string")throw new Error(`${g}: the translation of ${JSON.stringify(l)} is not a string`);h.set(l,c)}else if(typeof c=="string")h.set(l,c);else{if(!$(c)||typeof c.value!="string")throw new Error(`${g}: key ${JSON.stringify(l)} is not {"value": string, "state": string}`);h.set(l,c.state==="missing"?"":c.value)}S.set(i,h)}return{format:s,source:a,languages:S}}async function A(r){let n=await R(r,[p]);if(n===void 0)return;let t={};Object.setPrototypeOf(t,null);for(let[e,u]of n.languages)for(let[s,a]of u)Object.hasOwn(t,s)||(t[s]={},Object.setPrototypeOf(t[s],null)),t[s][e]=a;return{source:n.source,locales:[n.source,...n.languages.keys()],strings:t}}export{A as a};
@@ -0,0 +1,22 @@
1
+ /*! palbase 0.18.3 — Palbase SDK License (see LICENSE) */
2
+ import{e as Ge,g as He,h as We}from"./RKYEUHF2.js";import{h as Je}from"./WFE6Y3B7.js";import{a as Be}from"./C6NH2WOZ.js";import{r as $e,t as Ve,u as Fe}from"./YGFXUINB.js";import{b as G,c as L,e as Le,g as Se,h as K,i as Ke}from"./JRY3AOWY.js";import{a as je,b as H}from"./RLGT4XP5.js";import{b as S,d as q}from"./HMFOOFQZ.js";function Ct(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 ze(){let r=null;return{load:()=>r,save:e=>{r=e},clear:()=>{r=null},shared:!1}}function Xe(r){let e=null,t=!0,s=()=>{try{return globalThis.localStorage}catch{return}};return{shared:!0,load(){try{let n=s()?.getItem(r);return n==null?t?null:e:JSON.parse(n)}catch{return e}},save(n){e=n;try{let i=s();if(!i)throw new Error("no storage");i.setItem(r,JSON.stringify(n)),t=!0}catch{t=!1}},clear(){e=null,t=!0;try{s()?.removeItem(r)}catch{}},watch(n){let i=globalThis;if(typeof i.addEventListener!="function")return()=>{};let a=o=>{(o.key===r||o.key===null)&&n()};return i.addEventListener("storage",a),()=>i.removeEventListener?.("storage",a)}}}function _e(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 Nt=6e4,Ut=15e3;function Dt(r,e,t){let s=r?globalThis.navigator?.locks:void 0;return s?s.request(e,t):t()}var W=class{current=null;loaded;inflight=null;endReason=null;listeners=new Set;store;refresher;isRejected;now;lockName;refreshTimeoutMs;mode;constructor(e,t,s,n={}){this.store=e,this.refresher=t,this.isRejected=s,this.now=n.now??Date.now,this.lockName=n.lockName??"palbase.session.refresh",this.refreshTimeoutMs=n.refreshTimeoutMs??Ut,this.mode=n.refresh??"behind",this.loaded=Promise.resolve(e.load()).then(i=>{this.current=i}),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 n=t==="TOKEN_REFRESHED"?this.current:null,i={accessToken:e.access_token,refreshToken:e.refresh_token,expiresAt:this.now()+e.expires_in*1e3,userId:s?.id??n?.userId??_e(e.access_token),user:s??n?.user};return this.current=i,await this.store.save(i),this.emit(t,i),i}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 n=await this.store.load();(!n||!s||n.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>Nt)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=Dt(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 n=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(n,"TOKEN_REFRESHED")}catch(n){throw this.isRejected(n)&&this.current?.refreshToken===t.refreshToken&&await this.clear("SESSION_EXPIRED",Ct(n)),n}});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((n,i)=>{t=setTimeout(()=>i(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 xe=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 n of s)e?n.resolve():n.reject(new Error(`join ${this.name} refused: ${JSON.stringify(t)}`));if(e)for(let n of[...this.joiners])try{n()}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;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 xe(e,this,t)),s}disconnect(){this.closedByUs=!0,this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=null,this.stopHeartbeat();let e=this.ws;this.ws=null,this.opening=null,e?.close(1e3);for(let[,t]of this.replies)t("error",{reason:"socket closed"});this.replies.clear();for(let t of this.channels.values())t.closed("the socket was closed")}async tokenChanged(){if(!this.ws||this.ws.readyState!==1)return;let e=await this.opts.accessToken();if(e)for(let t of this.channels.values())t.state==="joined"&&this.push(t.joinRef,t.topic,"access_token",{access_token:e})}join(e){e.state="joining",this.open().then(()=>this.sendJoin(e)).catch(t=>e.settled(!1,{reason:t instanceof Error?t.message:String(t)}))}leave(e){e.state==="joined"&&this.ws?.readyState===1&&this.push(e.joinRef,e.topic,"phx_leave",{}),e.state="closed",this.channels.delete(e.name)}async request(e,t,s){let n=this.ws;if(this.channels.get(e.name)!==e||e.state!=="joined"||n?.readyState!==1)return{status:"error",response:{reason:"not joined"}};let i=this.nextRef(),a=JSON.stringify([e.joinRef,i,e.topic,t,s]),o=this.awaitReply(i);return n.send(a),o}open(){if(this.ws?.readyState===1)return Promise.resolve();if(this.opening)return this.opening;this.closedByUs=!1;let e=this.opts.webSocket??globalThis.WebSocket,t=`${this.opts.baseUrl.replace(/^http/,"ws")}/realtime/v1/websocket?vsn=2.0.0&apikey=${encodeURIComponent(this.opts.publishableKey)}`,s=new Promise((n,i)=>{let a=new e(t);this.ws=a,a.onopen=()=>{this.attempts=0,this.startHeartbeat(),n()},a.onmessage=o=>this.receive(String(o.data)),a.onerror=()=>i(new Error("the realtime socket could not be opened")),a.onclose=()=>this.dropped(a)});return this.opening=s,s.finally(()=>{this.opening===s&&(this.opening=null)}).catch(()=>{}),s}dropped(e){if(this.ws!==e)return;this.ws=null,this.stopHeartbeat();for(let[,n]of this.replies)n("error",{reason:"socket closed"});this.replies.clear();for(let n of this.channels.values())n.state==="joined"&&(n.state="joining");if(this.closedByUs||![...this.channels.values()].some(n=>n.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 n=[...this.channels.values()].filter(i=>i.state==="joining");this.open().then(()=>Promise.all(n.map(i=>this.sendJoin(i)))).catch(()=>{})},s))}async sendJoin(e){let t=await this.opts.accessToken(),s=this.nextRef();e.joinRef=s;let n=this.awaitReply(s),i={broadcast:{self:!1}};e.logSeq!==void 0&&(i.log={after:e.logSeq}),this.push(s,e.topic,"phx_join",{access_token:t,config:i},s);let{status:a,response:o}=await n;if(this.channels.get(e.name)!==e||e.state!=="joining"){a==="ok"&&this.ws?.readyState===1&&this.push(s,e.topic,"phx_leave",{});return}e.settled(a==="ok",o)}awaitReply(e){return new Promise(t=>{let s=J(setTimeout(()=>{this.replies.delete(e),t({status:"timeout",response:{reason:"no reply"}})},this.opts.replyTimeoutMs??1e4));this.replies.set(e,(n,i)=>{clearTimeout(s),this.replies.delete(e),t({status:n,response:i})})})}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,n,i,a]=t,o=typeof a=="object"&&a!==null?a:{};if(i==="phx_reply"&&typeof s=="string"){if(s===this.heartbeatRef){this.heartbeatRef=null;return}this.replies.get(s)?.(String(o.status),o.response??{});return}let d=[...this.channels.values()].find(c=>c.topic===n);if(d){if(i==="phx_close"){d.state="closed";return}if(i==="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(i,o)}}push(e,t,s,n,i=this.nextRef()){this.ws?.send(JSON.stringify([e,i,t,s,n]))}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 R="X-Palbase-Installation-Secret",Y="X-Palbase-Installation",Ze=new WeakMap;function O(r){return Ze.get(r)}var Qe=new WeakSet;function et(r){return Qe.has(r)}var qt=/^[A-Za-z0-9_-]{43}$/,X=class{id;constructor(e){let t=`palbase.installation.secret.${e}`,s;try{let n=Ye()?.getItem(t);n&&qt.test(n)&&(s=n)}catch{}if(!s){Qe.add(this),s=tt(crypto.getRandomValues(new Uint8Array(32)));try{Ye()?.setItem(t,s)}catch{}}Ze.set(this,s),this.id=Lt(s)}};function Lt(r){return tt(jt(new TextEncoder().encode(r)).subarray(0,16))}function Ye(){try{return globalThis.localStorage}catch{return}}function tt(r){let e="";for(let t of r)e+=String.fromCharCode(t);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}var Kt=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),E=(r,e)=>r>>>e|r<<32-e;function jt(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 n=new Uint32Array(64);for(let o=0;o<t.length;o+=64){for(let f=0;f<16;f++)n[f]=s.getUint32(o+f*4);for(let f=16;f<64;f++){let y=E(n[f-15],7)^E(n[f-15],18)^n[f-15]>>>3,b=E(n[f-2],17)^E(n[f-2],19)^n[f-2]>>>10;n[f]=n[f-16]+y+n[f-7]+b|0}let[d,c,l,g,p,k,_,h]=e;for(let f=0;f<64;f++){let y=h+(E(p,6)^E(p,11)^E(p,25))+(p&k^~p&_)+Kt[f]+n[f]|0,b=(E(d,2)^E(d,13)^E(d,22))+(d&c^d&l^c&l)|0;h=_,_=k,k=p,p=g+y|0,g=l,l=c,c=d,d=y+b|0}e[0]+=d,e[1]+=c,e[2]+=l,e[3]+=g,e[4]+=p,e[5]+=k,e[6]+=_,e[7]+=h}let i=new Uint8Array(32),a=new DataView(i.buffer);for(let o=0;o<8;o++)a.setUint32(o*4,e[o]);return i}var Vt=30*6e4,st=1e3,Ft=100,Bt=60*1024,Z=()=>globalThis.crypto?.randomUUID?globalThis.crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;function D(){try{return globalThis.localStorage}catch{return}}var 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,n,i,a,o={}){this.session=s,this.consent=n;let d={send:l=>e.send(this.granted("analytics")?{...l,headers:{...l.headers,[Y]:i.id}}:l)};this.api=G.client(d);let c={send:l=>(this.granted("analytics")?e:t).send(l)};this.perfApi=G.client(c),this.closingApi=G.client({send:l=>d.send({...l,keepalive:!0})}),this.closingPerfApi=G.client({send:l=>c.send({...l,keepalive:!0})}),this.flushMs=o.flushMs??5e3,this.flushAt=o.flushAt??20,this.now=o.now??Date.now,this.anonKey=`palbase.analytics.anonymous.${a}`,this.sessionKey=`palbase.analytics.session.${a}`,this.onceKey=`palbase.analytics.once.${a}`,s.onChange(l=>{l==="SIGNED_IN"?(this.identifyPending=!0,this.soon()):l==="SIGNED_OUT"&&(this.identifyPending=!1,this.reset())}),n.onChange((l,g)=>{g!=="granted"&&(l==="analytics"?(this.events=[],this.identifyPending=!1,this.samples=this.samples.map(Pe),this.reset()):l==="performance"&&(this.samples=[]))})}capture(e,t){for(let n of this.listeners)n(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 n=this.sessionId(this.now()),i=this.readOnce(),a=i?.session===n?i.keys:[];a.includes(e)||(this.writeOnce({session:n,keys:[...a,e].slice(-500)}),this.capture(t,s))}readOnce(){try{let e=D()?.getItem(this.onceKey);if(e)return JSON.parse(e)}catch{}return this.memoryOnce}writeOnce(e){this.memoryOnce=e;try{D()?.setItem(this.onceKey,JSON.stringify(e))}catch{}}onEvent(e){return this.listeners.add(e),()=>this.listeners.delete(e)}page(e={}){let t=globalThis.location,s=globalThis.document,n=e.url??(t?`${t.origin}${j(t.pathname)}`:"");if(!n)return;let i=e.referrer??Xt(s?.referrer);this.capture("$pageview",{...e.properties,url:n,...e.title??s?.title?{title:e.title??s?.title}:{},...i?{referrer:i}:{}})}async identify(e){this.identifyPending=!1;let t=this.session.snapshot()?.userId;!t||!this.granted("analytics")||(await this.flush(),await this.sendIdentify(this.api,t,e))}async sendIdentify(e,t,s){try{await e.identify({body:{distinct_id:t,anonymous_id:this.anonymousId(),traits:s,timestamp:this.now(),sent_at:this.now()}})}catch{}}reset(){this.memoryAnon=void 0,this.memorySession=void 0,this.memoryOnce=void 0;try{D()?.removeItem(this.anonKey),D()?.removeItem(this.sessionKey),D()?.removeItem(this.onceKey)}catch{}}async flush(e=!1){this.timer&&clearTimeout(this.timer),this.timer=void 0,this.granted("analytics")||(this.events=[]),this.granted("performance")?this.granted("analytics")||(this.samples=this.samples.map(Pe)):this.samples=[];let t=e?this.closingApi:this.api,s=e?this.closingPerfApi:this.perfApi,n=this.now(),i=this.session.snapshot()?.userId;for(this.identifyPending&&i&&this.granted("analytics")&&(this.identifyPending=!1,await this.sendIdentify(t,i));this.events.length>0;){let a=this.take(this.events,e);try{await t.batch({body:{events:a.map(o=>({...o,sent_at:n}))}})}catch{}}for(;this.samples.length>0;){let a=this.take(this.samples,e);try{await s.sendPerf({body:{items:a}})}catch{}}}start(e={}){this.stopAuto?.(),this.appVersion=e.appVersion;let t=globalThis;if(typeof t.addEventListener!="function"||typeof globalThis.document>"u")return()=>{};let s=[];e.pageViews!==!1&&s.push(this.watchPages(t)),e.webVitals!==!1&&s.push(Wt((a,o)=>this.sample("web_vital",a,o))),e.network!==!1&&s.push(this.watchFetch(t));let n=()=>{document.visibilityState==="hidden"&&this.flush(!0)},i=()=>{this.flush(!0)};return document.addEventListener("visibilitychange",n),t.addEventListener("pagehide",i),s.push(()=>{document.removeEventListener("visibilitychange",n),t.removeEventListener("pagehide",i)}),this.stopAuto=()=>{for(let a of s.splice(0))a();this.stopAuto=void 0},this.stopAuto}granted(e){return this.consent.state(e)==="granted"}async person(e){if(!this.granted("analytics"))return;let t=this.session.snapshot()?.userId,s=this.now();try{await this.api.setPersonProperties({body:{...e,...t?{}:{distinct_id:this.anonymousId()},timestamp:s,sent_at:s}})}catch{}}hold(e){this.events.length>=st&&this.events.shift(),this.events.push(e),this.soon()}sample(e,t,s,n={}){if(!this.granted("performance"))return;this.samples.length>=st&&this.samples.shift();let i={row_id:Z(),trace_type:e,name:t,value:Math.max(0,s),timestamp:this.now(),...n};this.samples.push(this.granted("analytics")?{...i,distinct_id:this.distinctId()}:Pe(i)),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,Ft);if(!t)return s;for(;s.length>1&&JSON.stringify(s).length>Bt;)e.unshift(s.pop());return s}distinctId(){return this.session.snapshot()?.userId??this.anonymousId()}anonymousId(){let e=D();try{let t=e?.getItem(this.anonKey);if(t)return t;let s=`anon_${Z()}`;if(e?.setItem(this.anonKey,s),e?.getItem(this.anonKey)===s)return s}catch{}return this.memoryAnon??=`anon_${Z()}`,this.memoryAnon}sessionId(e){let t=D(),s=this.memorySession;try{let i=t?.getItem(this.sessionKey);i&&(s=JSON.parse(i))}catch{}let n=s&&e-s.last<Vt?{id:s.id,last:e}:{id:`ses_${Z()}`,last:e};this.memorySession=n;try{t?.setItem(this.sessionKey,JSON.stringify(n))}catch{}return n.id}watchPages(e){let t="",s=()=>{let o=`${e.location.origin}${e.location.pathname}`;if(o===t)return;t=o;let d=`${e.location.origin}${j(e.location.pathname)}`;setTimeout(()=>this.page({url:d}),0)},n=e.history,i=n.pushState.bind(n),a=n.replaceState.bind(n);return n.pushState=(...o)=>{i(...o),s()},n.replaceState=(...o)=>{a(...o),s()},e.addEventListener("popstate",s),s(),()=>{n.pushState=i,n.replaceState=a,e.removeEventListener("popstate",s)}}watchFetch(e){let t=e.fetch;if(typeof t!="function")return()=>{};let s=async(n,i)=>{let a=performance.now(),o=n instanceof Request?n:void 0,d=(i?.method??o?.method??"GET").toUpperCase(),c;try{c=new URL(o?.url??String(n),e.location.href)}catch{c=void 0}let l=!!c&&c.pathname.startsWith("/analytics/")||Jt(i?.headers??o?.headers);try{let g=await t(n,i);return c&&!l&&this.sample("network",`${d} ${c.origin}${j(c.pathname)}`,performance.now()-a,{attrs:{status:String(g.status)},...g.headers.get("x-request-id")?{request_id:g.headers.get("x-request-id")}:{}}),g}catch(g){throw c&&!l&&this.sample("network",`${d} ${c.origin}${j(c.pathname)}`,performance.now()-a,{attrs:{status:"0"}}),g}};return e.fetch=s,()=>{e.fetch===s&&(e.fetch=t)}}};function Pe(r){let{distinct_id:e,request_id:t,...s}=r;return s}var Gt=r=>r.entryType==="layout-shift"&&"value"in r&&"hadRecentInput"in r,Ht=r=>r.entryType==="event"||r.entryType==="first-input";function Q(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 Wt(r){if(typeof document>"u"||typeof performance>"u"||typeof performance.getEntriesByType!="function")return()=>{};let e=0,t=0,s=0,n=[Q("largest-contentful-paint",c=>{for(let l of c)e=Math.max(e,l.startTime)}),Q("layout-shift",c=>{for(let l of c)Gt(l)&&!l.hadRecentInput&&(t+=l.value)}),Q("event",c=>{for(let l of c)Ht(l)&&(s=Math.max(s,l.duration))}),Q("paint",c=>{for(let l of c)l.name==="first-contentful-paint"&&r("FCP",l.startTime)})],i=performance.getEntriesByType("navigation")[0];i&&i.responseStart>0&&r("TTFB",i.responseStart);let a=!1,o=()=>{a||(a=!0,e>0&&r("LCP",e),r("CLS",t),s>0&&r("INP",s))},d=()=>{document.visibilityState==="hidden"&&o()};return document.addEventListener("visibilitychange",d),()=>{o(),document.removeEventListener("visibilitychange",d);for(let c of n)c?.disconnect()}}function Jt(r){if(!r)return!1;try{return new Headers(r).has("next-router-prefetch")}catch{return!1}}var zt=/^[a-z][a-z0-9_-]{0,31}$/;function j(r){return r.split("/").map(e=>{if(e==="")return e;let t=e.split(";",1)[0],s=t.toLowerCase();return zt.test(s)&&(s.match(/\d/g)?.length??0)<=2&&t.slice(1)===s.slice(1)&&s.split(/[-_]/).every(i=>i.length<=16)?s:":id"}).join("/")}function Xt(r){if(!r)return"";try{let e=new URL(r);return`${e.origin}${j(e.pathname)}`}catch{return j(r.split(/[?#]/,1)[0]??"")}}var pt=/^custom\.[a-z0-9_]{1,48}$/,Yt=/^[a-z][a-z0-9_]{0,63}$/,nt=r=>Yt.test(r)||pt.test(r),Zt=50,it=[5e3,3e4,12e4,6e5],Qt=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,c]of Object.entries(t.start??{})){if(!nt(d))throw new TypeError(`consent.start: ${JSON.stringify(d)} is not a consent key (a platform key, or custom.<name>)`);if(c!=="granted"&&c!=="denied")throw new TypeError(`consent.start.${d} is granted or denied`)}for(let d of t.customKeys??[])if(!pt.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(),n=()=>et(this.installation)?{}:{unknown:{on:!0,w:this.stamp()}},i={whose:null,install:this.installation.id,choices:{},unsent:[]};typeof s!="object"?this.kept={...i,...s==="unreadable"?{unknown:{on:!0,w:this.stamp()}}:n()}:s.whose==null&&s.install!==void 0&&s.install!==this.installation.id?this.kept={...i,unsent:s.unsent.filter(d=>d.user!==null),...s.keys?{keys:s.keys}:{},...n()}:this.kept=s,e.session.onChange((d,c)=>{this.engaged&&(d==="SIGNED_IN"&&c?this.signedIn(c):(d==="SIGNED_OUT"||d==="SESSION_EXPIRED")&&this.signedOut())});let a=globalThis;typeof a.addEventListener=="function"&&(a.addEventListener("storage",d=>{(d.key===this.storeKey||d.key===null)&&this.reload()}),a.addEventListener("online",()=>{this.engaged&&this.send()}));let o=this.kept;(e.options!==void 0||s!=="empty"&&(o.unknown?.on||o.unsent.length>0||o.link!==void 0||Object.keys(o.choices).length>0))&&this.engage()}async keys(){return this.engage(),[...(await this.platform()).map(t=>({key:t.key,category:t.category,title:{...t.title},description:{...t.description},ads:t.ads})),...this.customKeys.map(t=>({key:t,category:"custom",title:{},description:{},ads:!1}))]}state(e){if(x(this.kept)!==this.holder()||this.gpcRefuses(e))return"denied";let t=at(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[a,o]of t){if(!nt(a))throw new TypeError(`${JSON.stringify(a)} is not a consent key (a platform key, or custom.<name>)`);if(o!=="granted"&&o!=="denied")throw new TypeError(`${a}: a choice is granted or denied`)}if(t.length===0)return;this.engage();let s=this.chosenAt(),n=this.session.snapshot()?.userId??null,i=this.states();for(let[a,o]of t)this.queue({key:a,state:o,source:"app",chosen_at:s,user:n,...this.textVersion!==void 0?{text_version:this.textVersion}:{}});this.commit(i),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),n=await this.platform().catch(()=>this.kept.keys??[]),i=new Set(n.filter(d=>d.ads).map(d=>d.key)),a=this.kept.region?.jurisdiction==="us",o=new Date(this.now());return o.setUTCMonth(o.getUTCMonth()-12),s.filter(d=>{let c=this.kept.choices[d];return a&&i.has(d)&&c?.last_denied_at!==void 0&&Date.parse(c.last_denied_at)>o.getTime()?!1:!c||c.state==="unset"?!0:this.textVersion!==void 0&&c.source==="app"&&c.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{[R]: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 n=this.states(),i={};for(let h of e.choices)i[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 a=s.filter(h=>i[h.key]?.state!==h.state||Date.parse(i[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,f])=>A(h,f)):[];if(a.length+d.length>0&&(this.kept={...this.kept,void:C([...this.kept.void??[],...a,...d])}),t===null&&this.kept.resetAt!==void 0)for(let[h,f]of Object.entries(i))Date.parse(f.chosen_at)<this.kept.resetAt&&delete i[h];let c=new Set(Object.entries(i).map(([h,f])=>A(h,f))),l=(this.kept.void??[]).filter(h=>c.has(h));l.length>0&&(this.kept={...this.kept,unvoid:C([...this.kept.unvoid??[],...l])});let g=ft(this.kept),p;if(x(this.kept)!==(t===null?`device:${this.installation.id}`:`user:${t}`))p=i;else{p={};for(let h of[...new Set([...Object.keys(this.kept.choices),...Object.keys(i)])].sort()){let f=this.kept.choices[h],y=f&&!f.provisional&&!g.has(A(h,f))?f:void 0,b=i[h],M=b&&(!y||Date.parse(b.chosen_at)>=Date.parse(y.chosen_at))?b:y;M&&(p[h]=M)}}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 f=p[h.key];f&&Date.parse(f.chosen_at)>Date.parse(h.chosen_at)||(p[h.key]=rt(h,f))}let{install:k,..._}=this.kept;this.kept={..._,whose:t,...t===null?{install:this.installation.id}:{},choices:p,unknown:{on:!1,w:this.stamp()}},this.readFor=t,this.stale=!1,this.commit(n),this.refuseByGpc()}async refused(e,t,s){let n=t===e&&x(this.kept)===(t===null?`device:${this.installation.id}`:`user:${t}`),i=C([...this.kept.void??[],...s.map(d=>A(d.key,d))]);if(!n){this.kept={...this.kept,void:i},this.commit();return}let a=this.states(),o={...this.kept.choices};for(let d of s){if(this.kept.unsent.some(l=>l.key===d.key&&(l.user===null||l.user===e)&&Date.parse(l.chosen_at)>Date.parse(d.chosen_at)))continue;let c=o[d.key];o[d.key]={state:"denied",source:"app",chosen_at:d.chosen_at,...c?.last_denied_at!==void 0?{last_denied_at:c.last_denied_at}:{},provisional:!0}}this.kept={...this.kept,choices:o,void:i},this.commit(a);try{await this.read(e)}catch{this.stale=!0}}queue(e){let t=e.user===null?{...e,device:this.installation.id}:e,s=x(this.kept)===(t.user===null?`device:${this.installation.id}`:`user:${t.user}`);this.kept={...this.kept,unsent:gt([...this.kept.unsent,t]),...s?{choices:{...this.kept.choices,[t.key]:rt(t,this.kept.choices[t.key])}}:{}}}send(){if(this.sendAgain=!0,this.sending)return;let e=(async()=>{for(;this.sendAgain;)this.sendAgain=!1,await this.sendUnsent()||(this.sendAgain=!1)})();this.sending=e,e.finally(()=>{this.sending===e&&(this.sending=void 0)})}async sendUnsent(){this.retryTimer&&clearTimeout(this.retryTimer),this.retryTimer=void 0;let e=null;try{e=await this.subject();let t=await this.sendOf(null,e);if(e!==null&&(this.kept.link===e||t)){let s;try{s=(await this.userApi(e).linkConsents({headers:this.secret(),body:{installation_id:this.installation.id}})).data}catch(n){if(!lt(n))throw n}if(this.kept.link===e){let{link:n,...i}=this.kept;this.kept=i,this.commit()}if(s)this.adopt(s,e);else{let n=this.states();this.kept={...this.kept,unknown:{on:!0,w:this.stamp()}},this.commit(n)}}if(e!==null&&await this.sendOf(e,e),this.owesRead()&&(await this.read(e),this.owesRead()))throw new Error("the choices are not read yet");return this.retries=0,!0}catch(t){return t instanceof T&&(this.session.snapshot()?.userId??null)!==e?(this.sendAgain=!0,!0):(this.retryLater(),!1)}}async sendOf(e,t){let s=!1;for(;;){let n=this.nextGroup(e);if(n.length===0)return s;let i=n[0],a=e===null?this.deviceApi:this.userApi(e),o;try{o=(await a.chooseConsents({headers:this.secret(),body:{installation_id:this.installation.id,...i.source==="gpc"?{source:"gpc"}:{},...i.text_version!==void 0?{text_version:i.text_version}:{},choices:n.map(d=>({key:d.key,state:d.state,chosen_at:d.chosen_at}))}})).data}catch(d){if(!lt(d))throw d;if(n.length>1){this.kept={...this.kept,unsent:this.kept.unsent.map(c=>n.some(l=>ct(l,c))?{...c,alone:!0}:c)},this.commit();continue}}this.kept={...this.kept,unsent:this.kept.unsent.filter(d=>!n.some(c=>ct(c,d))),done:C([...this.kept.done??[],...n.map(ne)])},this.commit(),o?(s=!0,e===t&&this.adopt(o,e,n)):await this.refused(t,e,n)}}nextGroup(e){let t=this.kept.unsent.filter(a=>a.user===e&&(e!==null||(a.device??this.installation.id)===this.installation.id)),s=t[0];if(!s)return[];let n=[],i=new Set;if(s.alone)return[s];for(let a of t)if(!i.has(a.key)&&(i.add(a.key),!(a.alone||a.source!==s.source||a.text_version!==s.text_version)&&(n.push(a),n.length===Zt)))break;return n}retryLater(){if(this.retryTimer)return;let e=it[Math.min(this.retries,it.length-1)];this.retries++,this.retryTimer=setTimeout(()=>{this.retryTimer=void 0,this.send()},e),this.retryTimer.unref?.()}signedIn(e){this.readFor=void 0,this.kept={...this.kept,link:e.userId},this.commit(),this.follow(e),this.send()}signedOut(){this.unfollow(),this.readFor=void 0;let e=this.states(),t=this.chosenAt(),s=new Set([...Object.entries(this.kept.choices).filter(([,o])=>o.state!=="unset").map(([o])=>o),...this.kept.unsent.filter(o=>o.user===null&&(o.device??this.installation.id)===this.installation.id).map(o=>o.key),...Object.keys(this.start),...this.customKeys,...(this.kept.keys??[]).map(o=>o.key)]),n={};for(let[o,d]of Object.entries(this.kept.choices))n[o]={state:"unset",source:"app",chosen_at:t,...d.last_denied_at!==void 0?{last_denied_at:d.last_denied_at}:{}};let i=o=>o.user===null&&(o.device??this.installation.id)===this.installation.id,a=this.kept.unsent.filter(i);this.kept={whose:null,install:this.installation.id,resetAt:Date.parse(t),choices:n,unsent:this.kept.unsent.filter(o=>!i(o)),...this.kept.void?{void:this.kept.void}:{},...this.kept.unvoid?{unvoid:this.kept.unvoid}:{},done:C([...this.kept.done??[],...a.map(ne)]),...this.kept.region?{region:this.kept.region}:{},...this.kept.keys?{keys:this.kept.keys}:{},...this.kept.gpc?{gpc:this.kept.gpc}:{},...this.kept.unknown?{unknown:this.kept.unknown}:{}};for(let o of s)this.queue({key:o,state:"unset",source:"app",chosen_at:t,user:null});this.commit(e),this.send(),this.refuseByGpc()}follow(e){this.unfollow();let t=this.socket.channel(`consents:${this.ref}:${e.userId}`),s={userId:e.userId,channel:t,off:()=>{},version:-1},n=[t.on("broadcast",i=>{i.event==="changed"&&this.changed(s,Ie(i.payload))}),t.on("state_snapshot",i=>this.held(s,Ie(ut(i.entries)))),t.on("state_diff",i=>this.held(s,Ie(ut(i.set))))];s.off=()=>n.forEach(i=>i()),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(i=>i.key===e&&i.ads))return!1;let t=at(this.kept,e);if(t?.state==="denied")return!1;let s=this.kept.gpc?.[x(this.kept)],n=s!==void 0&&(this.kept.whose!=null||s>=(this.kept.resetAt??0));return!(t?.state==="granted"&&t.source==="app"&&n&&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(a=>a.ads&&this.gpcRefuses(a.key)&&!this.kept.unsent.some(o=>o.key===a.key&&o.source==="gpc"&&o.user===t));if(s.length===0)return;let n=this.chosenAt(),i=this.states();for(let a of s)this.queue({key:a.key,state:"denied",source:"gpc",chosen_at:n,user:t});this.kept={...this.kept,gpc:{...this.kept.gpc,[x(this.kept)]:Date.parse(n)}},this.commit(i),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 n=t.get(s);if(e.get(s)!==n)for(let i of[...this.listeners])try{i(s,n)}catch{}}}load(){let e;try{e=ht()?.getItem(this.storeKey)}catch{return"unreadable"}if(e==null)return"empty";try{let t=JSON.parse(e);if(ns(t))return t}catch{}return"unreadable"}reload(){let e=this.load();if(typeof e!="object"){this.write();return}let t=this.states();this.kept=ot(e,this.kept,"theirs",this.holder()),x(e)===x(this.kept)&&dt(this.kept)!==dt(e)&&this.write(),this.tell(t);let s=this.session.snapshot()?.userId??null;this.engaged&&this.kept.unsent.some(n=>n.user!==null&&n.user===s||n.user===null&&(n.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=ot(t,this.kept,"ours",this.holder())),this.write(),this.tell(e)}write(){try{ht()?.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 rt(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 ft(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 es(r,e,t,s){let n=e&&!s.has(A(r,e))?e:void 0,i=t&&!s.has(A(r,t))?t:void 0;if(!n||!i)return n??i;let a=Date.parse(n.chosen_at),o=Date.parse(i.chosen_at);return a!==o?a>o?n:i:te[n.state]!==te[i.state]?te[n.state]>te[i.state]?n:i:n.provisional?i:n}function ts(r,e){return!r||!e?r??e:e.w>r.w||e.w===r.w&&e.on?e:r}function ot(r,e,t,s){let n=C([...r.void??[],...e.void??[]]),i=C([...r.unvoid??[],...e.unvoid??[]]),a=ft({void:n,unvoid:i}),o={},d,c={...r.gpc};for(let[y,b]of Object.entries(e.gpc??{}))c[y]=Math.max(c[y]??0,b);let l;if(x(r)===x(e)){d=e;for(let y of[...new Set([...Object.keys(r.choices),...Object.keys(e.choices)])].sort()){let b=es(y,r.choices[y],e.choices[y],a);b&&(o[y]=b)}l=ts(r.unknown,e.unknown)}else{d=x(e)===s?e:x(r)===s?r:t==="ours"?e:r;for(let[y,b]of Object.entries(d.choices))a.has(A(y,b))||(o[y]=b);l=d.unknown}let g=C([...r.done??[],...e.done??[]]),p=gt([...r.unsent,...e.unsent]).filter(y=>!g.includes(ne(y))),k=t==="ours"?e:r,_=t==="ours"?r:e,h=k.region??_.region,f=k.keys??_.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:o,unsent:p,...g.length>0?{done:g}:{},...n.length>0?{void:n}:{},...i.length>0?{unvoid:i}:{},...k.link!==void 0?{link:k.link}:{},...h?{region:h}:{},...Object.keys(c).length>0?{gpc:c}:{},...f?{keys:f}:{},...l?{unknown:l}:{}}}function ne(r){return`${r.user??`device:${r.device??""}`}|${r.key}|${r.state}|${r.source}|${r.chosen_at}`}function at(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 C(r){return[...new Set(r)].slice(-Qt)}function dt(r){return JSON.stringify(r,(e,t)=>typeof t=="object"&&t!==null&&!Array.isArray(t)?Object.fromEntries(Object.entries(t).sort(([s],[n])=>s.localeCompare(n))):t)}function gt(r){let e=new Map;for(let t of r){let s=ne(t),n=e.get(s);e.set(s,n?n.alone||!t.alone?n:{...n,alone:!0}:t)}return[...e.values()].sort((t,s)=>Date.parse(t.chosen_at)-Date.parse(s.chosen_at))}var ss=new Set(["granted","denied","unset"]);function ns(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=(o,d)=>{if(typeof o!="object"||o===null)return!1;let c=o;return ss.has(c.state)&&typeof c.chosen_at=="string"&&(!d||typeof c.key=="string")},s=o=>o===void 0||typeof o=="object"&&o!==null&&typeof o.on=="boolean"&&typeof o.w=="number",n=r,i=o=>o===void 0||Array.isArray(o)&&o.every(d=>typeof d=="string"),a=n.whose===void 0||n.whose===null||typeof n.whose=="string";return Object.values(e.choices).every(o=>t(o,!1))&&e.unsent.every(o=>t(o,!0))&&(n.gpc===void 0||typeof n.gpc=="object"&&n.gpc!==null&&Object.values(n.gpc).every(o=>typeof o=="number"))&&s(n.unknown)&&i(n.done)&&i(n.void)&&i(n.unvoid)&&a}function ct(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 lt(r){return r instanceof S&&r.status>=400&&r.status<500&&r.status!==401&&r.status!==408&&r.status!==429}function ht(){try{return globalThis.localStorage}catch{return}}function ut(r){let e=typeof r=="object"&&r!==null?r.version:void 0;return typeof e=="object"&&e!==null?e.v:void 0}function Ie(r){let e=typeof r=="object"&&r!==null?r.version:void 0;return typeof e=="number"&&Number.isFinite(e)?e:void 0}var is=`
3
+ :host{display:block;color-scheme:light dark;font:15px/1.4 system-ui,-apple-system,"Segoe UI",Roboto,sans-serif}
4
+ .list{display:flex;flex-direction:column;gap:8px;margin:0;padding:0;list-style:none}
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}
6
+ .item:focus-visible{box-shadow:0 0 0 2px var(--accent)}
7
+ .item.unread .title{font-weight:600}
8
+ .item .dot{flex:0 0 8px;height:8px;margin-top:7px;border-radius:50%;background:transparent}
9
+ .item.unread .dot{background:var(--accent)}
10
+ .item img{flex:0 0 48px;width:48px;height:48px;border-radius:8px;object-fit:cover}
11
+ .text{display:flex;flex-direction:column;gap:2px;min-width:0;flex:1 1 auto}
12
+ .title{overflow-wrap:anywhere}
13
+ .body{color:var(--muted);overflow-wrap:anywhere}
14
+ .when{color:var(--muted);font-size:12px}
15
+ .card{position:relative;padding-right:32px;cursor:pointer}
16
+ .card.unread::before{content:"";position:absolute;left:-12px;top:14px;width:8px;height:8px;border-radius:50%;background:var(--accent)}
17
+ .delete{position:absolute;top:8px;right:8px;width:28px;height:28px;border:0;border-radius:14px;background:transparent;color:var(--muted);font-size:18px;line-height:1;cursor:pointer}
18
+ .delete:hover,.delete:focus-visible{background:var(--hover)}
19
+ .empty{padding:24px 12px;text-align:center;color:var(--muted)}
20
+ .light{--bg:#f4f4f6;--fg:#111;--muted:#5c5c66;--accent:#2f6bff;--hover:#0000000f}
21
+ .dark{--bg:#1f1f24;--fg:#f2f2f5;--muted:#a0a0ab;--accent:#5b8cff;--hover:#ffffff14}
22
+ `,ie=class{api;session;constructor(e,t){this.api=K.client(e),this.session=t}async list(e={}){return(await this.api.listMyInbox({query:{limit:e.limit,cursor:e.cursor,locale:e.locale}})).data}async unread(){return(await this.list({limit:1})).unread}async markRead(e){let t=e==="all"?{all:!0}:{ids:[...e]};return(await this.api.readMyInbox({body:t})).data.read}async remove(e){await this.api.deleteMyInboxMessage({path:{id:e}})}mount(e,t={}){let s=e.ownerDocument,n=s.defaultView,i=s.createElement("div");i.setAttribute("data-palbase-inbox","");let a=i.attachShadow({mode:"open"});Fe(s,a,is);let o=s.createElement("ul");o.className="list",a.append(o),e.append(i);let d=()=>t.appearance??(n?.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light"),c=[],l=0,g=[],p=!1,k=u=>{l=u,t.onUnread?.(u)},_=(u,v)=>{u.read_at||(u.read_at=new Date().toISOString(),k(Math.max(0,l-1)),y(),this.markRead([u.id]).catch(()=>{})),!(!v||!$e(v))&&(t.onOpen?t.onOpen(u,v):v.startsWith("https://")?n?.open(v,"_blank","noopener,noreferrer"):n?.location.assign(v))},h=async u=>{c=c.filter(v=>v.id!==u.id),u.read_at||k(Math.max(0,l-1)),y(),await this.remove(u.id).catch(()=>{})},f=u=>{try{return new Intl.DateTimeFormat(t.locale,{dateStyle:"medium",timeStyle:"short"}).format(new Date(u))}catch{return u}};function y(){if(g.forEach(u=>u.destroy()),g=[],o.replaceChildren(),o.className=`list ${d()}`,!c.length){let u=s.createElement("li");u.className="empty",u.textContent=t.labels?.empty??"No messages",o.append(u);return}for(let u of c)o.append(b(u))}let b=u=>{let v=s.createElement("li");v.setAttribute("data-id",u.id),v.tabIndex=0;let m=s.createElement("button");if(m.type="button",m.className="delete",m.textContent="\xD7",m.setAttribute("aria-label",t.labels?.delete??"Delete"),m.addEventListener("click",w=>{w.stopPropagation(),h(u)}),u.card){v.className=`card ${u.read_at?"":"unread"}`;let w=s.createElement("div");v.append(w,m);let P={onAction:()=>_(u,void 0),onDeepLink:I=>_(u,I),onLink:I=>_(u,I),onCustom:t.onCustom};g.push(Ve(w,{definition:u.card,locale:t.locale??n?.navigator.language??"en",appearance:d(),variables:u.variables??{}},P)),v.addEventListener("click",I=>{I.composedPath().some(B=>B instanceof HTMLElement&&B.tagName==="BUTTON")||_(u,u.deep_link)})}else{v.className=`item ${u.read_at?"":"unread"}`;let w=s.createElement("span");if(w.className="dot",v.append(w),u.image?.startsWith("https://")){let I=s.createElement("img");I.src=u.image,I.alt="",v.append(I)}let P=s.createElement("div");P.className="text";for(let[I,B]of[["title",u.title],["body",u.body],["when",f(u.created_at)]]){if(!B)continue;let ke=s.createElement("span");ke.className=I,ke.textContent=B,P.append(ke)}v.append(P,m),v.addEventListener("click",()=>_(u,u.deep_link))}return v.addEventListener("keydown",w=>{w.key==="Enter"&&w.target===v&&_(u,u.deep_link)}),v},M=0,U=async()=>{let u=++M;if(!(await this.session.session())?.userId){if(p||u!==M)return;c=[],k(0),y();return}let v=await this.list({limit:t.limit??50,locale:t.locale});p||u!==M||(c=v.items,k(v.unread),y())},F=()=>{s.visibilityState==="visible"&&U().catch(()=>{})};s.addEventListener("visibilitychange",F);let be=this.session.onChange(()=>{U().catch(()=>{})});return y(),U().catch(()=>{}),{refresh:U,get items(){return c},get unread(){return l},destroy(){p=!0,s.removeEventListener("visibilitychange",F),be?.(),g.forEach(u=>u.destroy()),i.remove()}}}};var rs=30*6e4,re="session_start";function oe(r){try{return r.localStorage}catch{return}}var os=()=>globalThis.crypto?.randomUUID?globalThis.crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;function as(r,e){for(let[t,s]of Object.entries(r??{})){let n=e?.[t];if(n==null||String(n)!==s)return!1}return!0}var ae=class{api;session;installation;g;now;requestPush;analyticsAllowed;purchases;asked=0;person=0;sessionKey;pendingKey;opts;messages=[];limits={per_session:1,per_day:3,min_minutes:10};shown={session:0,day:0,total:0};loaded=Promise.resolve();away=!1;memorySession;memoryPending=[];showing;stopWatching;queue=Promise.resolve();constructor(e,t,s,n,i,a,o,d=globalThis,c=Date.now){this.api=K.client({send:l=>e.send({...l,headers:{...l.headers,[R]:O(s)}})}),this.session=t,this.installation=s,this.requestPush=i,this.analyticsAllowed=a,this.purchases=o,this.g=d,this.now=c,this.sessionKey=`palbase.notify.inapp.session.${n}`,this.pendingKey=`palbase.notify.inapp.conversions.${n}`,t.onChange(l=>{l!=="SIGNED_IN"&&l!=="SIGNED_OUT"&&l!=="SESSION_EXPIRED"||(this.forget(),this.opts&&(this.showing?.message.close(),this.loaded=this.load()))})}get started(){return this.opts!==void 0}start(e={}){let t=!this.opts;if(this.opts=e,!t)return;let s=this.g.document,n=()=>{s?.visibilityState==="visible"?this.enqueue(re,void 0,!0):this.away=!0};s?.addEventListener("visibilitychange",n),this.stopWatching=()=>s?.removeEventListener("visibilitychange",n);let i=this.touch();this.loaded=this.load(),i&&this.trigger(re)}stop(){this.opts=void 0,this.stopWatching?.(),this.stopWatching=void 0,this.showing?.message.close()}refresh(){return this.loaded=this.load(),this.loaded}trigger(e,t){this.enqueue(e,t,!1)}settled(){return this.queue}enqueue(e,t,s){this.queue=this.queue.then(()=>this.take(e,t,s)).catch(()=>{})}async take(e,t,s){if(await this.converted(e),!!this.opts){if(this.touch())this.loaded=this.load(),e!==re&&await this.show(re,void 0);else if(this.away&&(this.loaded=this.load()),s)return;await this.show(e,t)}}async show(e,t){if(await this.loaded,!(!this.opts||this.showing)){for(let s of this.messages)if(!(s.trigger.event!==e||!as(s.trigger.where,t)||this.capped(s))&&await this.open(s))return}}capped(e){let t=this.now(),s=(o,d)=>o!==void 0&&d!==void 0&&t-Date.parse(o)<d*6e4,n=this.shown,i=e.shown,a=e.limits;return n.session>=this.limits.per_session||n.day>=this.limits.per_day||s(n.last_at,this.limits.min_minutes)||a.per_session!==void 0&&i.session>=a.per_session||a.per_day!==void 0&&i.day>=a.per_day||s(i.last_at,a.min_minutes)||a.max_total!==void 0&&i.total>=a.max_total}async open(e){let t=this.opts,s=this.person,n=await this.subject(),i,a;try{({id:i,variables:a}=(await this.api.showInAppMessage({body:{campaign_id:e.campaign_id,session_id:this.sessionId(),installation_id:this.installation.id}})).data)}catch(l){return l instanceof S&&l.status===409&&(this.loaded=this.load()),!1}if(!this.opts||this.showing||s!==this.person)return!0;let o=new Date(this.now()).toISOString();for(let l of[this.shown,e.shown])l.session++,l.day++,l.total++,l.last_at=o;e.conversion&&this.pend({impression:i,campaign:e.campaign_id,event:e.conversion.event,until:this.now()+e.conversion.hours*36e5,subject:n});let d=(l,g)=>{this.api.reportInAppEvent({path:{id:i},query:{installation_id:this.installation.id},body:{type:l,...g?{action:g}:{}}}).catch(()=>{})},c=Be({definition:e.definition,locale:t.locale??this.g.navigator?.language??"en",appearance:t.appearance??this.appearance(),variables:{...e.variables,...a}},{onAction:l=>{l.type!=="close"&&l.type!=="sheet"&&d("clicked",l.type)},onLink:t.onLink,onDeepLink:t.onDeepLink,onCustom:t.onCustom,onShowPaywall:t.onShowPaywall,onOffer:t.onOffer??(l=>this.takeOffer(l,t.onOfferError)),onRequestPush:t.onRequestPush??(()=>this.requestPush().then(()=>{})),labels:t.labels,onClose:l=>{this.showing?.message===c&&(this.showing=void 0),l!=="action"&&l!=="app"&&d("dismissed"),t.onClose?.(e.campaign_id,l)}},t.root?{root:t.root}:{});return this.showing={campaign:e.campaign_id,message:c},t.onShow?.(e.campaign_id),!0}async takeOffer(e,t){try{let s=(await this.purchases.offers()).find(o=>o.key===e);if(s?.kind==="grant"){await this.purchases.claimOffer(e);return}let n=s?.web?.plans[0];if(!s?.product||n===void 0)throw new S({op:"TakeOffer",status:0,code:"offer_not_open",message:`the offer ${e} is not the customer's to take on the web now`});let i=this.g.location,a=await this.purchases.checkout({product:s.product,plan:n,successUrl:i.href,cancelUrl:i.href,offer:e});i.assign(a)}catch(s){if(!t)throw s;t(s,e)}}async converted(e){let t=this.now(),s=this.pending().filter(a=>a.until>t),n=await this.subject(),i=this.analyticsAllowed()?s.filter(a=>a.event===e&&a.subject===n):[];this.keepPending(s.filter(a=>!i.includes(a))),await Promise.all(i.map(a=>this.api.reportInAppEvent({path:{id:a.impression},query:{installation_id:this.installation.id},body:{type:"converted"}}).catch(()=>{})))}forget(){this.person++,this.asked++,this.messages=[],this.shown={session:0,day:0,total:0}}async load(){this.away=!1;let e=++this.asked;try{let t=(await this.api.listMyInAppMessages({query:{session_id:this.sessionId(!1),installation_id:this.installation.id}})).data;if(e!==this.asked)return;this.messages=t.messages,this.limits=t.limits,this.shown=t.shown}catch{}}async subject(){let e=(await this.session.session())?.userId;return e?`u:${e}`:`i:${this.installation.id}`}appearance(){return this.g.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light"}touch(){let e=this.now(),t=this.readSession(),s=!t||e-t.last>=rs;return this.writeSession(s?{id:`ses_${os()}`,last:e}:{id:t.id,last:e}),s}sessionId(e=!0){return e&&this.touch(),(this.readSession()??this.memorySession).id}readSession(){try{let e=oe(this.g)?.getItem(this.sessionKey);if(e)return JSON.parse(e)}catch{}return this.memorySession}writeSession(e){this.memorySession=e;try{oe(this.g)?.setItem(this.sessionKey,JSON.stringify(e))}catch{}}pending(){try{let e=oe(this.g)?.getItem(this.pendingKey);if(e)return JSON.parse(e)}catch{}return this.memoryPending}keepPending(e){this.memoryPending=e;try{let t=oe(this.g);e.length?t?.setItem(this.pendingKey,JSON.stringify(e)):t?.removeItem(this.pendingKey)}catch{}}pend(e){this.keepPending([...this.pending().filter(t=>t.until>this.now()),e].slice(-50))}};var mt=r=>{let e=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(r.length/4)*4,"="),t=atob(e),s=new Uint8Array(t.length);for(let n=0;n<t.length;n++)s[n]=t.charCodeAt(n);return s},Te=class{api;session;installation;baseUrl;publishableKey;g;registered;changing=Promise.resolve();constructor(e,t,s,n,i,a=globalThis){this.api=K.client(e),this.session=t,this.installation=s,this.baseUrl=n,this.publishableKey=i,this.g=a,t.onChange(o=>{(o==="SIGNED_IN"||o==="SIGNED_OUT"||o==="SESSION_EXPIRED")&&(this.registered=void 0,this.changing=this.refresh().catch(()=>this.unsubscribe().catch(()=>{})))})}supported(){return!!this.g.navigator?.serviceWorker&&this.g.PushManager!==void 0&&this.g.Notification!==void 0}permission(){return this.supported()?this.g.Notification.permission:"unsupported"}workerUrl(e="/palbase-sw.js"){let t=new URLSearchParams({url:this.baseUrl,key:this.publishableKey});return`${e}${e.includes("?")?"&":"?"}${t}`}async subscribe(e={}){if(!this.supported())return!1;let t=this.g.Notification;if(t.permission==="default"&&await t.requestPermission()!=="granted"||t.permission==="denied")return!1;let s=this.g.navigator.serviceWorker,n=await s.register(this.workerUrl(e.serviceWorker),e.scope?{scope:e.scope}:void 0);await s.ready;let i=await n.pushManager.getSubscription(),a=(await this.api.getWebPushKey()).data.public_key;return i&&!ds(i.options.applicationServerKey,a)&&(await i.unsubscribe(),i=null),i??=await n.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:mt(a)}),await this.register(i),!0}async unsubscribe(){let e=await this.current();e&&await e.unsubscribe(),this.registered=void 0}async refresh(){if(!this.supported()||this.permission()!=="granted")return;let e=await this.current();e&&await this.register(e)}async current(){let e=this.g.navigator?.serviceWorker;return e?await(await e.getRegistration())?.pushManager.getSubscription()??null:null}async register(e){let t=e.toJSON(),s={endpoint:t.endpoint??e.endpoint,keys:{p256dh:t.keys?.p256dh??"",auth:t.keys?.auth??""}},i=`${this.session.snapshot()?.userId??""}|${s.endpoint}`;this.registered!==i&&(await this.api.registerDevice({headers:{[R]:O(this.installation)},body:{device_id:`web-${this.installation.id}`,token:JSON.stringify(s),platform:"web",locale:this.g.navigator?.language??null,installation_id:this.installation.id,timezone:Intl.DateTimeFormat().resolvedOptions().timeZone}}),this.registered=i)}};function ds(r,e){if(!r)return!1;let t=new Uint8Array(r),s=mt(e);return t.length===s.length&&t.every((n,i)=>n===s[i])}var de=class{push;inbox;inApp;constructor(e,t,s,n,i,a,o){this.push=new Te(e,t,s,a,o),this.inbox=new ie(e,t),this.inApp=new ae(e,t,s,new URL(a).origin,()=>this.push.subscribe(),()=>n.state("analytics")==="granted",i)}};var ce=class{api;session;socket;ref;fetch;appVersion;app;listeners=new Set;watch;following;last;constructor(e,t,s,n,i,a,o){this.api=Ke.client(e),this.session=t,this.socket=s,this.ref=n,this.fetch=i,this.appVersion=a,this.app=o}async me(){let e=this.session.snapshot()?.userId,t=(await this.api.getMyCustomerInfo()).data;return this.watch&&this.watch.userId===e&&this.offer(this.watch,t),t}async offerings(e="web"){return(await this.api.getOfferings({query:{channel:e}})).data}async paywall(e,t={}){return Je(this.api,this.ref,e,s=>this.checkout(s),{signal:t.signal,fetch:this.fetch,attributes:t.attributes,locale:t.locale,appVersion:this.appVersion,app:this.app})}async checkout(e){let t={product:e.product,plan:e.plan,success_url:e.successUrl,cancel_url:e.cancelUrl,source:e.source,...e.offer!==void 0?{offer:e.offer}:{}},s=(await this.api.createCheckout({body:t})).data;return s.redemption_key&&ls(this.keyName(s.session_id),s.redemption_key),s.url}async redemptionLink(e,t={}){let s=t.key??hs(this.keyName(e));if(!s)throw new S({op:"CreateCheckoutRedemption",status:0,code:"redemption_key_missing",message:"no redemption key for this checkout in this tab: the link was sent to the buyer's email"});let n=Date.now()+(t.waitSeconds??20)*1e3;for(;;)try{return(await this.api.createCheckoutRedemption({body:{session_id:e,key:s},signal:t.signal})).data}catch(i){let a=(i instanceof S&&i.code==="checkout_not_paid"?i.retryAfter??2:-1)*1e3;if(a<0||Date.now()+a>n)throw i;await us(a,t.signal)}}async redeem(e){let t=cs(e);if(!t)throw new S({op:"RedeemPurchase",status:0,code:"invalid_redemption_link",message:"not a redemption link: <scheme>://palbase/redeem?token=\u2026 or \u2026/purchases/redeem?token=\u2026"});let s=this.session.snapshot()?.userId,n=(await this.api.redeemPurchase({body:{token:t}})).data;return this.watch&&this.watch.userId===s&&this.offer(this.watch,n),n}async offers(){return(await this.api.listMyOffers()).data.offers}async offerShown(e){await this.api.recordOfferView({path:{offer_key:e}})}async claimOffer(e){return(await this.api.claimOffer({path:{offer_key:e}})).data}async redeemCoupon(e){return(await this.api.redeemCoupon({body:{code:e}})).data}async portal(e){return(await this.api.createPortalSession({body:{return_url:e}})).data.url}async mergeGrant(){return(await this.api.createMergeGrant()).data}async merge(e){let t=this.session.snapshot()?.userId,s=(await this.api.mergeGuest({body:{grant:typeof e=="string"?e:e.grant}})).data;return this.watch&&this.watch.userId===t&&this.offer(this.watch,s),s}async setRefundDataConsent(e){return(await this.api.setRefundDataConsent({body:{consented:e}})).data}keyName(e){return`palbase:${this.ref}:redemption:${e}`}onCustomerInfo(e){if(this.listeners.add(e),this.listeners.size===1)this.start();else if(this.last!==void 0){let t=this.last;queueMicrotask(()=>this.listeners.has(e)&&yt(e,t))}return()=>{this.listeners.delete(e)&&this.listeners.size===0&&this.stop()}}start(){this.following=this.session.onChange((e,t)=>{(e==="SIGNED_IN"||e==="SIGNED_OUT"||e==="SESSION_EXPIRED")&&this.follow(t)}),this.session.session().then(e=>{this.following&&!this.watch&&this.last===void 0&&this.follow(e)})}stop(){this.following?.(),this.following=void 0,this.unfollow(),this.last=void 0}follow(e){if(this.unfollow(),!e){this.tell(null);return}let t=this.socket.channel(`purchases:${this.ref}:${e.userId}`),s={userId:e.userId,channel:t,off:()=>{},revision:-1,reading:!1,wanted:Number.NEGATIVE_INFINITY},n=[t.on("broadcast",i=>{i.event==="changed"&&this.changed(s,Ee(i.payload))}),t.on("state_snapshot",i=>this.held(s,Ee(vt(i.entries)))),t.on("state_diff",i=>this.held(s,Ee(vt(i.set))))];s.off=()=>n.forEach(i=>i()),this.watch=s,t.join().catch(()=>{}),this.read(s)}unfollow(){let e=this.watch;e&&(this.watch=void 0,e.off(),e.channel.leave())}changed(e,t){this.watch!==e||t!==void 0&&t<=e.revision||(e.reading?e.wanted=Math.max(e.wanted,t??Number.POSITIVE_INFINITY):this.read(e))}held(e,t){t!==void 0&&this.changed(e,t)}async read(e){e.reading=!0;try{for(;;){e.wanted=Number.NEGATIVE_INFINITY;try{let t=(await this.api.getMyCustomerInfo()).data;if(this.watch!==e)return;this.offer(e,t)}catch{}if(this.watch!==e||e.wanted<=e.revision)return}}finally{e.reading=!1}}offer(e,t){this.watch!==e||t.revision<=e.revision||(e.revision=t.revision,this.tell(t))}tell(e){if(!(this.last===null&&e===null)){this.last=e;for(let t of[...this.listeners])yt(t,e)}}};function yt(r,e){try{r(e)}catch{}}function vt(r){let e=typeof r=="object"&&r!==null?r.revision:void 0;return typeof e=="object"&&e!==null?e.v:void 0}function Ee(r){let e=typeof r=="object"&&r!==null?r.revision:void 0;return typeof e=="number"&&Number.isFinite(e)?e:void 0}var wt=/^[A-Za-z0-9_-]{43}$/;function cs(r){let e=r.trim();if(wt.test(e))return e;let t;try{t=new URL(e)}catch{return}let s=t.host==="palbase"&&t.pathname==="/redeem",n=(t.protocol==="https:"||t.protocol==="http:")&&t.pathname==="/purchases/redeem",i=t.searchParams.get("token");return(s||n)&&i!==null&&wt.test(i)?i:void 0}function ls(r,e){try{globalThis.sessionStorage?.setItem(r,e)}catch{}}function hs(r){try{return globalThis.sessionStorage?.getItem(r)??void 0}catch{return}}function us(r,e){return new Promise((t,s)=>{if(e?.aborted)return s(e.reason);let n=setTimeout(()=>{e?.removeEventListener("abort",i),t()},r),i=()=>{clearTimeout(n),s(e?.reason)};e?.addEventListener("abort",i,{once:!0})})}var le=class{api;session;socket;installation;ref;analytics;appVersion;storageKey;held;listeners=new Set;started;leave=[];running;queued;fresh=!0;constructor(e,t,s,n,i,a,o,d){this.api=Le.client(e),this.session=t,this.socket=s,this.installation=n,this.ref=i,this.analytics=o,this.appVersion=d,this.storageKey=`palbase.flags.${a}`,this.held=ps(this.storageKey)}value(e){let t=this.mine();if(!t||!Object.hasOwn(t.values,e))return;let s=t.experiments[e];return s&&this.analytics.captureOnce(`$flag_exposure:${e}:${s.experiment_id}`,"$flag_exposure",{flag:e,experiment:s.experiment_id,variant:s.variant}),t.values[e]}bool(e,t){let s=this.value(e);return typeof s=="boolean"?s:t}string(e,t){let s=this.value(e);return typeof s=="string"?s:t}number(e,t){let s=this.value(e);return typeof s=="number"&&Number.isFinite(s)?s:t}json(e,t){let s=this.value(e);return typeof s=="object"&&s!==null?s:t}all(){return{...this.mine()?.values}}source(e){return this.mine()?.sources[e]}get version(){return this.mine()?.syncVersion}onChange(e){return this.listeners.add(e),this.start(),()=>{this.listeners.delete(e)}}refresh(){return this.started?this.read():this.start()}mine(){this.start();let e=this.held;return e&&e.user===(this.session.snapshot()?.userId??null)?e:void 0}start(){if(this.started)return this.started;this.session.onChange((t,s)=>{(t==="SIGNED_IN"||t==="SIGNED_OUT"||t==="SESSION_EXPIRED")&&this.follow(s).catch(()=>{})});let e=this.session.session().then(t=>this.follow(t));return e.catch(()=>{}),this.started=e,e}follow(e){let t=e?.userId??null;if(this.held&&this.held.user!==t){let s=Object.keys(this.held.values);this.held=void 0,bt(this.storageKey,void 0),this.tell(s)}return this.join(t),this.fresh=!0,this.read()}join(e){for(let s of this.leave.splice(0))s();let t=[`flags:${this.ref}`,...e!==null?[`flags:${this.ref}:${e}`]:[]];for(let s of t){let n=this.socket.channel(s),i=[n.on("broadcast",a=>{a.event==="changed"&&this.changed(Me(a.payload))}),n.on("state_snapshot",a=>this.changed(Me(kt(a.entries)))),n.on("state_diff",a=>this.changed(Me(kt(a.set))))];n.join().catch(()=>{}),this.leave.push(()=>{i.forEach(a=>a()),n.leave()})}}changed(e){if(e===void 0)return;let t=this.mine();t&&Number(t.syncVersion)>=e||this.read().catch(()=>{})}read(){if(this.queued)return this.queued;let e=(this.running??Promise.resolve()).catch(()=>{}).then(()=>(this.queued=void 0,this.fetch()));this.queued=e,this.running=e;let t=()=>{this.running===e&&(this.running=void 0)};return e.then(t,t),e}async fetch(){let e=(await this.session.session())?.userId??null,t=this.held?.user===e?this.held:void 0,s=this.headers(e,t?.etag);if(t&&!this.fresh)try{let c=await this.api.getDelta({query:{since:Number(t.syncVersion)},headers:s});if(c.status===304)return;let l={...t,values:{...t.values},sources:{...t.sources},experiments:{...t.experiments},syncVersion:c.data.sync_version,etag:c.headers.get("etag")??t.etag},g=new Set;for(let p of c.data.ops)g.add(p.key),p.op==="delete"?(delete l.values[p.key],delete l.sources[p.key],delete l.experiments[p.key]):(l.values[p.key]=p.value??null,l.sources[p.key]=p.source,p.experiment?l.experiments[p.key]=p.experiment:delete l.experiments[p.key]);this.apply(l,[...g]);return}catch(c){if(!(c instanceof S&&c.status===410))throw c}let n=await this.api.getSnapshot({headers:s});if(this.fresh=!1,n.status===304)return;let i=n.data,a={user:e,values:i.values,sources:i.sources,experiments:i.experiments??{},syncVersion:i.sync_version,contextHash:i.context_hash,etag:n.headers.get("etag")??void 0},o=t?.values??{},d=[...new Set([...Object.keys(o),...Object.keys(a.values)])].filter(c=>JSON.stringify(o[c])!==JSON.stringify(a.values[c]));this.apply(a,d)}headers(e,t){return{"X-Platform":"web",...this.appVersion?{"X-Palbase-Client-Version":this.appVersion}:{},[Y]:this.installation.id,...e===null?{[R]:O(this.installation)}:{},...t?{"If-None-Match":t}:{}}}apply(e,t){if(e.user!==(this.session.snapshot()?.userId??null))return;let s=this.held?.user===e.user?this.held:void 0;s&&!(Number(e.syncVersion)>Number(s.syncVersion)||e.syncVersion===s.syncVersion&&e.contextHash!==s.contextHash)||(this.held=e,bt(this.storageKey,e),t.length>0&&this.tell(t))}tell(e){for(let t of[...this.listeners])try{t(e)}catch{}}};function Re(){try{return globalThis.localStorage}catch{return}}function ps(r){try{let e=Re()?.getItem(r);if(!e)return;let t=JSON.parse(e);return typeof t!="object"||t===null||typeof t.values!="object"||t.values===null||typeof t.syncVersion!="string"?void 0:{user:typeof t.user=="string"?t.user:null,values:t.values,sources:t.sources??{},experiments:t.experiments??{},syncVersion:t.syncVersion,contextHash:t.contextHash??"",...typeof t.etag=="string"?{etag:t.etag}:{}}}catch{return}}function bt(r,e){try{e?Re()?.setItem(r,JSON.stringify(e)):Re()?.removeItem(r)}catch{}}function kt(r){let e=typeof r=="object"&&r!==null?r.sync_version:void 0;return typeof e=="object"&&e!==null?e.v:void 0}function Me(r){let e=typeof r=="object"&&r!==null?r.sync_version:void 0;return typeof e=="number"&&Number.isFinite(e)?e:void 0}var he=class{items=new Map;add(e,t,s){let n={clientMessageId:t.client_message_id,conversationId:e,request:t,state:"pending",attempts:0,error:null,createdAt:s};return this.items.set(n.clientMessageId,n),n}get(e){return this.items.get(e)}all(e){return[...this.items.values()].filter(t=>!e||t.conversationId===e).sort((t,s)=>t.createdAt<s.createdAt?-1:t.createdAt>s.createdAt?1:0)}settle(e,t){return e.sender_id!==t||!e.client_message_id?!1:this.items.delete(e.client_message_id)}retry(e){let t=this.items.get(e);t&&t.state==="failed"&&Object.assign(t,{state:"pending",error:null})}discard(e){return this.items.delete(e)}async flush(e,t){let s=new Map;for(let i of this.all())i.state!=="failed"&&s.set(i.conversationId,[...s.get(i.conversationId)??[],i]);let n=!1;return await Promise.all([...s.values()].map(async i=>{for(let a of i){if(!this.items.has(a.clientMessageId))continue;a.state="sending",a.attempts++;let o;try{o=await e(a)}catch{o={kind:"wait"}}if(o.kind==="wait"){this.items.has(a.clientMessageId)&&(a.state="pending"),n=this.items.has(a.clientMessageId),t(a,o);return}o.kind==="refused"?Object.assign(a,{state:"failed",error:o.code}):this.items.delete(a.clientMessageId),t(a,o)}})),n}save(){return this.all().map(e=>({...e,state:e.state==="sending"?"pending":e.state}))}load(e){this.items.clear();for(let t of e)this.items.set(t.clientMessageId,{...t,state:t.state==="sending"?"pending":t.state})}};function Oe(r,e){if(r===200||r===201)return{kind:"sent",message:e};if(r===202)return{kind:"scheduled",scheduled:e};if(r<400||r>=500||r===408||r===429)return{kind:"wait"};let t=e?.error;return{kind:"refused",code:typeof t=="string"?t:`http_${r}`}}function St(){return{list:!1,conversations:new Set,threads:new Set,scheduled:!1}}var ue=class{reader;cursor=null;conversations=new Map;members=new Map;messages=new Map;threads=new Map;scheduled=new Map;constructor(e){this.reader=e}apply(e){let t=St();for(let s of e.removed_conversations??[])this.drop(s.conversation_id,t);for(let s of e.conversations??[])this.putConversation(s,t);for(let s of e.members??[])this.putMember(s,t);for(let s of e.messages??[])this.putMessage(s,t);for(let s of e.hidden??[])this.messages.get(s.conversation_id)?.delete(s.message_id)&&t.conversations.add(s.conversation_id),this.threads.delete(s.message_id)&&t.threads.add(s.message_id);for(let s of e.threads??[])this.putThread(s,t);for(let s of e.scheduled??[])this.putScheduled(s,t);return t}reset(e){this.conversations.clear(),this.members.clear(),this.messages.clear(),this.threads.clear(),this.scheduled.clear();let t=this.apply(e);return t.list=!0,t.scheduled=!0,t}drop(e,t){this.conversations.delete(e),this.members.delete(e),this.messages.delete(e);for(let[s,n]of this.threads)n.conversation_id===e&&this.threads.delete(s);t.list=!0,t.conversations.add(e)}putConversation(e,t){let s=this.conversations.get(e.id);if(e.deleted){this.drop(e.id,t);return}let n=s?.me&&e.me&&e.me.read_seq<s.me.read_seq?this.readTo(e,e.me,s.me.read_seq):e.me,i=s&&!fs(n,s.me)?s.me:n,a={...e,me:i};if(s){if(e.version<s.version){if(i===s.me)return;a={...s,me:i}}else if(e.version===s.version&&ys(_t(a),s))return}e.gap&&this.messages.delete(e.id);for(let o of e.members??[])this.putMember(o,t);this.conversations.set(e.id,_t(a)),t.list=!0,t.conversations.add(e.id)}putMember(e,t){let s=this.members.get(e.conversation_id);s||(s=new Map,this.members.set(e.conversation_id,s));let n=s.get(e.user_id),i=e;if(n){if(e.version<n.version)return;if(e.version===n.version){let a=gs(n.read_seq,e.read_seq);if(a===n.read_seq&&e.delivered_seq<=n.delivered_seq)return;i={...n,read_seq:a,delivered_seq:Math.max(n.delivered_seq,e.delivered_seq)}}}s.set(e.user_id,i),t.conversations.add(e.conversation_id)}putMessage(e,t){let s=this.messages.get(e.conversation_id);s||(s=new Map,this.messages.set(e.conversation_id,s));let n=s.get(e.id);n&&e.version<=n.version||(s.set(e.id,e),t.conversations.add(e.conversation_id),e.thread_id&&t.threads.add(e.thread_id),(e.reply_count>0||n?.reply_count)&&t.threads.add(e.id),t.list=!0)}putThread(e,t){let s=this.threads.get(e.thread_id),n=s&&e.read_seq<s.read_seq?this.threadReadTo(e,s.read_seq):e;s&&n.version<=s.version&&n.unread_count===s.unread_count||(this.threads.set(e.thread_id,n),t.threads.add(e.thread_id))}putScheduled(e,t){let s=this.scheduled.get(e.id);s&&e.version<=s.version||(e.state==="scheduled"?this.scheduled.set(e.id,e):this.scheduled.delete(e.id),t.scheduled=!0)}read(e,t,s){let n=St(),i=this.conversations.get(e),a=i?Math.min(t,i.me?.left_seq??i.last_seq):t;if(s!==void 0){let o=this.threads.get(s);return!o||a<=o.read_seq||(this.threads.set(s,this.threadReadTo(o,a)),n.threads.add(s)),n}return!i?.me||a<=i.me.read_seq||(this.conversations.set(e,{...i,me:this.readTo(i,i.me,a)}),n.list=!0,n.conversations.add(e)),n}readTo(e,t,s){let n=t.left_seq??e.last_seq;if(s>=n)return{...t,read_seq:s,unread_count:0};let i=Math.max(t.read_seq,t.cleared_seq,t.joined_seq),a=this.timeline(e.id).filter(o=>o.seq>i&&o.seq<=s&&o.sender_id!==this.reader&&o.kind!=="system"&&!o.deleted).length;return{...t,read_seq:s,unread_count:Math.max(0,t.unread_count-a)}}threadReadTo(e,t){let s=this.answers(e.conversation_id,e.thread_id).filter(n=>n.seq>e.read_seq&&n.seq<=t&&n.sender_id!==this.reader&&!n.deleted).length;return{...e,read_seq:t,unread_count:Math.max(0,e.unread_count-s)}}expire(e,t){return this.messages.get(e)?.delete(t)??!1}list(){return[...this.conversations.values()].sort(ms)}timeline(e){return[...this.messages.get(e)?.values()??[]].filter(t=>!t.thread_id||t.also_in_conversation).sort((t,s)=>t.seq-s.seq)}answers(e,t){return[...this.messages.get(e)?.values()??[]].filter(s=>s.thread_id===t).sort((s,n)=>s.seq-n.seq)}membersOf(e){return[...this.members.get(e)?.values()??[]].sort((t,s)=>t.user_id<s.user_id?-1:t.user_id>s.user_id?1:0)}snapshot(){return{cursor:this.cursor,conversations:[...this.conversations.values()],members:[...this.members.values()].flatMap(e=>[...e.values()]),messages:[...this.messages.values()].flatMap(e=>[...e.values()]),threads:[...this.threads.values()],scheduled:[...this.scheduled.values()]}}load(e){this.reset({conversations:e.conversations,members:e.members,messages:e.messages,threads:e.threads,scheduled:e.scheduled}),this.cursor=e.cursor}};function fs(r,e){return r?e?r.version!==e.version?r.version>e.version:r.read_seq!==e.read_seq?r.read_seq>e.read_seq:r.unread_count!==e.unread_count||r.delivered_seq>e.delivered_seq:!0:!1}function gs(r,e){return r===null?e:e===null?r:Math.max(r,e)}function ms(r,e){let t=r.last_message_at??r.created_at,s=e.last_message_at??e.created_at;return t!==s?t<s?1:-1:r.id<e.id?1:-1}function _t(r){let{members:e,gap:t,...s}=r;return s}function ys(r,e){return JSON.stringify(r)===JSON.stringify(e)}var pe=class{store;outbox=new he;me;constructor(e){this.me=e,this.store=new ue(e)}apply(e){return this.settled(e,this.store.apply(e))}reset(e){return this.settled(e,this.store.reset(e))}settled(e,t){for(let s of e.messages??[])this.outbox.settle(s,this.me)&&t.conversations.add(s.conversation_id);return t}write(e,t,s){return this.outbox.add(e,t,s)}read(e,t,s){let n=t??(s?Math.max(0,...this.store.answers(e,s).map(i=>i.seq)):this.store.conversations.get(e)?.last_seq??0);return{upTo:n,touched:this.store.read(e,n,s)}}sent(e){return e.kind==="sent"?this.apply({messages:[e.message]}):e.kind==="scheduled"?this.apply({scheduled:[e.scheduled]}):null}timeline(e){return this.entries(this.store.timeline(e),this.outbox.all(e).filter(t=>!t.request.thread_id||t.request.also_in_conversation))}answers(e,t){return this.entries(this.store.answers(e,t),this.outbox.all(e).filter(s=>s.request.thread_id===t))}entries(e,t){let s=new Set(e.filter(n=>n.sender_id===this.me&&n.client_message_id).map(n=>n.client_message_id));return[...e.map(n=>({kind:"message",message:n})),...t.filter(n=>!s.has(n.clientMessageId)&&!n.request.send_at).map(n=>({kind:"pending",item:n}))]}kept(){return{store:this.store.snapshot(),outbox:this.outbox.save()}}load(e){this.store.load(e.store),this.outbox.load(e.outbox)}};function fe(){let r=globalThis.crypto?.subtle;if(!r)throw new Error("messaging: this platform has no WebCrypto to encrypt files with");return r}function vs(r){let e="";for(let t of r)e+=String.fromCharCode(t);return btoa(e).replaceAll("+","-").replaceAll("/","_").replace(/=+$/,"")}function ws(r){let e=atob(r.replaceAll("-","+").replaceAll("_","/")+"=".repeat((4-r.length%4)%4)),t=new Uint8Array(e.length);for(let s=0;s<e.length;s++)t[s]=e.charCodeAt(s);return t}async function xt(r){let e=crypto.getRandomValues(new Uint8Array(32)),t=crypto.getRandomValues(new Uint8Array(12));return{sealed:await bs(r,e,t),fileKey:vs(e)}}async function bs(r,e,t){let s=await fe().importKey("raw",e,"AES-GCM",!1,["encrypt"]),n=new Uint8Array(await fe().encrypt({name:"AES-GCM",iv:t},s,r)),i=new Uint8Array(1+t.length+n.length);return i[0]=1,i.set(t,1),i.set(n,1+t.length),i}async function Pt(r,e){if(r.length<29||r[0]!==1)throw new Error("messaging: not a file this SDK sealed");let t=await fe().importKey("raw",ws(e),"AES-GCM",!1,["decrypt"]);return new Uint8Array(await fe().decrypt({name:"AES-GCM",iv:r.subarray(1,13)},t,r.subarray(13)))}function $(r,e){return`palbase.messaging.v1.${r}.${e}`}var ge=class{kv;constructor(e){this.kv=e}async open(e){let t=await this.kv.get(e);if(t===null)return null;try{let s=JSON.parse(t);return s.format===1?{store:s.store,outbox:s.outbox}:null}catch{return null}}async save(e,t){await this.kv.set(e,JSON.stringify({format:1,store:ks(t.store),outbox:t.outbox}))}async drop(e){await this.kv.delete(e)}async dropOthers(e,t){let s=$(e,""),n=$(e,t);for(let i of await this.kv.list())i.startsWith(s)&&i!==n&&await this.kv.delete(i)}};function ks(r){let e=new Map;for(let s of r.messages)e.set(s.conversation_id,[...e.get(s.conversation_id)??[],s]);let t=[...e.values()].flatMap(s=>s.sort((n,i)=>i.seq-n.seq).slice(0,200));return{...r,messages:t}}function It(){let r=new Map;return{async get(e){return r.get(e)??null},async set(e,t){r.set(e,t)},async delete(e){r.delete(e)},async list(){return[...r.keys()]},get keys(){return[...r.keys()]}}}var Ss=500,_s=300,xs=2e3,Tt=6e3,Ps=3e4,Et=[1e3,2e3,5e3,1e4,3e4];function Is(r="palbase.messaging"){let e=globalThis.indexedDB;if(!e)return null;let t=null,s=()=>t??=new Promise((i,a)=>{let o=e.open(r,1);o.onupgradeneeded=()=>o.result.createObjectStore("kv"),o.onsuccess=()=>i(o.result),o.onerror=()=>a(o.error)}),n=(i,a)=>s().then(o=>new Promise((d,c)=>{let l=a(o.transaction("kv",i).objectStore("kv"));l.onsuccess=()=>d(l.result),l.onerror=()=>c(l.error)}));return{get:async i=>await n("readonly",a=>a.get(i))??null,set:async(i,a)=>{await n("readwrite",o=>o.put(a,i))},delete:async i=>{await n("readwrite",a=>a.delete(i))},list:async()=>(await n("readonly",i=>i.getAllKeys())).map(String)}}var me=class{api;local;transportFor;clients=new WeakMap;user=null;engine=null;starting=null;channel=null;off=[];heard=new Set;synced=!1;syncing=null;resync=!1;flushing=null;reflush=!1;retries=0;timers={save:void 0,deliver:void 0,retry:void 0,presence:void 0};delivered=new Map;expiring=new Map;typingBy=new Map;typedAt=new Map;loaded=new Set;earlier=new Map;saving=Promise.resolve();reopeners=new Set;incoming=new Set;session;socket;ref;fetchFn;opts;constructor(e,t,s,n,i,a,o={}){this.transportFor=t,this.session=s,this.socket=n,this.ref=i,this.fetchFn=a,this.opts=o,this.api=Se.client(e),this.local=new ge(o.storage??Is()??It()),s.onChange((c,l)=>{c==="SIGNED_OUT"||c==="SESSION_EXPIRED"?this.end():c==="SIGNED_IN"&&l?.userId!==this.user?this.end().then(async()=>{if(this.heard.size!==0){await this.ready();for(let g of[...this.reopeners])g()}}):c==="SIGNED_IN"&&this.engine&&this.user&&(this.unfollow(),this.follow(this.user),this.sync())});let d=globalThis;d.addEventListener?.("online",()=>this.wake()),d.document?.addEventListener?.("visibilitychange",()=>{d.document?.visibilityState==="visible"&&this.wake()})}async ready(){let e=this.session.snapshot()??await this.session.session();if(!e)throw new S({op:"messaging",status:401,code:"not_signed_in",message:"messaging is the signed-in person's: sign in first"});if(this.engine&&this.user===e.userId)return this.engine;if(this.starting&&this.user===e.userId)return this.starting;this.user=e.userId;let t=e.userId;return this.starting=(async()=>{let s=new pe(t);this.clients.set(s,Se.client(this.transportFor(t)));let n=await this.local.open($(this.ref,t));if(this.user!==t)throw new Error("messaging: the session changed while it started");n&&s.load(n),this.engine=s;for(let i of s.store.messages.values())for(let a of i.values())this.expireAt(a);return this.tell({list:!0,conversations:new Set(s.store.conversations.keys()),threads:new Set,scheduled:!0}),this.follow(t),this.opts.keepOnSignOut||this.local.dropOthers(this.ref,t).catch(()=>{}),this.sync().then(()=>this.flush()),this.presence(s),s})(),this.starting.catch(()=>{this.user===t&&(this.starting=null)}),this.starting}async end(){let e=this.user,t=this.engine;this.unfollow();for(let s of Object.values(this.timers))s&&clearTimeout(s);for(let s of this.expiring.values())clearTimeout(s);if(this.expiring.clear(),this.typingBy.clear(),this.delivered.clear(),this.loaded.clear(),this.earlier.clear(),this.engine=null,this.starting=null,this.user=null,this.synced=!1,e){let s=$(this.ref,e);await this.saving,this.opts.keepOnSignOut&&t?await this.local.save(s,t.kept()):await this.local.drop(s)}this.tell({list:!0,conversations:new Set,threads:new Set,scheduled:!0})}unfollow(){for(let e of this.off.splice(0))e();this.channel?.leave(),this.channel=null}follow(e){let t=this.socket.channel(`messaging:${this.ref}:${e}`);this.channel=t,this.off.push(t.on("broadcast",s=>{this.user===e&&(s.event==="changes"?this.heardLive(s.payload):s.event==="typing"&&this.typed(s.payload))}),t.onJoined(()=>{this.sync()})),t.join().catch(()=>{})}wake(){this.engine&&this.sync().then(()=>this.flush())}sync(){return this.syncing?(this.resync=!0,this.syncing):(this.syncing=(async()=>{try{do{this.resync=!1;let e=this.engine;if(!e)return;let t=(await this.as(e).sync({query:e.store.cursor?{since:e.store.cursor}:{}})).data;if(this.engine!==e)return;let s=t.reset?e.reset(t):e.apply(t),n=t.reset?[...this.loaded]:t.conversations.filter(i=>i.gap&&this.loaded.has(i.id)).map(i=>i.id);t.reset&&this.loaded.clear();for(let i of n)this.loaded.delete(i),this.earlier.delete(i);e.store.cursor=t.cursor,this.after(t,s);for(let i of n)this.openPage(i).catch(()=>{});this.synced||(s.list=!0),this.synced=!0,this.tell(s)}while(this.resync)}finally{this.syncing=null}})(),this.syncing)}onIncoming(e){return this.incoming.add(e),()=>{this.incoming.delete(e)}}heardLive(e){let t=this.engine;if(!t)return;let s=(e.messages??[]).filter(n=>n.version===1&&n.sender_id!==t.me&&!n.deleted&&n.kind!=="system"&&!t.store.messages.get(n.conversation_id)?.has(n.id));this.changed(e,t);for(let n of s)for(let i of[...this.incoming])i(n)}changed(e,t=this.engine){if(!t||t!==this.engine)return;let s=t.apply(e);this.after(e,s),this.tell(s)}after(e,t){for(let s of e.messages??[])this.expireAt(s),s.sender_id!==this.user&&!s.deleted&&(s.thread_id===null||s.also_in_conversation)&&this.delivered.set(s.conversation_id,Math.max(this.delivered.get(s.conversation_id)??0,s.seq));this.delivered.size>0&&(this.timers.deliver??=setTimeout(()=>{this.deliver()},Ss)),(t.list||t.conversations.size>0||t.threads.size>0||t.scheduled)&&this.save()}expireAt(e){let t=e.id,s=this.expiring.get(t);if(s&&clearTimeout(s),this.expiring.delete(t),!e.expires_at||e.deleted)return;let n=Date.parse(e.expires_at)-Date.now(),i=()=>{this.expiring.delete(t),this.engine?.store.expire(e.conversation_id,e.id)&&(this.tell({list:!0,conversations:new Set([e.conversation_id]),threads:new Set(e.thread_id?[e.thread_id]:[]),scheduled:!1}),this.save())};n<=0?i():this.expiring.set(t,setTimeout(i,Math.min(n,2**31-1)))}async deliver(){this.timers.deliver=void 0;let e=[...this.delivered].map(([t,s])=>({conversation_id:t,delivered_seq:s}));if(this.delivered.clear(),!(e.length===0||!this.engine))try{await this.as(this.engine).receipts({body:{receipts:e.slice(0,100)}})}catch{}}save(){this.timers.save??=setTimeout(()=>{this.timers.save=void 0;let e=this.engine,t=this.user;e&&t&&(this.saving=this.saving.then(()=>this.local.save($(this.ref,t),e.kept())).catch(()=>{}))},_s)}flush(){return this.flushing?(this.reflush=!0,this.flushing):(clearTimeout(this.timers.retry),this.timers.retry=void 0,this.flushing=(async()=>{try{let e=!1;do{this.reflush=!1;let t=this.engine;if(!t)return;let s=this.as(t);if(e=await t.outbox.flush(n=>this.post(s,n),(n,i)=>{let a=t.sent(i)??{list:!1,conversations:new Set([n.conversationId]),threads:new Set,scheduled:!1};a.conversations.add(n.conversationId),i.kind==="sent"&&this.after({messages:[i.message]},a),this.save(),this.tell(a)}),this.engine!==t)return}while(this.reflush&&!e);if(e){let t=Et[Math.min(this.retries++,Et.length-1)];this.timers.retry=setTimeout(()=>{this.flush()},t)}else this.retries=0}finally{this.flushing=null}})(),this.flushing)}async post(e,t){try{let s=await e.sendMessage({path:{conversation_id:t.conversationId},body:t.request});return Oe(s.status,s.data)}catch(s){return s instanceof S?s.isNetworkError?{kind:"wait"}:Oe(s.status,{error:s.code}):{kind:"wait"}}}presence(e){let t=()=>{if(this.engine!==e)return;let s=globalThis.document;(!s||s.visibilityState!=="hidden")&&this.as(e).presence().catch(()=>{}),this.timers.presence=setTimeout(t,Ps)};t()}as(e){return this.clients.get(e)}async seat(){let e=await this.ready();return{e,as:this.as(e)}}typed(e){let t=this.typingBy.get(e.conversation_id);t||this.typingBy.set(e.conversation_id,t=new Map),t.set(e.user_id,Date.now()+Tt),this.tell({list:!1,conversations:new Set([e.conversation_id]),threads:new Set,scheduled:!1}),setTimeout(()=>this.tell({list:!1,conversations:new Set([e.conversation_id]),threads:new Set,scheduled:!1}),Tt+50)}tell(e){for(let t of[...this.heard])t(e)}listen(e){return this.heard.add(e),this.ready().catch(()=>{}),()=>{this.heard.delete(e)}}onPerson(e){return this.reopeners.add(e),()=>{this.reopeners.delete(e)}}current(){return this.engine}typingIn(e){let t=Date.now();return[...this.typingBy.get(e)??[]].filter(([s,n])=>n>t&&s!==this.user).map(([s])=>s)}isSynced(){return this.synced}conversations(){return new Ae(this)}conversation(e){return new Ce(this,e)}async direct(e){let{e:t,as:s}=await this.seat(),n=(await s.openDirectConversation({body:{user_id:e}})).data;return this.changed({conversations:[n]},t),this.conversation(n.id)}async group(e){let{e:t,as:s}=await this.seat(),n=(await s.createGroup({body:{title:e.title,member_ids:e.memberIds,description:e.description,photo:e.photo,settings:e.settings}})).data;return this.changed({conversations:[n.conversation]},t),{conversation:this.conversation(n.conversation.id),notAdded:n.not_added}}thread(e,t){return new Ne(this,e,t)}scheduled(){return new Ue(this)}async threads(){let{as:e}=await this.seat();return(await e.listThreads()).data.data}async send(e,t){let{e:s}=await this.seat(),n=typeof t=="string"?{text:t}:t,i=n.files?.length?await this.upload(e,n.files):void 0,a={client_message_id:crypto.randomUUID(),...n.text!==void 0?{text:n.text}:{},...n.mentions?{mentions:n.mentions}:{},...i?{attachments:i}:{},...n.replyTo?{reply_to_id:n.replyTo}:{},...n.threadId?{thread_id:n.threadId}:{},...n.alsoInConversation?{also_in_conversation:!0}:{},...n.expiresIn!==void 0?{expires_in:n.expiresIn,expires_from:n.expiresFrom??"send"}:{},...n.viewOnce?{view_once:{limit:n.viewOnce.limit,...n.viewOnce.seconds?{seconds:n.viewOnce.seconds}:{}}}:{},...n.sendAt?{send_at:n.sendAt.toISOString()}:{}};if(s!==this.engine)throw new T(`the session is no longer ${s.me}'s`);let o=s.write(e,a,new Date().toISOString());return this.tell({list:!1,conversations:new Set([e]),threads:new Set(n.threadId?[n.threadId]:[]),scheduled:!1}),this.save(),this.flush(),o}async upload(e,t){let{as:s}=await this.seat(),n=[];for(let i of t){let a=i.data instanceof Uint8Array?i.data:new Uint8Array(await i.data.arrayBuffer()),{sealed:o,fileKey:d}=await xt(a),c=(await s.createUpload({path:{conversation_id:e},body:{size:o.length}})).data,l=await this.fetchFn(c.url,{method:"PUT",body:o,headers:{"content-type":"application/octet-stream"}});if(!l.ok)throw new S({op:"UploadFile",status:l.status,code:"upload_failed",message:`the file was not uploaded (${l.status})`});n.push({upload_id:c.id,content_type:i.contentType,file_key:d,...i.name?{name:i.name}:{},...i.width?{width:i.width}:{},...i.height?{height:i.height}:{},...i.durationMs?{duration_ms:i.durationMs}:{},...i.thumbnail?{thumbnail:i.thumbnail}:{}})}return n}async open(e,t){let{as:s}=await this.seat(),n=e.attachments.find(a=>a.id===t);if(!n?.file_key)throw new S({op:"OpenFile",status:404,code:"attachment_not_found",message:"no such file of the message, or one seen once"});let i=(await s.attachmentUrl({path:{conversation_id:e.conversation_id,message_id:e.id,attachment_id:n.id}})).data;return{id:n.id,name:n.name,contentType:n.content_type,bytes:await this.bytes(i.url,n.file_key)}}async viewOnce(e){let{as:t}=await this.seat(),s=(await t.viewOnce({path:{conversation_id:e.conversation_id,message_id:e.id}})).data;return Promise.all(s.attachments.map(async n=>({id:n.id,name:null,contentType:n.content_type,bytes:await this.bytes(n.url,n.file_key)})))}async bytes(e,t){let s=await this.fetchFn(e);if(!s.ok)throw new S({op:"OpenFile",status:s.status,code:"download_failed",message:`the file was not read (${s.status})`});return Pt(new Uint8Array(await s.arrayBuffer()),t)}async edit(e,t,s,n){let{e:i,as:a}=await this.seat(),o=(await a.editMessage({path:{conversation_id:e,message_id:t},body:{text:s,...n?{mentions:n}:{}}})).data;return this.changed({messages:[o]},i),o}async remove(e,t,s="everyone"){let{e:n,as:i}=await this.seat(),a=await i.deleteMessage({path:{conversation_id:e,message_id:t},query:{for:s}});a.status===200?this.changed({messages:[a.data]},n):this.changed({hidden:[{conversation_id:e,message_id:t}]},n)}async react(e,t,s,n={}){let{e:i,as:a}=await this.seat(),o=(await a.react({path:{conversation_id:e,message_id:t,emoji:s},body:n.replace?{replace:!0}:{}})).data;return this.changed({messages:[o]},i),o}async unreact(e,t,s){let{e:n,as:i}=await this.seat(),a=(await i.unreact({path:{conversation_id:e,message_id:t,emoji:s}})).data;return this.changed({messages:[a]},n),a}async markRead(e,t,s){let{e:n,as:i}=await this.seat(),{upTo:a,touched:o}=n.read(e,t,s);a<=0||((o.list||o.conversations.size>0||o.threads.size>0)&&(this.tell(o),this.save()),await i.receipts({body:{receipts:[{conversation_id:e,read_seq:a,...s?{thread_id:s}:{}}]}}))}async typing(e,t){let{as:s}=await this.seat(),n=this.typedAt.get(e)??0;Date.now()-n<xs||(this.typedAt.set(e,Date.now()),await s.typing({path:{conversation_id:e},body:t?{thread_id:t}:{}}).catch(()=>{}))}async update(e,t){let{e:s,as:n}=await this.seat(),i=(await n.updateConversation({path:{conversation_id:e},body:t})).data;return this.changed({conversations:[i]},s),i}async close(e){let{e:t,as:s}=await this.seat();if(await s.closeConversation({path:{conversation_id:e}}),t!==this.engine)return;let n=t.store.conversations.get(e)?.me,i=t.store.timeline(e).filter(a=>a.vanish&&a.sender_id!==t.me&&n&&a.seq<=n.read_seq);for(let a of i)t.store.expire(e,a.id);i.length>0&&(this.tell({list:!0,conversations:new Set([e]),threads:new Set,scheduled:!1}),this.save())}async screenshot(e){let{e:t,as:s}=await this.seat(),n=(await s.reportScreenshot({path:{conversation_id:e}})).data;return this.changed({messages:[n]},t),n}async leave(e){let{e:t,as:s}=await this.seat();await s.removeMember({path:{conversation_id:e,user_id:t.me}}),this.sync()}async deleteConversation(e){let{e:t,as:s}=await this.seat();await s.deleteConversation({path:{conversation_id:e}}),this.changed({removed_conversations:[{conversation_id:e,reason:"deleted"}]},t)}async notifications(e,t){let{as:s}=await this.seat();await s.setConversationNotifications({path:{conversation_id:e},body:t}),this.sync()}async cancelScheduled(e){let{e:t,as:s}=await this.seat();await s.cancelScheduled({path:{scheduled_id:e}}),t===this.engine&&t.store.scheduled.delete(e)&&(this.tell({list:!1,conversations:new Set,threads:new Set,scheduled:!0}),this.save())}async editScheduled(e,t){let{e:s,as:n}=await this.seat(),i=(await n.updateScheduled({path:{scheduled_id:e},body:t})).data;return this.changed({scheduled:[i]},s),i}async me(){let{as:e}=await this.seat();return(await e.getMyProfile()).data}async updateMe(e){let{as:t}=await this.seat(),s=(await t.updateMyProfile({body:e})).data;return e.read_receipts!==void 0&&this.sync(),s}async profiles(e){let{as:t}=await this.seat();return(await t.getProfiles({query:{user_ids:e.join(",")}})).data.data}async block(e){let{as:t}=await this.seat();await t.block({path:{user_id:e}})}async unblock(e){let{as:t}=await this.seat();await t.unblock({path:{user_id:e}})}async report(e){let{as:t}=await this.seat();return(await t.report({body:e})).data}async openPage(e){let{e:t}=await this.seat();this.loaded.has(e)||(this.loaded.add(e),t.store.timeline(e).length>0&&this.synced)||await this.page(e,null)}async page(e,t){let{e:s,as:n}=await this.seat(),i=(await n.listMessages({path:{conversation_id:e},query:t?{cursor:t,limit:50}:{limit:50}})).data;return s!==this.engine?!1:(this.earlier.set(e,i.next_cursor??null),this.changed({messages:i.data},s),!!i.next_cursor)}earlierOf(e){return this.earlier.get(e)}async openThread(e,t){let{e:s,as:n}=await this.seat(),i=(await n.getMessage({path:{conversation_id:e,message_id:t}})).data,a=(await n.listReplies({path:{conversation_id:e,message_id:t},query:{limit:100}})).data;this.changed({messages:[i,...a.data]},s)}async openScheduled(){let{e,as:t}=await this.seat();this.changed({scheduled:(await t.listScheduled()).data.data},e)}},V=class{listeners=new Set;unlisten=null;unperson=null;cached=null;m;constructor(e){this.m=e}get state(){return this.unlisten?this.cached??=this.read():this.read()}subscribe(e){return this.listeners.add(e),this.unlisten||(this.cached=null,this.unlisten=this.m.listen(t=>{if(this.touches(t)){this.cached=this.read();for(let s of[...this.listeners])s()}}),this.unperson=this.m.onPerson(()=>{this.cached=null,this.opened();for(let t of[...this.listeners])t()}),this.opened()),()=>{this.listeners.delete(e),this.listeners.size===0&&(this.unlisten?.(),this.unperson?.(),this.unlisten=null,this.unperson=null)}}opened(){}},Ae=class extends V{touches(e){return e.list||e.conversations.size>0}read(){let e=this.m.current()?.store.list()??[];return{items:e,unread:e.reduce((t,s)=>t+(s.me?.unread_count??0),0),synced:this.m.isSynced()}}},Ce=class extends V{id;constructor(e,t){super(e),this.id=t}opened(){this.m.openPage(this.id).catch(()=>{})}touches(e){return e.conversations.has(this.id)}read(){let e=this.m.current();return{conversation:e?.store.conversations.get(this.id)??null,entries:e?.timeline(this.id)??[],members:e?.store.membersOf(this.id)??[],typing:this.m.typingIn(this.id),hasEarlier:this.m.earlierOf(this.id)!==null}}refresh(){return this.m.page(this.id,null)}async loadEarlier(){let e=this.m.earlierOf(this.id);return e===null?!1:this.m.page(this.id,e??null)}send(e){return this.m.send(this.id,e)}markRead(e){return this.m.markRead(this.id,e)}typing(){return this.m.typing(this.id)}thread(e){return this.m.thread(this.id,e)}},Ne=class extends V{conversationId;rootId;constructor(e,t,s){super(e),this.conversationId=t,this.rootId=s}opened(){this.m.openThread(this.conversationId,this.rootId).catch(()=>{})}touches(e){return e.threads.has(this.rootId)||e.conversations.has(this.conversationId)}read(){let e=this.m.current();return{root:e?.store.messages.get(this.conversationId)?.get(this.rootId)??null,entries:e?.answers(this.conversationId,this.rootId)??[],thread:e?.store.threads.get(this.rootId)??null}}send(e){let t=typeof e=="string"?{text:e}:e;return this.m.send(this.conversationId,{...t,threadId:this.rootId})}markRead(){return this.m.markRead(this.conversationId,void 0,this.rootId)}},Ue=class extends V{opened(){this.m.openScheduled().catch(()=>{})}touches(e){return e.scheduled}read(){return[...this.m.current()?.store.scheduled.values()??[]].sort((e,t)=>e.send_at<t.send_at?-1:1)}};var ye=class{api;open;session;credentials;mfa;passkey;magicLink;phone;password;email;sessions;constructor(e,t,s,n){this.api=L.client(e),this.open=L.client(t),this.session=s,this.credentials=n;let i=this.api,a=this.open;this.mfa={challenge:async(o,d,c)=>this.signedIn((await a.mfaChallenge({body:{mfa_token:o,type:d,code:c}})).data),recovery:async(o,d)=>this.signedIn((await a.mfaRecovery({body:{mfa_token:o,code:d}})).data),sendSmsCode:async o=>{await a.mfaSmsChallenge({body:{mfa_token:o}})},sendEmailCode:async o=>{await a.mfaEmailChallenge({body:{mfa_token:o}})},enrollTotp:async()=>{let o=(await i.mfaEnroll({body:{type:"totp"}})).data;return{enrollmentId:o.enrollment_id,secret:o.secret,otpUrl:o.otp_url,qrCode:o.qr_code,recoveryCodes:o.recovery_codes}},verifyTotp:async o=>{await i.mfaVerifyEnrollment({body:{code:o}})},enrollSms:async o=>(await i.mfaSmsEnroll({body:{phone:o}})).data,verifySms:async o=>{await i.mfaSmsVerifyEnrollment({body:{code:o}})},enrollEmail:async()=>{await i.mfaEmailEnroll()},factors:async()=>(await i.mfaListFactors()).data,removeFactor:async(o,d)=>{await i.mfaRemoveFactor({path:{id:o},body:{current_password:d}})},regenerateRecoveryCodes:async()=>(await i.mfaRegenerateRecoveryCodes()).data,stepUp:async o=>this.steppedUp(async()=>(await i.stepUp({body:{method:"totp",code:o}})).data)},this.passkey={register:async o=>{let d=(await i.webauthnRegisterBegin({body:{name:o}})).data,c=await this.authenticator().create({publicKey:Mt(d.options.publicKey)});return(await i.webauthnRegisterFinish({body:Rt(c)})).data},signIn:async(o={})=>{let d=(await a.webauthnLoginBegin({body:o.userId?{user_id:o.userId}:{}})).data,c=await this.authenticator().get({publicKey:De(d.options.publicKey)}),l=await a.webauthnLoginFinish({query:o.userId?{user_id:o.userId}:void 0,body:qe(c)});return this.signedIn(l.data)},signUp:async(o,d)=>{let c=(await a.webauthnSignupBegin({body:{identifier:o,user_name:d}})).data,l=await this.authenticator().create({publicKey:Mt(c.options.publicKey)});await a.webauthnSignupFinish({query:{user_id:c.user_id},body:Rt(l)});let g=(await a.webauthnLoginBegin({body:{user_id:c.user_id}})).data,p=await this.authenticator().get({publicKey:De(g.options.publicKey)});return this.signedIn((await a.webauthnLoginFinish({query:{user_id:c.user_id},body:qe(p)})).data)},stepUp:async()=>this.steppedUp(async()=>{let o=(await i.stepUpWebAuthnBegin()).data,d=await this.authenticator().get({publicKey:De(o.publicKey)});return(await i.stepUp({body:{method:"webauthn",...qe(d)}})).data}),list:async()=>(await i.webauthnListCredentials()).data,remove:async o=>{await i.webauthnDeleteCredential({path:{id:o}})}},this.magicLink={send:async(o,d={})=>{await a.magicLinkRequest({body:{email:o,...d.redirectTo?{redirect_to:d.redirectTo}:{}}})},verify:async o=>this.signedIn((await a.magicLinkVerify({body:{token:o}})).data)},this.phone={sendCode:async o=>(await a.requestPhoneOtp({body:{phone:o,channel:"sms"}})).data,verifyCode:async(o,d)=>this.signInResult((await a.verifyPhoneOtp({body:{phone:o,token:d}})).data)},this.password={requestReset:async(o,d={})=>{await a.passwordResetRequest({body:{email:o,...d.redirectTo?{redirect_to:d.redirectTo}:{}}})},confirmReset:async(o,d)=>{await a.passwordResetConfirm({body:{token:o,new_password:d}})},change:async o=>(await i.passwordChange({body:o})).data,set:async o=>(await i.setPassword({body:o})).data},this.email={verify:async o=>{await a.verifyEmail({body:o})},resendVerification:async o=>(await a.resendVerification({body:{email:o}})).data},this.sessions={list:async()=>(await i.listSessions()).data,revoke:async o=>{await i.revokeSession({path:{id:o}})},revokeAll:async()=>{await i.revokeAllSessions()}}}onAuthStateChange(e){return this.session.onChange(e)}currentSession(){return this.session.session()}get sessionEndReason(){return this.session.endReason}async signUp(e){let t=(await this.open.signup({body:e})).data;return t.access_token&&t.refresh_token&&t.expires_in!==void 0&&await this.session.set({access_token:t.access_token,refresh_token:t.refresh_token,expires_in:t.expires_in},"SIGNED_IN",t.user),t}async signIn(e,t){return this.signInResult((await this.open.login({body:{email:e,password:t}})).data)}async signOut(){try{await this.session.session()&&await this.api.logout()}finally{await this.session.clear("SIGNED_OUT")}}async getUser(){let e=this.session.snapshot(),t=(await this.api.getMe()).data;return await this.session.setUser(t,e),t}async refreshSession(){return this.session.refresh()}async deleteAccount(e){await this.api.deleteAccount(e===void 0?void 0:{body:{password:e}}),await this.session.clear("SIGNED_OUT")}async signInResult(e){return"mfa_required"in e&&e.mfa_required?{mfaRequired:{mfaToken:e.mfa_token,factors:e.factors}}:{user:await this.signedIn(e)}}async setSession(e){return this.signedIn(e)}async signedIn(e){let t=await this.session.set({access_token:e.access_token,refresh_token:e.refresh_token,expires_in:e.expires_in},"SIGNED_IN",e.user);if(e.user)return e.user;let s=(await this.api.verifyTokenUser()).data;return await this.session.setUser(s,t),s}async steppedUp(e){let t=await this.session.session();if(!t)throw new T("a step-up raises the signed-in session: nobody is signed in");let s=await e();if((await this.session.session())?.refreshToken!==t.refreshToken)throw new T("the session changed during the step-up");return this.session.set({access_token:s.access_token,refresh_token:t.refreshToken,expires_in:s.expires_in},"TOKEN_REFRESHED")}authenticator(){if(!this.credentials)throw new Error("passkeys need navigator.credentials (or createClient({ webauthn }))");return this.credentials}},ve=r=>{let e=atob(r.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(r.length/4)*4,"=")),t=new Uint8Array(e.length);for(let s=0;s<e.length;s++)t[s]=e.charCodeAt(s);return t.buffer},N=r=>{if(!r)return;let e=r instanceof ArrayBuffer?new Uint8Array(r):new Uint8Array(r.buffer,r.byteOffset,r.byteLength),t="";for(let s of e)t+=String.fromCharCode(s);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")},Ot=r=>Array.isArray(r)?r.map(e=>({...e,id:ve(String(e.id))})):void 0;function Mt(r){let e=r.user;return{...r,challenge:ve(String(r.challenge)),user:{...e,id:ve(String(e.id))},excludeCredentials:Ot(r.excludeCredentials)}}function De(r){return{...r,challenge:ve(String(r.challenge)),allowCredentials:Ot(r.allowCredentials)}}function Rt(r){let e=r,t=e.response;return{id:e.id,rawId:N(e.rawId),type:"public-key",authenticatorAttachment:e.authenticatorAttachment??void 0,clientExtensionResults:e.getClientExtensionResults?.()??{},response:{clientDataJSON:N(t.clientDataJSON),attestationObject:N(t.attestationObject),transports:t.getTransports?.()}}}function qe(r){let e=r,t=e.response;return{id:e.id,rawId:N(e.rawId),type:"public-key",authenticatorAttachment:e.authenticatorAttachment??void 0,clientExtensionResults:e.getClientExtensionResults?.()??{},response:{clientDataJSON:N(t.clientDataJSON),authenticatorData:N(t.authenticatorData),signature:N(t.signature),userHandle:N(t.userHandle)}}}var Ts=/^pb_[a-z0-9]+_s/,Es=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Ms=new Set(["invalid_token","token_expired","session_expired","session_revoked","missing_token"]),Rs=new Set(["invalid_token","token_reuse","token_expired","session_revoked","session_expired","session_device_changed"]);function Os(r){return r.status===400&&r.code==="invalid_request"}function Jn(r){if(Ts.test(r.publishableKey)||"secretKey"in r)throw new TypeError("a secret key never goes into a client app: palbase/web takes the publishable key (pb_<ref>_c\u2026); servers use palbase/server");let e=/^pb_([a-z0-9]+)_c/.exec(r.publishableKey)?.[1];if(e===void 0)throw new TypeError("publishableKey is the project publishable key (pb_<ref>_c\u2026)");if(r.appId!==void 0&&!Es.test(r.appId))throw new TypeError("appId is the registered app's id, a UUID (settings.appId of palbase apps:sync), not its slug");let t=At(r.language),s=(m,w)=>{let P=r.fetch??globalThis.fetch;if(t===void 0)return P(m,w);let I=new Headers(w?.headers);return I.has("accept-language")||I.set("accept-language",t),P(m,{...w,headers:I})},n=new URL(r.url).origin,i=r.storage??(Cs()?Xe(`palbase.session.${n}`):ze()),a=r.retry??je,o=H(q({baseUrl:r.url,credentials:{publishableKey:r.publishableKey},fetch:s}),a),d=L.client(o),c=new W(i,async m=>(await d.refreshToken({body:{refresh_token:m}})).data,m=>m instanceof S&&(m.status===401&&Rs.has(m.code)||Os(m)),{lockName:`palbase.session.refresh.${n}`,refresh:r.refresh}),l=q({baseUrl:r.url,credentials:{publishableKey:r.publishableKey,accessToken:()=>c.accessToken()},fetch:s,xmlHttpRequest:r.xmlHttpRequest??(r.fetch===void 0?globalThis.XMLHttpRequest:void 0)}),g=H(we(l,c),a),p=new z({baseUrl:r.url,publishableKey:r.publishableKey,accessToken:()=>c.accessToken(),webSocket:r.webSocket});c.onChange(m=>{m==="SIGNED_OUT"||m==="SESSION_EXPIRED"||m==="SIGNED_IN"?p.disconnect():m==="TOKEN_REFRESHED"&&p.tokenChanged()});let k=new X(n),_=m=>H(we(q({baseUrl:r.url,credentials:{publishableKey:r.publishableKey,accessToken:async()=>{let w=await c.accessToken();if(w===void 0||_e(w)!==m)throw new T(`the session is no longer ${m}'s`);return w}},fetch:s}),c),a),h=m=>L.client(_(m)),f=new se({userApi:h,deviceApi:d,session:c,socket:p,ref:e,installation:k,origin:n,options:r.consent}),y=q({baseUrl:r.url,credentials:{publishableKey:r.publishableKey},fetch:s}),b=new ee(we(l,c),y,c,f,k,n),M=new ce(g,c,p,e,s,r.appVersion,r.appId),U=new de(g,c,k,f,M,r.url,r.publishableKey);b.onEvent((m,w)=>U.inApp.trigger(m,w)),r.analytics&&b.start(r.analytics===!0?{}:r.analytics);let F=new Map,be=m=>{let w=new URL(m).origin,P=F.get(w);return P||(P=H(we(q({baseUrl:w,credentials:{accessToken:()=>c.accessToken()},fetch:s}),c),a),F.set(w,P)),P},u=Ge(g),v=Object.assign(Object.create(He),{auth:new ye(g,o,c,r.webauthn??globalThis.navigator?.credentials),socket:p,transport:g,analytics:b,consent:f,installation:k,purchases:M,notify:U,flags:new le(g,c,p,k,e,n,b,r.appVersion),messaging:new me(g,_,c,p,e,s,r.messaging),setLanguage(m){t=At(m??void 0)},chatToolCall:(m,w,P={})=>u.toolCall(m,w,P.signal),chatWorkspaceFile:(m,w,P,I={})=>u.workspaceFile(m,w,P,I.signal)});return We(v,n,be,g,p,()=>c.snapshot()?.userId),v}var As=/^[A-Za-z]{1,8}(-[A-Za-z0-9]{1,8})*$/;function At(r){if(r===void 0)return;let e=typeof r=="string"?[r]:[...r];if(e.length!==0){for(let t of e)if(!As.test(t))throw new TypeError(`language ${JSON.stringify(t)} is a BCP 47 tag ("tr", "pt-BR")`);return e.map((t,s)=>s===0?t:`${t};q=${Math.max(.1,1-s/10).toFixed(1)}`).join(", ")}}function Cs(){try{return typeof globalThis.localStorage<"u"}catch{return!1}}function we(r,e){return{async send(t){let s=await e.session();try{return await r.send(t)}catch(n){let i=t.auth.some(a=>a.includes("userJWT"));if(!(n instanceof S)||n.status!==401||!Ms.has(n.code)||!i||!s)throw n;try{e.snapshot()?.refreshToken===s.refreshToken&&await e.refresh()}catch{throw n}if(e.snapshot()?.userId!==s.userId)throw n;return r.send(t)}}}}export{T as a,ze as b,Xe as c,xe as d,z as e,X as f,ee as g,se as h,ie as i,re as j,ae as k,Te as l,de as m,ce as n,cs as o,le as p,Is as q,me as r,Ae as s,Ce as t,Ne as u,Ue as v,Jn as w};
@@ -1,5 +1,5 @@
1
- /*! palbase 0.18.2 — Palbase SDK License (see LICENSE) */
2
- import{a as z,f as Q,g as Y,j as Z,k as X,l as ee,o as G,p as te,q as ne}from"./QEBQ452U.js";import{b as M,c as N,d as T}from"./JWBOJ4DZ.js";import{d as A}from"./FWE2RQ74.js";import{a as b,b as V,c as _,e as j}from"./PPIZUQG5.js";var l=class extends Error{kind;code;status;requestId;fields;retryAfter;data;constructor(e,n){super(n.message,n.cause===void 0?void 0:{cause:n.cause}),this.name="BackendError",this.kind=e,this.code=n.code,this.status=n.status??0,this.requestId=n.requestId,this.fields=n.fields,this.retryAfter=n.retryAfter,this.data=n.data}};function oe(t){return t instanceof l||typeof t=="object"&&t!==null&&t.name==="BackendError"&&typeof t.kind=="string"}function q(t){let e=t.body,n={code:t.code,message:t.message,status:t.status,requestId:t.requestId??qe(e,"request_id"),data:E(e,"data"),cause:t};if(t.code==="network_error")return new l("network",n);if(t.status===401&&t.code==="insufficient_user_authentication")return new l("stepUpRequired",n);if(t.status===401&&t.code==="app_attest_required")return new l("attestationRequired",n);if(t.status===401)return new l("unauthorized",n);if(t.status===429)return new l("rateLimited",{...n,retryAfter:Ne(e)??t.retryAfter});let s=Me(e);return t.status===400&&s?new l("validation",{...n,fields:s}):new l("server",n)}function R(t){return t instanceof V||t instanceof Error&&t.name==="PalbaseError"}function se(t){return Array.isArray(t)&&t.length>0&&t.every(e=>typeof e=="object"&&e!==null&&typeof e.field=="string"&&typeof e.message=="string")}function Me(t){let e=E(E(t,"data"),"fields");if(se(e))return e;let n=E(t,"fields");return se(n)?n:void 0}function Ne(t){return re(t,"retry_after")??re(E(t,"data"),"retryAfter")}function E(t,e){if(typeof t=="object"&&t!==null)return t[e]}function re(t,e){let n=E(t,e);return typeof n=="number"?n:void 0}function qe(t,e){let n=E(t,e);return typeof n=="string"?n:void 0}var De=/^[A-Za-z_$][A-Za-z0-9_$]*$/,Ke=Object.freeze(["adoptSession","analytics","appContext","appVersion","auth","callOnSignOut","cancelCallOnSignOut","configuration","consent","currentSession","flags","installation","module","moduleDirectory","notify","onSessionChange","onSignOut","preferences","realtime","scope","send","socket","storage","storedUserId","telemetry","transport","version","palbe","data","stores","purchases","messaging","notifications","perf","debug","equals","hashCode","toString","self","Type","init","deinit","subscript","then","constructor","__proto__"]),Be=new Set(Ke),Le=new Set(["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf","__proto__","__defineGetter__","__defineSetter__","__lookupGetter__","__lookupSetter__"]);function P(t){return t==="then"||t==="toJSON"||Le.has(t)}function ae(t){return t==="call"||t==="join"||P(t)}function ie(t){return typeof t=="string"&&De.test(t)&&!Be.has(t)&&!P(t)}function de(t){return typeof t=="string"&&/^[a-z][a-z0-9-]{0,62}$/.test(t)}function le(t){j(t)}function ce(t){return j(t).origin}var I=class{me;reader;messages=new Map;responses=new Map;order=[];turn=null;goal=null;goalWords=new Set;voiceWords=new Set;voice=null;history=new Map;forkedFrom=null;calls=new Map;taken=[];older=[];oldestLive;olderCursor;olderLeft=!0;loading;chatId;listeners=new Set;enders=new Set;snapshot;told=!1;ended=!1;constructor(e=()=>{},n,s){this.me=e,this.reader=n,this.chatId=s}get hasOlder(){return this.olderLeft}loadOlder(e={}){return this.loading??=this.readOlder(e).finally(()=>this.loading=void 0),this.loading}async readOlder(e){if(!this.olderLeft)return!1;let s={...this.olderCursor!==void 0?{cursor:this.olderCursor}:this.oldestLive!==void 0?{before:this.oldestLive}:{},...e.limit!==void 0?{limit:e.limit}:{},...e.signal?{signal:e.signal}:{}},r;if(e.load)r=await e.load(s);else{let a=this.idFor("loadOlder",e.chatId);if(!this.reader)throw new TypeError("loadOlder: this chat reads its past through the app's way: give load");r=await this.reader.parts(a,s)}if(this.ended)return!1;let o=(r?.parts??[]).map(a=>M(a)).filter(a=>a!==void 0);return this.older=[...o,...this.older],this.olderCursor=r?.nextCursor,this.olderLeft=typeof r?.nextCursor=="string"&&r.nextCursor!=="",this.refold(),this.olderLeft}idFor(e,n){let s=n??this.chatId;if(typeof s!="string"||s==="")throw new TypeError(`${e}: the chat's id is not known yet (no chatId in the join, no message heard): give { chatId }`);return s}refold(){this.messages.clear(),this.responses.clear(),this.order.length=0,this.turn=null,this.goal=null,this.goalWords.clear(),this.voiceWords.clear(),this.voice=null,this.history.clear(),this.forkedFrom=null,this.calls.clear();for(let e of this.older)this.fold(e);for(let e of this.taken)this.fold(e);this.changed()}get state(){return this.snapshot??=this.build()}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}async*[Symbol.asyncIterator](){let e,n,s=this.subscribe(()=>e?.()),r=()=>e?.();this.enders.add(r);try{for(;;){let o=this.state;if(o!==n){n=o,yield o;continue}if(this.ended)return;await new Promise(a=>e=a)}}finally{s(),this.enders.delete(r)}}end(){if(!this.ended){this.ended=!0;for(let e of[...this.enders])e()}}takePayload(e){let n=M(e);n&&this.take(n)}take(e){if(this.ended)return;this.taken.push(e);let n=e.seq;typeof n=="number"&&n>0&&(this.oldestLive===void 0||n<this.oldestLive)&&(this.oldestLive=n),this.fold(e)&&this.changed()}fold(e){switch(e.type){case"message":return this.chatId===void 0&&typeof e.message.chat_id=="string"&&e.message.chat_id!==""&&(this.chatId=e.message.chat_id),this.heard(e.message),!1;case"turn":{let n=this.response(e.response_id);n.status=e.status,n.waiting=e.waiting,n.error=e.error,n.end=typeof e.end=="string"?e.end:null,e.user_id!==void 0&&(n.startedBy=e.user_id),e.goal&&(n.goal={goalId:e.goal.goal_id,role:e.goal.role,seq:e.goal.seq}),this.turn=e;break}case"thinking":{let n=this.response(e.response_id);if(e.seq>0){if(n.thought.has(e.seq))return!1;n.thought.add(e.seq)}if(e.unavailable){n.marks.set("thinking:unavailable",{type:"thinking",text_offset:N(n.text),thinking:{stepId:null,runId:e.run_id,text:"",unavailable:!0,model:e.model??null,reason:e.reason??null}});break}let s=`thinking:${e.step_id??`seq:${e.seq}`}`,r=n.marks.get(s);r?r.thinking={...r.thinking,text:r.thinking.text+e.text}:n.marks.set(s,{type:"thinking",text_offset:N(n.text),thinking:{stepId:e.step_id??null,runId:e.run_id,text:e.text,unavailable:!1,model:null,reason:null}});break}case"goal":if(e.seq>0){if(this.goalWords.has(e.seq))return!1;this.goalWords.add(e.seq)}this.goalSaid(e),this.order.push({type:"goal",event:e});break;case"voice":{let n=`${e.voice_id}\0${e.status}`;if(this.voiceWords.has(n))return!1;this.voiceWords.add(n),(e.status==="closed"?this.voice===null||this.voice.voice_id===e.voice_id:!this.voiceWords.has(`${e.voice_id}\0closed`))&&(this.voice=e),this.order.push({type:"voice",event:e});break}case"transcript":return this.said(e),!1;case"history":e.forked_from&&(this.forkedFrom={chatId:e.forked_from.chat_id,beforeMessage:e.forked_from.before_message}),this.history.set(e.part,e.items);break;case"text":{let n=this.response(e.response_id);n.text=n.text.slice(0,T(n.text,e.offset))+e.text;break}case"reset":{let n=this.response(e.response_id);n.text=n.text.slice(0,T(n.text,e.offset));break}case"tool":{this.response(typeof e.agent_response_id=="string"&&e.agent_response_id!==""?e.agent_response_id:e.response_id).marks.set(`tool:${e.call_id}`,e),this.calls.set(e.call_id,e);break}case"agent":{if(this.response(e.parent_response_id).marks.set(e.run_id?`agent:${e.run_id}`:`agent:seq:${e.seq}`,e),!e.response_id)break;let n=this.response(e.response_id);if(n.runId=e.run_id,n.agent=e.name,n.parentId===null){n.parentId=e.parent_response_id;let s=this.order.findIndex(r=>r.type==="response"&&r.key===e.response_id);s>=0&&this.order.splice(s,1)}break}}return!0}goalSaid(e){if(e.kind==="set"&&e.goal){this.goal={id:e.goal_id,objective:e.goal.objective,rubric:e.goal.rubric,status:e.goal.status,stopCode:e.goal.stop_code,stopReason:e.goal.stop_reason,phase:e.goal.phase,maxTurns:e.goal.max_turns??null,maxCostUsd:e.goal.max_cost_usd??null,events:[e]};return}let n=this.goal;if(!n||n.id!==e.goal_id)return;let s={...n,events:[...n.events,e]};e.kind==="updated"&&e.goal?Object.assign(s,{objective:e.goal.objective,rubric:e.goal.rubric,status:e.goal.status,stopCode:e.goal.stop_code,stopReason:e.goal.stop_reason,phase:e.goal.phase,maxTurns:e.goal.max_turns??null,maxCostUsd:e.goal.max_cost_usd??null}):e.kind==="status_changed"&&typeof e.to=="string"?Object.assign(s,{status:e.to,stopCode:e.code??"",stopReason:e.reason??""}):e.kind==="cleared"&&Object.assign(s,{status:"cleared",stopReason:e.reason??""}),this.goal=s}heard(e){let n=Fe(e),s=this.messages.get(n),r=e.status==="delivered"||e.status==="failed"?e.status:"pending";this.messages.set(n,{clientId:e.client_id,id:e.id??s?.id??null,text:e.text,author:e.author??null,authorName:e.author_name??"",delivery:e.delivery??"next",status:s?.status==="delivered"?"delivered":r,error:e.error??null,responseId:e.response_id??s?.responseId??null,createdAt:e.created_at??s?.createdAt??"",mine:!1,metadata:e.metadata??s?.metadata??{},history:!1,truncated:!1,kind:e.kind??s?.kind??"text",voice:e.voice?{id:e.voice.id,role:e.voice.role}:s?.voice??null,attachments:e.attachments?ue(e.attachments):s?.attachments??[]}),s||this.place(e,n),this.changed()}said(e){let n=`voice\0${e.id}`,s=this.messages.get(n);this.messages.set(n,{clientId:"",id:e.id,text:e.text,author:e.user_id,authorName:e.author_name,delivery:"next",status:"delivered",error:null,responseId:null,createdAt:e.created_at,mine:!1,metadata:{},history:!1,truncated:!1,kind:"voice",voice:{id:e.voice_id,role:e.role},attachments:[]}),s||this.order.push({type:"message",key:n}),this.changed()}place(e,n){let s=e.response_id??null,o=s!==null&&![...this.messages.entries()].some(([a,i])=>a!==n&&i.responseId===s)?this.order.findIndex(a=>a.type==="response"&&a.key===s):-1;o>=0?this.order.splice(o,0,{type:"message",key:n}):this.order.push({type:"message",key:n})}response(e){let n=this.responses.get(e);return n||(n={id:e,status:null,waiting:null,end:null,error:null,text:"",marks:new Map,thought:new Set,runId:null,agent:null,parentId:null,startedBy:void 0,goal:null},this.responses.set(e,n),this.order.push({type:"response",key:e})),n}changed(){this.snapshot=void 0,!this.told&&(this.told=!0,queueMicrotask(()=>{this.told=!1;let e=this.state;for(let n of[...this.listeners])try{n(e)}catch{}}))}build(){let e=this.me(),n=d=>e!==void 0&&d.startedBy===e,s=new Map;for(let d of this.responses.values()){let u=d.parentId!==null?this.responses.get(d.parentId)??d:d;s.set(d.id,We(d,u.startedBy??null,n(u),d.goal??u.goal))}let r=new Map([...this.messages].map(([d,u])=>[d,e!==void 0&&u.author===e?{...u,mine:!0}:u])),o=[...this.history.entries()].sort(([d],[u])=>d-u).flatMap(([d,u])=>u.map((f,m)=>He(f,`${d}:${m}`,e))),a=[...o];for(let d of this.order)d.type==="goal"?a.push({type:"goal",goal:d.event}):d.type==="voice"?a.push({type:"voice",voice:d.event}):d.type==="message"?a.push({type:"message",message:r.get(d.key)}):this.responses.get(d.key).parentId===null&&a.push({type:"response",response:s.get(d.key)});let i=o.flatMap(d=>d.type==="message"?[d.message]:[]),c=o.flatMap(d=>d.type==="response"?[d.response]:[]),p=[...this.calls.values()].filter(d=>s.get(d.response_id)?.mine===!0);return{items:a,messages:[...i,...r.values()],responses:[...c,...s.values()],turn:this.turn,waiting:{approvals:p.filter(d=>d.status==="awaiting_approval"),outputs:p.filter(d=>d.status==="awaiting_output")},goal:this.goal,forkedFrom:this.forkedFrom,voice:this.voice?Je(this.voice,e):null}}};function Je(t,e){return{id:t.voice_id,userId:t.user_id,mine:e!==void 0&&t.user_id===e,delegation:t.delegation,status:t.status,seconds:typeof t.seconds=="number"?t.seconds:null,closeReason:t.close_reason??""}}function ue(t){return t.map((e,n)=>({kind:e.kind,name:e.name,contentType:e.content_type,size:e.size,sha256:e.sha256,position:n,bucket:e.bucket,path:e.path,workspacePath:e.workspace_path??null}))}function Fe(t){return`${t.author??""}\0${t.client_id}`}function We(t,e,n,s){let r=[...t.marks.values()].map((c,p)=>({m:c,i:p,at:T(t.text,Math.max(0,Number(c.text_offset)||0))}));r.sort((c,p)=>c.at-p.at||c.i-p.i);let o=[],a=[],i=0;for(let{m:c,at:p}of r)p>i&&o.push({type:"text",text:t.text.slice(i,p)}),i=Math.max(i,p),c.type==="thinking"?(o.push({type:"thinking",thinking:c.thinking}),a.push(c.thinking)):o.push(c.type==="tool"?{type:"tool",tool:c}:{type:"agent",agent:c});return i<t.text.length&&o.push({type:"text",text:t.text.slice(i)}),{id:t.id,status:t.status,waiting:t.waiting,end:t.end,error:t.error,text:t.text,parts:o,runId:t.runId,agent:t.agent,parentId:t.parentId,startedBy:e,mine:n,thinking:a,goal:s,history:!1,truncated:!1}}function He(t,e,n){let s=t.text_truncated===!0;if(t.role==="user"){let r=t.author??null;return{type:"message",message:{clientId:t.client_id??"",id:t.message_id??null,text:t.text,author:r,authorName:t.author_name??"",delivery:"next",status:"delivered",error:null,responseId:null,createdAt:t.created_at??"",mine:n!==void 0&&r===n,metadata:t.metadata??{},history:!0,truncated:s,kind:"text",voice:null,attachments:ue(t.attachments??[])}}}return{type:"response",response:{id:t.response_id??`history:${e}`,status:"completed",waiting:null,end:"completed",error:null,text:t.text,parts:t.text===""?[]:[{type:"text",text:t.text}],runId:null,agent:null,parentId:null,startedBy:null,mine:!1,thinking:[],goal:null,history:!0,truncated:s}}}var D=[["ApiKeyAuth","userJWT"]];function pe(t){return{async parts(e,n){let s={};n.limit!==void 0&&(s.limit=n.limit),n.cursor!==void 0?s.cursor=n.cursor:n.before!==void 0&&(s.before=n.before);let r=(await t.send({op:"ListChatParts",method:"GET",path:`/ai/chats/${_("ListChatParts","chat_id",e)}/parts`,auth:D,answers:{200:"json"},query:s,signal:n.signal})).data;return r.next_cursor===void 0?{parts:r.parts}:{parts:r.parts,nextCursor:r.next_cursor}},async toolCall(e,n,s){if(typeof n!="string"||n==="")throw new TypeError("chatToolCall: callId is a tool part's call_id");let r=(await t.send({op:"GetChatToolCall",method:"GET",path:`/ai/chats/${_("GetChatToolCall","chat_id",e)}/tool-calls/${_("GetChatToolCall","call_id",n)}`,auth:D,answers:{200:"json"},signal:s})).data;return{callId:r.call_id,name:r.name,status:r.status,runId:r.run_id,responseId:r.response_id,input:r.input,output:r.output,outputBytes:r.output_bytes,imageCount:r.image_count,isError:r.is_error}},async workspaceFile(e,n,s,r){if(typeof n!="string"||n==="")throw new TypeError("chatWorkspaceFile: path is the file as the workspace's tree names it, relative to its root");let o={path:n};return s!==void 0&&(o.manifest=s),(await t.send({op:"GetChatWorkspaceFile",method:"GET",path:`/ai/chats/${_("GetChatWorkspaceFile","chat_id",e)}/workspace/files`,auth:D,answers:{200:"raw"},query:o,signal:r})).data.blob()}}}var $=class extends Error{reason;constructor(e,n){super(e),this.name="GatewayError",this.reason=n}},he=new WeakMap;async function fe(t,e,n,s={},r=()=>{},o){let{pattern:a,events:i,messages:c,durable:p,chat:d}=Ue(e),u=Ve(a,n),f=he.get(t);f||he.set(t,f=new Map);let m=f,g=m.get(u)??{count:0};m.set(u,g),g.count++;let y=t.channel(u,p&&s.history!==!1?{after:0}:{});if(d&&!g.chat){let h=n.chatId,k=new I(r,o,typeof h=="string"&&h!==""?h:void 0);g.chat=k,g.unchat=y.on("broadcast",w=>{w.event==="chat"&&k.takePayload(w.payload)})}let x=()=>{--g.count>0||(m.delete(u),g.unchat?.(),g.chat?.end(),y.leave())};try{await y.join()}catch{let h=y.state==="refused"?ge(y.refusal,"unavailable"):"socket closed";throw x(),new $(`gateway ${JSON.stringify(u)} was not joined: ${h}`,h)}let C=!1,S=new Set,W=()=>{if(!C){C=!0,Ge();for(let h of[...S])h();x()}},Ge=y.onClosed(W),H=h=>{if(C)return()=>{};let k=y.on("broadcast",v=>{typeof v.event=="string"&&i.has(v.event)&&h(v.event,b(v.payload))}),w=()=>{S.delete(w),k()};return S.add(w),w},U={topic:u,get seq(){return y.logSeq},on(h,k){if(typeof h=="function")return H((w,v)=>h({event:w,payload:v}));if(!i.has(h))throw new TypeError(`gateway ${JSON.stringify(a)} declares no event ${JSON.stringify(String(h))}`);if(typeof k!="function")throw new TypeError(`gateway ${JSON.stringify(a)}: on(${JSON.stringify(h)}, \u2026) takes the function the event is handed to`);return H((w,v)=>{w===h&&k(v)})},off(h){S.has(h)&&h()},async send(h,k){if(!c.has(h))throw new TypeError(`gateway ${JSON.stringify(a)} declares no message ${JSON.stringify(String(h))}`);let w=C?{status:"error",response:{reason:"not joined"}}:await y.push("broadcast",{type:"broadcast",event:h,payload:k});if(w.status==="ok")return b(w.response.reply);let v=ge(w.response,"unavailable");throw new $(`gateway ${JSON.stringify(u)} did not take ${JSON.stringify(h)}: ${v}`,v)},leave:W};return d&&Object.defineProperty(U,"chat",{value:g.chat,enumerable:!0}),U}function Ue(t){let e=typeof t=="object"&&t!==null?t:{},n=s=>Array.isArray(s)&&s.every(r=>typeof r=="string");if(typeof e.pattern!="string"||e.pattern===""||!n(e.events)||!n(e.messages))throw new TypeError("join takes a gateway of the backend's generated module: its pattern, its events and its messages");return{pattern:e.pattern,events:new Set(e.events),messages:new Set(e.messages),durable:e.durable===!0,chat:e.chat===!0}}function Ve(t,e){let n=typeof e=="object"&&e!==null?e:{};return t.split(":").map(s=>{if(!(s.startsWith("{")&&s.endsWith("}")&&s.length>2))return s;let r=s.slice(1,-1),o=Object.hasOwn(n,r)?n[r]:void 0;if(typeof o!="string"||o==="")throw new TypeError(`gateway ${JSON.stringify(t)} needs a value for ${JSON.stringify(r)}`);if(o.includes(":"))throw new TypeError(`gateway ${JSON.stringify(t)}: the value of ${JSON.stringify(r)} is one segment of the channel's name and cannot hold ":"`);return o}).join(":")}function ge(t,e){let n=t?.reason;return typeof n=="string"&&n!==""?n:e}var ze=3600*1e3,O=new Map;function Qe(t,e,n=!1){let s=`${e.projectId}\0${e.signer}`,r=O.get(s);if(!n&&r&&Date.now()-r.at<ze)return r.list;let o=(async()=>{let a=te(),i;try{i=(await t.send({op:"GetTransitPublicKeys",method:"GET",path:"/secrets/transit/public",query:{nonce:a},auth:[["ApiKeyAuth"]],answers:{200:"json"}})).data}catch(c){throw new l("network",{code:"encryption_keys_unavailable",message:"the project's encryption keys could not be fetched: no encrypted field is sent without them",cause:c})}try{return await ne(i,e.signer,e.projectId,a)}catch(c){throw new l("decode",{code:"encryption_keys_unverified",message:"the project's list of encryption keys does not verify with the key this app was built with: nothing is sealed to it",cause:c})}})();return O.set(s,{list:o,at:Date.now()}),o.catch(()=>{O.get(s)?.list===o&&O.delete(s)}),o}async function ye(t,e,n,s,r,o){let i=(await Qe(t,e,o)).keys[0];return Y(i.kid,i.key,Q(e.projectId,n,s,r))}function K(t,e,n,s){return e==null||!s||s.length===0?Promise.resolve(e):G(e,n,s,(r,o)=>Z(t.key,r,o))}function me(t,e,n,s){return e===void 0||!n||n.length===0?Promise.resolve(e):G(e,"/response",n,async(r,o)=>{if(!X(o))throw new l("decode",{code:"field_not_encrypted",message:`${s}: ${r} came plain where the backend's contract says it is encrypted`});try{return await ee(t.key,r,o)}catch(a){throw new l("decode",{code:"field_unopenable",message:`${s}: ${r} does not open with this call's key`,cause:a})}})}function we(t){return t instanceof l&&(t.code==="encryption_key_retired"||t.code==="encryption_key_unknown")}var B=class{pending="";dataLines=[];eventName;consume(e){this.pending+=e.replace(/\r\n/g,`
1
+ /*! palbase 0.18.3 — Palbase SDK License (see LICENSE) */
2
+ import{a as z,f as Q,g as Y,j as Z,k as X,l as ee,o as G,p as te,q as ne}from"./7YJBMLWX.js";import{b as M,c as N,d as T}from"./7J76IQQO.js";import{d as A}from"./RLGT4XP5.js";import{a as b,b as V,c as _,e as j}from"./HMFOOFQZ.js";var l=class extends Error{kind;code;status;requestId;fields;retryAfter;data;constructor(e,n){super(n.message,n.cause===void 0?void 0:{cause:n.cause}),this.name="BackendError",this.kind=e,this.code=n.code,this.status=n.status??0,this.requestId=n.requestId,this.fields=n.fields,this.retryAfter=n.retryAfter,this.data=n.data}};function oe(t){return t instanceof l||typeof t=="object"&&t!==null&&t.name==="BackendError"&&typeof t.kind=="string"}function q(t){let e=t.body,n={code:t.code,message:t.message,status:t.status,requestId:t.requestId??qe(e,"request_id"),data:E(e,"data"),cause:t};if(t.code==="network_error")return new l("network",n);if(t.status===401&&t.code==="insufficient_user_authentication")return new l("stepUpRequired",n);if(t.status===401&&t.code==="app_attest_required")return new l("attestationRequired",n);if(t.status===401)return new l("unauthorized",n);if(t.status===429)return new l("rateLimited",{...n,retryAfter:Ne(e)??t.retryAfter});let s=Me(e);return t.status===400&&s?new l("validation",{...n,fields:s}):new l("server",n)}function R(t){return t instanceof V||t instanceof Error&&t.name==="PalbaseError"}function se(t){return Array.isArray(t)&&t.length>0&&t.every(e=>typeof e=="object"&&e!==null&&typeof e.field=="string"&&typeof e.message=="string")}function Me(t){let e=E(E(t,"data"),"fields");if(se(e))return e;let n=E(t,"fields");return se(n)?n:void 0}function Ne(t){return re(t,"retry_after")??re(E(t,"data"),"retryAfter")}function E(t,e){if(typeof t=="object"&&t!==null)return t[e]}function re(t,e){let n=E(t,e);return typeof n=="number"?n:void 0}function qe(t,e){let n=E(t,e);return typeof n=="string"?n:void 0}var De=/^[A-Za-z_$][A-Za-z0-9_$]*$/,Ke=Object.freeze(["adoptSession","analytics","appContext","appVersion","auth","callOnSignOut","cancelCallOnSignOut","configuration","consent","currentSession","flags","installation","module","moduleDirectory","notify","onSessionChange","onSignOut","preferences","realtime","scope","send","socket","storage","storedUserId","telemetry","transport","version","palbe","data","stores","purchases","messaging","notifications","perf","debug","equals","hashCode","toString","self","Type","init","deinit","subscript","then","constructor","__proto__"]),Be=new Set(Ke),Le=new Set(["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf","__proto__","__defineGetter__","__defineSetter__","__lookupGetter__","__lookupSetter__"]);function P(t){return t==="then"||t==="toJSON"||Le.has(t)}function ae(t){return t==="call"||t==="join"||P(t)}function ie(t){return typeof t=="string"&&De.test(t)&&!Be.has(t)&&!P(t)}function de(t){return typeof t=="string"&&/^[a-z][a-z0-9-]{0,62}$/.test(t)}function le(t){j(t)}function ce(t){return j(t).origin}var I=class{me;reader;messages=new Map;responses=new Map;order=[];turn=null;goal=null;goalWords=new Set;voiceWords=new Set;voice=null;history=new Map;forkedFrom=null;calls=new Map;taken=[];older=[];oldestLive;olderCursor;olderLeft=!0;loading;chatId;listeners=new Set;enders=new Set;snapshot;told=!1;ended=!1;constructor(e=()=>{},n,s){this.me=e,this.reader=n,this.chatId=s}get hasOlder(){return this.olderLeft}loadOlder(e={}){return this.loading??=this.readOlder(e).finally(()=>this.loading=void 0),this.loading}async readOlder(e){if(!this.olderLeft)return!1;let s={...this.olderCursor!==void 0?{cursor:this.olderCursor}:this.oldestLive!==void 0?{before:this.oldestLive}:{},...e.limit!==void 0?{limit:e.limit}:{},...e.signal?{signal:e.signal}:{}},r;if(e.load)r=await e.load(s);else{let a=this.idFor("loadOlder",e.chatId);if(!this.reader)throw new TypeError("loadOlder: this chat reads its past through the app's way: give load");r=await this.reader.parts(a,s)}if(this.ended)return!1;let o=(r?.parts??[]).map(a=>M(a)).filter(a=>a!==void 0);return this.older=[...o,...this.older],this.olderCursor=r?.nextCursor,this.olderLeft=typeof r?.nextCursor=="string"&&r.nextCursor!=="",this.refold(),this.olderLeft}idFor(e,n){let s=n??this.chatId;if(typeof s!="string"||s==="")throw new TypeError(`${e}: the chat's id is not known yet (no chatId in the join, no message heard): give { chatId }`);return s}refold(){this.messages.clear(),this.responses.clear(),this.order.length=0,this.turn=null,this.goal=null,this.goalWords.clear(),this.voiceWords.clear(),this.voice=null,this.history.clear(),this.forkedFrom=null,this.calls.clear();for(let e of this.older)this.fold(e);for(let e of this.taken)this.fold(e);this.changed()}get state(){return this.snapshot??=this.build()}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}async*[Symbol.asyncIterator](){let e,n,s=this.subscribe(()=>e?.()),r=()=>e?.();this.enders.add(r);try{for(;;){let o=this.state;if(o!==n){n=o,yield o;continue}if(this.ended)return;await new Promise(a=>e=a)}}finally{s(),this.enders.delete(r)}}end(){if(!this.ended){this.ended=!0;for(let e of[...this.enders])e()}}takePayload(e){let n=M(e);n&&this.take(n)}take(e){if(this.ended)return;this.taken.push(e);let n=e.seq;typeof n=="number"&&n>0&&(this.oldestLive===void 0||n<this.oldestLive)&&(this.oldestLive=n),this.fold(e)&&this.changed()}fold(e){switch(e.type){case"message":return this.chatId===void 0&&typeof e.message.chat_id=="string"&&e.message.chat_id!==""&&(this.chatId=e.message.chat_id),this.heard(e.message),!1;case"turn":{let n=this.response(e.response_id);n.status=e.status,n.waiting=e.waiting,n.error=e.error,n.end=typeof e.end=="string"?e.end:null,e.user_id!==void 0&&(n.startedBy=e.user_id),e.goal&&(n.goal={goalId:e.goal.goal_id,role:e.goal.role,seq:e.goal.seq}),this.turn=e;break}case"thinking":{let n=this.response(e.response_id);if(e.seq>0){if(n.thought.has(e.seq))return!1;n.thought.add(e.seq)}if(e.unavailable){n.marks.set("thinking:unavailable",{type:"thinking",text_offset:N(n.text),thinking:{stepId:null,runId:e.run_id,text:"",unavailable:!0,model:e.model??null,reason:e.reason??null}});break}let s=`thinking:${e.step_id??`seq:${e.seq}`}`,r=n.marks.get(s);r?r.thinking={...r.thinking,text:r.thinking.text+e.text}:n.marks.set(s,{type:"thinking",text_offset:N(n.text),thinking:{stepId:e.step_id??null,runId:e.run_id,text:e.text,unavailable:!1,model:null,reason:null}});break}case"goal":if(e.seq>0){if(this.goalWords.has(e.seq))return!1;this.goalWords.add(e.seq)}this.goalSaid(e),this.order.push({type:"goal",event:e});break;case"voice":{let n=`${e.voice_id}\0${e.status}`;if(this.voiceWords.has(n))return!1;this.voiceWords.add(n),(e.status==="closed"?this.voice===null||this.voice.voice_id===e.voice_id:!this.voiceWords.has(`${e.voice_id}\0closed`))&&(this.voice=e),this.order.push({type:"voice",event:e});break}case"transcript":return this.said(e),!1;case"history":e.forked_from&&(this.forkedFrom={chatId:e.forked_from.chat_id,beforeMessage:e.forked_from.before_message}),this.history.set(e.part,e.items);break;case"text":{let n=this.response(e.response_id);n.text=n.text.slice(0,T(n.text,e.offset))+e.text;break}case"reset":{let n=this.response(e.response_id);n.text=n.text.slice(0,T(n.text,e.offset));break}case"tool":{this.response(typeof e.agent_response_id=="string"&&e.agent_response_id!==""?e.agent_response_id:e.response_id).marks.set(`tool:${e.call_id}`,e),this.calls.set(e.call_id,e);break}case"agent":{if(this.response(e.parent_response_id).marks.set(e.run_id?`agent:${e.run_id}`:`agent:seq:${e.seq}`,e),!e.response_id)break;let n=this.response(e.response_id);if(n.runId=e.run_id,n.agent=e.name,n.parentId===null){n.parentId=e.parent_response_id;let s=this.order.findIndex(r=>r.type==="response"&&r.key===e.response_id);s>=0&&this.order.splice(s,1)}break}}return!0}goalSaid(e){if(e.kind==="set"&&e.goal){this.goal={id:e.goal_id,objective:e.goal.objective,rubric:e.goal.rubric,status:e.goal.status,stopCode:e.goal.stop_code,stopReason:e.goal.stop_reason,phase:e.goal.phase,maxTurns:e.goal.max_turns??null,maxCostUsd:e.goal.max_cost_usd??null,events:[e]};return}let n=this.goal;if(!n||n.id!==e.goal_id)return;let s={...n,events:[...n.events,e]};e.kind==="updated"&&e.goal?Object.assign(s,{objective:e.goal.objective,rubric:e.goal.rubric,status:e.goal.status,stopCode:e.goal.stop_code,stopReason:e.goal.stop_reason,phase:e.goal.phase,maxTurns:e.goal.max_turns??null,maxCostUsd:e.goal.max_cost_usd??null}):e.kind==="status_changed"&&typeof e.to=="string"?Object.assign(s,{status:e.to,stopCode:e.code??"",stopReason:e.reason??""}):e.kind==="cleared"&&Object.assign(s,{status:"cleared",stopReason:e.reason??""}),this.goal=s}heard(e){let n=Fe(e),s=this.messages.get(n),r=e.status==="delivered"||e.status==="failed"?e.status:"pending";this.messages.set(n,{clientId:e.client_id,id:e.id??s?.id??null,text:e.text,author:e.author??null,authorName:e.author_name??"",delivery:e.delivery??"next",status:s?.status==="delivered"?"delivered":r,error:e.error??null,responseId:e.response_id??s?.responseId??null,createdAt:e.created_at??s?.createdAt??"",mine:!1,metadata:e.metadata??s?.metadata??{},history:!1,truncated:!1,kind:e.kind??s?.kind??"text",voice:e.voice?{id:e.voice.id,role:e.voice.role}:s?.voice??null,attachments:e.attachments?ue(e.attachments):s?.attachments??[]}),s||this.place(e,n),this.changed()}said(e){let n=`voice\0${e.id}`,s=this.messages.get(n);this.messages.set(n,{clientId:"",id:e.id,text:e.text,author:e.user_id,authorName:e.author_name,delivery:"next",status:"delivered",error:null,responseId:null,createdAt:e.created_at,mine:!1,metadata:{},history:!1,truncated:!1,kind:"voice",voice:{id:e.voice_id,role:e.role},attachments:[]}),s||this.order.push({type:"message",key:n}),this.changed()}place(e,n){let s=e.response_id??null,o=s!==null&&![...this.messages.entries()].some(([a,i])=>a!==n&&i.responseId===s)?this.order.findIndex(a=>a.type==="response"&&a.key===s):-1;o>=0?this.order.splice(o,0,{type:"message",key:n}):this.order.push({type:"message",key:n})}response(e){let n=this.responses.get(e);return n||(n={id:e,status:null,waiting:null,end:null,error:null,text:"",marks:new Map,thought:new Set,runId:null,agent:null,parentId:null,startedBy:void 0,goal:null},this.responses.set(e,n),this.order.push({type:"response",key:e})),n}changed(){this.snapshot=void 0,!this.told&&(this.told=!0,queueMicrotask(()=>{this.told=!1;let e=this.state;for(let n of[...this.listeners])try{n(e)}catch{}}))}build(){let e=this.me(),n=d=>e!==void 0&&d.startedBy===e,s=new Map;for(let d of this.responses.values()){let u=d.parentId!==null?this.responses.get(d.parentId)??d:d;s.set(d.id,We(d,u.startedBy??null,n(u),d.goal??u.goal))}let r=new Map([...this.messages].map(([d,u])=>[d,e!==void 0&&u.author===e?{...u,mine:!0}:u])),o=[...this.history.entries()].sort(([d],[u])=>d-u).flatMap(([d,u])=>u.map((f,m)=>He(f,`${d}:${m}`,e))),a=[...o];for(let d of this.order)d.type==="goal"?a.push({type:"goal",goal:d.event}):d.type==="voice"?a.push({type:"voice",voice:d.event}):d.type==="message"?a.push({type:"message",message:r.get(d.key)}):this.responses.get(d.key).parentId===null&&a.push({type:"response",response:s.get(d.key)});let i=o.flatMap(d=>d.type==="message"?[d.message]:[]),c=o.flatMap(d=>d.type==="response"?[d.response]:[]),p=[...this.calls.values()].filter(d=>s.get(d.response_id)?.mine===!0);return{items:a,messages:[...i,...r.values()],responses:[...c,...s.values()],turn:this.turn,waiting:{approvals:p.filter(d=>d.status==="awaiting_approval"),outputs:p.filter(d=>d.status==="awaiting_output")},goal:this.goal,forkedFrom:this.forkedFrom,voice:this.voice?Je(this.voice,e):null}}};function Je(t,e){return{id:t.voice_id,userId:t.user_id,mine:e!==void 0&&t.user_id===e,delegation:t.delegation,status:t.status,seconds:typeof t.seconds=="number"?t.seconds:null,closeReason:t.close_reason??""}}function ue(t){return t.map((e,n)=>({kind:e.kind,name:e.name,contentType:e.content_type,size:e.size,sha256:e.sha256,position:n,bucket:e.bucket,path:e.path,workspacePath:e.workspace_path??null}))}function Fe(t){return`${t.author??""}\0${t.client_id}`}function We(t,e,n,s){let r=[...t.marks.values()].map((c,p)=>({m:c,i:p,at:T(t.text,Math.max(0,Number(c.text_offset)||0))}));r.sort((c,p)=>c.at-p.at||c.i-p.i);let o=[],a=[],i=0;for(let{m:c,at:p}of r)p>i&&o.push({type:"text",text:t.text.slice(i,p)}),i=Math.max(i,p),c.type==="thinking"?(o.push({type:"thinking",thinking:c.thinking}),a.push(c.thinking)):o.push(c.type==="tool"?{type:"tool",tool:c}:{type:"agent",agent:c});return i<t.text.length&&o.push({type:"text",text:t.text.slice(i)}),{id:t.id,status:t.status,waiting:t.waiting,end:t.end,error:t.error,text:t.text,parts:o,runId:t.runId,agent:t.agent,parentId:t.parentId,startedBy:e,mine:n,thinking:a,goal:s,history:!1,truncated:!1}}function He(t,e,n){let s=t.text_truncated===!0;if(t.role==="user"){let r=t.author??null;return{type:"message",message:{clientId:t.client_id??"",id:t.message_id??null,text:t.text,author:r,authorName:t.author_name??"",delivery:"next",status:"delivered",error:null,responseId:null,createdAt:t.created_at??"",mine:n!==void 0&&r===n,metadata:t.metadata??{},history:!0,truncated:s,kind:"text",voice:null,attachments:ue(t.attachments??[])}}}return{type:"response",response:{id:t.response_id??`history:${e}`,status:"completed",waiting:null,end:"completed",error:null,text:t.text,parts:t.text===""?[]:[{type:"text",text:t.text}],runId:null,agent:null,parentId:null,startedBy:null,mine:!1,thinking:[],goal:null,history:!0,truncated:s}}}var D=[["ApiKeyAuth","userJWT"]];function pe(t){return{async parts(e,n){let s={};n.limit!==void 0&&(s.limit=n.limit),n.cursor!==void 0?s.cursor=n.cursor:n.before!==void 0&&(s.before=n.before);let r=(await t.send({op:"ListChatParts",method:"GET",path:`/ai/chats/${_("ListChatParts","chat_id",e)}/parts`,auth:D,answers:{200:"json"},query:s,signal:n.signal})).data;return r.next_cursor===void 0?{parts:r.parts}:{parts:r.parts,nextCursor:r.next_cursor}},async toolCall(e,n,s){if(typeof n!="string"||n==="")throw new TypeError("chatToolCall: callId is a tool part's call_id");let r=(await t.send({op:"GetChatToolCall",method:"GET",path:`/ai/chats/${_("GetChatToolCall","chat_id",e)}/tool-calls/${_("GetChatToolCall","call_id",n)}`,auth:D,answers:{200:"json"},signal:s})).data;return{callId:r.call_id,name:r.name,status:r.status,runId:r.run_id,responseId:r.response_id,input:r.input,output:r.output,outputBytes:r.output_bytes,imageCount:r.image_count,isError:r.is_error}},async workspaceFile(e,n,s,r){if(typeof n!="string"||n==="")throw new TypeError("chatWorkspaceFile: path is the file as the workspace's tree names it, relative to its root");let o={path:n};return s!==void 0&&(o.manifest=s),(await t.send({op:"GetChatWorkspaceFile",method:"GET",path:`/ai/chats/${_("GetChatWorkspaceFile","chat_id",e)}/workspace/files`,auth:D,answers:{200:"raw"},query:o,signal:r})).data.blob()}}}var $=class extends Error{reason;constructor(e,n){super(e),this.name="GatewayError",this.reason=n}},he=new WeakMap;async function fe(t,e,n,s={},r=()=>{},o){let{pattern:a,events:i,messages:c,durable:p,chat:d}=Ue(e),u=Ve(a,n),f=he.get(t);f||he.set(t,f=new Map);let m=f,g=m.get(u)??{count:0};m.set(u,g),g.count++;let y=t.channel(u,p&&s.history!==!1?{after:0}:{});if(d&&!g.chat){let h=n.chatId,k=new I(r,o,typeof h=="string"&&h!==""?h:void 0);g.chat=k,g.unchat=y.on("broadcast",w=>{w.event==="chat"&&k.takePayload(w.payload)})}let x=()=>{--g.count>0||(m.delete(u),g.unchat?.(),g.chat?.end(),y.leave())};try{await y.join()}catch{let h=y.state==="refused"?ge(y.refusal,"unavailable"):"socket closed";throw x(),new $(`gateway ${JSON.stringify(u)} was not joined: ${h}`,h)}let C=!1,S=new Set,W=()=>{if(!C){C=!0,Ge();for(let h of[...S])h();x()}},Ge=y.onClosed(W),H=h=>{if(C)return()=>{};let k=y.on("broadcast",v=>{typeof v.event=="string"&&i.has(v.event)&&h(v.event,b(v.payload))}),w=()=>{S.delete(w),k()};return S.add(w),w},U={topic:u,get seq(){return y.logSeq},on(h,k){if(typeof h=="function")return H((w,v)=>h({event:w,payload:v}));if(!i.has(h))throw new TypeError(`gateway ${JSON.stringify(a)} declares no event ${JSON.stringify(String(h))}`);if(typeof k!="function")throw new TypeError(`gateway ${JSON.stringify(a)}: on(${JSON.stringify(h)}, \u2026) takes the function the event is handed to`);return H((w,v)=>{w===h&&k(v)})},off(h){S.has(h)&&h()},async send(h,k){if(!c.has(h))throw new TypeError(`gateway ${JSON.stringify(a)} declares no message ${JSON.stringify(String(h))}`);let w=C?{status:"error",response:{reason:"not joined"}}:await y.push("broadcast",{type:"broadcast",event:h,payload:k});if(w.status==="ok")return b(w.response.reply);let v=ge(w.response,"unavailable");throw new $(`gateway ${JSON.stringify(u)} did not take ${JSON.stringify(h)}: ${v}`,v)},leave:W};return d&&Object.defineProperty(U,"chat",{value:g.chat,enumerable:!0}),U}function Ue(t){let e=typeof t=="object"&&t!==null?t:{},n=s=>Array.isArray(s)&&s.every(r=>typeof r=="string");if(typeof e.pattern!="string"||e.pattern===""||!n(e.events)||!n(e.messages))throw new TypeError("join takes a gateway of the backend's generated module: its pattern, its events and its messages");return{pattern:e.pattern,events:new Set(e.events),messages:new Set(e.messages),durable:e.durable===!0,chat:e.chat===!0}}function Ve(t,e){let n=typeof e=="object"&&e!==null?e:{};return t.split(":").map(s=>{if(!(s.startsWith("{")&&s.endsWith("}")&&s.length>2))return s;let r=s.slice(1,-1),o=Object.hasOwn(n,r)?n[r]:void 0;if(typeof o!="string"||o==="")throw new TypeError(`gateway ${JSON.stringify(t)} needs a value for ${JSON.stringify(r)}`);if(o.includes(":"))throw new TypeError(`gateway ${JSON.stringify(t)}: the value of ${JSON.stringify(r)} is one segment of the channel's name and cannot hold ":"`);return o}).join(":")}function ge(t,e){let n=t?.reason;return typeof n=="string"&&n!==""?n:e}var ze=3600*1e3,O=new Map;function Qe(t,e,n=!1){let s=`${e.projectId}\0${e.signer}`,r=O.get(s);if(!n&&r&&Date.now()-r.at<ze)return r.list;let o=(async()=>{let a=te(),i;try{i=(await t.send({op:"GetTransitPublicKeys",method:"GET",path:"/secrets/transit/public",query:{nonce:a},auth:[["ApiKeyAuth"]],answers:{200:"json"}})).data}catch(c){throw new l("network",{code:"encryption_keys_unavailable",message:"the project's encryption keys could not be fetched: no encrypted field is sent without them",cause:c})}try{return await ne(i,e.signer,e.projectId,a)}catch(c){throw new l("decode",{code:"encryption_keys_unverified",message:"the project's list of encryption keys does not verify with the key this app was built with: nothing is sealed to it",cause:c})}})();return O.set(s,{list:o,at:Date.now()}),o.catch(()=>{O.get(s)?.list===o&&O.delete(s)}),o}async function ye(t,e,n,s,r,o){let i=(await Qe(t,e,o)).keys[0];return Y(i.kid,i.key,Q(e.projectId,n,s,r))}function K(t,e,n,s){return e==null||!s||s.length===0?Promise.resolve(e):G(e,n,s,(r,o)=>Z(t.key,r,o))}function me(t,e,n,s){return e===void 0||!n||n.length===0?Promise.resolve(e):G(e,"/response",n,async(r,o)=>{if(!X(o))throw new l("decode",{code:"field_not_encrypted",message:`${s}: ${r} came plain where the backend's contract says it is encrypted`});try{return await ee(t.key,r,o)}catch(a){throw new l("decode",{code:"field_unopenable",message:`${s}: ${r} does not open with this call's key`,cause:a})}})}function we(t){return t instanceof l&&(t.code==="encryption_key_retired"||t.code==="encryption_key_unknown")}var B=class{pending="";dataLines=[];eventName;consume(e){this.pending+=e.replace(/\r\n/g,`
3
3
  `);let n=[],s=this.pending.indexOf(`
4
4
  `);for(;s!==-1;){let r=this.pending.slice(0,s);this.pending=this.pending.slice(s+1);let o=r.endsWith("\r")?r.slice(0,-1):r;if(o==="")this.dataLines.length>0&&n.push({event:this.eventName,payload:this.dataLines.join(`
5
5
  `)}),this.dataLines=[],this.eventName=void 0;else if(!o.startsWith(":")){if(o.startsWith("data:")){let a=o.slice(5);this.dataLines.push(a.startsWith(" ")?a.slice(1):a)}else if(o.startsWith("event:")){let a=o.slice(6);this.eventName=a.startsWith(" ")?a.slice(1):a}}s=this.pending.indexOf(`
@@ -1,2 +1,2 @@
1
- /*! palbase 0.18.2 — Palbase SDK License (see LICENSE) */
2
- import{b as c,f as u}from"./PPIZUQG5.js";var l={attempts:3,maxWaitSeconds:30},y=new Set([429,502,503,504]);function x(e,t=l){let r=t.sleep??h;return{async send(o){let n=p(o),a=n.body,m=!a||a.kind!=="raw"||u(a.value),f=(n.method==="GET"||n.method==="HEAD"||n.idempotent===!0)&&m;for(let i=1;;i++)try{return await e.send(n)}catch(s){if(!f||i>=t.attempts||!(s instanceof c)||n.signal?.aborted)throw s;let d=b(s,i,t.maxWaitSeconds);if(d===void 0)throw s;await r(d*1e3,n.signal)}}}}function p(e){return e.idempotent?Object.entries(e.headers??{}).some(([r,o])=>r.toLowerCase()==="idempotency-key"&&o!==void 0&&o!==null&&o!=="")?e:{...e,headers:{...e.headers,"Idempotency-Key":w()}}:e}function b(e,t,r){return y.has(e.status)||e.code==="network_error"?e.retryAfter!==void 0?e.retryAfter<=r?e.retryAfter:void 0:Math.min(.5*2**(t-1),r)*(.8+Math.random()*.4):void 0}function h(e,t){return new Promise((r,o)=>{if(t?.aborted)return o(t.reason);let n=()=>{clearTimeout(a),o(t?.reason)},a=setTimeout(()=>{t?.removeEventListener("abort",n),r()},e);t?.addEventListener("abort",n,{once:!0})})}function w(){if(typeof crypto.randomUUID=="function")return crypto.randomUUID();let e=crypto.getRandomValues(new Uint8Array(16));e[6]=e[6]&15|64,e[8]=e[8]&63|128;let t=[...e].map(r=>r.toString(16).padStart(2,"0")).join("");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}export{l as a,x as b,b as c,w as d};
1
+ /*! palbase 0.18.3 — Palbase SDK License (see LICENSE) */
2
+ import{b as c,f as u}from"./HMFOOFQZ.js";var l={attempts:3,maxWaitSeconds:30},y=new Set([429,502,503,504]);function x(e,t=l){let r=t.sleep??h;return{async send(o){let n=p(o),a=n.body,m=!a||a.kind!=="raw"||u(a.value),f=(n.method==="GET"||n.method==="HEAD"||n.idempotent===!0)&&m;for(let i=1;;i++)try{return await e.send(n)}catch(s){if(!f||i>=t.attempts||!(s instanceof c)||n.signal?.aborted)throw s;let d=b(s,i,t.maxWaitSeconds);if(d===void 0)throw s;await r(d*1e3,n.signal)}}}}function p(e){return e.idempotent?Object.entries(e.headers??{}).some(([r,o])=>r.toLowerCase()==="idempotency-key"&&o!==void 0&&o!==null&&o!=="")?e:{...e,headers:{...e.headers,"Idempotency-Key":w()}}:e}function b(e,t,r){return y.has(e.status)||e.code==="network_error"?e.retryAfter!==void 0?e.retryAfter<=r?e.retryAfter:void 0:Math.min(.5*2**(t-1),r)*(.8+Math.random()*.4):void 0}function h(e,t){return new Promise((r,o)=>{if(t?.aborted)return o(t.reason);let n=()=>{clearTimeout(a),o(t?.reason)},a=setTimeout(()=>{t?.removeEventListener("abort",n),r()},e);t?.addEventListener("abort",n,{once:!0})})}function w(){if(typeof crypto.randomUUID=="function")return crypto.randomUUID();let e=crypto.getRandomValues(new Uint8Array(16));e[6]=e[6]&15|64,e[8]=e[8]&63|128;let t=[...e].map(r=>r.toString(16).padStart(2,"0")).join("");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}export{l as a,x as b,b as c,w as d};
@@ -1,2 +1,2 @@
1
- /*! palbase 0.18.2 — Palbase SDK License (see LICENSE) */
2
- import{b}from"./NWFZYTV4.js";import{a as k,b as A}from"./34GIR5XI.js";import{randomBytes as _}from"node:crypto";async function N(){let n={keys:[{id:"k1",key:_(32).toString("base64url"),activates_at:new Date(0).toISOString()}],lookup:_(32).toString("base64url")},e=new b({fetch:async()=>n});return await e.load(),e.close(),e}var f=class extends Error{status;error;data;body;constructor(e,a,l,d){let u=d!==null&&typeof d=="object"?d:{},o=u.error??String(l);super(`${e} ${a} \u2192 ${l} ${o}${u.error_description?`: ${u.error_description}`:""}`),this.name="TestApiError",this.status=l,this.error=o,this.data=u.data,this.body=u}};function x(n,e){if(!n)throw new Error(`${e} is not set: the test client has nowhere to send its requests \u2014 \`palbase test\` sets it, as the platform's test run does`);return n}function B(n){let e=n.split(".")[1];if(!e)return null;try{let a=JSON.parse(Buffer.from(e,"base64url").toString("utf8"));return typeof a.exp=="number"?a.exp-Math.floor(Date.now()/1e3):null}catch{return null}}function L(n){try{return JSON.parse(n)}catch{return n}}function $(n){let e=x(n.baseUrl,"PALBASE_TEST_BASE_URL").replace(/\/+$/,""),a=n.apiKey||void 0,l=(n.authUrl??e).replace(/\/+$/,""),d=n.fetch??fetch,u=[],o=null;async function c(r,t,s,i,T={},O=!0){let g={...T.headers},m=h=>Object.keys(g).some(R=>R.toLowerCase()===h);a!==void 0&&!m("apikey")&&(g.apikey=a),o&&O&&!m("authorization")&&(g.authorization=`Bearer ${o}`),i!==void 0&&!m("content-type")&&(g["content-type"]="application/json");let I=Date.now(),p=await d(`${r}${s}`,{method:t,headers:g,body:i===void 0?void 0:JSON.stringify(i)}),E=await p.text(),S=E?L(E):void 0;if(u.push({method:t,path:s,status:p.status,ms:Date.now()-I}),!p.ok){let h=p.status===401&&o?B(o):null;throw h!==null&&h<=0?new f(t,s,p.status,{error:"access_token_expired",error_description:`this run's access token expired ${-h}s ago: a test user's token is made for one run \u2014 run the tests again (\`palbase test\` makes new ones)`}):new f(t,s,p.status,S)}return S}let y={requests:u,get:(r,t)=>c(e,"GET",r,void 0,t),post:(r,t,s)=>c(e,"POST",r,t,s),patch:(r,t,s)=>c(e,"PATCH",r,t,s),put:(r,t,s)=>c(e,"PUT",r,t,s),delete:(r,t)=>c(e,"DELETE",r,void 0,t),query:(r,t,s)=>c(e,"QUERY",r,t,s),async signInAs(r){let t=n.identities?.[r];if(!t){let s=Object.keys(n.identities??{});throw s.length===0?new Error(`no test user named ${JSON.stringify(r)}: this run has no test users \u2014 none were named (the machine's test users, or \`palbase test --users <names>\`), or they could not be made: the run's log says which`):new Error(`no test user named ${JSON.stringify(r)} \u2014 this run has: ${s.join(", ")}. A run makes the test users its machine names (palbase machines:update <machine> --test-users <names>) or \`palbase test --users <names>\` names`)}return t.accessToken?(o=t.accessToken,{id:t.id??"",email:t.email}):y.signIn(t)},async signIn(r){if(a===void 0)throw new Error("PALBASE_TEST_API_KEY is not set: a sign-in at the project's auth is made with a publishable key of the project's (palbase apps:sdkconfig shows one) \u2014 a run's test users come with their tokens: api.signInAs(name)");let t=i=>c(l,"POST","/auth/login",r,i?{headers:i}:{},!1),s;try{s=await t()}catch(i){let T=i instanceof f&&i.status===403?k(i.body):null;if(!T)throw i;s=await t(await A(T))}return o=s.access_token,s.user??{id:""}},async signOut(){await c(l,"POST","/auth/logout",void 0),o=null},asAnonymous(){o=null}};return y}function P(n){if(!n)return{};let e;try{e=JSON.parse(n)}catch{throw new Error("PALBASE_TEST_IDENTITIES is set but is not JSON: the run that started these tests handed over a broken set of test users")}if(e===null||typeof e!="object"||Array.isArray(e))throw new Error("PALBASE_TEST_IDENTITIES is not an object of test users by name");return e}var j={get stack(){return!!process.env.PALBASE_TEST_BASE_URL},minted(n){return Object.prototype.hasOwnProperty.call(P(process.env.PALBASE_TEST_IDENTITIES),n)}},w,q=new Proxy({},{get(n,e){return w??=$({baseUrl:process.env.PALBASE_TEST_BASE_URL??"",apiKey:process.env.PALBASE_TEST_API_KEY??"",authUrl:process.env.PALBASE_TEST_AUTH_URL,identities:P(process.env.PALBASE_TEST_IDENTITIES)}),Reflect.get(w,e,w)}});export{N as a,f as b,$ as c,j as d,q as e};
1
+ /*! palbase 0.18.3 — Palbase SDK License (see LICENSE) */
2
+ import{b}from"./EBPOLJ27.js";import{a as k,b as A}from"./XYBDQRUX.js";import{randomBytes as _}from"node:crypto";async function N(){let n={keys:[{id:"k1",key:_(32).toString("base64url"),activates_at:new Date(0).toISOString()}],lookup:_(32).toString("base64url")},e=new b({fetch:async()=>n});return await e.load(),e.close(),e}var f=class extends Error{status;error;data;body;constructor(e,a,l,d){let u=d!==null&&typeof d=="object"?d:{},o=u.error??String(l);super(`${e} ${a} \u2192 ${l} ${o}${u.error_description?`: ${u.error_description}`:""}`),this.name="TestApiError",this.status=l,this.error=o,this.data=u.data,this.body=u}};function x(n,e){if(!n)throw new Error(`${e} is not set: the test client has nowhere to send its requests \u2014 \`palbase test\` sets it, as the platform's test run does`);return n}function B(n){let e=n.split(".")[1];if(!e)return null;try{let a=JSON.parse(Buffer.from(e,"base64url").toString("utf8"));return typeof a.exp=="number"?a.exp-Math.floor(Date.now()/1e3):null}catch{return null}}function L(n){try{return JSON.parse(n)}catch{return n}}function $(n){let e=x(n.baseUrl,"PALBASE_TEST_BASE_URL").replace(/\/+$/,""),a=n.apiKey||void 0,l=(n.authUrl??e).replace(/\/+$/,""),d=n.fetch??fetch,u=[],o=null;async function c(r,t,s,i,T={},O=!0){let g={...T.headers},m=h=>Object.keys(g).some(R=>R.toLowerCase()===h);a!==void 0&&!m("apikey")&&(g.apikey=a),o&&O&&!m("authorization")&&(g.authorization=`Bearer ${o}`),i!==void 0&&!m("content-type")&&(g["content-type"]="application/json");let I=Date.now(),p=await d(`${r}${s}`,{method:t,headers:g,body:i===void 0?void 0:JSON.stringify(i)}),E=await p.text(),S=E?L(E):void 0;if(u.push({method:t,path:s,status:p.status,ms:Date.now()-I}),!p.ok){let h=p.status===401&&o?B(o):null;throw h!==null&&h<=0?new f(t,s,p.status,{error:"access_token_expired",error_description:`this run's access token expired ${-h}s ago: a test user's token is made for one run \u2014 run the tests again (\`palbase test\` makes new ones)`}):new f(t,s,p.status,S)}return S}let y={requests:u,get:(r,t)=>c(e,"GET",r,void 0,t),post:(r,t,s)=>c(e,"POST",r,t,s),patch:(r,t,s)=>c(e,"PATCH",r,t,s),put:(r,t,s)=>c(e,"PUT",r,t,s),delete:(r,t)=>c(e,"DELETE",r,void 0,t),query:(r,t,s)=>c(e,"QUERY",r,t,s),async signInAs(r){let t=n.identities?.[r];if(!t){let s=Object.keys(n.identities??{});throw s.length===0?new Error(`no test user named ${JSON.stringify(r)}: this run has no test users \u2014 none were named (the machine's test users, or \`palbase test --users <names>\`), or they could not be made: the run's log says which`):new Error(`no test user named ${JSON.stringify(r)} \u2014 this run has: ${s.join(", ")}. A run makes the test users its machine names (palbase machines:update <machine> --test-users <names>) or \`palbase test --users <names>\` names`)}return t.accessToken?(o=t.accessToken,{id:t.id??"",email:t.email}):y.signIn(t)},async signIn(r){if(a===void 0)throw new Error("PALBASE_TEST_API_KEY is not set: a sign-in at the project's auth is made with a publishable key of the project's (palbase apps:sdkconfig shows one) \u2014 a run's test users come with their tokens: api.signInAs(name)");let t=i=>c(l,"POST","/auth/login",r,i?{headers:i}:{},!1),s;try{s=await t()}catch(i){let T=i instanceof f&&i.status===403?k(i.body):null;if(!T)throw i;s=await t(await A(T))}return o=s.access_token,s.user??{id:""}},async signOut(){await c(l,"POST","/auth/logout",void 0),o=null},asAnonymous(){o=null}};return y}function P(n){if(!n)return{};let e;try{e=JSON.parse(n)}catch{throw new Error("PALBASE_TEST_IDENTITIES is set but is not JSON: the run that started these tests handed over a broken set of test users")}if(e===null||typeof e!="object"||Array.isArray(e))throw new Error("PALBASE_TEST_IDENTITIES is not an object of test users by name");return e}var j={get stack(){return!!process.env.PALBASE_TEST_BASE_URL},minted(n){return Object.prototype.hasOwnProperty.call(P(process.env.PALBASE_TEST_IDENTITIES),n)}},w,q=new Proxy({},{get(n,e){return w??=$({baseUrl:process.env.PALBASE_TEST_BASE_URL??"",apiKey:process.env.PALBASE_TEST_API_KEY??"",authUrl:process.env.PALBASE_TEST_AUTH_URL,identities:P(process.env.PALBASE_TEST_IDENTITIES)}),Reflect.get(w,e,w)}});export{N as a,f as b,$ as c,j as d,q as e};
@@ -1,5 +1,5 @@
1
- /*! palbase 0.18.2 — Palbase SDK License (see LICENSE) */
2
- import"./X6FNTEXY.js";import{realpathSync as Je}from"node:fs";import{resolve as ge}from"node:path";import vt from"typescript";import{existsSync as he,readFileSync as be}from"node:fs";import{createRequire as Qe}from"node:module";import{dirname as re,join as G,relative as We,resolve as xe,sep as ne}from"node:path";var b=class extends Error{constructor(t){super(t),this.name="ContractAnalysisError"}},Z=new Set(["palbase/backend","@palbase/backend","palgres"]),Ge=new Set(["Get","Post","Put","Patch","Delete","Query","Upload"]);function we(e){if(typeof e.createProgram!="function"||typeof e.getDecorators!="function"||typeof e.readConfigFile!="function")throw new b(`the contract is read with TypeScript's compiler API, and the TypeScript given (v${e.version??"unknown"}) has none \u2014 TypeScript 7 is the Go-native compiler, whose package exposes version metadata only`)}var Ze={bun:"bun-types",node:"@types/node"},He=Qe(import.meta.url);function Xe(e,t,n){if(!n.types)return{types:void 0,files:[]};let r=[],s=[];for(let i of n.types){let o=Ze[i],a=e.resolveTypeReferenceDirective(i,G(t,"tsconfig.json"),n,e.sys).resolvedTypeReferenceDirective,c;if(!a&&o)try{c=He.resolve(`${o}/package.json`)}catch{c=void 0}if(!c){r.push(i);continue}let l=JSON.parse(be(c,"utf8"));s.push(G(re(c),l.types??l.typings??"index.d.ts"))}return{types:r,files:s}}function ke(e,t){we(e);let n=G(t,"tsconfig.json"),r={target:e.ScriptTarget.ES2022,module:e.ModuleKind.ESNext,moduleResolution:e.ModuleResolutionKind.Bundler,experimentalDecorators:!0,allowImportingTsExtensions:!0},s=[];if(he(n)){let i=e.readConfigFile(n,e.sys.readFile);if(i.error)throw new b(`${n}: ${e.flattenDiagnosticMessageText(i.error.messageText,`
1
+ /*! palbase 0.18.3 — Palbase SDK License (see LICENSE) */
2
+ import"./CSVO2J45.js";import{realpathSync as Je}from"node:fs";import{resolve as ge}from"node:path";import vt from"typescript";import{existsSync as he,readFileSync as be}from"node:fs";import{createRequire as Qe}from"node:module";import{dirname as re,join as G,relative as We,resolve as xe,sep as ne}from"node:path";var b=class extends Error{constructor(t){super(t),this.name="ContractAnalysisError"}},Z=new Set(["palbase/backend","@palbase/backend","palgres"]),Ge=new Set(["Get","Post","Put","Patch","Delete","Query","Upload"]);function we(e){if(typeof e.createProgram!="function"||typeof e.getDecorators!="function"||typeof e.readConfigFile!="function")throw new b(`the contract is read with TypeScript's compiler API, and the TypeScript given (v${e.version??"unknown"}) has none \u2014 TypeScript 7 is the Go-native compiler, whose package exposes version metadata only`)}var Ze={bun:"bun-types",node:"@types/node"},He=Qe(import.meta.url);function Xe(e,t,n){if(!n.types)return{types:void 0,files:[]};let r=[],s=[];for(let i of n.types){let o=Ze[i],a=e.resolveTypeReferenceDirective(i,G(t,"tsconfig.json"),n,e.sys).resolvedTypeReferenceDirective,c;if(!a&&o)try{c=He.resolve(`${o}/package.json`)}catch{c=void 0}if(!c){r.push(i);continue}let l=JSON.parse(be(c,"utf8"));s.push(G(re(c),l.types??l.typings??"index.d.ts"))}return{types:r,files:s}}function ke(e,t){we(e);let n=G(t,"tsconfig.json"),r={target:e.ScriptTarget.ES2022,module:e.ModuleKind.ESNext,moduleResolution:e.ModuleResolutionKind.Bundler,experimentalDecorators:!0,allowImportingTsExtensions:!0},s=[];if(he(n)){let i=e.readConfigFile(n,e.sys.readFile);if(i.error)throw new b(`${n}: ${e.flattenDiagnosticMessageText(i.error.messageText,`
3
3
  `)}`);let o=e.parseJsonConfigFileContent(i.config,e.sys,t);r=o.options,s=o.fileNames.filter(c=>/\.d\.[cm]?ts$/.test(c));let a=Xe(e,t,r);r={...r,types:a.types},s=[...s,...a.files]}return{options:{...r,strictNullChecks:!0,noEmit:!0,skipLibCheck:!0},ambient:s}}function Ee(e,t,n,r,s){we(e);let i=e.createProgram([...new Set(n)],r,s);return{ts:e,root:t,program:i,checker:i.getTypeChecker(),packages:new Map}}function $(e,t){let n=xe(t);return!n.includes(`${ne}node_modules${ne}`)&&!/\.d\.[cm]?ts$/.test(n)&&(n===e.root||n.startsWith(e.root+ne))}function v(e,t){return!!t&&$(e,t.getSourceFile().fileName)}function Ce(e,t){let n=[],r=re(xe(t)),s=null;for(;;){let i=e.packages.get(r);if(i!==void 0){s=i;break}n.push(r);let o=G(r,"package.json");if(he(o)){try{let c=JSON.parse(be(o,"utf8")).name;s=typeof c=="string"?c:null}catch{s=null}break}let a=re(r);if(a===r)break;r=a}for(let i of n)e.packages.set(i,s);return s}function se(e,t){if($(e,t))return!1;let n=Ce(e,t)??"";return n==="palbase"?/[\\/]types[\\/]backend[\\/]/.test(t):Z.has(n)}function ie(e,t){if($(e,t))return!1;let n=Ce(e,t)??"";return Z.has(n)||n==="palbase"||n.startsWith("@palbase/")}function O(e,t){let n=t.getSourceFile(),{line:r}=n.getLineAndCharacterOfPosition(t.getStart(n));return`${We(e.root,n.fileName)}:${r+1}`}function T(e,t){for(;t;){if(e.isParenthesizedExpression(t)||e.isAsExpression(t)||e.isNonNullExpression(t)||e.isAwaitExpression(t)||e.isTypeAssertionExpression(t)||e.isSatisfiesExpression(t)){t=t.expression;continue}return t}return t}function H(e,t){if(t&&t.flags&e.ts.SymbolFlags.Alias){let n=e.checker.getAliasedSymbol(t);if(n&&n.declarations)return n}return t}function L(e,t){let n=H(e,e.checker.getSymbolAtLocation(t));return n&&(n.valueDeclaration||n.declarations&&n.declarations[0])||null}function ye(e,t){let n=t;for(;n&&!e.isImportDeclaration(n)&&!e.isExportDeclaration(n);)n=n.parent;return n&&(e.isImportDeclaration(n)||e.isExportDeclaration(n))&&n.moduleSpecifier&&e.isStringLiteral(n.moduleSpecifier)?n.moduleSpecifier.text:null}function I(e,t){let n=e.ts;if(t=T(n,t),!t)return null;if(n.isPropertyAccessExpression(t)){let i=e.checker.getSymbolAtLocation(t.expression);return i&&(i.declarations||[]).some(a=>n.isNamespaceImport(a)&&Z.has(ye(n,a)??""))?t.name.text:null}if(!n.isIdentifier(t))return null;let r=e.checker.getSymbolAtLocation(t),s=new Set;for(;r&&!s.has(r);){s.add(r);for(let i of r.declarations||[]){if((n.isImportSpecifier(i)||n.isExportSpecifier(i))&&Z.has(ye(n,i)??""))return(i.propertyName||i.name).text;if(se(e,i.getSourceFile().fileName))return r.name}if(!(r.flags&n.SymbolFlags.Alias))return null;r=e.checker.getImmediateAliasedSymbol(r)}return null}function Te(e,t){let n=t.expression;return I(e,e.ts.isCallExpression(n)?n.expression:n)}function P(e,t){return t&&(e.isIdentifier(t)||e.isPrivateIdentifier(t)||e.isStringLiteral(t)||e.isNumericLiteral(t))?t.text:null}function X(e,t){let n=e.ts,r=[];for(let s of t.statements){if(!n.isClassDeclaration(s)||!(n.getDecorators(s)||[]).some(o=>Te(e,o)==="Controller"))continue;if(!s.name)throw new b(`${O(e,s)} \u2014 a @Controller class needs a name \u2014 its routes' errors are bound to it by name`);let i=[];for(let o of s.members)if(!(!n.isMethodDeclaration(o)||!o.body)&&(n.getDecorators(o)||[]).some(a=>Ge.has(Te(e,a)??""))){if(P(n,o.name)===null)throw new b(`${O(e,o)} \u2014 a route method needs a plain name; the contract reaches it by name`);i.push(o)}r.push({cls:s,routes:i})}return r}var Ye=new Set([2307,2580,2582,2583,2584,2591,2592,2593,2688,2867,2868,7016]);function et(e){let t=e.getSymbol();return t?.getName()==="Response"&&(t.declarations??[]).length>0&&(t.declarations??[]).every(n=>n.getSourceFile().isDeclarationFile)}function Ne(e){let{ts:t,program:n,checker:r}=e,s=!1;return function(o,a){let c=o.getSourceFile().fileName,l=o.name.getText(o.getSourceFile()),u=d=>{throw new b(`${c} \u2014 ${a}.${l}: cannot infer a safe response contract (${d}). Use a named Zod return schema for this response; any/unknown is never emitted as a successful contract.`)};if(!s){let d=[];for(let p of n.getSourceFiles()){if(d.length>=5)break;p.isDeclarationFile||n.isSourceFileFromExternalLibrary(p)||/[\\/]node_modules[\\/]/.test(p.fileName)||ie(e,p.fileName)||d.push(...n.getSemanticDiagnostics(p).filter(x=>x.category===t.DiagnosticCategory.Error&&!Ye.has(x.code)))}d.length&&u(t.formatDiagnostics(d.slice(0,5),{getCanonicalFileName:p=>p,getCurrentDirectory:()=>e.root,getNewLine:()=>`
4
4
  `})),s=!0}let m=r.getSignatureFromDeclaration(o),g=m&&r.getAwaitedType(r.getReturnTypeOfSignature(m));if(!g)return u("unresolved return type");if(g.flags&(t.TypeFlags.Void|t.TypeFlags.Undefined))return{kind:"void"};if(et(g))return{kind:"raw"};function y(d){let p=d.getSymbol();if(p?.getName()!=="Encrypted"||!(p.declarations??[]).some(S=>ie(e,S.getSourceFile().fileName)))return;let x=r.getTypeArguments(d);return x.length===1?x[0]:void 0}let f=new Set,V=0;function h(d,p){if(++V>2e3||f.size>24)return u(`${p}: contract is too large; name its schema`);let x=d.flags,S=t.TypeFlags;if(x&(S.Any|S.Unknown|S.Never|S.TypeParameter))return u(`${p}: ${r.typeToString(d)}`);let pe=y(d);if(pe)return`encrypted(${h(pe,p)})`;let Se=w=>{let k=r.getPropertiesOfType(w);if(!(w.flags&S.Object)||k.length!==1||k[0].name!=="__pg"||!(k[0].flags&t.SymbolFlags.Optional)||r.getIndexInfosOfType(w).length)return!1;let N=r.getTypeOfSymbolAtLocation(k[0],o);return(N.isUnion()?N.types:[N]).every(E=>E.flags&(S.StringLiteral|S.Undefined))};if(d.isIntersection()){let w=d.types.filter(k=>!Se(k));if(w.length===1&&w.length<d.types.length)return h(w[0],p)}if(Se(d))return u(`${p}: unknown PostgreSQL payload; name its response schema`);if(x&S.StringLiteral)return`z.literal(${JSON.stringify(d.value)})`;if(x&S.NumberLiteral)return`z.literal(${JSON.stringify(d.value)})`;if(x&S.BooleanLiteral)return`z.literal(${r.typeToString(d)==="true"})`;if(x&S.String)return"z.string()";if(x&S.TemplateLiteral){let w=d;if(w.types.length>8||!w.types.every(E=>E.flags&S.String))return u(`${p}: template literal requires an explicit schema`);let k=E=>E.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),N="^"+k(w.texts[0]);for(let E of w.texts.slice(1,-1))if(E){let te=k(E);N+=`(?:(?!${te})[\\s\\S])*${te}`}return N+="[\\s\\S]*"+k(w.texts.at(-1))+"$(?![\\s\\S])",N.length>4096?u(`${p}: template pattern is too large`):`z.string().regex(new RegExp(${JSON.stringify(N)}))`}if(x&S.Number)return"z.number().finite()";if(x&S.Boolean)return"z.boolean()";if(x&S.Null)return"z.null()";if(x&S.Undefined)return"z.undefined()";if(f.has(d))return u(`${p}: recursive response`);f.add(d);try{if(d.isUnion()){if(d.types.length>32)return u(`${p}: union has more than 32 alternatives`);let A=d.types.some(M=>M.flags&S.Null),W=d.types.some(M=>M.flags&S.Undefined),j=d.types.filter(M=>!(M.flags&(S.Null|S.Undefined)));return(j.length===0?A?"z.null()":"z.undefined()":j.length===1?h(j[0],p):`z.union([${j.map(M=>h(M,p)).join(",")}])`)+(A&&j.length?".nullable()":"")+(W?".optional()":"")}if(r.isTupleType(d))return u(`${p}: tuple requires an explicit schema`);if(r.isArrayType(d)){let A=r.getTypeArguments(d)[0];return A.flags&S.Never?"z.array(z.string()).length(0)":`z.array(${h(A,`${p}[]`)})`}let w=d.isIntersection()&&d.types.every(A=>A.flags&S.Object);if(!(x&S.Object)&&!w||d.getCallSignatures().length||d.getConstructSignatures().length)return u(`${p}: non-JSON type ${r.typeToString(d)}`);let k=d.symbol?.declarations?.[0];if(k&&(t.isClassDeclaration(k)||t.isClassExpression(k)))return u(`${p}: class instance ${r.typeToString(d)}`);let N=r.getPropertiesOfType(d),E=r.getIndexInfosOfType(d);return E.length?E.length!==1||!(E[0].keyType.flags&S.String)||N.length?u(`${p}: mixed or non-string index signature`):`z.record(z.string(), ${h(E[0].type,`${p}.*`)})`:N.length?`z.object({${N.map(A=>{if(A.escapedName.toString().startsWith("__@"))return u(`${p}: symbol property`);let W=A.getName(),j=h(r.getTypeOfSymbolAtLocation(A,o),`${p}.${W}`);return`${JSON.stringify(W)}:${j}${A.flags&t.SymbolFlags.Optional?".optional()":""}`}).join(",")}}).strict()`:u(`${p}: empty structural type`)}finally{f.delete(d)}}return{kind:"expression",expression:h(g,"return")}}}import{resolve as tt}from"node:path";var oe=Symbol("not a named schema");function Ae(e,t,n,r){let{ts:s}=e,i=r.getSourceFile(),o=r.name.getText(i),a=f=>new b(`${i.fileName} \u2014 ${n}.${o}: ${f}`);function c(f){if(s.isTypeReferenceNode(f)&&f.typeName.getText(i)==="Promise"&&f.typeArguments&&f.typeArguments.length===1)return c(f.typeArguments[0]);if(f.kind===s.SyntaxKind.VoidKeyword||f.kind===s.SyntaxKind.UndefinedKeyword)return null;let V=s.isArrayTypeNode(f)?f.elementType:s.isTypeReferenceNode(f)&&f.typeName.getText(i)==="Array"&&f.typeArguments&&f.typeArguments.length===1?f.typeArguments[0]:void 0,h=l(V??f);return h===oe?h:{...h,isArray:V!==void 0}}function l(f){if(s.isTypeReferenceNode(f)&&!f.typeArguments)return{typeName:f.typeName.getText(i),node:f.typeName};if(s.isTypeReferenceNode(f)&&f.typeArguments&&f.typeArguments.length===1){let V=f.typeName.getText(i);if(/^(z\.)?(infer|output|input)$/.test(V)){let h=f.typeArguments[0];if(s.isTypeQueryNode(h))return{typeName:h.exprName.getText(i),node:h.exprName};if(s.isTypeReferenceNode(h)&&!h.typeArguments)return{typeName:h.typeName.getText(i),node:h.typeName}}}if(f.kind===s.SyntaxKind.VoidKeyword)throw a("void cannot appear inside an array/Promise here");return oe}let u=()=>t(r,n);if(!r.type)return u();let m=c(r.type);if(m===null)return{kind:"void"};if(m===oe)return u();let g=nt(e,m.node);if(!g)return u();let y=rt(e,g.symbol);return y?{kind:"schema",...y,array:m.isArray}:u()}function nt(e,t){let{ts:n,checker:r}=e,s=r.getSymbolAtLocation(n.isQualifiedName(t)?t.right:t),i=H(e,s);if(!i||!(i.flags&n.SymbolFlags.Variable))return null;let o=i.valueDeclaration;return!o||!n.isVariableDeclaration(o)||!r.getTypeOfSymbolAtLocation(i,o).getProperty("~standard")?null:{symbol:i}}function rt(e,t){let n=t.valueDeclaration?.getSourceFile();if(!n||n.isDeclarationFile)return null;let r=e.checker.getSymbolAtLocation(n);if(!r)return null;let s=e.checker.getExportsOfModule(r).filter(i=>H(e,i)===t).map(i=>i.name);return s.length===0?null:{file:tt(n.fileName),exportName:s.includes(t.name)?t.name:s[0]}}var ue={BadRequest:{code:"bad_request",status:400,codeArg:null},Unauthorized:{code:"unauthorized",status:401,codeArg:1},Forbidden:{code:"forbidden",status:403,codeArg:1},NotFound:{code:"not_found",status:404,codeArg:1},Conflict:{code:"conflict",status:409,codeArg:1},UniqueViolation:{code:"unique_violation",status:409,codeArg:2},SerializationFailure:{code:"serialization_failure",status:409,codeArg:null},DeadlockDetected:{code:"deadlock_detected",status:409,codeArg:null},TooManyRequests:{code:"too_many_requests",status:429,codeArg:null}},st=new Set(["HttpError","PalError"]),it=[{member:"page",container:null,error:{name:"BadRequest",code:"bad_request",status:400}},{member:"$page",container:null,error:{name:"BadRequest",code:"bad_request",status:400}},{member:"update",container:/^RepositoryOf(\$\d+)?$/,error:{name:"NotFound",code:"not_found",status:404}},{member:"update",container:/^RepositoryOf(\$\d+)?$/,error:{name:"BadRequest",code:"bad_request",status:400}},{member:"updateScoped",container:/^RepositoryOf(\$\d+)?$/,error:{name:"BadRequest",code:"bad_request",status:400}}],ot=new Map([["expectOne",0],["expectNone",0],["expectAtLeast",1],["expectAtMost",1]]);function $e(e){let t={...e,ids:new WeakMap,nextId:1,providerSet:null,concrete:null,summaries:new Map,warnings:new Map,statusOf:null,round:0,cyclic:!1,grew:!1};return{analyze(n){let r;for(;t.round+=1,t.cyclic=!1,t.grew=!1,r=At(t,n),!(!t.cyclic||!t.grew););for(let s of t.summaries.values())s.final=!0;return r},warnings(){return[...t.warnings.values()]}}}function at(e,t,n){throw new b(`${O(e,t)} \u2014 ${n}`)}function q(e,t){let n=e.ids.get(t);return n||(n=e.nextId++,e.ids.set(t,n)),n}function de(e,t){return(e.getCombinedModifierFlags(t)&e.ModifierFlags.Static)!==0}function Fe(e,t){return(e.getCombinedModifierFlags(t)&e.ModifierFlags.Abstract)!==0}function F(e,t){return!!t&&(e.isClassDeclaration(t)||e.isClassExpression(t))}function Oe(e,t){if(!t)return null;if(F(e,t))return t;if((e.isVariableDeclaration(t)||e.isPropertyDeclaration(t)||e.isPropertyAssignment(t))&&t.initializer){let n=T(e,t.initializer);if(e.isClassExpression(n))return n}return null}function ct(e,t){if(t.name)return t.name.text;let n=t.parent;if(n&&(e.isVariableDeclaration(n)||e.isPropertyDeclaration(n)||e.isPropertyAssignment(n))&&n.name&&P(e,n.name))return P(e,n.name)??void 0}function _(e,t){let n=e.ts,r=T(n,t);if(!r)return null;let s=Oe(n,L(e,n.isPropertyAccessExpression(r)?r.name:r));return s&&v(e,s)?s:null}function J(e,t){let n=e.ts,r=(t.heritageClauses||[]).find(i=>i.token===n.SyntaxKind.ExtendsKeyword),s=r&&r.types[0]&&r.types[0].expression;return s?_(e,s):null}function Re(e,t,n){for(let r=J(e,t);r;r=J(e,r))if(r===n)return!0;return!1}function U(e,t,n,r){let s=e.ts;for(let i=t;i;i=J(e,i))for(let o of i.members)if(!(P(s,o.name)!==n||de(s,o)!==r)){if((s.isMethodDeclaration(o)||s.isGetAccessorDeclaration(o))&&o.body)return{fn:o,owner:i};if(s.isPropertyDeclaration(o)&&o.initializer){let a=T(s,o.initializer);if(s.isArrowFunction(a)||s.isFunctionExpression(a))return{fn:a,owner:i}}}return null}function lt(e){let t=e.ts;if(e.providerSet)return e.providerSet;let n=new Set;for(let r of e.program.getSourceFiles())if($(e,r.fileName)){for(let s of r.statements)if(t.isClassDeclaration(s))for(let i of t.getDecorators(s)||[]){let o=i.expression;if(!t.isCallExpression(o)||I(e,o.expression)!=="Module")continue;let a=T(t,o.arguments[0]);if(!(!a||!t.isObjectLiteralExpression(a)))for(let c of a.properties){if(!t.isPropertyAssignment(c)||P(t,c.name)!=="providers")continue;let l=T(t,c.initializer);if(t.isArrayLiteralExpression(l))for(let u of l.elements){let m=_(e,u);m&&n.add(m)}}}}return e.providerSet=n,n}function ve(e){let t=e.ts;if(e.concrete)return e.concrete;let n=[],r=s=>{F(t,s)&&!Fe(t,s)&&n.push(s),t.forEachChild(s,r)};for(let s of e.program.getSourceFiles())$(e,s.fileName)&&r(s);return e.concrete=n,n}function ze(e,t){let n=t.name?e.checker.getSymbolAtLocation(t.name):t.symbol;return n?e.checker.getDeclaredTypeOfSymbol(n):null}function ut(e,t){let n=t&&(t.getSymbol()||t.aliasSymbol),r=n&&(n.declarations||[]).find(s=>F(e.ts,s));return r&&F(e.ts,r)&&v(e,r)?r:null}function ae(e,t){return t.type?e.checker.getTypeFromTypeNode(t.type):e.checker.getTypeAtLocation(t.name||t)}function Q(e,t,n){let r=e.ts;if(!t)return;if(t.isUnion()){for(let l of t.types)Q(e,l,n);return}let s=r.TypeFlags,i=s.StringLike|s.NumberLike|s.BigIntLike|s.BooleanLike|s.EnumLike|s.ESSymbolLike|s.VoidLike|s.Null;if(t.flags&(s.Any|s.Unknown|i))return;let o=t.getSymbol();if(!o)return;let a=(o.declarations||[]).find(l=>F(r,l));if(a&&F(r,a)){if(!v(e,a))return;Fe(r,a)||n.add(a);for(let l of ve(e))Re(e,l,a)&&n.add(l);return}if((o.declarations||[]).some(l=>v(e,l)))for(let l of ve(e)){let u=ze(e,l);u&&e.checker.isTypeAssignableTo(u,t)&&n.add(l)}}function fe(e,t,n){let r=ut(e,t);if(r){let s=lt(e);if(s.has(r)){n.add(r);return}let i=[...s].filter(o=>o!==r&&Re(e,o,r));if(i.length===1){n.add(i[0]);return}}Q(e,t,n)}function ft(e,t){for(let n=e;n;n=n.parent)if(n===t)return!0;return!1}function je(e,t){return t.fn&&ft(e,t.fn)?t:{receiver:null,owner:null,fn:null}}function C(e,t,n,r=new Set){let s=e.ts,i=new Set;if(t=T(s,t),!t)return i;let o=`${q(e,t)}@${n.receiver?q(e,n.receiver):0}`;if(r.has(o))return i;r.add(o);let a=c=>{for(let l of c)i.add(l)};if(s.isNewExpression(t)){let c=_(e,t.expression);return c&&i.add(c),i}if(t.kind===s.SyntaxKind.ThisKeyword)return n.receiver&&i.add(n.receiver),i;if(s.isConditionalExpression(t))return a(C(e,t.whenTrue,n,r)),a(C(e,t.whenFalse,n,r)),i;if(s.isBinaryExpression(t)){let c=t.operatorToken.kind,l=s.SyntaxKind;if(c===l.QuestionQuestionToken||c===l.BarBarToken||c===l.AmpersandAmpersandToken)return a(C(e,t.left,n,r)),a(C(e,t.right,n,r)),i;if(c===l.CommaToken||c===l.EqualsToken)return a(C(e,t.right,n,r)),i}if(s.isCallExpression(t)){for(let c of ee(e,t,n))for(let l of Y(s,c.fn))a(C(e,l,c.ctx,r));if(i.size>0)return i}else if(s.isIdentifier(t)||s.isPropertyAccessExpression(t)){let c=L(e,s.isPropertyAccessExpression(t)?t.name:t);if(c&&s.isVariableDeclaration(c))return c.initializer&&a(C(e,c.initializer,je(c,n),r)),(!((s.getCombinedNodeFlags(c)&s.NodeFlags.Const)!==0)||!c.initializer)&&Q(e,ae(e,c),i),i;if(c&&s.isParameter(c)){let l=ae(e,c);return c.parent&&s.isConstructorDeclaration(c.parent)?fe(e,l,i):Q(e,l,i),i}if(c&&s.isPropertyDeclaration(c))return c.initializer?a(C(e,c.initializer,{receiver:c.parent,owner:c.parent,fn:null},r)):fe(e,ae(e,c),i),i;if(c&&s.isGetAccessorDeclaration(c)&&c.body){for(let l of Y(s,c))a(C(e,l,{receiver:c.parent,owner:c.parent,fn:c},r));if(i.size>0)return i}if(c&&s.isPropertyAssignment(c)&&(a(C(e,c.initializer,{receiver:null,owner:null,fn:null},r)),i.size>0))return i}return Q(e,e.checker.getTypeAtLocation(t),i),i}function Y(e,t){if(e.isArrowFunction(t)&&!e.isBlock(t.body))return[t.body];let n=e.isFunctionLike(t)?t.body:void 0;if(!n)return[];let r=[],s=i=>{if(e.isReturnStatement(i)){i.expression&&r.push(i.expression);return}e.isFunctionLike(i)||F(e,i)||e.forEachChild(i,s)};return e.forEachChild(n,s),r}function Me(e,t){return e.isPropertyAccessExpression(t)?t.name.text:e.isElementAccessExpression(t)&&e.isStringLiteralLike(t.argumentExpression)?t.argumentExpression.text:null}function Ie(e,t){return e.isPropertyAccessExpression(t)?t.name:t.argumentExpression}function dt(e,t){let n=e.ts,r=Me(n,t);if(r===null)return[];let s=e.checker.getSymbolAtLocation(Ie(n,t)),i=new Map;for(let o of s&&s.declarations||[]){if(!se(e,o.getSourceFile().fileName))continue;let a=o.parent,c=a&&a.name&&n.isIdentifier(a.name)?a.name.text:"";for(let l of it)l.member===r&&(!l.container||l.container.test(c))&&i.set(l.error.code,l.error)}return[...i.values()]}function mt(e,t){let n=e.checker.getSymbolAtLocation(Ie(e.ts,t));return n?(n.declarations||[]).some(r=>v(e,r)):!0}function Be(e,t,n){let r=e.ts,s=[];for(let i=t;i;i=J(e,i)){for(let a of i.members){if(!r.isPropertyDeclaration(a)||!a.initializer||de(r,a))continue;let c=T(r,a.initializer);r.isArrowFunction(c)||r.isFunctionExpression(c)||s.push({fn:a.initializer,ctx:{receiver:n,owner:i,fn:null}})}let o=i.members.find(a=>r.isConstructorDeclaration(a)&&!!a.body);if(o){s.push({fn:o,ctx:{receiver:n,owner:i,fn:o}});break}}return s}function ee(e,t,n){let r=e.ts,s=T(r,t.expression);if(s.kind===r.SyntaxKind.SuperKeyword){let c=n.owner&&J(e,n.owner);return c?Be(e,c,n.receiver):[]}let i=Me(r,s);if(i!==null){let c=s,l=T(r,c.expression);if(l.kind===r.SyntaxKind.SuperKeyword){let g=n.owner&&J(e,n.owner),y=g&&U(e,g,i,!1);return y?[{fn:y.fn,ctx:{receiver:n.receiver,owner:y.owner,fn:y.fn}}]:[]}let u=r.isIdentifier(l)||r.isPropertyAccessExpression(l)?_(e,l):null;if(u){let g=U(e,u,i,!0);return g?[{fn:g.fn,ctx:{receiver:null,owner:g.owner,fn:g.fn}}]:[]}if(!mt(e,c))return[];let m=[];for(let g of C(e,l,n)){let y=U(e,g,i,!1);y&&m.push({fn:y.fn,ctx:{receiver:g,owner:y.owner,fn:y.fn}})}if(m.length>0)return m}let o=e.checker.getResolvedSignature(t),a=o&&o.declaration;if(a&&!r.isJSDocSignature(a)&&a.body&&v(e,a)){let c=a,l=c.parent&&F(r,c.parent)?c.parent:null,u=l&&!de(r,c)?l:null;return[{fn:c,ctx:{receiver:u,owner:l,fn:c}}]}return[]}function De(e,t,n){let r=e.ts,s=T(r,t);if(!s)return[];if(r.isPropertyAccessExpression(s)){let i=L(e,s.name);if(!(i&&v(e,i)&&(r.isMethodDeclaration(i)||r.isPropertyDeclaration(i))))return[];let a=[];for(let c of C(e,s.expression,n)){let l=U(e,c,s.name.text,!1);l&&a.push({fn:l.fn,ctx:{receiver:c,owner:l.owner,fn:l.fn}})}return a}if(r.isIdentifier(s)){let i=L(e,s);if(!i||!v(e,i))return[];if(r.isFunctionDeclaration(i)&&i.body)return[{fn:i,ctx:{receiver:null,owner:null,fn:i}}];if(r.isVariableDeclaration(i)&&i.initializer){let o=T(r,i.initializer);if(r.isArrowFunction(o)||r.isFunctionExpression(o))return[{fn:o,ctx:{receiver:null,owner:null,fn:o}}]}}return[]}function K(e,t,n){let r=e.ts,s=T(r,t);if(!s)return null;if(n==="string"&&(r.isStringLiteral(s)||r.isNoSubstitutionTemplateLiteral(s)))return[s.text];if(n==="number"&&r.isNumericLiteral(s))return[Number(s.text)];let i=e.checker.getTypeAtLocation(s),o=[];for(let a of i.isUnion()?i.types:[i])if(n==="string"&&a.isStringLiteral())o.push(a.value);else if(n==="number"&&a.isNumberLiteral())o.push(a.value);else return null;return o.length>0?[...new Set(o)]:null}function Le(e,t,n){let r=O(e,t);e.warnings.has(r)||e.warnings.set(r,`${r} \u2014 ${n}`)}function gt(e,t){let n=T(e,t);return!n||e.isIdentifier(n)&&n.text==="undefined"||n.kind===e.SyntaxKind.VoidExpression}function Pe(e){let t=e.split(/[^A-Za-z0-9]+/).filter(Boolean).map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join("");return/^[A-Za-z]/.test(t)?t:`E${t}`}function Ke(e,t,n,r,s){if(st.has(t)){let c=K(e,n[0],"number"),l=K(e,n[1],"string");return!l||!c||c.length!==1?(Le(e,r,`new ${t}(status, code, \u2026) with a code or status decided at runtime cannot be typed; clients receive it as their untyped case. To type it, give the code and status literal types (or declare it with defineError)`),[]):l.map(u=>({name:s&&l.length===1?s:Pe(u),code:u,status:c[0]}))}let i=Object.prototype.hasOwnProperty.call(ue,t)?ue[t]:null;if(!i)return[];let o=[i.code];if(i.codeArg!==null&&n.length>i.codeArg&&!gt(e.ts,n[i.codeArg])&&(o=K(e,n[i.codeArg],"string"),!o))return Le(e,r,`new ${t}(\u2026) with a code decided at runtime cannot be typed; clients receive it as their untyped case. To type it, give the code a literal type (or declare it with defineError)`),[];let a=o;return a.map(c=>({name:s&&a.length===1?s:c===i.code?t:Pe(c),code:c,status:i.status}))}function me(e,t){let n=e.ts,r=t.initializer&&T(n,t.initializer);return r&&n.isCallExpression(r)&&I(e,r.expression)==="defineError"?r:null}function _e(e,t,n){let r=K(e,n.arguments[0],"string"),s=K(e,n.arguments[1],"number"),i=r&&r.length===1?r[0]:null,o=s&&s.length===1?s[0]:null;return(i===null||o===null)&&at(e,n,`defineError(...) for "${t.name.getText()}" declares a typed error, so its code and status must be known when the project is built (a literal, or a constant of literal type)`),{name:t.name.getText(),code:i,status:o}}function pt(e,t){let n=null,r=s=>{if(!(n||e.isFunctionLike(s))){if(e.isCallExpression(s)&&s.expression.kind===e.SyntaxKind.SuperKeyword){n=s;return}e.forEachChild(s,r)}};return t.body&&e.forEachChild(t.body,r),n}function Ve(e,t,n,r){let s=e.ts,i=(t.heritageClauses||[]).find(f=>f.token===s.SyntaxKind.ExtendsKeyword),o=i&&i.types[0]&&i.types[0].expression;if(!o)return[];let a=t.members.find(f=>s.isConstructorDeclaration(f)&&!!f.body),c=n,l=r;if(a){let f=pt(s,a);if(!f)return[];c=f.arguments,l=f}let u=ct(s,t),m=I(e,o);if(m)return Ke(e,m,c,l,u);let g=L(e,o);if(g&&s.isVariableDeclaration(g)){let f=me(e,g);return f?[{..._e(e,g,f),name:u||g.name.getText()}]:[]}let y=_(e,o);if(y){let f=Ve(e,y,c,l);return f.length===1&&u?[{...f[0],name:u}]:f}return[]}function St(e,t){let n=e.ts,r=t.arguments||[],s=I(e,t.expression);if(s)return Ke(e,s,r,t);let i=T(n,t.expression),o=L(e,n.isPropertyAccessExpression(i)?i.name:i);if(!o)return[];if(n.isVariableDeclaration(o)){let c=me(e,o);if(c)return[_e(e,o,c)]}let a=Oe(n,o);return a&&v(e,a)?Ve(e,a,r,t):[]}function z(e,t,n,r,s,i,o=new Set){let a=e.ts;if(t=T(a,t),!t)return;let c=`${q(e,t)}@${n.receiver?q(e,n.receiver):0}`;if(!o.has(c)){if(o.add(c),a.isNewExpression(t)){let l=O(e,t);R(e,r,s,i,St(e,t).map(u=>({...u,site:l})));return}if(a.isConditionalExpression(t)){z(e,t.whenTrue,n,r,s,i,o),z(e,t.whenFalse,n,r,s,i,o);return}if(a.isBinaryExpression(t)){let l=a.SyntaxKind,u=t.operatorToken.kind;(u===l.QuestionQuestionToken||u===l.BarBarToken)&&z(e,t.left,n,r,s,i,o),z(e,t.right,n,r,s,i,o);return}if(a.isCallExpression(t)){for(let l of ee(e,t,n))for(let u of Y(a,l.fn))z(e,u,l.ctx,r,s,i,o);return}if(a.isIdentifier(t)||a.isPropertyAccessExpression(t)){let l=L(e,a.isPropertyAccessExpression(t)?t.name:t);if(l&&(a.isVariableDeclaration(l)||a.isPropertyDeclaration(l))&&l.initializer){let u=a.isVariableDeclaration(l)?je(l,n):n;z(e,l.initializer,u,r,s,i,o)}}}}function ce(e,t){let n=e.ts;if(!n.isFunctionLike(t))return!1;if((n.getCombinedModifierFlags(t)&n.ModifierFlags.Async)!==0)return!0;let r=e.checker.getSignatureFromDeclaration(t);if(!r)return!1;let s=e.checker.getReturnTypeOfSignature(r),i=e.checker.getPromisedTypeOfPromise;return i?i.call(e.checker,s)!==void 0:e.checker.getAwaitedType(s)!==s}function yt(e,t,n){let r=null;for(let s=t.parent;s&&s!==n;s=s.parent)e.isFunctionLike(s)&&(e.getCombinedModifierFlags(s)&e.ModifierFlags.Async)!==0&&(r=s);return r}function Tt(e,t,n){for(let r=t.parent;r&&r!==n;r=r.parent)if(e.isAwaitExpression(r)||e.isForOfStatement(r)&&r.awaitModifier)return!0;return!1}function ht(e,t,n,r){for(let s=t.scopes.length-1;s>=0;s--){let i=t.scopes[s],o=yt(e.ts,n,i.node),a=r||o!==null;if(i.kind==="try"){if(!a||Tt(e.ts,o||n,i.node))return i.sink}else if(i.kind==="settle"){if(a)return null}else if(i.kind==="catch"&&a&&!i.rethrows)return null}return t.root}function bt(e){let t=e.ts;if(e.statusOf)return e.statusOf;let n=new Map;for(let[s,i]of Object.entries(ue))n.set(i.code,{status:i.status,site:`palbase/backend ${s}`});let r=s=>{if(t.isVariableDeclaration(s)&&t.isIdentifier(s.name)){let i=me(e,s),o=i&&K(e,i.arguments[0],"string"),a=i&&K(e,i.arguments[1],"number");o&&a&&o.length===1&&a.length===1&&!n.has(o[0])&&n.set(o[0],{status:a[0],site:O(e,s)})}t.forEachChild(s,r)};for(let s of e.program.getSourceFiles())$(e,s.fileName)&&r(s);return e.statusOf=n,n}function xt(e,t){let n=bt(e),r=n.get(t.code);if(!r){n.set(t.code,{status:t.status,site:t.site});return}if(r.status!==t.status)throw new b(`"${t.code}" is thrown with status ${t.status} (${t.site}) but the code carries status ${r.status} (${r.site}) \u2014 a client matches an error by its code, so one code carries one status. Throw the code's own class, or give the error its own code`)}function R(e,t,n,r,s){for(let o of s)xt(e,o);let i=ht(e,t,n,r);if(i)for(let o of s)i.has(o.code)||i.set(o.code,o)}function Ue(e,t,n){if(!n)return!1;let r=!1,s=o=>{let a=!1,c=l=>{a||(e.isIdentifier(l)&&l.text===n?a=!0:e.forEachChild(l,c))};return c(o),a},i=o=>{r||e.isFunctionLike(o)&&o!==t||(e.isThrowStatement(o)&&o.expression&&s(o.expression)?r=!0:e.forEachChild(o,i))};return i(t),r}function wt(e,t){let n=T(e,t);if(n&&(e.isArrowFunction(n)||e.isFunctionExpression(n))){let r=n.parameters[0];return r?e.isIdentifier(r.name)?e.isBlock(n.body)?Ue(e,n.body,r.name.text):!1:!0:!1}return!0}function kt(e,t,n){let r=e.ts;if(!r.isPropertyAccessExpression(t)||t.name.text!==n)return!1;let s=T(r,t.expression);if(!r.isIdentifier(s)||s.text!=="Promise")return!1;let i=L(e,s);return!i||!v(e,i)}function B(e,t,n){let r=e.ts,s=`${q(e,t)}@${n.receiver?q(e,n.receiver):0}`,i=e.summaries.get(s);if(i&&(i.final||i.round===e.round))return i.busy&&(e.cyclic=!0),i.errors;i={errors:i?new Map(i.errors):new Map,busy:!0,round:e.round,final:!1},e.summaries.set(s,i);let o=i.errors.size,a={root:i.errors,scopes:[]};if(r.isFunctionLike(t)){let c=t;for(let l of c.parameters||[])l.initializer&&D(e,l.initializer,n,a);c.body&&D(e,c.body,n,a)}else D(e,t,n,a);return i.busy=!1,i.errors.size!==o&&(e.grew=!0),i.errors}function le(e,t){return{root:e.root,scopes:[...e.scopes,t]}}function D(e,t,n,r){let s=e.ts;if(s.isTryStatement(t)){let o=new Map;D(e,t.tryBlock,n,le(r,{kind:"try",node:t.tryBlock,sink:o}));let a=t.catchClause;(!a||(a.variableDeclaration&&s.isIdentifier(a.variableDeclaration.name)?Ue(s,a.block,a.variableDeclaration.name.text):a.variableDeclaration))&&R(e,r,t,!1,[...o.values()]),a&&D(e,a.block,n,r),t.finallyBlock&&D(e,t.finallyBlock,n,r);return}if(s.isThrowStatement(t))t.expression&&z(e,t.expression,n,r,t,!1);else if(s.isCallExpression(t)){let o=T(s,t.expression);if(kt(e,o,"allSettled")){D(e,t.expression,n,r);let u=le(r,{kind:"settle",node:t});for(let m of t.arguments)D(e,m,n,u);return}let a=s.isPropertyAccessExpression(o)?o.name.text==="catch"?0:o.name.text==="then"&&t.arguments.length>1?1:-1:-1;if(a>=0){let u=o,m=wt(s,t.arguments[a]);D(e,u.expression,n,le(r,{kind:"catch",node:u.expression,rethrows:m}));for(let g of t.arguments)D(e,g,n,r);return}let c=s.isPropertyAccessExpression(o)?ot.get(o.name.text):void 0;c!==void 0&&t.arguments[c]&&z(e,t.arguments[c],n,r,t,!0);let l=dt(e,o);if(l.length>0){let u=O(e,t);R(e,r,t,!0,l.map(m=>({...m,site:u})))}for(let u of ee(e,t,n))R(e,r,t,ce(e,u.fn),[...B(e,u.fn,u.ctx).values()]);for(let u of t.arguments)for(let m of De(e,u,n))R(e,r,u,ce(e,m.fn),[...B(e,m.fn,m.ctx).values()])}else if(s.isNewExpression(t)){let o=_(e,t.expression);if(o)for(let a of Be(e,o,o))R(e,r,t,!1,[...B(e,a.fn,a.ctx).values()]);for(let a of t.arguments||[])for(let c of De(e,a,n))R(e,r,a,ce(e,c.fn),[...B(e,c.fn,c.ctx).values()])}else if(s.isPropertyAccessExpression(t)&&!(t.parent&&s.isCallExpression(t.parent)&&t.parent.expression===t)){let o=L(e,t.name);if(o&&s.isGetAccessorDeclaration(o)&&o.body&&v(e,o))for(let a of C(e,t.expression,n)){let c=U(e,a,t.name.text,!1);c&&R(e,r,t,!1,[...B(e,c.fn,{receiver:a,owner:c.owner,fn:c.fn}).values()])}}if(F(s,t))return;let i=s.isFunctionExpression(t)||s.isFunctionDeclaration(t)?{receiver:null,owner:null,fn:t}:n;s.forEachChild(t,o=>D(e,o,i,r))}function qe(e,t,n){let r=e.ts;if(n.has(t))return[];if(n.add(t),I(e,t.expression)==="Resolve")return[t];let s=[];for(let i of ee(e,t,{receiver:null,owner:null,fn:null}))for(let o of Y(r,i.fn)){let a=T(r,o);r.isCallExpression(a)&&s.push(...qe(e,a,n))}return s}function Et(e,t){let n=e.ts,r=[];for(let s of t.parameters)for(let i of n.getDecorators(s)||[]){let o=T(n,i.expression);if(n.isCallExpression(o))for(let a of qe(e,o,new Set)){let c=_(e,a.arguments[0]);if(!c)continue;let l=new Set;fe(e,ze(e,c),l);for(let u of l){let m=U(e,u,"resolve",!1);m&&r.push({fn:m.fn,ctx:{receiver:u,owner:m.owner,fn:m.fn}})}}}return r}function Ct(e){return e.charAt(0).toLowerCase()+e.slice(1)}function Nt(e,t,n){let r=new Map;for(let i of Et(e,n))for(let o of B(e,i.fn,i.ctx).values())r.has(o.code)||r.set(o.code,o);for(let i of B(e,n,{receiver:t,owner:t,fn:n}).values())r.has(i.code)||r.set(i.code,i);let s=new Map;for(let i of r.values()){let o=Ct(i.name),a=s.get(o);if(a)throw new b(`${t.name.text}.${P(e.ts,n.name)} can throw two errors named "${i.name}" \u2014 "${a.code}" (${a.site}) and "${i.code}" (${i.site}). Every client names an error case after it; give one of them its own defineError`);s.set(o,i)}return[...r.values()].map(({name:i,code:o,status:a})=>({name:i,code:o,status:a}))}function At(e,t){let n=[];for(let{cls:r,routes:s}of X(e,t)){let i={};for(let o of s)i[P(e.ts,o.name)]=Nt(e,r,o);n.push({className:r.name.text,ops:i})}return n}function Gt(e,t,n={}){let r=n.typescript??vt,s=Je(ge(e)),{options:i,ambient:o}=ke(r,s);return Dt(Ee(r,s,[Je(ge(t)),...o],i))}function Dt(e){let t=e.ts,n=Ne(e),r=$e(e),s=[],i=e.program.getSourceFiles().filter(a=>$(e,a.fileName)).sort((a,c)=>a.fileName<c.fileName?-1:a.fileName>c.fileName?1:0),o=[];for(let a of i){let c=X(e,a);if(c.length===0)continue;let l=new Map;for(let{cls:u,routes:m}of c)for(let g of m)try{l.set(`${u.name.text}.${P(t,g.name)}`,Ae(e,n,u.name.text,g))}catch(y){if(!(y instanceof b))throw y;o.push(y.message)}if(!(o.length>0))for(let{className:u,ops:m}of r.analyze(a))for(let[g,y]of Object.entries(m))s.push({file:ge(a.fileName),className:u,method:g,returns:l.get(`${u}.${g}`),throws:y})}if(o.length===1)throw new b(o[0]);if(o.length>1)throw new b(`${o.length} routes have no contract:
5
5
  ${o.map(a=>`- ${a}`).join(`