palbase 0.63.0 → 0.65.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) 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/{XHTUT6AV.js → 2HJQSGOO.js} +2 -2
  8. package/dist/chunks/{WXOQLEUW.js → 3TXOVBZP.js} +2 -2
  9. package/dist/chunks/{XPKA7LAF.js → 4NHRUBEF.js} +2 -2
  10. package/dist/chunks/{IX4TWJ7J.js → 5HMDOBEH.js} +2 -2
  11. package/dist/chunks/63TUW6P7.js +18 -0
  12. package/dist/chunks/{T74PPGHJ.js → 6GRY63N6.js} +2 -2
  13. package/dist/chunks/{WUQWOSEI.js → ARRJICH3.js} +2 -2
  14. package/dist/chunks/{VHTT6VB5.js → BYXX373R.js} +2 -2
  15. package/dist/chunks/{G4UNJNUL.js → CTWUVLVE.js} +1 -1
  16. package/dist/chunks/{COXA3LDU.js → CZGZTOK7.js} +2 -2
  17. package/dist/chunks/{UDS4W77D.js → DFX37NU3.js} +1 -1
  18. package/dist/chunks/{LGGBVI33.js → DLMWZYLL.js} +2 -2
  19. package/dist/chunks/{KGP3V3IA.js → G2JBUBZO.js} +2 -2
  20. package/dist/chunks/{SWB2U22R.js → GFG7WVN2.js} +2 -2
  21. package/dist/chunks/{RFRPB2IR.js → JHM7GTPD.js} +1 -1
  22. package/dist/chunks/KU6B2OXP.js +2 -0
  23. package/dist/chunks/{BVR7H5RY.js → KZZ3Y3DC.js} +1 -1
  24. package/dist/chunks/{ZG2LQB5B.js → TEF7WS37.js} +1 -1
  25. package/dist/chunks/{7YRDXDVI.js → X6JMSZBD.js} +2 -2
  26. package/dist/chunks/{YWG7F44Q.js → XSOQNHZ5.js} +1 -1
  27. package/dist/chunks/{EJ7YD4YY.js → YP3QTS4L.js} +1 -1
  28. package/dist/chunks/{IXFSQYJA.js → ZF3WKPVM.js} +2 -2
  29. package/dist/chunks/ZZRRJOEP.js +2 -0
  30. package/dist/cli.js +10804 -351
  31. package/dist/cloud/index.js +2 -2
  32. package/dist/refuse/ai.js +1 -1
  33. package/dist/refuse/backend.js +1 -1
  34. package/dist/refuse/cloud.js +1 -1
  35. package/dist/refuse/server.js +1 -1
  36. package/dist/server/index.js +2 -2
  37. package/dist/server/testing.js +2 -2
  38. package/dist/web/index.js +2 -2
  39. package/dist/web/message.js +2 -2
  40. package/dist/web/palbe.js +2 -2
  41. package/dist/web/paywall.js +2 -2
  42. package/dist/web/push-sw.js +1 -1
  43. package/dist/web/ssr.js +2 -2
  44. package/dist/web/vite.js +2 -2
  45. package/package.json +2 -2
  46. package/types/ai/src/chats.d.ts +20 -2
  47. package/types/ai/src/index.d.ts +2 -2
  48. package/types/ai/src/pools.d.ts +158 -9
  49. package/types/ai/src/tools.d.ts +83 -2
  50. package/types/cloud/src/generated/project.d.ts +2 -1
  51. package/types/internal/src/modules/ai.d.ts +338 -29
  52. package/types/internal/src/modules/events.d.ts +4 -3
  53. package/types/internal/src/modules/index.d.ts +1 -0
  54. package/types/internal/src/modules/storage.d.ts +1 -1
  55. package/types/internal/src/modules/workspaces.d.ts +604 -0
  56. package/types/server/src/server.d.ts +5 -0
  57. package/dist/chunks/5KIV2VHK.js +0 -2
  58. package/dist/chunks/5TXSFJYI.js +0 -18
  59. package/dist/chunks/BP35TQMR.js +0 -2
@@ -1,5 +1,5 @@
1
- /*! palbase 0.63.0 — Palbase SDK License (see LICENSE) */
2
- import{e as tt,g as st,h as it}from"./XHTUT6AV.js";import{h as nt}from"./XPKA7LAF.js";import{a as et}from"./WUQWOSEI.js";import{r as Ye,t as Qe,u as Ze}from"./EJ7YD4YY.js";import{b as B,c as $,e as Be,f as Je,i as _e,j as V,k as ze}from"./BP35TQMR.js";import{a as Xe,b as J}from"./KGP3V3IA.js";import{b,d as K}from"./LGGBVI33.js";function Qt(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 C=class extends Error{code="session_changed";constructor(e){super(e),this.name="SessionChangedError"}};function rt(){let r=null;return{load:()=>r,save:e=>{r=e},clear:()=>{r=null},shared:!1}}function at(r){let e=null,t=!0,s=()=>{try{return globalThis.localStorage}catch{return}};return{shared:!0,load(){try{let i=s()?.getItem(r);return i==null?t?null:e:JSON.parse(i)}catch{return e}},save(i){e=i;try{let n=s();if(!n)throw new Error("no storage");n.setItem(r,JSON.stringify(i)),t=!0}catch{t=!1}},clear(){e=null,t=!0;try{s()?.removeItem(r)}catch{}},watch(i){let n=globalThis;if(typeof n.addEventListener!="function")return()=>{};let a=o=>{(o.key===r||o.key===null)&&i()};return n.addEventListener("storage",a),()=>n.removeEventListener?.("storage",a)}}}function Pe(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 Zt=6e4,es=15e3;function ts(r,e,t){let s=r?globalThis.navigator?.locks:void 0;return s?s.request(e,t):t()}var X=class{current=null;loaded;inflight=null;endReason=null;listeners=new Set;store;refresher;isRejected;now;lockName;refreshTimeoutMs;mode;constructor(e,t,s,i={}){this.store=e,this.refresher=t,this.isRejected=s,this.now=i.now??Date.now,this.lockName=i.lockName??"palbase.session.refresh",this.refreshTimeoutMs=i.refreshTimeoutMs??es,this.mode=i.refresh??"behind",this.loaded=Promise.resolve(e.load()).then(n=>{this.current=n}),e.watch?.(()=>{this.reconcile()})}async session(){return await this.loaded,this.current}snapshot(){return this.current}onChange(e){return this.listeners.add(e),()=>this.listeners.delete(e)}async set(e,t,s){await this.loaded;let i=t==="TOKEN_REFRESHED"?this.current:null,n={accessToken:e.access_token,refreshToken:e.refresh_token,expiresAt:this.now()+e.expires_in*1e3,userId:s?.id??i?.userId??Pe(e.access_token),user:s??i?.user};return this.current=n,await this.store.save(n),this.emit(t,n),n}async setUser(e,t){await this.loaded,!(!this.current||!t||this.current.userId!==t.userId)&&(this.current={...this.current,user:e},await this.store.save(this.current),this.emit("USER_UPDATED",this.current))}async clear(e,t){await this.loaded;let s=this.current;this.current=null,this.inflight=null;let i=await this.store.load();(!i||!s||i.userId===s.userId)&&await this.store.clear(),s&&(e==="SESSION_EXPIRED"&&(this.endReason=t??"revoked"),this.emit(e,null))}async accessToken(){await this.loaded;let e=this.current;if(!e)return;let t=e.expiresAt-this.now();if(t>Zt)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=ts(this.store.shared===!0,this.lockName,async()=>{await this.loaded;let t=this.current;if(!t)throw new C("no session to refresh");let s=await this.adoptStored(t);if(s)return s;try{let i=await this.withTimeout(this.refresher(t.refreshToken));if(this.current?.refreshToken!==t.refreshToken)throw new C("the session changed while it was refreshed");return await this.set(i,"TOKEN_REFRESHED")}catch(i){throw this.isRejected(i)&&this.current?.refreshToken===t.refreshToken&&await this.clear("SESSION_EXPIRED",Qt(i)),i}});return this.inflight=e,e.finally(()=>{this.inflight===e&&(this.inflight=null)}).catch(()=>{}),e}async adoptStored(e){let t=await this.store.load();if(!t)throw this.current=null,this.emit("SIGNED_OUT",null),new C("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 C("another user signed in in another tab");if(t.refreshToken!==e.refreshToken&&t.expiresAt>=e.expiresAt)return this.current=t,this.emit("TOKEN_REFRESHED",t),t}async reconcile(){await this.loaded;let e=this.current,t=await this.store.load();if(!e){t&&(this.current=t,this.emit("SIGNED_IN",t));return}await this.adoptStored(e).catch(()=>{})}withTimeout(e){let t,s=new Promise((i,n)=>{t=setTimeout(()=>n(new Error(`the refresh did not answer within ${this.refreshTimeoutMs/1e3} s`)),this.refreshTimeoutMs)});return Promise.race([e,s]).finally(()=>clearTimeout(t))}emit(e,t){(e==="SIGNED_IN"||e==="SIGNED_OUT")&&(this.endReason=null);for(let s of this.listeners)try{s(e,t)}catch{}}};var Te=class{state="closed";refusal;logSeq;joinRef=null;refusals=0;retry=null;asking=0;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,e&&(this.refusals=0);let s=this.joinWaiters.splice(0);for(let i of s)e?i.resolve():i.reject(new Error(`join ${this.name} refused: ${JSON.stringify(t)}`));if(e)for(let i of[...this.joiners])try{i()}catch{}}closed(e){this.state="closed",this.joinRef=null,this.retry&&clearTimeout(this.retry),this.retry=null,this.refusals=0;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{}}},Y=class{ws=null;opening=null;ref=0;channels=new Map;lastJoin=new Map;replies=new Map;heartbeat=null;heartbeatRef=null;reconnectTimer=null;attempts=0;closedByUs=!1;asks=0;epoch=0;wasOpen=!1;current="idle";statusListeners=new Set;reconnects=0;opts;constructor(e){this.opts=e}get status(){return this.current}onStatus(e){return this.statusListeners.add(e),()=>{this.statusListeners.delete(e)}}setStatus(e){if(this.current!==e){this.current=e;for(let t of[...this.statusListeners])try{t(e)}catch{}}}channel(e,t){let s=this.channels.get(e);return s||this.channels.set(e,s=new Te(e,this,t)),s}disconnect(){this.closedByUs=!0,this.wasOpen=!1,this.epoch++,this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=null,this.attempts=0,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.asking=0,t.closed("the socket was closed");this.lastJoin.clear(),this.current!=="idle"&&this.setStatus("disconnected")}async tokenChanged(){if(this.askRefusedAgain(),!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})}askRefusedAgain(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null,this.open().catch(()=>{}));for(let e of this.channels.values())e.state==="refused"&&(e.retry&&clearTimeout(e.retry),e.retry=null,this.askAgain(e))}join(e){if(e.state="joining",this.ws?.readyState===1){this.sendJoin(e);return}this.reconnectTimer||this.open().catch(()=>{})}settle(e,t,s){e.settled(t,s),t||this.askAgainLater(e)}askAgainLater(e){let t=this.opts.refusedBackoff??[1e3,2e3,5e3,1e4,3e4,6e4,3e5],s=t[Math.min(e.refusals,t.length-1)]*(.8+Math.random()*.4);e.refusals++,e.retry&&clearTimeout(e.retry),e.retry=F(setTimeout(()=>{e.retry=null,this.askAgain(e)},s))}askAgain(e){this.reconnectTimer||this.channels.get(e.name)!==e||e.state!=="refused"||this.join(e)}joinWanted(){for(let e of this.channels.values())e.state==="refused"&&(e.retry&&clearTimeout(e.retry),e.retry=null,e.state="joining"),e.state==="joining"&&this.sendJoin(e)}leave(e){e.retry&&clearTimeout(e.retry),e.retry=null,e.state==="joined"&&(this.ws?.readyState===1&&this.push(e.joinRef,e.topic,"phx_leave",{}),this.lastJoin.get(e.name)===e&&this.lastJoin.delete(e.name)),e.state="closed",this.channels.delete(e.name)}async request(e,t,s){let i=this.ws;if(this.channels.get(e.name)!==e||e.state!=="joined"||i?.readyState!==1)return{status:"error",response:{reason:"not joined"}};let n=this.nextRef(),a=JSON.stringify([e.joinRef,n,e.topic,t,s]),o=this.awaitReply(n);return i.send(a),o}open(){if(this.ws?.readyState===1)return Promise.resolve();if(this.opening)return this.opening;this.closedByUs=!1,this.current!=="reconnecting"&&this.setStatus("connecting");let e=this.opts.webSocket??globalThis.WebSocket,t=`${this.opts.baseUrl.replace(/^http/,"ws")}/realtime/v1/websocket?vsn=2.0.0&apikey=${encodeURIComponent(this.opts.publishableKey)}`,s=new Promise((i,n)=>{let a;try{a=new e(t)}catch(o){this.setStatus("reconnecting");let l=o instanceof Error?o.message:String(o);for(let d of this.channels.values())d.state==="joining"&&this.settle(d,!1,{reason:l});n(o);return}this.ws=a,a.onopen=()=>{if(this.ws!==a){a.close(1e3),n(new Error("the socket was closed"));return}this.attempts=0,this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=null,this.wasOpen&&this.reconnects++,this.wasOpen=!0,this.startHeartbeat(),this.setStatus("connected"),this.joinWanted(),i()},a.onmessage=o=>this.receive(String(o.data)),a.onerror=()=>n(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,e.onmessage=null,this.stopHeartbeat();for(let[,i]of this.replies)i("error",{reason:"socket closed"});this.replies.clear();for(let i of this.channels.values())i.state==="joined"&&(i.state="joining");if(this.closedByUs)return;if(![...this.channels.values()].some(i=>i.state==="joining"||i.state==="refused")){this.wasOpen=!1,this.setStatus("disconnected");return}if(this.setStatus("reconnecting"),this.reconnectTimer)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=F(setTimeout(()=>{this.reconnectTimer=null,this.open().catch(()=>{})},s))}async sendJoin(e){if(e.asking)return;let t=++this.asks;e.asking=t;try{await this.ask(e)}finally{e.asking===t&&(e.asking=0)}}async ask(e){let t=this.ws;if(t?.readyState!==1)return;let s=this.epoch,i;try{i=await this.opts.accessToken()}catch(c){s===this.epoch&&this.ws===t&&this.channels.get(e.name)===e&&e.state==="joining"&&this.settle(e,!1,{reason:c instanceof Error?c.message:String(c)});return}if(s!==this.epoch||this.channels.get(e.name)!==e||e.state!=="joining"||this.ws!==t||t.readyState!==1)return;let n=this.nextRef();e.joinRef=n;let a=this.awaitReply(n),o={broadcast:{self:!1}};e.logSeq!==void 0&&(o.log={after:e.logSeq}),this.lastJoin.set(e.name,e),this.push(n,e.topic,"phx_join",{access_token:i,config:o},n);let{status:l,response:d}=await a;if(!(l!=="ok"&&this.ws!==t)){if(this.channels.get(e.name)!==e||e.state!=="joining"){this.lastJoin.get(e.name)===e&&(this.lastJoin.delete(e.name),l==="ok"&&this.ws?.readyState===1&&this.push(n,e.topic,"phx_leave",{}));return}if(l==="timeout"){this.askOnLater(e);return}this.settle(e,l==="ok",d)}}askOnLater(e){let t=this.opts.refusedBackoff??[1e3,2e3,5e3,1e4,3e4,6e4,3e5],s=t[Math.min(e.refusals,t.length-1)]*(.8+Math.random()*.4);e.refusals++,e.retry&&clearTimeout(e.retry),e.retry=F(setTimeout(()=>{e.retry=null,this.channels.get(e.name)===e&&e.state==="joining"&&this.ws?.readyState===1&&this.sendJoin(e)},s))}awaitReply(e){return new Promise(t=>{let s=F(setTimeout(()=>{this.replies.delete(e),t({status:"timeout",response:{reason:"no reply"}})},this.opts.replyTimeoutMs??1e4));this.replies.set(e,(i,n)=>{clearTimeout(s),this.replies.delete(e),t({status:i,response:n})})})}receive(e){let t;try{t=JSON.parse(e)}catch{return}if(!Array.isArray(t)||t.length!==5||typeof t[2]!="string"||typeof t[3]!="string")return;let[s,i,n,a,o]=t,l=typeof o=="object"&&o!==null?o:{};if(a==="phx_reply"&&typeof i=="string"){if(i===this.heartbeatRef){this.heartbeatRef=null;return}this.replies.get(i)?.(String(l.status),l.response??{});return}let d=[...this.channels.values()].find(c=>c.topic===n);if(d&&!((a==="phx_close"||a==="phx_error")&&typeof s=="string"&&d.joinRef!==null&&s!==d.joinRef)){if(a==="phx_close"){if(d.state!=="joined")return;d.state="refused",d.refusal={reason:"closed by the server"},this.askAgainLater(d);return}if(a==="phx_error"){d.state="joining",F(setTimeout(()=>this.channels.get(d.name)===d&&d.state==="joining"&&this.ws?.readyState===1&&void this.sendJoin(d),1e3));return}d.deliver(a,l)}}push(e,t,s,i,n=this.nextRef()){this.ws?.send(JSON.stringify([e,n,t,s,i]))}nextRef(){return String(++this.ref)}startHeartbeat(){this.stopHeartbeat(),this.heartbeat=F(setInterval(()=>{if(this.heartbeatRef!==null){this.heartbeatRef=null;let e=this.ws;e?.close(4e3),e&&this.dropped(e);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 F(r){return r.unref?.(),r}var O="X-Palbase-Installation-Secret",Z="X-Palbase-Installation",lt=new WeakMap;function A(r){return lt.get(r)}var dt=new WeakSet;function ct(r){return dt.has(r)}var ss=/^[A-Za-z0-9_-]{43}$/,Q=class{id;constructor(e){let t=`palbase.installation.secret.${e}`,s;try{let i=ot()?.getItem(t);i&&ss.test(i)&&(s=i)}catch{}if(!s){dt.add(this),s=ht(crypto.getRandomValues(new Uint8Array(32)));try{ot()?.setItem(t,s)}catch{}}lt.set(this,s),this.id=is(s)}};function is(r){return ht(rs(new TextEncoder().encode(r)).subarray(0,16))}function ot(){try{return globalThis.localStorage}catch{return}}function ht(r){let e="";for(let t of r)e+=String.fromCharCode(t);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}var ns=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]),I=(r,e)=>r>>>e|r<<32-e;function rs(r){let e=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),t=new Uint8Array(Math.ceil((r.length+9)/64)*64);t.set(r),t[r.length]=128;let s=new DataView(t.buffer);s.setUint32(t.length-8,Math.floor(r.length/536870912)),s.setUint32(t.length-4,r.length*8>>>0);let i=new Uint32Array(64);for(let o=0;o<t.length;o+=64){for(let g=0;g<16;g++)i[g]=s.getUint32(o+g*4);for(let g=16;g<64;g++){let v=I(i[g-15],7)^I(i[g-15],18)^i[g-15]>>>3,_=I(i[g-2],17)^I(i[g-2],19)^i[g-2]>>>10;i[g]=i[g-16]+v+i[g-7]+_|0}let[l,d,c,f,u,S,m,h]=e;for(let g=0;g<64;g++){let v=h+(I(u,6)^I(u,11)^I(u,25))+(u&S^~u&m)+ns[g]+i[g]|0,_=(I(l,2)^I(l,13)^I(l,22))+(l&d^l&c^d&c)|0;h=m,m=S,S=u,u=f+v|0,f=c,c=d,d=l,l=v+_|0}e[0]+=l,e[1]+=d,e[2]+=c,e[3]+=f,e[4]+=u,e[5]+=S,e[6]+=m,e[7]+=h}let n=new Uint8Array(32),a=new DataView(n.buffer);for(let o=0;o<8;o++)a.setUint32(o*4,e[o]);return n}var os=30*6e4,ut=1e3,ls=100,ds=60*1024,ee=()=>globalThis.crypto?.randomUUID?globalThis.crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;function q(){try{return globalThis.localStorage}catch{return}}var se=class{api;closingApi;perfApi;closingPerfApi;flushMs;flushAt;now;anonKey;sessionKey;onceKey;events=[];samples=[];timer;memoryAnon;memorySession;memoryOnce;appVersion;stopAuto;session;consent;identifyPending=!1;listeners=new Set;people={set:e=>this.person({set:e}),setOnce:e=>this.person({set_once:e}),unset:e=>this.person({unset:[...e]}),add:e=>this.person({add:e})};constructor(e,t,s,i,n,a,o={}){this.session=s,this.consent=i;let l={send:c=>e.send(this.granted("analytics")?{...c,headers:{...c.headers,[Z]:n.id}}:c)};this.api=B.client(l);let d={send:c=>(this.granted("analytics")?e:t).send(c)};this.perfApi=B.client(d),this.closingApi=B.client({send:c=>l.send({...c,keepalive:!0})}),this.closingPerfApi=B.client({send:c=>d.send({...c,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(c=>{c==="SIGNED_IN"?(this.identifyPending=!0,this.soon()):c==="SIGNED_OUT"&&(this.identifyPending=!1,this.reset())}),i.onChange((c,f)=>{f!=="granted"&&(c==="analytics"?(this.events=[],this.identifyPending=!1,this.samples=this.samples.map(xe),this.reset()):c==="performance"&&(this.samples=[]))})}capture(e,t){for(let i of this.listeners)i(e,t);if(!this.granted("analytics"))return;let s=this.now();this.hold({event:e,distinct_id:this.distinctId(),properties:t,timestamp:s,session_id:this.sessionId(s),...this.appVersion?{app_version:this.appVersion}:{}})}captureOnce(e,t,s){if(!this.granted("analytics"))return;let i=this.sessionId(this.now()),n=this.readOnce(),a=n?.session===i?n.keys:[];a.includes(e)||(this.writeOnce({session:i,keys:[...a,e].slice(-500)}),this.capture(t,s))}readOnce(){try{let e=q()?.getItem(this.onceKey);if(e)return JSON.parse(e)}catch{}return this.memoryOnce}writeOnce(e){this.memoryOnce=e;try{q()?.setItem(this.onceKey,JSON.stringify(e))}catch{}}onEvent(e){return this.listeners.add(e),()=>this.listeners.delete(e)}page(e={}){let t=globalThis.location,s=globalThis.document,i=e.url??(t?`${t.origin}${W(t.pathname)}`:"");if(!i)return;let n=e.referrer??gs(s?.referrer);this.capture("$pageview",{...e.properties,url:i,...e.title??s?.title?{title:e.title??s?.title}:{},...n?{referrer:n}:{}})}async identify(e){this.identifyPending=!1;let t=this.session.snapshot()?.userId;!t||!this.granted("analytics")||(await this.flush(),await this.sendIdentify(this.api,t,e))}async sendIdentify(e,t,s){try{await e.identify({body:{distinct_id:t,anonymous_id:this.anonymousId(),traits:s,timestamp:this.now(),sent_at:this.now()}})}catch{}}reset(){this.memoryAnon=void 0,this.memorySession=void 0,this.memoryOnce=void 0;try{q()?.removeItem(this.anonKey),q()?.removeItem(this.sessionKey),q()?.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(xe)):this.samples=[];let t=e?this.closingApi:this.api,s=e?this.closingPerfApi:this.perfApi,i=this.now(),n=this.session.snapshot()?.userId;for(this.identifyPending&&n&&this.granted("analytics")&&(this.identifyPending=!1,await this.sendIdentify(t,n));this.events.length>0;){let a=this.take(this.events,e);try{await t.batch({body:{events:a.map(o=>({...o,sent_at:i}))}})}catch{}}for(;this.samples.length>0;){let a=this.take(this.samples,e);try{await s.sendPerf({body:{items:a}})}catch{}}}start(e={}){this.stopAuto?.(),this.appVersion=e.appVersion;let t=globalThis;if(typeof t.addEventListener!="function"||typeof globalThis.document>"u")return()=>{};let s=[];e.pageViews!==!1&&s.push(this.watchPages(t)),e.webVitals!==!1&&s.push(us((a,o)=>this.sample("web_vital",a,o))),e.network!==!1&&s.push(this.watchFetch(t));let i=()=>{document.visibilityState==="hidden"&&this.flush(!0)},n=()=>{this.flush(!0)};return document.addEventListener("visibilitychange",i),t.addEventListener("pagehide",n),s.push(()=>{document.removeEventListener("visibilitychange",i),t.removeEventListener("pagehide",n)}),this.stopAuto=()=>{for(let 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>=ut&&this.events.shift(),this.events.push(e),this.soon()}sample(e,t,s,i={}){if(!this.granted("performance"))return;this.samples.length>=ut&&this.samples.shift();let n={row_id:ee(),trace_type:e,name:t,value:Math.max(0,s),timestamp:this.now(),...i};this.samples.push(this.granted("analytics")?{...n,distinct_id:this.distinctId()}:xe(n)),this.soon()}soon(){if(this.events.length+this.samples.length>=this.flushAt){this.flush();return}this.timer||(this.timer=setTimeout(()=>{this.flush()},this.flushMs),this.timer.unref?.())}take(e,t){let s=e.splice(0,ls);if(!t)return s;for(;s.length>1&&JSON.stringify(s).length>ds;)e.unshift(s.pop());return s}distinctId(){return this.session.snapshot()?.userId??this.anonymousId()}anonymousId(){let e=q();try{let t=e?.getItem(this.anonKey);if(t)return t;let s=`anon_${ee()}`;if(e?.setItem(this.anonKey,s),e?.getItem(this.anonKey)===s)return s}catch{}return this.memoryAnon??=`anon_${ee()}`,this.memoryAnon}sessionId(e){let t=q(),s=this.memorySession;try{let n=t?.getItem(this.sessionKey);n&&(s=JSON.parse(n))}catch{}let i=s&&e-s.last<os?{id:s.id,last:e}:{id:`ses_${ee()}`,last:e};this.memorySession=i;try{t?.setItem(this.sessionKey,JSON.stringify(i))}catch{}return i.id}watchPages(e){let t="",s=()=>{let o=`${e.location.origin}${e.location.pathname}`;if(o===t)return;t=o;let l=`${e.location.origin}${W(e.location.pathname)}`;setTimeout(()=>this.page({url:l}),0)},i=e.history,n=i.pushState.bind(i),a=i.replaceState.bind(i);return i.pushState=(...o)=>{n(...o),s()},i.replaceState=(...o)=>{a(...o),s()},e.addEventListener("popstate",s),s(),()=>{i.pushState=n,i.replaceState=a,e.removeEventListener("popstate",s)}}watchFetch(e){let t=e.fetch;if(typeof t!="function")return()=>{};let s=async(i,n)=>{let a=performance.now(),o=i instanceof Request?i:void 0,l=(n?.method??o?.method??"GET").toUpperCase(),d;try{d=new URL(o?.url??String(i),e.location.href)}catch{d=void 0}let c=!!d&&d.pathname.startsWith("/analytics/")||ps(n?.headers??o?.headers);try{let f=await t(i,n);return d&&!c&&this.sample("network",`${l} ${d.origin}${W(d.pathname)}`,performance.now()-a,{attrs:{status:String(f.status)},...f.headers.get("x-request-id")?{request_id:f.headers.get("x-request-id")}:{}}),f}catch(f){throw d&&!c&&this.sample("network",`${l} ${d.origin}${W(d.pathname)}`,performance.now()-a,{attrs:{status:"0"}}),f}};return e.fetch=s,()=>{e.fetch===s&&(e.fetch=t)}}};function xe(r){let{distinct_id:e,request_id:t,...s}=r;return s}var cs=r=>r.entryType==="layout-shift"&&"value"in r&&"hadRecentInput"in r,hs=r=>r.entryType==="event"||r.entryType==="first-input";function te(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 us(r){if(typeof document>"u"||typeof performance>"u"||typeof performance.getEntriesByType!="function")return()=>{};let e=0,t=0,s=0,i=[te("largest-contentful-paint",d=>{for(let c of d)e=Math.max(e,c.startTime)}),te("layout-shift",d=>{for(let c of d)cs(c)&&!c.hadRecentInput&&(t+=c.value)}),te("event",d=>{for(let c of d)hs(c)&&(s=Math.max(s,c.duration))}),te("paint",d=>{for(let c of d)c.name==="first-contentful-paint"&&r("FCP",c.startTime)})],n=performance.getEntriesByType("navigation")[0];n&&n.responseStart>0&&r("TTFB",n.responseStart);let a=!1,o=()=>{a||(a=!0,e>0&&r("LCP",e),r("CLS",t),s>0&&r("INP",s))},l=()=>{document.visibilityState==="hidden"&&o()};return document.addEventListener("visibilitychange",l),()=>{o(),document.removeEventListener("visibilitychange",l);for(let d of i)d?.disconnect()}}function ps(r){if(!r)return!1;try{return new Headers(r).has("next-router-prefetch")}catch{return!1}}var fs=/^[a-z][a-z0-9_-]{0,31}$/;function W(r){return r.split("/").map(e=>{if(e==="")return e;let t=e.split(";",1)[0],s=t.toLowerCase();return fs.test(s)&&(s.match(/\d/g)?.length??0)<=2&&t.slice(1)===s.slice(1)&&s.split(/[-_]/).every(n=>n.length<=16)?s:":id"}).join("/")}function gs(r){if(!r)return"";try{let e=new URL(r);return`${e.origin}${W(e.pathname)}`}catch{return W(r.split(/[?#]/,1)[0]??"")}}var _t=/^custom\.[a-z0-9_]{1,48}$/,ms=/^[a-z][a-z0-9_]{0,63}$/,pt=r=>ms.test(r)||_t.test(r),vs=50,ft=[5e3,3e4,12e4,6e5],ys=100,ne=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[l,d]of Object.entries(t.start??{})){if(!pt(l))throw new TypeError(`consent.start: ${JSON.stringify(l)} is not a consent key (a platform key, or custom.<name>)`);if(d!=="granted"&&d!=="denied")throw new TypeError(`consent.start.${l} is granted or denied`)}for(let l of t.customKeys??[])if(!_t.test(l))throw new TypeError(`consent.customKeys: ${JSON.stringify(l)} is not custom.<name> (a-z, 0-9 and _, 48 at most)`);if(t.textVersion!==void 0&&(t.textVersion===""||t.textVersion.length>64))throw new TypeError("consent.textVersion: 1 to 64 characters");this.userApi=e.userApi,this.deviceApi=e.deviceApi,this.session=e.session,this.socket=e.socket,this.ref=e.ref,this.installation=e.installation,this.start={...t.start},this.textVersion=t.textVersion,this.customKeys=[...t.customKeys??[]],this.storeKey=`palbase.consent.${e.origin}.${e.installation.id}`,this.now=e.now??Date.now;let s=this.load(),i=()=>ct(this.installation)?{}:{unknown:{on:!0,w:this.stamp()}},n={whose:null,install:this.installation.id,choices:{},unsent:[]};typeof s!="object"?this.kept={...n,...s==="unreadable"?{unknown:{on:!0,w:this.stamp()}}:i()}:s.whose==null&&s.install!==void 0&&s.install!==this.installation.id?this.kept={...n,unsent:s.unsent.filter(l=>l.user!==null),...s.keys?{keys:s.keys}:{},...i()}:this.kept=s,e.session.onChange((l,d)=>{this.engaged&&(l==="SIGNED_IN"&&d?this.signedIn(d):(l==="SIGNED_OUT"||l==="SESSION_EXPIRED")&&this.signedOut())});let a=globalThis;typeof a.addEventListener=="function"&&(a.addEventListener("storage",l=>{(l.key===this.storeKey||l.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(P(this.kept)!==this.holder()||this.gpcRefuses(e))return"denied";let t=vt(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||P(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(!pt(a))throw new TypeError(`${JSON.stringify(a)} is not a consent key (a platform key, or custom.<name>)`);if(o!=="granted"&&o!=="denied")throw new TypeError(`${a}: a choice is granted or denied`)}if(t.length===0)return;this.engage();let s=this.chosenAt(),i=this.session.snapshot()?.userId??null,n=this.states();for(let[a,o]of t)this.queue({key:a,state:o,source:"app",chosen_at:s,user:i,...this.textVersion!==void 0?{text_version:this.textVersion}:{}});this.commit(n),this.send()}onChange(e){return this.listeners.add(e),()=>this.listeners.delete(e)}async region(){this.engage();let e=await this.subject();if(this.readFor!==e)try{await this.read(e)}catch(t){if(!this.kept.region)throw t}return this.kept.region}async needsAsking(e){this.engage();let t=await this.subject();this.readFor!==t&&await this.read(t).catch(()=>{});let s=e??(await this.keys()).map(l=>l.key),i=await this.platform().catch(()=>this.kept.keys??[]),n=new Set(i.filter(l=>l.ads).map(l=>l.key)),a=this.kept.region?.jurisdiction==="us",o=new Date(this.now());return o.setUTCMonth(o.getUTCMonth()-12),s.filter(l=>{let d=this.kept.choices[l];return a&&n.has(l)&&d?.last_denied_at!==void 0&&Date.parse(d.last_denied_at)>o.getTime()?!1:!d||d.state==="unset"?!0:this.textVersion!==void 0&&d.source==="app"&&d.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{[O]:A(this.installation)}}platform(){return this.platformKeys??=this.deviceApi.listConsentKeys().then(e=>(this.kept={...this.kept,keys:e.data.keys},this.commit(),e.data.keys),e=>{if(this.platformKeys=void 0,this.kept.keys)return this.kept.keys;throw e}),this.platformKeys}async read(e){let s=(await(e===null?this.deviceApi:this.userApi(e)).getConsents({query:{installation_id:this.installation.id},headers:this.secret()})).data;this.adopt(s,e)}adopt(e,t,s=[]){if(this.kept={...this.kept,region:e.region},(this.session.snapshot()?.userId??null)!==t){this.commit();return}let i=this.states(),n={};for(let h of e.choices)n[h.key]={state:h.state,source:h.source,chosen_at:h.chosen_at,...h.text_version!==void 0?{text_version:h.text_version}:{},...h.last_denied_at!==void 0?{last_denied_at:h.last_denied_at}:{}};let a=s.filter(h=>n[h.key]?.state!==h.state||Date.parse(n[h.key]?.chosen_at??"")!==Date.parse(h.chosen_at)).map(h=>D(h.key,h)),l=P(this.kept)===(t===null?`device:${this.installation.id}`:`user:${t}`)?Object.entries(this.kept.choices).filter(([,h])=>h.provisional).map(([h,g])=>D(h,g)):[];if(a.length+l.length>0&&(this.kept={...this.kept,void:N([...this.kept.void??[],...a,...l])}),t===null&&this.kept.resetAt!==void 0)for(let[h,g]of Object.entries(n))Date.parse(g.chosen_at)<this.kept.resetAt&&delete n[h];let d=new Set(Object.entries(n).map(([h,g])=>D(h,g))),c=(this.kept.void??[]).filter(h=>d.has(h));c.length>0&&(this.kept={...this.kept,unvoid:N([...this.kept.unvoid??[],...c])});let f=Pt(this.kept),u;if(P(this.kept)!==(t===null?`device:${this.installation.id}`:`user:${t}`))u=n;else{u={};for(let h of[...new Set([...Object.keys(this.kept.choices),...Object.keys(n)])].sort()){let g=this.kept.choices[h],v=g&&!g.provisional&&!f.has(D(h,g))?g:void 0,_=n[h],M=_&&(!v||Date.parse(_.chosen_at)>=Date.parse(v.chosen_at))?_:v;M&&(u[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 g=u[h.key];g&&Date.parse(g.chosen_at)>Date.parse(h.chosen_at)||(u[h.key]=gt(h,g))}let{install:S,...m}=this.kept;this.kept={...m,whose:t,...t===null?{install:this.installation.id}:{},choices:u,unknown:{on:!1,w:this.stamp()}},this.readFor=t,this.stale=!1,this.commit(i),this.refuseByGpc()}async refused(e,t,s){let i=t===e&&P(this.kept)===(t===null?`device:${this.installation.id}`:`user:${t}`),n=N([...this.kept.void??[],...s.map(l=>D(l.key,l))]);if(!i){this.kept={...this.kept,void:n},this.commit();return}let a=this.states(),o={...this.kept.choices};for(let l of s){if(this.kept.unsent.some(c=>c.key===l.key&&(c.user===null||c.user===e)&&Date.parse(c.chosen_at)>Date.parse(l.chosen_at)))continue;let d=o[l.key];o[l.key]={state:"denied",source:"app",chosen_at:l.chosen_at,...d?.last_denied_at!==void 0?{last_denied_at:d.last_denied_at}:{},provisional:!0}}this.kept={...this.kept,choices:o,void:n},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=P(this.kept)===(t.user===null?`device:${this.installation.id}`:`user:${t.user}`);this.kept={...this.kept,unsent:Tt([...this.kept.unsent,t]),...s?{choices:{...this.kept.choices,[t.key]:gt(t,this.kept.choices[t.key])}}:{}}}send(){if(this.sendAgain=!0,this.sending)return;let e=(async()=>{for(;this.sendAgain;)this.sendAgain=!1,await this.sendUnsent()||(this.sendAgain=!1)})();this.sending=e,e.finally(()=>{this.sending===e&&(this.sending=void 0)})}async sendUnsent(){this.retryTimer&&clearTimeout(this.retryTimer),this.retryTimer=void 0;let e=this.session.snapshot()?.userId??null;try{e=await this.subject();let t=await this.sendOf(null,e);if(e!==null&&(this.kept.link===e||t)){let s;try{s=(await this.userApi(e).linkConsents({headers:this.secret(),body:{installation_id:this.installation.id}})).data}catch(i){if(!bt(i))throw i}if(this.kept.link===e){let{link:i,...n}=this.kept;this.kept=n,this.commit()}if(s)this.adopt(s,e);else{let i=this.states();this.kept={...this.kept,unknown:{on:!0,w:this.stamp()}},this.commit(i)}}if(e!==null&&await this.sendOf(e,e),this.owesRead()&&(await this.read(e),this.owesRead()))throw new Error("the choices are not read yet");return this.retries=0,!0}catch{return(this.session.snapshot()?.userId??null)!==e?(this.sendAgain=!0,!0):(this.retryLater(),!1)}}async sendOf(e,t){let s=!1;for(;;){let i=this.nextGroup(e);if(i.length===0)return s;let n=i[0],a=e===null?this.deviceApi:this.userApi(e),o;try{o=(await a.chooseConsents({headers:this.secret(),body:{installation_id:this.installation.id,...n.source==="gpc"?{source:"gpc"}:{},...n.text_version!==void 0?{text_version:n.text_version}:{},choices:i.map(l=>({key:l.key,state:l.state,chosen_at:l.chosen_at}))}})).data}catch(l){if(!bt(l))throw l;if(i.length>1){this.kept={...this.kept,unsent:this.kept.unsent.map(d=>i.some(c=>wt(c,d))?{...d,alone:!0}:d)},this.commit();continue}}this.kept={...this.kept,unsent:this.kept.unsent.filter(l=>!i.some(d=>wt(d,l))),done:N([...this.kept.done??[],...i.map(re)])},this.commit(),o?(s=!0,e===t&&this.adopt(o,e,i)):await this.refused(t,e,i)}}nextGroup(e){let t=this.kept.unsent.filter(a=>a.user===e&&(e!==null||(a.device??this.installation.id)===this.installation.id)),s=t[0];if(!s)return[];let i=[],n=new Set;if(s.alone)return[s];for(let a of t)if(!n.has(a.key)&&(n.add(a.key),!(a.alone||a.source!==s.source||a.text_version!==s.text_version)&&(i.push(a),i.length===vs)))break;return i}retryLater(){if(this.retryTimer)return;let e=ft[Math.min(this.retries,ft.length-1)];this.retries++,this.retryTimer=setTimeout(()=>{this.retryTimer=void 0,this.send()},e),this.retryTimer.unref?.()}signedIn(e){this.readFor=void 0,this.kept={...this.kept,link:e.userId},this.commit(),this.follow(e),this.send()}signedOut(){this.unfollow(),this.readFor=void 0;let e=this.states(),t=this.chosenAt(),s=new Set([...Object.entries(this.kept.choices).filter(([,o])=>o.state!=="unset").map(([o])=>o),...this.kept.unsent.filter(o=>o.user===null&&(o.device??this.installation.id)===this.installation.id).map(o=>o.key),...Object.keys(this.start),...this.customKeys,...(this.kept.keys??[]).map(o=>o.key)]),i={};for(let[o,l]of Object.entries(this.kept.choices))i[o]={state:"unset",source:"app",chosen_at:t,...l.last_denied_at!==void 0?{last_denied_at:l.last_denied_at}:{}};let n=o=>o.user===null&&(o.device??this.installation.id)===this.installation.id,a=this.kept.unsent.filter(n);this.kept={whose:null,install:this.installation.id,resetAt:Date.parse(t),choices:i,unsent:this.kept.unsent.filter(o=>!n(o)),...this.kept.void?{void:this.kept.void}:{},...this.kept.unvoid?{unvoid:this.kept.unvoid}:{},done:N([...this.kept.done??[],...a.map(re)]),...this.kept.region?{region:this.kept.region}:{},...this.kept.keys?{keys:this.kept.keys}:{},...this.kept.gpc?{gpc:this.kept.gpc}:{},...this.kept.unknown?{unknown:this.kept.unknown}:{}};for(let o of s)this.queue({key:o,state:"unset",source:"app",chosen_at:t,user:null});this.commit(e),this.send(),this.refuseByGpc()}follow(e){this.unfollow();let t=this.socket.channel(`consents:${this.ref}:${e.userId}`),s={userId:e.userId,channel:t,off:()=>{},version:-1},i=[t.on("broadcast",n=>{n.event==="changed"&&this.changed(s,Ce(n.payload))}),t.on("state_snapshot",n=>this.held(s,Ce(St(n.entries)))),t.on("state_diff",n=>this.held(s,Ce(St(n.set))))];s.off=()=>i.forEach(n=>n()),this.watch=s,t.join().catch(()=>{})}unfollow(){let e=this.watch;e&&(this.watch=void 0,e.off(),e.channel.leave())}held(e,t){t!==void 0&&this.changed(e,t)}changed(e,t){if(this.watch===e){if(t!==void 0){if(t<=e.version)return;e.version=t}this.read(e.userId).catch(()=>{this.watch===e&&(this.stale=!0,this.retryLater())})}}gpcRefuses(e){if(!this.gpc||!(this.kept.keys??[]).some(n=>n.key===e&&n.ads))return!1;let t=vt(this.kept,e);if(t?.state==="denied")return!1;let s=this.kept.gpc?.[P(this.kept)],i=s!==void 0&&(this.kept.whose!=null||s>=(this.kept.resetAt??0));return!(t?.state==="granted"&&t.source==="app"&&i&&Date.parse(t.chosen_at)>s)}async refuseByGpc(){if(!this.gpc||P(this.kept)!==this.holder())return;let e;try{e=await this.platform()}catch{return}if(P(this.kept)!==this.holder())return;let t=this.session.snapshot()?.userId??null,s=e.filter(a=>a.ads&&this.gpcRefuses(a.key)&&!this.kept.unsent.some(o=>o.key===a.key&&o.source==="gpc"&&o.user===t));if(s.length===0)return;let i=this.chosenAt(),n=this.states();for(let a of s)this.queue({key:a.key,state:"denied",source:"gpc",chosen_at:i,user:t});this.kept={...this.kept,gpc:{...this.kept.gpc,[P(this.kept)]:Date.parse(i)}},this.commit(n),this.send()}states(){let e=new Map;for(let t of[...Object.keys(this.start),...Object.keys(this.kept.choices)])e.set(t,this.state(t));return e}tell(e){let t=this.states();for(let s of new Set([...e.keys(),...t.keys()])){let i=t.get(s);if(e.get(s)!==i)for(let n of[...this.listeners])try{n(s,i)}catch{}}}load(){let e;try{e=kt()?.getItem(this.storeKey)}catch{return"unreadable"}if(e==null)return"empty";try{let t=JSON.parse(e);if(Ss(t))return t}catch{}return"unreadable"}reload(){let e=this.load();if(typeof e!="object"){this.write();return}let t=this.states();this.kept=mt(e,this.kept,"theirs",this.holder()),P(e)===P(this.kept)&&yt(this.kept)!==yt(e)&&this.write(),this.tell(t);let s=this.session.snapshot()?.userId??null;this.engaged&&this.kept.unsent.some(i=>i.user!==null&&i.user===s||i.user===null&&(i.device??this.installation.id)===this.installation.id)&&this.retryLater(),this.engaged&&this.refuseByGpc()}commit(e=this.states()){let t=this.load();typeof t=="object"&&(this.kept=mt(t,this.kept,"ours",this.holder())),this.write(),this.tell(e)}write(){try{kt()?.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 gt(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 D(r,e){return`${r}|${e.provisional?"provisional":e.state}|${Date.parse(e.chosen_at)}`}function Pt(r){let e=new Set(r.unvoid??[]);return new Set((r.void??[]).filter(t=>!e.has(t)))}var ie={denied:2,unset:1,granted:0};function ws(r,e,t,s){let i=e&&!s.has(D(r,e))?e:void 0,n=t&&!s.has(D(r,t))?t:void 0;if(!i||!n)return i??n;let a=Date.parse(i.chosen_at),o=Date.parse(n.chosen_at);return a!==o?a>o?i:n:ie[i.state]!==ie[n.state]?ie[i.state]>ie[n.state]?i:n:i.provisional?n:i}function bs(r,e){return!r||!e?r??e:e.w>r.w||e.w===r.w&&e.on?e:r}function mt(r,e,t,s){let i=N([...r.void??[],...e.void??[]]),n=N([...r.unvoid??[],...e.unvoid??[]]),a=Pt({void:i,unvoid:n}),o={},l,d={...r.gpc};for(let[v,_]of Object.entries(e.gpc??{}))d[v]=Math.max(d[v]??0,_);let c;if(P(r)===P(e)){l=e;for(let v of[...new Set([...Object.keys(r.choices),...Object.keys(e.choices)])].sort()){let _=ws(v,r.choices[v],e.choices[v],a);_&&(o[v]=_)}c=bs(r.unknown,e.unknown)}else{l=P(e)===s?e:P(r)===s?r:t==="ours"?e:r;for(let[v,_]of Object.entries(l.choices))a.has(D(v,_))||(o[v]=_);c=l.unknown}let f=N([...r.done??[],...e.done??[]]),u=Tt([...r.unsent,...e.unsent]).filter(v=>!f.includes(re(v))),S=t==="ours"?e:r,m=t==="ours"?r:e,h=S.region??m.region,g=S.keys??m.keys;return{whose:l.whose??null,...l.whose==null&&l.install!==void 0?{install:l.install}:{},...l.whose==null&&(r.resetAt!==void 0||e.resetAt!==void 0)&&P(r)===P(e)?{resetAt:Math.max(r.resetAt??0,e.resetAt??0)}:l.whose==null&&l.resetAt!==void 0?{resetAt:l.resetAt}:{},choices:o,unsent:u,...f.length>0?{done:f}:{},...i.length>0?{void:i}:{},...n.length>0?{unvoid:n}:{},...S.link!==void 0?{link:S.link}:{},...h?{region:h}:{},...Object.keys(d).length>0?{gpc:d}:{},...g?{keys:g}:{},...c?{unknown:c}:{}}}function re(r){return`${r.user??`device:${r.device??""}`}|${r.key}|${r.state}|${r.source}|${r.chosen_at}`}function vt(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 P(r){return r.whose!=null?`user:${r.whose}`:`device:${r.install??""}`}function N(r){return[...new Set(r)].slice(-ys)}function yt(r){return JSON.stringify(r,(e,t)=>typeof t=="object"&&t!==null&&!Array.isArray(t)?Object.fromEntries(Object.entries(t).sort(([s],[i])=>s.localeCompare(i))):t)}function Tt(r){let e=new Map;for(let t of r){let s=re(t),i=e.get(s);e.set(s,i?i.alone||!t.alone?i:{...i,alone:!0}:t)}return[...e.values()].sort((t,s)=>Date.parse(t.chosen_at)-Date.parse(s.chosen_at))}var ks=new Set(["granted","denied","unset"]);function Ss(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,l)=>{if(typeof o!="object"||o===null)return!1;let d=o;return ks.has(d.state)&&typeof d.chosen_at=="string"&&(!l||typeof d.key=="string")},s=o=>o===void 0||typeof o=="object"&&o!==null&&typeof o.on=="boolean"&&typeof o.w=="number",i=r,n=o=>o===void 0||Array.isArray(o)&&o.every(l=>typeof l=="string"),a=i.whose===void 0||i.whose===null||typeof i.whose=="string";return Object.values(e.choices).every(o=>t(o,!1))&&e.unsent.every(o=>t(o,!0))&&(i.gpc===void 0||typeof i.gpc=="object"&&i.gpc!==null&&Object.values(i.gpc).every(o=>typeof o=="number"))&&s(i.unknown)&&n(i.done)&&n(i.void)&&n(i.unvoid)&&a}function wt(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 bt(r){return r instanceof b&&r.status>=400&&r.status<500&&r.status!==401&&r.status!==408&&r.status!==429}function kt(){try{return globalThis.localStorage}catch{return}}function St(r){let e=typeof r=="object"&&r!==null?r.version:void 0;return typeof e=="object"&&e!==null?e.v:void 0}function Ce(r){let e=typeof r=="object"&&r!==null?r.version:void 0;return typeof e=="number"&&Number.isFinite(e)?e:void 0}var _s=`
1
+ /*! palbase 0.65.0 — Palbase SDK License (see LICENSE) */
2
+ import{e as tt,g as st,h as it}from"./2HJQSGOO.js";import{h as nt}from"./4NHRUBEF.js";import{a as et}from"./ARRJICH3.js";import{r as Ye,t as Qe,u as Ze}from"./YP3QTS4L.js";import{b as B,c as $,e as Be,f as Je,i as _e,j as V,k as ze}from"./KU6B2OXP.js";import{a as Xe,b as J}from"./G2JBUBZO.js";import{b,d as K}from"./DLMWZYLL.js";function Qt(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 C=class extends Error{code="session_changed";constructor(e){super(e),this.name="SessionChangedError"}};function rt(){let r=null;return{load:()=>r,save:e=>{r=e},clear:()=>{r=null},shared:!1}}function at(r){let e=null,t=!0,s=()=>{try{return globalThis.localStorage}catch{return}};return{shared:!0,load(){try{let i=s()?.getItem(r);return i==null?t?null:e:JSON.parse(i)}catch{return e}},save(i){e=i;try{let n=s();if(!n)throw new Error("no storage");n.setItem(r,JSON.stringify(i)),t=!0}catch{t=!1}},clear(){e=null,t=!0;try{s()?.removeItem(r)}catch{}},watch(i){let n=globalThis;if(typeof n.addEventListener!="function")return()=>{};let a=o=>{(o.key===r||o.key===null)&&i()};return n.addEventListener("storage",a),()=>n.removeEventListener?.("storage",a)}}}function Pe(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 Zt=6e4,es=15e3;function ts(r,e,t){let s=r?globalThis.navigator?.locks:void 0;return s?s.request(e,t):t()}var X=class{current=null;loaded;inflight=null;endReason=null;listeners=new Set;store;refresher;isRejected;now;lockName;refreshTimeoutMs;mode;constructor(e,t,s,i={}){this.store=e,this.refresher=t,this.isRejected=s,this.now=i.now??Date.now,this.lockName=i.lockName??"palbase.session.refresh",this.refreshTimeoutMs=i.refreshTimeoutMs??es,this.mode=i.refresh??"behind",this.loaded=Promise.resolve(e.load()).then(n=>{this.current=n}),e.watch?.(()=>{this.reconcile()})}async session(){return await this.loaded,this.current}snapshot(){return this.current}onChange(e){return this.listeners.add(e),()=>this.listeners.delete(e)}async set(e,t,s){await this.loaded;let i=t==="TOKEN_REFRESHED"?this.current:null,n={accessToken:e.access_token,refreshToken:e.refresh_token,expiresAt:this.now()+e.expires_in*1e3,userId:s?.id??i?.userId??Pe(e.access_token),user:s??i?.user};return this.current=n,await this.store.save(n),this.emit(t,n),n}async setUser(e,t){await this.loaded,!(!this.current||!t||this.current.userId!==t.userId)&&(this.current={...this.current,user:e},await this.store.save(this.current),this.emit("USER_UPDATED",this.current))}async clear(e,t){await this.loaded;let s=this.current;this.current=null,this.inflight=null;let i=await this.store.load();(!i||!s||i.userId===s.userId)&&await this.store.clear(),s&&(e==="SESSION_EXPIRED"&&(this.endReason=t??"revoked"),this.emit(e,null))}async accessToken(){await this.loaded;let e=this.current;if(!e)return;let t=e.expiresAt-this.now();if(t>Zt)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=ts(this.store.shared===!0,this.lockName,async()=>{await this.loaded;let t=this.current;if(!t)throw new C("no session to refresh");let s=await this.adoptStored(t);if(s)return s;try{let i=await this.withTimeout(this.refresher(t.refreshToken));if(this.current?.refreshToken!==t.refreshToken)throw new C("the session changed while it was refreshed");return await this.set(i,"TOKEN_REFRESHED")}catch(i){throw this.isRejected(i)&&this.current?.refreshToken===t.refreshToken&&await this.clear("SESSION_EXPIRED",Qt(i)),i}});return this.inflight=e,e.finally(()=>{this.inflight===e&&(this.inflight=null)}).catch(()=>{}),e}async adoptStored(e){let t=await this.store.load();if(!t)throw this.current=null,this.emit("SIGNED_OUT",null),new C("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 C("another user signed in in another tab");if(t.refreshToken!==e.refreshToken&&t.expiresAt>=e.expiresAt)return this.current=t,this.emit("TOKEN_REFRESHED",t),t}async reconcile(){await this.loaded;let e=this.current,t=await this.store.load();if(!e){t&&(this.current=t,this.emit("SIGNED_IN",t));return}await this.adoptStored(e).catch(()=>{})}withTimeout(e){let t,s=new Promise((i,n)=>{t=setTimeout(()=>n(new Error(`the refresh did not answer within ${this.refreshTimeoutMs/1e3} s`)),this.refreshTimeoutMs)});return Promise.race([e,s]).finally(()=>clearTimeout(t))}emit(e,t){(e==="SIGNED_IN"||e==="SIGNED_OUT")&&(this.endReason=null);for(let s of this.listeners)try{s(e,t)}catch{}}};var Te=class{state="closed";refusal;logSeq;joinRef=null;refusals=0;retry=null;asking=0;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,e&&(this.refusals=0);let s=this.joinWaiters.splice(0);for(let i of s)e?i.resolve():i.reject(new Error(`join ${this.name} refused: ${JSON.stringify(t)}`));if(e)for(let i of[...this.joiners])try{i()}catch{}}closed(e){this.state="closed",this.joinRef=null,this.retry&&clearTimeout(this.retry),this.retry=null,this.refusals=0;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{}}},Y=class{ws=null;opening=null;ref=0;channels=new Map;lastJoin=new Map;replies=new Map;heartbeat=null;heartbeatRef=null;reconnectTimer=null;attempts=0;closedByUs=!1;asks=0;epoch=0;wasOpen=!1;current="idle";statusListeners=new Set;reconnects=0;opts;constructor(e){this.opts=e}get status(){return this.current}onStatus(e){return this.statusListeners.add(e),()=>{this.statusListeners.delete(e)}}setStatus(e){if(this.current!==e){this.current=e;for(let t of[...this.statusListeners])try{t(e)}catch{}}}channel(e,t){let s=this.channels.get(e);return s||this.channels.set(e,s=new Te(e,this,t)),s}disconnect(){this.closedByUs=!0,this.wasOpen=!1,this.epoch++,this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=null,this.attempts=0,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.asking=0,t.closed("the socket was closed");this.lastJoin.clear(),this.current!=="idle"&&this.setStatus("disconnected")}async tokenChanged(){if(this.askRefusedAgain(),!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})}askRefusedAgain(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null,this.open().catch(()=>{}));for(let e of this.channels.values())e.state==="refused"&&(e.retry&&clearTimeout(e.retry),e.retry=null,this.askAgain(e))}join(e){if(e.state="joining",this.ws?.readyState===1){this.sendJoin(e);return}this.reconnectTimer||this.open().catch(()=>{})}settle(e,t,s){e.settled(t,s),t||this.askAgainLater(e)}askAgainLater(e){let t=this.opts.refusedBackoff??[1e3,2e3,5e3,1e4,3e4,6e4,3e5],s=t[Math.min(e.refusals,t.length-1)]*(.8+Math.random()*.4);e.refusals++,e.retry&&clearTimeout(e.retry),e.retry=F(setTimeout(()=>{e.retry=null,this.askAgain(e)},s))}askAgain(e){this.reconnectTimer||this.channels.get(e.name)!==e||e.state!=="refused"||this.join(e)}joinWanted(){for(let e of this.channels.values())e.state==="refused"&&(e.retry&&clearTimeout(e.retry),e.retry=null,e.state="joining"),e.state==="joining"&&this.sendJoin(e)}leave(e){e.retry&&clearTimeout(e.retry),e.retry=null,e.state==="joined"&&(this.ws?.readyState===1&&this.push(e.joinRef,e.topic,"phx_leave",{}),this.lastJoin.get(e.name)===e&&this.lastJoin.delete(e.name)),e.state="closed",this.channels.delete(e.name)}async request(e,t,s){let i=this.ws;if(this.channels.get(e.name)!==e||e.state!=="joined"||i?.readyState!==1)return{status:"error",response:{reason:"not joined"}};let n=this.nextRef(),a=JSON.stringify([e.joinRef,n,e.topic,t,s]),o=this.awaitReply(n);return i.send(a),o}open(){if(this.ws?.readyState===1)return Promise.resolve();if(this.opening)return this.opening;this.closedByUs=!1,this.current!=="reconnecting"&&this.setStatus("connecting");let e=this.opts.webSocket??globalThis.WebSocket,t=`${this.opts.baseUrl.replace(/^http/,"ws")}/realtime/v1/websocket?vsn=2.0.0&apikey=${encodeURIComponent(this.opts.publishableKey)}`,s=new Promise((i,n)=>{let a;try{a=new e(t)}catch(o){this.setStatus("reconnecting");let l=o instanceof Error?o.message:String(o);for(let d of this.channels.values())d.state==="joining"&&this.settle(d,!1,{reason:l});n(o);return}this.ws=a,a.onopen=()=>{if(this.ws!==a){a.close(1e3),n(new Error("the socket was closed"));return}this.attempts=0,this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=null,this.wasOpen&&this.reconnects++,this.wasOpen=!0,this.startHeartbeat(),this.setStatus("connected"),this.joinWanted(),i()},a.onmessage=o=>this.receive(String(o.data)),a.onerror=()=>n(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,e.onmessage=null,this.stopHeartbeat();for(let[,i]of this.replies)i("error",{reason:"socket closed"});this.replies.clear();for(let i of this.channels.values())i.state==="joined"&&(i.state="joining");if(this.closedByUs)return;if(![...this.channels.values()].some(i=>i.state==="joining"||i.state==="refused")){this.wasOpen=!1,this.setStatus("disconnected");return}if(this.setStatus("reconnecting"),this.reconnectTimer)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=F(setTimeout(()=>{this.reconnectTimer=null,this.open().catch(()=>{})},s))}async sendJoin(e){if(e.asking)return;let t=++this.asks;e.asking=t;try{await this.ask(e)}finally{e.asking===t&&(e.asking=0)}}async ask(e){let t=this.ws;if(t?.readyState!==1)return;let s=this.epoch,i;try{i=await this.opts.accessToken()}catch(c){s===this.epoch&&this.ws===t&&this.channels.get(e.name)===e&&e.state==="joining"&&this.settle(e,!1,{reason:c instanceof Error?c.message:String(c)});return}if(s!==this.epoch||this.channels.get(e.name)!==e||e.state!=="joining"||this.ws!==t||t.readyState!==1)return;let n=this.nextRef();e.joinRef=n;let a=this.awaitReply(n),o={broadcast:{self:!1}};e.logSeq!==void 0&&(o.log={after:e.logSeq}),this.lastJoin.set(e.name,e),this.push(n,e.topic,"phx_join",{access_token:i,config:o},n);let{status:l,response:d}=await a;if(!(l!=="ok"&&this.ws!==t)){if(this.channels.get(e.name)!==e||e.state!=="joining"){this.lastJoin.get(e.name)===e&&(this.lastJoin.delete(e.name),l==="ok"&&this.ws?.readyState===1&&this.push(n,e.topic,"phx_leave",{}));return}if(l==="timeout"){this.askOnLater(e);return}this.settle(e,l==="ok",d)}}askOnLater(e){let t=this.opts.refusedBackoff??[1e3,2e3,5e3,1e4,3e4,6e4,3e5],s=t[Math.min(e.refusals,t.length-1)]*(.8+Math.random()*.4);e.refusals++,e.retry&&clearTimeout(e.retry),e.retry=F(setTimeout(()=>{e.retry=null,this.channels.get(e.name)===e&&e.state==="joining"&&this.ws?.readyState===1&&this.sendJoin(e)},s))}awaitReply(e){return new Promise(t=>{let s=F(setTimeout(()=>{this.replies.delete(e),t({status:"timeout",response:{reason:"no reply"}})},this.opts.replyTimeoutMs??1e4));this.replies.set(e,(i,n)=>{clearTimeout(s),this.replies.delete(e),t({status:i,response:n})})})}receive(e){let t;try{t=JSON.parse(e)}catch{return}if(!Array.isArray(t)||t.length!==5||typeof t[2]!="string"||typeof t[3]!="string")return;let[s,i,n,a,o]=t,l=typeof o=="object"&&o!==null?o:{};if(a==="phx_reply"&&typeof i=="string"){if(i===this.heartbeatRef){this.heartbeatRef=null;return}this.replies.get(i)?.(String(l.status),l.response??{});return}let d=[...this.channels.values()].find(c=>c.topic===n);if(d&&!((a==="phx_close"||a==="phx_error")&&typeof s=="string"&&d.joinRef!==null&&s!==d.joinRef)){if(a==="phx_close"){if(d.state!=="joined")return;d.state="refused",d.refusal={reason:"closed by the server"},this.askAgainLater(d);return}if(a==="phx_error"){d.state="joining",F(setTimeout(()=>this.channels.get(d.name)===d&&d.state==="joining"&&this.ws?.readyState===1&&void this.sendJoin(d),1e3));return}d.deliver(a,l)}}push(e,t,s,i,n=this.nextRef()){this.ws?.send(JSON.stringify([e,n,t,s,i]))}nextRef(){return String(++this.ref)}startHeartbeat(){this.stopHeartbeat(),this.heartbeat=F(setInterval(()=>{if(this.heartbeatRef!==null){this.heartbeatRef=null;let e=this.ws;e?.close(4e3),e&&this.dropped(e);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 F(r){return r.unref?.(),r}var O="X-Palbase-Installation-Secret",Z="X-Palbase-Installation",lt=new WeakMap;function A(r){return lt.get(r)}var dt=new WeakSet;function ct(r){return dt.has(r)}var ss=/^[A-Za-z0-9_-]{43}$/,Q=class{id;constructor(e){let t=`palbase.installation.secret.${e}`,s;try{let i=ot()?.getItem(t);i&&ss.test(i)&&(s=i)}catch{}if(!s){dt.add(this),s=ht(crypto.getRandomValues(new Uint8Array(32)));try{ot()?.setItem(t,s)}catch{}}lt.set(this,s),this.id=is(s)}};function is(r){return ht(rs(new TextEncoder().encode(r)).subarray(0,16))}function ot(){try{return globalThis.localStorage}catch{return}}function ht(r){let e="";for(let t of r)e+=String.fromCharCode(t);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}var ns=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]),I=(r,e)=>r>>>e|r<<32-e;function rs(r){let e=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),t=new Uint8Array(Math.ceil((r.length+9)/64)*64);t.set(r),t[r.length]=128;let s=new DataView(t.buffer);s.setUint32(t.length-8,Math.floor(r.length/536870912)),s.setUint32(t.length-4,r.length*8>>>0);let i=new Uint32Array(64);for(let o=0;o<t.length;o+=64){for(let g=0;g<16;g++)i[g]=s.getUint32(o+g*4);for(let g=16;g<64;g++){let v=I(i[g-15],7)^I(i[g-15],18)^i[g-15]>>>3,_=I(i[g-2],17)^I(i[g-2],19)^i[g-2]>>>10;i[g]=i[g-16]+v+i[g-7]+_|0}let[l,d,c,f,u,S,m,h]=e;for(let g=0;g<64;g++){let v=h+(I(u,6)^I(u,11)^I(u,25))+(u&S^~u&m)+ns[g]+i[g]|0,_=(I(l,2)^I(l,13)^I(l,22))+(l&d^l&c^d&c)|0;h=m,m=S,S=u,u=f+v|0,f=c,c=d,d=l,l=v+_|0}e[0]+=l,e[1]+=d,e[2]+=c,e[3]+=f,e[4]+=u,e[5]+=S,e[6]+=m,e[7]+=h}let n=new Uint8Array(32),a=new DataView(n.buffer);for(let o=0;o<8;o++)a.setUint32(o*4,e[o]);return n}var os=30*6e4,ut=1e3,ls=100,ds=60*1024,ee=()=>globalThis.crypto?.randomUUID?globalThis.crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;function q(){try{return globalThis.localStorage}catch{return}}var se=class{api;closingApi;perfApi;closingPerfApi;flushMs;flushAt;now;anonKey;sessionKey;onceKey;events=[];samples=[];timer;memoryAnon;memorySession;memoryOnce;appVersion;stopAuto;session;consent;identifyPending=!1;listeners=new Set;people={set:e=>this.person({set:e}),setOnce:e=>this.person({set_once:e}),unset:e=>this.person({unset:[...e]}),add:e=>this.person({add:e})};constructor(e,t,s,i,n,a,o={}){this.session=s,this.consent=i;let l={send:c=>e.send(this.granted("analytics")?{...c,headers:{...c.headers,[Z]:n.id}}:c)};this.api=B.client(l);let d={send:c=>(this.granted("analytics")?e:t).send(c)};this.perfApi=B.client(d),this.closingApi=B.client({send:c=>l.send({...c,keepalive:!0})}),this.closingPerfApi=B.client({send:c=>d.send({...c,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(c=>{c==="SIGNED_IN"?(this.identifyPending=!0,this.soon()):c==="SIGNED_OUT"&&(this.identifyPending=!1,this.reset())}),i.onChange((c,f)=>{f!=="granted"&&(c==="analytics"?(this.events=[],this.identifyPending=!1,this.samples=this.samples.map(xe),this.reset()):c==="performance"&&(this.samples=[]))})}capture(e,t){for(let i of this.listeners)i(e,t);if(!this.granted("analytics"))return;let s=this.now();this.hold({event:e,distinct_id:this.distinctId(),properties:t,timestamp:s,session_id:this.sessionId(s),...this.appVersion?{app_version:this.appVersion}:{}})}captureOnce(e,t,s){if(!this.granted("analytics"))return;let i=this.sessionId(this.now()),n=this.readOnce(),a=n?.session===i?n.keys:[];a.includes(e)||(this.writeOnce({session:i,keys:[...a,e].slice(-500)}),this.capture(t,s))}readOnce(){try{let e=q()?.getItem(this.onceKey);if(e)return JSON.parse(e)}catch{}return this.memoryOnce}writeOnce(e){this.memoryOnce=e;try{q()?.setItem(this.onceKey,JSON.stringify(e))}catch{}}onEvent(e){return this.listeners.add(e),()=>this.listeners.delete(e)}page(e={}){let t=globalThis.location,s=globalThis.document,i=e.url??(t?`${t.origin}${W(t.pathname)}`:"");if(!i)return;let n=e.referrer??gs(s?.referrer);this.capture("$pageview",{...e.properties,url:i,...e.title??s?.title?{title:e.title??s?.title}:{},...n?{referrer:n}:{}})}async identify(e){this.identifyPending=!1;let t=this.session.snapshot()?.userId;!t||!this.granted("analytics")||(await this.flush(),await this.sendIdentify(this.api,t,e))}async sendIdentify(e,t,s){try{await e.identify({body:{distinct_id:t,anonymous_id:this.anonymousId(),traits:s,timestamp:this.now(),sent_at:this.now()}})}catch{}}reset(){this.memoryAnon=void 0,this.memorySession=void 0,this.memoryOnce=void 0;try{q()?.removeItem(this.anonKey),q()?.removeItem(this.sessionKey),q()?.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(xe)):this.samples=[];let t=e?this.closingApi:this.api,s=e?this.closingPerfApi:this.perfApi,i=this.now(),n=this.session.snapshot()?.userId;for(this.identifyPending&&n&&this.granted("analytics")&&(this.identifyPending=!1,await this.sendIdentify(t,n));this.events.length>0;){let a=this.take(this.events,e);try{await t.batch({body:{events:a.map(o=>({...o,sent_at:i}))}})}catch{}}for(;this.samples.length>0;){let a=this.take(this.samples,e);try{await s.sendPerf({body:{items:a}})}catch{}}}start(e={}){this.stopAuto?.(),this.appVersion=e.appVersion;let t=globalThis;if(typeof t.addEventListener!="function"||typeof globalThis.document>"u")return()=>{};let s=[];e.pageViews!==!1&&s.push(this.watchPages(t)),e.webVitals!==!1&&s.push(us((a,o)=>this.sample("web_vital",a,o))),e.network!==!1&&s.push(this.watchFetch(t));let i=()=>{document.visibilityState==="hidden"&&this.flush(!0)},n=()=>{this.flush(!0)};return document.addEventListener("visibilitychange",i),t.addEventListener("pagehide",n),s.push(()=>{document.removeEventListener("visibilitychange",i),t.removeEventListener("pagehide",n)}),this.stopAuto=()=>{for(let 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>=ut&&this.events.shift(),this.events.push(e),this.soon()}sample(e,t,s,i={}){if(!this.granted("performance"))return;this.samples.length>=ut&&this.samples.shift();let n={row_id:ee(),trace_type:e,name:t,value:Math.max(0,s),timestamp:this.now(),...i};this.samples.push(this.granted("analytics")?{...n,distinct_id:this.distinctId()}:xe(n)),this.soon()}soon(){if(this.events.length+this.samples.length>=this.flushAt){this.flush();return}this.timer||(this.timer=setTimeout(()=>{this.flush()},this.flushMs),this.timer.unref?.())}take(e,t){let s=e.splice(0,ls);if(!t)return s;for(;s.length>1&&JSON.stringify(s).length>ds;)e.unshift(s.pop());return s}distinctId(){return this.session.snapshot()?.userId??this.anonymousId()}anonymousId(){let e=q();try{let t=e?.getItem(this.anonKey);if(t)return t;let s=`anon_${ee()}`;if(e?.setItem(this.anonKey,s),e?.getItem(this.anonKey)===s)return s}catch{}return this.memoryAnon??=`anon_${ee()}`,this.memoryAnon}sessionId(e){let t=q(),s=this.memorySession;try{let n=t?.getItem(this.sessionKey);n&&(s=JSON.parse(n))}catch{}let i=s&&e-s.last<os?{id:s.id,last:e}:{id:`ses_${ee()}`,last:e};this.memorySession=i;try{t?.setItem(this.sessionKey,JSON.stringify(i))}catch{}return i.id}watchPages(e){let t="",s=()=>{let o=`${e.location.origin}${e.location.pathname}`;if(o===t)return;t=o;let l=`${e.location.origin}${W(e.location.pathname)}`;setTimeout(()=>this.page({url:l}),0)},i=e.history,n=i.pushState.bind(i),a=i.replaceState.bind(i);return i.pushState=(...o)=>{n(...o),s()},i.replaceState=(...o)=>{a(...o),s()},e.addEventListener("popstate",s),s(),()=>{i.pushState=n,i.replaceState=a,e.removeEventListener("popstate",s)}}watchFetch(e){let t=e.fetch;if(typeof t!="function")return()=>{};let s=async(i,n)=>{let a=performance.now(),o=i instanceof Request?i:void 0,l=(n?.method??o?.method??"GET").toUpperCase(),d;try{d=new URL(o?.url??String(i),e.location.href)}catch{d=void 0}let c=!!d&&d.pathname.startsWith("/analytics/")||ps(n?.headers??o?.headers);try{let f=await t(i,n);return d&&!c&&this.sample("network",`${l} ${d.origin}${W(d.pathname)}`,performance.now()-a,{attrs:{status:String(f.status)},...f.headers.get("x-request-id")?{request_id:f.headers.get("x-request-id")}:{}}),f}catch(f){throw d&&!c&&this.sample("network",`${l} ${d.origin}${W(d.pathname)}`,performance.now()-a,{attrs:{status:"0"}}),f}};return e.fetch=s,()=>{e.fetch===s&&(e.fetch=t)}}};function xe(r){let{distinct_id:e,request_id:t,...s}=r;return s}var cs=r=>r.entryType==="layout-shift"&&"value"in r&&"hadRecentInput"in r,hs=r=>r.entryType==="event"||r.entryType==="first-input";function te(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 us(r){if(typeof document>"u"||typeof performance>"u"||typeof performance.getEntriesByType!="function")return()=>{};let e=0,t=0,s=0,i=[te("largest-contentful-paint",d=>{for(let c of d)e=Math.max(e,c.startTime)}),te("layout-shift",d=>{for(let c of d)cs(c)&&!c.hadRecentInput&&(t+=c.value)}),te("event",d=>{for(let c of d)hs(c)&&(s=Math.max(s,c.duration))}),te("paint",d=>{for(let c of d)c.name==="first-contentful-paint"&&r("FCP",c.startTime)})],n=performance.getEntriesByType("navigation")[0];n&&n.responseStart>0&&r("TTFB",n.responseStart);let a=!1,o=()=>{a||(a=!0,e>0&&r("LCP",e),r("CLS",t),s>0&&r("INP",s))},l=()=>{document.visibilityState==="hidden"&&o()};return document.addEventListener("visibilitychange",l),()=>{o(),document.removeEventListener("visibilitychange",l);for(let d of i)d?.disconnect()}}function ps(r){if(!r)return!1;try{return new Headers(r).has("next-router-prefetch")}catch{return!1}}var fs=/^[a-z][a-z0-9_-]{0,31}$/;function W(r){return r.split("/").map(e=>{if(e==="")return e;let t=e.split(";",1)[0],s=t.toLowerCase();return fs.test(s)&&(s.match(/\d/g)?.length??0)<=2&&t.slice(1)===s.slice(1)&&s.split(/[-_]/).every(n=>n.length<=16)?s:":id"}).join("/")}function gs(r){if(!r)return"";try{let e=new URL(r);return`${e.origin}${W(e.pathname)}`}catch{return W(r.split(/[?#]/,1)[0]??"")}}var _t=/^custom\.[a-z0-9_]{1,48}$/,ms=/^[a-z][a-z0-9_]{0,63}$/,pt=r=>ms.test(r)||_t.test(r),vs=50,ft=[5e3,3e4,12e4,6e5],ys=100,ne=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[l,d]of Object.entries(t.start??{})){if(!pt(l))throw new TypeError(`consent.start: ${JSON.stringify(l)} is not a consent key (a platform key, or custom.<name>)`);if(d!=="granted"&&d!=="denied")throw new TypeError(`consent.start.${l} is granted or denied`)}for(let l of t.customKeys??[])if(!_t.test(l))throw new TypeError(`consent.customKeys: ${JSON.stringify(l)} is not custom.<name> (a-z, 0-9 and _, 48 at most)`);if(t.textVersion!==void 0&&(t.textVersion===""||t.textVersion.length>64))throw new TypeError("consent.textVersion: 1 to 64 characters");this.userApi=e.userApi,this.deviceApi=e.deviceApi,this.session=e.session,this.socket=e.socket,this.ref=e.ref,this.installation=e.installation,this.start={...t.start},this.textVersion=t.textVersion,this.customKeys=[...t.customKeys??[]],this.storeKey=`palbase.consent.${e.origin}.${e.installation.id}`,this.now=e.now??Date.now;let s=this.load(),i=()=>ct(this.installation)?{}:{unknown:{on:!0,w:this.stamp()}},n={whose:null,install:this.installation.id,choices:{},unsent:[]};typeof s!="object"?this.kept={...n,...s==="unreadable"?{unknown:{on:!0,w:this.stamp()}}:i()}:s.whose==null&&s.install!==void 0&&s.install!==this.installation.id?this.kept={...n,unsent:s.unsent.filter(l=>l.user!==null),...s.keys?{keys:s.keys}:{},...i()}:this.kept=s,e.session.onChange((l,d)=>{this.engaged&&(l==="SIGNED_IN"&&d?this.signedIn(d):(l==="SIGNED_OUT"||l==="SESSION_EXPIRED")&&this.signedOut())});let a=globalThis;typeof a.addEventListener=="function"&&(a.addEventListener("storage",l=>{(l.key===this.storeKey||l.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(P(this.kept)!==this.holder()||this.gpcRefuses(e))return"denied";let t=vt(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||P(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(!pt(a))throw new TypeError(`${JSON.stringify(a)} is not a consent key (a platform key, or custom.<name>)`);if(o!=="granted"&&o!=="denied")throw new TypeError(`${a}: a choice is granted or denied`)}if(t.length===0)return;this.engage();let s=this.chosenAt(),i=this.session.snapshot()?.userId??null,n=this.states();for(let[a,o]of t)this.queue({key:a,state:o,source:"app",chosen_at:s,user:i,...this.textVersion!==void 0?{text_version:this.textVersion}:{}});this.commit(n),this.send()}onChange(e){return this.listeners.add(e),()=>this.listeners.delete(e)}async region(){this.engage();let e=await this.subject();if(this.readFor!==e)try{await this.read(e)}catch(t){if(!this.kept.region)throw t}return this.kept.region}async needsAsking(e){this.engage();let t=await this.subject();this.readFor!==t&&await this.read(t).catch(()=>{});let s=e??(await this.keys()).map(l=>l.key),i=await this.platform().catch(()=>this.kept.keys??[]),n=new Set(i.filter(l=>l.ads).map(l=>l.key)),a=this.kept.region?.jurisdiction==="us",o=new Date(this.now());return o.setUTCMonth(o.getUTCMonth()-12),s.filter(l=>{let d=this.kept.choices[l];return a&&n.has(l)&&d?.last_denied_at!==void 0&&Date.parse(d.last_denied_at)>o.getTime()?!1:!d||d.state==="unset"?!0:this.textVersion!==void 0&&d.source==="app"&&d.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{[O]:A(this.installation)}}platform(){return this.platformKeys??=this.deviceApi.listConsentKeys().then(e=>(this.kept={...this.kept,keys:e.data.keys},this.commit(),e.data.keys),e=>{if(this.platformKeys=void 0,this.kept.keys)return this.kept.keys;throw e}),this.platformKeys}async read(e){let s=(await(e===null?this.deviceApi:this.userApi(e)).getConsents({query:{installation_id:this.installation.id},headers:this.secret()})).data;this.adopt(s,e)}adopt(e,t,s=[]){if(this.kept={...this.kept,region:e.region},(this.session.snapshot()?.userId??null)!==t){this.commit();return}let i=this.states(),n={};for(let h of e.choices)n[h.key]={state:h.state,source:h.source,chosen_at:h.chosen_at,...h.text_version!==void 0?{text_version:h.text_version}:{},...h.last_denied_at!==void 0?{last_denied_at:h.last_denied_at}:{}};let a=s.filter(h=>n[h.key]?.state!==h.state||Date.parse(n[h.key]?.chosen_at??"")!==Date.parse(h.chosen_at)).map(h=>D(h.key,h)),l=P(this.kept)===(t===null?`device:${this.installation.id}`:`user:${t}`)?Object.entries(this.kept.choices).filter(([,h])=>h.provisional).map(([h,g])=>D(h,g)):[];if(a.length+l.length>0&&(this.kept={...this.kept,void:N([...this.kept.void??[],...a,...l])}),t===null&&this.kept.resetAt!==void 0)for(let[h,g]of Object.entries(n))Date.parse(g.chosen_at)<this.kept.resetAt&&delete n[h];let d=new Set(Object.entries(n).map(([h,g])=>D(h,g))),c=(this.kept.void??[]).filter(h=>d.has(h));c.length>0&&(this.kept={...this.kept,unvoid:N([...this.kept.unvoid??[],...c])});let f=Pt(this.kept),u;if(P(this.kept)!==(t===null?`device:${this.installation.id}`:`user:${t}`))u=n;else{u={};for(let h of[...new Set([...Object.keys(this.kept.choices),...Object.keys(n)])].sort()){let g=this.kept.choices[h],v=g&&!g.provisional&&!f.has(D(h,g))?g:void 0,_=n[h],M=_&&(!v||Date.parse(_.chosen_at)>=Date.parse(v.chosen_at))?_:v;M&&(u[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 g=u[h.key];g&&Date.parse(g.chosen_at)>Date.parse(h.chosen_at)||(u[h.key]=gt(h,g))}let{install:S,...m}=this.kept;this.kept={...m,whose:t,...t===null?{install:this.installation.id}:{},choices:u,unknown:{on:!1,w:this.stamp()}},this.readFor=t,this.stale=!1,this.commit(i),this.refuseByGpc()}async refused(e,t,s){let i=t===e&&P(this.kept)===(t===null?`device:${this.installation.id}`:`user:${t}`),n=N([...this.kept.void??[],...s.map(l=>D(l.key,l))]);if(!i){this.kept={...this.kept,void:n},this.commit();return}let a=this.states(),o={...this.kept.choices};for(let l of s){if(this.kept.unsent.some(c=>c.key===l.key&&(c.user===null||c.user===e)&&Date.parse(c.chosen_at)>Date.parse(l.chosen_at)))continue;let d=o[l.key];o[l.key]={state:"denied",source:"app",chosen_at:l.chosen_at,...d?.last_denied_at!==void 0?{last_denied_at:d.last_denied_at}:{},provisional:!0}}this.kept={...this.kept,choices:o,void:n},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=P(this.kept)===(t.user===null?`device:${this.installation.id}`:`user:${t.user}`);this.kept={...this.kept,unsent:Tt([...this.kept.unsent,t]),...s?{choices:{...this.kept.choices,[t.key]:gt(t,this.kept.choices[t.key])}}:{}}}send(){if(this.sendAgain=!0,this.sending)return;let e=(async()=>{for(;this.sendAgain;)this.sendAgain=!1,await this.sendUnsent()||(this.sendAgain=!1)})();this.sending=e,e.finally(()=>{this.sending===e&&(this.sending=void 0)})}async sendUnsent(){this.retryTimer&&clearTimeout(this.retryTimer),this.retryTimer=void 0;let e=this.session.snapshot()?.userId??null;try{e=await this.subject();let t=await this.sendOf(null,e);if(e!==null&&(this.kept.link===e||t)){let s;try{s=(await this.userApi(e).linkConsents({headers:this.secret(),body:{installation_id:this.installation.id}})).data}catch(i){if(!bt(i))throw i}if(this.kept.link===e){let{link:i,...n}=this.kept;this.kept=n,this.commit()}if(s)this.adopt(s,e);else{let i=this.states();this.kept={...this.kept,unknown:{on:!0,w:this.stamp()}},this.commit(i)}}if(e!==null&&await this.sendOf(e,e),this.owesRead()&&(await this.read(e),this.owesRead()))throw new Error("the choices are not read yet");return this.retries=0,!0}catch{return(this.session.snapshot()?.userId??null)!==e?(this.sendAgain=!0,!0):(this.retryLater(),!1)}}async sendOf(e,t){let s=!1;for(;;){let i=this.nextGroup(e);if(i.length===0)return s;let n=i[0],a=e===null?this.deviceApi:this.userApi(e),o;try{o=(await a.chooseConsents({headers:this.secret(),body:{installation_id:this.installation.id,...n.source==="gpc"?{source:"gpc"}:{},...n.text_version!==void 0?{text_version:n.text_version}:{},choices:i.map(l=>({key:l.key,state:l.state,chosen_at:l.chosen_at}))}})).data}catch(l){if(!bt(l))throw l;if(i.length>1){this.kept={...this.kept,unsent:this.kept.unsent.map(d=>i.some(c=>wt(c,d))?{...d,alone:!0}:d)},this.commit();continue}}this.kept={...this.kept,unsent:this.kept.unsent.filter(l=>!i.some(d=>wt(d,l))),done:N([...this.kept.done??[],...i.map(re)])},this.commit(),o?(s=!0,e===t&&this.adopt(o,e,i)):await this.refused(t,e,i)}}nextGroup(e){let t=this.kept.unsent.filter(a=>a.user===e&&(e!==null||(a.device??this.installation.id)===this.installation.id)),s=t[0];if(!s)return[];let i=[],n=new Set;if(s.alone)return[s];for(let a of t)if(!n.has(a.key)&&(n.add(a.key),!(a.alone||a.source!==s.source||a.text_version!==s.text_version)&&(i.push(a),i.length===vs)))break;return i}retryLater(){if(this.retryTimer)return;let e=ft[Math.min(this.retries,ft.length-1)];this.retries++,this.retryTimer=setTimeout(()=>{this.retryTimer=void 0,this.send()},e),this.retryTimer.unref?.()}signedIn(e){this.readFor=void 0,this.kept={...this.kept,link:e.userId},this.commit(),this.follow(e),this.send()}signedOut(){this.unfollow(),this.readFor=void 0;let e=this.states(),t=this.chosenAt(),s=new Set([...Object.entries(this.kept.choices).filter(([,o])=>o.state!=="unset").map(([o])=>o),...this.kept.unsent.filter(o=>o.user===null&&(o.device??this.installation.id)===this.installation.id).map(o=>o.key),...Object.keys(this.start),...this.customKeys,...(this.kept.keys??[]).map(o=>o.key)]),i={};for(let[o,l]of Object.entries(this.kept.choices))i[o]={state:"unset",source:"app",chosen_at:t,...l.last_denied_at!==void 0?{last_denied_at:l.last_denied_at}:{}};let n=o=>o.user===null&&(o.device??this.installation.id)===this.installation.id,a=this.kept.unsent.filter(n);this.kept={whose:null,install:this.installation.id,resetAt:Date.parse(t),choices:i,unsent:this.kept.unsent.filter(o=>!n(o)),...this.kept.void?{void:this.kept.void}:{},...this.kept.unvoid?{unvoid:this.kept.unvoid}:{},done:N([...this.kept.done??[],...a.map(re)]),...this.kept.region?{region:this.kept.region}:{},...this.kept.keys?{keys:this.kept.keys}:{},...this.kept.gpc?{gpc:this.kept.gpc}:{},...this.kept.unknown?{unknown:this.kept.unknown}:{}};for(let o of s)this.queue({key:o,state:"unset",source:"app",chosen_at:t,user:null});this.commit(e),this.send(),this.refuseByGpc()}follow(e){this.unfollow();let t=this.socket.channel(`consents:${this.ref}:${e.userId}`),s={userId:e.userId,channel:t,off:()=>{},version:-1},i=[t.on("broadcast",n=>{n.event==="changed"&&this.changed(s,Ce(n.payload))}),t.on("state_snapshot",n=>this.held(s,Ce(St(n.entries)))),t.on("state_diff",n=>this.held(s,Ce(St(n.set))))];s.off=()=>i.forEach(n=>n()),this.watch=s,t.join().catch(()=>{})}unfollow(){let e=this.watch;e&&(this.watch=void 0,e.off(),e.channel.leave())}held(e,t){t!==void 0&&this.changed(e,t)}changed(e,t){if(this.watch===e){if(t!==void 0){if(t<=e.version)return;e.version=t}this.read(e.userId).catch(()=>{this.watch===e&&(this.stale=!0,this.retryLater())})}}gpcRefuses(e){if(!this.gpc||!(this.kept.keys??[]).some(n=>n.key===e&&n.ads))return!1;let t=vt(this.kept,e);if(t?.state==="denied")return!1;let s=this.kept.gpc?.[P(this.kept)],i=s!==void 0&&(this.kept.whose!=null||s>=(this.kept.resetAt??0));return!(t?.state==="granted"&&t.source==="app"&&i&&Date.parse(t.chosen_at)>s)}async refuseByGpc(){if(!this.gpc||P(this.kept)!==this.holder())return;let e;try{e=await this.platform()}catch{return}if(P(this.kept)!==this.holder())return;let t=this.session.snapshot()?.userId??null,s=e.filter(a=>a.ads&&this.gpcRefuses(a.key)&&!this.kept.unsent.some(o=>o.key===a.key&&o.source==="gpc"&&o.user===t));if(s.length===0)return;let i=this.chosenAt(),n=this.states();for(let a of s)this.queue({key:a.key,state:"denied",source:"gpc",chosen_at:i,user:t});this.kept={...this.kept,gpc:{...this.kept.gpc,[P(this.kept)]:Date.parse(i)}},this.commit(n),this.send()}states(){let e=new Map;for(let t of[...Object.keys(this.start),...Object.keys(this.kept.choices)])e.set(t,this.state(t));return e}tell(e){let t=this.states();for(let s of new Set([...e.keys(),...t.keys()])){let i=t.get(s);if(e.get(s)!==i)for(let n of[...this.listeners])try{n(s,i)}catch{}}}load(){let e;try{e=kt()?.getItem(this.storeKey)}catch{return"unreadable"}if(e==null)return"empty";try{let t=JSON.parse(e);if(Ss(t))return t}catch{}return"unreadable"}reload(){let e=this.load();if(typeof e!="object"){this.write();return}let t=this.states();this.kept=mt(e,this.kept,"theirs",this.holder()),P(e)===P(this.kept)&&yt(this.kept)!==yt(e)&&this.write(),this.tell(t);let s=this.session.snapshot()?.userId??null;this.engaged&&this.kept.unsent.some(i=>i.user!==null&&i.user===s||i.user===null&&(i.device??this.installation.id)===this.installation.id)&&this.retryLater(),this.engaged&&this.refuseByGpc()}commit(e=this.states()){let t=this.load();typeof t=="object"&&(this.kept=mt(t,this.kept,"ours",this.holder())),this.write(),this.tell(e)}write(){try{kt()?.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 gt(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 D(r,e){return`${r}|${e.provisional?"provisional":e.state}|${Date.parse(e.chosen_at)}`}function Pt(r){let e=new Set(r.unvoid??[]);return new Set((r.void??[]).filter(t=>!e.has(t)))}var ie={denied:2,unset:1,granted:0};function ws(r,e,t,s){let i=e&&!s.has(D(r,e))?e:void 0,n=t&&!s.has(D(r,t))?t:void 0;if(!i||!n)return i??n;let a=Date.parse(i.chosen_at),o=Date.parse(n.chosen_at);return a!==o?a>o?i:n:ie[i.state]!==ie[n.state]?ie[i.state]>ie[n.state]?i:n:i.provisional?n:i}function bs(r,e){return!r||!e?r??e:e.w>r.w||e.w===r.w&&e.on?e:r}function mt(r,e,t,s){let i=N([...r.void??[],...e.void??[]]),n=N([...r.unvoid??[],...e.unvoid??[]]),a=Pt({void:i,unvoid:n}),o={},l,d={...r.gpc};for(let[v,_]of Object.entries(e.gpc??{}))d[v]=Math.max(d[v]??0,_);let c;if(P(r)===P(e)){l=e;for(let v of[...new Set([...Object.keys(r.choices),...Object.keys(e.choices)])].sort()){let _=ws(v,r.choices[v],e.choices[v],a);_&&(o[v]=_)}c=bs(r.unknown,e.unknown)}else{l=P(e)===s?e:P(r)===s?r:t==="ours"?e:r;for(let[v,_]of Object.entries(l.choices))a.has(D(v,_))||(o[v]=_);c=l.unknown}let f=N([...r.done??[],...e.done??[]]),u=Tt([...r.unsent,...e.unsent]).filter(v=>!f.includes(re(v))),S=t==="ours"?e:r,m=t==="ours"?r:e,h=S.region??m.region,g=S.keys??m.keys;return{whose:l.whose??null,...l.whose==null&&l.install!==void 0?{install:l.install}:{},...l.whose==null&&(r.resetAt!==void 0||e.resetAt!==void 0)&&P(r)===P(e)?{resetAt:Math.max(r.resetAt??0,e.resetAt??0)}:l.whose==null&&l.resetAt!==void 0?{resetAt:l.resetAt}:{},choices:o,unsent:u,...f.length>0?{done:f}:{},...i.length>0?{void:i}:{},...n.length>0?{unvoid:n}:{},...S.link!==void 0?{link:S.link}:{},...h?{region:h}:{},...Object.keys(d).length>0?{gpc:d}:{},...g?{keys:g}:{},...c?{unknown:c}:{}}}function re(r){return`${r.user??`device:${r.device??""}`}|${r.key}|${r.state}|${r.source}|${r.chosen_at}`}function vt(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 P(r){return r.whose!=null?`user:${r.whose}`:`device:${r.install??""}`}function N(r){return[...new Set(r)].slice(-ys)}function yt(r){return JSON.stringify(r,(e,t)=>typeof t=="object"&&t!==null&&!Array.isArray(t)?Object.fromEntries(Object.entries(t).sort(([s],[i])=>s.localeCompare(i))):t)}function Tt(r){let e=new Map;for(let t of r){let s=re(t),i=e.get(s);e.set(s,i?i.alone||!t.alone?i:{...i,alone:!0}:t)}return[...e.values()].sort((t,s)=>Date.parse(t.chosen_at)-Date.parse(s.chosen_at))}var ks=new Set(["granted","denied","unset"]);function Ss(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,l)=>{if(typeof o!="object"||o===null)return!1;let d=o;return ks.has(d.state)&&typeof d.chosen_at=="string"&&(!l||typeof d.key=="string")},s=o=>o===void 0||typeof o=="object"&&o!==null&&typeof o.on=="boolean"&&typeof o.w=="number",i=r,n=o=>o===void 0||Array.isArray(o)&&o.every(l=>typeof l=="string"),a=i.whose===void 0||i.whose===null||typeof i.whose=="string";return Object.values(e.choices).every(o=>t(o,!1))&&e.unsent.every(o=>t(o,!0))&&(i.gpc===void 0||typeof i.gpc=="object"&&i.gpc!==null&&Object.values(i.gpc).every(o=>typeof o=="number"))&&s(i.unknown)&&n(i.done)&&n(i.void)&&n(i.unvoid)&&a}function wt(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 bt(r){return r instanceof b&&r.status>=400&&r.status<500&&r.status!==401&&r.status!==408&&r.status!==429}function kt(){try{return globalThis.localStorage}catch{return}}function St(r){let e=typeof r=="object"&&r!==null?r.version:void 0;return typeof e=="object"&&e!==null?e.v:void 0}function Ce(r){let e=typeof r=="object"&&r!==null?r.version:void 0;return typeof e=="number"&&Number.isFinite(e)?e:void 0}var _s=`
3
3
  :host{display:block;color-scheme:light dark;font:15px/1.4 system-ui,-apple-system,"Segoe UI",Roboto,sans-serif}
4
4
  .list{display:flex;flex-direction:column;gap:8px;margin:0;padding:0;list-style:none}
5
5
  .item{position:relative;display:flex;gap:12px;align-items:flex-start;padding:12px 40px 12px 12px;border-radius:12px;background:var(--bg);color:var(--fg);cursor:pointer;outline:none}
@@ -1,2 +1,2 @@
1
- /*! palbase 0.63.0 — Palbase SDK License (see LICENSE) */
2
- import{c as D,g as b,l as O,m as _,s as F}from"./EJ7YD4YY.js";import{b as w}from"./LGGBVI33.js";var I=20,M=2048,S=256,j=/^[A-Za-z][A-Za-z0-9_.-]{0,39}$/,m=e=>new w({op:"GetPlacementPaywall",status:0,code:"invalid_attributes",message:e});function L(e){let n='"';for(let t=0;t<e.length;t++){let a=e.charCodeAt(t);a===34?n+='\\"':a===92?n+="\\\\":a>=32&&a<=126?n+=e[t]:n+=`\\u${a.toString(16).padStart(4,"0")}`}return`${n}"`}function T(e){let n=Object.keys(e??{}).sort((i,r)=>i<r?-1:i>r?1:0);if(n.length===0)return;if(n.length>I)throw m(`${n.length} attributes: at most ${I}`);let t=[];for(let i of n){if(!j.test(i))throw m(`the attribute ${JSON.stringify(i)}: a key is a letter, then letters, digits and _ . -, at most 40`);let r=e[i],s;if(typeof r=="string"){if(new TextEncoder().encode(r).length>S)throw m(`the attribute ${JSON.stringify(i)} is over ${S} bytes`);s=L(r)}else if(typeof r=="number"){if(!Number.isFinite(r))throw m(`the attribute ${JSON.stringify(i)} is no number`);s=String(Object.is(r,-0)?0:r)}else if(typeof r=="boolean")s=r?"true":"false";else throw m(`the attribute ${JSON.stringify(i)}: a value is a text, a number or a boolean`);t.push(`"${i}":${s}`)}let a=`{${t.join(",")}}`;if(a.length>M)throw m(`the attributes are ${a.length} bytes: at most ${M}`);return a}function x(e){let n=/^P(\d+)([DWMY])$/.exec(e??"");if(!n)return null;let t=Number(n[1]);if(!Number.isSafeInteger(t)||t<1)return null;switch(n[2]){case"D":return{count:t,unit:"day",months:t*12/365};case"W":return{count:t,unit:"week",months:t*12/52};case"M":return{count:t,unit:"month",months:t};default:return{count:t,unit:"year",months:t*12}}}function R(e){try{return new Intl.NumberFormat("en",{style:"currency",currency:e}).resolvedOptions().maximumFractionDigits??2}catch{return 2}}function $(e,n,t){let a=e/10**R(n);try{return new Intl.NumberFormat(t,{style:"currency",currency:n}).format(a)}catch{return`${a.toFixed(R(n))} ${n}`}}function X(e,n){try{let t=new Intl.NumberFormat(n,{style:"unit",unit:e.unit,unitDisplay:"long"});return e.count>1?t.format(e.count):t.formatToParts(1).filter(i=>i.type==="unit").map(i=>i.value).join("").trim()||t.format(1)}catch{return e.count>1?`${e.count} ${e.unit}s`:e.unit}}var K={en:e=>`${e} free`,tr:e=>`${e} \xFCcretsiz`,de:e=>`${e} kostenlos`,es:e=>`${e} gratis`,it:e=>`${e} gratis`,nl:e=>`${e} gratis`,pt:e=>`${e} gr\xE1tis`,sv:e=>`${e} gratis`,da:e=>`${e} gratis`,nb:e=>`${e} gratis`};function B(e,n){let t;try{t=new Intl.NumberFormat(n,{style:"unit",unit:e.unit,unitDisplay:"long"}).format(e.count)}catch{t=`${e.count} ${e.unit}${e.count>1?"s":""}`}let a=K[n.split("-")[0].toLowerCase()];return a?a(t):t}function H(e,n){try{return new Intl.NumberFormat(n,{style:"percent",maximumFractionDigits:0}).format(e)}catch{return`${Math.round(e*100)}%`}}function E(e,n){let t=new Map,a=new Map;for(let r of e){let s=x(r.period);if(!s)continue;let u=r.price.amount/s.months;t.set(r.key,u),a.set(r.price.currency,Math.max(a.get(r.price.currency)??0,u))}let i={};for(let r of e){let s={product_name:r.productName,price:$(r.price.amount,r.price.currency,n)},u=x(r.period);if(u){s.period=X(u,n),s.price_per_month=$(Math.round(t.get(r.key)),r.price.currency,n);let o=a.get(r.price.currency)??0,d=o>0?Math.floor((1-t.get(r.key)/o)*100)/100:0;d>=.01&&(s.savings=H(d,n))}let l=r.intro?.mode==="free_trial"?x(r.intro.duration):null;l&&(s.trial=B(l,n)),r.offer&&(s.offer_price=$(Math.floor((r.price.amount*(100-r.offer.percentOff)+50)/100),r.price.currency,n)),i[r.key]=s}return i}var V={version:"0.63.0"};var C=`palbase-js/${V.version}`;var k=class{placement;source;definition;assets;offerings;offers;shown;deps;exposed=!1;constructor(n,t,a,i,r,s,u={},l=[]){this.placement=n,this.source=t,this.definition=a,this.assets=u,this.offerings=i,this.offers=l,this.shown=r,this.deps=s}packages(n){return E(Y(this.offerings,O(this.definition),n,Z(this.definition,this.offers)),n)}render(n,t){let a=t.locale??globalThis.navigator?.language??this.definition.default_locale,i=t.appearance===void 0?q():void 0,r=this.packages(a),s=F(n,{definition:this.definition,locale:a,appearance:t.appearance??(i?.matches?"dark":"light"),platform:"web",packages:r,eligible:Object.entries(r).filter(([,o])=>o.trial).map(([o])=>o),offers:this.offers.filter(o=>o.web).map(o=>o.key),links:t.links,assets:this.assets},{onPurchase:async o=>{try{let d=await this.deps.checkout({product:o.product,plan:o.plan,successUrl:t.successUrl,cancelUrl:t.cancelUrl,...o.offer!==void 0?{offer:o.offer}:{}});t.onCheckout?t.onCheckout(d,o):globalThis.location.assign(d)}catch(d){if(!t.onError)throw d;t.onError(d,o)}},onClose:t.onClose,onLink:t.onLink,labels:t.labels}),u=o=>s.update({appearance:o.matches?"dark":"light"});i?.addEventListener?.("change",u),!this.exposed&&this.shown&&(this.exposed=!0,this.deps.expose(this));let l=s.destroy.bind(s);return s.destroy=()=>{i?.removeEventListener?.("change",u),l()},s}};function q(){try{return globalThis.matchMedia?.("(prefers-color-scheme: dark)")}catch{return}}function W(e,n){if(!e)return;let t=n.split("-")[0];return e[n]?.name??e[t]?.name??Object.values(e).find(a=>a.name)?.name}function Y(e,n,t,a=new Map){let i=[];for(let r of n){let[s,u]=r.split("."),l=e.products.find(f=>f.key===s),o=l?.channels.web,d=o?.plans.find(f=>f.key===u);if(!l||!o||!d)continue;let p=a.get(r),g=p?.discount?p.discount.percent:p?.trial?100:void 0;i.push({key:r,productName:W(o.locales,t)??l.key,price:{amount:d.price.amount,currency:d.price.currency},period:d.period,intro:d.intro,...g!==void 0?{offer:{percentOff:g}}:{}})}return i}function Z(e,n){let t=new Map;for(let[a,i]of _(e)){let r=n.find(s=>s.key===i);r?.web&&t.set(a,r)}return t}var G={en:{cta:"Continue",terms:"Terms",privacy:"Privacy"},tr:{cta:"Devam et",terms:"Ko\u015Fullar",privacy:"Gizlilik"},de:{cta:"Weiter",terms:"Bedingungen",privacy:"Datenschutz"},es:{cta:"Continuar",terms:"T\xE9rminos",privacy:"Privacidad"},fr:{cta:"Continuer",terms:"Conditions",privacy:"Confidentialit\xE9"},it:{cta:"Continua",terms:"Termini",privacy:"Privacy"},pt:{cta:"Continuar",terms:"Termos",privacy:"Privacidade"},nl:{cta:"Doorgaan",terms:"Voorwaarden",privacy:"Privacy"},ja:{cta:"\u7D9A\u3051\u308B",terms:"\u5229\u7528\u898F\u7D04",privacy:"\u30D7\u30E9\u30A4\u30D0\u30B7\u30FC"}},N=e=>({type:"button",action:{type:e},content:{type:"text",text:{t:e},size:"caption",color:"muted"}});function Q(e){let n=e.products.flatMap(t=>(t.channels.web?.plans??[]).map(a=>({product:t.key,plan:a.key}))).slice(0,6);return n.length===0?null:{schema:2,name:"Default",default_locale:"en",locales:G,theme:{colors:{light:{background:"#FFFFFF",surface:"#F2F2F7",text:"#111114",muted:"#6B6B70",accent:"#111114",on_accent:"#FFFFFF",stroke:"#E5E5EA"},dark:{background:"#000000",surface:"#1C1C1E",text:"#F5F5F7",muted:"#9A9AA0",accent:"#F5F5F7",on_accent:"#000000",stroke:"#2C2C2E"}},typography:{headline:{size:17,weight:600,text_style:"headline"},caption:{size:13,weight:400,text_style:"footnote"}},radii:{card:14},spacing:{sm:8,md:16,lg:24}},root:{type:"stack",spacing:"md",align:"stretch",style:{padding:"lg"},children:[{type:"stack",axis:"horizontal",children:[{type:"spacer"},{type:"button",action:{type:"close"},content:{type:"icon",name:"close",color:"muted",size:22}}]},{type:"spacer"},{type:"stack",spacing:"sm",align:"stretch",children:n.map(({product:t,plan:a})=>({type:"package",product:t,plan:a,style:{padding:"md",corners:"card",background:"surface",border:{width:1,color:"stroke"}},states:{selected:{border:{width:2,color:"accent"}}},children:[{type:"stack",axis:"horizontal",spacing:"sm",children:[{type:"stack",align:"start",spacing:2,children:[{type:"text",text:"{{product_name}}",size:"headline",align:"start"},{type:"text",text:"{{period}}",size:"caption",color:"muted",align:"start"}]},{type:"spacer"},{type:"text",text:"{{price}}",size:"headline"}]}]}))},{type:"purchase_button",style:{padding:"md",corners:"card",background:"accent"},content:{type:"text",text:{t:"cta"},size:"headline",color:"on_accent"}},{type:"stack",axis:"horizontal",spacing:"md",distribution:"center",children:[N("terms"),N("privacy")]}]}}}function h(){try{return globalThis.localStorage}catch{return}}function ee(e){try{let n=h()?.getItem(e);if(!n)return;let t=JSON.parse(n),a=t?.answer;return typeof a!="object"||a===null||typeof a.paywall_id!="string"||typeof a.version!="number"||typeof a.definition!="object"||a.definition===null||typeof a.offerings!="object"||a.definition.schema!==2?void 0:{etag:typeof t.etag=="string"?t.etag:void 0,answer:a}}catch{return}}function P(e,n){try{n?h()?.setItem(e,JSON.stringify(n)):h()?.removeItem(e)}catch{}}var z=()=>globalThis.crypto?.randomUUID?globalThis.crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,U;function te(e){let n=`palbase.installation.${e}`;try{let t=h()?.getItem(n);if(t&&/^[A-Za-z0-9._:-]{1,128}$/.test(t))return t;let a=z();if(h()?.setItem(n,a),h()?.getItem(n)===a)return a}catch{}return U??=z(),U}async function ye(e,n,t,a,i={}){let{signal:r,fetch:s}=i,u=T(i.attributes),l=`palbase.paywall.${n}.${t}`,o=te(n),p={checkout:a,expose:async c=>{if(c.shown)try{let v={paywall_id:c.shown.paywallId,version:c.shown.version,...c.shown.variant!==void 0?{variant:c.shown.variant}:{},...c.shown.ruleId!==void 0?{rule_id:c.shown.ruleId}:{}};await e.recordPaywallExposure({path:{placement:t},headers:{"X-Palbase-Installation":o},body:v})}catch{}}},g=async(c,v)=>new k(t,v,c.definition,c.offerings,{paywallId:c.paywall_id,version:c.version,...c.variant!==void 0?{variant:c.variant}:{},...c.rule_id!==void 0?{ruleId:c.rule_id}:{}},p,await D(c.assets??[],{signal:r,...s?{fetch:s}:{}}),c.offers??[]),f=ee(l),y;try{y=await e.getPlacementPaywall({path:{placement:t},query:{channel:"web"},headers:{"X-Palbase-Paywall-Schema":2,"X-Palbase-Installation":o,"X-Platform":"web","X-Palbase-SDK":C,...i.appVersion?{"X-Palbase-Client-Version":i.appVersion}:{},...i.app?{"X-Palbase-App":i.app}:{},...i.locale?{"Accept-Language":i.locale}:{},...u!==void 0?{"X-Palbase-Attributes":u}:{},...f?.etag?{"If-None-Match":f.etag}:{}},signal:r})}catch(c){if(c instanceof w&&c.status===404||c instanceof w&&c.status===400&&c.code.startsWith("invalid_"))return P(l,void 0),A(e,t,p,r);if(f&&!r?.aborted)return g(f.answer,"cache");throw c}return y.status===200?(P(l,{etag:y.headers.get("etag")??void 0,answer:y.data}),g(y.data,"server")):y.status===304&&f?g(f.answer,"server"):(P(l,void 0),A(e,t,p,r))}async function A(e,n,t,a){let i=(await e.getOfferings({query:{channel:"web"},signal:a})).data,r=Q(i);return r?new k(n,"default",r,i,void 0,t):null}export{T as a,x as b,$ as c,X as d,E as e,k as f,Q as g,ye as h};
1
+ /*! palbase 0.65.0 — Palbase SDK License (see LICENSE) */
2
+ import{c as D,g as b,l as O,m as _,s as F}from"./YP3QTS4L.js";import{b as w}from"./DLMWZYLL.js";var I=20,M=2048,S=256,j=/^[A-Za-z][A-Za-z0-9_.-]{0,39}$/,m=e=>new w({op:"GetPlacementPaywall",status:0,code:"invalid_attributes",message:e});function L(e){let n='"';for(let t=0;t<e.length;t++){let a=e.charCodeAt(t);a===34?n+='\\"':a===92?n+="\\\\":a>=32&&a<=126?n+=e[t]:n+=`\\u${a.toString(16).padStart(4,"0")}`}return`${n}"`}function T(e){let n=Object.keys(e??{}).sort((i,r)=>i<r?-1:i>r?1:0);if(n.length===0)return;if(n.length>I)throw m(`${n.length} attributes: at most ${I}`);let t=[];for(let i of n){if(!j.test(i))throw m(`the attribute ${JSON.stringify(i)}: a key is a letter, then letters, digits and _ . -, at most 40`);let r=e[i],s;if(typeof r=="string"){if(new TextEncoder().encode(r).length>S)throw m(`the attribute ${JSON.stringify(i)} is over ${S} bytes`);s=L(r)}else if(typeof r=="number"){if(!Number.isFinite(r))throw m(`the attribute ${JSON.stringify(i)} is no number`);s=String(Object.is(r,-0)?0:r)}else if(typeof r=="boolean")s=r?"true":"false";else throw m(`the attribute ${JSON.stringify(i)}: a value is a text, a number or a boolean`);t.push(`"${i}":${s}`)}let a=`{${t.join(",")}}`;if(a.length>M)throw m(`the attributes are ${a.length} bytes: at most ${M}`);return a}function x(e){let n=/^P(\d+)([DWMY])$/.exec(e??"");if(!n)return null;let t=Number(n[1]);if(!Number.isSafeInteger(t)||t<1)return null;switch(n[2]){case"D":return{count:t,unit:"day",months:t*12/365};case"W":return{count:t,unit:"week",months:t*12/52};case"M":return{count:t,unit:"month",months:t};default:return{count:t,unit:"year",months:t*12}}}function R(e){try{return new Intl.NumberFormat("en",{style:"currency",currency:e}).resolvedOptions().maximumFractionDigits??2}catch{return 2}}function $(e,n,t){let a=e/10**R(n);try{return new Intl.NumberFormat(t,{style:"currency",currency:n}).format(a)}catch{return`${a.toFixed(R(n))} ${n}`}}function X(e,n){try{let t=new Intl.NumberFormat(n,{style:"unit",unit:e.unit,unitDisplay:"long"});return e.count>1?t.format(e.count):t.formatToParts(1).filter(i=>i.type==="unit").map(i=>i.value).join("").trim()||t.format(1)}catch{return e.count>1?`${e.count} ${e.unit}s`:e.unit}}var K={en:e=>`${e} free`,tr:e=>`${e} \xFCcretsiz`,de:e=>`${e} kostenlos`,es:e=>`${e} gratis`,it:e=>`${e} gratis`,nl:e=>`${e} gratis`,pt:e=>`${e} gr\xE1tis`,sv:e=>`${e} gratis`,da:e=>`${e} gratis`,nb:e=>`${e} gratis`};function B(e,n){let t;try{t=new Intl.NumberFormat(n,{style:"unit",unit:e.unit,unitDisplay:"long"}).format(e.count)}catch{t=`${e.count} ${e.unit}${e.count>1?"s":""}`}let a=K[n.split("-")[0].toLowerCase()];return a?a(t):t}function H(e,n){try{return new Intl.NumberFormat(n,{style:"percent",maximumFractionDigits:0}).format(e)}catch{return`${Math.round(e*100)}%`}}function E(e,n){let t=new Map,a=new Map;for(let r of e){let s=x(r.period);if(!s)continue;let u=r.price.amount/s.months;t.set(r.key,u),a.set(r.price.currency,Math.max(a.get(r.price.currency)??0,u))}let i={};for(let r of e){let s={product_name:r.productName,price:$(r.price.amount,r.price.currency,n)},u=x(r.period);if(u){s.period=X(u,n),s.price_per_month=$(Math.round(t.get(r.key)),r.price.currency,n);let o=a.get(r.price.currency)??0,d=o>0?Math.floor((1-t.get(r.key)/o)*100)/100:0;d>=.01&&(s.savings=H(d,n))}let l=r.intro?.mode==="free_trial"?x(r.intro.duration):null;l&&(s.trial=B(l,n)),r.offer&&(s.offer_price=$(Math.floor((r.price.amount*(100-r.offer.percentOff)+50)/100),r.price.currency,n)),i[r.key]=s}return i}var V={version:"0.65.0"};var C=`palbase-js/${V.version}`;var k=class{placement;source;definition;assets;offerings;offers;shown;deps;exposed=!1;constructor(n,t,a,i,r,s,u={},l=[]){this.placement=n,this.source=t,this.definition=a,this.assets=u,this.offerings=i,this.offers=l,this.shown=r,this.deps=s}packages(n){return E(Y(this.offerings,O(this.definition),n,Z(this.definition,this.offers)),n)}render(n,t){let a=t.locale??globalThis.navigator?.language??this.definition.default_locale,i=t.appearance===void 0?q():void 0,r=this.packages(a),s=F(n,{definition:this.definition,locale:a,appearance:t.appearance??(i?.matches?"dark":"light"),platform:"web",packages:r,eligible:Object.entries(r).filter(([,o])=>o.trial).map(([o])=>o),offers:this.offers.filter(o=>o.web).map(o=>o.key),links:t.links,assets:this.assets},{onPurchase:async o=>{try{let d=await this.deps.checkout({product:o.product,plan:o.plan,successUrl:t.successUrl,cancelUrl:t.cancelUrl,...o.offer!==void 0?{offer:o.offer}:{}});t.onCheckout?t.onCheckout(d,o):globalThis.location.assign(d)}catch(d){if(!t.onError)throw d;t.onError(d,o)}},onClose:t.onClose,onLink:t.onLink,labels:t.labels}),u=o=>s.update({appearance:o.matches?"dark":"light"});i?.addEventListener?.("change",u),!this.exposed&&this.shown&&(this.exposed=!0,this.deps.expose(this));let l=s.destroy.bind(s);return s.destroy=()=>{i?.removeEventListener?.("change",u),l()},s}};function q(){try{return globalThis.matchMedia?.("(prefers-color-scheme: dark)")}catch{return}}function W(e,n){if(!e)return;let t=n.split("-")[0];return e[n]?.name??e[t]?.name??Object.values(e).find(a=>a.name)?.name}function Y(e,n,t,a=new Map){let i=[];for(let r of n){let[s,u]=r.split("."),l=e.products.find(f=>f.key===s),o=l?.channels.web,d=o?.plans.find(f=>f.key===u);if(!l||!o||!d)continue;let p=a.get(r),g=p?.discount?p.discount.percent:p?.trial?100:void 0;i.push({key:r,productName:W(o.locales,t)??l.key,price:{amount:d.price.amount,currency:d.price.currency},period:d.period,intro:d.intro,...g!==void 0?{offer:{percentOff:g}}:{}})}return i}function Z(e,n){let t=new Map;for(let[a,i]of _(e)){let r=n.find(s=>s.key===i);r?.web&&t.set(a,r)}return t}var G={en:{cta:"Continue",terms:"Terms",privacy:"Privacy"},tr:{cta:"Devam et",terms:"Ko\u015Fullar",privacy:"Gizlilik"},de:{cta:"Weiter",terms:"Bedingungen",privacy:"Datenschutz"},es:{cta:"Continuar",terms:"T\xE9rminos",privacy:"Privacidad"},fr:{cta:"Continuer",terms:"Conditions",privacy:"Confidentialit\xE9"},it:{cta:"Continua",terms:"Termini",privacy:"Privacy"},pt:{cta:"Continuar",terms:"Termos",privacy:"Privacidade"},nl:{cta:"Doorgaan",terms:"Voorwaarden",privacy:"Privacy"},ja:{cta:"\u7D9A\u3051\u308B",terms:"\u5229\u7528\u898F\u7D04",privacy:"\u30D7\u30E9\u30A4\u30D0\u30B7\u30FC"}},N=e=>({type:"button",action:{type:e},content:{type:"text",text:{t:e},size:"caption",color:"muted"}});function Q(e){let n=e.products.flatMap(t=>(t.channels.web?.plans??[]).map(a=>({product:t.key,plan:a.key}))).slice(0,6);return n.length===0?null:{schema:2,name:"Default",default_locale:"en",locales:G,theme:{colors:{light:{background:"#FFFFFF",surface:"#F2F2F7",text:"#111114",muted:"#6B6B70",accent:"#111114",on_accent:"#FFFFFF",stroke:"#E5E5EA"},dark:{background:"#000000",surface:"#1C1C1E",text:"#F5F5F7",muted:"#9A9AA0",accent:"#F5F5F7",on_accent:"#000000",stroke:"#2C2C2E"}},typography:{headline:{size:17,weight:600,text_style:"headline"},caption:{size:13,weight:400,text_style:"footnote"}},radii:{card:14},spacing:{sm:8,md:16,lg:24}},root:{type:"stack",spacing:"md",align:"stretch",style:{padding:"lg"},children:[{type:"stack",axis:"horizontal",children:[{type:"spacer"},{type:"button",action:{type:"close"},content:{type:"icon",name:"close",color:"muted",size:22}}]},{type:"spacer"},{type:"stack",spacing:"sm",align:"stretch",children:n.map(({product:t,plan:a})=>({type:"package",product:t,plan:a,style:{padding:"md",corners:"card",background:"surface",border:{width:1,color:"stroke"}},states:{selected:{border:{width:2,color:"accent"}}},children:[{type:"stack",axis:"horizontal",spacing:"sm",children:[{type:"stack",align:"start",spacing:2,children:[{type:"text",text:"{{product_name}}",size:"headline",align:"start"},{type:"text",text:"{{period}}",size:"caption",color:"muted",align:"start"}]},{type:"spacer"},{type:"text",text:"{{price}}",size:"headline"}]}]}))},{type:"purchase_button",style:{padding:"md",corners:"card",background:"accent"},content:{type:"text",text:{t:"cta"},size:"headline",color:"on_accent"}},{type:"stack",axis:"horizontal",spacing:"md",distribution:"center",children:[N("terms"),N("privacy")]}]}}}function h(){try{return globalThis.localStorage}catch{return}}function ee(e){try{let n=h()?.getItem(e);if(!n)return;let t=JSON.parse(n),a=t?.answer;return typeof a!="object"||a===null||typeof a.paywall_id!="string"||typeof a.version!="number"||typeof a.definition!="object"||a.definition===null||typeof a.offerings!="object"||a.definition.schema!==2?void 0:{etag:typeof t.etag=="string"?t.etag:void 0,answer:a}}catch{return}}function P(e,n){try{n?h()?.setItem(e,JSON.stringify(n)):h()?.removeItem(e)}catch{}}var z=()=>globalThis.crypto?.randomUUID?globalThis.crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,U;function te(e){let n=`palbase.installation.${e}`;try{let t=h()?.getItem(n);if(t&&/^[A-Za-z0-9._:-]{1,128}$/.test(t))return t;let a=z();if(h()?.setItem(n,a),h()?.getItem(n)===a)return a}catch{}return U??=z(),U}async function ye(e,n,t,a,i={}){let{signal:r,fetch:s}=i,u=T(i.attributes),l=`palbase.paywall.${n}.${t}`,o=te(n),p={checkout:a,expose:async c=>{if(c.shown)try{let v={paywall_id:c.shown.paywallId,version:c.shown.version,...c.shown.variant!==void 0?{variant:c.shown.variant}:{},...c.shown.ruleId!==void 0?{rule_id:c.shown.ruleId}:{}};await e.recordPaywallExposure({path:{placement:t},headers:{"X-Palbase-Installation":o},body:v})}catch{}}},g=async(c,v)=>new k(t,v,c.definition,c.offerings,{paywallId:c.paywall_id,version:c.version,...c.variant!==void 0?{variant:c.variant}:{},...c.rule_id!==void 0?{ruleId:c.rule_id}:{}},p,await D(c.assets??[],{signal:r,...s?{fetch:s}:{}}),c.offers??[]),f=ee(l),y;try{y=await e.getPlacementPaywall({path:{placement:t},query:{channel:"web"},headers:{"X-Palbase-Paywall-Schema":2,"X-Palbase-Installation":o,"X-Platform":"web","X-Palbase-SDK":C,...i.appVersion?{"X-Palbase-Client-Version":i.appVersion}:{},...i.app?{"X-Palbase-App":i.app}:{},...i.locale?{"Accept-Language":i.locale}:{},...u!==void 0?{"X-Palbase-Attributes":u}:{},...f?.etag?{"If-None-Match":f.etag}:{}},signal:r})}catch(c){if(c instanceof w&&c.status===404||c instanceof w&&c.status===400&&c.code.startsWith("invalid_"))return P(l,void 0),A(e,t,p,r);if(f&&!r?.aborted)return g(f.answer,"cache");throw c}return y.status===200?(P(l,{etag:y.headers.get("etag")??void 0,answer:y.data}),g(y.data,"server")):y.status===304&&f?g(f.answer,"server"):(P(l,void 0),A(e,t,p,r))}async function A(e,n,t,a){let i=(await e.getOfferings({query:{channel:"web"},signal:a})).data,r=Q(i);return r?new k(n,"default",r,i,void 0,t):null}export{T as a,x as b,$ as c,X as d,E as e,k as f,Q as g,ye as h};
@@ -1,4 +1,4 @@
1
- /*! palbase 0.63.0 — Palbase SDK License (see LICENSE) */
2
- import{f as m}from"./5TXSFJYI.js";import{AsyncLocalStorage as O}from"node:async_hooks";function h(n,e){return new Proxy(e,{get(s,t,i){if(c.getStore()?.services===void 0)return Reflect.get(s,t,i);let o=R(n,t,s),r=o[t];return typeof r=="function"?r.bind(o):r}})}function R(n,e,s){let t=c.getStore()?.services;if(t===void 0)return s;let i=t[n];if(i!==void 0)return i;if(n==="Log"||typeof e=="symbol"||e==="then")return s;throw new Error(`${n}.${String(e)} was read, but this test did not provide ${n}. Pass it: withServices({ ${n}: \u2026 }, () => \u2026)`)}var P=Symbol.for("palbase.backend.requestScope"),c=globalThis[P]??=new O,d,w,E,G={get ai(){if(!d)throw new Error("Palbase.ai is called before the app is served (serve() binds it)");return d.ai}};function H(n){d=n}function F(n){w=n}var T=h("Gateways",{to(n,e){if(!w)throw new Error("Palbase.gateways is reached before the app is served (createApp() binds it)");return w.to(n,e)}}),Z=new Proxy({},{get(n,e){if(e==="gateways")return T;if(e==="ai")return E??=m({server:G});if(!d)throw new Error(`Palbase.${String(e)} is reached before the app is served (serve() binds it)`);return d[e]}}),B=new Proxy({},{get(n,e){let s=c.getStore(),t=s?.database;if(!t)throw new Error(s?.services?`Database.${String(e)} was read, and this test gave no Database: withServices({ Database: fake.raw }, \u2026)`:s?`Database.${String(e)}: this app declares no database \u2014 PalbaseFactory.create(\u2026, { db: { schemas } })`:`Database.${String(e)} is reached outside a request: it is the request's transaction, reached from a handler, a service it calls or an @On`);let i=t[e];return typeof i=="function"?i.bind(t):i}});function l(n,e,s){let t={time:new Date().toISOString(),level:n,msg:e},i=c.getStore();if(i&&(t.request_id=i.requestId),s)for(let[r,a]of Object.entries(s))t[r]=a instanceof Error?{name:a.name,message:a.message,stack:a.stack}:a;let o=k(t);n==="error"||n==="warn"?process.stderr.write(`${o}
1
+ /*! palbase 0.65.0 — Palbase SDK License (see LICENSE) */
2
+ import{f as m}from"./63TUW6P7.js";import{AsyncLocalStorage as O}from"node:async_hooks";function h(n,e){return new Proxy(e,{get(s,t,i){if(c.getStore()?.services===void 0)return Reflect.get(s,t,i);let o=R(n,t,s),r=o[t];return typeof r=="function"?r.bind(o):r}})}function R(n,e,s){let t=c.getStore()?.services;if(t===void 0)return s;let i=t[n];if(i!==void 0)return i;if(n==="Log"||typeof e=="symbol"||e==="then")return s;throw new Error(`${n}.${String(e)} was read, but this test did not provide ${n}. Pass it: withServices({ ${n}: \u2026 }, () => \u2026)`)}var P=Symbol.for("palbase.backend.requestScope"),c=globalThis[P]??=new O,d,w,E,G={get ai(){if(!d)throw new Error("Palbase.ai is called before the app is served (serve() binds it)");return d.ai}};function H(n){d=n}function F(n){w=n}var T=h("Gateways",{to(n,e){if(!w)throw new Error("Palbase.gateways is reached before the app is served (createApp() binds it)");return w.to(n,e)}}),Z=new Proxy({},{get(n,e){if(e==="gateways")return T;if(e==="ai")return E??=m({server:G});if(!d)throw new Error(`Palbase.${String(e)} is reached before the app is served (serve() binds it)`);return d[e]}}),B=new Proxy({},{get(n,e){let s=c.getStore(),t=s?.database;if(!t)throw new Error(s?.services?`Database.${String(e)} was read, and this test gave no Database: withServices({ Database: fake.raw }, \u2026)`:s?`Database.${String(e)}: this app declares no database \u2014 PalbaseFactory.create(\u2026, { db: { schemas } })`:`Database.${String(e)} is reached outside a request: it is the request's transaction, reached from a handler, a service it calls or an @On`);let i=t[e];return typeof i=="function"?i.bind(t):i}});function l(n,e,s){let t={time:new Date().toISOString(),level:n,msg:e},i=c.getStore();if(i&&(t.request_id=i.requestId),s)for(let[r,a]of Object.entries(s))t[r]=a instanceof Error?{name:a.name,message:a.message,stack:a.stack}:a;let o=k(t);n==="error"||n==="warn"?process.stderr.write(`${o}
3
3
  `):process.stdout.write(`${o}
4
4
  `)}function k(n){try{return JSON.stringify(n)}catch{let e=new WeakSet;try{return JSON.stringify(n,(s,t)=>{if(typeof t=="bigint")return t.toString();if(typeof t=="object"&&t!==null){if(e.has(t))return"[circular]";e.add(t)}return t})}catch{return JSON.stringify({time:n.time,level:n.level,msg:n.msg,request_id:n.request_id,unwritable:"a field of this line could not be written"})}}}var v=h("Log",{debug:(n,e)=>l("debug",n,e),info:(n,e)=>l("info",n,e),warn:(n,e)=>l("warn",n,e),error:(n,e)=>l("error",n,e)});var L=512,_=8,q=64,D=/^[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$/,S={"i-klingon":"tlh","en-gb-oed":"en-GB-oxendict","sgn-be-fr":"sfb","zh-cmn-hans":"cmn-Hans","zh-yue":"yue","hy-arevela":"hy-arevela"};function $(n){let e=n.indexOf("-");return e>0?n.slice(0,e):n}function j(n){let e=n.split("-"),s=(e[0]??"").toLowerCase();return s==="mo"&&e.length===1?"ro-MD":s==="tl"?(e[0]="fil",e.join("-")):s==="sh"?(e[0]="sr",e.length>1&&/^[A-Za-z]{4}$/.test(e[1]??"")||e.splice(1,0,"Latn"),e.join("-")):n}function I(n){let e=n.trim().replaceAll("_","-");if(e===""||e==="*"||e.length>q)return;let s=e.toLowerCase(),t=Object.hasOwn(S,s)?S[s]:void 0;if(t===void 0){try{t=Intl.getCanonicalLocales(j(e))[0]}catch{return}if(t===void 0)return}let i=$(t);if(!(i===""||i==="und"||i==="mul"))return t}function z(n){let e=n.split("-"),s=e.findIndex((r,a)=>a>0&&r.length===1),t=s>0?e.slice(0,s):e,i=[],o=r=>{i.includes(r)||i.push(r)};for(let r=t.length;r>1||r===t.length;r--)o(t.slice(0,r).join("-"));if(!t.slice(1).some(r=>/^[A-Za-z]{4}$/.test(r)))try{let r=new Intl.Locale(t.join("-")).maximize().script;r&&o(`${t[0]}-${r}`)}catch{}return o(t[0]),i}function Y(n,e){let s=[],t=i=>{i!==""&&!s.includes(i)&&s.push(i)};if(n!==null&&n.length<=L){let i=[];for(let o of n.split(",")){let r=o.trim();if(r==="")continue;let a=1,f=r.indexOf(";");if(f>=0){let A=r.slice(f+1);r=r.slice(0,f).trim();for(let p of A.split(";")){let b=p.indexOf("=");if(b<0||p.slice(0,b).trim().toLowerCase()!=="q")continue;let y=p.slice(b+1).trim(),g=D.test(y)?Number(y):Number.NaN;a=Number.isFinite(g)&&g>=0&&g<=1?g:0}}a>0&&i.push({tag:r,q:a,at:i.length})}i.sort((o,r)=>r.q-o.q||o.at-r.at);for(let{tag:o}of i.slice(0,_)){let r=I(o);if(r!==void 0)for(let a of z(r))t(a)}}return e!==void 0&&e!==""&&t(e),s}function N(n,e,s){let t=n.strings??{},i=Object.hasOwn(t,e)?t[e]:null;for(let o of s){if(o===n.source)break;let r=i!=null&&Object.hasOwn(i,o)?i[o]:void 0;if(typeof r=="string"&&r!=="")return{text:r,locale:o}}return{text:e,locale:n.source}}var C=/\{\{\s*([A-Za-z_][A-Za-z0-9_]*)\s*\}\}/g;function x(n,e){return n.replace(C,(s,t,i,o)=>{if(o[i-1]==="{"||o[i+s.length]==="}")return s;let r=e!==void 0&&Object.hasOwn(e,t)?e[t]:void 0;return r==null?"":String(r)})}var u;function W(n){u=n===void 0?void 0:{root:n,said:!1}}function Q(n,e){let s=c.getStore(),t=s?.strings;if(t===void 0)return u&&!u.said&&s?.services===void 0&&(u.said=!0,v.warn(`[palbase] t(): the app has no palbase/strings (looked in ${u.root}) \u2014 every sentence is said as it is written. \`npx palbase strings\` starts the table; an image takes it with COPY palbase ./palbase`)),x(n,e);let{text:i,locale:o}=N(t,n,s?.locales??[t.source]),r=s?.usedLocales;return r!==void 0&&!r.includes(o)&&r.push(o),x(i,e)}export{h as a,R as b,c,H as d,F as e,Z as f,B as g,v as h,Y as i,W as j,Q as k};
@@ -0,0 +1,18 @@
1
+ /*! palbase 0.65.0 — Palbase SDK License (see LICENSE) */
2
+ import{a as N,c as Ie,d as Oe,e as Me}from"./GFG7WVN2.js";import{a as je}from"./JHM7GTPD.js";import{a as Re}from"./KU6B2OXP.js";import{a as Pe,b as Ce,c as $e}from"./G2JBUBZO.js";import{b as x,d as Ee}from"./DLMWZYLL.js";async function*Ne(e,t={}){let s=e.getReader(),a=new TextDecoder,i="",l="",c=[],u,r=()=>{s.cancel().catch(()=>{})};t.signal?.addEventListener("abort",r,{once:!0});try{if(t.signal?.aborted)return;for(;;){let{done:n,value:o}=await s.read();if(n||t.signal?.aborted)return;t.onBytes?.(),i+=a.decode(o,{stream:!0});for(let d=i.indexOf(`
3
+ `);d>=0;d=i.indexOf(`
4
+ `)){let g=i.slice(0,i[d-1]==="\r"?d-1:d);i=i.slice(d+1),g===""?(l!==""&&(yield u===void 0?{event:l,data:c.join(`
5
+ `)}:{event:l,data:c.join(`
6
+ `),id:u}),l="",c=[],u=void 0):g.startsWith("event:")?l=de(g,6):g.startsWith("data:")?c.push(de(g,5)):g.startsWith("id:")&&(u=de(g,3))}}}finally{t.signal?.removeEventListener("abort",r);try{await s.cancel()}catch{}}}function de(e,t){let s=e.slice(t);return s.startsWith(" ")?s.slice(1):s}var Ft=/\s/;function Z(e,t){for(;t<e.length&&Ft.test(e[t]);)t++;return t}function Be(e,t){let s="";for(let a=t+1;a<e.length;a++){let i=e[a];if(i==='"')return{value:s,complete:!0,empty:!1,at:a+1};if(i!=="\\"){s+=i;continue}let l=e[a+1];if(l===void 0)break;if(l==="u"){let c=e.slice(a+2,a+6);if(c.length<4)break;s+=String.fromCharCode(Number.parseInt(c,16)),a+=5;continue}s+={n:`
7
+ `,t:" ",r:"\r",b:"\b",f:"\f"}[l]??l,a++}return{value:s,complete:!1,empty:!1,at:e.length}}function pe(e,t){t=Z(e,t);let s=e[t];if(s===void 0)return{value:void 0,complete:!1,empty:!0,at:t};if(s==='"')return Be(e,t);if(s==="{")return zt(e,t);if(s==="[")return Kt(e,t);let a=t;for(;a<e.length&&/[-+0-9.A-Za-z]/.test(e[a]);)a++;if(a===e.length)return{value:void 0,complete:!1,empty:!0,at:a};try{return{value:JSON.parse(e.slice(t,a)),complete:!0,empty:!1,at:a}}catch{return{value:void 0,complete:!1,empty:!0,at:e.length}}}function zt(e,t){let s={},a=t+1;for(;;){if(a=Z(e,a),e[a]==="}")return{value:s,complete:!0,empty:!1,at:a+1};if(e[a]===","){a++;continue}if(e[a]!=='"')return{value:s,complete:!1,empty:!1,at:e.length};let i=Be(e,a);if(!i.complete)return{value:s,complete:!1,empty:!1,at:e.length};if(a=Z(e,i.at),e[a]!==":")return{value:s,complete:!1,empty:!1,at:e.length};let l=pe(e,a+1);if(l.empty||Object.defineProperty(s,i.value,{value:l.value,enumerable:!0,writable:!0,configurable:!0}),!l.complete)return{value:s,complete:!1,empty:!1,at:e.length};a=l.at}}function Kt(e,t){let s=[],a=t+1;for(;;){if(a=Z(e,a),e[a]==="]")return{value:s,complete:!0,empty:!1,at:a+1};if(e[a]===","){a++;continue}if(a>=e.length)return{value:s,complete:!1,empty:!1,at:a};let i=pe(e,a);if(i.empty||s.push(i.value),!i.complete)return{value:s,complete:!1,empty:!1,at:e.length};a=i.at}}function ue(e){let t=pe(e,0);return t.empty?void 0:t.value}var w=class extends Error{path;constructor(t,s){super(`${t}: ${s}`),this.name="AISchemaError",this.path=t}},Ht=new Set(["type","properties","required","additionalProperties","items","enum","description","title","minimum","maximum","minLength","maxLength","minItems","maxItems"]),Xt=new Set(["format","pattern","exclusiveMinimum","exclusiveMaximum","multipleOf","uniqueItems","contentEncoding","contentMediaType","default","examples","readOnly","writeOnly","deprecated","$comment"]),Yt=new Set(["object","array","string","integer","number","boolean"]),De=12,We=512,Zt=/^[A-Za-z][A-Za-z0-9_-]{0,63}$/;function B(e,t="answer"){if(!Zt.test(t))throw new w(t||"(name)","a schema name starts with a letter and holds letters, digits, _ and -, 64 at most");let s=e?.["~standard"];if(!s||s.version!==1||typeof s.validate!="function")throw new w(t,"not a Standard Schema: pass a zod (4.2+), valibot or arktype schema");if(!s.jsonSchema||typeof s.jsonSchema.output!="function")throw new w(t,`${s.vendor}'s schema cannot say itself as JSON Schema; use a version that implements Standard JSON Schema`);let a;try{a=s.jsonSchema.output({target:"draft-2020-12",libraryOptions:{unrepresentable:"throw"}})}catch(c){throw new w(t,`the schema has a part JSON Schema cannot say (${c.message}): a function, a transform, a date \u2014 give the model a string and convert it after`)}if(a.type!=="object")throw new w(t,"the answer is an object: wrap the value in z.object({ \u2026 })");let l=ge(a,t,0,{properties:0});return{name:t,json:l,async check(c){let u=await s.validate(c);if(u.issues){let r=u.issues[0],n=(r?.path??[]).map(o=>String(typeof o=="object"?o.key:o)).join(".");throw new w(n?`${t}.${n}`:t,`the model's answer does not match the schema: ${r?.message??"invalid"}`)}return u.value}}}function ge(e,t,s,a){if(s>De)throw new w(t,`nests deeper than ${De} levels, the most the provider takes`);for(let c of["anyOf","oneOf","allOf"])if(c in e)throw new w(t,Qt(e[c])??"is a union of several shapes: the provider holds a model to one shape per field \u2014 use an enum, or one object with every field");for(let c of["$ref","$defs","definitions","$dynamicRef"])if(c in e)throw new w(t,"refers to another schema (a recursive or shared type): the provider takes no references \u2014 write the shape out, a bounded number of levels deep");if(e.type==="object"&&("propertyNames"in e||"patternProperties"in e||e.additionalProperties!==void 0&&e.additionalProperties!==!1))throw new w(t,"accepts fields it does not name (a record, passthrough or catchall): the provider holds a model only to the fields named \u2014 name them");for(let c of["prefixItems","patternProperties","propertyNames","not","if","then","else","dependentRequired","dependentSchemas","const","minProperties","maxProperties","contains","unevaluatedProperties","unevaluatedItems"])if(c in e)throw new w(t,`uses ${c}, which the provider cannot hold a model to`);if(Array.isArray(e.type))throw new w(t,`may be ${e.type.join(" or ")}: one type per field \u2014 a nullable field is not expressible; give it a value that means "none" (an empty string, an enum member)`);let i=e.type;if(typeof i!="string"&&!("enum"in e))throw new w(t,"has no type: the provider holds a model only to a typed value");if(typeof i=="string"&&!Yt.has(i))throw new w(t,`is of type ${i}, which the provider does not take`);let l={};for(let[c,u]of Object.entries(e))if(!(c==="$schema"||c==="id"||c==="$id")&&!Xt.has(c)){if(!Ht.has(c))throw new w(t,`uses ${c}, which the provider cannot hold a model to`);l[c]=u}if("enum"in e&&typeof i!="string"){let c=e.enum,u=new Set(c.map(r=>r===null?"null":typeof r));if(u.size!==1||u.has("null"))throw new w(t,"an enum of values of several types (or with null): one type per field");l.type=u.has("string")?"string":u.has("boolean")?"boolean":"number"}if(i==="object"){let c=e.properties??{},u=Object.keys(c);if(u.length===0)throw new w(t,"is an object with no fields (a record, or any object): the provider holds a model only to named fields \u2014 name them");if(e.additionalProperties!==void 0&&e.additionalProperties!==!1)throw new w(t,"accepts fields it does not name (passthrough, catchall, record): the provider holds a model only to the fields named");if(a.properties+=u.length,a.properties>We)throw new w(t,`the schema has more than ${We} fields in all, the most the provider takes`);let r=new Set(e.required??[]),n={};for(let o of u){if(!r.has(o))throw new w(`${t}.${o}`,'is optional: the provider makes the model write every field \u2014 make it required (give it a value that means "none"), or leave it out of the schema');n[o]=ge(c[o],`${t}.${o}`,s+1,a)}l.properties=n,l.required=u,l.additionalProperties=!1}if(i==="array"){let c=e.items;if(!c||typeof c!="object"||Array.isArray(c))throw new w(t,"is a list with no one shape for its items: the provider takes a list of one shape");l.items=ge(c,`${t}[]`,s+1,a)}return l}function Qt(e){if(Array.isArray(e)&&e.length===2&&e.some(t=>t?.type==="null"))return'is nullable: the provider makes the model write a value of one type \u2014 drop .nullable() and give it a value that means "none"'}var en=new Set(["image/png","image/jpeg","image/webp","image/gif"]);function z(e){return Array.isArray(e)&&e.length>0&&e.every(Ue)?e.map(qe):Ue(e)?[qe(e)]:e==null?[{type:"text",text:""}]:typeof e=="string"?[{type:"text",text:e}]:[{type:"text",text:JSON.stringify(e)??String(e)}]}function Ue(e){if(typeof e!="object"||e===null)return!1;let t=e;return t.type==="text"?typeof t.text=="string":t.type==="image"?(typeof t.mediaType=="string"||typeof t.media_type=="string")&&(typeof t.data=="string"||t.data instanceof Uint8Array):t.type===void 0&&typeof t.mediaType=="string"&&t.bytes instanceof Uint8Array}function qe(e){if("type"in e&&e.type==="text")return{type:"text",text:e.text};let t="bytes"in e||"mediaType"in e?e.mediaType:e.media_type;if(!en.has(t))throw new TypeError(`a tool's picture is image/png, image/jpeg, image/webp or image/gif (got ${JSON.stringify(t)})`);let s="bytes"in e?e.bytes:e.data;return{type:"image",media_type:t,data:typeof s=="string"?s:tn(s)}}function tn(e){let t="";for(let s=0;s<e.length;s+=32768)t+=String.fromCharCode(...e.subarray(s,s+32768));return btoa(t)}var Qe=Symbol.for("palbase.ai.deferred"),Le=60,Ve=86400;function et(e={}){let t=e?.expiresInSeconds;if(t!==void 0&&(!Number.isInteger(t)||t<Le||t>Ve))throw new TypeError(`ai.deferred: expiresInSeconds is how long the call waits for its answer, ${Le} to ${Ve} seconds (got ${String(t)})`);return Object.freeze({[Qe]:!0,...t!==void 0?{expiresInSeconds:t}:{}})}function nn(e){return typeof e=="object"&&e!==null&&e[Qe]===!0}var tt=Symbol.for("palbase.ai.reply"),rn=/^[A-Za-z0-9_.:-]{1,160}$/;function H(e,t){if(typeof e!="object"||e===null)throw new TypeError(`${t}: workspaceTree is the tree the tool's writes left the workspace at \u2014 what chats.workspace.write answered ({ manifestId, seq }), either or both`);let{manifestId:s,seq:a}=e,i={};if(s!==void 0){if(typeof s!="string"||!rn.test(s))throw new TypeError(`${t}: workspaceTree.manifestId is a tree's id as chats.workspace.write answered it (got ${JSON.stringify(s)})`);i.manifest_id=s}if(a!==void 0){if(!Number.isSafeInteger(a)||a<1)throw new TypeError(`${t}: workspaceTree.seq is a place in the workspace's history, a whole number from 1 (got ${String(a)})`);i.seq=a}if(i.manifest_id===void 0&&i.seq===void 0)throw new TypeError(`${t}: workspaceTree names the tree \u2014 its manifestId, its seq, or both`);return i}function nt(e,t){let s=H(t?.workspaceTree,"ai.answer");return Object.freeze({[tt]:!0,output:e,workspaceTree:Object.freeze({...s.manifest_id!==void 0?{manifestId:s.manifest_id}:{},...s.seq!==void 0?{seq:s.seq}:{}})})}function sn(e){return typeof e=="object"&&e!==null&&e[tt]===!0}var on=Symbol.for("palbase.ai.declared"),an=Symbol.for("palbase.ai.tool_error"),fe=class extends Error{workspaceTree;constructor(t,s){if(super(t),this.name="ToolError",Object.defineProperty(this,an,{value:!0}),s?.workspaceTree!==void 0){let a=H(s.workspaceTree,"ToolError");this.workspaceTree=Object.freeze({...a.manifest_id!==void 0?{manifestId:a.manifest_id}:{},...a.seq!==void 0?{seq:a.seq}:{}})}}};function W(){let e=globalThis,t=e[on]??={tools:new Map,clientTools:new Map,agents:new Map,repos:new Map,twice:new Set};return t.repos??=new Map,t.clientTools??=new Map,t}function Q(e,t,s,a,i=(l,c)=>l===c){let l=e.get(s);l===void 0?e.set(s,a):i(l,a)||W().twice.add(`${t}:${s}`)}var rt=/^[A-Za-z][A-Za-z0-9_-]{0,63}$/,_=/^[a-z][a-z0-9_-]{0,63}$/,ee=/^[A-Za-z0-9_.:-]{1,160}$/,st=128,ln=/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}\p{Cs}]/u,te=`${st} bytes at most, no control, format (bidi, zero-width) or line-separator character`;function ne(e){return typeof e=="string"&&new TextEncoder().encode(e).byteLength<=st&&!ln.test(e)}function ot(e,t){if(e===void 0)return{type:"object",properties:{}};let s=e?.["~standard"];if(!s||s.version!==1||typeof s.validate!="function")throw new TypeError(`${t}: input is a Standard Schema \u2014 a zod (4.2+), valibot or arktype object schema`);if(!s.jsonSchema||typeof s.jsonSchema.output!="function")throw new TypeError(`${t}: ${s.vendor}'s schema cannot say itself as JSON Schema; use a version that implements Standard JSON Schema`);let a;try{a=s.jsonSchema.output({target:"draft-2020-12",libraryOptions:{unrepresentable:"throw"}})}catch(u){throw new TypeError(`${t}: the input has a part JSON Schema cannot say (${u.message}) \u2014 a function, a transform, a date: take a string and convert it in run`)}if(a.type!=="object")throw new TypeError(`${t}: a tool takes an object \u2014 wrap the input in z.object({ \u2026 })`);let i=JSON.stringify(a);if(/"\$(ref|defs|dynamicRef)"/.test(i))throw new TypeError(`${t}: the input refers to another schema (a recursive or shared type) \u2014 write the shape out`);let{$schema:l,...c}=a;return c}function at(e){let t=`ai.tool(${JSON.stringify(e?.name??null)})`;if(typeof e?.name!="string"||!rt.test(e.name))throw new TypeError(`${t}: name is letters, digits, _ and -, starting with a letter, at most 64`);if(typeof e.description!="string"||e.description.trim()==="")throw new TypeError(`${t}: description says what it does \u2014 the agent reads it to choose`);if(typeof e.run!="function")throw new TypeError(`${t}: run(input, ctx) is what a call does`);if(e.machine!==void 0&&!_.test(e.machine))throw new TypeError(`${t}: machine is the name of one of the project's machines`);if(e.input===void 0)throw new TypeError(`${t}: input is what it takes \u2014 z.object({}) for nothing`);let s=ot(e.input,t),a=e.input["~standard"],i=e.run,l={source:"backend",name:e.name,description:e.description,input:e.input,parameters:s,approval:e.approval===!0,...e.machine!==void 0?{machine:e.machine}:{},async call(u,r){let n=await a.validate(u);if(n.issues){let d=n.issues[0],g=(d?.path??[]).map(E=>String(typeof E=="object"?E.key:E)).join(".");return{output:[{type:"text",text:`the input does not match ${e.name}'s schema${g?` at ${g}`:""}: ${d?.message??"invalid"}`}],is_error:!0}}let o=await i(n.value,r);if(nn(o))return r.chatId===""?{output:[{type:"text",text:`${e.name} answers later, and a one-shot answer waits for no call: it answers at once, or in a chat`}],is_error:!0}:{deferred:!0,...o.expiresInSeconds!==void 0?{expires_in_seconds:o.expiresInSeconds}:{}};if(sn(o)){let d={output:z(o.output),is_error:!1};return o.workspaceTree!==void 0&&(d.workspace_tree=H(o.workspaceTree,t)),d}return{output:z(o),is_error:!1}}};Object.freeze(l);let c=W();return c.clientTools.has(l.name)&&c.twice.add(`tool:${l.name}`),Q(c.tools,"tool",l.name,l),l}function it(e){let t=`ai.clientTool(${JSON.stringify(e?.name??null)})`;if(typeof e?.name!="string"||!rt.test(e.name))throw new TypeError(`${t}: name is letters, digits, _ and -, starting with a letter, at most 64`);if(typeof e.description!="string"||e.description.trim()==="")throw new TypeError(`${t}: description says what it does \u2014 the agent reads it to choose`);let s=Object.freeze({source:"client",name:e.name,description:e.description,parameters:ot(e.input,t),approval:e.approval===!0}),a=W();return a.tools.has(s.name)&&a.twice.add(`tool:${s.name}`),Q(a.clientTools,"tool",s.name,s,(i,l)=>JSON.stringify(i)===JSON.stringify(l)),s}var cn=/^[A-Za-z0-9_.-]{1,100}\/[A-Za-z0-9_.-]{1,100}$/;function lt(e){let t=e??{};if(typeof t.name!="string"||!_.test(t.name))throw new TypeError("ai.repo: name is lowercase letters, digits, _ and -, starting with a letter, at most 64");if(typeof t.repository!="string"||!cn.test(t.repository))throw new TypeError(`ai.repo(${JSON.stringify(t.name)}): repository is a GitHub repository, owner/name`);if(typeof t.token!="function")throw new TypeError(`ai.repo(${JSON.stringify(t.name)}): token is the function that gives a token for one clone or push`);if(t.machine!==void 0&&!_.test(t.machine))throw new TypeError(`ai.repo(${JSON.stringify(t.name)}): machine is the project's machine that gives its tokens`);let s=t.token,a={kind:"repo",name:t.name,repository:t.repository,defaultBranch:t.defaultBranch??"main",...t.machine!==void 0?{machine:t.machine}:{},async token(i){return await s(i)}};return Q(W().repos,"repo",t.name,a),a}function ct(e){if(typeof e!="function")throw new TypeError("ai.repoTokens(give): give is the function that gives a token for one clone or push of a repository put by name");let t=W();t.repoTokens===void 0?t.repoTokens=e:t.repoTokens!==e&&t.twice.add("repoTokens")}function dt(e,t,s={}){let a=`ai.agent(${JSON.stringify(e??null)})`;if(typeof e!="string"||!_.test(e))throw new TypeError(`${a}: name is lowercase letters, digits, _ and -, starting with a letter, at most 64`);if(typeof t!="function")throw new TypeError(`${a}: the agent is a function of the turn's context that returns its definition`);let i=s??{};if(i.machine!==void 0&&!_.test(i.machine))throw new TypeError(`${a}: machine is the name of one of the project's machines`);let l=i.description===void 0?void 0:pt(i.description,a),c={kind:"agent",name:e,...l!==void 0?{description:l}:{},...i.machine!==void 0?{machine:i.machine}:{},async resolve(u){let r=await t(u),n=re(r,`${a} for chat ${u.chatId}`);if(n.backend!==void 0)throw new TypeError(`${a}: a backend's agent is its definition \u2014 it names no other backend`);return n.description===void 0&&l!==void 0&&(n.description=l),{definition:n,tools:dn(r)}}};return Object.freeze(c),Q(W().agents,"agent",e,c),c}function X(e){return typeof e=="object"&&e!==null&&e.kind==="agent"?e:void 0}function dn(e){return[...e.tools??[],...(e.subagents??[]).flatMap(s=>s.tools??[])].filter(s=>s.source==="backend")}var Ge=["web.search","web.fetch","workspace.fetch_archive"];function K(e,t){if(typeof e!="object"||e===null)throw new TypeError(`${t}: a tool is ai.tool(\u2026), ai.clientTool(\u2026), { source: 'https', name }, { source: 'mcp', name } or { source: 'platform', name }`);let s=e.approval===!0?{approval:!0}:{};switch(e.source){case"backend":if(typeof e.call!="function")throw new TypeError(`${t}: a backend tool is made with ai.tool({ name, description, input, run })`);return{source:"backend",name:e.name,description:e.description,parameters:e.parameters,...s,...e.machine!==void 0?{machine:e.machine}:{}};case"client":return{source:"client",name:e.name,description:e.description,parameters:e.parameters,...s};case"https":if(typeof e.name!="string"||!_.test(e.name))throw new TypeError(`${t}: { source: 'https', name } names an endpoint the project put`);return{source:"https",name:e.name,...s};case"mcp":if(typeof e.name!="string"||!_.test(e.name))throw new TypeError(`${t}: { source: 'mcp', name } names an MCP server the project put`);return{source:"mcp",name:e.name,...s,...e.only!==void 0?{only:[...e.only]}:{}};case"platform":{let a=Object.keys(e).filter(i=>i!=="source"&&i!=="name");if(typeof e.name!="string"||!Ge.includes(e.name))throw new TypeError(`${t}: { source: 'platform', name } names one of the platform's tools: ${Ge.join(", ")}`);if(a.length>0)throw new TypeError(`${t}: the platform's ${e.name} is given by its name alone (not ${a.join(", ")})`);return{source:"platform",name:e.name}}default:throw new TypeError(`${t}: a tool's source is backend, client, https, mcp or platform (got ${JSON.stringify(e.source)})`)}}var Je=1e4,Fe=["none","minimal","low","medium","high","xhigh","max"],pn=1e8,un=/^[A-Za-z]{2,8}(-[A-Za-z0-9]{1,8})*$/,ze=1024,gn=/^[A-Z][A-Z0-9_]{0,127}$/,Ke=64,D=32768,He=65536;function he(e){return typeof e=="string"&&gn.test(e)&&!e.startsWith("PALAI_")}var Xe=e=>new TextEncoder().encode(e).byteLength,Ye=32,fn=["header","query","body"];function ye(e,t){let s={};if(e.hosts!==void 0){if(!Array.isArray(e.hosts)||e.hosts.length>Ye)throw new TypeError(`${t}: hosts is a list of ${Ye} hosts at most (api.stripe.com, *.stripe.com); [] takes them all away`);e.hosts.forEach((a,i)=>{if(typeof a!="string"||a==="")throw new TypeError(`${t}: hosts[${i}] is a host, as text (api.stripe.com, *.stripe.com)`)}),s.hosts=[...e.hosts]}if(e.inject!==void 0){if(!Array.isArray(e.inject)||e.inject.length===0)throw new TypeError(`${t}: inject is where in a request it may be put \u2014 header, query, body \u2014 at least one`);e.inject.forEach((a,i)=>{if(typeof a!="string"||!fn.includes(a))throw new TypeError(`${t}: inject[${i}] is header, query or body (a secret never goes over plain http)`)}),s.inject=[...e.inject]}if(e.open!==void 0){if(typeof e.open!="boolean")throw new TypeError(`${t}: open is true (the agent reads it as it is) or false (sealed)`);s.open=e.open}if(e.secret!==void 0){if(typeof e.secret!="boolean")throw new TypeError(`${t}: secret is true (the default) or false (a plain variable the agent reads as it is)`);s.secret=e.secret}if(e.acknowledgeOpen!==void 0){if(typeof e.acknowledgeOpen!="boolean")throw new TypeError(`${t}: acknowledgeOpen is true, said with open: true or with secret: false`);s.acknowledge_open=e.acknowledgeOpen}if(e.acknowledgeGuessable!==void 0){if(typeof e.acknowledgeGuessable!="boolean")throw new TypeError(`${t}: acknowledgeGuessable is true, said with a sealed value a person may have chosen`);s.acknowledge_guessable=e.acknowledgeGuessable}return s}var mn={person_required:"where a secret goes \u2014 its hosts, inject, open, secret \u2014 is changed without its value by a person alone: an owner or an admin of the organization signed in to Studio (AI \u203A Secrets) or to the CLI as themselves (palbase login), never a key or a token, the project's secret key included. Or say it again with its value",secret_unusable:"a sealed secret's value is 8 bytes or more on one line \u2014 no CR, LF or NUL: a value that is no secret is { secret: false }, one the agent may read as it is { open: true, acknowledgeOpen: true }",secret_guessable:"the value looks like one a person chose (fewer than 16 characters, or one kind of character only), and the proxy hides a sealed value an allowed host echoes back, which lets an agent confirm a guess there: use a random key, say acknowledgeGuessable: true to keep it sealed anyway, or make it open",open_not_acknowledged:"an open secret, and a secret made no secret (secret: false), is read by the agent as it is \u2014 anyone who can drive the project's agents can get its value: say acknowledgeOpen: true to say you read this"};function hn(e,t){if(!(e instanceof x))return e;let s=mn[e.code];return s?new x({op:e.op,status:e.status,code:e.code,message:`${t}: ${s} (the platform: ${e.message}; ${e.op}: ${e.status} ${e.code})`,requestId:e.requestId,retryAfter:e.retryAfter,body:e.body,cause:e}):e}function R(e,t){return e.catch(s=>{throw hn(s,t)})}var Ze=["value","hosts","inject","open","secret","acknowledgeOpen","acknowledgeGuessable"];function yn(e,t){let s={};if(e.env!==void 0){if(typeof e.env!="object"||e.env===null||Array.isArray(e.env))throw new TypeError(`${t}: env is the agent's own variables, { NAME: value }`);let a=Object.entries(e.env);if(a.length>Ke)throw new TypeError(`${t}: env names ${Ke} variables at most`);let i={},l=c=>typeof c=="string"&&Xe(c)<=D&&!c.includes("\0");for(let[c,u]of a){if(!he(c))throw new TypeError(`${t}: env: ${JSON.stringify(c.slice(0,140))} is no variable's name \u2014 upper-case letters, digits and _, a letter first, at most 128, and not PALAI_\u2026, the engine's own`);if(typeof u=="object"&&u!==null&&!Array.isArray(u)){let r=Object.keys(u).find(o=>!Ze.includes(o));if(r!==void 0)throw new TypeError(`${t}: env.${c}: ${JSON.stringify(r.slice(0,64))} is not one of ${Ze.join(", ")}`);let n=u;if(n.value!==void 0&&!l(n.value))throw new TypeError(`${t}: env.${c}.value is text of ${D} bytes at most, no NUL ('' keeps the value it has)`);i[c]={...n.value!==void 0?{value:n.value}:{},...ye(n,`${t}: env.${c}`)};continue}if(!l(u))throw new TypeError(`${t}: env.${c} is text of ${D} bytes at most, no NUL ('' keeps the value it has), or { value, hosts, inject, open, secret, acknowledgeOpen, acknowledgeGuessable }`);i[c]=u}s.env=i}if(e.setup!==void 0){if(typeof e.setup!="string"||Xe(e.setup)>He||e.setup.includes("\0"))throw new TypeError(`${t}: setup is a shell script of ${He} bytes at most, no NUL`);s.setup=e.setup}return s}function pt(e,t){if(typeof e!="string"||e.trim()===""||e.length>ze)throw new TypeError(`${t}: description says what the agent is for, in a sentence or two (${ze} characters at most)`);return e}function wn(e,t){let s=e?.prepared;if(s!==void 0&&typeof s=="object"&&s!==null&&typeof s.json=="object")return s.json;if(typeof e!="object"||e===null||!("~standard"in e))throw new TypeError(`${t}: output is the shape of its one-shot answers \u2014 a zod (valibot, arktype) object schema, or ai.schema(name, schema)`);return B(e,"output").json}function we(e,t){if(!Number.isInteger(e)||e<1||e>Je)throw new TypeError(`${t}: maxToolCalls is a whole number, 1 to ${Je} (got ${String(e)})`);return e}function me(e,t){let s={};if(e.effort!==void 0){if(typeof e.effort!="string"||!Fe.includes(e.effort))throw new TypeError(`${t}: effort is one of ${Fe.join(", ")} \u2014 which a model takes is its catalogue entry's (ai.models())`);s.effort=e.effort}if(e.contextWindow!==void 0){if(!Number.isInteger(e.contextWindow)||e.contextWindow<1||e.contextWindow>pn)throw new TypeError(`${t}: contextWindow is a number of tokens (got ${String(e.contextWindow)})`);s.context_window=e.contextWindow}if(e.thinking!==void 0){if(e.thinking!=="visible"&&e.thinking!=="hidden")throw new TypeError(`${t}: thinking is visible (the model's reasoning in the chat's stream) or hidden`);s.thinking=e.thinking}return s}function re(e,t){if(typeof e!="object"||e===null)throw new TypeError(`${t}: a definition is { description, instructions, model, tools, subagents, advisor, maxToolCalls, effort, contextWindow, thinking, language, env, setup, output }`);let s={};if(e.description!==void 0&&(s.description=pt(e.description,t)),e.instructions!==void 0&&(s.instructions=e.instructions),e.model!==void 0&&(s.model=e.model),e.maxToolCalls!==void 0&&(s.max_tool_calls=we(e.maxToolCalls,t)),Object.assign(s,me(e,t)),e.language!==void 0){if(typeof e.language!="string"||e.language.length>35||!un.test(e.language))throw new TypeError(`${t}: language is the language of the person the turn works for, as a BCP 47 tag (tr, en-GB)`);s.language=e.language}if(Object.assign(s,yn(e,t)),e.output!==void 0&&(s.output=wn(e.output,t)),e.tools!==void 0&&(s.tools=e.tools.map(a=>K(a,t))),e.subagents!==void 0){for(let a of e.subagents){let i=(a?.tools??[]).find(l=>l?.source==="platform");if(i)throw new TypeError(`${t} subagent ${a.name}: the platform's ${i.name} is the agent's tool \u2014 its subagents work with the agent's`)}s.subagents=e.subagents.map(a=>({name:a.name,description:a.description,...a.instructions!==void 0?{instructions:a.instructions}:{},...a.model!==void 0?{model:a.model}:{},...a.required!==void 0?{required:a.required}:{},...me(a,`${t} subagent ${a.name}`),...a.tools!==void 0?{tools:a.tools.map(i=>K(i,`${t} subagent ${a.name}`))}:{}}))}return e.advisor!==void 0&&(s.advisor=bn(e.advisor,`${t} advisor`)),s}function bn(e,t){if(typeof e!="object"||e===null)throw new TypeError(`${t}: an advisor is { model, instructions, effort, tools }`);let s={};if(e.model!==void 0&&(s.model=e.model),e.instructions!==void 0){if(typeof e.instructions!="string"||new TextEncoder().encode(e.instructions).length>64*1024)throw new TypeError(`${t}: instructions is text, 64 KiB at most`);s.instructions=e.instructions}let{effort:a}=me({effort:e.effort},t);if(a!==void 0&&(s.effort=a),e.tools!==void 0){if(!Array.isArray(e.tools)||e.tools.length>32)throw new TypeError(`${t}: tools is 32 MCP servers at most`);s.tools=e.tools.map(i=>{if(i?.source!=="mcp")throw new TypeError(`${t}: the advisor reads; its tools are MCP servers' ({ source: 'mcp', name }), whose tools it is given when they say they only read`);if(i.approval===!0)throw new TypeError(`${t}: nothing the advisor reads waits for a person (approval)`);return K(i,t)})}return s}function U(e,t){if(typeof e!="string"||!_.test(e))throw new TypeError(`${t}: an agent's name is lowercase letters, digits, _ and -, starting with a letter, at most 64 (got ${JSON.stringify(e)})`);return e}function ut(e,t){if(!Number.isSafeInteger(e)||e<1)throw new TypeError(`${t}: revision is the draft's revision as it was read (Agent's revision), a whole number from 1 (got ${String(e)})`);return e}function gt(e,t){let s={approve:e};return t.reason!==void 0&&(s.reason=t.reason),t.as!==void 0&&(s.as=t.as),s}var kn=/^[a-z][a-z0-9-]{1,62}$/,ft=4,mt=8;function Tn(e){let t={},s=(a,i)=>{if(typeof a?.bucket!="string"||!kn.test(a.bucket))throw new TypeError(`chats.send: ${i}'s bucket is one of the project's buckets, by its name`);if(typeof a.path!="string"||a.path===""||a.path.length>1024)throw new TypeError(`chats.send: ${i}'s path is its path in the bucket (1024 characters at most)`);return{bucket:a.bucket,path:a.path}};if(e.images!==void 0){if(!Array.isArray(e.images)||e.images.length>ft)throw new TypeError(`chats.send: images are ${ft} at most \u2014 as many as the model is shown at once`);t.images=e.images.map((a,i)=>s(a,`images[${i}]`))}if(e.files!==void 0){if(!Array.isArray(e.files)||e.files.length>mt)throw new TypeError(`chats.send: files are ${mt} at most`);t.files=e.files.map((a,i)=>{let l=s(a,`files[${i}]`);if(a.filename!==void 0){if(typeof a.filename!="string"||a.filename===""||a.filename.length>255)throw new TypeError(`chats.send: files[${i}].filename is its name in the workspace (255 characters at most)`);l.filename=a.filename}if(a.contentType!==void 0){if(typeof a.contentType!="string"||a.contentType===""||a.contentType.length>128)throw new TypeError(`chats.send: files[${i}].contentType is a media type (application/pdf)`);l.content_type=a.contentType}return l})}return t}function se(e){return{id:e.id,chatId:e.chat_id,userId:e.user_id,delegation:e.delegation,status:e.status,seconds:e.seconds,startedAt:e.started_at,closedAt:e.closed_at,closeReason:e.close_reason??""}}var Sn=["speak","tell","know","instruct"];function ht(){return"cm_"+crypto.randomUUID()}async function oe(e,t,s=4){for(let a=1;;a++)try{return await e()}catch(i){if(a>=s||!(i instanceof x)||i.status===429||t?.aborted)throw i;let l=$e(i,a,30);if(l===void 0)throw i;await new Promise((c,u)=>{let r=setTimeout(c,l*1e3);t?.addEventListener("abort",()=>(clearTimeout(r),u(t.reason)),{once:!0})})}}function be(e){return{id:e.id,chatId:e.chat_id,objective:e.objective,rubric:e.rubric,status:e.status,stopCode:e.stop_code,stopReason:e.stop_reason,phase:e.phase,setBy:e.set_by,maxTurns:e.max_turns,budget:e.budget===null?null:{maxCostUsd:e.budget.max_cost_usd},usage:{turns:e.usage.turns,verifications:e.usage.verifications,costUsd:e.usage.cost_usd,costIsLowerBound:e.usage.cost_is_lower_bound,activeSeconds:e.usage.active_seconds},achievedAt:e.achieved_at,createdAt:e.created_at,updatedAt:e.updated_at}}var yt=e=>({user_id:e.userId,...e.name!==void 0?{name:e.name}:{},...e.email!==void 0?{email:e.email}:{},...e.owner!==void 0?{owner:e.owner}:{}}),An=/^[A-Za-z0-9-]{1,64}$/,wt=16;function vn(e){if(!Array.isArray(e)||e.length>wt)throw new TypeError(`chats.create: workspace.trailers are ${wt} at most, each { key, value }`);return e.map((t,s)=>{if(typeof t?.key!="string"||!An.test(t.key))throw new TypeError(`chats.create: workspace.trailers[${s}].key is a git trailer's token: letters, digits and -, at most 64 (PalCore-Task, Co-authored-by)`);if(typeof t.value!="string"||t.value===""||/[\r\n]/.test(t.value)||new TextEncoder().encode(t.value).byteLength>512)throw new TypeError(`chats.create: workspace.trailers[${s}].value is one line of 512 bytes at most`);return{key:t.key,value:t.value}})}var bt=2048,kt=255;function Tt(e,t){let s=a=>new TextEncoder().encode(a).byteLength;if(typeof e!="string"||e===""||s(e)>bt||e.startsWith("/")||e.split("/").some(a=>a===""||a==="."||a===".."||s(a)>kt))throw new TypeError(`${t}: path is a file of the chat's workspace, relative to its root (repo/src/config.json): 1 to ${bt} bytes, each segment 1 to ${kt}, no . or .. segment, no leading or trailing slash`);return e}var ke=64*1024*1024;async function xn(e,t){let s=r=>new RangeError(`${t}: a workspace's file is written up to 64 MiB (${ke} bytes); this one is ${r}`);if(typeof e=="string"&&(e=new TextEncoder().encode(e)),e instanceof Uint8Array||e instanceof Blob){let r=e instanceof Blob?e.size:e.byteLength;if(r>ke)throw s(`${r} bytes`);return e}if(!(e instanceof ReadableStream))throw new TypeError(`${t}: the file's bytes are text, a Uint8Array, a Blob or a ReadableStream`);let a=e.getReader(),i=[],l=0;try{for(;;){let{done:r,value:n}=await a.read();if(r)break;if(!(n instanceof Uint8Array))throw new TypeError(`${t}: a stream's chunks are Uint8Arrays (got ${typeof n})`);if(l+=n.byteLength,l>ke)throw s("more");i.push(n)}}catch(r){throw await a.cancel(r).catch(()=>{}),r}finally{a.releaseLock()}let c=new Uint8Array(l),u=0;for(let r of i)c.set(r,u),u+=r.byteLength;return c}var St=e=>({path:e.path,manifestId:e.manifest_id,seq:e.seq});function At(e){return{id:e.id,access:e.access,...e.label?{label:e.label}:{},expiresAt:e.expires_at,workspaceId:e.workspace_id}}var vt=604800;function _n(e){return{runId:e.run_id,responseId:e.response_id,parentRunId:e.parent_run_id??null,subagent:e.subagent,model:e.model,state:e.state,inputTokens:e.input_tokens,outputTokens:e.output_tokens,cacheReadTokens:e.cache_read_tokens,cacheWriteTokens:e.cache_write_tokens,costNanoUsd:e.cost_nano_usd,usd:e.usd,unpriced:e.unpriced}}function xt(e){return{clients:e.clients,userMessagesPerMinute:e.user_messages_per_minute,historyLimitBytes:e.history_limit_bytes,historyBytes:e.history_bytes,monthlyBudgetUsd:e.monthly_budget_usd??null,openSecretsForAppUsers:e.open_secrets_for_app_users===!0}}function En(e){return new Proxy(e,{get(t,s){let a=t[s];return typeof a=="function"?(...i)=>N(a.apply(t,i)):a}})}function _t(e){let t=En(e),s={async create(r){let n=typeof r.agent=="string"||r.agent===void 0?r.agent:X(r.agent)?.name;if(r.agent!==void 0&&n===void 0)throw new TypeError("chats.create: agent is one of the project's agents by name (name@N for a version), or a backend's ai.agent");if(n===void 0&&r.definition===void 0)throw new TypeError("chats.create: an agent (one of the project's, by name) or a definition of the chat's own");let o={agent:n??"assistant"};if(r.definition!==void 0&&(o.definition=re(r.definition,"chats.create")),r.title!==void 0&&(o.title=r.title),r.metadata!==void 0&&(o.metadata=r.metadata),r.members!==void 0&&(o.members=r.members.map(yt)),r.pool!==void 0){if(typeof r.pool!="string"||!ee.test(r.pool))throw new TypeError("chats.create: pool is one of the project's runner pools (ai.pools), by its id or its name");o.pool=r.pool}return r.workspace!==void 0&&(o.workspace={repos:r.workspace.repos.map(d=>({repo:typeof d.repo=="string"?d.repo:d.repo.name,...d.branch!==void 0?{branch:d.branch}:{}})),...r.workspace.autoPush!==void 0?{auto_push:r.workspace.autoPush}:{},...r.workspace.trailers!==void 0?{trailers:vn(r.workspace.trailers)}:{}}),(await(r.definition!==void 0?R(t.createChat({body:o,signal:r.signal}),"chats.create"):t.createChat({body:o,signal:r.signal}))).data},async get(r,n={}){return(await t.getChat({path:{chat_id:r},signal:n.signal})).data},async list(r={}){let n=r.metadata===void 0?void 0:Object.entries(r.metadata).map(([d,g])=>`${d}:${g}`),o=(await t.listChats({query:{member:r.member,limit:r.limit,cursor:r.cursor,metadata:n},signal:r.signal})).data;return o.next_cursor===void 0?{chats:o.chats}:{chats:o.chats,nextCursor:o.next_cursor}},async delete(r){await t.deleteChat({path:{chat_id:r}})},members:{async put(r,n,o){let d={};return o.name!==void 0&&(d.name=o.name),o.email!==void 0&&(d.email=o.email),o.owner!==void 0&&(d.owner=o.owner),(await t.putChatMember({path:{chat_id:r,user_id:n},body:d})).data},async delete(r,n){await t.deleteChatMember({path:{chat_id:r,user_id:n}})}},async send(r,n){let o={client_id:n.clientId??ht(),text:n.text};return n.delivery!==void 0&&(o.delivery=n.delivery),n.as!==void 0&&(o.as=n.as),n.budget!==void 0&&(o.budget={max_cost_usd:n.budget.maxCostUsd}),n.metadata!==void 0&&(o.metadata=n.metadata),n.context!==void 0&&(o.context=n.context),Object.assign(o,Tn(n)),oe(async()=>(await t.sendChatMessage({path:{chat_id:r},body:o,signal:n.signal})).data,n.signal)},async turnCost(r,n,o={}){let d=(await t.getChatTurnCost({path:{chat_id:r,response_id:n},signal:o.signal})).data,g={chatId:d.chat_id,responseId:d.response_id,inputTokens:d.input_tokens,outputTokens:d.output_tokens,costNanoUsd:d.cost_nano_usd,usd:d.usd,unpriced:d.unpriced,final:d.final,runs:d.runs.map(_n)};return d.advisor&&(g.advisor={inputTokens:d.advisor.input_tokens,outputTokens:d.advisor.output_tokens,cacheReadTokens:d.advisor.cache_read_tokens,cacheWriteTokens:d.advisor.cache_write_tokens,costNanoUsd:d.advisor.cost_nano_usd,usd:d.advisor.usd,unpriced:d.advisor.unpriced}),g},async artifacts(r,n,o={}){return(await t.listChatTurnArtifacts({path:{chat_id:r,response_id:n},signal:o.signal})).data.artifacts.map(g=>({id:g.id,mediaType:g.media_type,...g.logical_type?{logicalType:g.logical_type}:{},sizeBytes:g.size_bytes,checksum:g.checksum,createdAt:g.created_at}))},async artifact(r,n,o,d={}){return(await t.getChatTurnArtifact({path:{chat_id:r,response_id:n,artifact_id:o},signal:d.signal})).data},async messages(r,n={}){let o=(await t.listChatMessages({path:{chat_id:r},query:{limit:n.limit,cursor:n.cursor},signal:n.signal})).data;return o.next_cursor===void 0?{messages:o.messages}:{messages:o.messages,nextCursor:o.next_cursor}},async parts(r,n={}){if(n.cursor!==void 0&&n.before!==void 0)throw new TypeError("chats.parts: cursor (where a page left off) or before (the oldest part the app's channel holds, by its id), not both");if(n.before!==void 0&&(!Number.isSafeInteger(n.before)||n.before<1))throw new TypeError(`chats.parts: before is a part's id \u2014 its journal sequence, a whole number from 1 (got ${String(n.before)})`);if(n.limit!==void 0&&n.turns!==void 0)throw new TypeError("chats.parts: limit (events) or turns (turns), not both");if(n.turns!==void 0&&(!Number.isSafeInteger(n.turns)||n.turns<1||n.turns>20))throw new TypeError(`chats.parts: turns is how many of the chat's turns a page reads back to, 1 to 20 (got ${String(n.turns)})`);let o=(await t.listChatParts({path:{chat_id:r},query:{limit:n.limit,turns:n.turns,cursor:n.cursor,before:n.before},signal:n.signal})).data;return{parts:o.parts.map(g=>({type:g.type,...g.id!==void 0?{id:g.id}:{},partId:g.part_id,data:g.data})),...o.next_cursor!==void 0?{nextCursor:o.next_cursor}:{},...o.turns!==void 0?{turns:o.turns}:{}}},async toolCall(r,n,o={}){let d=(await t.getChatToolCall({path:{chat_id:r,call_id:n},signal:o.signal})).data;return{callId:d.call_id,name:d.name,status:d.status,runId:d.run_id,responseId:d.response_id,input:d.input,output:d.output,outputBytes:d.output_bytes,imageCount:d.image_count,isError:d.is_error}},async toolCalls(r,n){if(typeof n?.turn!="string"||n.turn==="")throw new TypeError("chats.toolCalls: turn is the turn's responseId \u2014 a message's, or a turn's or an agent part's");let o=(await t.listTurnToolCalls({path:{chat_id:r},query:{turn:n.turn,limit:n.limit,cursor:n.cursor},signal:n.signal})).data,d=o.tool_calls.map(g=>({callId:g.call_id,name:g.name,state:g.state,createdAt:g.created_at,updatedAt:g.updated_at,arguments:g.arguments,...g.result!==void 0?{result:g.result}:{}}));return o.next_cursor===void 0?{toolCalls:d}:{toolCalls:d,nextCursor:o.next_cursor}},workspace:{async file(r,n,o={}){if(typeof n!="string"||n==="")throw new TypeError("chats.workspace.file: path is the file as the workspace's tree names it (repo/output/app/App.zip)");return(await t.getChatWorkspaceFile({path:{chat_id:r},query:{path:n,...o.manifest!==void 0?{manifest:o.manifest}:{}},signal:o.signal})).data},async addRepo(r,n){let o=typeof n?.repo=="string"?n.repo:n?.repo?.name;if(typeof o!="string"||!_.test(o))throw new TypeError("chats.workspace.addRepo: repo is the project's name for the repository (ai.repos.put), or its ai.repo");let d={repo:o};return n.branch!==void 0&&(d.branch=n.branch),(await t.addChatWorkspaceRepo({path:{chat_id:r},body:d,signal:n.signal})).data},async write(r,n,o,d={}){Tt(n,"chats.workspace.write");let g=await xn(o,"chats.workspace.write"),E=await t.putChatWorkspaceFile({path:{chat_id:r},query:{path:n},body:g,...d.contentType!==void 0?{contentType:d.contentType}:{},signal:d.signal});return St(E.data)},async remove(r,n,o={}){return Tt(n,"chats.workspace.remove"),St((await t.deleteChatWorkspaceFile({path:{chat_id:r},query:{path:n},signal:o.signal})).data)},tokens:{async create(r,n){if(n?.access!=="read"&&n?.access!=="write")throw new TypeError("chats.workspace.tokens.create: access is read (the workspace followed) or write (followed and written, both ways)");let o={access:n.access};if(n.ttlSeconds!==void 0){if(!Number.isSafeInteger(n.ttlSeconds)||n.ttlSeconds<1||n.ttlSeconds>vt)throw new TypeError(`chats.workspace.tokens.create: ttlSeconds is how long it lives, 1 to ${vt} seconds (got ${String(n.ttlSeconds)})`);o.ttl_seconds=n.ttlSeconds}if(n.label!==void 0){if(!ne(n.label))throw new TypeError(`chats.workspace.tokens.create: label is what it is for \u2014 the machine's name \u2014 ${te}`);o.label=n.label}let d=(await t.createChatWorkspaceToken({path:{chat_id:r},body:o,signal:n.signal})).data;return{...At(d),token:d.token,syncUrl:d.sync_url}},async list(r,n={}){return(await t.listChatWorkspaceTokens({path:{chat_id:r},signal:n.signal})).data.tokens.map(At)},async revoke(r,n,o={}){if(typeof n!="string"||n==="")throw new TypeError("chats.workspace.tokens.revoke: tokenId is the token's id (tokens.list)");await t.revokeChatWorkspaceToken({path:{chat_id:r,token:n},signal:o.signal})}}},events(r){if(typeof r!="string"||!/^chat_[0-9a-f]{32}$/.test(r))throw new TypeError(`chats.events(id): a chat's id, chat_ and 32 hex digits (got ${JSON.stringify(r)})`);return Object.freeze({kind:"ai.chat",chatId:r,async pipe(n,o={}){await t.putChatPipe({path:{chat_id:r},body:{topic:n},signal:o.signal})},async unpipe(n={}){await t.deleteChatPipe({path:{chat_id:r},signal:n.signal})}})},async stop(r,n={}){return(await t.stopChat({path:{chat_id:r},...n.as!==void 0?{body:{as:n.as}}:{},signal:n.signal})).data.stopped},async approve(r,n,o={}){return(await t.decideChatApproval({path:{chat_id:r,approval_id:n},body:gt(!0,o)})).data},async deny(r,n,o={}){return(await t.decideChatApproval({path:{chat_id:r,approval_id:n},body:gt(!1,o)})).data},async answer(r,n,o,d={}){let g={output:z(o)};d.isError&&(g.is_error=!0),d.as!==void 0&&(g.as=d.as),d.workspaceTree!==void 0&&(g.workspace_tree=H(d.workspaceTree,"chats.answer"));try{return await oe(()=>t.answerChatToolCall({path:{chat_id:r,call_id:n},body:g})),!0}catch(E){if(E instanceof x&&E.status===409)return!1;throw E}},async sendToSubagent(r,n,o,d={}){let g={client_id:d.clientId??ht(),text:o};d.as!==void 0&&(g.as=d.as);let E=await oe(async()=>(await t.sendSubagentMessage({path:{chat_id:r,run_id:n},body:g})).data);return{runId:E.run_id,clientId:E.client_id}},async stopSubagent(r,n,o={}){return{runId:(await oe(async()=>(await t.stopSubagent({path:{chat_id:r,run_id:n},body:o.as!==void 0?{as:o.as}:{},signal:o.signal})).data,o.signal)).run_id}},async fork(r,n){if(typeof n?.beforeMessage!="string"||n.beforeMessage==="")throw new TypeError("chats.fork: beforeMessage is the id of the message the fork is cut before (a message's id, msg_\u2026)");let o={before_message:n.beforeMessage};return n.title!==void 0&&(o.title=n.title),n.members!==void 0&&(o.members=n.members.map(yt)),(await t.forkChat({path:{chat_id:r},body:o,signal:n.signal})).data},goal:{async set(r,n){let o={objective:n.objective};return n.rubric!==void 0&&(o.rubric=n.rubric),n.maxTurns!==void 0&&(o.max_turns=n.maxTurns),n.budget!==void 0&&(o.budget={max_cost_usd:n.budget.maxCostUsd}),n.as!==void 0&&(o.as=n.as),be((await t.setChatGoal({path:{chat_id:r},body:o,signal:n.signal})).data)},async get(r,n={}){return be((await t.getChatGoal({path:{chat_id:r},query:n.as!==void 0?{as:n.as}:void 0,signal:n.signal})).data)},async update(r,n){let o={};return n.status!==void 0&&(o.status=n.status),n.reason!==void 0&&(o.reason=n.reason),n.objective!==void 0&&(o.objective=n.objective),n.rubric!==void 0&&(o.rubric=n.rubric),n.maxTurns!==void 0&&(o.max_turns=n.maxTurns),n.budget!==void 0&&(o.budget=n.budget===null?null:{max_cost_usd:n.budget.maxCostUsd}),n.as!==void 0&&(o.as=n.as),be((await t.updateChatGoal({path:{chat_id:r},body:o,signal:n.signal})).data)},async clear(r,n={}){await t.clearChatGoal({path:{chat_id:r},query:n.as!==void 0?{as:n.as}:void 0,signal:n.signal})}},voice:{async start(r,n){if(typeof n?.sdp!="string"||!n.sdp.startsWith("v="))throw new TypeError("chats.voice.start: sdp is the app's WebRTC offer (an SDP, v=0 \u2026): its peer connection's localDescription.sdp");if(n.delegation!==void 0&&n.delegation!=="chat"&&n.delegation!=="events")throw new TypeError("chats.voice.start: delegation is chat (a turn of the chat) or events (ai.voice.delegated)");let o={sdp:n.sdp};n.voice!==void 0&&(o.voice=n.voice),n.delegation!==void 0&&(o.delegation=n.delegation),n.as!==void 0&&(o.as=n.as),n.instructions!==void 0&&(o.instructions=n.instructions),n.context!==void 0&&(o.context=n.context);let d=(await t.startChatVoice({path:{chat_id:r},body:o,signal:n.signal})).data;if(typeof d.sdp!="string"||d.sdp==="")throw new x({op:"startChatVoice",status:502,code:"no_answer",message:"the voice was started but its WebRTC answer was not given"});return{...se(d),sdp:d.sdp}},async get(r,n,o={}){return se((await t.getChatVoice({path:{chat_id:r,voice_id:n},query:o.as!==void 0?{as:o.as}:void 0,signal:o.signal})).data)},async command(r,n,o){if(!Sn.includes(o?.type))throw new TypeError("chats.voice.command: type is speak (say this exactly), tell (say it in your own words), know (keep it in mind) or instruct (behave so)");if(typeof o.text!="string"||o.text==="")throw new TypeError("chats.voice.command: text is what the voice is given");if(o.delegationId!==void 0&&o.type!=="speak"&&o.type!=="tell")throw new TypeError("chats.voice.command: delegationId names the request a speak or a tell answers");if(o.interrupt!==void 0&&(typeof o.interrupt!="boolean"||o.type!=="speak"))throw new TypeError("chats.voice.command: interrupt is a speak's: it cuts what the voice is saying");let d={type:o.type,text:o.text};return o.delegationId!==void 0&&(d.delegation_id=o.delegationId),o.interrupt===!0&&(d.interrupt=!0),o.as!==void 0&&(d.as=o.as),se((await t.commandChatVoice({path:{chat_id:r,voice_id:n},body:d,signal:o.signal})).data)},async close(r,n,o={}){return se((await t.closeChatVoice({path:{chat_id:r,voice_id:n},query:o.as!==void 0?{as:o.as}:void 0,signal:o.signal})).data)}}},a={async list(r={}){return(await t.listAgents({signal:r.signal})).data.agents},async get(r,n={}){return(await t.getAgent({path:{name:U(r,"agents.get")},signal:n.signal})).data},async saveDraft(r,n,o={}){let d=`agents.saveDraft(${JSON.stringify(r)})`;if(U(r,"agents.saveDraft"),X(n))throw new TypeError(`${d}: a backend's ai.agent is its code's \u2014 its build's contract names it, and its chats ask its machine; it has no draft to save`);if(n===void 0)throw new TypeError(`${d}: its definition \u2014 { instructions, model, tools, \u2026 }`);let g=re(n,d);return(await R(t.putAgent({path:{name:r},...o.revision!==void 0?{query:{revision:ut(o.revision,d)}}:{},body:g,signal:o.signal}),d)).data},async publish(r,n={}){let o=`agents.publish(${JSON.stringify(r)})`;U(r,"agents.publish");let d=n.revision!==void 0?{revision:ut(n.revision,o)}:{};return(await t.publishAgent({path:{name:r},body:d,signal:n.signal})).data},async rollback(r,n,o={}){if(U(r,"agents.rollback"),!Number.isSafeInteger(n)||n<1)throw new TypeError(`agents.rollback(${JSON.stringify(r)}): version is one it had \u2014 a whole number from 1 (got ${String(n)})`);return(await R(t.rollbackAgent({path:{name:r},body:{version:n},signal:o.signal}),`agents.rollback(${JSON.stringify(r)})`)).data},async versions(r,n={}){U(r,"agents.versions");let o=(await t.listAgentVersions({path:{name:r},query:{limit:n.limit,cursor:n.cursor},signal:n.signal})).data;return o.next_cursor===void 0?{versions:o.versions,publishedVersion:o.published_version}:{versions:o.versions,publishedVersion:o.published_version,nextCursor:o.next_cursor}},async delete(r,n={}){await t.deleteAgent({path:{name:U(r,"agents.delete")},signal:n.signal})},async tools(r={}){return(await t.listTools({signal:r.signal})).data.tools}},i={async put(r,n){let o={kind:n.kind,url:n.url};if(n.description!==void 0&&(o.description=n.description),n.parameters!==void 0&&(o.parameters=n.parameters),n.approval!==void 0&&(o.approval=n.approval),n.workspace!==void 0){if(typeof n.workspace!="boolean")throw new TypeError("endpoints.put: workspace is true for an endpoint of the project's own that reads or writes a chat's workspace, false (the default) for any other");o.workspace=n.workspace}return(await t.putEndpoint({path:{name:r},body:o})).data},async list(){return(await t.listEndpoints({})).data.endpoints},async delete(r){await t.deleteEndpoint({path:{name:r}})}},l={async get(){return xt((await t.getSettings({})).data)},async put(r){let n={};if(r.clients!==void 0&&(n.clients=r.clients),r.userMessagesPerMinute!==void 0&&(n.user_messages_per_minute=r.userMessagesPerMinute),r.historyLimitBytes!==void 0&&(n.history_limit_bytes=r.historyLimitBytes),r.openSecretsForAppUsers!==void 0){if(typeof r.openSecretsForAppUsers!="boolean")throw new TypeError("settings.put: openSecretsForAppUsers is true (an app's users' work has the project's open secrets) or false");n.open_secrets_for_app_users=r.openSecretsForAppUsers}try{return xt((await t.putSettings({body:n})).data)}catch(o){throw r.openSecretsForAppUsers!==void 0&&o instanceof x&&o.code==="person_required"?new x({op:o.op,status:o.status,code:o.code,requestId:o.requestId,body:o.body,cause:o,message:`settings.put: whether an app's users' work has the project's open secrets is a person's to say \u2014 an owner or an admin of the organization signed in to Studio (AI \u203A Settings) or to the CLI as themselves (palbase ai:settings:set --open-secrets-for-app-users), never a key or a token, the project's secret key included (${o.op}: ${o.status} ${o.code})`}):o}}},c=r=>({name:r.name,repository:r.repository,defaultBranch:r.default_branch,backend:r.backend,createdAt:r.created_at});return{chats:s,agents:a,endpoints:i,settings:l,repos:{async put(r,n){let o=typeof r=="string"?r:r.name;if(typeof o!="string"||!_.test(o))throw new TypeError("repos.put: name is lowercase letters, digits, _ and -, starting with a letter, at most 64");let d=typeof r=="string"?{repository:n?.repository??"",...n?.defaultBranch?{default_branch:n.defaultBranch}:{},...n?.backend?{backend:n.backend}:{}}:{repository:r.repository,default_branch:r.defaultBranch,...r.machine?{backend:r.machine}:{}};return c((await t.putRepo({path:{name:o},body:d})).data)},async list(r={}){let n=(await t.listRepos({query:{limit:r.limit,cursor:r.cursor}})).data,o=n.repos.map(c);return n.next_cursor===void 0?{repos:o}:{repos:o,nextCursor:n.next_cursor}},async delete(r){await t.deleteRepo({path:{name:r}})}}}}function P(e,t,s){if(typeof e!="string"||!ee.test(e))throw new TypeError(`${t}: ${s} (got ${JSON.stringify(e)})`);return e}var ae="the pool is one of the project's runner pools, by its id or its name",Te="the machine is a pool's machine by its id (pools.state(pool).machines)";function Et(e){return{id:e.id,name:e.name,os:e.os,arch:e.arch,...e.created_at!==void 0?{createdAt:e.created_at}:{},...e.machines!==void 0?{machines:e.machines}:{},...e.capacity_total!==void 0?{capacityTotal:e.capacity_total}:{},...e.capacity_used!==void 0?{capacityUsed:e.capacity_used}:{},...e.waiting!==void 0?{waiting:e.waiting}:{}}}function Rt(e){return{id:e.id,...e.label?{label:e.label}:{},...e.created_at!==void 0?{createdAt:e.created_at}:{},...e.expires_at!==void 0?{expiresAt:e.expires_at}:{},...e.last_used_at?{lastUsedAt:e.last_used_at}:{},...e.revoked_at?{revokedAt:e.revoked_at}:{}}}function Rn(e){return{id:e.id,state:e.state,capacity:e.capacity,used:e.used,...e.label?{label:e.label}:{},...e.os?{os:e.os}:{},...e.arch?{arch:e.arch}:{},idleSince:e.idle_since??null,lastSeenAt:e.last_seen_at??null,registeredAt:e.registered_at??null}}var ie=e=>({key:e.key,secret:e.secret,hosts:e.hosts??[],inject:e.inject??[],open:e.open===!0,updatedAt:e.updated_at}),Se=e=>({requestId:e.request_id,key:e.key,agent:e.agent??null,origin:e.origin??null,host:e.host,domain:e.domain??e.host,status:e.status,asks:e.asks,firstAskedAt:e.first_asked_at,lastAskedAt:e.last_asked_at,decidedAt:e.decided_at??null}),Pn=e=>({allowanceId:e.allowance_id,origin:e.origin??"kept",agent:e.agent,key:e.key,host:e.host,domain:e.domain??e.host,allowedAt:e.allowed_at,allowedBy:e.allowed_by}),Pt="the ask is one env.hostRequests.list says, by its id (shr_\u2026)",Cn="an open secret is read by the agent as it is: anyone who can drive the project's agents \u2014 an app's user where the project lets them, a prompt the agent reads \u2014 can get its value. Say acknowledgeOpen: true with open: true to say you read this";function Ct(e,t,s){if(typeof t!="object"||t===null)throw new TypeError(`${s}(${JSON.stringify(e)}): options are { secret, hosts, inject, open, acknowledgeOpen, acknowledgeGuessable }`);let a=ye(t,`${s}(${JSON.stringify(e)})`);if(t.open===!0&&t.acknowledgeOpen!==!0)throw new TypeError(`${s}(${JSON.stringify(e)}): ${Cn}`);return a}function le(e,t){if(!he(e))throw new TypeError(`${t}: ${JSON.stringify(typeof e=="string"?e.slice(0,140):e)} is no variable's name \u2014 upper-case letters, digits and _, a letter first, at most 128, and not PALAI_\u2026, the engine's own`);return e}function $t(e){return{pools:{async create(i){if(typeof i?.name!="string"||!_.test(i.name))throw new TypeError("pools.create: name is lowercase letters, digits, _ and -, a letter first, at most 64 \u2014 the project's once");if(i.os!=="linux"&&i.os!=="macos")throw new TypeError("pools.create: os is its machines' operating system, linux or macos (a pool is of one type)");if(i.arch!=="amd64"&&i.arch!=="arm64")throw new TypeError("pools.create: arch is its machines' architecture, amd64 or arm64 (a pool is of one type)");return Et((await e.createPool({body:{name:i.name,os:i.os,arch:i.arch},signal:i.signal})).data)},async list(i={}){return(await e.listPools({signal:i.signal})).data.pools.map(Et)},async delete(i,l={}){await e.deletePool({path:{pool:P(i,"pools.delete",ae)},signal:l.signal})},async state(i,l={}){let c=(await e.getPoolState({path:{pool:P(i,"pools.state",ae)},signal:l.signal})).data;return{pool:{id:c.pool.id,name:c.pool.name,os:c.pool.os,arch:c.pool.arch},capacityTotal:c.capacity_total,capacityUsed:c.capacity_used,waiting:c.waiting,oldestWaitingSince:c.oldest_waiting_since??null,machines:c.machines.map(Rn)}},keys:{async create(i,l={}){let c={};if(l.label!==void 0){if(!ne(l.label))throw new TypeError(`pools.keys.create: label is what the key is for, ${te}`);c.label=l.label}let u=(await e.createPoolKey({path:{pool:P(i,"pools.keys.create",ae)},body:c,signal:l.signal})).data;if(typeof u.key!="string"||u.key==="")throw new x({op:"createPoolKey",status:502,code:"no_key",message:`the key ${u.id} was minted but not said: revoke it (pools.keys.revoke) and mint another`});return{...Rt(u),key:u.key,...u.enroll_url?{enrollUrl:u.enroll_url}:{},...u.enroll?{enroll:{url:u.enroll.url,...u.enroll.server_name?{serverName:u.enroll.server_name}:{},...u.enroll.ca_certificate?{caCertificate:u.enroll.ca_certificate}:{}}}:{}}},async list(i,l={}){return(await e.listPoolKeys({path:{pool:P(i,"pools.keys.list",ae)},signal:l.signal})).data.keys.map(Rt)},async revoke(i,l={}){await e.revokePoolKey({path:{key:P(i,"pools.keys.revoke","the key is a pool's key by its id (pools.keys.list)")},signal:l.signal})}}},machines:{async cordon(i,l={}){await e.cordonMachine({path:{machine:P(i,"machines.cordon",Te)},signal:l.signal})},async resume(i,l={}){await e.resumeMachine({path:{machine:P(i,"machines.resume",Te)},signal:l.signal})},async delete(i,l={}){await e.deleteMachine({path:{machine:P(i,"machines.delete",Te)},signal:l.signal})}},env:{async set(i,l,c={}){le(i,"env.set");let u=`env.set(${JSON.stringify(i)})`;if(typeof l!="string"||l===""||new TextEncoder().encode(l).byteLength>D||l.includes("\0"))throw new TypeError(`${u}: the value is text of 1 to ${D} bytes, no NUL \u2014 to change what a variable says of itself and keep its value: env.update`);let r={value:l,...Ct(i,c,"env.set")};return ie((await R(e.putEnv({path:{key:i},body:r,signal:c.signal}),u)).data)},async update(i,l){le(i,"env.update");let c=Ct(i,l,"env.update");if(Object.keys(c).every(u=>u.startsWith("acknowledge_")))throw new TypeError(`env.update(${JSON.stringify(i)}): say what changes \u2014 secret, hosts, inject or open (its value: env.set)`);return ie((await R(e.putEnv({path:{key:i},body:c,signal:l.signal}),`env.update(${JSON.stringify(i)})`)).data)},async unset(i,l={}){await e.deleteEnv({path:{key:le(i,"env.unset")},signal:l.signal})},async list(i={}){return(await e.listEnv({signal:i.signal})).data.variables.map(ie)},async allowHost(i,l,c={}){if(le(i,"env.allowHost"),typeof l!="string"||l===""||l.length>253)throw new TypeError(`env.allowHost(${JSON.stringify(i)}): the host is an exact DNS name (api.stripe.com) or *. and one (*.stripe.com), as text`);return ie((await R(e.allowEnvHost({path:{key:i},body:{host:l},signal:c.signal}),`env.allowHost(${JSON.stringify(i)})`)).data)},hostRequests:{async list(i={}){if(i.status!==void 0&&!["asked","allowed","dismissed"].includes(i.status))throw new TypeError("env.hostRequests.list: status is asked (the default), allowed or dismissed");let l=i.status!==void 0?{status:i.status}:void 0;return(await e.listEnvHostRequests({...l?{query:l}:{},signal:i.signal})).data.requests.map(Se)},async allow(i,l={}){let c=P(i,"env.hostRequests.allow",Pt);return Se((await R(e.allowEnvHostRequest({path:{request_id:c},signal:l.signal}),`env.hostRequests.allow(${JSON.stringify(c)})`)).data)},async dismiss(i,l={}){let c=P(i,"env.hostRequests.dismiss",Pt);return Se((await R(e.dismissEnvHostRequest({path:{request_id:c},signal:l.signal}),`env.hostRequests.dismiss(${JSON.stringify(c)})`)).data)}},allowances:{async list(i={}){return(await e.listEnvAllowances({signal:i.signal})).data.allowances.map(Pn)},async remove(i,l={}){let c=P(i,"env.allowances.remove","the allowance is one env.allowances.list says, by its id (sha_\u2026)");await R(e.deleteEnvAllowance({path:{allowance_id:c},signal:l.signal}),`env.allowances.remove(${JSON.stringify(c)})`)}}}}}var $n=/^pb_[a-z0-9]+_s/;function It(e){let t=globalThis;return t.process?.env?.[e]??t.Deno?.env?.get(e)}function Ae(){return"ai_"+crypto.randomUUID()}function ve(e){if(e.prepared)return e;let t=e;return{name:"answer",schema:t,prepared:B(t,"answer")}}var Ot=4,In=/^[a-z][a-z0-9-]{1,62}$/,Mt=["image/png","image/jpeg","image/webp","image/gif"],jt=5<<20,Nt=6<<20;function Ut(e){let t="";for(let s=0;s<e.length;s+=32768)t+=String.fromCharCode(...e.subarray(s,s+32768));return btoa(t)}function On(e){return e.length%4!==0||!/^[A-Za-z0-9+/]*={0,2}$/.test(e)?-1:e.length/4*3-(e.endsWith("==")?2:e.endsWith("=")?1:0)}function Mn(e){if(!Array.isArray(e))throw new TypeError("images is a list of { bucket, path } (a file of the project's storage), { url } (an https address) or { mediaType, data } (its bytes)");if(e.length>Ot)throw new TypeError(`a question takes ${Ot} pictures at most (got ${e.length})`);let t=0;return e.map((s,a)=>{let i=s??{};if("bytes"in i||s instanceof Uint8Array)throw new TypeError(`images[${a}]: a picture's bytes are { mediaType, data } \u2014 or, in the project's storage, { bucket, path }`);if("data"in i||"mediaType"in i){if(i.bucket!==void 0||i.path!==void 0||i.url!==void 0)throw new TypeError(`images[${a}] is { bucket, path }, { url } or { mediaType, data }: one of them`);if(typeof i.mediaType!="string"||!Mt.includes(i.mediaType))throw new TypeError(`images[${a}].mediaType is the picture's type: ${Mt.join(", ")}`);let l=i.data instanceof Uint8Array?Ut(i.data):i.data,c=typeof l=="string"?On(l):-1;if(c<0)throw new TypeError(`images[${a}].data is the picture's bytes: base64, or a Uint8Array`);if(c===0||c>jt)throw new TypeError(`images[${a}] is ${c} bytes: a picture given by its bytes is 1 byte to ${jt>>20} MiB`);if(t+=c,t>Nt)throw new TypeError(`the pictures given by their bytes are ${Nt>>20} MiB at most together: put a larger one in the project's storage and give { bucket, path }`);return{media_type:i.mediaType,data:l}}if(typeof i.url=="string"){if(i.bucket!==void 0||i.path!==void 0)throw new TypeError(`images[${a}] is { bucket, path } or { url }, not both`);let l;try{l=new URL(i.url)}catch{throw new TypeError(`images[${a}].url is not an address: ${JSON.stringify(i.url.slice(0,80))}`)}if(l.protocol!=="https:"||i.url.length>2048)throw new TypeError(`images[${a}].url is an https address of 2048 characters at most`);return{url:i.url}}if(typeof i.bucket!="string"||!In.test(i.bucket)||typeof i.path!="string"||i.path==="")throw new TypeError(`images[${a}] is { bucket, path } \u2014 a file of the project's storage \u2014 { url } or { mediaType, data }`);return{bucket:i.bucket,path:i.path}})}var jn=/^[a-z][a-z0-9_-]{0,63}(@[1-9][0-9]{0,8})?$/;function qt(e){let t=typeof e=="string"?e:X(e)?.name;if(typeof t!="string"||!jn.test(t))throw new TypeError(`agent is one of the project's agents by name (support), name@N for its version N (support@3), or a backend's ai.agent (got ${JSON.stringify(typeof e=="string"?e:typeof e)})`);return t}function Y(e,t={},s){if(e.prompt===void 0&&e.messages===void 0)throw new TypeError("ask a model something: prompt, or messages");let a={...t};if(e.agent!==void 0&&(a.agent=qt(e.agent)),e.prompt!==void 0&&(a.input=e.prompt),e.messages!==void 0&&(a.messages=e.messages),e.instructions!==void 0&&(a.instructions=e.instructions),e.model!==void 0&&(a.model=e.model),e.metadata!==void 0&&(a.metadata=e.metadata),e.images!==void 0&&(a.images=Mn(e.images)),e.tools!==void 0&&(a.tools=e.tools.map((i,l)=>{if(i?.source==="client")throw new TypeError(`tools[${l}]: ${i.name} is a client tool \u2014 an app answers it, in a chat; a one-shot answer has no app to wait for`);if(i?.source==="platform")throw new TypeError(`tools[${l}]: the platform's ${i.name} is a chat's agent's tool \u2014 a one-shot answer is given none`);let c=K(i,`tools[${l}]`);return c.source==="backend"&&c.machine===void 0&&s!==void 0&&(c.machine=s),c})),e.maxToolCalls!==void 0){if(!e.tools?.length)throw new TypeError("maxToolCalls bounds the calls of the tools given: give tools");a.max_tool_calls=we(e.maxToolCalls,"ask")}return a}function Bt(e,t){if(e.output===null||e.output===void 0)throw new w(t,"the answer is text, not a document: the agent has no output (the shape of its one-shot answers) \u2014 give it one, give generate a schema, or ask() it");return e.output}var I=class extends Error{code;response;constructor(t){super(t.error?.message??`the response ended ${t.status}`),this.name="AIResponseError",this.code=t.error?.code??t.status,this.response=t}};function Nn(e){let t=Uint8Array.from(atob(e),i=>i.charCodeAt(0)),s=new DataView(t.buffer,t.byteOffset,t.byteLength),a=new Array(t.byteLength/4);for(let i=0;i<a.length;i++)a[i]=s.getFloat32(i*4,!0);return a}async function Dt(e){let t,s;return e instanceof Uint8Array?(t=e,s=Wt(t)):typeof Blob<"u"&&e instanceof Blob?(t=new Uint8Array(await e.arrayBuffer()),s=e.type||Wt(t)):(t=e.bytes,s=e.mediaType),{media_type:s,data:Ut(t)}}function Wt(e){return e[0]===137&&e[1]===80?"image/png":e[0]===255&&e[1]===216?"image/jpeg":e[8]===87&&e[9]===69&&e[10]===66&&e[11]===80?"image/webp":"application/octet-stream"}function Bn(e){let t=e.url??It("PALBASE_URL"),s=e.secretKey??It("PALBASE_SECRET_KEY");if(typeof t!="string"||t==="")throw new TypeError("url is the project address (https://<ref>.<domain>) \u2014 or set PALBASE_URL");if(typeof s!="string"||!$n.test(s))throw new TypeError("secretKey is the project secret key (pb_<ref>_s\u2026) \u2014 or set PALBASE_SECRET_KEY; a model call is billed to the project, so it is never made with a publishable key");let a=Ce(Ee({baseUrl:t,credentials:{secretKey:s},fetch:e.fetch}),e.retry??Pe);return Re.client(a)}function Dn(e){return new Proxy({},{get:(t,s)=>e.ai[s]})}function Wn(e={}){if(je())throw new TypeError("palbase/ai runs on a server: it speaks with the project secret key, which never goes into a browser or a mobile app \u2014 call your backend, and let it ask the model");if(e.machine!==void 0&&!_.test(e.machine))throw new TypeError("machine is the name of one of the project's machines");let t=e.server?Dn(e.server):Bn(e),s=e.resumeFor??12e4;async function a(p,f,h=Ae()){return N(t.createResponse({headers:{"Idempotency-Key":h},body:p,signal:f}))}async function i(p,f={}){return(await t.getResponse({path:{response_id:p},signal:f.signal})).data}async function l(p,f,h,S,y){let b=0,A=p,C=Ae(),q=()=>Date.now()+s,L=q();for(let V=0;;V++)try{if(A||(f===null?A=(await a({...y,stream:!0},S,C)).data:A=(await t.followResponse({path:{response_id:f},query:{offset:b},signal:S})).data),!A.body)throw new Error("the stream has no body");for await(let k of Ne(A.body)){let v=JSON.parse(k.data);switch(k.event){case"response":f===null&&(f=v.id,h.admitted(v));break;case"delta":{let j=v.offset+Ie(v.text);if(j>b){let ce=v.offset>=b?v.text:Me(v.text,b-v.offset);h.delta(b,ce),b=j}L=q();break}case"reset":v.offset<b&&(b=v.offset,h.reset(b));break;case"terminal":return v}}throw new Error("the stream ended before its answer did")}catch(k){if(A=null,S?.aborted||k instanceof x&&k.status>0&&k.status<500&&k.status!==429||f===null&&!(k instanceof x)||Date.now()>L)throw k;await new Promise(v=>setTimeout(v,Math.min(250*2**Math.min(V,4),4e3)))}}function c(p){if(p.status!=="completed")throw new I(p);return p.text??""}function u(p,f){let h=Y(p,f?{schema:f.prepared.json,schema_name:f.name}:{},e.machine),S=[],y=!1,b,A=null,C=()=>{let m=A;A=null,m?.()},q,L,V=new Promise((m,T)=>{q=m,L=T});V.catch(()=>{});let k="",v=l(null,null,{admitted:m=>q(m.id),delta:(m,T)=>{k+=T,S.push(T),C()},reset:m=>{let T=Oe(k,m);k=k.slice(0,T),S.push("\0reset:"+T),C()}},p.signal,h).then(m=>{let T=m.status==="completed"?m.text??"":"";return T.length>k.length&&T.startsWith(k)&&(S.push(T.slice(k.length)),k=T),y=!0,C(),m},m=>{throw y=!0,b=m,L(m),C(),m});v.catch(()=>{});async function*j(){for(let m=0;;m++){for(;m>=S.length;){if(y){if(b)throw b;return}await new Promise(T=>A=T)}yield S[m]}}async function*ce(){for await(let m of j())m.startsWith("\0reset:")||(yield m)}async function*Jt(){let m="",T="";for await(let J of j()){J.startsWith("\0reset:")?m=m.slice(0,Number(J.slice(7))):m+=J;let O=ue(m);if(O===void 0)continue;let M=JSON.stringify(O);M!==T&&(T=M,yield O)}}let G=v.then(m=>{if(m.status!=="completed")throw new I(m);return m});G.catch(()=>{});let xe=f?G.then(m=>f.prepared.check(m.output)):Promise.reject(new TypeError("object is a schema stream's"));xe.catch(()=>{});let _e=G.then(m=>m.text??k);return _e.catch(()=>{}),{id:V,response:G,text:_e,get textStream(){return ce()},get partialObjectStream(){return Jt()},object:xe,toResponse(m={}){let T=new TextEncoder,J=new ReadableStream({async start(M){try{for await(let F of j())F.startsWith("\0reset:")?M.enqueue(T.encode(`event: reset
8
+ data: ${JSON.stringify({offset:Number(F.slice(7))})}
9
+
10
+ `)):M.enqueue(T.encode(`data: ${JSON.stringify({text:F})}
11
+
12
+ `));let $=await G;M.enqueue(T.encode(`event: done
13
+ data: ${JSON.stringify({id:$.id,text:$.text,output:$.output,usage:$.usage})}
14
+
15
+ `))}catch($){let F=$ instanceof I||$ instanceof x?$.code:"stream_failed";M.enqueue(T.encode(`event: error
16
+ data: ${JSON.stringify({code:F})}
17
+
18
+ `))}finally{M.close()}}}),O=new Headers(m.headers);return O.set("content-type","text/event-stream"),O.set("cache-control","no-store"),O.set("x-accel-buffering","no"),new globalThis.Response(J,{...m,headers:O})}}}async function r(p,f){return l(null,null,{admitted:()=>{},delta:()=>{},reset:()=>{}},p.signal,Y(p,f,e.machine))}let{chats:n,agents:o,endpoints:d,settings:g,repos:E}=_t(t),{pools:Lt,machines:Vt,env:Gt}=$t(t);return{module:t,chats:n,agents:o,endpoints:d,settings:g,repos:E,pools:Lt,machines:Vt,env:Gt,tool:at,clientTool:it,deferred:et,answer:nt,agent:dt,repo:lt,repoTokens:ct,async ask(p,f={}){let h=typeof p=="string"?{...f,prompt:p}:p;return c(await r(h,{}))},async generate(p){if(p.schema===void 0){if(p.agent===void 0)throw new TypeError("generate: a schema \u2014 the answer's shape \u2014 or an agent whose output is");if(p.background){let A=(await a(Y(p,{background:!0},e.machine),p.signal)).data;return{id:A.id,status:A.status}}let y=await r(p,{});if(y.status!=="completed")throw new I(y);return Bt(y,qt(p.agent))}let f=ve(p.schema),h={schema:f.prepared.json,schema_name:f.name};if(p.background){let b=(await a(Y(p,{...h,background:!0},e.machine),p.signal)).data;return{id:b.id,status:b.status}}let S=await r(p,h);if(S.status!=="completed")throw new I(S);return f.prepared.check(S.output)},stream(p){return u(p,p.schema?ve(p.schema):void 0)},async start(p){let f=(await a(Y(p,{background:!0},e.machine),p.signal)).data;return{id:f.id,status:f.status}},schema(p,f){return{name:p,schema:f,prepared:B(f,p)}},response:i,async result(p,f){let h=await i(p);if(h.status!=="completed")throw new I(h);return f===void 0?Bt(h,"the response"):ve(f).prepared.check(h.output)},async cancel(p){return(await t.cancelResponse({path:{response_id:p}})).data},async embed(p,f={}){let h=Array.isArray(p)?p:[p],S=[];for(let y=0;y<h.length;y+=1024){let b=await N(t.createEmbeddings({body:{input:h.slice(y,y+1024),model:f.model,dimensions:f.dimensions},signal:f.signal}));for(let A of b.data.vectors)S.push(Nn(A))}return Array.isArray(p)?S:S[0]},async image(p){let f={prompt:p.prompt};for(let y of["model","size","quality","background","format","count"])p[y]!==void 0&&(f[y]=p[y]);p.references?.length&&(f.references=await Promise.all(p.references.map(Dt))),p.mask&&(f.mask=await Dt(p.mask));let h=(await N(t.createImage({headers:{"Idempotency-Key":Ae()},body:f,signal:p.signal}))).data;for(let y=0;h.status==="running";y++){if(await new Promise(b=>setTimeout(b,Math.min(500+y*250,3e3))),p.signal?.aborted)throw p.signal.reason;h=(await t.getImage({path:{image_id:h.id},signal:p.signal})).data}if(h.status!=="completed")throw new Error(`the image failed: ${h.error?.code??"image_failed"}: ${h.error?.message??""}`);let S=await Promise.all(h.files.map(async y=>{let A=(await t.getImageFile({path:{image_id:h.id,position:y.position},signal:p.signal})).data;return{mediaType:y.media_type,bytes:new Uint8Array(await A.arrayBuffer())}}));return{id:h.id,model:h.model,pictures:S,costNanoUSD:h.usage?.cost_nano_usd??0,save(y,b,A=0){let C=S[A];if(!C)throw new RangeError(`the job made ${S.length} picture(s)`);return y.upload(b,C.bytes,{contentType:C.mediaType})}}},async models(){return(await t.listModels({})).data},async usage(p={}){let f=p.metadata===void 0?void 0:JSON.stringify(p.metadata),h=(await t.listUsage({query:{kind:p.kind,limit:p.limit,cursor:p.cursor,metadata:f}})).data;return{usage:h.usage,nextCursor:h.next_cursor}},async spend(p={}){return(await t.getSpend({signal:p.signal})).data},async connectProvider(p,f){return(await t.connectProvider({path:{provider:p},body:{key:f}})).data},async disconnectProvider(p){await t.disconnectProvider({path:{provider:p}})}}}export{ue as a,w as b,B as c,fe as d,I as e,Wn as f};
@@ -1,2 +1,2 @@
1
- /*! palbase 0.63.0 — Palbase SDK License (see LICENSE) */
2
- import{b as d,m as k}from"./UDS4W77D.js";function S(n){let o=n.meta;if(typeof o!="function")throw new TypeError("encrypted() takes a zod schema: z.string(), z.number(), z.object(\u2026)");return o.call(n,{[d]:!0})}var p=class{value;constructor(o){this.value=o}toJSON(){throw new TypeError("an encrypt() value is sealed by the engine, in a route's answer: it is never JSON of its own")}},m=0;function $(n){if(n===void 0)throw new TypeError("encrypt() takes a JSON value: undefined is none");if(n instanceof p)throw new TypeError("encrypt() of an encrypt() value: one is enough");return m++,new p(n)}function j(){return m}function O(n){let o=[],s=new Set,f=(t,a)=>{if(t instanceof p){if(o.push(a),g(t.value,new Set))throw new TypeError(`${a}: an encrypt() value holds another \u2014 encrypt the whole, or its parts`);return t.value}if(typeof t!="object"||t===null||s.has(t))return t;if(Array.isArray(t)){s.add(t);let r=t.map((c,e)=>f(c,`${a}/${e}`));return s.delete(t),r}let y=Object.getPrototypeOf(t);if(y!==Object.prototype&&y!==null)return t;s.add(t);let i={};for(let[r,c]of Object.entries(t))i[r]=f(c,`${a}/${k(r)}`);return s.delete(t),i};return{value:f(n,"/response"),pointers:o}}function g(n,o){return n instanceof p?!0:typeof n!="object"||n===null||o.has(n)?!1:(o.add(n),Object.values(n).some(s=>g(s,o)))}function v(n,o,s){let f=new Set,l=n,t=l?.$defs??{},a=(i,r,c)=>{if(typeof i!="object"||i===null)return;let e=i;if(typeof e.$ref=="string"){if(c.has(e.$ref))return;let u=new Set(c).add(e.$ref);e.$ref==="#"?a(l,r,u):e.$ref.startsWith("#/$defs/")&&a(t[e.$ref.slice(8)],r,u)}if(e[d]===!0){f.add(r);return}for(let u of["anyOf","oneOf","allOf"])if(Array.isArray(e[u]))for(let w of e[u])a(w,r,c);if(typeof e.properties=="object"&&e.properties!==null)for(let[u,w]of Object.entries(e.properties))a(w,`${r}/${k(u)}`,c);typeof e.items=="object"&&e.items!==null&&a(e.items,`${r}/*`,c);for(let u of["additionalProperties","patternProperties","prefixItems"])if(e[u]!==void 0&&y(e[u]))throw new TypeError(`${s}: an encrypted field is a named property \u2014 not every key of a record, nor a tuple's place`)},y=i=>{if(h(i))return!0;let r=typeof i=="object"&&i!==null?i.$ref:void 0;return typeof r=="string"&&h(r==="#"?l:t[r.slice(8)])};return a(n,o,new Set),[...f]}function T(n){let s=n["~standard"].jsonSchema?.input;if(typeof s!="function")return{};try{return s({target:"draft-2020-12",libraryOptions:{unrepresentable:"any"}})}catch{return{}}}function h(n){return JSON.stringify(n??null).includes(`"${d}":true`)}export{S as a,$ as b,j as c,O as d,v as e,T as f,h as g};
1
+ /*! palbase 0.65.0 — Palbase SDK License (see LICENSE) */
2
+ import{b as d,m as k}from"./DFX37NU3.js";function S(n){let o=n.meta;if(typeof o!="function")throw new TypeError("encrypted() takes a zod schema: z.string(), z.number(), z.object(\u2026)");return o.call(n,{[d]:!0})}var p=class{value;constructor(o){this.value=o}toJSON(){throw new TypeError("an encrypt() value is sealed by the engine, in a route's answer: it is never JSON of its own")}},m=0;function $(n){if(n===void 0)throw new TypeError("encrypt() takes a JSON value: undefined is none");if(n instanceof p)throw new TypeError("encrypt() of an encrypt() value: one is enough");return m++,new p(n)}function j(){return m}function O(n){let o=[],s=new Set,f=(t,a)=>{if(t instanceof p){if(o.push(a),g(t.value,new Set))throw new TypeError(`${a}: an encrypt() value holds another \u2014 encrypt the whole, or its parts`);return t.value}if(typeof t!="object"||t===null||s.has(t))return t;if(Array.isArray(t)){s.add(t);let r=t.map((c,e)=>f(c,`${a}/${e}`));return s.delete(t),r}let y=Object.getPrototypeOf(t);if(y!==Object.prototype&&y!==null)return t;s.add(t);let i={};for(let[r,c]of Object.entries(t))i[r]=f(c,`${a}/${k(r)}`);return s.delete(t),i};return{value:f(n,"/response"),pointers:o}}function g(n,o){return n instanceof p?!0:typeof n!="object"||n===null||o.has(n)?!1:(o.add(n),Object.values(n).some(s=>g(s,o)))}function v(n,o,s){let f=new Set,l=n,t=l?.$defs??{},a=(i,r,c)=>{if(typeof i!="object"||i===null)return;let e=i;if(typeof e.$ref=="string"){if(c.has(e.$ref))return;let u=new Set(c).add(e.$ref);e.$ref==="#"?a(l,r,u):e.$ref.startsWith("#/$defs/")&&a(t[e.$ref.slice(8)],r,u)}if(e[d]===!0){f.add(r);return}for(let u of["anyOf","oneOf","allOf"])if(Array.isArray(e[u]))for(let w of e[u])a(w,r,c);if(typeof e.properties=="object"&&e.properties!==null)for(let[u,w]of Object.entries(e.properties))a(w,`${r}/${k(u)}`,c);typeof e.items=="object"&&e.items!==null&&a(e.items,`${r}/*`,c);for(let u of["additionalProperties","patternProperties","prefixItems"])if(e[u]!==void 0&&y(e[u]))throw new TypeError(`${s}: an encrypted field is a named property \u2014 not every key of a record, nor a tuple's place`)},y=i=>{if(h(i))return!0;let r=typeof i=="object"&&i!==null?i.$ref:void 0;return typeof r=="string"&&h(r==="#"?l:t[r.slice(8)])};return a(n,o,new Set),[...f]}function T(n){let s=n["~standard"].jsonSchema?.input;if(typeof s!="function")return{};try{return s({target:"draft-2020-12",libraryOptions:{unrepresentable:"any"}})}catch{return{}}}function h(n){return JSON.stringify(n??null).includes(`"${d}":true`)}export{S as a,$ as b,j as c,O as d,v as e,T as f,h as g};
@@ -1,5 +1,5 @@
1
- /*! palbase 0.63.0 — Palbase SDK License (see LICENSE) */
2
- import{p as R,t as k,u as H}from"./EJ7YD4YY.js";var N=40,V=`
1
+ /*! palbase 0.65.0 — Palbase SDK License (see LICENSE) */
2
+ import{p as R,t as k,u as H}from"./YP3QTS4L.js";var N=40,V=`
3
3
  :host{display:contents}
4
4
  .pm-modal,.pm-full{position:fixed;inset:0;width:100%;height:100%;max-width:none;max-height:none;margin:0;border:0;background:transparent;color:inherit;overflow:hidden;display:flex;flex-direction:column}
5
5
  .pm-modal::backdrop,.pm-full::backdrop{background:transparent}