palbase 0.14.1 → 0.14.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/dist/ai/index.js +2 -2
  2. package/dist/backend/engine.js +2 -2
  3. package/dist/backend/env.js +1 -1
  4. package/dist/backend/index.js +3 -3
  5. package/dist/backend/stack.js +1 -1
  6. package/dist/backend/test.js +2 -2
  7. package/dist/chunks/{VLNIDQ36.js → 3AENUHVO.js} +2 -2
  8. package/dist/chunks/{YIFQY4BF.js → 427AGWP3.js} +2 -2
  9. package/dist/chunks/{3CUWIZU2.js → 44ULNVPP.js} +1 -1
  10. package/dist/chunks/{RZBBS4OL.js → 4UQ4J7RV.js} +2 -2
  11. package/dist/chunks/{XCY7TFJH.js → 5H7UNNH6.js} +2 -2
  12. package/dist/chunks/{FZB357V4.js → 6NC5RYCS.js} +1 -1
  13. package/dist/chunks/{VSB66HSU.js → 7DQ76T2V.js} +2 -2
  14. package/dist/chunks/{O2LHK2GF.js → A46IASZE.js} +2 -2
  15. package/dist/chunks/{LND5DXD3.js → BRHGS5AI.js} +2 -2
  16. package/dist/chunks/{2CR3IN7R.js → CUL5OL4P.js} +2 -2
  17. package/dist/chunks/{IXOQ6JI5.js → DIOZGDFQ.js} +1 -1
  18. package/dist/chunks/{7UQMB3JW.js → HHZSOYPP.js} +1 -1
  19. package/dist/chunks/{RBDGMOJT.js → JKWWY2LJ.js} +2 -2
  20. package/dist/chunks/LUFWGH2V.js +2 -0
  21. package/dist/chunks/{GHEORI3H.js → OMK2YEDZ.js} +2 -2
  22. package/dist/chunks/{2PCIM4VH.js → P67I4TNQ.js} +1 -1
  23. package/dist/chunks/{NVA3C3Z3.js → PRJZTG2I.js} +1 -1
  24. package/dist/chunks/{EH4ZWZCT.js → QZH6GPCR.js} +2 -2
  25. package/dist/chunks/{URK5PA2R.js → RD5JFDGQ.js} +2 -2
  26. package/dist/chunks/{S6HM2J7J.js → SBUC7GHR.js} +2 -2
  27. package/dist/chunks/{YYLNEVUC.js → W3OCV3QH.js} +2 -2
  28. package/dist/chunks/{KLEVI5C3.js → WXNFMEW7.js} +2 -2
  29. package/dist/chunks/{UXURIXBA.js → ZZNGA77G.js} +1 -1
  30. package/dist/cli.js +108 -108
  31. package/dist/refuse/ai.js +1 -1
  32. package/dist/refuse/backend.js +1 -1
  33. package/dist/refuse/server.js +1 -1
  34. package/dist/server/index.js +2 -2
  35. package/dist/server/testing.js +2 -2
  36. package/dist/web/index.js +2 -2
  37. package/dist/web/message.js +2 -2
  38. package/dist/web/palbe.js +2 -2
  39. package/dist/web/paywall.js +2 -2
  40. package/dist/web/push-sw.js +1 -1
  41. package/dist/web/ssr.js +2 -2
  42. package/dist/web/vite.js +2 -2
  43. package/package.json +2 -2
  44. package/types/internal/src/modules/ai.d.ts +3 -7
  45. package/types/internal/src/modules/secrets.d.ts +1 -1
  46. package/types/internal/src/modules/stores.d.ts +57 -0
  47. package/types/server/src/transit.d.ts +8 -1
  48. package/dist/chunks/WZLLB24Q.js +0 -2
package/dist/ai/index.js CHANGED
@@ -1,2 +1,2 @@
1
- /*! palbase 0.14.1 — Palbase SDK License (see LICENSE) */
2
- import{a,b,c,d,e,f}from"../chunks/LND5DXD3.js";import"../chunks/VLNIDQ36.js";import"../chunks/3CUWIZU2.js";import"../chunks/GHEORI3H.js";import"../chunks/URK5PA2R.js";import"../chunks/RBDGMOJT.js";import"../chunks/2PCIM4VH.js";import"../chunks/FZB357V4.js";export{e as AIResponseError,b as AISchemaError,d as ToolError,f as createAI,a as partial,c as prepare};
1
+ /*! palbase 0.14.2 — Palbase SDK License (see LICENSE) */
2
+ import{a,b,c,d,e,f}from"../chunks/BRHGS5AI.js";import"../chunks/3AENUHVO.js";import"../chunks/44ULNVPP.js";import"../chunks/OMK2YEDZ.js";import"../chunks/RD5JFDGQ.js";import"../chunks/JKWWY2LJ.js";import"../chunks/P67I4TNQ.js";import"../chunks/6NC5RYCS.js";export{e as AIResponseError,b as AISchemaError,d as ToolError,f as createAI,a as partial,c as prepare};
@@ -1,2 +1,2 @@
1
- /*! palbase 0.14.1 — Palbase SDK License (see LICENSE) */
2
- import{ha as w,la as h}from"../chunks/EH4ZWZCT.js";import"../chunks/S6HM2J7J.js";import"../chunks/2CR3IN7R.js";import"../chunks/WZLLB24Q.js";import"../chunks/7UQMB3JW.js";import"../chunks/UXURIXBA.js";import"../chunks/LND5DXD3.js";import"../chunks/VLNIDQ36.js";import"../chunks/3CUWIZU2.js";import"../chunks/GHEORI3H.js";import"../chunks/URK5PA2R.js";import"../chunks/RBDGMOJT.js";import"../chunks/2PCIM4VH.js";import"../chunks/FZB357V4.js";import{binding as R,createDatabase as v}from"palgres";var y=new WeakMap;function q(p,e,a){if(!a?.schemas?.length)throw new TypeError("createRequestDatabase(sql, identity, { schemas }): the engine compiles each call against the app's schemas \u2014 pass the schema files' default exports");let u=a.schemas,n=y.get(p);n||y.set(p,n=new Map);let r=n.get(u);r||n.set(u,r=new Map);let o=e.role===e.serviceRole?"service":e.role==="anon"?"anon":"authenticated",g=o==="service"?{service:e.serviceRole}:{[o]:e.role,service:e.serviceRole},f=`${o}\0${e.role}\0${e.serviceRole}`,i=r.get(f);i||(i=v({sql:p,schemas:u,binding:R(0,!0),roles:g,...a.fields!==void 0?{fields:a.fields}:{}}),r.set(f,i));let b=JSON.parse(e.claimsJson),m=i.then(s=>s.request({role:o,claims:b},{diagnostics:a.diagnostics,signal:a.signal})),d=s=>new Proxy(()=>{},{apply:async(t,D,c)=>{let l=(await m).client;return s(l).apply(l,c)}});return{client:new Proxy({},{get(s,t){if(t!=="then")return t==="diagnostics"?()=>null:t==="asService"?()=>new Proxy({},{get:(D,c)=>c==="then"?void 0:d(l=>l.asService()[c])}):d(D=>D[t])}}),commit:async()=>(await m).commit(),rollback:async s=>(await m).rollback(s)}}export{w as createApp,q as createRequestDatabase,h as makeMemoryCache};
1
+ /*! palbase 0.14.2 — Palbase SDK License (see LICENSE) */
2
+ import{ha as w,la as h}from"../chunks/QZH6GPCR.js";import"../chunks/SBUC7GHR.js";import"../chunks/CUL5OL4P.js";import"../chunks/LUFWGH2V.js";import"../chunks/HHZSOYPP.js";import"../chunks/ZZNGA77G.js";import"../chunks/BRHGS5AI.js";import"../chunks/3AENUHVO.js";import"../chunks/44ULNVPP.js";import"../chunks/OMK2YEDZ.js";import"../chunks/RD5JFDGQ.js";import"../chunks/JKWWY2LJ.js";import"../chunks/P67I4TNQ.js";import"../chunks/6NC5RYCS.js";import{binding as R,createDatabase as v}from"palgres";var y=new WeakMap;function q(p,e,a){if(!a?.schemas?.length)throw new TypeError("createRequestDatabase(sql, identity, { schemas }): the engine compiles each call against the app's schemas \u2014 pass the schema files' default exports");let u=a.schemas,n=y.get(p);n||y.set(p,n=new Map);let r=n.get(u);r||n.set(u,r=new Map);let o=e.role===e.serviceRole?"service":e.role==="anon"?"anon":"authenticated",g=o==="service"?{service:e.serviceRole}:{[o]:e.role,service:e.serviceRole},f=`${o}\0${e.role}\0${e.serviceRole}`,i=r.get(f);i||(i=v({sql:p,schemas:u,binding:R(0,!0),roles:g,...a.fields!==void 0?{fields:a.fields}:{}}),r.set(f,i));let b=JSON.parse(e.claimsJson),m=i.then(s=>s.request({role:o,claims:b},{diagnostics:a.diagnostics,signal:a.signal})),d=s=>new Proxy(()=>{},{apply:async(t,D,c)=>{let l=(await m).client;return s(l).apply(l,c)}});return{client:new Proxy({},{get(s,t){if(t!=="then")return t==="diagnostics"?()=>null:t==="asService"?()=>new Proxy({},{get:(D,c)=>c==="then"?void 0:d(l=>l.asService()[c])}):d(D=>D[t])}}),commit:async()=>(await m).commit(),rollback:async s=>(await m).rollback(s)}}export{w as createApp,q as createRequestDatabase,h as makeMemoryCache};
@@ -1 +1 @@
1
- /*! palbase 0.14.1 — Palbase SDK License (see LICENSE) */
1
+ /*! palbase 0.14.2 — Palbase SDK License (see LICENSE) */
@@ -1,5 +1,5 @@
1
- /*! palbase 0.14.1 — Palbase SDK License (see LICENSE) */
2
- import{$ as It,A as F,B as dt,C as ut,D as ht,E as ft,F as gt,G as bt,H as mt,I as yt,J as wt,K as Pt,L as St,M as vt,N as At,O as kt,P as Et,Q as Tt,R as _t,S as xt,T as Rt,U as Ot,V as Ct,W as Bt,X as re,Y as Ft,Z as Mt,_ as $t,a as Q,aa as Lt,b as X,ba as Ut,c as Z,ca as Dt,d as Ne,da as jt,e as qe,ea as Nt,f as We,fa as M,g as Ke,ga as Vt,h as Ve,ha as $,i as Ge,ia as V,j as ze,ja as Gt,k as He,ka as zt,l as Ye,m as Je,n as Qe,o as Xe,p as Ze,q as et,r as tt,s as rt,t as st,u as nt,v as at,w as ot,x as it,y as lt,z as ct}from"../chunks/EH4ZWZCT.js";import{a as ne}from"../chunks/IXOQ6JI5.js";import{a as x,b as ee,c as te,f as b,g as pt,h as d,j as se,k as Kt}from"../chunks/S6HM2J7J.js";import{a as qt,b as Wt}from"../chunks/2CR3IN7R.js";import{d as _,j as De,k as je,l as H,m as B,t as Y,u as J}from"../chunks/WZLLB24Q.js";import"../chunks/7UQMB3JW.js";import"../chunks/UXURIXBA.js";import"../chunks/LND5DXD3.js";import"../chunks/VLNIDQ36.js";import"../chunks/3CUWIZU2.js";import{m as Ue}from"../chunks/GHEORI3H.js";import"../chunks/URK5PA2R.js";import{b as A,c as K}from"../chunks/RBDGMOJT.js";import"../chunks/2PCIM4VH.js";import"../chunks/FZB357V4.js";import"reflect-metadata";import{existsSync as G,writeFileSync as _r,writeSync as xr}from"node:fs";import{createServer as Rr}from"node:http";import{dirname as k,join as z,resolve as xe}from"node:path";import{Readable as Or}from"node:stream";var Ht=2e3,Yt=1e4,Jt=/^[A-Za-z0-9_-]{1,64}$/,Qt=512,I=class{linesPerSecond;batchSize;flushMs;maxPending;sendMs;shutdownMs;now;tokens;refilled;unlogged=0;unloggedSince;pending=[];timer;sending;inFlight;pausedUntil=0;lastSendWarning=0;sink;constructor(e,r={}){this.sink=e,this.linesPerSecond=r.linesPerSecond??10,this.batchSize=Math.min(100,r.batchSize??100),this.flushMs=r.flushMs??2e3,this.maxPending=r.maxPending??2e3,this.sendMs=r.sendMs??Yt,this.shutdownMs=r.shutdownMs??Ht,this.now=r.now??Date.now,this.tokens=this.linesPerSecond,this.refilled=this.now(),this.unloggedSince=this.refilled}record(e){this.log(e),this.sink&&this.trace(e)}async flush(){this.timer&&clearTimeout(this.timer),this.timer=void 0;let e=!1,r,s=new Promise(a=>r=a),n=setTimeout(()=>{e=!0,r()},this.shutdownMs);try{for(;!e&&(this.pending.length>0||this.sending)&&(await Promise.race([this.sending??this.send(),s]),!(this.now()<this.pausedUntil)););}finally{clearTimeout(n)}e&&this.letGo()}letGo(){let e=this.inFlight,r=(e?.traces??0)+this.pending.length;this.pending=[],e&&(e.letGo=!0,e.call.abort(new Error(`analytics did not answer within the ${this.shutdownMs} ms a flush waits`))),r>0&&d.warn(`[palbase] request traces were not sent to analytics within the ${this.shutdownMs} ms a flush waits; ${r} dropped`)}log(e){let r=this.now();if(this.tokens=Math.min(this.linesPerSecond,this.tokens+(r-this.refilled)/1e3*this.linesPerSecond),this.refilled=r,this.unlogged>0&&r-this.unloggedSince>=6e4&&(d.info(`[palbase] ${this.unlogged} more requests answered in the last minute than the log keeps a line for (Analytics \u203A Network has every one)`),this.unlogged=0,this.unloggedSince=r),this.tokens<1){this.unlogged===0&&(this.unloggedSince=r),this.unlogged++;return}this.tokens-=1;let s=e.status>=500?"error":e.status>=400&&e.status!==499?"warn":"info",n=Math.round(e.durationMs*10)/10;d[s](`${e.method} ${e.path} ${e.status} ${n}ms`,{route:e.endpoint,status:e.status,duration_ms:n,...e.userId?{user_id:e.userId}:{}})}trace(e){this.pending.length>=this.maxPending&&this.pending.shift(),this.pending.push({request_id:Jt.test(e.requestId)?e.requestId:e.requestId.replace(/[^A-Za-z0-9_-]/g,"_").slice(0,64)||"unnamed",source:"backend",endpoint:e.endpoint.slice(0,Qt),method:e.method,status:e.status,duration_ms:Math.max(0,Math.round(e.durationMs)),timestamp:this.now(),...e.userId?{distinct_id:e.userId}:{}}),this.pending.length>=this.batchSize&&!this.sending?this.send():!this.timer&&!this.sending&&this.schedule(this.flushMs)}schedule(e){this.timer=setTimeout(()=>{this.send()},e),this.timer.unref?.()}send(){if(this.timer&&clearTimeout(this.timer),this.timer=void 0,this.sending||this.pending.length===0||this.now()<this.pausedUntil||!this.sink)return this.sending??Promise.resolve();let e=this.pending.splice(0,this.batchSize),r=this.sink,s={call:new AbortController,traces:e.length,letGo:!1};this.inFlight=s;let n=setTimeout(()=>s.call.abort(new Error(`analytics did not answer in ${this.sendMs} ms`)),this.sendMs);return n.unref?.(),this.sending=(async()=>{try{await r.sendTraceBatch({body:{traces:e},signal:s.call.signal})}catch(a){if(s.letGo)return;let i=a.status,o=i??(s.call.signal.aborted?`no answer in ${this.sendMs} ms`:"unreachable"),c=a.retryAfter;this.pausedUntil=this.now()+(typeof c=="number"&&c>0?c*1e3:i===429?1e3:5e3),this.now()-this.lastSendWarning>6e4&&(this.lastSendWarning=this.now(),d.warn(`[palbase] request traces were not sent to analytics (${o}); ${e.length} dropped`,{error:a}))}finally{if(clearTimeout(n),this.sending=void 0,this.inFlight=void 0,this.pending.length>0){let a=Math.max(0,this.pausedUntil-this.now());this.schedule(this.pending.length>=this.batchSize?a:Math.max(a,this.flushMs))}}})(),this.sending}};import{createHmac as Xt}from"node:crypto";import{bind as Zt,bunDriver as er,createDatabase as tr,envBlock as rr,createSearchWorker as sr,cutOff as nr,forgetUser as ar,MigrationOpen as or,MigrationRefused as ir,Migrator as ce,renewingBunPool as ae,VersionNotMigrated as lr}from"palgres";import{toModel as de}from"palgres/dsl";var cr=["start","complete","rollback","plan","status","types"],dr=/^(deploy|cli:[^\u0000-\u001f\u007f]{1,200})$/u;function ue(t){let e=t.PALBASE_DB_MIGRATE;if(!(e===void 0||e==="")){if(!cr.includes(e))throw new Error(`[palbase] PALBASE_DB_MIGRATE is start, complete, rollback, plan, status or types, not ${e}`);return e}}function pe(t){let e=Array.isArray(t.schemas)?t.schemas:[t.schemas];for(let r of e)if(r.name===M.name)throw new Error(`[palbase] db.schemas: the ${M.name} schema is the framework's own (its tables are migrated with the app's) \u2014 name the app's schema otherwise`);return[...e,M]}function U(t){return de(pe(t))}function ur(t){return t.tables.some(e=>e.search!==void 0)}function D(t){return t.tables.some(e=>!e.ignored&&e.columns.some(r=>r.user!==void 0&&!r.ignored))}function he(t){let e=t.PALBASE_DB_CONNECTIONS;if(e===void 0||e==="")return 31;let r=Number(e);if(!Number.isSafeInteger(r)||r<4)throw new Error(`[palbase] PALBASE_DB_CONNECTIONS is how many connections the app may hold to its database, 4 at least (a request's transaction, the two further ones it may hold, one to cancel with) \u2014 not ${e}`);return r}function pr(t){if(!Number.isSafeInteger(t)||t<3)throw new Error(`[palbase] db.driver: a pool of ${t} connection(s) \u2014 the engine needs at least 3: one request's transaction and the two further ones it may hold`);let e=Math.floor(t/3);return{concurrency:e,nestedConcurrency:e*2}}var oe=5;function fe(t,e){if(t.driver)return t.driver;let r=globalThis.Bun;if(!r)throw new Error("[palbase] db.driver: off Bun there is no SQL client built in \u2014 give one: postgres.js with { types: POSTGRES_JS_TYPES }, its engine postgresJsDriver(pool, control)");let s=e-1;return n=>{let a=ae(()=>new r.SQL({url:n,prepare:!1,max:s})),i=ae(()=>new r.SQL({url:n,prepare:!1,max:1}));return{pool:{reserve:()=>a.reserve(),unsafe:(o,c)=>a.unsafe(o,c),begin:o=>a.current.begin(o)},engine:er(a,i),poolSize:s,close:async()=>{await a.close({timeout:oe}),await i.close({timeout:oe})}}}}async function ge(t){return t==="rollback"?(d.info("[palbase] migrate rollback: this app declares no database; nothing of it to take back"),await R(t,{state:"none"}),0):(d.error(`[palbase] migrate ${t}: this app declares no database \u2014 PalbaseFactory.create(\u2026, { db: { schemas } })`),1)}async function be(t,e){if(!t)return d.error("[palbase] db types: this app declares no database \u2014 PalbaseFactory.create(\u2026, { db: { schemas } })"),1;let r=Array.isArray(t.schemas)?t.schemas:[t.schemas];return await R("types",rr(r,{module:"palbase/backend/env"}),e),0}async function me(t,e,r){let s=e.PALBASE_DB_OWNER_URL;if(!s)return d.error("[palbase] PALBASE_DB_MIGRATE without PALBASE_DB_OWNER_URL: a migration runs as the tables' owner"),1;let n=e.PALBASE_DB_MIGRATION_BY||"deploy";if(!dr.test(n))return d.error("[palbase] PALBASE_DB_MIGRATION_BY is deploy, or cli:<who>"),1;let a=fe(t,he(e)),i=a(s),o,c=l=>d.error(`[palbase] migrate ${r}: ${l}`);try{let l=U(t),u=new ce(i.pool,{log:f=>{/ is held by others | held by writers/.test(f)&&(o=f.trim()),d.info(f)},shadow:f=>{let g=new URL(s);g.pathname=`/${f}`;let y=a(g.toString());return{reserve:()=>y.pool.reserve(),end:()=>y.close()}},openedBy:n,fields:()=>hr(e)});if(r==="plan"){let f=await u.plan(l);return await R(r,f),f.refusals.length>0?1:0}if(r==="status")return await R(r,await u.status()),0;let h=r==="start"?await fr(u,l,n):r==="complete"?await u.complete():await u.rollback();return d.info(`[palbase] migrate ${r}: done`,{result:h}),await R(r,h),0}catch(l){return l instanceof ir?(d.error(`[palbase] migrate ${r}: refused`,{refusals:l.refusals}),c(`refused \u2014 ${l.refusals.join("; ")}`),1):nr(l)?(d.error(`[palbase] migrate ${r}: cut off; run again, it goes on from where it stopped`,{error:l}),c(`cut off \u2014 ${o??ie(l)}`),75):(d.error(`[palbase] migrate ${r}: failed`,{error:l}),c(`failed \u2014 ${ie(l)}`),1)}finally{await i.close().catch(()=>{})}}async function hr(t){let e=t.PALBASE_URL,r=t.PALBASE_SECRET_KEY;if(!e||!r)throw new Error("[palbase] this migration seals or opens an encrypted column's rows: it reads the project's field keys with PALBASE_URL and PALBASE_SECRET_KEY");let s=_({url:e,secretKey:r}).fields;return await s.load(),s.close(),s}async function fr(t,e,r){try{return await t.start(e)}catch(s){if(!(s instanceof or)||r!=="deploy"||!s.openedBy?.startsWith("cli:"))throw s;return d.warn(`[palbase] migrate start: the migration ${s.openedBy} opened (version ${s.to}) gives way to this release \u2014 rolled back first`),await t.rollback(),await t.start(e)}}var gr=(t,e)=>{process.stdout.write(t,()=>e())};function R(t,e,r=gr){return new Promise(s=>r(`${JSON.stringify({palbase_migrate:t,result:e})}
1
+ /*! palbase 0.14.2 — Palbase SDK License (see LICENSE) */
2
+ import{$ as It,A as F,B as dt,C as ut,D as ht,E as ft,F as gt,G as bt,H as mt,I as yt,J as wt,K as Pt,L as St,M as vt,N as At,O as kt,P as Et,Q as Tt,R as _t,S as xt,T as Rt,U as Ot,V as Ct,W as Bt,X as re,Y as Ft,Z as Mt,_ as $t,a as Q,aa as Lt,b as X,ba as Ut,c as Z,ca as Dt,d as Ne,da as jt,e as qe,ea as Nt,f as We,fa as M,g as Ke,ga as Vt,h as Ve,ha as $,i as Ge,ia as V,j as ze,ja as Gt,k as He,ka as zt,l as Ye,m as Je,n as Qe,o as Xe,p as Ze,q as et,r as tt,s as rt,t as st,u as nt,v as at,w as ot,x as it,y as lt,z as ct}from"../chunks/QZH6GPCR.js";import{a as ne}from"../chunks/DIOZGDFQ.js";import{a as x,b as ee,c as te,f as b,g as pt,h as d,j as se,k as Kt}from"../chunks/SBUC7GHR.js";import{a as qt,b as Wt}from"../chunks/CUL5OL4P.js";import{d as _,j as De,k as je,l as H,m as B,t as Y,u as J}from"../chunks/LUFWGH2V.js";import"../chunks/HHZSOYPP.js";import"../chunks/ZZNGA77G.js";import"../chunks/BRHGS5AI.js";import"../chunks/3AENUHVO.js";import"../chunks/44ULNVPP.js";import{m as Ue}from"../chunks/OMK2YEDZ.js";import"../chunks/RD5JFDGQ.js";import{b as A,c as K}from"../chunks/JKWWY2LJ.js";import"../chunks/P67I4TNQ.js";import"../chunks/6NC5RYCS.js";import"reflect-metadata";import{existsSync as G,writeFileSync as _r,writeSync as xr}from"node:fs";import{createServer as Rr}from"node:http";import{dirname as k,join as z,resolve as xe}from"node:path";import{Readable as Or}from"node:stream";var Ht=2e3,Yt=1e4,Jt=/^[A-Za-z0-9_-]{1,64}$/,Qt=512,I=class{linesPerSecond;batchSize;flushMs;maxPending;sendMs;shutdownMs;now;tokens;refilled;unlogged=0;unloggedSince;pending=[];timer;sending;inFlight;pausedUntil=0;lastSendWarning=0;sink;constructor(e,r={}){this.sink=e,this.linesPerSecond=r.linesPerSecond??10,this.batchSize=Math.min(100,r.batchSize??100),this.flushMs=r.flushMs??2e3,this.maxPending=r.maxPending??2e3,this.sendMs=r.sendMs??Yt,this.shutdownMs=r.shutdownMs??Ht,this.now=r.now??Date.now,this.tokens=this.linesPerSecond,this.refilled=this.now(),this.unloggedSince=this.refilled}record(e){this.log(e),this.sink&&this.trace(e)}async flush(){this.timer&&clearTimeout(this.timer),this.timer=void 0;let e=!1,r,s=new Promise(a=>r=a),n=setTimeout(()=>{e=!0,r()},this.shutdownMs);try{for(;!e&&(this.pending.length>0||this.sending)&&(await Promise.race([this.sending??this.send(),s]),!(this.now()<this.pausedUntil)););}finally{clearTimeout(n)}e&&this.letGo()}letGo(){let e=this.inFlight,r=(e?.traces??0)+this.pending.length;this.pending=[],e&&(e.letGo=!0,e.call.abort(new Error(`analytics did not answer within the ${this.shutdownMs} ms a flush waits`))),r>0&&d.warn(`[palbase] request traces were not sent to analytics within the ${this.shutdownMs} ms a flush waits; ${r} dropped`)}log(e){let r=this.now();if(this.tokens=Math.min(this.linesPerSecond,this.tokens+(r-this.refilled)/1e3*this.linesPerSecond),this.refilled=r,this.unlogged>0&&r-this.unloggedSince>=6e4&&(d.info(`[palbase] ${this.unlogged} more requests answered in the last minute than the log keeps a line for (Analytics \u203A Network has every one)`),this.unlogged=0,this.unloggedSince=r),this.tokens<1){this.unlogged===0&&(this.unloggedSince=r),this.unlogged++;return}this.tokens-=1;let s=e.status>=500?"error":e.status>=400&&e.status!==499?"warn":"info",n=Math.round(e.durationMs*10)/10;d[s](`${e.method} ${e.path} ${e.status} ${n}ms`,{route:e.endpoint,status:e.status,duration_ms:n,...e.userId?{user_id:e.userId}:{}})}trace(e){this.pending.length>=this.maxPending&&this.pending.shift(),this.pending.push({request_id:Jt.test(e.requestId)?e.requestId:e.requestId.replace(/[^A-Za-z0-9_-]/g,"_").slice(0,64)||"unnamed",source:"backend",endpoint:e.endpoint.slice(0,Qt),method:e.method,status:e.status,duration_ms:Math.max(0,Math.round(e.durationMs)),timestamp:this.now(),...e.userId?{distinct_id:e.userId}:{}}),this.pending.length>=this.batchSize&&!this.sending?this.send():!this.timer&&!this.sending&&this.schedule(this.flushMs)}schedule(e){this.timer=setTimeout(()=>{this.send()},e),this.timer.unref?.()}send(){if(this.timer&&clearTimeout(this.timer),this.timer=void 0,this.sending||this.pending.length===0||this.now()<this.pausedUntil||!this.sink)return this.sending??Promise.resolve();let e=this.pending.splice(0,this.batchSize),r=this.sink,s={call:new AbortController,traces:e.length,letGo:!1};this.inFlight=s;let n=setTimeout(()=>s.call.abort(new Error(`analytics did not answer in ${this.sendMs} ms`)),this.sendMs);return n.unref?.(),this.sending=(async()=>{try{await r.sendTraceBatch({body:{traces:e},signal:s.call.signal})}catch(a){if(s.letGo)return;let i=a.status,o=i??(s.call.signal.aborted?`no answer in ${this.sendMs} ms`:"unreachable"),c=a.retryAfter;this.pausedUntil=this.now()+(typeof c=="number"&&c>0?c*1e3:i===429?1e3:5e3),this.now()-this.lastSendWarning>6e4&&(this.lastSendWarning=this.now(),d.warn(`[palbase] request traces were not sent to analytics (${o}); ${e.length} dropped`,{error:a}))}finally{if(clearTimeout(n),this.sending=void 0,this.inFlight=void 0,this.pending.length>0){let a=Math.max(0,this.pausedUntil-this.now());this.schedule(this.pending.length>=this.batchSize?a:Math.max(a,this.flushMs))}}})(),this.sending}};import{createHmac as Xt}from"node:crypto";import{bind as Zt,bunDriver as er,createDatabase as tr,envBlock as rr,createSearchWorker as sr,cutOff as nr,forgetUser as ar,MigrationOpen as or,MigrationRefused as ir,Migrator as ce,renewingBunPool as ae,VersionNotMigrated as lr}from"palgres";import{toModel as de}from"palgres/dsl";var cr=["start","complete","rollback","plan","status","types"],dr=/^(deploy|cli:[^\u0000-\u001f\u007f]{1,200})$/u;function ue(t){let e=t.PALBASE_DB_MIGRATE;if(!(e===void 0||e==="")){if(!cr.includes(e))throw new Error(`[palbase] PALBASE_DB_MIGRATE is start, complete, rollback, plan, status or types, not ${e}`);return e}}function pe(t){let e=Array.isArray(t.schemas)?t.schemas:[t.schemas];for(let r of e)if(r.name===M.name)throw new Error(`[palbase] db.schemas: the ${M.name} schema is the framework's own (its tables are migrated with the app's) \u2014 name the app's schema otherwise`);return[...e,M]}function U(t){return de(pe(t))}function ur(t){return t.tables.some(e=>e.search!==void 0)}function D(t){return t.tables.some(e=>!e.ignored&&e.columns.some(r=>r.user!==void 0&&!r.ignored))}function he(t){let e=t.PALBASE_DB_CONNECTIONS;if(e===void 0||e==="")return 31;let r=Number(e);if(!Number.isSafeInteger(r)||r<4)throw new Error(`[palbase] PALBASE_DB_CONNECTIONS is how many connections the app may hold to its database, 4 at least (a request's transaction, the two further ones it may hold, one to cancel with) \u2014 not ${e}`);return r}function pr(t){if(!Number.isSafeInteger(t)||t<3)throw new Error(`[palbase] db.driver: a pool of ${t} connection(s) \u2014 the engine needs at least 3: one request's transaction and the two further ones it may hold`);let e=Math.floor(t/3);return{concurrency:e,nestedConcurrency:e*2}}var oe=5;function fe(t,e){if(t.driver)return t.driver;let r=globalThis.Bun;if(!r)throw new Error("[palbase] db.driver: off Bun there is no SQL client built in \u2014 give one: postgres.js with { types: POSTGRES_JS_TYPES }, its engine postgresJsDriver(pool, control)");let s=e-1;return n=>{let a=ae(()=>new r.SQL({url:n,prepare:!1,max:s})),i=ae(()=>new r.SQL({url:n,prepare:!1,max:1}));return{pool:{reserve:()=>a.reserve(),unsafe:(o,c)=>a.unsafe(o,c),begin:o=>a.current.begin(o)},engine:er(a,i),poolSize:s,close:async()=>{await a.close({timeout:oe}),await i.close({timeout:oe})}}}}async function ge(t){return t==="rollback"?(d.info("[palbase] migrate rollback: this app declares no database; nothing of it to take back"),await R(t,{state:"none"}),0):(d.error(`[palbase] migrate ${t}: this app declares no database \u2014 PalbaseFactory.create(\u2026, { db: { schemas } })`),1)}async function be(t,e){if(!t)return d.error("[palbase] db types: this app declares no database \u2014 PalbaseFactory.create(\u2026, { db: { schemas } })"),1;let r=Array.isArray(t.schemas)?t.schemas:[t.schemas];return await R("types",rr(r,{module:"palbase/backend/env"}),e),0}async function me(t,e,r){let s=e.PALBASE_DB_OWNER_URL;if(!s)return d.error("[palbase] PALBASE_DB_MIGRATE without PALBASE_DB_OWNER_URL: a migration runs as the tables' owner"),1;let n=e.PALBASE_DB_MIGRATION_BY||"deploy";if(!dr.test(n))return d.error("[palbase] PALBASE_DB_MIGRATION_BY is deploy, or cli:<who>"),1;let a=fe(t,he(e)),i=a(s),o,c=l=>d.error(`[palbase] migrate ${r}: ${l}`);try{let l=U(t),u=new ce(i.pool,{log:f=>{/ is held by others | held by writers/.test(f)&&(o=f.trim()),d.info(f)},shadow:f=>{let g=new URL(s);g.pathname=`/${f}`;let y=a(g.toString());return{reserve:()=>y.pool.reserve(),end:()=>y.close()}},openedBy:n,fields:()=>hr(e)});if(r==="plan"){let f=await u.plan(l);return await R(r,f),f.refusals.length>0?1:0}if(r==="status")return await R(r,await u.status()),0;let h=r==="start"?await fr(u,l,n):r==="complete"?await u.complete():await u.rollback();return d.info(`[palbase] migrate ${r}: done`,{result:h}),await R(r,h),0}catch(l){return l instanceof ir?(d.error(`[palbase] migrate ${r}: refused`,{refusals:l.refusals}),c(`refused \u2014 ${l.refusals.join("; ")}`),1):nr(l)?(d.error(`[palbase] migrate ${r}: cut off; run again, it goes on from where it stopped`,{error:l}),c(`cut off \u2014 ${o??ie(l)}`),75):(d.error(`[palbase] migrate ${r}: failed`,{error:l}),c(`failed \u2014 ${ie(l)}`),1)}finally{await i.close().catch(()=>{})}}async function hr(t){let e=t.PALBASE_URL,r=t.PALBASE_SECRET_KEY;if(!e||!r)throw new Error("[palbase] this migration seals or opens an encrypted column's rows: it reads the project's field keys with PALBASE_URL and PALBASE_SECRET_KEY");let s=_({url:e,secretKey:r}).fields;return await s.load(),s.close(),s}async function fr(t,e,r){try{return await t.start(e)}catch(s){if(!(s instanceof or)||r!=="deploy"||!s.openedBy?.startsWith("cli:"))throw s;return d.warn(`[palbase] migrate start: the migration ${s.openedBy} opened (version ${s.to}) gives way to this release \u2014 rolled back first`),await t.rollback(),await t.start(e)}}var gr=(t,e)=>{process.stdout.write(t,()=>e())};function R(t,e,r=gr){return new Promise(s=>r(`${JSON.stringify({palbase_migrate:t,result:e})}
3
3
  `,s))}function ie(t){return(t instanceof Error?t.message:String(t)).split(`
4
4
  `)[0].slice(0,300)||(t instanceof Error?t.name:"unknown")}async function br(t,e){try{return await new ce(t).plan(e)}catch{return}}var le="palbase.idempotency_keys.response_body";function mr(t,e){let r=null,s=!1,n=async()=>{let o=e.currentKey();if(!(s||o===r)){s=!0;try{let c=await t.reseal();r=o;let l=c.reduce((u,h)=>u+h.resealed,0);l>0&&d.info(`[palbase] fields: ${l} value(s) sealed again with key ${o}`,{report:c})}catch(c){d.warn(`[palbase] fields: sealing again with key ${o} stopped; tried again in a minute`,{error:c})}finally{s=!1}}},a=setTimeout(n,1e4),i=setInterval(n,6e4);for(let o of[a,i])o.unref?.();return()=>{clearTimeout(a),clearInterval(i)}}var L=class extends Error{digest;plan;constructor(e,r){super([`[palbase] this schema (${e}) has no version in the database yet: palbase db:push tries it there (a database of your own: palbase db:push --url <its address>)`,...r?yr(r):[" palbase db:plan says what it would change"]].join(`
5
5
  `)),this.name="SchemaNotPushed",this.digest=e,this.plan=r}};function yr(t){let e=[t.adoption?` takes the database over as version 1${t.to>1?`, then version 1 \u2192 ${t.to}`:""}`:` version ${t.from??"none"} \u2192 ${t.to}`];t.changes.length===0&&t.refusals.length===0&&e.push(" nothing to change");for(let r of t.changes)e.push(` + ${r}`);for(let r of t.refusals)e.push(` \u2717 ${r}`);return e}var wr=8e4;async function ye(t,e,r,s){let n=t.url??e.PALBASE_DB_URL;if(!n)throw new Error("[palbase] db.url / PALBASE_DB_URL is the database the app connects to");let a=pe(t),i=de(a),o=fe(t,he(e))(n);try{let c=!1,l=p=>{c||(c=!0,d.warn(`[palbase] database: not answering yet (${p instanceof Error?p.message:String(p)}) \u2014 waiting for it, as one waking does`))},u=await Zt(o.engine,i,{waitMs:s.onPlatform?wr:0,onUnreachable:l}).catch(async p=>{throw s.onPlatform||!(p instanceof lr)?p:new L(p.digest,await br(o.pool,i))}),h=Xt("sha256",r).update("palgres page cursor").digest("hex"),f=t.embed??s.embed,g=s.fields,y=await tr({sql:o.engine,schemas:a,binding:u,cursorSecret:h,admission:pr(o.poolSize),embed:f,log:p=>d.warn(`[palbase] ${p}`),fields:async()=>(await g.load(),g)}),S=g.loaded?mr(y,g):()=>{},m=ur(i)?sr({sql:o.engine,embed:f,log:p=>d.info(`[palbase] ${p}`)}):void 0;return{model:i,binding:u,app:y,requests:t.requests??"caller",forget:p=>ar(o.engine,u,i,p),...m?{search:m}:{},keptAnswers:{seal:p=>g.loaded?g.encrypt(le,p):p,open:async p=>g.isEncrypted(p)?(g.loaded||await g.load(),g.decrypt(le,p)):p},close:async()=>{S(),g.close(),await o.close()}}}catch(c){throw await o.close(),c}}function Pr(t){let e=Buffer.from(t,"base64"),r=new Array(e.byteLength/4);for(let s=0;s<r.length;s++)r[s]=e.readFloatLE(s*4);return r}function we(t){return async({texts:e,model:r,dimensions:s})=>{let{data:n}=await t.ai.createEmbeddings({body:{input:e,model:r,dimensions:s}});return{model:n.model,vectors:n.vectors.map(Pr)}}}var Sr=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function Pe(t,e,r){let s=[],n=t.url??e.PALBASE_URL??"",a="";try{let u=new URL(n);a=u.origin,u.protocol!=="https:"&&u.hostname!=="localhost"&&u.hostname!=="127.0.0.1"&&s.push("palbase.url / PALBASE_URL is https://<ref>.<domain>"),(u.pathname!=="/"||u.search||u.hash)&&s.push("palbase.url / PALBASE_URL is the project origin alone")}catch{s.push("palbase.url / PALBASE_URL is the project address, https://<ref>.<domain>")}let i=t.projectId??e.PALBASE_PROJECT_ID??"";Sr.test(i)||s.push("palbase.projectId / PALBASE_PROJECT_ID is the project id (a UUID)");let o=t.secretKey??e.PALBASE_SECRET_KEY??"";/^pb_[a-z0-9]+_s/.test(o)||s.push("palbase.secretKey / PALBASE_SECRET_KEY is the project secret key (pb_<ref>_s\u2026), kept in the project's Secrets");let c=(t.platformSecret??e.PALBASE_PLATFORM_SECRET)||void 0;c!==void 0&&!/^[0-9a-f]{64}$/.test(c)&&s.push("palbase.platformSecret / PALBASE_PLATFORM_SECRET is the key the platform signs its calls to this machine with (64 hex characters): the platform sets it, unset off the platform");let l=(t.webhookSecret??e.PALBASE_WEBHOOK_SECRET)||void 0;if(r.needsWebhookSecret&&(c!==void 0||l!==void 0)&&!/^whsec_[0-9a-f]{64}$/.test(l??"")&&s.push("palbase.webhookSecret / PALBASE_WEBHOOK_SECRET is the project's webhook endpoint secret (whsec_\u2026): the platform delivers this app events \u2014 its @On handlers', or user.deleted for the users its tables keep"),s.length>0)throw new Error(`[palbase] the app cannot start:
@@ -9,4 +9,4 @@ ${s.join(`
9
9
  `)}
10
10
  `}function Ae(t,e,r=Ar){let s=Buffer.from(e,"utf8"),n=new Int32Array(new SharedArrayBuffer(4));for(let a=0;a<s.length;)try{a+=r(t,s,a,s.length-a)}catch(i){if(i.code!=="EAGAIN")throw i;Atomics.wait(n,0,0,5)}}var ke=2e4,Ee=5e3,Cr=15e3,Br="/_palbase/health";function Fr(t){let e=new Set,r=s=>{if(e.has(s))return!1;e.add(s);let n=F(s,Q);return n?n.providers.some(a=>F(a,X)!==void 0&&F(a,Z)===void 0)||n.imports.some(r):!1};return t.some(r)}var Mr={async create(t,e={}){let r=Array.isArray(t)?t:[t],s=e.env??process.env,n=ue(s);if(n!==void 0){let w=n==="types"?await be(e.db):e.db?await me(e.db,s,n):await ge(n);throw process.exit(w),new j(w)}let a=s.PALBASE_CONTRACT_OUT;if(a){let w;try{await _e(Te(s)),w=await $r(r,e,s)}catch(v){throw xr(2,`[palbase] the contract: ${v instanceof Error?v.message:String(v)}
11
11
  `),process.exit(1),new O}throw a==="/dev/stdout"?Ae(1,ve(w)):_r(a,`${w}
12
- `),process.exit(0),new O}let i=Te(s),o=await _e(i);o&&d.info(`[palbase] strings: ${o.source} and ${o.locales.length-1} other language(s), ${Object.keys(o.strings).length} sentence(s), from ${i}/palbase/strings`),se(o?void 0:i);let c=e.db?U(e.db):void 0,l=await J({env:s,url:e.palbase?.url,secretKey:e.palbase?.secretKey});l&&d.info(`[palbase] secrets: ${l.loaded.length} from the project's ${l.set} set${l.kept.length>0?`; ${l.kept.join(", ")} kept as the environment gives them`:""}`),l&&l.refused.length>0&&d.warn(`[palbase] secrets not set \u2014 names a process reads as its own, not the app's: ${l.refused.map(w=>JSON.stringify(w)).join(", ")}`);let u=Fr(r)||c!==void 0&&D(c),h=Pe(e.palbase??{},s,{needsWebhookSecret:u});u&&h.webhookSecret===void 0&&d.warn("[palbase] events: none is delivered here \u2014 the platform delivers them to the app's machine, not to this computer; its @On handlers (and forgetting a deleted user's rows) run there. Set PALBASE_WEBHOOK_SECRET to take a delivery forwarded here");let f=_({url:h.url,secretKey:h.secretKey}),g=e.port??Number(s.PORT??"8080");if(!Number.isInteger(g)||g<0||g>65535)throw new Error(`[palbase] PORT is a port number, not ${String(e.port??s.PORT)}`);let y=e.db?await ye(e.db,s,h.secretKey,{onPlatform:h.platformSecret!==void 0,embed:we(f),fields:f.fields}):void 0;y&&d.info(`[palbase] database: version ${y.binding.version}`);let S=y&&D(y.model)?{"user.deleted":[w=>Ir(y,w)]}:void 0,m=h.platformSecret===void 0?void 0:{secret:h.platformSecret},p=e.requestTelemetry===!1?void 0:new I(f.analytics),C=()=>$({modules:r,verifier:new B({issuer:h.url,projectId:h.projectId,standing:H({url:h.url,secretKey:h.secretKey})}),server:f,webhookSecret:h.webhookSecret,env:s,projectId:h.projectId,telemetry:p,auth:e.auth,tokens:e.tokens,rateLimit:e.rateLimit,maxBodyBytes:e.bodyLimit,cors:Dr(e.cors,s.PALBASE_WEB_ORIGINS),platform:m,events:S,database:y&&{app:y.app,requests:y.requests,keptAnswers:y.keptAnswers},strings:o}),T=C(),q=e.boot?.attempts??5,W=e.boot?.backoffMs??1e3;for(let w=1;;w++)try{await T.start();break}catch(v){if(w>=q)throw d.error(`[palbase] the app did not start after ${q} attempts`,{error:v}),v;d.warn(`[palbase] the app did not start (attempt ${w} of ${q}); trying again in ${W} ms`,{error:v}),await new Promise(Le=>setTimeout(Le,W)),W*=2,T=C()}return Lr(T,f,g,e.host??"0.0.0.0",e.exitOnFatal??!0,y)}};function Te(t){let e=t.PALBASE_CONTRACT_ENTRY??process.argv[1];if(!e)return process.cwd();let r=k(xe(e));for(;!G(z(r,"package.json"))&&k(r)!==r;)r=k(r);return G(z(r,"package.json"))?r:process.cwd()}async function _e(t){try{return await ne(t)}catch(e){throw new Error(`[palbase] the app's strings: ${e instanceof Error?e.message:String(e)}`)}}async function $r(t,e,r){let s=xe(r.PALBASE_CONTRACT_ENTRY??process.argv[1]??"");if(!/\.[cm]?tsx?$/.test(s))throw new Error(`the contract is read from the app's TypeScript source, and this run's entry is ${s||"none"}: start it from its source (bun run src/main.ts), or name the source's entry in PALBASE_CONTRACT_ENTRY`);let n=k(s);for(;!G(z(n,"package.json"))&&k(n)!==n;)n=k(n);let{analyzeProject:a}=await import("../chunks/O2LHK2GF.js"),{routeContracts:i}=await import("../chunks/YIFQY4BF.js"),o=a(n,s);for(let u of o.warnings)d.warn(`[palbase] the contract: ${u}`);let c="https://contract.palbase.invalid",l=$({modules:t,verifier:new B({issuer:c,projectId:"contract",standing:()=>Promise.reject(new Error("the contract run serves nothing"))}),server:_({url:c,secretKey:"pb_contract_s"}),env:r,projectId:"contract",auth:e.auth,tokens:e.tokens,rateLimit:e.rateLimit,maxBodyBytes:e.bodyLimit,cors:e.cors,contractOnly:{database:e.db!==void 0,routes:await i(o.routes),errors:re()},events:e.db&&D(U(e.db))?{"user.deleted":[]}:void 0});return JSON.stringify(l.contract())}var O=class extends Error{constructor(){super("[palbase] the contract run ended"),this.name="ContractRunEnded"}},j=class extends Error{code;constructor(e){super(`[palbase] the migration run ended with ${e}`),this.name="MigrationRunEnded",this.code=e}};async function Ir(t,e){let r=e.data?.user_id;if(typeof r!="string"||r==="")throw new Error("[palbase] user.deleted without a user_id");let s=await t.forget(r);d.info(`[palbase] user ${r} deleted: ${s.deleted} row(s) gone, ${s.detached} forgot them`)}async function Lr(t,e,r,s,n,a){let i,o={on:!1},c=(m,p)=>new URL(m.url).pathname===Br&&m.method==="GET"?Promise.resolve(o.on?Response.json({ok:!1,stopping:!0},{status:503}):Response.json({ok:!0})):t.handle(m,p),l=Rr((m,p)=>{Ur(c,m,p,o).finally(()=>{o.on&&l.closeIdleConnections()})});l.keepAliveTimeout=29e4,l.headersTimeout=3e5;try{await new Promise((m,p)=>{l.once("error",p),l.listen(r,s,()=>m())})}catch(m){throw await t.stop(),await a?.close(),m}let u=l.address().port;d.info(`[palbase] serving ${t.routes.length} route(s) on :${u}`,{routes:t.routes}),a?.search?.start();let h=m=>i??=(async()=>{d.info("[palbase] stopping: finishing the requests in flight"),o.on=!0;let p=new Promise(T=>l.close(()=>T()));l.closeIdleConnections();let C=setTimeout(()=>l.closeAllConnections(),m);await p,clearTimeout(C),process.off("SIGINT",y),process.off("uncaughtException",S),process.off("unhandledRejection",S);try{await t.stop(),await a?.search?.stop(),await a?.close()}finally{process.off("SIGTERM",y)}})(),f=()=>h(ke),g=!1,y=()=>{if(g){d.info("[palbase] stopping: told to stop again; the requests in flight are still being finished");return}g=!0;let m=setTimeout(()=>{d.error("[palbase] stopping took longer than it is given; the process ends"),process.exit(1)},ke+Cr);m.unref(),f().then(()=>{clearTimeout(m),process.exit(0)},p=>{clearTimeout(m),d.error("[palbase] stopping failed; the process ends",{error:p}),process.exit(1)})},S=m=>{d.error("[palbase] the app crashed; stopping so the machine starts it again",{error:m});let p=setTimeout(()=>process.exit(1),Ee+1e3);h(Ee).finally(()=>{clearTimeout(p),process.exit(1)})};return process.on("SIGTERM",y),process.once("SIGINT",y),n&&(process.on("uncaughtException",S),process.on("unhandledRejection",S)),{routes:t.routes,palbase:e,port:u,handle:c,close:f}}async function Ur(t,e,r,s){try{let n=e.url??"/",a;try{if(!n.startsWith("/"))throw new TypeError("the request target is not a path");a=new URL(`http://localhost${n}`)}catch{r.statusCode=400,r.end();return}let i=new Headers;for(let[h,f]of Object.entries(e.headers))if(f!==void 0)if(Array.isArray(f))for(let g of f)i.append(h,g);else i.set(h,f);let o=e.method!=="GET"&&e.method!=="HEAD",c=new AbortController;r.on("close",()=>{r.writableFinished||c.abort(new Error("the client closed the connection"))});let l=new Request(a,{method:e.method,headers:i,body:o?Or.toWeb(e):void 0,duplex:"half",signal:c.signal}),u=await t(l,{remoteAddress:e.socket.remoteAddress});if(r.statusCode=u.status,u.headers.forEach((h,f)=>r.setHeader(f,h)),s.on&&r.setHeader("connection","close"),u.body)for await(let h of u.body)r.write(h);r.end()}catch(n){d.error("[palbase] the request could not be answered",{error:n}),r.headersSent||(r.statusCode=500),r.end()}}function Dr(t,e,r=s=>console.warn(s)){let s=(e??"").split(",").map(o=>o.trim()).filter(o=>o!=="");if(s.length===0||t?.origins==="*")return t;let n=s.filter(o=>V(o)),a=s.filter(o=>!V(o));a.length>0&&r(`[palbase] the project's web origins ${a.map(o=>JSON.stringify(o)).join(", ")} are not CORS origins (https://host[:port], http only for localhost): browsers there are not let in`);let i=[...new Set([...t?.origins??[],...n])];return i.length===0?t:{...t,origins:i}}import{bigint as Ys,boolean as Js,check as Qs,date as Xs,defineSchema as Zs,defineTable as en,enumType as tn,foreignKey as rn,index as sn,integer as nn,jsonb as an,numeric as on,ownedByUser as ln,policy as cn,raw as dn,sqlType as un,text as pn,timestamp as hn,userRef as fn,uuid as gn}from"palgres/dsl";import{increment as mn,now as yn}from"palgres";function E(t){if(t instanceof A)return{data:null,error:{code:t.code,message:t.message},status:t.status};throw t}async function P(t,e){try{let r=await t();return{data:await e(r.data),error:null,status:r.status}}catch(r){return E(r)}}var jr=x("Secrets",{async get(t){if(Y(t))return null;let e=process.env[t];return typeof e=="string"&&e!==""?e:null}}),Nr=100,qr=1e3,Wr=168*3600,Kr={s:1,m:60,h:3600,d:86400};function Vr(t){let e=String(t).trim();if(!/^(\d+(\.\d+)?[dhms])+$/.test(e))return;let r=0;for(let[,s,,n]of e.matchAll(/(\d+(\.\d+)?)([dhms])/g))r+=Math.round(Number(s)*Kr[n]*1e3);return Math.ceil(r/1e3)}function $e(t,e,r){let s="getPublicUrl",n;try{n=String(e).split("/").map(i=>K(s,"path",i)).join("%2F")}catch(i){throw i instanceof A&&i.code==="invalid_path_parameter"?new A({op:s,status:0,code:"invalid_path_parameter",message:`${s}: the object path ${JSON.stringify(e)} has an empty, "." or ".." segment: storage keeps no such object`}):i}let a=`${b.url}/storage/public/${K(s,"bucket",t)}/${n}`;return r?`${a}?variant=${encodeURIComponent(r)}`:a}function Re(t){return{path:t.path,name:t.path,bucket:t.bucket,size:t.size,contentType:t.content_type,checksum:t.checksum_sha256,...t.width!==void 0?{width:t.width}:{},...t.height!==void 0?{height:t.height}:{},...t.thumbhash!==void 0?{thumbhash:t.thumbhash}:{},variants:Object.fromEntries(Object.keys(t.variants??{}).map(e=>[e,$e(t.bucket,t.path,e)]))}}function Gr(t){return{async upload(e,r,s){let n=s?.contentType??(r instanceof Blob&&r.type!==""?r.type:void 0);try{let a=await b.storage.putObject({path:{bucket:t,path:e},headers:s?.upsert?void 0:{"If-None-Match":"*"},body:r,contentType:n});return{data:Re(a.data),error:null,status:a.status}}catch(a){return a instanceof A&&a.status===412&&a.code==="object_exists"?{data:null,error:{code:"already_exists",message:"An object already exists at that path: upload with { upsert: true } to replace it"},status:409}:E(a)}},async download(e){try{let r=await b.storage.getObject({path:{bucket:t,path:e}});if(r.status===304)throw new Error("storage answered 304 to a read that sent no entity tag");let s=r.data;try{return{data:await s.blob(),error:null,status:r.status}}catch(n){return{data:null,error:{code:"network_error",message:`the object's bytes stopped arriving: ${n instanceof Error?n.message:String(n)}`},status:0}}}catch(r){return E(r)}},getPublicUrl(e,r){return $e(t,e,r?.variant)},async createSignedUrl(e,r){let s=Vr(r?.expiresIn);return s===void 0||s<1||s>Wr?{data:null,error:{code:"bad_request",message:`expiresIn is a duration from 1s to 7d, like "15m", "1h" or "7d" (got ${JSON.stringify(r?.expiresIn)})`},status:400}:P(()=>b.storage.createSignedUrl({path:{bucket:t},body:{path:e,expires_in:s}}),n=>({signedUrl:n.url,expiresAt:n.expires_at}))},async list(e,r){let s=r?.limit??Nr,n=r?.offset??0;if(!Number.isInteger(s)||s<0||!Number.isInteger(n)||n<0)return{data:null,error:{code:"bad_request",message:"limit and offset are whole numbers, 0 or more"},status:400};let a=[],i,o=200;try{for(;a.length<s;){let c=Math.max(1,Math.min(qr,n+s-a.length)),l=await b.storage.listObjects({path:{bucket:t},query:{...e?{prefix:e}:{},limit:c,...i?{cursor:i}:{}}});o=l.status;for(let u of l.data.objects)n>0?n--:a.length<s&&a.push(Re(u));if(i=l.data.next_cursor,!i)break}}catch(c){return E(c)}return{data:a,error:null,status:o}},async remove(e){let r=[];for(let s of e){try{await b.storage.deleteObject({path:{bucket:t,path:s}})}catch(n){return E(n)}r.push({path:s,name:s,bucket:t,size:0,contentType:"",checksum:"",variants:{}})}return{data:r,error:null,status:200}},move(e,r){return P(()=>b.storage.moveObject({path:{bucket:t},body:{from:e,to:r}}),()=>{})},copy(e,r){return P(()=>b.storage.copyObject({path:{bucket:t},body:{from:e,to:r}}),()=>{})}}}var zr={bucket:Gr},Oe=t=>ee("Storage",t,zr),Hr={bucket:t=>Oe("bucket").bucket(t),buckets:new Proxy({},{get:(t,e)=>typeof e=="string"?Oe("buckets").bucket(e):void 0})},Yr=x("Notifications",{push:{send(t){let{to:e,...r}=t,s=typeof e=="string"?{user_ids:[e]}:Array.isArray(e)?{user_ids:e}:{topic:e.topic};return P(()=>b.notify.sendPush({body:{...r,to:s}}),n=>({message_ids:n.message_ids,recipients:n.message_ids.length,skipped_user_ids:n.skipped_user_ids}))}},email:{async send(t){let{to:e,templateSlug:r,...s}=t,n={...s,...r!==void 0?{template:r}:{}};if(!Array.isArray(e))return P(()=>b.notify.sendEmail({body:{...n,to:e}}),o=>({...o.message_id!==void 0?{message_id:o.message_id}:{},...o.skipped?{skipped:!0}:{}}));let a=[],i=202;for(let o of e)try{let c=await b.notify.sendEmail({body:{...n,to:o}});i=c.status,a.push(c.data.message_id??null)}catch(c){return E(c)}return{data:{message_ids:a},error:null,status:i}}}}),Ce=t=>typeof t=="boolean"?t:t!=null&&t!==0&&t!=="",Be=t=>typeof t=="string"?{name:t}:null,Fe=t=>t==="override"?"user":t,Jr=t=>t!==null&&typeof t=="object"&&!Array.isArray(t)&&"userId"in t;function Ie(){return te.getStore()?.userId}function N(t){let e=t&&"userId"in t?t.userId??void 0:Ie();return P(()=>e?b.flags.getUserValues({path:{user_id:e}}):b.flags.getValues(),r=>r.values??{})}var Me={setOverrideForUser:(t,e,r)=>P(()=>b.flags.putUserValue({path:{user_id:t,key:e},body:{value:r}}),s=>({key:s.key,value:s.value,source:Fe(s.source)})),setOverridesForUser:(t,e)=>P(()=>b.flags.putUserValues({path:{user_id:t},body:{values:e}}),r=>({values:r.values??{}})),clearOverrideForUser:(t,e)=>P(()=>b.flags.deleteUserValue({path:{user_id:t,key:e}}),r=>({key:r.key,value:r.value,source:Fe(r.source)})),clearAllOverridesForUser:t=>P(()=>b.flags.deleteUserValues({path:{user_id:t}}),e=>({deleted:e.deleted})),batchSetOverrides:t=>P(()=>b.flags.batchUserValues({body:{operations:t.map(e=>({user_id:e.userId,values:e.values}))}}),e=>({applied:e.applied}))},Qr=x("Flags",{async isEnabled(t,e){let r=s=>(d.warn(`[palbase] flag "${t}" could not be read (${s}): treating it as off`),!1);try{let s=await N(e);return s.error?r(`${s.error.code}: ${s.error.message}`):Ce(s.data[t])}catch(s){return r(s instanceof Error?s.message:String(s))}},async getVariant(t,e){let r=await N(e);return r.error?{data:null,error:r.error,status:r.status}:{data:Be(r.data[t]),error:null,status:r.status}},async getAll(t){let e=await N(t);return e.error?{data:null,error:e.error,status:e.status}:{data:Object.entries(e.data).map(([r,s])=>{let n=Be(s);return{name:r,enabled:Ce(s),...n?{variant:n}:{}}}),error:null,status:e.status}},async get(t,e,r){let s,n=!1,a;r!==void 0?(s=e,n=!0,a=r):Jr(e)?a=e:e!==void 0&&(s=e,n=!0);let i=await N(a);if(i.error)return n?{data:s??null,error:null,status:i.status}:{data:null,error:i.error,status:i.status};let o=i.data[t];return{data:o===void 0?s??null:o,error:null,status:i.status}},async setOverride(t,e){let r=Ie();return r?Me.setOverrideForUser(r,t,e):{data:null,error:{code:"no_user",message:"Flags.setOverride writes the signed-in user's value: this request has none \u2014 Flags.$asService().setOverrideForUser(userId, key, value) writes anyone's"},status:400}},$asService(){return Me}}),Xr=x("Realtime",{broadcast(t,e,r){return P(()=>b.realtime.broadcast({body:{messages:[{topic:t,event:e,payload:r??{}}]}}),()=>{})},state:{set(t,e,r){return P(()=>b.realtime.writeState({body:{ops:[{topic:t,key:e,value:r}]}}),()=>{})},clear(t,e){return P(()=>b.realtime.writeState({body:{ops:[{topic:t,key:e,delete:!0}]}}),()=>{})}}});import{z as Tn}from"zod";export{je as AuthUnavailable,vt as Authorize,Mt as BadRequest,He as Body,Gt as CACHE_MAX_TTL,zt as Cache,wt as ChatPart,st as Client,$t as Conflict,O as ContractRunEnded,Ne as Controller,lt as Cron,pt as Database,It as DeadlockDetected,Ge as Delete,Rt as DiError,Ue as EVENT_TYPES,Qr as Flags,Bt as Forbidden,St as Gateway,Pt as GatewayRefusal,qe as Get,Je as Headers,Lt as HttpError,at as Injectable,d as Log,Vt as MAX_BODY_BYTES,j as MigrationRunEnded,ot as Module,Ut as NotFound,Yr as Notifications,it as On,kt as OnConnect,Et as OnDisconnect,Tt as OnEmpty,At as OnFirst,Ze as OptionalUser,Ot as PalError,b as Palbase,A as PalbaseError,Mr as PalbaseFactory,Qe as Param,Ve as Patch,We as Post,Ke as Put,ze as Query,Ye as QueryParams,Xr as Realtime,et as Req,tt as RequestId,nt as Resolve,L as SchemaNotPushed,jr as Secrets,Dt as SerializationFailure,Hr as Storage,_t as Subscribe,ft as Task,ht as TaskFailure,gt as Tasks,bt as TestUserTemplate,De as TokenError,B as TokenVerifier,jt as TooManyRequests,rt as TraceId,Ct as Unauthorized,Nt as UniqueViolation,mt as Upload,yt as UploadedObject,Xe as User,ct as Webhook,Ys as bigint,Js as boolean,Qs as check,$ as createApp,Xs as date,Ft as defineError,Zs as defineSchema,en as defineTable,Wt as encrypt,qt as encrypted,tn as enumType,rn as foreignKey,dt as getRegisteredControllers,ut as getRoutes,xt as getWebhookManifest,mn as increment,sn as index,nn as integer,an as jsonb,yn as now,on as numeric,ln as ownedByUser,cn as policy,dn as raw,un as sqlType,Kt as t,pn as text,hn as timestamp,fn as userRef,gn as uuid,Tn as z};
12
+ `),process.exit(0),new O}let i=Te(s),o=await _e(i);o&&d.info(`[palbase] strings: ${o.source} and ${o.locales.length-1} other language(s), ${Object.keys(o.strings).length} sentence(s), from ${i}/palbase/strings`),se(o?void 0:i);let c=e.db?U(e.db):void 0,l=await J({env:s,url:e.palbase?.url,secretKey:e.palbase?.secretKey});l&&d.info(`[palbase] secrets: ${l.loaded.length} from the project's ${l.set} set${l.kept.length>0?`; ${l.kept.join(", ")} kept as the environment gives them`:""}`),l&&l.refused.length>0&&d.warn(`[palbase] secrets not set \u2014 names a process reads as its own, not the app's: ${l.refused.map(w=>JSON.stringify(w)).join(", ")}`);let u=Fr(r)||c!==void 0&&D(c),h=Pe(e.palbase??{},s,{needsWebhookSecret:u});u&&h.webhookSecret===void 0&&d.warn("[palbase] events: none is delivered here \u2014 the platform delivers them to the app's machine, not to this computer; its @On handlers (and forgetting a deleted user's rows) run there. Set PALBASE_WEBHOOK_SECRET to take a delivery forwarded here");let f=_({url:h.url,secretKey:h.secretKey}),g=e.port??Number(s.PORT??"8080");if(!Number.isInteger(g)||g<0||g>65535)throw new Error(`[palbase] PORT is a port number, not ${String(e.port??s.PORT)}`);let y=e.db?await ye(e.db,s,h.secretKey,{onPlatform:h.platformSecret!==void 0,embed:we(f),fields:f.fields}):void 0;y&&d.info(`[palbase] database: version ${y.binding.version}`);let S=y&&D(y.model)?{"user.deleted":[w=>Ir(y,w)]}:void 0,m=h.platformSecret===void 0?void 0:{secret:h.platformSecret},p=e.requestTelemetry===!1?void 0:new I(f.analytics),C=()=>$({modules:r,verifier:new B({issuer:h.url,projectId:h.projectId,standing:H({url:h.url,secretKey:h.secretKey})}),server:f,webhookSecret:h.webhookSecret,env:s,projectId:h.projectId,telemetry:p,auth:e.auth,tokens:e.tokens,rateLimit:e.rateLimit,maxBodyBytes:e.bodyLimit,cors:Dr(e.cors,s.PALBASE_WEB_ORIGINS),platform:m,events:S,database:y&&{app:y.app,requests:y.requests,keptAnswers:y.keptAnswers},strings:o}),T=C(),q=e.boot?.attempts??5,W=e.boot?.backoffMs??1e3;for(let w=1;;w++)try{await T.start();break}catch(v){if(w>=q)throw d.error(`[palbase] the app did not start after ${q} attempts`,{error:v}),v;d.warn(`[palbase] the app did not start (attempt ${w} of ${q}); trying again in ${W} ms`,{error:v}),await new Promise(Le=>setTimeout(Le,W)),W*=2,T=C()}return Lr(T,f,g,e.host??"0.0.0.0",e.exitOnFatal??!0,y)}};function Te(t){let e=t.PALBASE_CONTRACT_ENTRY??process.argv[1];if(!e)return process.cwd();let r=k(xe(e));for(;!G(z(r,"package.json"))&&k(r)!==r;)r=k(r);return G(z(r,"package.json"))?r:process.cwd()}async function _e(t){try{return await ne(t)}catch(e){throw new Error(`[palbase] the app's strings: ${e instanceof Error?e.message:String(e)}`)}}async function $r(t,e,r){let s=xe(r.PALBASE_CONTRACT_ENTRY??process.argv[1]??"");if(!/\.[cm]?tsx?$/.test(s))throw new Error(`the contract is read from the app's TypeScript source, and this run's entry is ${s||"none"}: start it from its source (bun run src/main.ts), or name the source's entry in PALBASE_CONTRACT_ENTRY`);let n=k(s);for(;!G(z(n,"package.json"))&&k(n)!==n;)n=k(n);let{analyzeProject:a}=await import("../chunks/A46IASZE.js"),{routeContracts:i}=await import("../chunks/427AGWP3.js"),o=a(n,s);for(let u of o.warnings)d.warn(`[palbase] the contract: ${u}`);let c="https://contract.palbase.invalid",l=$({modules:t,verifier:new B({issuer:c,projectId:"contract",standing:()=>Promise.reject(new Error("the contract run serves nothing"))}),server:_({url:c,secretKey:"pb_contract_s"}),env:r,projectId:"contract",auth:e.auth,tokens:e.tokens,rateLimit:e.rateLimit,maxBodyBytes:e.bodyLimit,cors:e.cors,contractOnly:{database:e.db!==void 0,routes:await i(o.routes),errors:re()},events:e.db&&D(U(e.db))?{"user.deleted":[]}:void 0});return JSON.stringify(l.contract())}var O=class extends Error{constructor(){super("[palbase] the contract run ended"),this.name="ContractRunEnded"}},j=class extends Error{code;constructor(e){super(`[palbase] the migration run ended with ${e}`),this.name="MigrationRunEnded",this.code=e}};async function Ir(t,e){let r=e.data?.user_id;if(typeof r!="string"||r==="")throw new Error("[palbase] user.deleted without a user_id");let s=await t.forget(r);d.info(`[palbase] user ${r} deleted: ${s.deleted} row(s) gone, ${s.detached} forgot them`)}async function Lr(t,e,r,s,n,a){let i,o={on:!1},c=(m,p)=>new URL(m.url).pathname===Br&&m.method==="GET"?Promise.resolve(o.on?Response.json({ok:!1,stopping:!0},{status:503}):Response.json({ok:!0})):t.handle(m,p),l=Rr((m,p)=>{Ur(c,m,p,o).finally(()=>{o.on&&l.closeIdleConnections()})});l.keepAliveTimeout=29e4,l.headersTimeout=3e5;try{await new Promise((m,p)=>{l.once("error",p),l.listen(r,s,()=>m())})}catch(m){throw await t.stop(),await a?.close(),m}let u=l.address().port;d.info(`[palbase] serving ${t.routes.length} route(s) on :${u}`,{routes:t.routes}),a?.search?.start();let h=m=>i??=(async()=>{d.info("[palbase] stopping: finishing the requests in flight"),o.on=!0;let p=new Promise(T=>l.close(()=>T()));l.closeIdleConnections();let C=setTimeout(()=>l.closeAllConnections(),m);await p,clearTimeout(C),process.off("SIGINT",y),process.off("uncaughtException",S),process.off("unhandledRejection",S);try{await t.stop(),await a?.search?.stop(),await a?.close()}finally{process.off("SIGTERM",y)}})(),f=()=>h(ke),g=!1,y=()=>{if(g){d.info("[palbase] stopping: told to stop again; the requests in flight are still being finished");return}g=!0;let m=setTimeout(()=>{d.error("[palbase] stopping took longer than it is given; the process ends"),process.exit(1)},ke+Cr);m.unref(),f().then(()=>{clearTimeout(m),process.exit(0)},p=>{clearTimeout(m),d.error("[palbase] stopping failed; the process ends",{error:p}),process.exit(1)})},S=m=>{d.error("[palbase] the app crashed; stopping so the machine starts it again",{error:m});let p=setTimeout(()=>process.exit(1),Ee+1e3);h(Ee).finally(()=>{clearTimeout(p),process.exit(1)})};return process.on("SIGTERM",y),process.once("SIGINT",y),n&&(process.on("uncaughtException",S),process.on("unhandledRejection",S)),{routes:t.routes,palbase:e,port:u,handle:c,close:f}}async function Ur(t,e,r,s){try{let n=e.url??"/",a;try{if(!n.startsWith("/"))throw new TypeError("the request target is not a path");a=new URL(`http://localhost${n}`)}catch{r.statusCode=400,r.end();return}let i=new Headers;for(let[h,f]of Object.entries(e.headers))if(f!==void 0)if(Array.isArray(f))for(let g of f)i.append(h,g);else i.set(h,f);let o=e.method!=="GET"&&e.method!=="HEAD",c=new AbortController;r.on("close",()=>{r.writableFinished||c.abort(new Error("the client closed the connection"))});let l=new Request(a,{method:e.method,headers:i,body:o?Or.toWeb(e):void 0,duplex:"half",signal:c.signal}),u=await t(l,{remoteAddress:e.socket.remoteAddress});if(r.statusCode=u.status,u.headers.forEach((h,f)=>r.setHeader(f,h)),s.on&&r.setHeader("connection","close"),u.body)for await(let h of u.body)r.write(h);r.end()}catch(n){d.error("[palbase] the request could not be answered",{error:n}),r.headersSent||(r.statusCode=500),r.end()}}function Dr(t,e,r=s=>console.warn(s)){let s=(e??"").split(",").map(o=>o.trim()).filter(o=>o!=="");if(s.length===0||t?.origins==="*")return t;let n=s.filter(o=>V(o)),a=s.filter(o=>!V(o));a.length>0&&r(`[palbase] the project's web origins ${a.map(o=>JSON.stringify(o)).join(", ")} are not CORS origins (https://host[:port], http only for localhost): browsers there are not let in`);let i=[...new Set([...t?.origins??[],...n])];return i.length===0?t:{...t,origins:i}}import{bigint as Ys,boolean as Js,check as Qs,date as Xs,defineSchema as Zs,defineTable as en,enumType as tn,foreignKey as rn,index as sn,integer as nn,jsonb as an,numeric as on,ownedByUser as ln,policy as cn,raw as dn,sqlType as un,text as pn,timestamp as hn,userRef as fn,uuid as gn}from"palgres/dsl";import{increment as mn,now as yn}from"palgres";function E(t){if(t instanceof A)return{data:null,error:{code:t.code,message:t.message},status:t.status};throw t}async function P(t,e){try{let r=await t();return{data:await e(r.data),error:null,status:r.status}}catch(r){return E(r)}}var jr=x("Secrets",{async get(t){if(Y(t))return null;let e=process.env[t];return typeof e=="string"&&e!==""?e:null}}),Nr=100,qr=1e3,Wr=168*3600,Kr={s:1,m:60,h:3600,d:86400};function Vr(t){let e=String(t).trim();if(!/^(\d+(\.\d+)?[dhms])+$/.test(e))return;let r=0;for(let[,s,,n]of e.matchAll(/(\d+(\.\d+)?)([dhms])/g))r+=Math.round(Number(s)*Kr[n]*1e3);return Math.ceil(r/1e3)}function $e(t,e,r){let s="getPublicUrl",n;try{n=String(e).split("/").map(i=>K(s,"path",i)).join("%2F")}catch(i){throw i instanceof A&&i.code==="invalid_path_parameter"?new A({op:s,status:0,code:"invalid_path_parameter",message:`${s}: the object path ${JSON.stringify(e)} has an empty, "." or ".." segment: storage keeps no such object`}):i}let a=`${b.url}/storage/public/${K(s,"bucket",t)}/${n}`;return r?`${a}?variant=${encodeURIComponent(r)}`:a}function Re(t){return{path:t.path,name:t.path,bucket:t.bucket,size:t.size,contentType:t.content_type,checksum:t.checksum_sha256,...t.width!==void 0?{width:t.width}:{},...t.height!==void 0?{height:t.height}:{},...t.thumbhash!==void 0?{thumbhash:t.thumbhash}:{},variants:Object.fromEntries(Object.keys(t.variants??{}).map(e=>[e,$e(t.bucket,t.path,e)]))}}function Gr(t){return{async upload(e,r,s){let n=s?.contentType??(r instanceof Blob&&r.type!==""?r.type:void 0);try{let a=await b.storage.putObject({path:{bucket:t,path:e},headers:s?.upsert?void 0:{"If-None-Match":"*"},body:r,contentType:n});return{data:Re(a.data),error:null,status:a.status}}catch(a){return a instanceof A&&a.status===412&&a.code==="object_exists"?{data:null,error:{code:"already_exists",message:"An object already exists at that path: upload with { upsert: true } to replace it"},status:409}:E(a)}},async download(e){try{let r=await b.storage.getObject({path:{bucket:t,path:e}});if(r.status===304)throw new Error("storage answered 304 to a read that sent no entity tag");let s=r.data;try{return{data:await s.blob(),error:null,status:r.status}}catch(n){return{data:null,error:{code:"network_error",message:`the object's bytes stopped arriving: ${n instanceof Error?n.message:String(n)}`},status:0}}}catch(r){return E(r)}},getPublicUrl(e,r){return $e(t,e,r?.variant)},async createSignedUrl(e,r){let s=Vr(r?.expiresIn);return s===void 0||s<1||s>Wr?{data:null,error:{code:"bad_request",message:`expiresIn is a duration from 1s to 7d, like "15m", "1h" or "7d" (got ${JSON.stringify(r?.expiresIn)})`},status:400}:P(()=>b.storage.createSignedUrl({path:{bucket:t},body:{path:e,expires_in:s}}),n=>({signedUrl:n.url,expiresAt:n.expires_at}))},async list(e,r){let s=r?.limit??Nr,n=r?.offset??0;if(!Number.isInteger(s)||s<0||!Number.isInteger(n)||n<0)return{data:null,error:{code:"bad_request",message:"limit and offset are whole numbers, 0 or more"},status:400};let a=[],i,o=200;try{for(;a.length<s;){let c=Math.max(1,Math.min(qr,n+s-a.length)),l=await b.storage.listObjects({path:{bucket:t},query:{...e?{prefix:e}:{},limit:c,...i?{cursor:i}:{}}});o=l.status;for(let u of l.data.objects)n>0?n--:a.length<s&&a.push(Re(u));if(i=l.data.next_cursor,!i)break}}catch(c){return E(c)}return{data:a,error:null,status:o}},async remove(e){let r=[];for(let s of e){try{await b.storage.deleteObject({path:{bucket:t,path:s}})}catch(n){return E(n)}r.push({path:s,name:s,bucket:t,size:0,contentType:"",checksum:"",variants:{}})}return{data:r,error:null,status:200}},move(e,r){return P(()=>b.storage.moveObject({path:{bucket:t},body:{from:e,to:r}}),()=>{})},copy(e,r){return P(()=>b.storage.copyObject({path:{bucket:t},body:{from:e,to:r}}),()=>{})}}}var zr={bucket:Gr},Oe=t=>ee("Storage",t,zr),Hr={bucket:t=>Oe("bucket").bucket(t),buckets:new Proxy({},{get:(t,e)=>typeof e=="string"?Oe("buckets").bucket(e):void 0})},Yr=x("Notifications",{push:{send(t){let{to:e,...r}=t,s=typeof e=="string"?{user_ids:[e]}:Array.isArray(e)?{user_ids:e}:{topic:e.topic};return P(()=>b.notify.sendPush({body:{...r,to:s}}),n=>({message_ids:n.message_ids,recipients:n.message_ids.length,skipped_user_ids:n.skipped_user_ids}))}},email:{async send(t){let{to:e,templateSlug:r,...s}=t,n={...s,...r!==void 0?{template:r}:{}};if(!Array.isArray(e))return P(()=>b.notify.sendEmail({body:{...n,to:e}}),o=>({...o.message_id!==void 0?{message_id:o.message_id}:{},...o.skipped?{skipped:!0}:{}}));let a=[],i=202;for(let o of e)try{let c=await b.notify.sendEmail({body:{...n,to:o}});i=c.status,a.push(c.data.message_id??null)}catch(c){return E(c)}return{data:{message_ids:a},error:null,status:i}}}}),Ce=t=>typeof t=="boolean"?t:t!=null&&t!==0&&t!=="",Be=t=>typeof t=="string"?{name:t}:null,Fe=t=>t==="override"?"user":t,Jr=t=>t!==null&&typeof t=="object"&&!Array.isArray(t)&&"userId"in t;function Ie(){return te.getStore()?.userId}function N(t){let e=t&&"userId"in t?t.userId??void 0:Ie();return P(()=>e?b.flags.getUserValues({path:{user_id:e}}):b.flags.getValues(),r=>r.values??{})}var Me={setOverrideForUser:(t,e,r)=>P(()=>b.flags.putUserValue({path:{user_id:t,key:e},body:{value:r}}),s=>({key:s.key,value:s.value,source:Fe(s.source)})),setOverridesForUser:(t,e)=>P(()=>b.flags.putUserValues({path:{user_id:t},body:{values:e}}),r=>({values:r.values??{}})),clearOverrideForUser:(t,e)=>P(()=>b.flags.deleteUserValue({path:{user_id:t,key:e}}),r=>({key:r.key,value:r.value,source:Fe(r.source)})),clearAllOverridesForUser:t=>P(()=>b.flags.deleteUserValues({path:{user_id:t}}),e=>({deleted:e.deleted})),batchSetOverrides:t=>P(()=>b.flags.batchUserValues({body:{operations:t.map(e=>({user_id:e.userId,values:e.values}))}}),e=>({applied:e.applied}))},Qr=x("Flags",{async isEnabled(t,e){let r=s=>(d.warn(`[palbase] flag "${t}" could not be read (${s}): treating it as off`),!1);try{let s=await N(e);return s.error?r(`${s.error.code}: ${s.error.message}`):Ce(s.data[t])}catch(s){return r(s instanceof Error?s.message:String(s))}},async getVariant(t,e){let r=await N(e);return r.error?{data:null,error:r.error,status:r.status}:{data:Be(r.data[t]),error:null,status:r.status}},async getAll(t){let e=await N(t);return e.error?{data:null,error:e.error,status:e.status}:{data:Object.entries(e.data).map(([r,s])=>{let n=Be(s);return{name:r,enabled:Ce(s),...n?{variant:n}:{}}}),error:null,status:e.status}},async get(t,e,r){let s,n=!1,a;r!==void 0?(s=e,n=!0,a=r):Jr(e)?a=e:e!==void 0&&(s=e,n=!0);let i=await N(a);if(i.error)return n?{data:s??null,error:null,status:i.status}:{data:null,error:i.error,status:i.status};let o=i.data[t];return{data:o===void 0?s??null:o,error:null,status:i.status}},async setOverride(t,e){let r=Ie();return r?Me.setOverrideForUser(r,t,e):{data:null,error:{code:"no_user",message:"Flags.setOverride writes the signed-in user's value: this request has none \u2014 Flags.$asService().setOverrideForUser(userId, key, value) writes anyone's"},status:400}},$asService(){return Me}}),Xr=x("Realtime",{broadcast(t,e,r){return P(()=>b.realtime.broadcast({body:{messages:[{topic:t,event:e,payload:r??{}}]}}),()=>{})},state:{set(t,e,r){return P(()=>b.realtime.writeState({body:{ops:[{topic:t,key:e,value:r}]}}),()=>{})},clear(t,e){return P(()=>b.realtime.writeState({body:{ops:[{topic:t,key:e,delete:!0}]}}),()=>{})}}});import{z as Tn}from"zod";export{je as AuthUnavailable,vt as Authorize,Mt as BadRequest,He as Body,Gt as CACHE_MAX_TTL,zt as Cache,wt as ChatPart,st as Client,$t as Conflict,O as ContractRunEnded,Ne as Controller,lt as Cron,pt as Database,It as DeadlockDetected,Ge as Delete,Rt as DiError,Ue as EVENT_TYPES,Qr as Flags,Bt as Forbidden,St as Gateway,Pt as GatewayRefusal,qe as Get,Je as Headers,Lt as HttpError,at as Injectable,d as Log,Vt as MAX_BODY_BYTES,j as MigrationRunEnded,ot as Module,Ut as NotFound,Yr as Notifications,it as On,kt as OnConnect,Et as OnDisconnect,Tt as OnEmpty,At as OnFirst,Ze as OptionalUser,Ot as PalError,b as Palbase,A as PalbaseError,Mr as PalbaseFactory,Qe as Param,Ve as Patch,We as Post,Ke as Put,ze as Query,Ye as QueryParams,Xr as Realtime,et as Req,tt as RequestId,nt as Resolve,L as SchemaNotPushed,jr as Secrets,Dt as SerializationFailure,Hr as Storage,_t as Subscribe,ft as Task,ht as TaskFailure,gt as Tasks,bt as TestUserTemplate,De as TokenError,B as TokenVerifier,jt as TooManyRequests,rt as TraceId,Ct as Unauthorized,Nt as UniqueViolation,mt as Upload,yt as UploadedObject,Xe as User,ct as Webhook,Ys as bigint,Js as boolean,Qs as check,$ as createApp,Xs as date,Ft as defineError,Zs as defineSchema,en as defineTable,Wt as encrypt,qt as encrypted,tn as enumType,rn as foreignKey,dt as getRegisteredControllers,ut as getRoutes,xt as getWebhookManifest,mn as increment,sn as index,nn as integer,an as jsonb,yn as now,on as numeric,ln as ownedByUser,cn as policy,dn as raw,un as sqlType,Kt as t,pn as text,hn as timestamp,fn as userRef,gn as uuid,Tn as z};
@@ -1 +1 @@
1
- /*! palbase 0.14.1 — Palbase SDK License (see LICENSE) */
1
+ /*! palbase 0.14.2 — Palbase SDK License (see LICENSE) */
@@ -1,2 +1,2 @@
1
- /*! palbase 0.14.1 — Palbase SDK License (see LICENSE) */
2
- import{a as u}from"../chunks/IXOQ6JI5.js";import{c as p,i as c}from"../chunks/S6HM2J7J.js";import{b as l,c as g,d as f,e as y}from"../chunks/KLEVI5C3.js";import"../chunks/7UQMB3JW.js";import"../chunks/LND5DXD3.js";import"../chunks/VLNIDQ36.js";import"../chunks/3CUWIZU2.js";import"../chunks/GHEORI3H.js";import"../chunks/URK5PA2R.js";import"../chunks/RBDGMOJT.js";import"../chunks/2PCIM4VH.js";import"../chunks/FZB357V4.js";import"reflect-metadata";import{randomUUID as m}from"node:crypto";import{createFakeClient as w,typedDatabase as d}from"palgres/testing";function T(t,n,a){if(a?.acceptLanguage!==void 0&&a.strings===void 0)throw new TypeError("withServices: acceptLanguage chooses among the languages of a strings table, and none was given \u2014 { strings: await loadStringsTable(appRoot), acceptLanguage }");let{Database:r,...o}=t,e=a?.strings;return p.run({requestId:`test_${m()}`,database:r===void 0?void 0:d(r),services:o,...e!==void 0?{strings:e,locales:c(a?.acceptLanguage??null,e.source),usedLocales:[]}:{}},n)}function b(){let t=new Map,n=new Map,a=[],r=e=>{if(t.has(e))return t.get(e);if(n.has(e))return n.get(e);if(a.includes(e)){let s=[...a.slice(a.indexOf(e)),e].map(i=>i.name??String(i));throw new TypeError(`isolated(): ${s.join(" \u2192 ")} needs itself to be built \u2014 give one of them with .with(Token, value)`)}a.push(e);try{let s=Reflect.getMetadata("design:paramtypes",e)??[],i=new e(...s.map(r));return n.set(e,i),i}finally{a.pop()}},o={with(e,s){return t.set(e,s),o},get:e=>r(e)};return o}function h(){let t=w();return{db:d(t),raw:t,queries:t.queries,seed:(n,a)=>t.seed(n,a),inserted:n=>t.inserted(n),updated:n=>t.updated(n),deleted:n=>t.deleted(n)}}export{l as TestApiError,y as api,g as createTestApi,h as fakeDatabase,b as isolated,u as loadStringsTable,f as testRun,T as withServices};
1
+ /*! palbase 0.14.2 — Palbase SDK License (see LICENSE) */
2
+ import{a as u}from"../chunks/DIOZGDFQ.js";import{c as p,i as c}from"../chunks/SBUC7GHR.js";import{b as l,c as g,d as f,e as y}from"../chunks/WXNFMEW7.js";import"../chunks/HHZSOYPP.js";import"../chunks/BRHGS5AI.js";import"../chunks/3AENUHVO.js";import"../chunks/44ULNVPP.js";import"../chunks/OMK2YEDZ.js";import"../chunks/RD5JFDGQ.js";import"../chunks/JKWWY2LJ.js";import"../chunks/P67I4TNQ.js";import"../chunks/6NC5RYCS.js";import"reflect-metadata";import{randomUUID as m}from"node:crypto";import{createFakeClient as w,typedDatabase as d}from"palgres/testing";function T(t,n,a){if(a?.acceptLanguage!==void 0&&a.strings===void 0)throw new TypeError("withServices: acceptLanguage chooses among the languages of a strings table, and none was given \u2014 { strings: await loadStringsTable(appRoot), acceptLanguage }");let{Database:r,...o}=t,e=a?.strings;return p.run({requestId:`test_${m()}`,database:r===void 0?void 0:d(r),services:o,...e!==void 0?{strings:e,locales:c(a?.acceptLanguage??null,e.source),usedLocales:[]}:{}},n)}function b(){let t=new Map,n=new Map,a=[],r=e=>{if(t.has(e))return t.get(e);if(n.has(e))return n.get(e);if(a.includes(e)){let s=[...a.slice(a.indexOf(e)),e].map(i=>i.name??String(i));throw new TypeError(`isolated(): ${s.join(" \u2192 ")} needs itself to be built \u2014 give one of them with .with(Token, value)`)}a.push(e);try{let s=Reflect.getMetadata("design:paramtypes",e)??[],i=new e(...s.map(r));return n.set(e,i),i}finally{a.pop()}},o={with(e,s){return t.set(e,s),o},get:e=>r(e)};return o}function h(){let t=w();return{db:d(t),raw:t,queries:t.queries,seed:(n,a)=>t.seed(n,a),inserted:n=>t.inserted(n),updated:n=>t.updated(n),deleted:n=>t.deleted(n)}}export{l as TestApiError,y as api,g as createTestApi,h as fakeDatabase,b as isolated,u as loadStringsTable,f as testRun,T as withServices};
@@ -1,2 +1,2 @@
1
- /*! palbase 0.14.1 — Palbase SDK License (see LICENSE) */
2
- import{a as d,b as u}from"./RBDGMOJT.js";var p={too_many_chats:()=>"this user is in as many chats as they may be (100): delete or leave one before starting another",too_many_endpoints:()=>"the project holds as many tool endpoints as it may (32): delete one (ai.endpoints.delete) before putting another",too_many_messages:t=>`this user has sent as many messages this minute as the project allows${t.retryAfter!==void 0?`: write again in ${t.retryAfter} s`:""}`,history_full:()=>"the project keeps as much chat history as it may: delete chats to write again",not_your_turn:()=>"this turn is another member's: only the member who started it (or the project's server) answers its tools and decides its approvals",not_a_member:()=>"the member the server acts as (as) is not in this chat: put them in it first (chats.members.put), or act as the server",goal_lapsed:()=>"the goal was set as a member who no longer stands where they stood then (out of the chat, or the chat no longer theirs alone): it is not resumed \u2014 clear it, or set another for the chat as it is now",goal_achieved:()=>"the goal is achieved: set a new one (chats.goal.set) to work on",turn_running:()=>"the chat's agent is at work on a turn: fork it once the turn has ended, or stop it first (chats.stop)",fork_too_large:()=>"what came before that message is more than a fork begins with (512 KiB): fork it before an earlier message",too_many_voices:t=>`this user has started as many voices this hour as the project allows (5)${t.retryAfter!==void 0?`: start again in ${t.retryAfter} s`:""}`,voice_active:()=>"another member's voice is live in this chat \u2014 one voice talks in a chat at a time: wait for it to end",not_your_voice:()=>"this voice is another member's: only its member \u2014 or the server as itself \u2014 reads, tells and closes it",voice_closed:()=>"the voice has ended: start a new one (chats.voice.start)",no_workspace:()=>"this chat works in no workspace, and files go into one: start the chat with a workspace, or send pictures as images",attachment_not_found:()=>"a picture or a file given is not one its writer may attach: a file of the project's storage \u2014 for a member, their own or a public bucket's",attachment_too_large:()=>"an attachment is past its bound: 5 MiB a picture, 15 MiB a file",attachment_changed:()=>"a file changed while it was being attached: send the message again",unsupported_image:()=>"a picture is not png, jpeg, webp or gif by its bytes: send it as a file",image_not_found:()=>"a picture given is not a file of the project's storage: upload it first (storage.from(bucket).upload(path, file)) and give that bucket and path",storage_unavailable:t=>`the project's storage did not answer when the model was to read a picture${t.retryAfter!==void 0?`: try again in ${t.retryAfter} s`:"; try again shortly"}`,draft_changed:()=>"the agent's draft was saved again since its revision was read: read it again (ai.agents.get) and make the change on that one",agent_defined_in_code:()=>"this agent is the backend's code's (its build's contract names it): it is changed in the code, and has no draft, versions or delete",nothing_to_publish:()=>"the agent's draft is the version published already: save a change to it first (ai.agents.saveDraft)",agent_not_published:()=>"the agent has no version published yet: publish its draft (ai.agents.publish) before a chat or an answer names it"},g=new WeakSet;function c(t){if(!(t instanceof u)||g.has(t))return t;let r=p[t.code];if(!r)return t;let s=new u({op:t.op,status:t.status,code:t.code,message:`${r(t)} (${t.op}: ${t.status} ${t.code})`,requestId:t.requestId,retryAfter:t.retryAfter,body:t.body,cause:t});return g.add(s),s}function m(t){return t.catch(r=>{throw c(r)})}function _(t){if(typeof t!="object"||t===null)return;let r=t,s=r.data;if(typeof r.type!="string"||typeof s!="object"||s===null||Array.isArray(s))return;let e=d(s),i=typeof r.id=="number"&&Number.isSafeInteger(r.id)?r.id:0;switch(r.type){case"message":return typeof e.client_id=="string"?{type:"message",seq:i,message:e}:void 0;case"turn":{if(typeof e.response_id!="string"||typeof e.status!="string")return;let n={...e,type:"turn",seq:i};return n.waiting??=null,n.error??=null,n}case"text":{let n=e.offset;return typeof e.response_id!="string"||typeof n!="number"||!Number.isInteger(n)||n<0?void 0:{type:"text",response_id:e.response_id,offset:n,text:typeof e.text=="string"?e.text:""}}case"reset":{let n=e.offset;return typeof e.response_id!="string"||typeof n!="number"||!Number.isInteger(n)||n<0?void 0:{type:"reset",response_id:e.response_id,offset:n}}case"tool":{if(typeof e.call_id!="string"||typeof e.response_id!="string")return;let n=e.omitted_bytes;return{...e,type:"tool",seq:i,omittedBytes:typeof n=="number"&&Number.isSafeInteger(n)&&n>0?n:0,outputTruncated:e.output_truncated===!0}}case"agent":return typeof e.parent_response_id=="string"?{...e,type:"agent",seq:i}:void 0;case"thinking":{if(typeof e.response_id!="string")return;let n=typeof e.run_id=="string"?e.run_id:"";return e.unavailable===!0?{type:"thinking",seq:i,response_id:e.response_id,run_id:n,text:"",unavailable:!0,model:typeof e.model=="string"?e.model:"",reason:typeof e.reason=="string"?e.reason:""}:typeof e.text!="string"?void 0:{type:"thinking",seq:i,response_id:e.response_id,run_id:n,...typeof e.step_id=="string"&&e.step_id!==""?{step_id:e.step_id}:{},text:e.text}}case"goal":{if(typeof e.goal_id!="string"||typeof e.kind!="string")return;let{seq:n,...o}=e;return{...o,type:"goal",seq:i,...typeof n=="number"?{turn:n}:{}}}case"history":{if(!Array.isArray(e.items)||typeof e.part!="number"||!Number.isInteger(e.part)||e.part<0)return;let n=e.items.filter(a=>typeof a=="object"&&a!==null&&(a.role==="user"||a.role==="assistant")&&typeof a.text=="string"),o=e.forked_from;return{type:"history",forked_from:o&&typeof o.chat_id=="string"?o:null,part:e.part,parts:typeof e.parts=="number"?e.parts:e.part+1,items:n}}case"voice":return typeof e.voice_id!="string"||e.voice_id===""||typeof e.status!="string"?void 0:{...e,type:"voice",seq:i,user_id:typeof e.user_id=="string"?e.user_id:null};case"transcript":return typeof e.id!="string"||e.id===""||typeof e.text!="string"?void 0:{type:"transcript",seq:i,id:e.id,voice_id:typeof e.voice_id=="string"?e.voice_id:"",role:typeof e.role=="string"?e.role:"",user_id:typeof e.user_id=="string"?e.user_id:null,author_name:typeof e.author_name=="string"?e.author_name:"",text:e.text,final:e.final!==!1,created_at:typeof e.created_at=="string"?e.created_at:""};default:return}}function b(t){let r=0;for(let s=0;s<t.length;s++){let e=t.charCodeAt(s);e<128?r+=1:e<2048?r+=2:e>=55296&&e<=56319&&s+1<t.length&&(t.charCodeAt(s+1)&64512)===56320?(r+=4,s++):r+=3}return r}function l(t,r){if(r<=0)return 0;let s=0;for(let e=0;e<t.length;e++){let i=t.charCodeAt(e),n=3,o=1;if(i<128?n=1:i<2048?n=2:i>=55296&&i<=56319&&e+1<t.length&&(t.charCodeAt(e+1)&64512)===56320&&(n=4,o=2),s+=n,s>=r)return e+o;e+=o-1}return t.length}function v(t,r){return t.slice(l(t,r))}export{m as a,_ as b,b as c,l as d,v as e};
1
+ /*! palbase 0.14.2 — Palbase SDK License (see LICENSE) */
2
+ import{a as d,b as u}from"./JKWWY2LJ.js";var p={too_many_chats:()=>"this user is in as many chats as they may be (100): delete or leave one before starting another",too_many_endpoints:()=>"the project holds as many tool endpoints as it may (32): delete one (ai.endpoints.delete) before putting another",too_many_messages:t=>`this user has sent as many messages this minute as the project allows${t.retryAfter!==void 0?`: write again in ${t.retryAfter} s`:""}`,history_full:()=>"the project keeps as much chat history as it may: delete chats to write again",not_your_turn:()=>"this turn is another member's: only the member who started it (or the project's server) answers its tools and decides its approvals",not_a_member:()=>"the member the server acts as (as) is not in this chat: put them in it first (chats.members.put), or act as the server",goal_lapsed:()=>"the goal was set as a member who no longer stands where they stood then (out of the chat, or the chat no longer theirs alone): it is not resumed \u2014 clear it, or set another for the chat as it is now",goal_achieved:()=>"the goal is achieved: set a new one (chats.goal.set) to work on",turn_running:()=>"the chat's agent is at work on a turn: fork it once the turn has ended, or stop it first (chats.stop)",fork_too_large:()=>"what came before that message is more than a fork begins with (512 KiB): fork it before an earlier message",too_many_voices:t=>`this user has started as many voices this hour as the project allows (5)${t.retryAfter!==void 0?`: start again in ${t.retryAfter} s`:""}`,voice_active:()=>"another member's voice is live in this chat \u2014 one voice talks in a chat at a time: wait for it to end",not_your_voice:()=>"this voice is another member's: only its member \u2014 or the server as itself \u2014 reads, tells and closes it",voice_closed:()=>"the voice has ended: start a new one (chats.voice.start)",no_workspace:()=>"this chat works in no workspace, and files go into one: start the chat with a workspace, or send pictures as images",attachment_not_found:()=>"a picture or a file given is not one its writer may attach: a file of the project's storage \u2014 for a member, their own or a public bucket's",attachment_too_large:()=>"an attachment is past its bound: 5 MiB a picture, 15 MiB a file",attachment_changed:()=>"a file changed while it was being attached: send the message again",unsupported_image:()=>"a picture is not png, jpeg, webp or gif by its bytes: send it as a file",image_not_found:()=>"a picture given is not a file of the project's storage: upload it first (storage.from(bucket).upload(path, file)) and give that bucket and path",storage_unavailable:t=>`the project's storage did not answer when the model was to read a picture${t.retryAfter!==void 0?`: try again in ${t.retryAfter} s`:"; try again shortly"}`,draft_changed:()=>"the agent's draft was saved again since its revision was read: read it again (ai.agents.get) and make the change on that one",agent_defined_in_code:()=>"this agent is the backend's code's (its build's contract names it): it is changed in the code, and has no draft, versions or delete",nothing_to_publish:()=>"the agent's draft is the version published already: save a change to it first (ai.agents.saveDraft)",agent_not_published:()=>"the agent has no version published yet: publish its draft (ai.agents.publish) before a chat or an answer names it"},g=new WeakSet;function c(t){if(!(t instanceof u)||g.has(t))return t;let r=p[t.code];if(!r)return t;let s=new u({op:t.op,status:t.status,code:t.code,message:`${r(t)} (${t.op}: ${t.status} ${t.code})`,requestId:t.requestId,retryAfter:t.retryAfter,body:t.body,cause:t});return g.add(s),s}function m(t){return t.catch(r=>{throw c(r)})}function _(t){if(typeof t!="object"||t===null)return;let r=t,s=r.data;if(typeof r.type!="string"||typeof s!="object"||s===null||Array.isArray(s))return;let e=d(s),i=typeof r.id=="number"&&Number.isSafeInteger(r.id)?r.id:0;switch(r.type){case"message":return typeof e.client_id=="string"?{type:"message",seq:i,message:e}:void 0;case"turn":{if(typeof e.response_id!="string"||typeof e.status!="string")return;let n={...e,type:"turn",seq:i};return n.waiting??=null,n.error??=null,n}case"text":{let n=e.offset;return typeof e.response_id!="string"||typeof n!="number"||!Number.isInteger(n)||n<0?void 0:{type:"text",response_id:e.response_id,offset:n,text:typeof e.text=="string"?e.text:""}}case"reset":{let n=e.offset;return typeof e.response_id!="string"||typeof n!="number"||!Number.isInteger(n)||n<0?void 0:{type:"reset",response_id:e.response_id,offset:n}}case"tool":{if(typeof e.call_id!="string"||typeof e.response_id!="string")return;let n=e.omitted_bytes;return{...e,type:"tool",seq:i,omittedBytes:typeof n=="number"&&Number.isSafeInteger(n)&&n>0?n:0,outputTruncated:e.output_truncated===!0}}case"agent":return typeof e.parent_response_id=="string"?{...e,type:"agent",seq:i}:void 0;case"thinking":{if(typeof e.response_id!="string")return;let n=typeof e.run_id=="string"?e.run_id:"";return e.unavailable===!0?{type:"thinking",seq:i,response_id:e.response_id,run_id:n,text:"",unavailable:!0,model:typeof e.model=="string"?e.model:"",reason:typeof e.reason=="string"?e.reason:""}:typeof e.text!="string"?void 0:{type:"thinking",seq:i,response_id:e.response_id,run_id:n,...typeof e.step_id=="string"&&e.step_id!==""?{step_id:e.step_id}:{},text:e.text}}case"goal":{if(typeof e.goal_id!="string"||typeof e.kind!="string")return;let{seq:n,...o}=e;return{...o,type:"goal",seq:i,...typeof n=="number"?{turn:n}:{}}}case"history":{if(!Array.isArray(e.items)||typeof e.part!="number"||!Number.isInteger(e.part)||e.part<0)return;let n=e.items.filter(a=>typeof a=="object"&&a!==null&&(a.role==="user"||a.role==="assistant")&&typeof a.text=="string"),o=e.forked_from;return{type:"history",forked_from:o&&typeof o.chat_id=="string"?o:null,part:e.part,parts:typeof e.parts=="number"?e.parts:e.part+1,items:n}}case"voice":return typeof e.voice_id!="string"||e.voice_id===""||typeof e.status!="string"?void 0:{...e,type:"voice",seq:i,user_id:typeof e.user_id=="string"?e.user_id:null};case"transcript":return typeof e.id!="string"||e.id===""||typeof e.text!="string"?void 0:{type:"transcript",seq:i,id:e.id,voice_id:typeof e.voice_id=="string"?e.voice_id:"",role:typeof e.role=="string"?e.role:"",user_id:typeof e.user_id=="string"?e.user_id:null,author_name:typeof e.author_name=="string"?e.author_name:"",text:e.text,final:e.final!==!1,created_at:typeof e.created_at=="string"?e.created_at:""};default:return}}function b(t){let r=0;for(let s=0;s<t.length;s++){let e=t.charCodeAt(s);e<128?r+=1:e<2048?r+=2:e>=55296&&e<=56319&&s+1<t.length&&(t.charCodeAt(s+1)&64512)===56320?(r+=4,s++):r+=3}return r}function l(t,r){if(r<=0)return 0;let s=0;for(let e=0;e<t.length;e++){let i=t.charCodeAt(e),n=3,o=1;if(i<128?n=1:i<2048?n=2:i>=55296&&i<=56319&&e+1<t.length&&(t.charCodeAt(e+1)&64512)===56320&&(n=4,o=2),s+=n,s>=r)return e+o;e+=o-1}return t.length}function v(t,r){return t.slice(l(t,r))}export{m as a,_ as b,b as c,l as d,v as e};
@@ -1,2 +1,2 @@
1
- /*! palbase 0.14.1 — Palbase SDK License (see LICENSE) */
2
- import{a as s,f as a,g as i}from"./2CR3IN7R.js";import"./UXURIXBA.js";import"./FZB357V4.js";import{pathToFileURL as m}from"node:url";import{z as u}from"zod";async function w(e){let t=new Map,n=new Map;for(let r of e){let d=`${r.className}.${r.method}`,o=n.get(r.className);if(o!==void 0&&o!==r.file)throw new Error(`two controllers are named ${r.className} (${o}, ${r.file}): the contract tells routes apart by their class's name \u2014 rename one`);n.set(r.className,r.file),t.set(d,{returns:await h(r),throws:r.throws})}return r=>t.get(`${r.controller.name}.${r.fn}`)}async function h(e){let t=`${e.file} \u2014 ${e.className}.${e.method}`;switch(e.returns.kind){case"void":return{kind:"void"};case"raw":return{kind:"raw"};case"schema":{let r=(await import(m(e.returns.file).href))[e.returns.exportName];if(!c(r))throw new Error(`${t}: its return type names ${e.returns.exportName}, which ${e.returns.file} exports as no schema (a zod, valibot or arktype schema)`);if(i(a(r)))throw new Error(`${t}: ${e.returns.exportName} marks an encrypted field (encrypted()) \u2014 an answer's is encrypt(value) in what the handler returns, its type Encrypted<T>, which the contract reads`);return{kind:"json",schema:r,array:e.returns.array}}case"expression":{let n=new Function("z","encrypted",`return (${e.returns.expression});`)(u,s);if(!c(n))throw new Error(`${t}: the schema made of its return type is not one`);return{kind:"json",schema:n,array:!1}}}}function c(e){return typeof e=="object"&&e!==null&&typeof e["~standard"]?.validate=="function"}export{w as routeContracts};
1
+ /*! palbase 0.14.2 — Palbase SDK License (see LICENSE) */
2
+ import{a as s,f as a,g as i}from"./CUL5OL4P.js";import"./ZZNGA77G.js";import"./6NC5RYCS.js";import{pathToFileURL as m}from"node:url";import{z as u}from"zod";async function w(e){let t=new Map,n=new Map;for(let r of e){let d=`${r.className}.${r.method}`,o=n.get(r.className);if(o!==void 0&&o!==r.file)throw new Error(`two controllers are named ${r.className} (${o}, ${r.file}): the contract tells routes apart by their class's name \u2014 rename one`);n.set(r.className,r.file),t.set(d,{returns:await h(r),throws:r.throws})}return r=>t.get(`${r.controller.name}.${r.fn}`)}async function h(e){let t=`${e.file} \u2014 ${e.className}.${e.method}`;switch(e.returns.kind){case"void":return{kind:"void"};case"raw":return{kind:"raw"};case"schema":{let r=(await import(m(e.returns.file).href))[e.returns.exportName];if(!c(r))throw new Error(`${t}: its return type names ${e.returns.exportName}, which ${e.returns.file} exports as no schema (a zod, valibot or arktype schema)`);if(i(a(r)))throw new Error(`${t}: ${e.returns.exportName} marks an encrypted field (encrypted()) \u2014 an answer's is encrypt(value) in what the handler returns, its type Encrypted<T>, which the contract reads`);return{kind:"json",schema:r,array:e.returns.array}}case"expression":{let n=new Function("z","encrypted",`return (${e.returns.expression});`)(u,s);if(!c(n))throw new Error(`${t}: the schema made of its return type is not one`);return{kind:"json",schema:n,array:!1}}}}function c(e){return typeof e=="object"&&e!==null&&typeof e["~standard"]?.validate=="function"}export{w as routeContracts};
@@ -1,2 +1,2 @@
1
- /*! palbase 0.14.1 — Palbase SDK License (see LICENSE) */
1
+ /*! palbase 0.14.2 — Palbase SDK License (see LICENSE) */
2
2
  function o(){let n=globalThis;if(typeof n.document<"u"||n.navigator?.product==="ReactNative")return!0;let t=n.navigator?.userAgent;return typeof t=="string"&&t.startsWith("Mozilla/")}export{o as a};
@@ -1,5 +1,5 @@
1
- /*! palbase 0.14.1 — Palbase SDK License (see LICENSE) */
2
- import{e as Re,g as Ae,h as Oe}from"./XCY7TFJH.js";import{h as Ce}from"./VSB66HSU.js";import{a as Ee}from"./YYLNEVUC.js";import{r as xe,t as Pe,u as Te}from"./NVA3C3Z3.js";import{b as V,c as K,e as Se,g as j,h as _e}from"./GHEORI3H.js";import{a as Ie,b as F}from"./URK5PA2R.js";import{b as I,d as U}from"./RBDGMOJT.js";function ht(n){let e=n,t=e?.body,s=t&&typeof t=="object"?t.reason:void 0;return s==="user_deleted"?"userDeleted":s==="user_banned"?"userBanned":e?.code==="session_expired"||e?.code==="token_expired"?"expired":"revoked"}var T=class extends Error{code="session_changed";constructor(e){super(e),this.name="SessionChangedError"}};function Me(){let n=null;return{load:()=>n,save:e=>{n=e},clear:()=>{n=null},shared:!1}}function Ne(n){let e=null,t=!0,s=()=>{try{return globalThis.localStorage}catch{return}};return{shared:!0,load(){try{let i=s()?.getItem(n);return i==null?t?null:e:JSON.parse(i)}catch{return e}},save(i){e=i;try{let r=s();if(!r)throw new Error("no storage");r.setItem(n,JSON.stringify(i)),t=!0}catch{t=!1}},clear(){e=null,t=!0;try{s()?.removeItem(n)}catch{}},watch(i){let r=globalThis;if(typeof r.addEventListener!="function")return()=>{};let a=o=>{(o.key===n||o.key===null)&&i()};return r.addEventListener("storage",a),()=>r.removeEventListener?.("storage",a)}}}function fe(n){try{let e=n.split(".")[1]??"",t=atob(e.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(e.length/4)*4,"=")),s=JSON.parse(t).sub;return typeof s=="string"?s:""}catch{return""}}var pt=6e4,ft=15e3;function gt(n,e,t){let s=n?globalThis.navigator?.locks:void 0;return s?s.request(e,t):t()}var W=class{current=null;loaded;inflight=null;endReason=null;listeners=new Set;store;refresher;isRejected;now;lockName;refreshTimeoutMs;mode;constructor(e,t,s,i={}){this.store=e,this.refresher=t,this.isRejected=s,this.now=i.now??Date.now,this.lockName=i.lockName??"palbase.session.refresh",this.refreshTimeoutMs=i.refreshTimeoutMs??ft,this.mode=i.refresh??"behind",this.loaded=Promise.resolve(e.load()).then(r=>{this.current=r}),e.watch?.(()=>{this.reconcile()})}async session(){return await this.loaded,this.current}snapshot(){return this.current}onChange(e){return this.listeners.add(e),()=>this.listeners.delete(e)}async set(e,t,s){await this.loaded;let i=t==="TOKEN_REFRESHED"?this.current:null,r={accessToken:e.access_token,refreshToken:e.refresh_token,expiresAt:this.now()+e.expires_in*1e3,userId:s?.id??i?.userId??fe(e.access_token),user:s??i?.user};return this.current=r,await this.store.save(r),this.emit(t,r),r}async setUser(e,t){await this.loaded,!(!this.current||!t||this.current.userId!==t.userId)&&(this.current={...this.current,user:e},await this.store.save(this.current),this.emit("USER_UPDATED",this.current))}async clear(e,t){await this.loaded;let s=this.current;this.current=null,this.inflight=null;let i=await this.store.load();(!i||!s||i.userId===s.userId)&&await this.store.clear(),s&&(e==="SESSION_EXPIRED"&&(this.endReason=t??"revoked"),this.emit(e,null))}async accessToken(){await this.loaded;let e=this.current;if(!e)return;let t=e.expiresAt-this.now();if(t>pt)return e.accessToken;if(this.mode==="never")return t>0?e.accessToken:void 0;if(t>0&&this.mode==="behind")return this.refresh().catch(()=>{}),e.accessToken;if(t>0)try{return(await this.refresh()).accessToken}catch(s){if(this.current===e)return e.accessToken;throw s}return(await this.refresh()).accessToken}refresh(){if(this.mode==="never")return Promise.reject(new Error("this client does not renew its session (refresh: 'never'): where the session cannot be written back, the request's middleware renews it"));if(this.inflight)return this.inflight;let e=gt(this.store.shared===!0,this.lockName,async()=>{await this.loaded;let t=this.current;if(!t)throw new T("no session to refresh");let s=await this.adoptStored(t);if(s)return s;try{let i=await this.withTimeout(this.refresher(t.refreshToken));if(this.current?.refreshToken!==t.refreshToken)throw new T("the session changed while it was refreshed");return await this.set(i,"TOKEN_REFRESHED")}catch(i){throw this.isRejected(i)&&this.current?.refreshToken===t.refreshToken&&await this.clear("SESSION_EXPIRED",ht(i)),i}});return this.inflight=e,e.finally(()=>{this.inflight===e&&(this.inflight=null)}).catch(()=>{}),e}async adoptStored(e){let t=await this.store.load();if(!t)throw this.current=null,this.emit("SIGNED_OUT",null),new T("signed out in another tab");if(t.userId!==e.userId)throw this.current=t,this.emit("SIGNED_OUT",null),this.emit("SIGNED_IN",t),new T("another user signed in in another tab");if(t.refreshToken!==e.refreshToken&&t.expiresAt>=e.expiresAt)return this.current=t,this.emit("TOKEN_REFRESHED",t),t}async reconcile(){await this.loaded;let e=this.current,t=await this.store.load();if(!e){t&&(this.current=t,this.emit("SIGNED_IN",t));return}await this.adoptStored(e).catch(()=>{})}withTimeout(e){let t,s=new Promise((i,r)=>{t=setTimeout(()=>r(new Error(`the refresh did not answer within ${this.refreshTimeoutMs/1e3} s`)),this.refreshTimeoutMs)});return Promise.race([e,s]).finally(()=>clearTimeout(t))}emit(e,t){(e==="SIGNED_IN"||e==="SIGNED_OUT")&&(this.endReason=null);for(let s of this.listeners)try{s(e,t)}catch{}}};var ge=class{state="closed";refusal;logSeq;joinRef=null;listeners=new Map;closers=new Set;joinWaiters=[];name;socket;constructor(e,t,s={}){this.name=e,this.socket=t,this.logSeq=s.after}get topic(){return`realtime:${this.name}`}join(){if(this.state==="joined")return Promise.resolve();let e=new Promise((t,s)=>this.joinWaiters.push({resolve:t,reject:s}));return this.state!=="joining"&&this.socket.join(this),e}leave(){this.socket.leave(this)}push(e,t){return this.socket.request(this,e,t)}on(e,t){let s=this.listeners.get(e);return s||this.listeners.set(e,s=new Set),s.add(t),()=>s.delete(t)}onClosed(e){return this.closers.add(e),()=>this.closers.delete(e)}deliver(e,t){e==="broadcast"&&typeof t.seq=="number"&&(this.logSeq=t.seq);for(let s of this.listeners.get(e)??[])try{s(t)}catch{}}settled(e,t){e&&typeof t.log_seq=="number"&&(this.logSeq=t.log_seq),this.state=e?"joined":"refused",this.refusal=e?void 0:t;let s=this.joinWaiters.splice(0);for(let i of s)e?i.resolve():i.reject(new Error(`join ${this.name} refused: ${JSON.stringify(t)}`))}closed(e){this.state="closed",this.joinRef=null;let t=this.joinWaiters.splice(0);for(let s of t)s.reject(new Error(`join ${this.name}: ${e}`));for(let s of[...this.closers])try{s()}catch{}}},B=class{ws=null;opening=null;ref=0;channels=new Map;replies=new Map;heartbeat=null;heartbeatRef=null;reconnectTimer=null;attempts=0;closedByUs=!1;reconnects=0;opts;constructor(e){this.opts=e}channel(e,t){let s=this.channels.get(e);return s||this.channels.set(e,s=new ge(e,this,t)),s}disconnect(){this.closedByUs=!0,this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=null,this.stopHeartbeat();let e=this.ws;this.ws=null,this.opening=null,e?.close(1e3);for(let[,t]of this.replies)t("error",{reason:"socket closed"});this.replies.clear();for(let t of this.channels.values())t.closed("the socket was closed")}async tokenChanged(){if(!this.ws||this.ws.readyState!==1)return;let e=await this.opts.accessToken();if(e)for(let t of this.channels.values())t.state==="joined"&&this.push(t.joinRef,t.topic,"access_token",{access_token:e})}join(e){e.state="joining",this.open().then(()=>this.sendJoin(e)).catch(t=>e.settled(!1,{reason:t instanceof Error?t.message:String(t)}))}leave(e){e.state==="joined"&&this.ws?.readyState===1&&this.push(e.joinRef,e.topic,"phx_leave",{}),e.state="closed",this.channels.delete(e.name)}async request(e,t,s){let i=this.ws;if(this.channels.get(e.name)!==e||e.state!=="joined"||i?.readyState!==1)return{status:"error",response:{reason:"not joined"}};let r=this.nextRef(),a=JSON.stringify([e.joinRef,r,e.topic,t,s]),o=this.awaitReply(r);return i.send(a),o}open(){if(this.ws?.readyState===1)return Promise.resolve();if(this.opening)return this.opening;this.closedByUs=!1;let e=this.opts.webSocket??globalThis.WebSocket,t=`${this.opts.baseUrl.replace(/^http/,"ws")}/realtime/v1/websocket?vsn=2.0.0&apikey=${encodeURIComponent(this.opts.publishableKey)}`,s=new Promise((i,r)=>{let a=new e(t);this.ws=a,a.onopen=()=>{this.attempts=0,this.startHeartbeat(),i()},a.onmessage=o=>this.receive(String(o.data)),a.onerror=()=>r(new Error("the realtime socket could not be opened")),a.onclose=()=>this.dropped(a)});return this.opening=s,s.finally(()=>{this.opening===s&&(this.opening=null)}).catch(()=>{}),s}dropped(e){if(this.ws!==e)return;this.ws=null,this.stopHeartbeat();for(let[,i]of this.replies)i("error",{reason:"socket closed"});this.replies.clear();for(let i of this.channels.values())i.state==="joined"&&(i.state="joining");if(this.closedByUs||![...this.channels.values()].some(i=>i.state==="joining"))return;let t=this.opts.backoff??[500,1e3,2e3,5e3,1e4,3e4],s=t[Math.min(this.attempts,t.length-1)]*(.8+Math.random()*.4);this.attempts++,this.reconnectTimer=J(setTimeout(()=>{this.reconnectTimer=null,this.reconnects++;let i=[...this.channels.values()].filter(r=>r.state==="joining");this.open().then(()=>Promise.all(i.map(r=>this.sendJoin(r)))).catch(()=>{})},s))}async sendJoin(e){let t=await this.opts.accessToken(),s=this.nextRef();e.joinRef=s;let i=this.awaitReply(s),r={broadcast:{self:!1}};e.logSeq!==void 0&&(r.log={after:e.logSeq}),this.push(s,e.topic,"phx_join",{access_token:t,config:r},s);let{status:a,response:o}=await i;if(this.channels.get(e.name)!==e||e.state!=="joining"){a==="ok"&&this.ws?.readyState===1&&this.push(s,e.topic,"phx_leave",{});return}e.settled(a==="ok",o)}awaitReply(e){return new Promise(t=>{let s=J(setTimeout(()=>{this.replies.delete(e),t({status:"timeout",response:{reason:"no reply"}})},this.opts.replyTimeoutMs??1e4));this.replies.set(e,(i,r)=>{clearTimeout(s),this.replies.delete(e),t({status:i,response:r})})})}receive(e){let t;try{t=JSON.parse(e)}catch{return}if(!Array.isArray(t)||t.length!==5||typeof t[2]!="string"||typeof t[3]!="string")return;let[,s,i,r,a]=t,o=typeof a=="object"&&a!==null?a:{};if(r==="phx_reply"&&typeof s=="string"){if(s===this.heartbeatRef){this.heartbeatRef=null;return}this.replies.get(s)?.(String(o.status),o.response??{});return}let c=[...this.channels.values()].find(l=>l.topic===i);if(c){if(r==="phx_close"){c.state="closed";return}if(r==="phx_error"){c.state="joining",J(setTimeout(()=>this.channels.get(c.name)===c&&c.state==="joining"&&this.ws?.readyState===1&&void this.sendJoin(c),1e3));return}c.deliver(r,o)}}push(e,t,s,i,r=this.nextRef()){this.ws?.send(JSON.stringify([e,r,t,s,i]))}nextRef(){return String(++this.ref)}startHeartbeat(){this.stopHeartbeat(),this.heartbeat=J(setInterval(()=>{if(this.heartbeatRef!==null){this.heartbeatRef=null,this.ws?.close(4e3);return}this.heartbeatRef=this.nextRef(),this.push(null,"phoenix","heartbeat",{},this.heartbeatRef)},this.opts.heartbeatMs??25e3))}stopHeartbeat(){this.heartbeat&&clearInterval(this.heartbeat),this.heartbeat=null,this.heartbeatRef=null}};function J(n){return n.unref?.(),n}var A="X-Palbase-Installation-Secret",z="X-Palbase-Installation",De=new WeakMap;function O(n){return De.get(n)}var Ue=new WeakSet;function Ke(n){return Ue.has(n)}var yt=/^[A-Za-z0-9_-]{43}$/,X=class{id;constructor(e){let t=`palbase.installation.secret.${e}`,s;try{let i=Le()?.getItem(t);i&&yt.test(i)&&(s=i)}catch{}if(!s){Ue.add(this),s=je(crypto.getRandomValues(new Uint8Array(32)));try{Le()?.setItem(t,s)}catch{}}De.set(this,s),this.id=mt(s)}};function mt(n){return je(wt(new TextEncoder().encode(n)).subarray(0,16))}function Le(){try{return globalThis.localStorage}catch{return}}function je(n){let e="";for(let t of n)e+=String.fromCharCode(t);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}var vt=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),E=(n,e)=>n>>>e|n<<32-e;function wt(n){let e=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),t=new Uint8Array(Math.ceil((n.length+9)/64)*64);t.set(n),t[n.length]=128;let s=new DataView(t.buffer);s.setUint32(t.length-8,Math.floor(n.length/536870912)),s.setUint32(t.length-4,n.length*8>>>0);let i=new Uint32Array(64);for(let o=0;o<t.length;o+=64){for(let g=0;g<16;g++)i[g]=s.getUint32(o+g*4);for(let g=16;g<64;g++){let m=E(i[g-15],7)^E(i[g-15],18)^i[g-15]>>>3,k=E(i[g-2],17)^E(i[g-2],19)^i[g-2]>>>10;i[g]=i[g-16]+m+i[g-7]+k|0}let[c,l,d,y,f,b,S,u]=e;for(let g=0;g<64;g++){let m=u+(E(f,6)^E(f,11)^E(f,25))+(f&b^~f&S)+vt[g]+i[g]|0,k=(E(c,2)^E(c,13)^E(c,22))+(c&l^c&d^l&d)|0;u=S,S=b,b=f,f=y+m|0,y=d,d=l,l=c,c=m+k|0}e[0]+=c,e[1]+=l,e[2]+=d,e[3]+=y,e[4]+=f,e[5]+=b,e[6]+=S,e[7]+=u}let r=new Uint8Array(32),a=new DataView(r.buffer);for(let o=0;o<8;o++)a.setUint32(o*4,e[o]);return r}var kt=30*6e4,$e=1e3,St=100,_t=60*1024,Y=()=>globalThis.crypto?.randomUUID?globalThis.crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;function D(){try{return globalThis.localStorage}catch{return}}var Q=class{api;closingApi;perfApi;closingPerfApi;flushMs;flushAt;now;anonKey;sessionKey;onceKey;events=[];samples=[];timer;memoryAnon;memorySession;memoryOnce;appVersion;stopAuto;session;consent;identifyPending=!1;listeners=new Set;people={set:e=>this.person({set:e}),setOnce:e=>this.person({set_once:e}),unset:e=>this.person({unset:[...e]}),add:e=>this.person({add:e})};constructor(e,t,s,i,r,a,o={}){this.session=s,this.consent=i;let c={send:d=>e.send(this.granted("analytics")?{...d,headers:{...d.headers,[z]:r.id}}:d)};this.api=V.client(c);let l={send:d=>(this.granted("analytics")?e:t).send(d)};this.perfApi=V.client(l),this.closingApi=V.client({send:d=>c.send({...d,keepalive:!0})}),this.closingPerfApi=V.client({send:d=>l.send({...d,keepalive:!0})}),this.flushMs=o.flushMs??5e3,this.flushAt=o.flushAt??20,this.now=o.now??Date.now,this.anonKey=`palbase.analytics.anonymous.${a}`,this.sessionKey=`palbase.analytics.session.${a}`,this.onceKey=`palbase.analytics.once.${a}`,s.onChange(d=>{d==="SIGNED_IN"?(this.identifyPending=!0,this.soon()):d==="SIGNED_OUT"&&(this.identifyPending=!1,this.reset())}),i.onChange((d,y)=>{y!=="granted"&&(d==="analytics"?(this.events=[],this.identifyPending=!1,this.samples=this.samples.map(ye),this.reset()):d==="performance"&&(this.samples=[]))})}capture(e,t){for(let i of this.listeners)i(e,t);if(!this.granted("analytics"))return;let s=this.now();this.hold({event:e,distinct_id:this.distinctId(),properties:t,timestamp:s,session_id:this.sessionId(s),...this.appVersion?{app_version:this.appVersion}:{}})}captureOnce(e,t,s){if(!this.granted("analytics"))return;let i=this.sessionId(this.now()),r=this.readOnce(),a=r?.session===i?r.keys:[];a.includes(e)||(this.writeOnce({session:i,keys:[...a,e].slice(-500)}),this.capture(t,s))}readOnce(){try{let e=D()?.getItem(this.onceKey);if(e)return JSON.parse(e)}catch{}return this.memoryOnce}writeOnce(e){this.memoryOnce=e;try{D()?.setItem(this.onceKey,JSON.stringify(e))}catch{}}onEvent(e){return this.listeners.add(e),()=>this.listeners.delete(e)}page(e={}){let t=globalThis.location,s=globalThis.document,i=e.url??(t?`${t.origin}${$(t.pathname)}`:"");if(!i)return;let r=e.referrer??Rt(s?.referrer);this.capture("$pageview",{...e.properties,url:i,...e.title??s?.title?{title:e.title??s?.title}:{},...r?{referrer:r}:{}})}async identify(e){this.identifyPending=!1;let t=this.session.snapshot()?.userId;!t||!this.granted("analytics")||(await this.flush(),await this.sendIdentify(this.api,t,e))}async sendIdentify(e,t,s){try{await e.identify({body:{distinct_id:t,anonymous_id:this.anonymousId(),traits:s,timestamp:this.now(),sent_at:this.now()}})}catch{}}reset(){this.memoryAnon=void 0,this.memorySession=void 0,this.memoryOnce=void 0;try{D()?.removeItem(this.anonKey),D()?.removeItem(this.sessionKey),D()?.removeItem(this.onceKey)}catch{}}async flush(e=!1){this.timer&&clearTimeout(this.timer),this.timer=void 0,this.granted("analytics")||(this.events=[]),this.granted("performance")?this.granted("analytics")||(this.samples=this.samples.map(ye)):this.samples=[];let t=e?this.closingApi:this.api,s=e?this.closingPerfApi:this.perfApi,i=this.now(),r=this.session.snapshot()?.userId;for(this.identifyPending&&r&&this.granted("analytics")&&(this.identifyPending=!1,await this.sendIdentify(t,r));this.events.length>0;){let a=this.take(this.events,e);try{await t.batch({body:{events:a.map(o=>({...o,sent_at:i}))}})}catch{}}for(;this.samples.length>0;){let a=this.take(this.samples,e);try{await s.sendPerf({body:{items:a}})}catch{}}}start(e={}){this.stopAuto?.(),this.appVersion=e.appVersion;let t=globalThis;if(typeof t.addEventListener!="function"||typeof globalThis.document>"u")return()=>{};let s=[];e.pageViews!==!1&&s.push(this.watchPages(t)),e.webVitals!==!1&&s.push(Pt((a,o)=>this.sample("web_vital",a,o))),e.network!==!1&&s.push(this.watchFetch(t));let i=()=>{document.visibilityState==="hidden"&&this.flush(!0)},r=()=>{this.flush(!0)};return document.addEventListener("visibilitychange",i),t.addEventListener("pagehide",r),s.push(()=>{document.removeEventListener("visibilitychange",i),t.removeEventListener("pagehide",r)}),this.stopAuto=()=>{for(let a of s.splice(0))a();this.stopAuto=void 0},this.stopAuto}granted(e){return this.consent.state(e)==="granted"}async person(e){if(!this.granted("analytics"))return;let t=this.session.snapshot()?.userId,s=this.now();try{await this.api.setPersonProperties({body:{...e,...t?{}:{distinct_id:this.anonymousId()},timestamp:s,sent_at:s}})}catch{}}hold(e){this.events.length>=$e&&this.events.shift(),this.events.push(e),this.soon()}sample(e,t,s,i={}){if(!this.granted("performance"))return;this.samples.length>=$e&&this.samples.shift();let r={row_id:Y(),trace_type:e,name:t,value:Math.max(0,s),timestamp:this.now(),...i};this.samples.push(this.granted("analytics")?{...r,distinct_id:this.distinctId()}:ye(r)),this.soon()}soon(){if(this.events.length+this.samples.length>=this.flushAt){this.flush();return}this.timer||(this.timer=setTimeout(()=>{this.flush()},this.flushMs),this.timer.unref?.())}take(e,t){let s=e.splice(0,St);if(!t)return s;for(;s.length>1&&JSON.stringify(s).length>_t;)e.unshift(s.pop());return s}distinctId(){return this.session.snapshot()?.userId??this.anonymousId()}anonymousId(){let e=D();try{let t=e?.getItem(this.anonKey);if(t)return t;let s=`anon_${Y()}`;if(e?.setItem(this.anonKey,s),e?.getItem(this.anonKey)===s)return s}catch{}return this.memoryAnon??=`anon_${Y()}`,this.memoryAnon}sessionId(e){let t=D(),s=this.memorySession;try{let r=t?.getItem(this.sessionKey);r&&(s=JSON.parse(r))}catch{}let i=s&&e-s.last<kt?{id:s.id,last:e}:{id:`ses_${Y()}`,last:e};this.memorySession=i;try{t?.setItem(this.sessionKey,JSON.stringify(i))}catch{}return i.id}watchPages(e){let t="",s=()=>{let o=`${e.location.origin}${e.location.pathname}`;if(o===t)return;t=o;let c=`${e.location.origin}${$(e.location.pathname)}`;setTimeout(()=>this.page({url:c}),0)},i=e.history,r=i.pushState.bind(i),a=i.replaceState.bind(i);return i.pushState=(...o)=>{r(...o),s()},i.replaceState=(...o)=>{a(...o),s()},e.addEventListener("popstate",s),s(),()=>{i.pushState=r,i.replaceState=a,e.removeEventListener("popstate",s)}}watchFetch(e){let t=e.fetch;if(typeof t!="function")return()=>{};let s=async(i,r)=>{let a=performance.now(),o=i instanceof Request?i:void 0,c=(r?.method??o?.method??"GET").toUpperCase(),l;try{l=new URL(o?.url??String(i),e.location.href)}catch{l=void 0}let d=!!l&&l.pathname.startsWith("/analytics/")||Tt(r?.headers??o?.headers);try{let y=await t(i,r);return l&&!d&&this.sample("network",`${c} ${l.origin}${$(l.pathname)}`,performance.now()-a,{attrs:{status:String(y.status)},...y.headers.get("x-request-id")?{request_id:y.headers.get("x-request-id")}:{}}),y}catch(y){throw l&&!d&&this.sample("network",`${c} ${l.origin}${$(l.pathname)}`,performance.now()-a,{attrs:{status:"0"}}),y}};return e.fetch=s,()=>{e.fetch===s&&(e.fetch=t)}}};function ye(n){let{distinct_id:e,request_id:t,...s}=n;return s}var It=n=>n.entryType==="layout-shift"&&"value"in n&&"hadRecentInput"in n,xt=n=>n.entryType==="event"||n.entryType==="first-input";function Z(n,e){if(!(typeof PerformanceObserver>"u"))try{let t=new PerformanceObserver(s=>e(s.getEntries()));return t.observe({type:n,buffered:!0}),t}catch{return}}function Pt(n){if(typeof document>"u"||typeof performance>"u"||typeof performance.getEntriesByType!="function")return()=>{};let e=0,t=0,s=0,i=[Z("largest-contentful-paint",l=>{for(let d of l)e=Math.max(e,d.startTime)}),Z("layout-shift",l=>{for(let d of l)It(d)&&!d.hadRecentInput&&(t+=d.value)}),Z("event",l=>{for(let d of l)xt(d)&&(s=Math.max(s,d.duration))}),Z("paint",l=>{for(let d of l)d.name==="first-contentful-paint"&&n("FCP",d.startTime)})],r=performance.getEntriesByType("navigation")[0];r&&r.responseStart>0&&n("TTFB",r.responseStart);let a=!1,o=()=>{a||(a=!0,e>0&&n("LCP",e),n("CLS",t),s>0&&n("INP",s))},c=()=>{document.visibilityState==="hidden"&&o()};return document.addEventListener("visibilitychange",c),()=>{o(),document.removeEventListener("visibilitychange",c);for(let l of i)l?.disconnect()}}function Tt(n){if(!n)return!1;try{return new Headers(n).has("next-router-prefetch")}catch{return!1}}var Et=/^[a-z][a-z0-9_-]{0,31}$/;function $(n){return n.split("/").map(e=>{if(e==="")return e;let t=e.split(";",1)[0],s=t.toLowerCase();return Et.test(s)&&(s.match(/\d/g)?.length??0)<=2&&t.slice(1)===s.slice(1)&&s.split(/[-_]/).every(r=>r.length<=16)?s:":id"}).join("/")}function Rt(n){if(!n)return"";try{let e=new URL(n);return`${e.origin}${$(e.pathname)}`}catch{return $(n.split(/[?#]/,1)[0]??"")}}var Ye=/^custom\.[a-z0-9_]{1,48}$/,At=/^[a-z][a-z0-9_]{0,63}$/,qe=n=>At.test(n)||Ye.test(n),Ot=50,Ve=[5e3,3e4,12e4,6e5],Ct=100,te=class{userApi;deviceApi;session;socket;ref;installation;start;textVersion;customKeys;storeKey;now;kept;listeners=new Set;engaged=!1;platformKeys;watch;sending;sendAgain=!1;retryTimer;retries=0;readFor;stale=!1;lastW=0;lastChosen=0;gpc=globalThis.navigator?.globalPrivacyControl===!0;constructor(e){let t=e.options??{};for(let[c,l]of Object.entries(t.start??{})){if(!qe(c))throw new TypeError(`consent.start: ${JSON.stringify(c)} is not a consent key (a platform key, or custom.<name>)`);if(l!=="granted"&&l!=="denied")throw new TypeError(`consent.start.${c} is granted or denied`)}for(let c of t.customKeys??[])if(!Ye.test(c))throw new TypeError(`consent.customKeys: ${JSON.stringify(c)} is not custom.<name> (a-z, 0-9 and _, 48 at most)`);if(t.textVersion!==void 0&&(t.textVersion===""||t.textVersion.length>64))throw new TypeError("consent.textVersion: 1 to 64 characters");this.userApi=e.userApi,this.deviceApi=e.deviceApi,this.session=e.session,this.socket=e.socket,this.ref=e.ref,this.installation=e.installation,this.start={...t.start},this.textVersion=t.textVersion,this.customKeys=[...t.customKeys??[]],this.storeKey=`palbase.consent.${e.origin}.${e.installation.id}`,this.now=e.now??Date.now;let s=this.load(),i=()=>Ke(this.installation)?{}:{unknown:{on:!0,w:this.stamp()}},r={whose:null,install:this.installation.id,choices:{},unsent:[]};typeof s!="object"?this.kept={...r,...s==="unreadable"?{unknown:{on:!0,w:this.stamp()}}:i()}:s.whose==null&&s.install!==void 0&&s.install!==this.installation.id?this.kept={...r,unsent:s.unsent.filter(c=>c.user!==null),...s.keys?{keys:s.keys}:{},...i()}:this.kept=s,e.session.onChange((c,l)=>{this.engaged&&(c==="SIGNED_IN"&&l?this.signedIn(l):(c==="SIGNED_OUT"||c==="SESSION_EXPIRED")&&this.signedOut())});let a=globalThis;typeof a.addEventListener=="function"&&(a.addEventListener("storage",c=>{(c.key===this.storeKey||c.key===null)&&this.reload()}),a.addEventListener("online",()=>{this.engaged&&this.send()}));let o=this.kept;(e.options!==void 0||s!=="empty"&&(o.unknown?.on||o.unsent.length>0||o.link!==void 0||Object.keys(o.choices).length>0))&&this.engage()}async keys(){return this.engage(),[...(await this.platform()).map(t=>({key:t.key,category:t.category,title:{...t.title},description:{...t.description},ads:t.ads})),...this.customKeys.map(t=>({key:t,category:"custom",title:{},description:{},ads:!1}))]}state(e){if(_(this.kept)!==this.holder()||this.gpcRefuses(e))return"denied";let t=Ge(this.kept,e);return t&&t.state!=="unset"?t.state:this.kept.unknown?.on?"denied":this.start[e]}owesRead(){return this.stale||this.kept.unknown?.on===!0||_(this.kept)!==this.holder()||Object.values(this.kept.choices).some(e=>e.provisional)}holder(){let e=this.session.snapshot()?.userId;return e?`user:${e}`:`device:${this.installation.id}`}lastDeniedAt(e){let t=this.kept.choices[e]?.last_denied_at;return t?new Date(t):void 0}set(e,t){this.setMany({[e]:t})}setMany(e){let t=Object.entries(e);for(let[a,o]of t){if(!qe(a))throw new TypeError(`${JSON.stringify(a)} is not a consent key (a platform key, or custom.<name>)`);if(o!=="granted"&&o!=="denied")throw new TypeError(`${a}: a choice is granted or denied`)}if(t.length===0)return;this.engage();let s=this.chosenAt(),i=this.session.snapshot()?.userId??null,r=this.states();for(let[a,o]of t)this.queue({key:a,state:o,source:"app",chosen_at:s,user:i,...this.textVersion!==void 0?{text_version:this.textVersion}:{}});this.commit(r),this.send()}onChange(e){return this.listeners.add(e),()=>this.listeners.delete(e)}async region(){this.engage();let e=await this.subject();if(this.readFor!==e)try{await this.read(e)}catch(t){if(!this.kept.region)throw t}return this.kept.region}async needsAsking(e){this.engage();let t=await this.subject();this.readFor!==t&&await this.read(t).catch(()=>{});let s=e??(await this.keys()).map(c=>c.key),i=await this.platform().catch(()=>this.kept.keys??[]),r=new Set(i.filter(c=>c.ads).map(c=>c.key)),a=this.kept.region?.jurisdiction==="us",o=new Date(this.now());return o.setUTCMonth(o.getUTCMonth()-12),s.filter(c=>{let l=this.kept.choices[c];return a&&r.has(c)&&l?.last_denied_at!==void 0&&Date.parse(l.last_denied_at)>o.getTime()?!1:!l||l.state==="unset"?!0:this.textVersion!==void 0&&l.source==="app"&&l.text_version!==this.textVersion})}engage(){this.engaged||(this.engaged=!0,this.session.session().then(e=>{e&&!this.watch&&this.follow(e),this.send(),this.refuseByGpc()}))}async subject(){return(await this.session.session())?.userId??null}secret(){return{[A]:O(this.installation)}}platform(){return this.platformKeys??=this.deviceApi.listConsentKeys().then(e=>(this.kept={...this.kept,keys:e.data.keys},this.commit(),e.data.keys),e=>{if(this.platformKeys=void 0,this.kept.keys)return this.kept.keys;throw e}),this.platformKeys}async read(e){let s=(await(e===null?this.deviceApi:this.userApi(e)).getConsents({query:{installation_id:this.installation.id},headers:this.secret()})).data;this.adopt(s,e)}adopt(e,t,s=[]){if(this.kept={...this.kept,region:e.region},(this.session.snapshot()?.userId??null)!==t){this.commit();return}let i=this.states(),r={};for(let u of e.choices)r[u.key]={state:u.state,source:u.source,chosen_at:u.chosen_at,...u.text_version!==void 0?{text_version:u.text_version}:{},...u.last_denied_at!==void 0?{last_denied_at:u.last_denied_at}:{}};let a=s.filter(u=>r[u.key]?.state!==u.state||Date.parse(r[u.key]?.chosen_at??"")!==Date.parse(u.chosen_at)).map(u=>C(u.key,u)),c=_(this.kept)===(t===null?`device:${this.installation.id}`:`user:${t}`)?Object.entries(this.kept.choices).filter(([,u])=>u.provisional).map(([u,g])=>C(u,g)):[];if(a.length+c.length>0&&(this.kept={...this.kept,void:M([...this.kept.void??[],...a,...c])}),t===null&&this.kept.resetAt!==void 0)for(let[u,g]of Object.entries(r))Date.parse(g.chosen_at)<this.kept.resetAt&&delete r[u];let l=new Set(Object.entries(r).map(([u,g])=>C(u,g))),d=(this.kept.void??[]).filter(u=>l.has(u));d.length>0&&(this.kept={...this.kept,unvoid:M([...this.kept.unvoid??[],...d])});let y=Ze(this.kept),f;if(_(this.kept)!==(t===null?`device:${this.installation.id}`:`user:${t}`))f=r;else{f={};for(let u of[...new Set([...Object.keys(this.kept.choices),...Object.keys(r)])].sort()){let g=this.kept.choices[u],m=g&&!g.provisional&&!y.has(C(u,g))?g:void 0,k=r[u],R=k&&(!m||Date.parse(k.chosen_at)>=Date.parse(m.chosen_at))?k:m;R&&(f[u]=R)}}for(let u of this.kept.unsent){if(u.user!==null&&u.user!==t||u.user===null&&u.device!==void 0&&u.device!==this.installation.id||u.user===null&&t!==null)continue;let g=f[u.key];g&&Date.parse(g.chosen_at)>Date.parse(u.chosen_at)||(f[u.key]=Fe(u,g))}let{install:b,...S}=this.kept;this.kept={...S,whose:t,...t===null?{install:this.installation.id}:{},choices:f,unknown:{on:!1,w:this.stamp()}},this.readFor=t,this.stale=!1,this.commit(i),this.refuseByGpc()}async refused(e,t,s){let i=t===e&&_(this.kept)===(t===null?`device:${this.installation.id}`:`user:${t}`),r=M([...this.kept.void??[],...s.map(c=>C(c.key,c))]);if(!i){this.kept={...this.kept,void:r},this.commit();return}let a=this.states(),o={...this.kept.choices};for(let c of s){if(this.kept.unsent.some(d=>d.key===c.key&&(d.user===null||d.user===e)&&Date.parse(d.chosen_at)>Date.parse(c.chosen_at)))continue;let l=o[c.key];o[c.key]={state:"denied",source:"app",chosen_at:c.chosen_at,...l?.last_denied_at!==void 0?{last_denied_at:l.last_denied_at}:{},provisional:!0}}this.kept={...this.kept,choices:o,void:r},this.commit(a);try{await this.read(e)}catch{this.stale=!0}}queue(e){let t=e.user===null?{...e,device:this.installation.id}:e,s=_(this.kept)===(t.user===null?`device:${this.installation.id}`:`user:${t.user}`);this.kept={...this.kept,unsent:Qe([...this.kept.unsent,t]),...s?{choices:{...this.kept.choices,[t.key]:Fe(t,this.kept.choices[t.key])}}:{}}}send(){if(this.sendAgain=!0,this.sending)return;let e=(async()=>{for(;this.sendAgain;)this.sendAgain=!1,await this.sendUnsent()||(this.sendAgain=!1)})();this.sending=e,e.finally(()=>{this.sending===e&&(this.sending=void 0)})}async sendUnsent(){this.retryTimer&&clearTimeout(this.retryTimer),this.retryTimer=void 0;let e=null;try{e=await this.subject();let t=await this.sendOf(null,e);if(e!==null&&(this.kept.link===e||t)){let s;try{s=(await this.userApi(e).linkConsents({headers:this.secret(),body:{installation_id:this.installation.id}})).data}catch(i){if(!Be(i))throw i}if(this.kept.link===e){let{link:i,...r}=this.kept;this.kept=r,this.commit()}if(s)this.adopt(s,e);else{let i=this.states();this.kept={...this.kept,unknown:{on:!0,w:this.stamp()}},this.commit(i)}}if(e!==null&&await this.sendOf(e,e),this.owesRead()&&(await this.read(e),this.owesRead()))throw new Error("the choices are not read yet");return this.retries=0,!0}catch(t){return t instanceof T&&(this.session.snapshot()?.userId??null)!==e?(this.sendAgain=!0,!0):(this.retryLater(),!1)}}async sendOf(e,t){let s=!1;for(;;){let i=this.nextGroup(e);if(i.length===0)return s;let r=i[0],a=e===null?this.deviceApi:this.userApi(e),o;try{o=(await a.chooseConsents({headers:this.secret(),body:{installation_id:this.installation.id,...r.source==="gpc"?{source:"gpc"}:{},...r.text_version!==void 0?{text_version:r.text_version}:{},choices:i.map(c=>({key:c.key,state:c.state,chosen_at:c.chosen_at}))}})).data}catch(c){if(!Be(c))throw c;if(i.length>1){this.kept={...this.kept,unsent:this.kept.unsent.map(l=>i.some(d=>Je(d,l))?{...l,alone:!0}:l)},this.commit();continue}}this.kept={...this.kept,unsent:this.kept.unsent.filter(c=>!i.some(l=>Je(l,c))),done:M([...this.kept.done??[],...i.map(se)])},this.commit(),o?(s=!0,e===t&&this.adopt(o,e,i)):await this.refused(t,e,i)}}nextGroup(e){let t=this.kept.unsent.filter(a=>a.user===e&&(e!==null||(a.device??this.installation.id)===this.installation.id)),s=t[0];if(!s)return[];let i=[],r=new Set;if(s.alone)return[s];for(let a of t)if(!r.has(a.key)&&(r.add(a.key),!(a.alone||a.source!==s.source||a.text_version!==s.text_version)&&(i.push(a),i.length===Ot)))break;return i}retryLater(){if(this.retryTimer)return;let e=Ve[Math.min(this.retries,Ve.length-1)];this.retries++,this.retryTimer=setTimeout(()=>{this.retryTimer=void 0,this.send()},e),this.retryTimer.unref?.()}signedIn(e){this.readFor=void 0,this.kept={...this.kept,link:e.userId},this.commit(),this.follow(e),this.send()}signedOut(){this.unfollow(),this.readFor=void 0;let e=this.states(),t=this.chosenAt(),s=new Set([...Object.entries(this.kept.choices).filter(([,o])=>o.state!=="unset").map(([o])=>o),...this.kept.unsent.filter(o=>o.user===null&&(o.device??this.installation.id)===this.installation.id).map(o=>o.key),...Object.keys(this.start),...this.customKeys,...(this.kept.keys??[]).map(o=>o.key)]),i={};for(let[o,c]of Object.entries(this.kept.choices))i[o]={state:"unset",source:"app",chosen_at:t,...c.last_denied_at!==void 0?{last_denied_at:c.last_denied_at}:{}};let r=o=>o.user===null&&(o.device??this.installation.id)===this.installation.id,a=this.kept.unsent.filter(r);this.kept={whose:null,install:this.installation.id,resetAt:Date.parse(t),choices:i,unsent:this.kept.unsent.filter(o=>!r(o)),...this.kept.void?{void:this.kept.void}:{},...this.kept.unvoid?{unvoid:this.kept.unvoid}:{},done:M([...this.kept.done??[],...a.map(se)]),...this.kept.region?{region:this.kept.region}:{},...this.kept.keys?{keys:this.kept.keys}:{},...this.kept.gpc?{gpc:this.kept.gpc}:{},...this.kept.unknown?{unknown:this.kept.unknown}:{}};for(let o of s)this.queue({key:o,state:"unset",source:"app",chosen_at:t,user:null});this.commit(e),this.send(),this.refuseByGpc()}follow(e){this.unfollow();let t=this.socket.channel(`consents:${this.ref}:${e.userId}`),s={userId:e.userId,channel:t,off:()=>{},version:-1},i=[t.on("broadcast",r=>{r.event==="changed"&&this.changed(s,me(r.payload))}),t.on("state_snapshot",r=>this.held(s,me(ze(r.entries)))),t.on("state_diff",r=>this.held(s,me(ze(r.set))))];s.off=()=>i.forEach(r=>r()),this.watch=s,t.join().catch(()=>{})}unfollow(){let e=this.watch;e&&(this.watch=void 0,e.off(),e.channel.leave())}held(e,t){t!==void 0&&this.changed(e,t)}changed(e,t){if(this.watch===e){if(t!==void 0){if(t<=e.version)return;e.version=t}this.read(e.userId).catch(()=>{this.watch===e&&(this.stale=!0,this.retryLater())})}}gpcRefuses(e){if(!this.gpc||!(this.kept.keys??[]).some(r=>r.key===e&&r.ads))return!1;let t=Ge(this.kept,e);if(t?.state==="denied")return!1;let s=this.kept.gpc?.[_(this.kept)],i=s!==void 0&&(this.kept.whose!=null||s>=(this.kept.resetAt??0));return!(t?.state==="granted"&&t.source==="app"&&i&&Date.parse(t.chosen_at)>s)}async refuseByGpc(){if(!this.gpc||_(this.kept)!==this.holder())return;let e;try{e=await this.platform()}catch{return}if(_(this.kept)!==this.holder())return;let t=this.session.snapshot()?.userId??null,s=e.filter(a=>a.ads&&this.gpcRefuses(a.key)&&!this.kept.unsent.some(o=>o.key===a.key&&o.source==="gpc"&&o.user===t));if(s.length===0)return;let i=this.chosenAt(),r=this.states();for(let a of s)this.queue({key:a.key,state:"denied",source:"gpc",chosen_at:i,user:t});this.kept={...this.kept,gpc:{...this.kept.gpc,[_(this.kept)]:Date.parse(i)}},this.commit(r),this.send()}states(){let e=new Map;for(let t of[...Object.keys(this.start),...Object.keys(this.kept.choices)])e.set(t,this.state(t));return e}tell(e){let t=this.states();for(let s of new Set([...e.keys(),...t.keys()])){let i=t.get(s);if(e.get(s)!==i)for(let r of[...this.listeners])try{r(s,i)}catch{}}}load(){let e;try{e=Xe()?.getItem(this.storeKey)}catch{return"unreadable"}if(e==null)return"empty";try{let t=JSON.parse(e);if(Dt(t))return t}catch{}return"unreadable"}reload(){let e=this.load();if(typeof e!="object"){this.write();return}let t=this.states();this.kept=He(e,this.kept,"theirs",this.holder()),_(e)===_(this.kept)&&We(this.kept)!==We(e)&&this.write(),this.tell(t);let s=this.session.snapshot()?.userId??null;this.engaged&&this.kept.unsent.some(i=>i.user!==null&&i.user===s||i.user===null&&(i.device??this.installation.id)===this.installation.id)&&this.retryLater(),this.engaged&&this.refuseByGpc()}commit(e=this.states()){let t=this.load();typeof t=="object"&&(this.kept=He(t,this.kept,"ours",this.holder())),this.write(),this.tell(e)}write(){try{Xe()?.setItem(this.storeKey,JSON.stringify(this.kept))}catch{}}chosenAt(){return this.lastChosen=Math.max(this.now(),this.lastChosen+1),new Date(this.lastChosen).toISOString()}stamp(){let e=this.kept,t=e?Math.max(0,e.unknown?.w??0):0;return this.lastW=Math.max(this.now(),this.lastW+1,t+1),this.lastW}};function Fe(n,e){let t=n.state==="denied"?n.chosen_at:e?.last_denied_at;return{state:n.state,source:n.source,chosen_at:n.chosen_at,...n.text_version!==void 0?{text_version:n.text_version}:{},...t!==void 0?{last_denied_at:t}:{}}}function C(n,e){return`${n}|${e.provisional?"provisional":e.state}|${Date.parse(e.chosen_at)}`}function Ze(n){let e=new Set(n.unvoid??[]);return new Set((n.void??[]).filter(t=>!e.has(t)))}var ee={denied:2,unset:1,granted:0};function Mt(n,e,t,s){let i=e&&!s.has(C(n,e))?e:void 0,r=t&&!s.has(C(n,t))?t:void 0;if(!i||!r)return i??r;let a=Date.parse(i.chosen_at),o=Date.parse(r.chosen_at);return a!==o?a>o?i:r:ee[i.state]!==ee[r.state]?ee[i.state]>ee[r.state]?i:r:i.provisional?r:i}function Nt(n,e){return!n||!e?n??e:e.w>n.w||e.w===n.w&&e.on?e:n}function He(n,e,t,s){let i=M([...n.void??[],...e.void??[]]),r=M([...n.unvoid??[],...e.unvoid??[]]),a=Ze({void:i,unvoid:r}),o={},c,l={...n.gpc};for(let[m,k]of Object.entries(e.gpc??{}))l[m]=Math.max(l[m]??0,k);let d;if(_(n)===_(e)){c=e;for(let m of[...new Set([...Object.keys(n.choices),...Object.keys(e.choices)])].sort()){let k=Mt(m,n.choices[m],e.choices[m],a);k&&(o[m]=k)}d=Nt(n.unknown,e.unknown)}else{c=_(e)===s?e:_(n)===s?n:t==="ours"?e:n;for(let[m,k]of Object.entries(c.choices))a.has(C(m,k))||(o[m]=k);d=c.unknown}let y=M([...n.done??[],...e.done??[]]),f=Qe([...n.unsent,...e.unsent]).filter(m=>!y.includes(se(m))),b=t==="ours"?e:n,S=t==="ours"?n:e,u=b.region??S.region,g=b.keys??S.keys;return{whose:c.whose??null,...c.whose==null&&c.install!==void 0?{install:c.install}:{},...c.whose==null&&(n.resetAt!==void 0||e.resetAt!==void 0)&&_(n)===_(e)?{resetAt:Math.max(n.resetAt??0,e.resetAt??0)}:c.whose==null&&c.resetAt!==void 0?{resetAt:c.resetAt}:{},choices:o,unsent:f,...y.length>0?{done:y}:{},...i.length>0?{void:i}:{},...r.length>0?{unvoid:r}:{},...b.link!==void 0?{link:b.link}:{},...u?{region:u}:{},...Object.keys(l).length>0?{gpc:l}:{},...g?{keys:g}:{},...d?{unknown:d}:{}}}function se(n){return`${n.user??`device:${n.device??""}`}|${n.key}|${n.state}|${n.source}|${n.chosen_at}`}function Ge(n,e){let t=n.choices[e];if(!t||n.whose!=null||n.resetAt===void 0||Date.parse(t.chosen_at)>=n.resetAt)return t}function _(n){return n.whose!=null?`user:${n.whose}`:`device:${n.install??""}`}function M(n){return[...new Set(n)].slice(-Ct)}function We(n){return JSON.stringify(n,(e,t)=>typeof t=="object"&&t!==null&&!Array.isArray(t)?Object.fromEntries(Object.entries(t).sort(([s],[i])=>s.localeCompare(i))):t)}function Qe(n){let e=new Map;for(let t of n){let s=se(t),i=e.get(s);e.set(s,i?i.alone||!t.alone?i:{...i,alone:!0}:t)}return[...e.values()].sort((t,s)=>Date.parse(t.chosen_at)-Date.parse(s.chosen_at))}var Lt=new Set(["granted","denied","unset"]);function Dt(n){if(typeof n!="object"||n===null)return!1;let e=n;if(typeof e.choices!="object"||e.choices===null||Array.isArray(e.choices)||!Array.isArray(e.unsent))return!1;let t=(o,c)=>{if(typeof o!="object"||o===null)return!1;let l=o;return Lt.has(l.state)&&typeof l.chosen_at=="string"&&(!c||typeof l.key=="string")},s=o=>o===void 0||typeof o=="object"&&o!==null&&typeof o.on=="boolean"&&typeof o.w=="number",i=n,r=o=>o===void 0||Array.isArray(o)&&o.every(c=>typeof c=="string"),a=i.whose===void 0||i.whose===null||typeof i.whose=="string";return Object.values(e.choices).every(o=>t(o,!1))&&e.unsent.every(o=>t(o,!0))&&(i.gpc===void 0||typeof i.gpc=="object"&&i.gpc!==null&&Object.values(i.gpc).every(o=>typeof o=="number"))&&s(i.unknown)&&r(i.done)&&r(i.void)&&r(i.unvoid)&&a}function Je(n,e){return n.key===e.key&&n.user===e.user&&n.state===e.state&&n.source===e.source&&n.chosen_at===e.chosen_at}function Be(n){return n instanceof I&&n.status>=400&&n.status<500&&n.status!==401&&n.status!==408&&n.status!==429}function Xe(){try{return globalThis.localStorage}catch{return}}function ze(n){let e=typeof n=="object"&&n!==null?n.version:void 0;return typeof e=="object"&&e!==null?e.v:void 0}function me(n){let e=typeof n=="object"&&n!==null?n.version:void 0;return typeof e=="number"&&Number.isFinite(e)?e:void 0}var Ut=`
1
+ /*! palbase 0.14.2 — Palbase SDK License (see LICENSE) */
2
+ import{e as Re,g as Ae,h as Oe}from"./5H7UNNH6.js";import{h as Ce}from"./7DQ76T2V.js";import{a as Ee}from"./W3OCV3QH.js";import{r as xe,t as Pe,u as Te}from"./PRJZTG2I.js";import{b as V,c as K,e as Se,g as j,h as _e}from"./OMK2YEDZ.js";import{a as Ie,b as F}from"./RD5JFDGQ.js";import{b as I,d as U}from"./JKWWY2LJ.js";function ht(n){let e=n,t=e?.body,s=t&&typeof t=="object"?t.reason:void 0;return s==="user_deleted"?"userDeleted":s==="user_banned"?"userBanned":e?.code==="session_expired"||e?.code==="token_expired"?"expired":"revoked"}var T=class extends Error{code="session_changed";constructor(e){super(e),this.name="SessionChangedError"}};function Me(){let n=null;return{load:()=>n,save:e=>{n=e},clear:()=>{n=null},shared:!1}}function Ne(n){let e=null,t=!0,s=()=>{try{return globalThis.localStorage}catch{return}};return{shared:!0,load(){try{let i=s()?.getItem(n);return i==null?t?null:e:JSON.parse(i)}catch{return e}},save(i){e=i;try{let r=s();if(!r)throw new Error("no storage");r.setItem(n,JSON.stringify(i)),t=!0}catch{t=!1}},clear(){e=null,t=!0;try{s()?.removeItem(n)}catch{}},watch(i){let r=globalThis;if(typeof r.addEventListener!="function")return()=>{};let a=o=>{(o.key===n||o.key===null)&&i()};return r.addEventListener("storage",a),()=>r.removeEventListener?.("storage",a)}}}function fe(n){try{let e=n.split(".")[1]??"",t=atob(e.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(e.length/4)*4,"=")),s=JSON.parse(t).sub;return typeof s=="string"?s:""}catch{return""}}var pt=6e4,ft=15e3;function gt(n,e,t){let s=n?globalThis.navigator?.locks:void 0;return s?s.request(e,t):t()}var W=class{current=null;loaded;inflight=null;endReason=null;listeners=new Set;store;refresher;isRejected;now;lockName;refreshTimeoutMs;mode;constructor(e,t,s,i={}){this.store=e,this.refresher=t,this.isRejected=s,this.now=i.now??Date.now,this.lockName=i.lockName??"palbase.session.refresh",this.refreshTimeoutMs=i.refreshTimeoutMs??ft,this.mode=i.refresh??"behind",this.loaded=Promise.resolve(e.load()).then(r=>{this.current=r}),e.watch?.(()=>{this.reconcile()})}async session(){return await this.loaded,this.current}snapshot(){return this.current}onChange(e){return this.listeners.add(e),()=>this.listeners.delete(e)}async set(e,t,s){await this.loaded;let i=t==="TOKEN_REFRESHED"?this.current:null,r={accessToken:e.access_token,refreshToken:e.refresh_token,expiresAt:this.now()+e.expires_in*1e3,userId:s?.id??i?.userId??fe(e.access_token),user:s??i?.user};return this.current=r,await this.store.save(r),this.emit(t,r),r}async setUser(e,t){await this.loaded,!(!this.current||!t||this.current.userId!==t.userId)&&(this.current={...this.current,user:e},await this.store.save(this.current),this.emit("USER_UPDATED",this.current))}async clear(e,t){await this.loaded;let s=this.current;this.current=null,this.inflight=null;let i=await this.store.load();(!i||!s||i.userId===s.userId)&&await this.store.clear(),s&&(e==="SESSION_EXPIRED"&&(this.endReason=t??"revoked"),this.emit(e,null))}async accessToken(){await this.loaded;let e=this.current;if(!e)return;let t=e.expiresAt-this.now();if(t>pt)return e.accessToken;if(this.mode==="never")return t>0?e.accessToken:void 0;if(t>0&&this.mode==="behind")return this.refresh().catch(()=>{}),e.accessToken;if(t>0)try{return(await this.refresh()).accessToken}catch(s){if(this.current===e)return e.accessToken;throw s}return(await this.refresh()).accessToken}refresh(){if(this.mode==="never")return Promise.reject(new Error("this client does not renew its session (refresh: 'never'): where the session cannot be written back, the request's middleware renews it"));if(this.inflight)return this.inflight;let e=gt(this.store.shared===!0,this.lockName,async()=>{await this.loaded;let t=this.current;if(!t)throw new T("no session to refresh");let s=await this.adoptStored(t);if(s)return s;try{let i=await this.withTimeout(this.refresher(t.refreshToken));if(this.current?.refreshToken!==t.refreshToken)throw new T("the session changed while it was refreshed");return await this.set(i,"TOKEN_REFRESHED")}catch(i){throw this.isRejected(i)&&this.current?.refreshToken===t.refreshToken&&await this.clear("SESSION_EXPIRED",ht(i)),i}});return this.inflight=e,e.finally(()=>{this.inflight===e&&(this.inflight=null)}).catch(()=>{}),e}async adoptStored(e){let t=await this.store.load();if(!t)throw this.current=null,this.emit("SIGNED_OUT",null),new T("signed out in another tab");if(t.userId!==e.userId)throw this.current=t,this.emit("SIGNED_OUT",null),this.emit("SIGNED_IN",t),new T("another user signed in in another tab");if(t.refreshToken!==e.refreshToken&&t.expiresAt>=e.expiresAt)return this.current=t,this.emit("TOKEN_REFRESHED",t),t}async reconcile(){await this.loaded;let e=this.current,t=await this.store.load();if(!e){t&&(this.current=t,this.emit("SIGNED_IN",t));return}await this.adoptStored(e).catch(()=>{})}withTimeout(e){let t,s=new Promise((i,r)=>{t=setTimeout(()=>r(new Error(`the refresh did not answer within ${this.refreshTimeoutMs/1e3} s`)),this.refreshTimeoutMs)});return Promise.race([e,s]).finally(()=>clearTimeout(t))}emit(e,t){(e==="SIGNED_IN"||e==="SIGNED_OUT")&&(this.endReason=null);for(let s of this.listeners)try{s(e,t)}catch{}}};var ge=class{state="closed";refusal;logSeq;joinRef=null;listeners=new Map;closers=new Set;joinWaiters=[];name;socket;constructor(e,t,s={}){this.name=e,this.socket=t,this.logSeq=s.after}get topic(){return`realtime:${this.name}`}join(){if(this.state==="joined")return Promise.resolve();let e=new Promise((t,s)=>this.joinWaiters.push({resolve:t,reject:s}));return this.state!=="joining"&&this.socket.join(this),e}leave(){this.socket.leave(this)}push(e,t){return this.socket.request(this,e,t)}on(e,t){let s=this.listeners.get(e);return s||this.listeners.set(e,s=new Set),s.add(t),()=>s.delete(t)}onClosed(e){return this.closers.add(e),()=>this.closers.delete(e)}deliver(e,t){e==="broadcast"&&typeof t.seq=="number"&&(this.logSeq=t.seq);for(let s of this.listeners.get(e)??[])try{s(t)}catch{}}settled(e,t){e&&typeof t.log_seq=="number"&&(this.logSeq=t.log_seq),this.state=e?"joined":"refused",this.refusal=e?void 0:t;let s=this.joinWaiters.splice(0);for(let i of s)e?i.resolve():i.reject(new Error(`join ${this.name} refused: ${JSON.stringify(t)}`))}closed(e){this.state="closed",this.joinRef=null;let t=this.joinWaiters.splice(0);for(let s of t)s.reject(new Error(`join ${this.name}: ${e}`));for(let s of[...this.closers])try{s()}catch{}}},B=class{ws=null;opening=null;ref=0;channels=new Map;replies=new Map;heartbeat=null;heartbeatRef=null;reconnectTimer=null;attempts=0;closedByUs=!1;reconnects=0;opts;constructor(e){this.opts=e}channel(e,t){let s=this.channels.get(e);return s||this.channels.set(e,s=new ge(e,this,t)),s}disconnect(){this.closedByUs=!0,this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=null,this.stopHeartbeat();let e=this.ws;this.ws=null,this.opening=null,e?.close(1e3);for(let[,t]of this.replies)t("error",{reason:"socket closed"});this.replies.clear();for(let t of this.channels.values())t.closed("the socket was closed")}async tokenChanged(){if(!this.ws||this.ws.readyState!==1)return;let e=await this.opts.accessToken();if(e)for(let t of this.channels.values())t.state==="joined"&&this.push(t.joinRef,t.topic,"access_token",{access_token:e})}join(e){e.state="joining",this.open().then(()=>this.sendJoin(e)).catch(t=>e.settled(!1,{reason:t instanceof Error?t.message:String(t)}))}leave(e){e.state==="joined"&&this.ws?.readyState===1&&this.push(e.joinRef,e.topic,"phx_leave",{}),e.state="closed",this.channels.delete(e.name)}async request(e,t,s){let i=this.ws;if(this.channels.get(e.name)!==e||e.state!=="joined"||i?.readyState!==1)return{status:"error",response:{reason:"not joined"}};let r=this.nextRef(),a=JSON.stringify([e.joinRef,r,e.topic,t,s]),o=this.awaitReply(r);return i.send(a),o}open(){if(this.ws?.readyState===1)return Promise.resolve();if(this.opening)return this.opening;this.closedByUs=!1;let e=this.opts.webSocket??globalThis.WebSocket,t=`${this.opts.baseUrl.replace(/^http/,"ws")}/realtime/v1/websocket?vsn=2.0.0&apikey=${encodeURIComponent(this.opts.publishableKey)}`,s=new Promise((i,r)=>{let a=new e(t);this.ws=a,a.onopen=()=>{this.attempts=0,this.startHeartbeat(),i()},a.onmessage=o=>this.receive(String(o.data)),a.onerror=()=>r(new Error("the realtime socket could not be opened")),a.onclose=()=>this.dropped(a)});return this.opening=s,s.finally(()=>{this.opening===s&&(this.opening=null)}).catch(()=>{}),s}dropped(e){if(this.ws!==e)return;this.ws=null,this.stopHeartbeat();for(let[,i]of this.replies)i("error",{reason:"socket closed"});this.replies.clear();for(let i of this.channels.values())i.state==="joined"&&(i.state="joining");if(this.closedByUs||![...this.channels.values()].some(i=>i.state==="joining"))return;let t=this.opts.backoff??[500,1e3,2e3,5e3,1e4,3e4],s=t[Math.min(this.attempts,t.length-1)]*(.8+Math.random()*.4);this.attempts++,this.reconnectTimer=J(setTimeout(()=>{this.reconnectTimer=null,this.reconnects++;let i=[...this.channels.values()].filter(r=>r.state==="joining");this.open().then(()=>Promise.all(i.map(r=>this.sendJoin(r)))).catch(()=>{})},s))}async sendJoin(e){let t=await this.opts.accessToken(),s=this.nextRef();e.joinRef=s;let i=this.awaitReply(s),r={broadcast:{self:!1}};e.logSeq!==void 0&&(r.log={after:e.logSeq}),this.push(s,e.topic,"phx_join",{access_token:t,config:r},s);let{status:a,response:o}=await i;if(this.channels.get(e.name)!==e||e.state!=="joining"){a==="ok"&&this.ws?.readyState===1&&this.push(s,e.topic,"phx_leave",{});return}e.settled(a==="ok",o)}awaitReply(e){return new Promise(t=>{let s=J(setTimeout(()=>{this.replies.delete(e),t({status:"timeout",response:{reason:"no reply"}})},this.opts.replyTimeoutMs??1e4));this.replies.set(e,(i,r)=>{clearTimeout(s),this.replies.delete(e),t({status:i,response:r})})})}receive(e){let t;try{t=JSON.parse(e)}catch{return}if(!Array.isArray(t)||t.length!==5||typeof t[2]!="string"||typeof t[3]!="string")return;let[,s,i,r,a]=t,o=typeof a=="object"&&a!==null?a:{};if(r==="phx_reply"&&typeof s=="string"){if(s===this.heartbeatRef){this.heartbeatRef=null;return}this.replies.get(s)?.(String(o.status),o.response??{});return}let c=[...this.channels.values()].find(l=>l.topic===i);if(c){if(r==="phx_close"){c.state="closed";return}if(r==="phx_error"){c.state="joining",J(setTimeout(()=>this.channels.get(c.name)===c&&c.state==="joining"&&this.ws?.readyState===1&&void this.sendJoin(c),1e3));return}c.deliver(r,o)}}push(e,t,s,i,r=this.nextRef()){this.ws?.send(JSON.stringify([e,r,t,s,i]))}nextRef(){return String(++this.ref)}startHeartbeat(){this.stopHeartbeat(),this.heartbeat=J(setInterval(()=>{if(this.heartbeatRef!==null){this.heartbeatRef=null,this.ws?.close(4e3);return}this.heartbeatRef=this.nextRef(),this.push(null,"phoenix","heartbeat",{},this.heartbeatRef)},this.opts.heartbeatMs??25e3))}stopHeartbeat(){this.heartbeat&&clearInterval(this.heartbeat),this.heartbeat=null,this.heartbeatRef=null}};function J(n){return n.unref?.(),n}var A="X-Palbase-Installation-Secret",z="X-Palbase-Installation",De=new WeakMap;function O(n){return De.get(n)}var Ue=new WeakSet;function Ke(n){return Ue.has(n)}var yt=/^[A-Za-z0-9_-]{43}$/,X=class{id;constructor(e){let t=`palbase.installation.secret.${e}`,s;try{let i=Le()?.getItem(t);i&&yt.test(i)&&(s=i)}catch{}if(!s){Ue.add(this),s=je(crypto.getRandomValues(new Uint8Array(32)));try{Le()?.setItem(t,s)}catch{}}De.set(this,s),this.id=mt(s)}};function mt(n){return je(wt(new TextEncoder().encode(n)).subarray(0,16))}function Le(){try{return globalThis.localStorage}catch{return}}function je(n){let e="";for(let t of n)e+=String.fromCharCode(t);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}var vt=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),E=(n,e)=>n>>>e|n<<32-e;function wt(n){let e=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),t=new Uint8Array(Math.ceil((n.length+9)/64)*64);t.set(n),t[n.length]=128;let s=new DataView(t.buffer);s.setUint32(t.length-8,Math.floor(n.length/536870912)),s.setUint32(t.length-4,n.length*8>>>0);let i=new Uint32Array(64);for(let o=0;o<t.length;o+=64){for(let g=0;g<16;g++)i[g]=s.getUint32(o+g*4);for(let g=16;g<64;g++){let m=E(i[g-15],7)^E(i[g-15],18)^i[g-15]>>>3,k=E(i[g-2],17)^E(i[g-2],19)^i[g-2]>>>10;i[g]=i[g-16]+m+i[g-7]+k|0}let[c,l,d,y,f,b,S,u]=e;for(let g=0;g<64;g++){let m=u+(E(f,6)^E(f,11)^E(f,25))+(f&b^~f&S)+vt[g]+i[g]|0,k=(E(c,2)^E(c,13)^E(c,22))+(c&l^c&d^l&d)|0;u=S,S=b,b=f,f=y+m|0,y=d,d=l,l=c,c=m+k|0}e[0]+=c,e[1]+=l,e[2]+=d,e[3]+=y,e[4]+=f,e[5]+=b,e[6]+=S,e[7]+=u}let r=new Uint8Array(32),a=new DataView(r.buffer);for(let o=0;o<8;o++)a.setUint32(o*4,e[o]);return r}var kt=30*6e4,$e=1e3,St=100,_t=60*1024,Y=()=>globalThis.crypto?.randomUUID?globalThis.crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;function D(){try{return globalThis.localStorage}catch{return}}var Q=class{api;closingApi;perfApi;closingPerfApi;flushMs;flushAt;now;anonKey;sessionKey;onceKey;events=[];samples=[];timer;memoryAnon;memorySession;memoryOnce;appVersion;stopAuto;session;consent;identifyPending=!1;listeners=new Set;people={set:e=>this.person({set:e}),setOnce:e=>this.person({set_once:e}),unset:e=>this.person({unset:[...e]}),add:e=>this.person({add:e})};constructor(e,t,s,i,r,a,o={}){this.session=s,this.consent=i;let c={send:d=>e.send(this.granted("analytics")?{...d,headers:{...d.headers,[z]:r.id}}:d)};this.api=V.client(c);let l={send:d=>(this.granted("analytics")?e:t).send(d)};this.perfApi=V.client(l),this.closingApi=V.client({send:d=>c.send({...d,keepalive:!0})}),this.closingPerfApi=V.client({send:d=>l.send({...d,keepalive:!0})}),this.flushMs=o.flushMs??5e3,this.flushAt=o.flushAt??20,this.now=o.now??Date.now,this.anonKey=`palbase.analytics.anonymous.${a}`,this.sessionKey=`palbase.analytics.session.${a}`,this.onceKey=`palbase.analytics.once.${a}`,s.onChange(d=>{d==="SIGNED_IN"?(this.identifyPending=!0,this.soon()):d==="SIGNED_OUT"&&(this.identifyPending=!1,this.reset())}),i.onChange((d,y)=>{y!=="granted"&&(d==="analytics"?(this.events=[],this.identifyPending=!1,this.samples=this.samples.map(ye),this.reset()):d==="performance"&&(this.samples=[]))})}capture(e,t){for(let i of this.listeners)i(e,t);if(!this.granted("analytics"))return;let s=this.now();this.hold({event:e,distinct_id:this.distinctId(),properties:t,timestamp:s,session_id:this.sessionId(s),...this.appVersion?{app_version:this.appVersion}:{}})}captureOnce(e,t,s){if(!this.granted("analytics"))return;let i=this.sessionId(this.now()),r=this.readOnce(),a=r?.session===i?r.keys:[];a.includes(e)||(this.writeOnce({session:i,keys:[...a,e].slice(-500)}),this.capture(t,s))}readOnce(){try{let e=D()?.getItem(this.onceKey);if(e)return JSON.parse(e)}catch{}return this.memoryOnce}writeOnce(e){this.memoryOnce=e;try{D()?.setItem(this.onceKey,JSON.stringify(e))}catch{}}onEvent(e){return this.listeners.add(e),()=>this.listeners.delete(e)}page(e={}){let t=globalThis.location,s=globalThis.document,i=e.url??(t?`${t.origin}${$(t.pathname)}`:"");if(!i)return;let r=e.referrer??Rt(s?.referrer);this.capture("$pageview",{...e.properties,url:i,...e.title??s?.title?{title:e.title??s?.title}:{},...r?{referrer:r}:{}})}async identify(e){this.identifyPending=!1;let t=this.session.snapshot()?.userId;!t||!this.granted("analytics")||(await this.flush(),await this.sendIdentify(this.api,t,e))}async sendIdentify(e,t,s){try{await e.identify({body:{distinct_id:t,anonymous_id:this.anonymousId(),traits:s,timestamp:this.now(),sent_at:this.now()}})}catch{}}reset(){this.memoryAnon=void 0,this.memorySession=void 0,this.memoryOnce=void 0;try{D()?.removeItem(this.anonKey),D()?.removeItem(this.sessionKey),D()?.removeItem(this.onceKey)}catch{}}async flush(e=!1){this.timer&&clearTimeout(this.timer),this.timer=void 0,this.granted("analytics")||(this.events=[]),this.granted("performance")?this.granted("analytics")||(this.samples=this.samples.map(ye)):this.samples=[];let t=e?this.closingApi:this.api,s=e?this.closingPerfApi:this.perfApi,i=this.now(),r=this.session.snapshot()?.userId;for(this.identifyPending&&r&&this.granted("analytics")&&(this.identifyPending=!1,await this.sendIdentify(t,r));this.events.length>0;){let a=this.take(this.events,e);try{await t.batch({body:{events:a.map(o=>({...o,sent_at:i}))}})}catch{}}for(;this.samples.length>0;){let a=this.take(this.samples,e);try{await s.sendPerf({body:{items:a}})}catch{}}}start(e={}){this.stopAuto?.(),this.appVersion=e.appVersion;let t=globalThis;if(typeof t.addEventListener!="function"||typeof globalThis.document>"u")return()=>{};let s=[];e.pageViews!==!1&&s.push(this.watchPages(t)),e.webVitals!==!1&&s.push(Pt((a,o)=>this.sample("web_vital",a,o))),e.network!==!1&&s.push(this.watchFetch(t));let i=()=>{document.visibilityState==="hidden"&&this.flush(!0)},r=()=>{this.flush(!0)};return document.addEventListener("visibilitychange",i),t.addEventListener("pagehide",r),s.push(()=>{document.removeEventListener("visibilitychange",i),t.removeEventListener("pagehide",r)}),this.stopAuto=()=>{for(let a of s.splice(0))a();this.stopAuto=void 0},this.stopAuto}granted(e){return this.consent.state(e)==="granted"}async person(e){if(!this.granted("analytics"))return;let t=this.session.snapshot()?.userId,s=this.now();try{await this.api.setPersonProperties({body:{...e,...t?{}:{distinct_id:this.anonymousId()},timestamp:s,sent_at:s}})}catch{}}hold(e){this.events.length>=$e&&this.events.shift(),this.events.push(e),this.soon()}sample(e,t,s,i={}){if(!this.granted("performance"))return;this.samples.length>=$e&&this.samples.shift();let r={row_id:Y(),trace_type:e,name:t,value:Math.max(0,s),timestamp:this.now(),...i};this.samples.push(this.granted("analytics")?{...r,distinct_id:this.distinctId()}:ye(r)),this.soon()}soon(){if(this.events.length+this.samples.length>=this.flushAt){this.flush();return}this.timer||(this.timer=setTimeout(()=>{this.flush()},this.flushMs),this.timer.unref?.())}take(e,t){let s=e.splice(0,St);if(!t)return s;for(;s.length>1&&JSON.stringify(s).length>_t;)e.unshift(s.pop());return s}distinctId(){return this.session.snapshot()?.userId??this.anonymousId()}anonymousId(){let e=D();try{let t=e?.getItem(this.anonKey);if(t)return t;let s=`anon_${Y()}`;if(e?.setItem(this.anonKey,s),e?.getItem(this.anonKey)===s)return s}catch{}return this.memoryAnon??=`anon_${Y()}`,this.memoryAnon}sessionId(e){let t=D(),s=this.memorySession;try{let r=t?.getItem(this.sessionKey);r&&(s=JSON.parse(r))}catch{}let i=s&&e-s.last<kt?{id:s.id,last:e}:{id:`ses_${Y()}`,last:e};this.memorySession=i;try{t?.setItem(this.sessionKey,JSON.stringify(i))}catch{}return i.id}watchPages(e){let t="",s=()=>{let o=`${e.location.origin}${e.location.pathname}`;if(o===t)return;t=o;let c=`${e.location.origin}${$(e.location.pathname)}`;setTimeout(()=>this.page({url:c}),0)},i=e.history,r=i.pushState.bind(i),a=i.replaceState.bind(i);return i.pushState=(...o)=>{r(...o),s()},i.replaceState=(...o)=>{a(...o),s()},e.addEventListener("popstate",s),s(),()=>{i.pushState=r,i.replaceState=a,e.removeEventListener("popstate",s)}}watchFetch(e){let t=e.fetch;if(typeof t!="function")return()=>{};let s=async(i,r)=>{let a=performance.now(),o=i instanceof Request?i:void 0,c=(r?.method??o?.method??"GET").toUpperCase(),l;try{l=new URL(o?.url??String(i),e.location.href)}catch{l=void 0}let d=!!l&&l.pathname.startsWith("/analytics/")||Tt(r?.headers??o?.headers);try{let y=await t(i,r);return l&&!d&&this.sample("network",`${c} ${l.origin}${$(l.pathname)}`,performance.now()-a,{attrs:{status:String(y.status)},...y.headers.get("x-request-id")?{request_id:y.headers.get("x-request-id")}:{}}),y}catch(y){throw l&&!d&&this.sample("network",`${c} ${l.origin}${$(l.pathname)}`,performance.now()-a,{attrs:{status:"0"}}),y}};return e.fetch=s,()=>{e.fetch===s&&(e.fetch=t)}}};function ye(n){let{distinct_id:e,request_id:t,...s}=n;return s}var It=n=>n.entryType==="layout-shift"&&"value"in n&&"hadRecentInput"in n,xt=n=>n.entryType==="event"||n.entryType==="first-input";function Z(n,e){if(!(typeof PerformanceObserver>"u"))try{let t=new PerformanceObserver(s=>e(s.getEntries()));return t.observe({type:n,buffered:!0}),t}catch{return}}function Pt(n){if(typeof document>"u"||typeof performance>"u"||typeof performance.getEntriesByType!="function")return()=>{};let e=0,t=0,s=0,i=[Z("largest-contentful-paint",l=>{for(let d of l)e=Math.max(e,d.startTime)}),Z("layout-shift",l=>{for(let d of l)It(d)&&!d.hadRecentInput&&(t+=d.value)}),Z("event",l=>{for(let d of l)xt(d)&&(s=Math.max(s,d.duration))}),Z("paint",l=>{for(let d of l)d.name==="first-contentful-paint"&&n("FCP",d.startTime)})],r=performance.getEntriesByType("navigation")[0];r&&r.responseStart>0&&n("TTFB",r.responseStart);let a=!1,o=()=>{a||(a=!0,e>0&&n("LCP",e),n("CLS",t),s>0&&n("INP",s))},c=()=>{document.visibilityState==="hidden"&&o()};return document.addEventListener("visibilitychange",c),()=>{o(),document.removeEventListener("visibilitychange",c);for(let l of i)l?.disconnect()}}function Tt(n){if(!n)return!1;try{return new Headers(n).has("next-router-prefetch")}catch{return!1}}var Et=/^[a-z][a-z0-9_-]{0,31}$/;function $(n){return n.split("/").map(e=>{if(e==="")return e;let t=e.split(";",1)[0],s=t.toLowerCase();return Et.test(s)&&(s.match(/\d/g)?.length??0)<=2&&t.slice(1)===s.slice(1)&&s.split(/[-_]/).every(r=>r.length<=16)?s:":id"}).join("/")}function Rt(n){if(!n)return"";try{let e=new URL(n);return`${e.origin}${$(e.pathname)}`}catch{return $(n.split(/[?#]/,1)[0]??"")}}var Ye=/^custom\.[a-z0-9_]{1,48}$/,At=/^[a-z][a-z0-9_]{0,63}$/,qe=n=>At.test(n)||Ye.test(n),Ot=50,Ve=[5e3,3e4,12e4,6e5],Ct=100,te=class{userApi;deviceApi;session;socket;ref;installation;start;textVersion;customKeys;storeKey;now;kept;listeners=new Set;engaged=!1;platformKeys;watch;sending;sendAgain=!1;retryTimer;retries=0;readFor;stale=!1;lastW=0;lastChosen=0;gpc=globalThis.navigator?.globalPrivacyControl===!0;constructor(e){let t=e.options??{};for(let[c,l]of Object.entries(t.start??{})){if(!qe(c))throw new TypeError(`consent.start: ${JSON.stringify(c)} is not a consent key (a platform key, or custom.<name>)`);if(l!=="granted"&&l!=="denied")throw new TypeError(`consent.start.${c} is granted or denied`)}for(let c of t.customKeys??[])if(!Ye.test(c))throw new TypeError(`consent.customKeys: ${JSON.stringify(c)} is not custom.<name> (a-z, 0-9 and _, 48 at most)`);if(t.textVersion!==void 0&&(t.textVersion===""||t.textVersion.length>64))throw new TypeError("consent.textVersion: 1 to 64 characters");this.userApi=e.userApi,this.deviceApi=e.deviceApi,this.session=e.session,this.socket=e.socket,this.ref=e.ref,this.installation=e.installation,this.start={...t.start},this.textVersion=t.textVersion,this.customKeys=[...t.customKeys??[]],this.storeKey=`palbase.consent.${e.origin}.${e.installation.id}`,this.now=e.now??Date.now;let s=this.load(),i=()=>Ke(this.installation)?{}:{unknown:{on:!0,w:this.stamp()}},r={whose:null,install:this.installation.id,choices:{},unsent:[]};typeof s!="object"?this.kept={...r,...s==="unreadable"?{unknown:{on:!0,w:this.stamp()}}:i()}:s.whose==null&&s.install!==void 0&&s.install!==this.installation.id?this.kept={...r,unsent:s.unsent.filter(c=>c.user!==null),...s.keys?{keys:s.keys}:{},...i()}:this.kept=s,e.session.onChange((c,l)=>{this.engaged&&(c==="SIGNED_IN"&&l?this.signedIn(l):(c==="SIGNED_OUT"||c==="SESSION_EXPIRED")&&this.signedOut())});let a=globalThis;typeof a.addEventListener=="function"&&(a.addEventListener("storage",c=>{(c.key===this.storeKey||c.key===null)&&this.reload()}),a.addEventListener("online",()=>{this.engaged&&this.send()}));let o=this.kept;(e.options!==void 0||s!=="empty"&&(o.unknown?.on||o.unsent.length>0||o.link!==void 0||Object.keys(o.choices).length>0))&&this.engage()}async keys(){return this.engage(),[...(await this.platform()).map(t=>({key:t.key,category:t.category,title:{...t.title},description:{...t.description},ads:t.ads})),...this.customKeys.map(t=>({key:t,category:"custom",title:{},description:{},ads:!1}))]}state(e){if(_(this.kept)!==this.holder()||this.gpcRefuses(e))return"denied";let t=Ge(this.kept,e);return t&&t.state!=="unset"?t.state:this.kept.unknown?.on?"denied":this.start[e]}owesRead(){return this.stale||this.kept.unknown?.on===!0||_(this.kept)!==this.holder()||Object.values(this.kept.choices).some(e=>e.provisional)}holder(){let e=this.session.snapshot()?.userId;return e?`user:${e}`:`device:${this.installation.id}`}lastDeniedAt(e){let t=this.kept.choices[e]?.last_denied_at;return t?new Date(t):void 0}set(e,t){this.setMany({[e]:t})}setMany(e){let t=Object.entries(e);for(let[a,o]of t){if(!qe(a))throw new TypeError(`${JSON.stringify(a)} is not a consent key (a platform key, or custom.<name>)`);if(o!=="granted"&&o!=="denied")throw new TypeError(`${a}: a choice is granted or denied`)}if(t.length===0)return;this.engage();let s=this.chosenAt(),i=this.session.snapshot()?.userId??null,r=this.states();for(let[a,o]of t)this.queue({key:a,state:o,source:"app",chosen_at:s,user:i,...this.textVersion!==void 0?{text_version:this.textVersion}:{}});this.commit(r),this.send()}onChange(e){return this.listeners.add(e),()=>this.listeners.delete(e)}async region(){this.engage();let e=await this.subject();if(this.readFor!==e)try{await this.read(e)}catch(t){if(!this.kept.region)throw t}return this.kept.region}async needsAsking(e){this.engage();let t=await this.subject();this.readFor!==t&&await this.read(t).catch(()=>{});let s=e??(await this.keys()).map(c=>c.key),i=await this.platform().catch(()=>this.kept.keys??[]),r=new Set(i.filter(c=>c.ads).map(c=>c.key)),a=this.kept.region?.jurisdiction==="us",o=new Date(this.now());return o.setUTCMonth(o.getUTCMonth()-12),s.filter(c=>{let l=this.kept.choices[c];return a&&r.has(c)&&l?.last_denied_at!==void 0&&Date.parse(l.last_denied_at)>o.getTime()?!1:!l||l.state==="unset"?!0:this.textVersion!==void 0&&l.source==="app"&&l.text_version!==this.textVersion})}engage(){this.engaged||(this.engaged=!0,this.session.session().then(e=>{e&&!this.watch&&this.follow(e),this.send(),this.refuseByGpc()}))}async subject(){return(await this.session.session())?.userId??null}secret(){return{[A]:O(this.installation)}}platform(){return this.platformKeys??=this.deviceApi.listConsentKeys().then(e=>(this.kept={...this.kept,keys:e.data.keys},this.commit(),e.data.keys),e=>{if(this.platformKeys=void 0,this.kept.keys)return this.kept.keys;throw e}),this.platformKeys}async read(e){let s=(await(e===null?this.deviceApi:this.userApi(e)).getConsents({query:{installation_id:this.installation.id},headers:this.secret()})).data;this.adopt(s,e)}adopt(e,t,s=[]){if(this.kept={...this.kept,region:e.region},(this.session.snapshot()?.userId??null)!==t){this.commit();return}let i=this.states(),r={};for(let u of e.choices)r[u.key]={state:u.state,source:u.source,chosen_at:u.chosen_at,...u.text_version!==void 0?{text_version:u.text_version}:{},...u.last_denied_at!==void 0?{last_denied_at:u.last_denied_at}:{}};let a=s.filter(u=>r[u.key]?.state!==u.state||Date.parse(r[u.key]?.chosen_at??"")!==Date.parse(u.chosen_at)).map(u=>C(u.key,u)),c=_(this.kept)===(t===null?`device:${this.installation.id}`:`user:${t}`)?Object.entries(this.kept.choices).filter(([,u])=>u.provisional).map(([u,g])=>C(u,g)):[];if(a.length+c.length>0&&(this.kept={...this.kept,void:M([...this.kept.void??[],...a,...c])}),t===null&&this.kept.resetAt!==void 0)for(let[u,g]of Object.entries(r))Date.parse(g.chosen_at)<this.kept.resetAt&&delete r[u];let l=new Set(Object.entries(r).map(([u,g])=>C(u,g))),d=(this.kept.void??[]).filter(u=>l.has(u));d.length>0&&(this.kept={...this.kept,unvoid:M([...this.kept.unvoid??[],...d])});let y=Ze(this.kept),f;if(_(this.kept)!==(t===null?`device:${this.installation.id}`:`user:${t}`))f=r;else{f={};for(let u of[...new Set([...Object.keys(this.kept.choices),...Object.keys(r)])].sort()){let g=this.kept.choices[u],m=g&&!g.provisional&&!y.has(C(u,g))?g:void 0,k=r[u],R=k&&(!m||Date.parse(k.chosen_at)>=Date.parse(m.chosen_at))?k:m;R&&(f[u]=R)}}for(let u of this.kept.unsent){if(u.user!==null&&u.user!==t||u.user===null&&u.device!==void 0&&u.device!==this.installation.id||u.user===null&&t!==null)continue;let g=f[u.key];g&&Date.parse(g.chosen_at)>Date.parse(u.chosen_at)||(f[u.key]=Fe(u,g))}let{install:b,...S}=this.kept;this.kept={...S,whose:t,...t===null?{install:this.installation.id}:{},choices:f,unknown:{on:!1,w:this.stamp()}},this.readFor=t,this.stale=!1,this.commit(i),this.refuseByGpc()}async refused(e,t,s){let i=t===e&&_(this.kept)===(t===null?`device:${this.installation.id}`:`user:${t}`),r=M([...this.kept.void??[],...s.map(c=>C(c.key,c))]);if(!i){this.kept={...this.kept,void:r},this.commit();return}let a=this.states(),o={...this.kept.choices};for(let c of s){if(this.kept.unsent.some(d=>d.key===c.key&&(d.user===null||d.user===e)&&Date.parse(d.chosen_at)>Date.parse(c.chosen_at)))continue;let l=o[c.key];o[c.key]={state:"denied",source:"app",chosen_at:c.chosen_at,...l?.last_denied_at!==void 0?{last_denied_at:l.last_denied_at}:{},provisional:!0}}this.kept={...this.kept,choices:o,void:r},this.commit(a);try{await this.read(e)}catch{this.stale=!0}}queue(e){let t=e.user===null?{...e,device:this.installation.id}:e,s=_(this.kept)===(t.user===null?`device:${this.installation.id}`:`user:${t.user}`);this.kept={...this.kept,unsent:Qe([...this.kept.unsent,t]),...s?{choices:{...this.kept.choices,[t.key]:Fe(t,this.kept.choices[t.key])}}:{}}}send(){if(this.sendAgain=!0,this.sending)return;let e=(async()=>{for(;this.sendAgain;)this.sendAgain=!1,await this.sendUnsent()||(this.sendAgain=!1)})();this.sending=e,e.finally(()=>{this.sending===e&&(this.sending=void 0)})}async sendUnsent(){this.retryTimer&&clearTimeout(this.retryTimer),this.retryTimer=void 0;let e=null;try{e=await this.subject();let t=await this.sendOf(null,e);if(e!==null&&(this.kept.link===e||t)){let s;try{s=(await this.userApi(e).linkConsents({headers:this.secret(),body:{installation_id:this.installation.id}})).data}catch(i){if(!Be(i))throw i}if(this.kept.link===e){let{link:i,...r}=this.kept;this.kept=r,this.commit()}if(s)this.adopt(s,e);else{let i=this.states();this.kept={...this.kept,unknown:{on:!0,w:this.stamp()}},this.commit(i)}}if(e!==null&&await this.sendOf(e,e),this.owesRead()&&(await this.read(e),this.owesRead()))throw new Error("the choices are not read yet");return this.retries=0,!0}catch(t){return t instanceof T&&(this.session.snapshot()?.userId??null)!==e?(this.sendAgain=!0,!0):(this.retryLater(),!1)}}async sendOf(e,t){let s=!1;for(;;){let i=this.nextGroup(e);if(i.length===0)return s;let r=i[0],a=e===null?this.deviceApi:this.userApi(e),o;try{o=(await a.chooseConsents({headers:this.secret(),body:{installation_id:this.installation.id,...r.source==="gpc"?{source:"gpc"}:{},...r.text_version!==void 0?{text_version:r.text_version}:{},choices:i.map(c=>({key:c.key,state:c.state,chosen_at:c.chosen_at}))}})).data}catch(c){if(!Be(c))throw c;if(i.length>1){this.kept={...this.kept,unsent:this.kept.unsent.map(l=>i.some(d=>Je(d,l))?{...l,alone:!0}:l)},this.commit();continue}}this.kept={...this.kept,unsent:this.kept.unsent.filter(c=>!i.some(l=>Je(l,c))),done:M([...this.kept.done??[],...i.map(se)])},this.commit(),o?(s=!0,e===t&&this.adopt(o,e,i)):await this.refused(t,e,i)}}nextGroup(e){let t=this.kept.unsent.filter(a=>a.user===e&&(e!==null||(a.device??this.installation.id)===this.installation.id)),s=t[0];if(!s)return[];let i=[],r=new Set;if(s.alone)return[s];for(let a of t)if(!r.has(a.key)&&(r.add(a.key),!(a.alone||a.source!==s.source||a.text_version!==s.text_version)&&(i.push(a),i.length===Ot)))break;return i}retryLater(){if(this.retryTimer)return;let e=Ve[Math.min(this.retries,Ve.length-1)];this.retries++,this.retryTimer=setTimeout(()=>{this.retryTimer=void 0,this.send()},e),this.retryTimer.unref?.()}signedIn(e){this.readFor=void 0,this.kept={...this.kept,link:e.userId},this.commit(),this.follow(e),this.send()}signedOut(){this.unfollow(),this.readFor=void 0;let e=this.states(),t=this.chosenAt(),s=new Set([...Object.entries(this.kept.choices).filter(([,o])=>o.state!=="unset").map(([o])=>o),...this.kept.unsent.filter(o=>o.user===null&&(o.device??this.installation.id)===this.installation.id).map(o=>o.key),...Object.keys(this.start),...this.customKeys,...(this.kept.keys??[]).map(o=>o.key)]),i={};for(let[o,c]of Object.entries(this.kept.choices))i[o]={state:"unset",source:"app",chosen_at:t,...c.last_denied_at!==void 0?{last_denied_at:c.last_denied_at}:{}};let r=o=>o.user===null&&(o.device??this.installation.id)===this.installation.id,a=this.kept.unsent.filter(r);this.kept={whose:null,install:this.installation.id,resetAt:Date.parse(t),choices:i,unsent:this.kept.unsent.filter(o=>!r(o)),...this.kept.void?{void:this.kept.void}:{},...this.kept.unvoid?{unvoid:this.kept.unvoid}:{},done:M([...this.kept.done??[],...a.map(se)]),...this.kept.region?{region:this.kept.region}:{},...this.kept.keys?{keys:this.kept.keys}:{},...this.kept.gpc?{gpc:this.kept.gpc}:{},...this.kept.unknown?{unknown:this.kept.unknown}:{}};for(let o of s)this.queue({key:o,state:"unset",source:"app",chosen_at:t,user:null});this.commit(e),this.send(),this.refuseByGpc()}follow(e){this.unfollow();let t=this.socket.channel(`consents:${this.ref}:${e.userId}`),s={userId:e.userId,channel:t,off:()=>{},version:-1},i=[t.on("broadcast",r=>{r.event==="changed"&&this.changed(s,me(r.payload))}),t.on("state_snapshot",r=>this.held(s,me(ze(r.entries)))),t.on("state_diff",r=>this.held(s,me(ze(r.set))))];s.off=()=>i.forEach(r=>r()),this.watch=s,t.join().catch(()=>{})}unfollow(){let e=this.watch;e&&(this.watch=void 0,e.off(),e.channel.leave())}held(e,t){t!==void 0&&this.changed(e,t)}changed(e,t){if(this.watch===e){if(t!==void 0){if(t<=e.version)return;e.version=t}this.read(e.userId).catch(()=>{this.watch===e&&(this.stale=!0,this.retryLater())})}}gpcRefuses(e){if(!this.gpc||!(this.kept.keys??[]).some(r=>r.key===e&&r.ads))return!1;let t=Ge(this.kept,e);if(t?.state==="denied")return!1;let s=this.kept.gpc?.[_(this.kept)],i=s!==void 0&&(this.kept.whose!=null||s>=(this.kept.resetAt??0));return!(t?.state==="granted"&&t.source==="app"&&i&&Date.parse(t.chosen_at)>s)}async refuseByGpc(){if(!this.gpc||_(this.kept)!==this.holder())return;let e;try{e=await this.platform()}catch{return}if(_(this.kept)!==this.holder())return;let t=this.session.snapshot()?.userId??null,s=e.filter(a=>a.ads&&this.gpcRefuses(a.key)&&!this.kept.unsent.some(o=>o.key===a.key&&o.source==="gpc"&&o.user===t));if(s.length===0)return;let i=this.chosenAt(),r=this.states();for(let a of s)this.queue({key:a.key,state:"denied",source:"gpc",chosen_at:i,user:t});this.kept={...this.kept,gpc:{...this.kept.gpc,[_(this.kept)]:Date.parse(i)}},this.commit(r),this.send()}states(){let e=new Map;for(let t of[...Object.keys(this.start),...Object.keys(this.kept.choices)])e.set(t,this.state(t));return e}tell(e){let t=this.states();for(let s of new Set([...e.keys(),...t.keys()])){let i=t.get(s);if(e.get(s)!==i)for(let r of[...this.listeners])try{r(s,i)}catch{}}}load(){let e;try{e=Xe()?.getItem(this.storeKey)}catch{return"unreadable"}if(e==null)return"empty";try{let t=JSON.parse(e);if(Dt(t))return t}catch{}return"unreadable"}reload(){let e=this.load();if(typeof e!="object"){this.write();return}let t=this.states();this.kept=He(e,this.kept,"theirs",this.holder()),_(e)===_(this.kept)&&We(this.kept)!==We(e)&&this.write(),this.tell(t);let s=this.session.snapshot()?.userId??null;this.engaged&&this.kept.unsent.some(i=>i.user!==null&&i.user===s||i.user===null&&(i.device??this.installation.id)===this.installation.id)&&this.retryLater(),this.engaged&&this.refuseByGpc()}commit(e=this.states()){let t=this.load();typeof t=="object"&&(this.kept=He(t,this.kept,"ours",this.holder())),this.write(),this.tell(e)}write(){try{Xe()?.setItem(this.storeKey,JSON.stringify(this.kept))}catch{}}chosenAt(){return this.lastChosen=Math.max(this.now(),this.lastChosen+1),new Date(this.lastChosen).toISOString()}stamp(){let e=this.kept,t=e?Math.max(0,e.unknown?.w??0):0;return this.lastW=Math.max(this.now(),this.lastW+1,t+1),this.lastW}};function Fe(n,e){let t=n.state==="denied"?n.chosen_at:e?.last_denied_at;return{state:n.state,source:n.source,chosen_at:n.chosen_at,...n.text_version!==void 0?{text_version:n.text_version}:{},...t!==void 0?{last_denied_at:t}:{}}}function C(n,e){return`${n}|${e.provisional?"provisional":e.state}|${Date.parse(e.chosen_at)}`}function Ze(n){let e=new Set(n.unvoid??[]);return new Set((n.void??[]).filter(t=>!e.has(t)))}var ee={denied:2,unset:1,granted:0};function Mt(n,e,t,s){let i=e&&!s.has(C(n,e))?e:void 0,r=t&&!s.has(C(n,t))?t:void 0;if(!i||!r)return i??r;let a=Date.parse(i.chosen_at),o=Date.parse(r.chosen_at);return a!==o?a>o?i:r:ee[i.state]!==ee[r.state]?ee[i.state]>ee[r.state]?i:r:i.provisional?r:i}function Nt(n,e){return!n||!e?n??e:e.w>n.w||e.w===n.w&&e.on?e:n}function He(n,e,t,s){let i=M([...n.void??[],...e.void??[]]),r=M([...n.unvoid??[],...e.unvoid??[]]),a=Ze({void:i,unvoid:r}),o={},c,l={...n.gpc};for(let[m,k]of Object.entries(e.gpc??{}))l[m]=Math.max(l[m]??0,k);let d;if(_(n)===_(e)){c=e;for(let m of[...new Set([...Object.keys(n.choices),...Object.keys(e.choices)])].sort()){let k=Mt(m,n.choices[m],e.choices[m],a);k&&(o[m]=k)}d=Nt(n.unknown,e.unknown)}else{c=_(e)===s?e:_(n)===s?n:t==="ours"?e:n;for(let[m,k]of Object.entries(c.choices))a.has(C(m,k))||(o[m]=k);d=c.unknown}let y=M([...n.done??[],...e.done??[]]),f=Qe([...n.unsent,...e.unsent]).filter(m=>!y.includes(se(m))),b=t==="ours"?e:n,S=t==="ours"?n:e,u=b.region??S.region,g=b.keys??S.keys;return{whose:c.whose??null,...c.whose==null&&c.install!==void 0?{install:c.install}:{},...c.whose==null&&(n.resetAt!==void 0||e.resetAt!==void 0)&&_(n)===_(e)?{resetAt:Math.max(n.resetAt??0,e.resetAt??0)}:c.whose==null&&c.resetAt!==void 0?{resetAt:c.resetAt}:{},choices:o,unsent:f,...y.length>0?{done:y}:{},...i.length>0?{void:i}:{},...r.length>0?{unvoid:r}:{},...b.link!==void 0?{link:b.link}:{},...u?{region:u}:{},...Object.keys(l).length>0?{gpc:l}:{},...g?{keys:g}:{},...d?{unknown:d}:{}}}function se(n){return`${n.user??`device:${n.device??""}`}|${n.key}|${n.state}|${n.source}|${n.chosen_at}`}function Ge(n,e){let t=n.choices[e];if(!t||n.whose!=null||n.resetAt===void 0||Date.parse(t.chosen_at)>=n.resetAt)return t}function _(n){return n.whose!=null?`user:${n.whose}`:`device:${n.install??""}`}function M(n){return[...new Set(n)].slice(-Ct)}function We(n){return JSON.stringify(n,(e,t)=>typeof t=="object"&&t!==null&&!Array.isArray(t)?Object.fromEntries(Object.entries(t).sort(([s],[i])=>s.localeCompare(i))):t)}function Qe(n){let e=new Map;for(let t of n){let s=se(t),i=e.get(s);e.set(s,i?i.alone||!t.alone?i:{...i,alone:!0}:t)}return[...e.values()].sort((t,s)=>Date.parse(t.chosen_at)-Date.parse(s.chosen_at))}var Lt=new Set(["granted","denied","unset"]);function Dt(n){if(typeof n!="object"||n===null)return!1;let e=n;if(typeof e.choices!="object"||e.choices===null||Array.isArray(e.choices)||!Array.isArray(e.unsent))return!1;let t=(o,c)=>{if(typeof o!="object"||o===null)return!1;let l=o;return Lt.has(l.state)&&typeof l.chosen_at=="string"&&(!c||typeof l.key=="string")},s=o=>o===void 0||typeof o=="object"&&o!==null&&typeof o.on=="boolean"&&typeof o.w=="number",i=n,r=o=>o===void 0||Array.isArray(o)&&o.every(c=>typeof c=="string"),a=i.whose===void 0||i.whose===null||typeof i.whose=="string";return Object.values(e.choices).every(o=>t(o,!1))&&e.unsent.every(o=>t(o,!0))&&(i.gpc===void 0||typeof i.gpc=="object"&&i.gpc!==null&&Object.values(i.gpc).every(o=>typeof o=="number"))&&s(i.unknown)&&r(i.done)&&r(i.void)&&r(i.unvoid)&&a}function Je(n,e){return n.key===e.key&&n.user===e.user&&n.state===e.state&&n.source===e.source&&n.chosen_at===e.chosen_at}function Be(n){return n instanceof I&&n.status>=400&&n.status<500&&n.status!==401&&n.status!==408&&n.status!==429}function Xe(){try{return globalThis.localStorage}catch{return}}function ze(n){let e=typeof n=="object"&&n!==null?n.version:void 0;return typeof e=="object"&&e!==null?e.v:void 0}function me(n){let e=typeof n=="object"&&n!==null?n.version:void 0;return typeof e=="number"&&Number.isFinite(e)?e:void 0}var Ut=`
3
3
  :host{display:block;color-scheme:light dark;font:15px/1.4 system-ui,-apple-system,"Segoe UI",Roboto,sans-serif}
4
4
  .list{display:flex;flex-direction:column;gap:8px;margin:0;padding:0;list-style:none}
5
5
  .item{position:relative;display:flex;gap:12px;align-items:flex-start;padding:12px 40px 12px 12px;border-radius:12px;background:var(--bg);color:var(--fg);cursor:pointer;outline:none}