palbase 0.3.1 → 0.3.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 (38) hide show
  1. package/LICENSE +11 -5
  2. package/dist/ai/index.js +2 -2
  3. package/dist/backend/engine.js +2 -2
  4. package/dist/backend/env.js +1 -1
  5. package/dist/backend/index.js +3 -3
  6. package/dist/backend/stack.js +1 -1
  7. package/dist/backend/test.js +2 -2
  8. package/dist/chunks/{XNRYSI7A.js → 32BPNFZX.js} +1 -1
  9. package/dist/chunks/33DZIPGE.js +2 -0
  10. package/dist/chunks/44SLUFBO.js +92 -0
  11. package/dist/chunks/{6FQGUDBD.js → CNRFJ7AK.js} +2 -2
  12. package/dist/chunks/{MJPUCGXY.js → HHSKJTI6.js} +2 -2
  13. package/dist/chunks/{4MOCDBZP.js → HJVB6KIR.js} +1 -1
  14. package/dist/chunks/{4K4MKD2J.js → JFWH2INT.js} +2 -2
  15. package/dist/chunks/{4UPL27ED.js → QA3GIZMI.js} +1 -1
  16. package/dist/chunks/{INXQWVHU.js → QD5XLRIJ.js} +2 -2
  17. package/dist/chunks/{XOGEEZNP.js → QRWBXKEM.js} +2 -2
  18. package/dist/chunks/{NTMO2LFH.js → RHQ2NBCI.js} +2 -2
  19. package/dist/chunks/{TV7W53F2.js → TTKDWRP5.js} +2 -2
  20. package/dist/chunks/{JF7KZUPL.js → XUG2RG4F.js} +2 -2
  21. package/dist/chunks/{VTNEPJRV.js → YSZ2RSTS.js} +1 -1
  22. package/dist/chunks/{L6GKX3XI.js → ZEFNZ6DZ.js} +2 -2
  23. package/dist/cli.js +154 -133
  24. package/dist/refuse/ai.js +1 -1
  25. package/dist/refuse/backend.js +1 -1
  26. package/dist/refuse/server.js +1 -1
  27. package/dist/server/index.js +2 -2
  28. package/dist/server/testing.js +2 -2
  29. package/dist/web/index.js +2 -2
  30. package/dist/web/palbe.js +2 -2
  31. package/dist/web/paywall.js +2 -2
  32. package/dist/web/vite.js +2 -2
  33. package/package.json +6 -6
  34. package/types/internal/src/modules/purchases.d.ts +77 -4
  35. package/types/internal/src/modules/storage.d.ts +3 -2
  36. package/types/server/src/auth/jwt.d.ts +4 -1
  37. package/dist/chunks/2YUVLZLK.js +0 -87
  38. package/dist/chunks/FVIHTHHV.js +0 -2
package/LICENSE CHANGED
@@ -1,6 +1,7 @@
1
1
  Palbase SDK License
2
2
 
3
- Copyright (c) 2024-present Palbase. All rights reserved.
3
+ Copyright (c) 2024-present Pallasite OÜ (Estonian registry code 17348411), Tallinn, Estonia ("Pallasite",
4
+ "we"), the maker of Palbase. All rights reserved.
4
5
 
5
6
  The Palbase SDK — the compiled libraries, their interface files and the documentation distributed with them
6
7
  ("the SDK") — is licensed, not sold. Its source code is not part of this distribution.
@@ -17,14 +18,19 @@ The Palbase SDK — the compiled libraries, their interface files and the docume
17
18
  code, except to the extent applicable law expressly permits it notwithstanding this restriction;
18
19
  c. remove or alter any notice in the SDK.
19
20
 
20
- 3. Ownership. Palbase keeps all rights in the SDK that this license does not expressly grant.
21
+ 3. Ownership. Pallasite keeps all rights in the SDK that this license does not expressly grant.
21
22
 
22
23
  4. No warranty. The SDK is provided "as is", without warranty of any kind, express or implied, including the
23
24
  warranties of merchantability, fitness for a particular purpose and non-infringement.
24
25
 
25
- 5. Limitation of liability. In no event shall Palbase be liable for any claim, damages or other liability,
26
- whether in an action of contract, tort or otherwise, arising from, out of or in connection with the SDK or
27
- its use.
26
+ 5. Limitation of liability. To the extent permitted by applicable law, in no event shall Pallasite be liable
27
+ for any claim, damages or other liability, whether in an action of contract, tort or otherwise, arising
28
+ from, out of or in connection with the SDK or its use.
28
29
 
29
30
  6. Termination. This license ends automatically if you break its terms; you must then stop using and
30
31
  distributing the SDK.
32
+
33
+ 7. Governing law and venue. This license, and any dispute arising out of or in connection with it, is governed
34
+ by the laws of the Republic of Estonia, excluding their conflict-of-laws rules. The courts of Estonia have
35
+ exclusive jurisdiction, with Harju County Court (Harju Maakohus) in Tallinn as the court of first instance,
36
+ except where mandatory law gives you the right to bring a claim elsewhere.
package/dist/ai/index.js CHANGED
@@ -1,5 +1,5 @@
1
- /*! palbase 0.3.1 — Palbase SDK License (see LICENSE) */
2
- import{a as V}from"../chunks/XNRYSI7A.js";import{a as W}from"../chunks/6FQGUDBD.js";import{a as q,b as Y}from"../chunks/TV7W53F2.js";import{b as U,d as z}from"../chunks/MJPUCGXY.js";import"../chunks/4MOCDBZP.js";import"../chunks/VTNEPJRV.js";async function*Z(e){let t=e.getReader(),a=new TextDecoder,r="",o="",l="";try{for(;;){let{done:d,value:g}=await t.read();if(d)return;r+=a.decode(g,{stream:!0}).replace(/\r\n/g,`
1
+ /*! palbase 0.3.2 — Palbase SDK License (see LICENSE) */
2
+ import{a as V}from"../chunks/32BPNFZX.js";import{a as W}from"../chunks/CNRFJ7AK.js";import{a as q,b as Y}from"../chunks/TTKDWRP5.js";import{b as U,d as z}from"../chunks/HHSKJTI6.js";import"../chunks/HJVB6KIR.js";import"../chunks/YSZ2RSTS.js";async function*Z(e){let t=e.getReader(),a=new TextDecoder,r="",o="",l="";try{for(;;){let{done:d,value:g}=await t.read();if(d)return;r+=a.decode(g,{stream:!0}).replace(/\r\n/g,`
3
3
  `);for(let b=r.indexOf(`
4
4
  `);b>=0;b=r.indexOf(`
5
5
  `)){let v=r.slice(0,b);r=r.slice(b+1),v===""?(o!==""&&(yield{event:o,data:l}),o="",l=""):v.startsWith("event: ")?o=v.slice(7):v.startsWith("data: ")&&(l=v.slice(6))}}}finally{try{await t.cancel()}catch{}}}var se=/\s/;function M(e,t){for(;t<e.length&&se.test(e[t]);)t++;return t}function H(e,t){let a="";for(let r=t+1;r<e.length;r++){let o=e[r];if(o==='"')return{value:a,complete:!0,empty:!1,at:r+1};if(o!=="\\"){a+=o;continue}let l=e[r+1];if(l===void 0)break;if(l==="u"){let d=e.slice(r+2,r+6);if(d.length<4)break;a+=String.fromCharCode(Number.parseInt(d,16)),r+=5;continue}a+={n:`
@@ -1,2 +1,2 @@
1
- /*! palbase 0.3.1 — Palbase SDK License (see LICENSE) */
2
- import{ba as h,ea as d}from"../chunks/XOGEEZNP.js";import"../chunks/4UPL27ED.js";import"../chunks/FVIHTHHV.js";import"../chunks/XNRYSI7A.js";import"../chunks/6FQGUDBD.js";import"../chunks/TV7W53F2.js";import"../chunks/MJPUCGXY.js";import"../chunks/4MOCDBZP.js";import"../chunks/VTNEPJRV.js";import{binding as R,createDatabase as v}from"palgres";var b=new WeakMap;function q(l,e,n){if(!n?.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=n.schemas,s=b.get(l);s||b.set(l,s=new Map);let r=s.get(u);r||s.set(u,r=new Map);let o=e.role===e.serviceRole?"service":e.role==="anon"?"anon":"authenticated",f=o==="service"?{service:e.serviceRole}:{[o]:e.role,service:e.serviceRole},g=`${o}\0${e.role}\0${e.serviceRole}`,i=r.get(g);i||(i=v({sql:l,schemas:u,binding:R(0,!0),roles:f}),r.set(g,i));let w=JSON.parse(e.claimsJson),m=i.then(a=>a.request({role:o,claims:w},{diagnostics:n.diagnostics,signal:n.signal})),y=a=>new Proxy(()=>{},{apply:async(t,D,c)=>{let p=(await m).client;return a(p).apply(p,c)}});return{client:new Proxy({},{get(a,t){if(t!=="then")return t==="diagnostics"?()=>null:t==="asService"?()=>new Proxy({},{get:(D,c)=>c==="then"?void 0:y(p=>p.asService()[c])}):y(D=>D[t])}}),commit:async()=>(await m).commit(),rollback:async a=>(await m).rollback(a)}}export{h as createApp,q as createRequestDatabase,d as makeMemoryCache};
1
+ /*! palbase 0.3.2 — Palbase SDK License (see LICENSE) */
2
+ import{ba as h,ea as d}from"../chunks/QRWBXKEM.js";import"../chunks/QA3GIZMI.js";import"../chunks/33DZIPGE.js";import"../chunks/32BPNFZX.js";import"../chunks/CNRFJ7AK.js";import"../chunks/TTKDWRP5.js";import"../chunks/HHSKJTI6.js";import"../chunks/HJVB6KIR.js";import"../chunks/YSZ2RSTS.js";import{binding as R,createDatabase as v}from"palgres";var b=new WeakMap;function q(l,e,n){if(!n?.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=n.schemas,s=b.get(l);s||b.set(l,s=new Map);let r=s.get(u);r||s.set(u,r=new Map);let o=e.role===e.serviceRole?"service":e.role==="anon"?"anon":"authenticated",f=o==="service"?{service:e.serviceRole}:{[o]:e.role,service:e.serviceRole},g=`${o}\0${e.role}\0${e.serviceRole}`,i=r.get(g);i||(i=v({sql:l,schemas:u,binding:R(0,!0),roles:f}),r.set(g,i));let w=JSON.parse(e.claimsJson),m=i.then(a=>a.request({role:o,claims:w},{diagnostics:n.diagnostics,signal:n.signal})),y=a=>new Proxy(()=>{},{apply:async(t,D,c)=>{let p=(await m).client;return a(p).apply(p,c)}});return{client:new Proxy({},{get(a,t){if(t!=="then")return t==="diagnostics"?()=>null:t==="asService"?()=>new Proxy({},{get:(D,c)=>c==="then"?void 0:y(p=>p.asService()[c])}):y(D=>D[t])}}),commit:async()=>(await m).commit(),rollback:async a=>(await m).rollback(a)}}export{h as createApp,q as createRequestDatabase,d as makeMemoryCache};
@@ -1 +1 @@
1
- /*! palbase 0.3.1 — Palbase SDK License (see LICENSE) */
1
+ /*! palbase 0.3.2 — Palbase SDK License (see LICENSE) */
@@ -1,5 +1,5 @@
1
- /*! palbase 0.3.1 — Palbase SDK License (see LICENSE) */
2
- import{$ as C,A as T,B as Qe,C as Xe,D as Ze,E as et,F as rt,G as st,H as nt,I as at,J as ot,K as it,L as lt,M as ct,N as dt,O as ut,P as pt,Q as ht,R as Y,S as bt,T as mt,U as gt,V as ft,W as yt,X as wt,Y as Pt,Z as St,_ as vt,a as K,aa as kt,b as z,ba as B,c as G,ca as At,d as _e,da as Rt,e as Oe,f as Te,g as Ce,h as Be,i as Fe,j as Me,k as Ie,l as Le,m as $e,n as Ue,o as De,p as je,q as Ne,r as qe,s as Ve,t as We,u as Ke,v as ze,w as Ge,x as He,y as Je,z as Ye}from"../chunks/XOGEEZNP.js";import{b as Et}from"../chunks/INXQWVHU.js";import{a as E,b as H,c as J,e as h,f as tt,g as d}from"../chunks/4UPL27ED.js";import{a as j,g as Ee,h as xe,i as q,j as O,q as V,r as W}from"../chunks/FVIHTHHV.js";import"../chunks/XNRYSI7A.js";import{m as Re}from"../chunks/6FQGUDBD.js";import"../chunks/TV7W53F2.js";import{b as _}from"../chunks/MJPUCGXY.js";import"../chunks/4MOCDBZP.js";import"../chunks/VTNEPJRV.js";import"reflect-metadata";import{existsSync as er,writeFileSync as tr,writeSync as he}from"node:fs";import{createServer as rr}from"node:http";import{dirname as N,join as sr,resolve as nr}from"node:path";import{Readable as ar}from"node:stream";var xt=2e3,_t=1e4,Ot=/^[A-Za-z0-9_-]{1,64}$/,Tt=512,F=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??_t,this.shutdownMs=r.shutdownMs??xt,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:Ot.test(e.requestId)?e.requestId:e.requestId.replace(/[^A-Za-z0-9_-]/g,"_").slice(0,64)||"unnamed",source:"backend",endpoint:e.endpoint.slice(0,Tt),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 l=a.status,o=l??(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:l===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 Ct}from"node:crypto";import{bind as Bt,bunDriver as Ft,createDatabase as Mt,createSearchWorker as It,cutOff as Lt,forgetUser as $t,MigrationOpen as Ut,MigrationRefused as Dt,Migrator as ee,renewingBunPool as Q,VersionNotMigrated as jt}from"palgres";import{toModel as te}from"palgres/dsl";var Nt=["start","complete","rollback","plan","status"],qt=/^(deploy|cli:[^\u0000-\u001f\u007f]{1,200})$/u;function re(t){let e=t.PALBASE_DB_MIGRATE;if(!(e===void 0||e==="")){if(!Nt.includes(e))throw new Error(`[palbase] PALBASE_DB_MIGRATE is start, complete, rollback, plan or status, not ${e}`);return e}}function se(t){let e=Array.isArray(t.schemas)?t.schemas:[t.schemas];for(let r of e)if(r.name===C.name)throw new Error(`[palbase] db.schemas: the ${C.name} schema is the framework's own (its tables are migrated with the app's) \u2014 name the app's schema otherwise`);return[...e,C]}function L(t){return te(se(t))}function Vt(t){return t.tables.some(e=>e.search!==void 0)}function $(t){return t.tables.some(e=>!e.ignored&&e.columns.some(r=>r.user!==void 0&&!r.ignored))}function ne(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 Wt(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 X=5;function ae(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=Q(()=>new r.SQL({url:n,prepare:!1,max:s})),l=Q(()=>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:Ft(a,l),poolSize:s,close:async()=>{await a.close({timeout:X}),await l.close({timeout:X})}}}}function oe(t){return t==="rollback"?(d.info("[palbase] migrate rollback: this app declares no database; nothing of it to take back"),M(t,{state:"none"}),0):(d.error(`[palbase] migrate ${t}: this app declares no database \u2014 PalbaseFactory.create(\u2026, { db: { schemas } })`),1)}async function ie(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(!qt.test(n))return d.error("[palbase] PALBASE_DB_MIGRATION_BY is deploy, or cli:<who>"),1;let a=ae(t,ne(e)),l=a(s),o,c=i=>d.error(`[palbase] migrate ${r}: ${i}`);try{let i=L(t),u=new ee(l.pool,{log:p=>{/ is held by others | held by writers/.test(p)&&(o=p.trim()),d.info(p)},shadow:p=>{let g=new URL(s);g.pathname=`/${p}`;let P=a(g.toString());return{reserve:()=>P.pool.reserve(),end:()=>P.close()}},openedBy:n});if(r==="plan"){let p=await u.plan(i);return M(r,p),p.refusals.length>0?1:0}if(r==="status")return M(r,await u.status()),0;let m=r==="start"?await Kt(u,i,n):r==="complete"?await u.complete():await u.rollback();return d.info(`[palbase] migrate ${r}: done`,{result:m}),M(r,m),0}catch(i){return i instanceof Dt?(d.error(`[palbase] migrate ${r}: refused`,{refusals:i.refusals}),c(`refused \u2014 ${i.refusals.join("; ")}`),1):Lt(i)?(d.error(`[palbase] migrate ${r}: cut off; run again, it goes on from where it stopped`,{error:i}),c(`cut off \u2014 ${o??Z(i)}`),75):(d.error(`[palbase] migrate ${r}: failed`,{error:i}),c(`failed \u2014 ${Z(i)}`),1)}finally{await l.close().catch(()=>{})}}async function Kt(t,e,r){try{return await t.start(e)}catch(s){if(!(s instanceof Ut)||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)}}function M(t,e){process.stdout.write(`${JSON.stringify({palbase_migrate:t,result:e})}
1
+ /*! palbase 0.3.2 — Palbase SDK License (see LICENSE) */
2
+ import{$ as C,A as T,B as Qe,C as Xe,D as Ze,E as et,F as rt,G as st,H as nt,I as at,J as ot,K as it,L as lt,M as ct,N as dt,O as ut,P as pt,Q as ht,R as Y,S as bt,T as mt,U as gt,V as ft,W as yt,X as wt,Y as Pt,Z as St,_ as vt,a as K,aa as kt,b as z,ba as B,c as G,ca as At,d as _e,da as Rt,e as Oe,f as Te,g as Ce,h as Be,i as Fe,j as Me,k as Ie,l as Le,m as $e,n as Ue,o as De,p as je,q as Ne,r as qe,s as Ve,t as We,u as Ke,v as ze,w as Ge,x as He,y as Je,z as Ye}from"../chunks/QRWBXKEM.js";import{b as Et}from"../chunks/QD5XLRIJ.js";import{a as E,b as H,c as J,e as h,f as tt,g as d}from"../chunks/QA3GIZMI.js";import{a as j,g as Ee,h as xe,i as q,j as O,q as V,r as W}from"../chunks/33DZIPGE.js";import"../chunks/32BPNFZX.js";import{m as Re}from"../chunks/CNRFJ7AK.js";import"../chunks/TTKDWRP5.js";import{b as _}from"../chunks/HHSKJTI6.js";import"../chunks/HJVB6KIR.js";import"../chunks/YSZ2RSTS.js";import"reflect-metadata";import{existsSync as er,writeFileSync as tr,writeSync as he}from"node:fs";import{createServer as rr}from"node:http";import{dirname as N,join as sr,resolve as nr}from"node:path";import{Readable as ar}from"node:stream";var xt=2e3,_t=1e4,Ot=/^[A-Za-z0-9_-]{1,64}$/,Tt=512,F=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??_t,this.shutdownMs=r.shutdownMs??xt,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:Ot.test(e.requestId)?e.requestId:e.requestId.replace(/[^A-Za-z0-9_-]/g,"_").slice(0,64)||"unnamed",source:"backend",endpoint:e.endpoint.slice(0,Tt),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 l=a.status,o=l??(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:l===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 Ct}from"node:crypto";import{bind as Bt,bunDriver as Ft,createDatabase as Mt,createSearchWorker as It,cutOff as Lt,forgetUser as $t,MigrationOpen as Ut,MigrationRefused as Dt,Migrator as ee,renewingBunPool as Q,VersionNotMigrated as jt}from"palgres";import{toModel as te}from"palgres/dsl";var Nt=["start","complete","rollback","plan","status"],qt=/^(deploy|cli:[^\u0000-\u001f\u007f]{1,200})$/u;function re(t){let e=t.PALBASE_DB_MIGRATE;if(!(e===void 0||e==="")){if(!Nt.includes(e))throw new Error(`[palbase] PALBASE_DB_MIGRATE is start, complete, rollback, plan or status, not ${e}`);return e}}function se(t){let e=Array.isArray(t.schemas)?t.schemas:[t.schemas];for(let r of e)if(r.name===C.name)throw new Error(`[palbase] db.schemas: the ${C.name} schema is the framework's own (its tables are migrated with the app's) \u2014 name the app's schema otherwise`);return[...e,C]}function L(t){return te(se(t))}function Vt(t){return t.tables.some(e=>e.search!==void 0)}function $(t){return t.tables.some(e=>!e.ignored&&e.columns.some(r=>r.user!==void 0&&!r.ignored))}function ne(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 Wt(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 X=5;function ae(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=Q(()=>new r.SQL({url:n,prepare:!1,max:s})),l=Q(()=>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:Ft(a,l),poolSize:s,close:async()=>{await a.close({timeout:X}),await l.close({timeout:X})}}}}function oe(t){return t==="rollback"?(d.info("[palbase] migrate rollback: this app declares no database; nothing of it to take back"),M(t,{state:"none"}),0):(d.error(`[palbase] migrate ${t}: this app declares no database \u2014 PalbaseFactory.create(\u2026, { db: { schemas } })`),1)}async function ie(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(!qt.test(n))return d.error("[palbase] PALBASE_DB_MIGRATION_BY is deploy, or cli:<who>"),1;let a=ae(t,ne(e)),l=a(s),o,c=i=>d.error(`[palbase] migrate ${r}: ${i}`);try{let i=L(t),u=new ee(l.pool,{log:p=>{/ is held by others | held by writers/.test(p)&&(o=p.trim()),d.info(p)},shadow:p=>{let g=new URL(s);g.pathname=`/${p}`;let P=a(g.toString());return{reserve:()=>P.pool.reserve(),end:()=>P.close()}},openedBy:n});if(r==="plan"){let p=await u.plan(i);return M(r,p),p.refusals.length>0?1:0}if(r==="status")return M(r,await u.status()),0;let m=r==="start"?await Kt(u,i,n):r==="complete"?await u.complete():await u.rollback();return d.info(`[palbase] migrate ${r}: done`,{result:m}),M(r,m),0}catch(i){return i instanceof Dt?(d.error(`[palbase] migrate ${r}: refused`,{refusals:i.refusals}),c(`refused \u2014 ${i.refusals.join("; ")}`),1):Lt(i)?(d.error(`[palbase] migrate ${r}: cut off; run again, it goes on from where it stopped`,{error:i}),c(`cut off \u2014 ${o??Z(i)}`),75):(d.error(`[palbase] migrate ${r}: failed`,{error:i}),c(`failed \u2014 ${Z(i)}`),1)}finally{await l.close().catch(()=>{})}}async function Kt(t,e,r){try{return await t.start(e)}catch(s){if(!(s instanceof Ut)||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)}}function M(t,e){process.stdout.write(`${JSON.stringify({palbase_migrate:t,result:e})}
3
3
  `)}function Z(t){return(t instanceof Error?t.message:String(t)).split(`
4
4
  `)[0].slice(0,300)||(t instanceof Error?t.name:"unknown")}async function zt(t,e){try{return await new ee(t).plan(e)}catch{return}}var I=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?Gt(r):[" palbase db:plan says what it would change"]].join(`
5
5
  `)),this.name="SchemaNotPushed",this.digest=e,this.plan=r}};function Gt(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}async function le(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=se(t),l=te(a),o=ae(t,ne(e))(n);try{let c=await Bt(o.engine,l,{waitMs:s.onPlatform?6e4:0}).catch(async g=>{throw s.onPlatform||!(g instanceof jt)?g:new I(g.digest,await zt(o.pool,l))}),i=Ct("sha256",r).update("palgres page cursor").digest("hex"),u=t.embed??s.embed,m=await Mt({sql:o.engine,schemas:a,binding:c,cursorSecret:i,admission:Wt(o.poolSize),embed:u,log:g=>d.warn(`[palbase] ${g}`)}),p=Vt(l)?It({sql:o.engine,embed:u,log:g=>d.info(`[palbase] ${g}`)}):void 0;return{model:l,binding:c,app:m,requests:t.requests??"caller",forget:g=>$t(o.engine,c,l,g),...p?{search:p}:{},close:()=>o.close()}}catch(c){throw await o.close(),c}}function Ht(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 ce(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(Ht)}}}var Jt=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function de(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 l=t.projectId??e.PALBASE_PROJECT_ID??"";Jt.test(l)||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 i=(t.webhookSecret??e.PALBASE_WEBHOOK_SECRET)||void 0;if(r.needsWebhookSecret&&(c!==void 0||i!==void 0)&&!/^whsec_[0-9a-f]{64}$/.test(i??"")&&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
  `}var be=2e4,me=5e3,or=15e3,ir="/_palbase/health";function lr(t){let e=new Set,r=s=>{if(e.has(s))return!1;e.add(s);let n=T(s,K);return n?n.providers.some(a=>T(a,z)!==void 0&&T(a,G)===void 0)||n.imports.some(r):!1};return t.some(r)}var cr={async create(t,e={}){let r=Array.isArray(t)?t:[t],s=e.env??process.env,n=re(s);if(n!==void 0){let y=e.db?await ie(e.db,s,n):oe(n);throw process.exit(y),new U(y)}let a=s.PALBASE_CONTRACT_OUT;if(a){let y;try{y=await dr(r,e,s)}catch(S){throw he(2,`[palbase] the contract: ${S instanceof Error?S.message:String(S)}
11
11
  `),process.exit(1),new x}throw a==="/dev/stdout"?he(1,pe(y)):tr(a,`${y}
12
- `),process.exit(0),new x}let l=e.db?L(e.db):void 0,o=await W({env:s,url:e.palbase?.url,secretKey:e.palbase?.secretKey});o&&d.info(`[palbase] secrets: ${o.loaded.length} from the project's ${o.set} set${o.kept.length>0?`; ${o.kept.join(", ")} kept as the environment gives them`:""}`),o&&o.refused.length>0&&d.warn(`[palbase] secrets not set \u2014 names a process reads as its own, not the app's: ${o.refused.map(y=>JSON.stringify(y)).join(", ")}`);let c=lr(r)||l!==void 0&&$(l),i=de(e.palbase??{},s,{needsWebhookSecret:c});c&&i.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 u=j({url:i.url,secretKey:i.secretKey}),m=e.port??Number(s.PORT??"8080");if(!Number.isInteger(m)||m<0||m>65535)throw new Error(`[palbase] PORT is a port number, not ${String(e.port??s.PORT)}`);let p=e.db?await le(e.db,s,i.secretKey,{onPlatform:i.platformSecret!==void 0,embed:ce(u)}):void 0;p&&d.info(`[palbase] database: version ${p.binding.version}`);let g=p&&$(p.model)?{"user.deleted":[y=>ur(p,y)]}:void 0,P=i.platformSecret===void 0?void 0:{secret:i.platformSecret},v=e.requestTelemetry===!1?void 0:new F(u.analytics),b=()=>B({modules:r,verifier:new O({issuer:i.url,projectId:i.projectId,standing:q({url:i.url,secretKey:i.secretKey})}),server:u,webhookSecret:i.webhookSecret,env:s,projectId:i.projectId,telemetry:v,auth:e.auth,tokens:e.tokens,rateLimit:e.rateLimit,maxBodyBytes:e.bodyLimit,cors:e.cors,platform:P,events:g,database:p&&{app:p.app,requests:p.requests}}),f=b(),A=e.boot?.attempts??5,R=e.boot?.backoffMs??1e3;for(let y=1;;y++)try{await f.start();break}catch(S){if(y>=A)throw d.error(`[palbase] the app did not start after ${A} attempts`,{error:S}),S;d.warn(`[palbase] the app did not start (attempt ${y} of ${A}); trying again in ${R} ms`,{error:S}),await new Promise(Ae=>setTimeout(Ae,R)),R*=2,f=b()}return pr(f,u,m,e.host??"0.0.0.0",e.exitOnFatal??!0,p)}};async function dr(t,e,r){let s=nr(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=N(s);for(;!er(sr(n,"package.json"))&&N(n)!==n;)n=N(n);let{analyzeProject:a}=await import("../chunks/JF7KZUPL.js"),{routeContracts:l}=await import("../chunks/NTMO2LFH.js"),o=a(n,s);for(let u of o.warnings)d.warn(`[palbase] the contract: ${u}`);let c="https://contract.palbase.invalid",i=B({modules:t,verifier:new O({issuer:c,projectId:"contract",standing:()=>Promise.reject(new Error("the contract run serves nothing"))}),server:j({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 l(o.routes),errors:Y()},events:e.db&&$(L(e.db))?{"user.deleted":[]}:void 0});return JSON.stringify(i.contract(),null,2)}var x=class extends Error{constructor(){super("[palbase] the contract run ended"),this.name="ContractRunEnded"}},U=class extends Error{code;constructor(e){super(`[palbase] the migration run ended with ${e}`),this.name="MigrationRunEnded",this.code=e}};async function ur(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 pr(t,e,r,s,n,a){let l,o={on:!1},c=(b,f)=>new URL(b.url).pathname===ir&&b.method==="GET"?Promise.resolve(o.on?Response.json({ok:!1,stopping:!0},{status:503}):Response.json({ok:!0})):t.handle(b,f),i=rr((b,f)=>{hr(c,b,f,o).finally(()=>{o.on&&i.closeIdleConnections()})});i.keepAliveTimeout=29e4,i.headersTimeout=3e5;try{await new Promise((b,f)=>{i.once("error",f),i.listen(r,s,()=>b())})}catch(b){throw await t.stop(),await a?.close(),b}let u=i.address().port;d.info(`[palbase] serving ${t.routes.length} route(s) on :${u}`,{routes:t.routes}),a?.search?.start();let m=b=>l??=(async()=>{d.info("[palbase] stopping: finishing the requests in flight"),o.on=!0;let f=new Promise(R=>i.close(()=>R()));i.closeIdleConnections();let A=setTimeout(()=>i.closeAllConnections(),b);await f,clearTimeout(A),process.off("SIGINT",P),process.off("uncaughtException",v),process.off("unhandledRejection",v);try{await t.stop(),await a?.search?.stop(),await a?.close()}finally{process.off("SIGTERM",P)}})(),p=()=>m(be),g=!1,P=()=>{if(g){d.info("[palbase] stopping: told to stop again; the requests in flight are still being finished");return}g=!0;let b=setTimeout(()=>{d.error("[palbase] stopping took longer than it is given; the process ends"),process.exit(1)},be+or);b.unref(),p().then(()=>{clearTimeout(b),process.exit(0)},f=>{clearTimeout(b),d.error("[palbase] stopping failed; the process ends",{error:f}),process.exit(1)})},v=b=>{d.error("[palbase] the app crashed; stopping so the machine starts it again",{error:b});let f=setTimeout(()=>process.exit(1),me+1e3);m(me).finally(()=>{clearTimeout(f),process.exit(1)})};return process.on("SIGTERM",P),process.once("SIGINT",P),n&&(process.on("uncaughtException",v),process.on("unhandledRejection",v)),{routes:t.routes,palbase:e,port:u,handle:c,close:p}}async function hr(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 l=new Headers;for(let[m,p]of Object.entries(e.headers))if(p!==void 0)if(Array.isArray(p))for(let g of p)l.append(m,g);else l.set(m,p);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 i=new Request(a,{method:e.method,headers:l,body:o?ar.toWeb(e):void 0,duplex:"half",signal:c.signal}),u=await t(i,{remoteAddress:e.socket.remoteAddress});if(r.statusCode=u.status,u.headers.forEach((m,p)=>r.setHeader(p,m)),s.on&&r.setHeader("connection","close"),u.body)for await(let m of u.body)r.write(m);r.end()}catch(n){d.error("[palbase] the request could not be answered",{error:n}),r.headersSent||(r.statusCode=500),r.end()}}import{bigint as gs,boolean as fs,check as ys,date as ws,defineSchema as Ps,defineTable as Ss,enumType as vs,foreignKey as ks,index as As,integer as Rs,jsonb as Es,numeric as xs,ownedByUser as _s,policy as Os,raw as Ts,sqlType as Cs,text as Bs,timestamp as Fs,userRef as Ms,uuid as Is}from"palgres/dsl";import{increment as $s,now as Us}from"palgres";function k(t){if(t instanceof _)return{data:null,error:{code:t.code,message:t.message},status:t.status};throw t}async function w(t,e){try{let r=await t();return{data:await e(r.data),error:null,status:r.status}}catch(r){return k(r)}}var br=E("Secrets",{async get(t){if(V(t))return null;let e=process.env[t];return typeof e=="string"&&e!==""?e:null}}),mr=100,gr=1e3,fr=168*3600,yr={s:1,m:60,h:3600,d:86400};function wr(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)*yr[n]*1e3);return Math.ceil(r/1e3)}function ve(t,e,r){let s=`${h.url}/storage/public/${encodeURIComponent(t)}/${encodeURIComponent(e)}`;return r?`${s}?variant=${encodeURIComponent(r)}`:s}function ge(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,ve(t.bucket,t.path,e)]))}}function Pr(t){return{async upload(e,r,s){let n=s?.contentType??(r instanceof Blob&&r.type!==""?r.type:void 0);try{let a=await h.storage.putObject({path:{bucket:t,path:e},headers:s?.upsert?void 0:{"If-None-Match":"*"},body:r,contentType:n});return{data:ge(a.data),error:null,status:a.status}}catch(a){return a instanceof _&&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}:k(a)}},async download(e){try{let r=await h.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 k(r)}},getPublicUrl(e,r){return ve(t,e,r?.variant)},async createSignedUrl(e,r){let s=wr(r?.expiresIn);return s===void 0||s<1||s>fr?{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}:w(()=>h.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??mr,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=[],l,o=200;try{for(;a.length<s;){let c=Math.max(1,Math.min(gr,n+s-a.length)),i=await h.storage.listObjects({path:{bucket:t},query:{...e?{prefix:e}:{},limit:c,...l?{cursor:l}:{}}});o=i.status;for(let u of i.data.objects)n>0?n--:a.length<s&&a.push(ge(u));if(l=i.data.next_cursor,!l)break}}catch(c){return k(c)}return{data:a,error:null,status:o}},async remove(e){let r=[];for(let s of e){try{await h.storage.deleteObject({path:{bucket:t,path:s}})}catch(n){return k(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 w(()=>h.storage.moveObject({path:{bucket:t},body:{from:e,to:r}}),()=>{})},copy(e,r){return w(()=>h.storage.copyObject({path:{bucket:t},body:{from:e,to:r}}),()=>{})}}}var Sr={bucket:Pr},fe=t=>H("Storage",t,Sr),vr={bucket:t=>fe("bucket").bucket(t),buckets:new Proxy({},{get:(t,e)=>typeof e=="string"?fe("buckets").bucket(e):void 0})},kr=E("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 w(()=>h.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 w(()=>h.notify.sendEmail({body:{...n,to:e}}),o=>({...o.message_id!==void 0?{message_id:o.message_id}:{},...o.skipped?{skipped:!0}:{}}));let a=[],l=202;for(let o of e)try{let c=await h.notify.sendEmail({body:{...n,to:o}});l=c.status,a.push(c.data.message_id??null)}catch(c){return k(c)}return{data:{message_ids:a},error:null,status:l}}}}),ye=t=>typeof t=="boolean"?t:t!=null&&t!==0&&t!=="",we=t=>typeof t=="string"?{name:t}:null,Pe=t=>t==="override"?"user":"system",Ar=t=>t!==null&&typeof t=="object"&&!Array.isArray(t)&&("userId"in t||"properties"in t);function ke(){return J.getStore()?.userId}function D(t){let e=t&&"userId"in t?t.userId??void 0:ke();return w(()=>e?h.flags.getUserValues({path:{user_id:e}}):h.flags.getValues(),r=>r.values??{})}var Se={setOverrideForUser:(t,e,r)=>w(()=>h.flags.putUserValue({path:{user_id:t,key:e},body:{value:r}}),s=>({key:s.key,value:s.value,source:Pe(s.source)})),setOverridesForUser:(t,e)=>w(()=>h.flags.putUserValues({path:{user_id:t},body:{values:e}}),r=>({values:r.values??{}})),clearOverrideForUser:(t,e)=>w(()=>h.flags.deleteUserValue({path:{user_id:t,key:e}}),r=>({key:r.key,value:r.value,source:Pe(r.source)})),clearAllOverridesForUser:t=>w(()=>h.flags.deleteUserValues({path:{user_id:t}}),e=>({deleted:e.deleted})),batchSetOverrides:t=>w(()=>h.flags.batchUserValues({body:{operations:t.map(e=>({user_id:e.userId,values:e.values}))}}),e=>({applied:e.applied}))},Rr=E("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 D(e);return s.error?r(`${s.error.code}: ${s.error.message}`):ye(s.data[t])}catch(s){return r(s instanceof Error?s.message:String(s))}},async getVariant(t,e){let r=await D(e);return r.error?{data:null,error:r.error,status:r.status}:{data:we(r.data[t]),error:null,status:r.status}},async getAll(t){let e=await D(t);return e.error?{data:null,error:e.error,status:e.status}:{data:Object.entries(e.data).map(([r,s])=>{let n=we(s);return{name:r,enabled:ye(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):Ar(e)?a=e:e!==void 0&&(s=e,n=!0);let l=await D(a);if(l.error)return n?{data:s??null,error:null,status:l.status}:{data:null,error:l.error,status:l.status};let o=l.data[t];return{data:o===void 0?s??null:o,error:null,status:l.status}},async setOverride(t,e){let r=ke();return r?Se.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 Se}}),Er=E("Realtime",{broadcast(t,e,r){return w(()=>h.realtime.broadcast({body:{messages:[{topic:t,event:e,payload:r??{}}]}}),()=>{})},state:{set(t,e,r){return w(()=>h.realtime.writeState({body:{ops:[{topic:t,key:e,value:r}]}}),()=>{})},clear(t,e){return w(()=>h.realtime.writeState({body:{ops:[{topic:t,key:e,delete:!0}]}}),()=>{})}}});import{z as zs}from"zod";export{xe as AuthUnavailable,mt as BadRequest,Ie as Body,At as CACHE_MAX_TTL,Rt as Cache,We as Client,gt as Conflict,x as ContractRunEnded,_e as Controller,tt as Database,ft as DeadlockDetected,Fe as Delete,dt as DiError,Re as EVENT_TYPES,Rr as Flags,ht as Forbidden,Oe as Get,$e as Headers,yt as HttpError,ze as Injectable,Je as Job,d as Log,kt as MAX_BODY_BYTES,U as MigrationRunEnded,Ge as Module,wt as NotFound,kr as Notifications,He as On,st as OnAuthorize,it as OnEmpty,nt as OnFirst,at as OnJoin,ot as OnLeave,lt as OnMessage,je as OptionalUser,ut as PalError,h as Palbase,_ as PalbaseError,cr as PalbaseFactory,Ue as Param,Be as Patch,Te as Post,Ce as Put,Me as Query,Le as QueryParams,Er as Realtime,Ne as Req,qe as RequestId,Ke as Resolve,rt as Room,I as SchemaNotPushed,br as Secrets,Pt as SerializationFailure,vr as Storage,Ee as TokenError,O as TokenVerifier,St as TooManyRequests,Ve as TraceId,pt as Unauthorized,vt as UniqueViolation,Ze as Upload,et as UploadedObject,De as User,Ye as Webhook,gs as bigint,fs as boolean,ys as check,B as createApp,ws as date,bt as defineError,Ps as defineSchema,Ss as defineTable,vs as enumType,ks as foreignKey,Qe as getRegisteredControllers,Xe as getRoutes,ct as getWebhookManifest,$s as increment,As as index,Rs as integer,Es as jsonb,Us as now,xs as numeric,_s as ownedByUser,Os as policy,Ts as raw,Cs as sqlType,Et as t,Bs as text,Fs as timestamp,Ms as userRef,Is as uuid,zs as z};
12
+ `),process.exit(0),new x}let l=e.db?L(e.db):void 0,o=await W({env:s,url:e.palbase?.url,secretKey:e.palbase?.secretKey});o&&d.info(`[palbase] secrets: ${o.loaded.length} from the project's ${o.set} set${o.kept.length>0?`; ${o.kept.join(", ")} kept as the environment gives them`:""}`),o&&o.refused.length>0&&d.warn(`[palbase] secrets not set \u2014 names a process reads as its own, not the app's: ${o.refused.map(y=>JSON.stringify(y)).join(", ")}`);let c=lr(r)||l!==void 0&&$(l),i=de(e.palbase??{},s,{needsWebhookSecret:c});c&&i.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 u=j({url:i.url,secretKey:i.secretKey}),m=e.port??Number(s.PORT??"8080");if(!Number.isInteger(m)||m<0||m>65535)throw new Error(`[palbase] PORT is a port number, not ${String(e.port??s.PORT)}`);let p=e.db?await le(e.db,s,i.secretKey,{onPlatform:i.platformSecret!==void 0,embed:ce(u)}):void 0;p&&d.info(`[palbase] database: version ${p.binding.version}`);let g=p&&$(p.model)?{"user.deleted":[y=>ur(p,y)]}:void 0,P=i.platformSecret===void 0?void 0:{secret:i.platformSecret},v=e.requestTelemetry===!1?void 0:new F(u.analytics),b=()=>B({modules:r,verifier:new O({issuer:i.url,projectId:i.projectId,standing:q({url:i.url,secretKey:i.secretKey})}),server:u,webhookSecret:i.webhookSecret,env:s,projectId:i.projectId,telemetry:v,auth:e.auth,tokens:e.tokens,rateLimit:e.rateLimit,maxBodyBytes:e.bodyLimit,cors:e.cors,platform:P,events:g,database:p&&{app:p.app,requests:p.requests}}),f=b(),A=e.boot?.attempts??5,R=e.boot?.backoffMs??1e3;for(let y=1;;y++)try{await f.start();break}catch(S){if(y>=A)throw d.error(`[palbase] the app did not start after ${A} attempts`,{error:S}),S;d.warn(`[palbase] the app did not start (attempt ${y} of ${A}); trying again in ${R} ms`,{error:S}),await new Promise(Ae=>setTimeout(Ae,R)),R*=2,f=b()}return pr(f,u,m,e.host??"0.0.0.0",e.exitOnFatal??!0,p)}};async function dr(t,e,r){let s=nr(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=N(s);for(;!er(sr(n,"package.json"))&&N(n)!==n;)n=N(n);let{analyzeProject:a}=await import("../chunks/XUG2RG4F.js"),{routeContracts:l}=await import("../chunks/RHQ2NBCI.js"),o=a(n,s);for(let u of o.warnings)d.warn(`[palbase] the contract: ${u}`);let c="https://contract.palbase.invalid",i=B({modules:t,verifier:new O({issuer:c,projectId:"contract",standing:()=>Promise.reject(new Error("the contract run serves nothing"))}),server:j({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 l(o.routes),errors:Y()},events:e.db&&$(L(e.db))?{"user.deleted":[]}:void 0});return JSON.stringify(i.contract(),null,2)}var x=class extends Error{constructor(){super("[palbase] the contract run ended"),this.name="ContractRunEnded"}},U=class extends Error{code;constructor(e){super(`[palbase] the migration run ended with ${e}`),this.name="MigrationRunEnded",this.code=e}};async function ur(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 pr(t,e,r,s,n,a){let l,o={on:!1},c=(b,f)=>new URL(b.url).pathname===ir&&b.method==="GET"?Promise.resolve(o.on?Response.json({ok:!1,stopping:!0},{status:503}):Response.json({ok:!0})):t.handle(b,f),i=rr((b,f)=>{hr(c,b,f,o).finally(()=>{o.on&&i.closeIdleConnections()})});i.keepAliveTimeout=29e4,i.headersTimeout=3e5;try{await new Promise((b,f)=>{i.once("error",f),i.listen(r,s,()=>b())})}catch(b){throw await t.stop(),await a?.close(),b}let u=i.address().port;d.info(`[palbase] serving ${t.routes.length} route(s) on :${u}`,{routes:t.routes}),a?.search?.start();let m=b=>l??=(async()=>{d.info("[palbase] stopping: finishing the requests in flight"),o.on=!0;let f=new Promise(R=>i.close(()=>R()));i.closeIdleConnections();let A=setTimeout(()=>i.closeAllConnections(),b);await f,clearTimeout(A),process.off("SIGINT",P),process.off("uncaughtException",v),process.off("unhandledRejection",v);try{await t.stop(),await a?.search?.stop(),await a?.close()}finally{process.off("SIGTERM",P)}})(),p=()=>m(be),g=!1,P=()=>{if(g){d.info("[palbase] stopping: told to stop again; the requests in flight are still being finished");return}g=!0;let b=setTimeout(()=>{d.error("[palbase] stopping took longer than it is given; the process ends"),process.exit(1)},be+or);b.unref(),p().then(()=>{clearTimeout(b),process.exit(0)},f=>{clearTimeout(b),d.error("[palbase] stopping failed; the process ends",{error:f}),process.exit(1)})},v=b=>{d.error("[palbase] the app crashed; stopping so the machine starts it again",{error:b});let f=setTimeout(()=>process.exit(1),me+1e3);m(me).finally(()=>{clearTimeout(f),process.exit(1)})};return process.on("SIGTERM",P),process.once("SIGINT",P),n&&(process.on("uncaughtException",v),process.on("unhandledRejection",v)),{routes:t.routes,palbase:e,port:u,handle:c,close:p}}async function hr(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 l=new Headers;for(let[m,p]of Object.entries(e.headers))if(p!==void 0)if(Array.isArray(p))for(let g of p)l.append(m,g);else l.set(m,p);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 i=new Request(a,{method:e.method,headers:l,body:o?ar.toWeb(e):void 0,duplex:"half",signal:c.signal}),u=await t(i,{remoteAddress:e.socket.remoteAddress});if(r.statusCode=u.status,u.headers.forEach((m,p)=>r.setHeader(p,m)),s.on&&r.setHeader("connection","close"),u.body)for await(let m of u.body)r.write(m);r.end()}catch(n){d.error("[palbase] the request could not be answered",{error:n}),r.headersSent||(r.statusCode=500),r.end()}}import{bigint as gs,boolean as fs,check as ys,date as ws,defineSchema as Ps,defineTable as Ss,enumType as vs,foreignKey as ks,index as As,integer as Rs,jsonb as Es,numeric as xs,ownedByUser as _s,policy as Os,raw as Ts,sqlType as Cs,text as Bs,timestamp as Fs,userRef as Ms,uuid as Is}from"palgres/dsl";import{increment as $s,now as Us}from"palgres";function k(t){if(t instanceof _)return{data:null,error:{code:t.code,message:t.message},status:t.status};throw t}async function w(t,e){try{let r=await t();return{data:await e(r.data),error:null,status:r.status}}catch(r){return k(r)}}var br=E("Secrets",{async get(t){if(V(t))return null;let e=process.env[t];return typeof e=="string"&&e!==""?e:null}}),mr=100,gr=1e3,fr=168*3600,yr={s:1,m:60,h:3600,d:86400};function wr(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)*yr[n]*1e3);return Math.ceil(r/1e3)}function ve(t,e,r){let s=`${h.url}/storage/public/${encodeURIComponent(t)}/${encodeURIComponent(e)}`;return r?`${s}?variant=${encodeURIComponent(r)}`:s}function ge(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,ve(t.bucket,t.path,e)]))}}function Pr(t){return{async upload(e,r,s){let n=s?.contentType??(r instanceof Blob&&r.type!==""?r.type:void 0);try{let a=await h.storage.putObject({path:{bucket:t,path:e},headers:s?.upsert?void 0:{"If-None-Match":"*"},body:r,contentType:n});return{data:ge(a.data),error:null,status:a.status}}catch(a){return a instanceof _&&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}:k(a)}},async download(e){try{let r=await h.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 k(r)}},getPublicUrl(e,r){return ve(t,e,r?.variant)},async createSignedUrl(e,r){let s=wr(r?.expiresIn);return s===void 0||s<1||s>fr?{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}:w(()=>h.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??mr,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=[],l,o=200;try{for(;a.length<s;){let c=Math.max(1,Math.min(gr,n+s-a.length)),i=await h.storage.listObjects({path:{bucket:t},query:{...e?{prefix:e}:{},limit:c,...l?{cursor:l}:{}}});o=i.status;for(let u of i.data.objects)n>0?n--:a.length<s&&a.push(ge(u));if(l=i.data.next_cursor,!l)break}}catch(c){return k(c)}return{data:a,error:null,status:o}},async remove(e){let r=[];for(let s of e){try{await h.storage.deleteObject({path:{bucket:t,path:s}})}catch(n){return k(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 w(()=>h.storage.moveObject({path:{bucket:t},body:{from:e,to:r}}),()=>{})},copy(e,r){return w(()=>h.storage.copyObject({path:{bucket:t},body:{from:e,to:r}}),()=>{})}}}var Sr={bucket:Pr},fe=t=>H("Storage",t,Sr),vr={bucket:t=>fe("bucket").bucket(t),buckets:new Proxy({},{get:(t,e)=>typeof e=="string"?fe("buckets").bucket(e):void 0})},kr=E("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 w(()=>h.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 w(()=>h.notify.sendEmail({body:{...n,to:e}}),o=>({...o.message_id!==void 0?{message_id:o.message_id}:{},...o.skipped?{skipped:!0}:{}}));let a=[],l=202;for(let o of e)try{let c=await h.notify.sendEmail({body:{...n,to:o}});l=c.status,a.push(c.data.message_id??null)}catch(c){return k(c)}return{data:{message_ids:a},error:null,status:l}}}}),ye=t=>typeof t=="boolean"?t:t!=null&&t!==0&&t!=="",we=t=>typeof t=="string"?{name:t}:null,Pe=t=>t==="override"?"user":"system",Ar=t=>t!==null&&typeof t=="object"&&!Array.isArray(t)&&("userId"in t||"properties"in t);function ke(){return J.getStore()?.userId}function D(t){let e=t&&"userId"in t?t.userId??void 0:ke();return w(()=>e?h.flags.getUserValues({path:{user_id:e}}):h.flags.getValues(),r=>r.values??{})}var Se={setOverrideForUser:(t,e,r)=>w(()=>h.flags.putUserValue({path:{user_id:t,key:e},body:{value:r}}),s=>({key:s.key,value:s.value,source:Pe(s.source)})),setOverridesForUser:(t,e)=>w(()=>h.flags.putUserValues({path:{user_id:t},body:{values:e}}),r=>({values:r.values??{}})),clearOverrideForUser:(t,e)=>w(()=>h.flags.deleteUserValue({path:{user_id:t,key:e}}),r=>({key:r.key,value:r.value,source:Pe(r.source)})),clearAllOverridesForUser:t=>w(()=>h.flags.deleteUserValues({path:{user_id:t}}),e=>({deleted:e.deleted})),batchSetOverrides:t=>w(()=>h.flags.batchUserValues({body:{operations:t.map(e=>({user_id:e.userId,values:e.values}))}}),e=>({applied:e.applied}))},Rr=E("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 D(e);return s.error?r(`${s.error.code}: ${s.error.message}`):ye(s.data[t])}catch(s){return r(s instanceof Error?s.message:String(s))}},async getVariant(t,e){let r=await D(e);return r.error?{data:null,error:r.error,status:r.status}:{data:we(r.data[t]),error:null,status:r.status}},async getAll(t){let e=await D(t);return e.error?{data:null,error:e.error,status:e.status}:{data:Object.entries(e.data).map(([r,s])=>{let n=we(s);return{name:r,enabled:ye(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):Ar(e)?a=e:e!==void 0&&(s=e,n=!0);let l=await D(a);if(l.error)return n?{data:s??null,error:null,status:l.status}:{data:null,error:l.error,status:l.status};let o=l.data[t];return{data:o===void 0?s??null:o,error:null,status:l.status}},async setOverride(t,e){let r=ke();return r?Se.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 Se}}),Er=E("Realtime",{broadcast(t,e,r){return w(()=>h.realtime.broadcast({body:{messages:[{topic:t,event:e,payload:r??{}}]}}),()=>{})},state:{set(t,e,r){return w(()=>h.realtime.writeState({body:{ops:[{topic:t,key:e,value:r}]}}),()=>{})},clear(t,e){return w(()=>h.realtime.writeState({body:{ops:[{topic:t,key:e,delete:!0}]}}),()=>{})}}});import{z as zs}from"zod";export{xe as AuthUnavailable,mt as BadRequest,Ie as Body,At as CACHE_MAX_TTL,Rt as Cache,We as Client,gt as Conflict,x as ContractRunEnded,_e as Controller,tt as Database,ft as DeadlockDetected,Fe as Delete,dt as DiError,Re as EVENT_TYPES,Rr as Flags,ht as Forbidden,Oe as Get,$e as Headers,yt as HttpError,ze as Injectable,Je as Job,d as Log,kt as MAX_BODY_BYTES,U as MigrationRunEnded,Ge as Module,wt as NotFound,kr as Notifications,He as On,st as OnAuthorize,it as OnEmpty,nt as OnFirst,at as OnJoin,ot as OnLeave,lt as OnMessage,je as OptionalUser,ut as PalError,h as Palbase,_ as PalbaseError,cr as PalbaseFactory,Ue as Param,Be as Patch,Te as Post,Ce as Put,Me as Query,Le as QueryParams,Er as Realtime,Ne as Req,qe as RequestId,Ke as Resolve,rt as Room,I as SchemaNotPushed,br as Secrets,Pt as SerializationFailure,vr as Storage,Ee as TokenError,O as TokenVerifier,St as TooManyRequests,Ve as TraceId,pt as Unauthorized,vt as UniqueViolation,Ze as Upload,et as UploadedObject,De as User,Ye as Webhook,gs as bigint,fs as boolean,ys as check,B as createApp,ws as date,bt as defineError,Ps as defineSchema,Ss as defineTable,vs as enumType,ks as foreignKey,Qe as getRegisteredControllers,Xe as getRoutes,ct as getWebhookManifest,$s as increment,As as index,Rs as integer,Es as jsonb,Us as now,xs as numeric,_s as ownedByUser,Os as policy,Ts as raw,Cs as sqlType,Et as t,Bs as text,Fs as timestamp,Ms as userRef,Is as uuid,zs as z};
@@ -1 +1 @@
1
- /*! palbase 0.3.1 — Palbase SDK License (see LICENSE) */
1
+ /*! palbase 0.3.2 — Palbase SDK License (see LICENSE) */
@@ -1,2 +1,2 @@
1
- /*! palbase 0.3.1 — Palbase SDK License (see LICENSE) */
2
- import{a as k,b as $,c as R,d as E}from"../chunks/4K4MKD2J.js";import{a as h}from"../chunks/INXQWVHU.js";import{c as m}from"../chunks/4UPL27ED.js";import"../chunks/4MOCDBZP.js";import"../chunks/VTNEPJRV.js";import"reflect-metadata";import{randomUUID as C}from"node:crypto";import{createFakeClient as O,typedDatabase as b}from"palgres/testing";function x(t,r,n){if(n?.acceptLanguage!==void 0&&n.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:o,...i}=t,e=n?.strings;return m.run({requestId:`test_${C()}`,database:o===void 0?void 0:b(o),services:i,...e!==void 0?{strings:e,locales:h(n?.acceptLanguage??null,e.source),usedLocales:[]}:{}},r)}function D(){let t=new Map,r=new Map,n=[],o=e=>{if(t.has(e))return t.get(e);if(r.has(e))return r.get(e);if(n.includes(e)){let a=[...n.slice(n.indexOf(e)),e].map(c=>c.name??String(c));throw new TypeError(`isolated(): ${a.join(" \u2192 ")} needs itself to be built \u2014 give one of them with .with(Token, value)`)}n.push(e);try{let a=Reflect.getMetadata("design:paramtypes",e)??[],c=new e(...a.map(o));return r.set(e,c),c}finally{n.pop()}},i={with(e,a){return t.set(e,a),i},get:e=>o(e)};return i}function F(){let t=O();return{db:b(t),raw:t,queries:t.queries,seed:(r,n)=>t.seed(r,n),inserted:r=>t.inserted(r),updated:r=>t.updated(r),deleted:r=>t.deleted(r)}}import{lstat as N,readdir as j,readFile as L}from"node:fs/promises";import{join as T}from"node:path";var l="palbase/strings",u="_meta.json",f=t=>typeof t=="object"&&t!==null&&!Array.isArray(t);function S(t){try{return Intl.getCanonicalLocales(t),!0}catch{return!1}}function v(t,r){try{return JSON.parse(t)}catch(n){throw new Error(`${r} is not JSON: ${n.message}`)}}async function I(t){let r=T(t,l);try{if(!(await N(r)).isDirectory())throw new Error(`${l} is not a directory: the strings live in a directory of their own`)}catch(s){if(s.code==="ENOENT")return;throw s}let n=new Map;for(let s of await j(r,{withFileTypes:!0}))if(!(s.name.startsWith(".")||!s.name.endsWith(".json"))){if(!s.isFile())throw new Error(`${l}/${s.name} is not a regular file`);n.set(s.name,await L(T(r,s.name),"utf8"))}if(n.size===0)return;let o=n.get(u);if(o===void 0)throw new Error(`${l}/${u} is missing: it names the source language, and without it the language files are not a table`);let i=v(o,`${l}/${u}`);if(!f(i)||i.version!==2)throw new Error(`${l}/${u}: version ${JSON.stringify(f(i)?i.version:i)} is not one this reads (2)`);let e=i.source;if(typeof e!="string"||e===""||!S(e))throw new Error(`${l}/${u}: source ${JSON.stringify(e)} is not a language tag`);let a={},c=[];Object.setPrototypeOf(a,null);for(let s of[...n.keys()].sort()){if(s===u)continue;let g=s.slice(0,-5),d=`${l}/${s}`;if(g===""||!S(g))throw new Error(`${d}: ${JSON.stringify(g)} is not a language tag`);if(g===e)throw new Error(`${d}: ${g} is the source language \u2014 its text is the key itself, and it has no file`);let w=v(n.get(s),d);if(!f(w))throw new Error(`${d}: not a JSON object`);for(let[y,p]of Object.entries(w)){if(!f(p)||typeof p.value!="string"||typeof p.state!="string")throw new Error(`${d}: key ${JSON.stringify(y)} is not {"value": string, "state": string}`);(a[y]??={})[g]={value:p.value,state:p.state}}c.push(g)}return{version:1,source:e,locales:[e,...c],strings:a}}export{k as TestApiError,E as api,$ as createTestApi,F as fakeDatabase,D as isolated,I as loadStringsTable,R as testRun,x as withServices};
1
+ /*! palbase 0.3.2 — Palbase SDK License (see LICENSE) */
2
+ import{a as k,b as $,c as R,d as E}from"../chunks/JFWH2INT.js";import{a as h}from"../chunks/QD5XLRIJ.js";import{c as m}from"../chunks/QA3GIZMI.js";import"../chunks/HJVB6KIR.js";import"../chunks/YSZ2RSTS.js";import"reflect-metadata";import{randomUUID as C}from"node:crypto";import{createFakeClient as O,typedDatabase as b}from"palgres/testing";function x(t,r,n){if(n?.acceptLanguage!==void 0&&n.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:o,...i}=t,e=n?.strings;return m.run({requestId:`test_${C()}`,database:o===void 0?void 0:b(o),services:i,...e!==void 0?{strings:e,locales:h(n?.acceptLanguage??null,e.source),usedLocales:[]}:{}},r)}function D(){let t=new Map,r=new Map,n=[],o=e=>{if(t.has(e))return t.get(e);if(r.has(e))return r.get(e);if(n.includes(e)){let a=[...n.slice(n.indexOf(e)),e].map(c=>c.name??String(c));throw new TypeError(`isolated(): ${a.join(" \u2192 ")} needs itself to be built \u2014 give one of them with .with(Token, value)`)}n.push(e);try{let a=Reflect.getMetadata("design:paramtypes",e)??[],c=new e(...a.map(o));return r.set(e,c),c}finally{n.pop()}},i={with(e,a){return t.set(e,a),i},get:e=>o(e)};return i}function F(){let t=O();return{db:b(t),raw:t,queries:t.queries,seed:(r,n)=>t.seed(r,n),inserted:r=>t.inserted(r),updated:r=>t.updated(r),deleted:r=>t.deleted(r)}}import{lstat as N,readdir as j,readFile as L}from"node:fs/promises";import{join as T}from"node:path";var l="palbase/strings",u="_meta.json",f=t=>typeof t=="object"&&t!==null&&!Array.isArray(t);function S(t){try{return Intl.getCanonicalLocales(t),!0}catch{return!1}}function v(t,r){try{return JSON.parse(t)}catch(n){throw new Error(`${r} is not JSON: ${n.message}`)}}async function I(t){let r=T(t,l);try{if(!(await N(r)).isDirectory())throw new Error(`${l} is not a directory: the strings live in a directory of their own`)}catch(s){if(s.code==="ENOENT")return;throw s}let n=new Map;for(let s of await j(r,{withFileTypes:!0}))if(!(s.name.startsWith(".")||!s.name.endsWith(".json"))){if(!s.isFile())throw new Error(`${l}/${s.name} is not a regular file`);n.set(s.name,await L(T(r,s.name),"utf8"))}if(n.size===0)return;let o=n.get(u);if(o===void 0)throw new Error(`${l}/${u} is missing: it names the source language, and without it the language files are not a table`);let i=v(o,`${l}/${u}`);if(!f(i)||i.version!==2)throw new Error(`${l}/${u}: version ${JSON.stringify(f(i)?i.version:i)} is not one this reads (2)`);let e=i.source;if(typeof e!="string"||e===""||!S(e))throw new Error(`${l}/${u}: source ${JSON.stringify(e)} is not a language tag`);let a={},c=[];Object.setPrototypeOf(a,null);for(let s of[...n.keys()].sort()){if(s===u)continue;let g=s.slice(0,-5),d=`${l}/${s}`;if(g===""||!S(g))throw new Error(`${d}: ${JSON.stringify(g)} is not a language tag`);if(g===e)throw new Error(`${d}: ${g} is the source language \u2014 its text is the key itself, and it has no file`);let w=v(n.get(s),d);if(!f(w))throw new Error(`${d}: not a JSON object`);for(let[y,p]of Object.entries(w)){if(!f(p)||typeof p.value!="string"||typeof p.state!="string")throw new Error(`${d}: key ${JSON.stringify(y)} is not {"value": string, "state": string}`);(a[y]??={})[g]={value:p.value,state:p.state}}c.push(g)}return{version:1,source:e,locales:[e,...c],strings:a}}export{k as TestApiError,E as api,$ as createTestApi,F as fakeDatabase,D as isolated,I as loadStringsTable,R as testRun,x as withServices};
@@ -1,2 +1,2 @@
1
- /*! palbase 0.3.1 — Palbase SDK License (see LICENSE) */
1
+ /*! palbase 0.3.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};
@@ -0,0 +1,2 @@
1
+ /*! palbase 0.3.2 — Palbase SDK License (see LICENSE) */
2
+ import{a as D}from"./32BPNFZX.js";import{a as A,b as R,c as b,d as x,e as O,f as j,g as M,h as U,i as C,j as L,k as K,l as $}from"./CNRFJ7AK.js";import{a as N,b as I}from"./TTKDWRP5.js";import{b as v,d as w}from"./HHSKJTI6.js";var ae=/^pb_[a-z0-9]+_s/;function E(n){if(D())throw new TypeError("palbase/server runs on a server: its secret key never goes into a browser or a mobile app \u2014 apps use palbase/web (or the native SDKs) with the publishable key");if(typeof n.secretKey!="string"||!ae.test(n.secretKey))throw new TypeError("secretKey is the project secret key (pb_<ref>_s\u2026); a publishable key belongs in palbase/web");let e=I(w({baseUrl:n.url,credentials:{secretKey:n.secretKey},fetch:n.fetch,solveProofOfWork:n.solveProofOfWork??!1}),n.retry??N);return{ai:A.client(e),analytics:R.client(e),auth:b.client(e),cache:x.client(e),flags:O.client(e),machines:j.client(e),notify:M.client(e),purchases:U.client(e),realtime:C.client(e),secrets:L.client(e),storage:K.client(e),stores:$.client(e),transport:e,url:new URL(n.url).origin}}var f=class extends Error{code;constructor(e,t){super(t),this.name="WebhookSignatureError",this.code=e}},ue=300,de=/^[0-9]{1,12}$/,le=/^[0-9a-f]{64}$/,W=8,fe=/^whsec_[0-9A-Za-z]{32,}$/,he=1024*1024;async function B(n){if(typeof n.secret!="string"||!fe.test(n.secret))throw new TypeError("secret is the webhook endpoint secret (whsec_\u2026), not an API key");await F(n);let e;try{e=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(z(n.body)))}catch{throw new f("invalid_body","the signed body is not JSON")}if(!be(e))throw new f("invalid_body","the signed body is not a Palbase event (id, type, project_id, created_at, data)");return e}async function F(n){if(typeof n.secret!="string"||n.secret==="")throw new TypeError("secret is the key the request was signed with");let e=z(n.body),{t,v1:r}=H(n),s=await crypto.subtle.importKey("raw",new TextEncoder().encode(n.secret),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),o=new Uint8Array(await crypto.subtle.sign("HMAC",s,we(new TextEncoder().encode(`${t}.`),e))),a=!1;for(let u of r)me(o,ge(u))&&(a=!0);if(!a)throw new f("signature_mismatch","no v1 in Palbase-Signature is this body signed with this secret")}function H(n){let e=n.toleranceSeconds??ue;if(!Number.isFinite(e)||e<0)throw new TypeError(`toleranceSeconds is a number of seconds, 0 or more (got ${String(n.toleranceSeconds)})`);let t=(n.now??Date.now)();if(!Number.isFinite(t))throw new TypeError(`now() returns epoch milliseconds (got ${String(t)})`);let r=n.signature;if(typeof r!="string"||r.trim()==="")throw new f("missing_signature","the request carries no Palbase-Signature header");let s,o=[];for(let a of r.split(",")){let u=a.indexOf("=");if(u<=0)throw new f("malformed_signature","Palbase-Signature is t=<seconds>,v1=<hex>");let c=a.slice(0,u).trim(),i=a.slice(u+1).trim();if(c==="t"){if(s!==void 0||!de.test(i))throw new f("malformed_signature","Palbase-Signature carries one t, in unix seconds");s=i}else if(c==="v1"){if(!le.test(i))throw new f("malformed_signature","a v1 is 64 lowercase hex characters");if(o.length===W)throw new f("malformed_signature",`Palbase-Signature carries at most ${W} v1`);o.push(i)}}if(s===void 0||o.length===0)throw new f("malformed_signature","Palbase-Signature is t=<seconds>,v1=<hex>");if(Math.abs(t/1e3-Number(s))>e)throw new f("stale_timestamp",`the signature's time is more than ${e} s from now: an old delivery sent again is not taken`);return{t:s,v1:o}}async function pe(n,e,t={}){let r=await ye(n,t.maxBytes??he);return B({toleranceSeconds:t.toleranceSeconds,now:t.now,secret:e,signature:n.headers.get("palbase-signature"),body:r})}async function ye(n,e){let t=()=>new f("body_too_large",`the body is larger than ${e} bytes`),r=Number(n.headers.get("content-length")??"NaN");if(Number.isFinite(r)&&r>e)throw t();if(!n.body)return new Uint8Array(0);let s=n.body.getReader(),o=[],a=0;for(;;){let{done:i,value:l}=await s.read();if(i)break;if(a+=l.byteLength,a>e)throw await s.cancel().catch(()=>{}),t();o.push(l)}let u=new Uint8Array(a),c=0;for(let i of o)u.set(i,c),c+=i.byteLength;return u}function z(n){if(typeof n=="string")return new TextEncoder().encode(n);if(n instanceof Uint8Array)return n;if(n instanceof ArrayBuffer)return new Uint8Array(n);throw new TypeError("body is the raw request body (string or bytes): a parsed object is not what was signed \u2014 read the body before any JSON middleware")}function ge(n){let e=new Uint8Array(n.length/2);for(let t=0;t<e.length;t++)e[t]=parseInt(n.slice(t*2,t*2+2),16);return e}function me(n,e){if(n.byteLength!==e.byteLength)return!1;let t=0;for(let r=0;r<n.byteLength;r++)t|=n[r]^e[r];return t===0}function we(n,e){let t=new Uint8Array(n.byteLength+e.byteLength);return t.set(n,0),t.set(e,n.byteLength),t}function be(n){if(typeof n!="object"||n===null)return!1;let e=n;return typeof e.id=="string"&&typeof e.type=="string"&&typeof e.project_id=="string"&&typeof e.created_at=="string"&&"data"in e}var V=60,ke=60,Se=8*1024,ve=1e5;function _(n){let e=n instanceof Uint8Array?n:new Uint8Array(n),t="";for(let r of e)t+=String.fromCharCode(r);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function Y(n){let e=n.replace(/[\s=]+/g,"");if(!/^[A-Za-z0-9+/_-]*$/.test(e)||e.length%4===1)return;let t=atob(e.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(e.length/4)*4,"=")),r=new Uint8Array(t.length);for(let s=0;s<t.length;s++)r[s]=t.charCodeAt(s);return r}function J(n){let e=Y(n);if(e)try{let t=JSON.parse(new TextDecoder().decode(e));return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:void 0}catch{return}}var k=class{byKey=new Map;held=0;sweptAt=Number.NEGATIVE_INFINITY;max;constructor(e=ve){this.max=e}spend(e,t){if(t>=e.until)throw new d("proof","the DPoP proof is not taken: it was checked too long ago");let r=this.byKey.get(e.jkt);if(r){this.forgetOld(e.jkt,r,t);let s=r.get(e.jti);if(s!==void 0&&s>t)throw new d("proof","the DPoP proof is not taken: it was used before");s!==void 0&&r.delete(e.jti)&&this.held--}this.held>=this.max&&this.makeRoom(t),r=this.byKey.get(e.jkt),r||(r=new Map,this.byKey.set(e.jkt,r)),r.set(e.jti,e.until),this.held++}forgetOld(e,t,r){for(let[s,o]of t){if(o>r)break;t.delete(s),this.held--}t.size===0&&this.byKey.delete(e)}makeRoom(e){if(e-this.sweptAt>=1e3){this.sweptAt=e;for(let[r,s]of this.byKey){for(let[o,a]of s)a>e||(s.delete(o),this.held--);s.size===0&&this.byKey.delete(r)}this.held=0;for(let r of this.byKey.values())this.held+=r.size}if(this.held<this.max)return;let t=[...this.byKey].sort((r,s)=>s[1].size-r[1].size);for(let[r,s]of t){if(this.held<=this.max*.9)break;this.byKey.delete(r),this.held-=s.size}}};async function Ee(n,e){let t=`{"crv":"P-256","kty":"EC","x":"${n}","y":"${e}"}`;return _(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(t)))}function q(n){try{let e=new URL(n);return e.username!==""||e.password!==""?void 0:`${e.protocol}//${e.host}${e.pathname}`}catch{return}}async function G(n,e,t,r){let s=ie=>{throw new d("proof",`the DPoP proof is not taken: ${ie}`)},o=t.proof;if(!o)return s("there is none (a DPoP-bound token comes with a DPoP header)");if(o.length>Se)return s("it is too long");let a=o.split(".");if(a.length!==3)return s("it is not a JWS of three parts");let u=J(a[0]),c=J(a[1]);if(!u||!c)return s("its header or claims are not base64url JSON");if(u.typ!=="dpop+jwt")return s("its typ is not dpop+jwt");if(u.alg!=="ES256")return s(`it is signed with ${String(u.alg)}; only ES256 is taken`);let i=u.jwk;if(!i||typeof i!="object"||i.kty!=="EC"||i.crv!=="P-256"||typeof i.x!="string"||typeof i.y!="string")return s("its header carries no P-256 public key");if("d"in i)return s("its header carries a private key");if(await Ee(i.x,i.y)!==e)return s("it is signed by a key the token does not name");let l;try{l=await crypto.subtle.importKey("jwk",{kty:"EC",crv:"P-256",x:i.x,y:i.y,ext:!0},{name:"ECDSA",namedCurve:"P-256"},!1,["verify"])}catch{return s("its key is not a P-256 point")}let p=Y(a[2]);if(!p||!await crypto.subtle.verify({name:"ECDSA",hash:"SHA-256"},l,p,new TextEncoder().encode(`${a[0]}.${a[1]}`)).catch(()=>!1))return s("its signature does not verify");if(typeof c.htm!="string"||c.htm.toUpperCase()!==t.method.toUpperCase())return s(`it is for ${String(c.htm)}, not ${t.method}`);let h=typeof c.htu=="string"?q(c.htu):void 0,y=q(t.url);if(!h||!y||h!==y)return s(`it is for ${String(c.htu)}, not ${y??t.url}`);let re=r/1e3;if(typeof c.iat!="number"||Math.abs(c.iat-re)>V)return s("it was not made within a minute of now");let se=_(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(n)));if(c.ath!==se)return s("it is not for this token (ath)");if(typeof c.jti!="string"||c.jti===""||c.jti.length>256)return s("it has no jti (or one longer than 256)");let oe=_(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(c.jti)));return{jkt:e,jti:oe,until:(c.iat+V+ke)*1e3+1}}var d=class extends Error{reason;constructor(e,t){super(t),this.name="TokenError",this.reason=e}},g=class extends Error{constructor(e,t){super(e,t),this.name="AuthUnavailable"}};function _e(n){return async e=>{let t=b.client(w({baseUrl:n.url,credentials:{secretKey:n.secretKey,accessToken:()=>e},fetch:n.fetch}));try{return await t.verifyTokenUser(),!0}catch(r){if(r instanceof v&&r.status===401)return!1;throw r}}}var T={ES256:{kty:"EC",import:{name:"ECDSA",namedCurve:"P-256"},verify:{name:"ECDSA",hash:"SHA-256"}},PS256:{kty:"RSA",import:{name:"RSA-PSS",hash:"SHA-256"},verify:{name:"RSA-PSS",saltLength:32}}},X=60,Te=16*1024,Pe=10*6e4,Ae=5e4,Z=n=>typeof n=="string"&&Object.hasOwn(T,n),P=class{issuer;projectId;fetchImpl;now;maxKeyAgeMs;refetchIntervalMs;fetchTimeoutMs;standing;standingTtlMs;standingStaleMs;standings=new Map;asking=new Map;keys=new Map;keysUntil=0;lastFetch=Number.NEGATIVE_INFINITY;lastFailure=void 0;inflight=null;seenProofs=new k;constructor(e){let t=new URL(e.issuer);if(t.origin!==e.issuer.replace(/\/$/,""))throw new TypeError(`issuer is the project's origin (https://<ref>.<domain>), not ${e.issuer}`);if(typeof e.projectId!="string"||e.projectId==="")throw new TypeError("projectId is the project id the tokens carry");if(this.issuer=t.origin,this.projectId=e.projectId,this.fetchImpl=e.fetch??globalThis.fetch,this.now=e.now??Date.now,this.maxKeyAgeMs=e.maxKeyAgeMs??60*6e4,this.refetchIntervalMs=e.refetchIntervalMs??3e4,this.fetchTimeoutMs=e.fetchTimeoutMs??5e3,typeof e.standing!="function")throw new TypeError("standing is how the verifier asks whether a token's session stands");this.standing=e.standing,this.standingTtlMs=e.standingTtlMs??1e3,this.standingStaleMs=e.standingStaleMs??15e3}async verify(e,t){if(typeof e!="string"||e.length===0||e.length>Te)throw new d("malformed","the token is not a JWT");let r=e.split(".");if(r.length!==3)throw new d("malformed","the token is not a JWS of three parts");let s=Q(r[0]),o=Q(r[1]);if(!s||!o)throw new d("malformed","the token header or claims are not base64url JSON");let a=s.alg;if(!Z(a))throw new d("algorithm",`the token is signed with ${String(a)}; only ES256 and PS256 are taken`);let u=s.kid;if(typeof u!="string"||u==="")throw new d("malformed","the token header names no kid");let c=await this.key(u);if(!c)throw new d("unknown_key",`no key ${u} in the project's key set`);if(c.alg!==a)throw new d("algorithm",`key ${u} is ${c.alg}, the token says ${a}`);let i=te(r[2]);if(!i)throw new d("malformed","the signature is not base64url");let l=new TextEncoder().encode(`${r[0]}.${r[1]}`);if(!await crypto.subtle.verify(T[c.alg].verify,c.key,i,l).catch(()=>!1))throw new d("signature","the signature does not verify");let m=this.check(o),h=o.cnf,y;if(h!==void 0){if(!t)throw new d("bound","the token is bound to a key (DPoP): it comes with the DPoP scheme and a proof, not as a Bearer");if(typeof h!="object"||h===null||typeof h.jkt!="string"||h.jkt==="")throw new d("bound","the token is bound to a key it does not name (cnf.jkt)");y=await G(e,h.jkt,t,this.now())}else if(t)throw new d("not_bound","the DPoP scheme came with a token bound to no key");if(!await this.stands(e,m.sessionId))throw new d("session_ended","the token's session has ended (signed out, revoked, or its user banned)");return y&&this.seenProofs.spend(y,this.now()),m}async verifyRequest(e){let t=e.headers instanceof Headers?e.headers:xe(e.headers),r=t.get("authorization")??"";if(r==="")return null;let s=/^(bearer|dpop)\s+(\S+)$/i.exec(r);if(!s)throw new d("malformed","the Authorization header is not a Bearer or DPoP token");let o=s[1].toLowerCase()==="dpop",a=new URL(e.url,`http://${t.get("host")??"localhost"}`);return this.verify(s[2],o?{proof:t.get("dpop"),method:e.method,url:ee(t,a)}:void 0)}async stands(e,t){let r=this.now(),s=this.standings.get(t);if(s&&r<s.until)return s.live;let o=this.asking.get(t);o||(o=this.standing(e,t).finally(()=>this.asking.delete(t)),this.asking.set(t,o));let a;try{a=await o}catch(c){let i=this.standings.get(t),l=this.now();if(i&&l<i.at+this.standingStaleMs)return i.until=Math.min(l+this.standingTtlMs,i.at+this.standingStaleMs),i.live;throw new g("a session's standing cannot be read now",{cause:c})}let u=this.now();return this.standings.delete(t),this.standings.set(t,{live:a,at:u,until:u+this.standingTtlMs}),this.standings.size>Ae&&this.standings.delete(this.standings.keys().next().value),a}check(e){if(e.iss!==this.issuer)throw new d("issuer",`the token was issued by ${String(e.iss)}, not this project`);if(!(Array.isArray(e.aud)?e.aud:[e.aud]).includes(this.issuer))throw new d("audience","the token is not meant for this project");if(e.project_id!==this.projectId)throw new d("project","the token names another project");let r=this.now()/1e3;if(typeof e.exp!="number"||e.exp+X<=r)throw new d("expired","the token has expired");if(e.nbf!==void 0&&(typeof e.nbf!="number"||e.nbf-X>r))throw new d("not_yet_valid","the token is not valid yet");if(typeof e.sub!="string"||e.sub===""||typeof e.auth_time!="number")throw new d("not_a_user","the token is not a user's");if(typeof e.session_id!="string"||e.session_id==="")throw new d("not_a_session","the token is no session's");let s=e.custom_claims;if(s!==void 0&&(typeof s!="object"||s===null||s.type!==void 0))throw new d("not_a_session","the token is a custom one (an exchange or an approval), not a session's");return{id:e.sub,email:typeof e.email=="string"?e.email:null,emailVerified:e.email_verified===!0,role:typeof e.role=="string"?e.role:null,sessionId:typeof e.session_id=="string"?e.session_id:null,claims:Object.freeze({...e})}}async key(e){let t=this.now();if(t>=this.keysUntil){let s=this.keys.size>0&&t<this.keysUntil+Pe;if(this.lastFailure!==void 0&&t-this.lastFetch<this.refetchIntervalMs){if(!s)throw new g("the project's key set cannot be read now",{cause:this.lastFailure})}else try{await this.refresh()}catch(o){if(!s)throw o}}let r=this.keys.get(e);return!r&&t-this.lastFetch>=this.refetchIntervalMs&&(await this.refresh(),r=this.keys.get(e)),r}refresh(){if(this.inflight)return this.inflight;let e=this.load().finally(()=>{this.inflight=null});return this.inflight=e,e}async load(){this.lastFetch=this.now();let e,t;try{if(t=await this.fetchImpl(`${this.issuer}/.well-known/jwks.json`,{redirect:"error",headers:{accept:"application/json"},signal:AbortSignal.timeout(this.fetchTimeoutMs)}),!t.ok)throw new Error(`the project's key set answered ${t.status}`);e=await t.json()}catch(o){throw this.lastFailure=o,new g("the project's key set cannot be read now",{cause:o})}this.lastFailure=void 0;let r=new Map;for(let o of Array.isArray(e.keys)?e.keys:[]){let a=o.alg;if(typeof o.kid!="string"||!Z(a))continue;let u=T[a];if(o.kty!==u.kty||o.use!==void 0&&o.use!=="sig")continue;let{d:c,...i}=o;try{r.set(o.kid,{alg:a,key:await crypto.subtle.importKey("jwk",i,u.import,!1,["verify"])})}catch{}}this.keys=r;let s=Oe(t.headers.get("cache-control"))??this.maxKeyAgeMs;this.keysUntil=this.now()+Math.min(Math.max(s,this.refetchIntervalMs),this.maxKeyAgeMs)}};function ee(n,e){let t=n.get("x-forwarded-proto")?.split(",")[0]?.trim().toLowerCase(),r=t==="https"||t==="http"?t:e.protocol.slice(0,-1),s=n.get("host")??e.host;return Re.test(s)?`${r}://${s}${e.pathname}`:""}var Re=/^(?:[a-z0-9-]+(?:\.[a-z0-9-]+)*|\[[0-9a-f:.]+\])(?::[0-9]{1,5})?$/i;function xe(n){let e=new Headers;for(let[t,r]of Object.entries(n))if(r!==void 0)for(let s of Array.isArray(r)?r:[r])e.append(t,s);return e}function Oe(n){let e=/(?:^|,)\s*max-age=(\d+)/i.exec(n??"");return e?Number(e[1])*1e3:void 0}function te(n){if(!/^[A-Za-z0-9_-]*$/.test(n)||n.length%4===1)return null;let e=atob(n.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(n.length/4)*4,"=")),t=new Uint8Array(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return t}function Q(n){let e=te(n);if(!e)return null;try{let t=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(e));return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:null}catch{return null}}function je(n,e,t=Date.now()){let r=Object.hasOwn(n.entitlements,e)?n.entitlements[e]:void 0;return r?.active?r.expires_at===null?!0:Date.parse(r.expires_at)>(typeof t=="number"?t:t.getTime()):!1}var S=class extends Error{receipt;constructor(e){super(`the reservation ${JSON.stringify(e.idempotency_key)} is ${e.status} already: its job is not run again (a new one is a new Idempotency-Key)`),this.name="ReservationSettled",this.receipt=e}};async function Me(n,e,t,r){let{idempotencyKey:s,amount:o,ttlSeconds:a,metadata:u}=t;if(typeof s!="string"||s==="")throw new TypeError("idempotencyKey names the reservation for good: a retry with it is the same hold, never a second");let c={amount:o,...t.credits!==void 0?{credits:t.credits}:{limit:t.limit},...a!==void 0?{ttl_seconds:a}:{},...u!==void 0?{metadata:u}:{}},i=(await n.purchases.holdSpend({path:{customer_id:e},headers:{"Idempotency-Key":s},body:c})).data;if(i.status!=="held")throw new S(i);let l={customer_id:i.customer,spend_id:i.id},p;try{p=await r(i)}catch(m){throw await n.purchases.releaseSpend({path:l}).catch(()=>{}),m}return await n.purchases.commitSpend({path:l}),p}async function*Ue(n){let e,t=new Set;do{let r=(await n(e)).data;yield r;let s=r.next_cursor??void 0;if(s!==void 0&&t.has(s))throw new Error(`the listing answered a cursor it had answered before (${s})`);s!==void 0&&t.add(s),e=s}while(e)}var Ce=/^[A-Za-z_][A-Za-z0-9_]{0,127}$/,Le=/^(PALBASE_|NODE_|BUN_|NPM_|LD_|DYLD_|GIT_|SSH_)|^(PATH|HOME|SHELL|USER|TMPDIR|TMP|TEMP|PWD|IFS|ENV|BASH_ENV|SSL_CERT_FILE|SSL_CERT_DIR|CURL_CA_BUNDLE|REQUESTS_CA_BUNDLE|NO_PROXY|ALL_PROXY|HTTP_PROXY|HTTPS_PROXY|PG\w*)$/i;function ne(n){return!Ce.test(n)||Le.test(n)||/_PROXY$/i.test(n)}var Ke=/^(PORT|PALBASE_(URL|PROJECT_ID|REPLICAS|SECRET_KEY|WEBHOOK_SECRET|PLATFORM_SECRET|CONTRACT_OUT|SECRETS|DB_[A-Z0-9_]+))$/;function $e(n){return Ke.test(n)}async function Ne(n={}){let e=n.env??process.env,t=e.PALBASE_SECRETS;if(t===void 0||t==="")return;if(t!=="development"&&t!=="production")throw new TypeError(`PALBASE_SECRETS is development or production, not ${t}`);let r=n.url??e.PALBASE_URL??"",s=n.secretKey??e.PALBASE_SECRET_KEY??"";if(r===""||s==="")throw new TypeError("PALBASE_SECRETS reads the project's Secrets with PALBASE_URL and PALBASE_SECRET_KEY: give both (palbase env:pull writes them)");let o=E({url:new URL(r).origin,secretKey:s,fetch:n.fetch}),{data:a}=await o.secrets.getEnvironmentValues({path:{environment:t}}),u=[],c=[],i=[];for(let[l,p]of Object.entries(a.values)){if(ne(l)){i.push(l);continue}if(e[l]!==void 0&&e[l]!==""){c.push(l);continue}e[l]=p,u.push(l)}return{set:t,loaded:u.sort(),kept:c.sort(),refused:i.sort()}}export{E as a,f as b,B as c,F as d,H as e,pe as f,d as g,g as h,_e as i,P as j,ee as k,je as l,S as m,Me as n,Ue as o,ne as p,$e as q,Ne as r};
@@ -0,0 +1,92 @@
1
+ /*! palbase 0.3.2 — Palbase SDK License (see LICENSE) */
2
+ import{b as oe}from"./HHSKJTI6.js";var Jt=s=>[...new Uint8Array(s)].map(t=>t.toString(16).padStart(2,"0")).join(""),Ut=s=>`pw-font-${s}`;function ie(s){return(typeof s=="string"?/^asset:([0-9a-f-]{36})$/.exec(s):null)?.[1]}async function Ge(s,t={}){let n={},i=t.fetch??((p,l)=>globalThis.fetch(p,l));return await Promise.all(s.map(async p=>{try{if(!/^https:\/\//.test(p.url))return;let l=await i(p.url,{signal:t.signal,credentials:"omit"});if(!l.ok)return;let f=await l.arrayBuffer();if(f.byteLength!==p.bytes&&p.bytes>0||Jt(await globalThis.crypto.subtle.digest("SHA-256",f))!==p.sha256.toLowerCase())return;let g=Vt(p.kind,new Uint8Array(f));if(g===void 0)return;let h=await Bt(p,f,g,t);h&&(n[p.id]=h)}catch{}})),n}var F=(s,t,n=0)=>s.length>=n+t.length&&t.every((i,p)=>s[n+p]===i),q=s=>[...s].map(t=>t.charCodeAt(0));function Vt(s,t){switch(s){case"image":return F(t,[137,80,78,71,13,10,26,10])?"image/png":F(t,[255,216,255])?"image/jpeg":F(t,q("RIFF"))&&F(t,q("WEBP"),8)?"image/webp":void 0;case"video":return F(t,q("ftyp"),4)?F(t,q("qt "),8)?"video/quicktime":"video/mp4":F(t,[26,69,223,163])?"video/webm":void 0;case"font":return F(t,q("wOF2"))?"font/woff2":F(t,q("wOFF"))?"font/woff":F(t,q("OTTO"))?"font/otf":F(t,[0,1,0,0])||F(t,q("true"))?"font/ttf":void 0;case"html":return F(t,[80,75,3,4])||F(t,[80,75,5,6])?"application/zip":void 0;default:return}}async function Bt(s,t,n,i){switch(s.kind){case"image":case"video":return{kind:s.kind,url:URL.createObjectURL(new Blob([t],{type:n}))};case"font":{let p=Ut(s.id),l=globalThis.FontFace,f=i.fonts??globalThis.document?.fonts;if(!l||!f)return;let y=new l(p,t,{display:"block"});return await y.load(),f.add(y),{kind:"font",url:"",family:p}}case"html":{let p=await qt(new Uint8Array(t)),l=Yt(p);return l===void 0?void 0:{kind:"html",url:"",html:l}}}}async function qt(s){let t=new DataView(s.buffer,s.byteOffset,s.byteLength),n=-1;for(let y=s.length-22;y>=Math.max(0,s.length-22-65535);y--)if(t.getUint32(y,!0)===101010256){n=y;break}if(n<0)throw new Error("not a zip");let i=t.getUint16(n+10,!0),p=t.getUint32(n+16,!0),l=new Map,f=0;for(let y=0;y<i;y++){if(t.getUint32(p,!0)!==33639248)throw new Error("a broken zip");let g=t.getUint16(p+10,!0),h=t.getUint32(p+20,!0),w=t.getUint32(p+24,!0),v=t.getUint16(p+28,!0),M=t.getUint16(p+30,!0),x=t.getUint16(p+32,!0),R=t.getUint32(p+42,!0),b=new TextDecoder().decode(s.subarray(p+46,p+46+v));if(p+=46+v+M+x,b.endsWith("/"))continue;if(b.startsWith("/")||b.split("/").includes(".."))throw new Error("a path leaving the zip");if(f+=w,l.size>=200||f>20971520)throw new Error("a zip too large");let T=R+30+t.getUint16(R+26,!0)+t.getUint16(R+28,!0),C=s.subarray(T,T+h);if(g===0)l.set(b,C);else if(g===8)l.set(b,await Wt(C));else throw new Error("a zip entry compressed another way")}return l}async function Wt(s){let t=new Response(new Uint8Array(s)).body.pipeThrough(new DecompressionStream("deflate-raw"));return new Uint8Array(await new Response(t).arrayBuffer())}var Kt={html:"text/html",css:"text/css",js:"text/javascript",mjs:"text/javascript",json:"application/json",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",webp:"image/webp",gif:"image/gif",svg:"image/svg+xml",mp4:"video/mp4",webm:"video/webm",woff2:"font/woff2",woff:"font/woff",ttf:"font/ttf",otf:"font/otf"};function Ye(s,t){let n=Kt[s.split(".").pop()?.toLowerCase()??""]??"application/octet-stream",i="";for(let p=0;p<t.length;p+=32768)i+=String.fromCharCode(...t.subarray(p,p+32768));return`data:${n};base64,${btoa(i)}`}var Xt="default-src 'none'; img-src data:; media-src data:; font-src data:; style-src 'unsafe-inline' data:; script-src 'unsafe-inline' data:";function Yt(s){let t=s.get("index.html");if(!t)return;let n=new TextDecoder().decode(t),i=h=>new TextDecoder().decode(s.get(h)),p=h=>{let w=h.replace(/^\.\//,"").split(/[?#]/)[0];return s.has(w)?w:void 0},l=h=>h.replace(/url\(\s*(['"]?)([^'")]+)\1\s*\)/g,(w,v,M)=>{let x=p(M);return x?`url("${Ye(x,s.get(x))}")`:w}),f=globalThis.DOMParser;if(!f)return;let y=new f().parseFromString(n,"text/html");for(let h of[...y.querySelectorAll('link[rel~="stylesheet"][href]')]){let w=p(h.getAttribute("href")),v=y.createElement("style");v.textContent=w?l(i(w)):"",h.replaceWith(v)}for(let h of[...y.querySelectorAll("style")])h.textContent=l(h.textContent??"");for(let h of[...y.querySelectorAll("[src], [href], [poster]")])for(let w of["src","href","poster"]){let v=h.getAttribute(w);if(v===null)continue;let M=p(v);M?h.setAttribute(w,Ye(M,s.get(M))):/^(https?:)?\/\//i.test(v)&&h.removeAttribute(w)}for(let h of[...y.querySelectorAll("[style]")])h.setAttribute("style",l(h.getAttribute("style")??""));let g=y.createElement("meta");return g.setAttribute("http-equiv","Content-Security-Policy"),g.setAttribute("content",Xt),y.head.prepend(g),`<!doctype html>${y.documentElement.outerHTML}`}var Ze=20,Qe=2048,et=256,Gt=/^[A-Za-z][A-Za-z0-9_.-]{0,39}$/,Q=s=>new oe({op:"GetPlacementPaywall",status:0,code:"invalid_attributes",message:s});function Zt(s){let t='"';for(let n=0;n<s.length;n++){let i=s.charCodeAt(n);i===34?t+='\\"':i===92?t+="\\\\":i>=32&&i<=126?t+=s[n]:t+=`\\u${i.toString(16).padStart(4,"0")}`}return`${t}"`}function tt(s){let t=Object.keys(s??{}).sort((p,l)=>p<l?-1:p>l?1:0);if(t.length===0)return;if(t.length>Ze)throw Q(`${t.length} attributes: at most ${Ze}`);let n=[];for(let p of t){if(!Gt.test(p))throw Q(`the attribute ${JSON.stringify(p)}: a key is a letter, then letters, digits and _ . -, at most 40`);let l=s[p],f;if(typeof l=="string"){if(new TextEncoder().encode(l).length>et)throw Q(`the attribute ${JSON.stringify(p)} is over ${et} bytes`);f=Zt(l)}else if(typeof l=="number"){if(!Number.isFinite(l))throw Q(`the attribute ${JSON.stringify(p)} is no number`);f=String(Object.is(l,-0)?0:l)}else if(typeof l=="boolean")f=l?"true":"false";else throw Q(`the attribute ${JSON.stringify(p)}: a value is a text, a number or a boolean`);n.push(`"${p}":${f}`)}let i=`{${n.join(",")}}`;if(i.length>Qe)throw Q(`the attributes are ${i.length} bytes: at most ${Qe}`);return i}function _e(s){let t=/^P(\d+)([DWMY])$/.exec(s??"");if(!t)return null;let n=Number(t[1]);if(!Number.isSafeInteger(n)||n<1)return null;switch(t[2]){case"D":return{count:n,unit:"day",months:n*12/365};case"W":return{count:n,unit:"week",months:n*12/52};case"M":return{count:n,unit:"month",months:n};default:return{count:n,unit:"year",months:n*12}}}function nt(s){try{return new Intl.NumberFormat("en",{style:"currency",currency:s}).resolvedOptions().maximumFractionDigits??2}catch{return 2}}function st(s,t,n){let i=s/10**nt(t);try{return new Intl.NumberFormat(n,{style:"currency",currency:t}).format(i)}catch{return`${i.toFixed(nt(t))} ${t}`}}function Qt(s,t){try{let n=new Intl.NumberFormat(t,{style:"unit",unit:s.unit,unitDisplay:"long"});return s.count>1?n.format(s.count):n.formatToParts(1).filter(p=>p.type==="unit").map(p=>p.value).join("").trim()||n.format(1)}catch{return s.count>1?`${s.count} ${s.unit}s`:s.unit}}var en={en:s=>`${s} free`,tr:s=>`${s} \xFCcretsiz`,de:s=>`${s} kostenlos`,es:s=>`${s} gratis`,it:s=>`${s} gratis`,nl:s=>`${s} gratis`,pt:s=>`${s} gr\xE1tis`,sv:s=>`${s} gratis`,da:s=>`${s} gratis`,nb:s=>`${s} gratis`};function tn(s,t){let n;try{n=new Intl.NumberFormat(t,{style:"unit",unit:s.unit,unitDisplay:"long"}).format(s.count)}catch{n=`${s.count} ${s.unit}${s.count>1?"s":""}`}let i=en[t.split("-")[0].toLowerCase()];return i?i(n):n}function nn(s,t){try{return new Intl.NumberFormat(t,{style:"percent",maximumFractionDigits:0}).format(s)}catch{return`${Math.round(s*100)}%`}}function rt(s,t){let n=new Map,i=new Map;for(let l of s){let f=_e(l.period);if(!f)continue;let y=l.price.amount/f.months;n.set(l.key,y),i.set(l.price.currency,Math.max(i.get(l.price.currency)??0,y))}let p={};for(let l of s){let f={product_name:l.productName,price:st(l.price.amount,l.price.currency,t)},y=_e(l.period);if(y){f.period=Qt(y,t),f.price_per_month=st(Math.round(n.get(l.key)),l.price.currency,t);let h=i.get(l.price.currency)??0,w=h>0?Math.floor((1-n.get(l.key)/h)*100)/100:0;w>=.01&&(f.savings=nn(w,t))}let g=l.intro?.mode==="free_trial"?_e(l.intro.duration):null;g&&(f.trial=tn(g,t)),p[l.key]=f}return p}var W=(s,t,n)=>`M${s-n} ${t}a${n} ${n} 0 1 0 ${2*n} 0a${n} ${n} 0 1 0 ${-2*n} 0`,ue={ad_free:["M3 7h18v10H3z","M4 4l16 16"],bell:["M6 16v-5a6 6 0 0 1 12 0v5l2 2H4z","M10 21a2 2 0 0 0 4 0"],bolt:["M13 2L4 14h7l-1 8 9-12h-7z"],book:["M5 4h11a3 3 0 0 1 3 3v13H8a3 3 0 0 1-3-3z","M5 17a3 3 0 0 1 3-3h11"],chart:["M3 20h18","M6 20v-8","M11 20V5","M16 20v-6","M21 20V9"],chat:["M4 5h16v11H9l-5 4z"],check:["M5 12l5 5 9-10"],check_circle:[W(12,12,9),"M8 12l3 3 5-6"],clock:[W(12,12,9),"M12 7v5l3 2"],cloud:["M7 18a4 4 0 0 1-.5-7.97A6 6 0 0 1 18 9a4.5 4.5 0 0 1-.5 9z"],crown:["M3 8l4 4 5-7 5 7 4-4-2 11H5z"],download:["M12 4v11","M7 10l5 5 5-5","M4 20h16"],gift:["M3 9h18v4H3z","M5 13v8h14v-8","M12 9v12","M12 9C10 5 6 5 6 7.5S12 9 12 9zm0 0c2-4 6-4 6-1.5S12 9 12 9z"],globe:[W(12,12,9),"M3 12h18","M12 3a14 14 0 0 1 0 18a14 14 0 0 1 0-18z"],heart:["M12 20s-7-4.5-9-9a4.5 4.5 0 0 1 9-3 4.5 4.5 0 0 1 9 3c-2 4.5-9 9-9 9z"],infinity:["M7 9a3 3 0 1 0 0 6c3 0 7-6 10-6a3 3 0 1 1 0 6c-3 0-7-6-10-6z"],lock_open:["M5 11h14v10H5z","M8 11V7a4 4 0 0 1 7.5-2"],music:["M9 18V5l11-2v13",W(6,18,3),W(17,16,3)],people:[W(9,8,3.5),"M2 20a7 7 0 0 1 14 0","M16 4.5a3.5 3.5 0 0 1 0 7","M18 14a6 6 0 0 1 4 6"],person:[W(12,8,4),"M4 21a8 8 0 0 1 16 0"],photo:["M3 5h18v14H3z",W(8.5,9.5,1.5),"M3 17l5-5 4 4 3-3 6 6"],shield:["M12 3l8 3v6c0 5-3.5 8-8 9-4.5-1-8-4-8-9V6z"],sparkles:["M12 3l1.8 5.2L19 10l-5.2 1.8L12 17l-1.8-5.2L5 10l5.2-1.8z","M19 15l.8 2.2L22 18l-2.2.8L19 21l-.8-2.2L16 18l2.2-.8z"],star:["M12 3l2.8 5.7 6.2.9-4.5 4.4 1 6.2L12 17.3l-5.5 2.9 1-6.2L3 9.6l6.2-.9z"],video:["M3 6h12v12H3z","M15 10l6-3v10l-6-3z"],arrow_right:["M4 12h15","M13 6l6 6-6 6"],calendar:["M4 6h16v15H4z","M4 10h16","M8 3v5","M16 3v5"],close:["M6 6l12 12","M18 6L6 18"],lock:["M5 11h14v10H5z","M8 11V7a4 4 0 0 1 8 0v4"],play:["M7 4l13 8-13 8z"],quote:["M5 17c3 0 4-2 4-5V7H4v5h3","M15 17c3 0 4-2 4-5V7h-5v5h3"],trophy:["M7 4h10v5a5 5 0 0 1-10 0z","M7 6H4v2a3 3 0 0 0 3 3","M17 6h3v2a3 3 0 0 1-3 3","M12 14v4","M8 21h8","M9 18h6v3H9z"]};var ot="http://www.w3.org/2000/svg";function fe(s,t,n){let i=s.createElementNS(ot,"svg");i.setAttribute("viewBox","0 0 24 24"),i.setAttribute("width",String(n)),i.setAttribute("height",String(n)),i.setAttribute("fill","none"),i.setAttribute("stroke","currentColor"),i.setAttribute("stroke-width","2"),i.setAttribute("stroke-linecap","round"),i.setAttribute("stroke-linejoin","round"),i.setAttribute("aria-hidden","true"),i.setAttribute("focusable","false");for(let p of t){let l=s.createElementNS(ot,"path");l.setAttribute("d",p),i.append(l)}return i}var he=2,m=(s,t=!1)=>({kind:"value",value:"plain",def:s,required:t}),N=s=>({kind:"value",value:"color",def:s}),it=s=>({kind:"value",value:"spacing",def:s}),sn=s=>({kind:"value",value:"radius",def:s}),Y=(s=!1)=>({kind:"text",required:s}),Ee=(s,t=!1)=>({kind:"list",item:s,required:t}),ae=(s,t=!1)=>({kind:"object",item:s,required:t}),at=(s=!1)=>({kind:"component",required:s}),Le={kind:"components"},lt={stack:{axis:m("vertical"),spacing:it(0),align:m("center"),distribution:m("start"),scroll:m(!1),children:Le},text:{text:Y(),spans:Ee("span"),font:m(),size:m(),weight:m(),line_height:m(),letter_spacing:m(),color:{kind:"value",value:"textColor",def:"text"},align:m("center"),max_lines:m(),uppercase:m(!1)},image:{src:m(void 0,!0),fit:m("fit"),aspect:m(),mask:ae("mask"),overlay:{kind:"value",value:"textColor"},alt:Y(),decorative:m(!1)},icon:{name:m(void 0,!0),color:N("accent"),size:m(24)},video:{src:m(void 0,!0),poster:m(),autoplay:m(!0),loop:m(!0),mute:m(!0),controls:m(!1),fit:m("fill"),aspect:m(),alt:Y()},button:{action:ae("action",!0),content:at(!0)},purchase_button:{content:at(!0),package:m()},package:{product:m(void 0,!0),plan:m(void 0,!0),selected:m(!1),children:Le},tabs:{},switch:{},carousel:{pages:Le,peek:m(0),spacing:m(8),loop:m(!1),auto_advance_ms:m(),indicator:ae("indicator"),height:m("")},countdown:{},timeline:{items:Ee("timeline_item",!0),line_color:N("accent"),line_width:m(2),icon_color:N("on_accent"),color:N("text"),spacing:m(16)},features:{items:Ee("feature",!0),icon_color:N("accent"),color:N("text"),spacing:m(12)},spacer:{size:it()},divider:{color:N("muted"),thickness:m(1)},custom_html:{src:m(void 0,!0),height:m("",!0)}},ee={style:{padding:{kind:"edges"},margin:{kind:"edges"},width:m(""),height:m(""),max_width:m(),background:{kind:"fill"},border:ae("border"),corners:{kind:"corners"},shadow:ae("shadow"),opacity:m(1)},border:{width:m(),color:N("")},shadow:{color:N(""),radius:m(0),x:m(0),y:m(0)},linear:{type:m(""),angle:m(180),stops:m()},radial:{type:m(""),center_x:m(.5),center_y:m(.5),radius:m(.5),stops:m()},image_fill:{type:m(""),src:m(),fit:m("fill")},video_fill:{type:m(""),src:m(),poster:m(),loop:m(!0)},animation:{type:m(""),duration_ms:m(300),delay_ms:m(0),easing:m("ease_out")},action:{type:m(""),url:m(),sheet:m(),package:m()},mask:{shape:m(""),radius:sn(0),depth:m(16)},span:{text:Y(!0),bold:m(!1),italic:m(!1),underline:m(!1),strikethrough:m(!1),color:N(""),link:m()},timeline_item:{icon:m(void 0,!0),title:Y(!0),text:Y(),color:N("")},feature:{icon:m(void 0,!0),text:Y(!0)},indicator:{style:m("dots"),color:N("muted"),active_color:N("accent"),size:m(8),spacing:m(6)},typography:{font:m("system"),size:m(),weight:m(400),line_height:m(),letter_spacing:m(0),text_style:m("body")}},rn={linear:"linear",radial:"radial",image:"image_fill",video:"video_fill"},on=["top","bottom","leading","trailing"],an=["top_leading","top_trailing","bottom_leading","bottom_trailing"],Fn=Object.keys(lt),ln=/\{\{\s*([^{}]*?)\s*\}\}/g,te=(s,t)=>typeof s=="object"&&s!==null&&Object.hasOwn(s,t),S=s=>typeof s=="object"&&s!==null&&!Array.isArray(s)?s:{},J=s=>Array.isArray(s)?s:[],X=(s,t)=>s??t;function cn(s){let t=Math.floor(s/86400),n=Math.floor(s%86400/3600),i=Math.floor(s%3600/60),p=s%60,l=y=>String(y).padStart(2,"0");return{countdown:t>0?`${t}d ${l(n)}:${l(i)}:${l(p)}`:n>0?`${n}:${l(i)}:${l(p)}`:`${l(i)}:${l(p)}`,days:String(t),hours:l(n),minutes:l(i),seconds:l(p)}}function ct(s){let t=[],n=p=>{if(Array.isArray(p))return p.forEach(n);if(typeof p!="object"||p===null)return;let l=p;if(l.type==="package"&&typeof l.product=="string"&&typeof l.plan=="string"){let f=`${l.product}.${l.plan}`;t.includes(f)||t.push(f)}for(let f of Object.keys(l).sort())n(l[f])},i=s;for(let p of["header","root","footer"])n(i[p]);for(let p of Object.keys(S(i.sheets)).sort())n(S(S(i.sheets)[p]).root);return t}function Cn(s,t){return new ge(s,t).resolve().tree}function dt(s,t){return new ge(s,t).resolve()}var ge=class{d;opts;lang;texts={};palette;typography={};radii;spacing;packages;selected="";tab="";paths=new WeakMap;tabsShown={};switchesOn={};countdowns={};constructor(t,n){this.d=t,this.opts=n,this.packages=n.packages;let i=S(this.d.locales),p=String(this.d.default_locale??""),l=n.locale;te(i,l)||(l=l.split("-")[0]??"",te(i,l)||(l=p)),this.lang=l;for(let y of[p,l])for(let[g,h]of Object.entries(S(i[y])))typeof h=="string"&&(this.texts[g]=h);let f=S(this.d.theme);this.palette=S(S(f.colors)[n.appearance]);for(let[y,g]of Object.entries(S(f.typography))){let h={};for(let[w,v]of Object.entries(ee.typography)){let M=X(S(g)[w],v.def);M!=null&&(h[w]=M)}this.typography[y]=h}this.radii=S(f.radii),this.spacing=S(f.spacing)}resolve(){let[t,n]=this.initialState();this.tab=t,this.selected=n;let i={selected:n,theme:{colors:this.palette,typography:this.typography,radii:this.radii,spacing:this.spacing}};for(let l of["header","root","footer"]){let f=this.d[l];if(typeof f=="object"&&f!==null){let y=this.component(S(f),l,"",!1);y&&(i[l]=y)}}let p={};if(typeof this.d.sheets=="object"&&this.d.sheets!==null){let l={};for(let[f,y]of Object.entries(S(this.d.sheets))){let g=this.component(S(S(y).root),`sheets.${f}.root`,"",!1);g&&(l[f]=g);let h=this.text(S(y).title,this.packages[this.selected]);h!==null&&(p[f]=h)}i.sheets=l}return{tree:i,pathOf:l=>this.paths.get(l),tabs:this.tabsShown,switches:this.switchesOn,sheetTitles:p,countdowns:this.countdowns,language:this.lang}}switchOn(t,n){return this.opts.switches&&Object.hasOwn(this.opts.switches,n)?this.opts.switches[n]:this.opts.switch?this.opts.switch==="on":t.default===!0}tabShown(t,n){let p=J(t.tabs).map(S).map(f=>String(f.id)),l=this.opts.tabs?.[n];return l!==void 0&&p.includes(l)?l:this.opts.tab?this.opts.tab:typeof t.default=="string"&&t.default!==""?t.default:p[0]??""}initialState(){let t="",n="",i="",p="",l=(y,g)=>{if(Array.isArray(y)){y.forEach((w,v)=>l(w,`${g}[${v}]`));return}if(typeof y!="object"||y===null)return;let h=y;switch(h.type){case"package":{let w=`${h.product}.${h.plan}`;i===""&&(i=w),h.selected===!0&&n===""&&(n=w);break}case"switch":{let w=this.switchOn(h,g),v=w?h.on_package:h.off_package;typeof v=="string"&&p===""&&(p=v),l(w?h.on:h.off,`${g}.${w?"on":"off"}`);return}case"tabs":{let w=this.tabShown(h,g);t===""&&(t=w),J(h.tabs).forEach((v,M)=>{let x=S(v);x.id===w&&(typeof x.package=="string"&&p===""&&(p=x.package),l(x.content,`${g}.tabs[${M}].content`))});return}}for(let w of Object.keys(h).sort())w!=="sheets"&&l(h[w],g===""?w:`${g}.${w}`)};for(let y of["header","root","footer"])l(this.d[y],y);let f=this.opts.selected||p||n||i;return[t,f]}holds(t,n){let i=n||this.selected;for(let[p,l]of Object.entries(t))switch(p){case"selected_package":if(!J(l).includes(this.selected))return!1;break;case"intro_eligible":if((this.opts.eligible??[]).includes(i)!==l)return!1;break;case"platform":if(!J(l).includes(this.opts.platform))return!1;break;case"locale":if(!J(l).includes(this.opts.locale)&&!J(l).includes(this.lang))return!1;break;case"appearance":if(l!==this.opts.appearance)return!1;break;case"tab":if(l!==this.tab)return!1;break}return!0}component(t,n,i,p){if(typeof t.visible=="object"&&t.visible!==null&&!this.holds(S(t.visible),i))return null;let l=String(t.type),f=i,y=p;l==="package"&&(f=`${t.product}.${t.plan}`,y=f===this.selected);let g={type:l};this.paths.set(g,n),te(t,"id")&&(g.id=t.id);let h={...S(t.style)};y&&Object.assign(h,S(S(t.states).selected)),Object.keys(h).length>0&&(g.style=this.style(h)),typeof t.animation=="object"&&t.animation!==null&&(g.animation=this.defaults(S(t.animation),ee.animation));let w=this.packages[f||this.selected];switch(l){case"tabs":return this.tabs(t,g,n,f);case"switch":return this.switchOf(t,g,n,f,y);case"countdown":return this.countdown(t,g,n,f,y);case"purchase_button":{let v=typeof t.package=="string"?t.package:this.selected;g.package=v;let M=this.component(S(t.content),`${n}.content`,v,y);return M?(g.content=M,g):null}case"package":g.product=t.product,g.plan=t.plan,g.selected=y}for(let[v,M]of Object.entries(lt[l]??{})){if(l==="package"&&(v==="product"||v==="plan"||v==="selected"))continue;let x=t[v],R=te(t,v);switch(M.kind){case"component":{if(!R)continue;let b=this.component(S(x),`${n}.${v}`,f,y);if(!b&&M.required)return null;b&&(g[v]=b);break}case"components":{let b=[];J(x).forEach((T,C)=>{let K=this.component(S(T),`${n}.${v}[${C}]`,f,y);K&&b.push(K)}),g[v]=b;break}case"text":{let b=this.text(x,w);if(b!==null)g[v]=b;else if(M.required||l==="text"&&v==="text"&&R)return null;break}case"list":{let b=[];for(let T of J(x)){let C=this.item(M.item,S(T),w);C&&b.push(C)}if(l==="text"&&b.length===0&&R)return null;R&&(g[v]=b);break}case"object":{R?g[v]=this.object(S(x),M.item,w):v==="indicator"&&(g[v]=this.object({},M.item,w));break}case"value":{let b=this.value(X(x,M.def),M);b!=null&&b!==""&&(g[v]=b);break}}}return l==="text"&&this.typeStyle(g),g}typeStyle(t){if(typeof t.size!="string"){t.size!==void 0&&t.size!==null&&(t.text_style="body");return}let n=this.typography[t.size];for(let i of["font","weight","line_height","letter_spacing","text_style"])!te(t,i)&&n?.[i]!==void 0&&n?.[i]!==null&&(t[i]=n[i]);t.size=n?.size??null}tabs(t,n,i,p){let l=this.tabShown(t,i);this.tabsShown[i]=l;let f=[];return J(t.tabs).forEach((y,g)=>{let h=S(y),w=h.id===l,v=this.component(S(h.label),`${i}.tabs[${g}].label`,p,w);if(f.push({id:h.id,selected:w,label:v}),w){let M=this.component(S(h.content),`${i}.tabs[${g}].content`,p,!1);M&&(n.content=M)}}),n.tabs=f,typeof t.bar=="object"&&t.bar!==null&&(n.bar=this.style(S(t.bar))),n}switchOf(t,n,i,p,l){let f=this.switchOn(t,i);this.switchesOn[i]=f,n.on=f;let y=this.text(t.label,this.packages[p||this.selected]);y!==null&&(n.label=y),n.tint=this.color(String(X(t.tint,"accent")));let g=f?"on":"off",h=this.component(S(t[g]),`${i}.${g}`,p,l);return h&&(n.content=h),n}countdown(t,n,i,p,l){let f=S(t.target),y=this.opts.now??Date.now(),g;if(typeof f.after_open_seconds=="number"?g=Math.trunc(f.after_open_seconds)-(this.opts.openedSecondsAgo??0):g=Math.trunc((Date.parse(String(f.at))-y)/1e3),g>0){n.state="counting",n.remaining_seconds=g,this.countdowns[i]=g;let h=this.packages,w={};for(let[M,x]of Object.entries(h))w[M]={...x,...cn(g)};this.packages=w;let v=this.component(S(t.counting),`${i}.counting`,p,l);return v&&(n.content=v),this.packages=h,n}if(n.state="ended",n.remaining_seconds=0,typeof t.ended=="object"&&t.ended!==null){let h=this.component(S(t.ended),`${i}.ended`,p,l);h&&(n.content=h)}return n}item(t,n,i){let p={};for(let[l,f]of Object.entries(ee[t]??{})){let y=n[l];if(f.kind==="text"){let g=this.text(y,i);if(g!==null)p[l]=g;else if(f.required)return null}else{let g=f.def,h=this.value(X(y,g),f);h!=null&&(te(n,l)||g!=null&&g!=="")&&(p[l]=h)}}return p}object(t,n,i){return n==="style"?this.style(t):this.item(n,t,i)??{}}defaults(t,n){let i={};for(let[p,l]of Object.entries(n)){let f=X(t[p],l.def);f!=null&&f!==""&&(i[p]=f)}return i}style(t){let n={};for(let[i,p]of Object.entries(t)){let l=ee.style[i];if(!l){n[i]=p;continue}switch(l.kind){case"edges":n[i]=this.sides(p,on,this.spacing);break;case"corners":n[i]=this.sides(p,an,this.radii);break;case"fill":n[i]=this.fill(p);break;case"object":{let f=S(p),y={};for(let[g,h]of Object.entries(ee[l.item]??{})){let w=X(f[g],h.def);w!=null&&w!==""&&(y[g]=this.value(w,h))}n[i]=y;break}default:n[i]=p}}return n}sides(t,n,i){let p={};for(let l of n){let f=typeof t=="object"&&t!==null?X(S(t)[l],0):t;p[l]=$e(f,i)}return p}fill(t){if(typeof t=="string")return{type:"color",color:this.color(t)};let n=S(t),i=this.defaults(n,ee[rn[String(n.type)]??""]??{});return Array.isArray(n.stops)&&(i.stops=n.stops.map(p=>({color:this.color(String(S(p).color)),at:S(p).at}))),i}value(t,n){if(n.kind!=="value")return t;switch(n.value){case"color":return typeof t=="string"&&t!==""?this.color(t):t;case"textColor":return typeof t=="string"?this.color(t):t==null?t:this.fill(t);case"spacing":return $e(t,this.spacing);case"radius":return $e(t,this.radii);default:return t}}color(t){let n=Object.hasOwn(this.palette,t)?this.palette[t]:void 0;return typeof n=="string"?n:t}text(t,n){let i;if(typeof t=="string")i=t;else if(typeof t=="object"&&t!==null&&!Array.isArray(t)){let l=t.t;i=typeof l=="string"&&Object.hasOwn(this.texts,l)?this.texts[l]:""}else return null;let p=!1;return i=i.replace(ln,(l,f)=>{let y=n&&Object.hasOwn(n,f)?n[f]:void 0;return typeof y!="string"||y===""?(p=!0,""):y}),p||i.trim()===""?null:i}};function $e(s,t){return typeof s=="string"?Object.hasOwn(t,s)?t[s]:null:s}var dn={packages:"Choose a plan",close:"Close",restore:"Restore purchases",page:(s,t)=>`${s} of ${t}`},ne={system:'-apple-system, BlinkMacSystemFont, "SF Pro Text", system-ui, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif',rounded:'ui-rounded, "SF Pro Rounded", Nunito, "Varela Round", system-ui, -apple-system, sans-serif',serif:'ui-serif, "New York", "Iowan Old Style", Georgia, "Times New Roman", serif',mono:'ui-monospace, "SF Mono", Menlo, Consolas, "Liberation Mono", monospace'},pn=1.35,pt=20,un=new Set(["button","purchase_button","package","text"]),fn=new Set(["ar","he","fa","ur","ps","yi","dv","ug","ku","sd"]),ut={ease_out:"cubic-bezier(0.16, 1, 0.3, 1)",ease_in_out:"cubic-bezier(0.65, 0, 0.35, 1)",spring:"cubic-bezier(0.34, 1.56, 0.64, 1)"},gn={start:"flex-start",center:"center",end:"flex-end",stretch:"stretch"},hn={start:"flex-start",center:"center",end:"flex-end",space_between:"space-between",space_around:"space-around",space_evenly:"space-evenly"},yn={stack:["children"],package:["children"],button:["content"],purchase_button:["content"],tabs:["tabs","content"],switch:["content"],carousel:["pages"],countdown:["content"]},mn={package:["selected"],purchase_button:["package"],switch:["on"],countdown:["state","remaining_seconds"]},wn=`
3
+ :host{display:block;height:100%}
4
+ .pw2{position:relative;box-sizing:border-box;display:flex;flex-direction:column;height:100%;overflow:hidden;font-family:${ne.system};font-size:1rem;line-height:1.3;-webkit-font-smoothing:antialiased;-webkit-text-size-adjust:100%;text-rendering:optimizeLegibility}
5
+ .pw2 *,.pw2 *::before,.pw2 *::after{box-sizing:border-box}
6
+ .pw2-head,.pw2-foot{flex:none;display:flex;flex-direction:column;position:relative;z-index:1}
7
+ .pw2-head[hidden],.pw2-foot[hidden]{display:none}
8
+ .pw2-foot{max-height:30%;overflow-y:auto;scrollbar-width:none}
9
+ .pw2-foot .pw-text{font-size:min(var(--pw-fs,1rem),var(--pw-fs-max,21.6px))}
10
+ .pw2.pw2-large{overflow-y:auto;overscroll-behavior:contain;scrollbar-width:none}
11
+ .pw2.pw2-large>.pw2-body{flex:1 0 auto;overflow:visible;min-height:auto}
12
+ .pw2.pw2-large>.pw2-foot{position:sticky;bottom:0}
13
+ .pw2{padding-left:env(safe-area-inset-left,0px);padding-right:env(safe-area-inset-right,0px)}
14
+ .pw2-head,.pw2-body.pw2-top{padding-top:env(safe-area-inset-top,0px)}
15
+ .pw2-foot,.pw2-body.pw2-bottom{padding-bottom:env(safe-area-inset-bottom,0px)}
16
+ .pw2-body{flex:1 1 auto;min-height:0;overflow-y:auto;overflow-x:hidden;display:flex;flex-direction:column;overscroll-behavior:contain;scrollbar-width:none}
17
+ .pw2-body::-webkit-scrollbar{display:none}
18
+ .pw2-body>.pw-c{flex:1 0 auto}
19
+ .pw-c{position:relative;min-width:0}
20
+ .pw-c[style*="--pw-bw"]{isolation:isolate}
21
+ .pw-c[style*="--pw-bw"]::after{content:"";position:absolute;inset:0;border:var(--pw-bw) solid var(--pw-bc);border-radius:inherit;pointer-events:none;z-index:2}
22
+ .pw-stack{display:flex;flex-direction:column}
23
+ .pw-stack.h{flex-direction:row}
24
+ .pw-stack.z{display:grid}
25
+ .pw-stack.z>.pw-c{grid-area:1/1}
26
+ .pw-stack.scroll{overflow-y:auto;scrollbar-width:none}
27
+ .pw-stack.h.scroll{overflow-x:auto;overflow-y:hidden}
28
+ .pw-stack.scroll>.pw-c{flex-shrink:0}
29
+ .pw-text{margin:0;overflow-wrap:break-word;white-space:pre-line}
30
+ /* A text beside others wraps between its words, never inside one: a price stays whole, what is beside it wraps. */
31
+ .pw-stack.h>.pw-text{min-width:min-content}
32
+ .pw-text a{color:inherit}
33
+ .pw-clamp{display:-webkit-box;-webkit-box-orient:vertical;overflow:hidden}
34
+ .pw-grad{-webkit-background-clip:text;background-clip:text;color:transparent!important;-webkit-text-fill-color:transparent}
35
+ .pw-icon{display:inline-flex;flex:none}
36
+ .pw-icon svg{display:block}
37
+ .pw-img{overflow:hidden;flex:none}
38
+ .pw-img img,.pw-img video{display:block;width:100%;height:100%}
39
+ .pw-img.natural img{height:auto}
40
+ .pw-overlay{position:absolute;inset:0;pointer-events:none}
41
+ .pw-bgvideo{position:absolute;inset:0;width:100%;height:100%;object-fit:cover;z-index:-1;pointer-events:none}
42
+ button.pw-c{font:inherit;color:inherit;background:none;border:0;margin:0;padding:0;cursor:pointer;text-align:inherit;display:flex;flex-direction:column;align-items:stretch;justify-content:center;-webkit-tap-highlight-color:transparent;transition:opacity .15s ease,transform .15s ease}
43
+ button.pw-c:active{transform:scale(.98)}
44
+ button.pw-c:disabled{cursor:default;opacity:.5}
45
+ .pw-pkg{cursor:pointer;display:flex;flex-direction:column;transition:background-color .2s ease,border-color .2s ease,box-shadow .2s ease}
46
+ .pw-pkg[aria-disabled=true]{cursor:default;opacity:.55}
47
+ :focus-visible{outline:2px solid currentColor;outline-offset:2px}
48
+ .pw-features{list-style:none;margin:0;padding:0;display:flex;flex-direction:column}
49
+ .pw-feature{display:flex;align-items:center;gap:12px;text-align:start}
50
+ .pw-timeline{list-style:none;margin:0;padding:0;display:flex;flex-direction:column}
51
+ .pw-step{display:grid;grid-template-columns:auto 1fr;column-gap:14px;position:relative;text-align:start}
52
+ .pw-dot{width:32px;height:32px;border-radius:50%;display:grid;place-items:center;position:relative;z-index:1}
53
+ .pw-line{position:absolute;left:calc(16px - var(--pw-line-w)/2);top:32px;width:var(--pw-line-w);bottom:calc(-1 * var(--pw-gap))}
54
+ .pw-step:last-child .pw-line{display:none}
55
+ .pw-step-title{font-weight:600}
56
+ .pw-step-text{opacity:.72;font-size:.9375rem;margin-top:2px}
57
+ .pw-tabs{display:flex;flex-direction:column;gap:12px}
58
+ .pw-tablist{display:flex}
59
+ .pw-tab{flex:1 1 0;min-width:0;font:inherit;color:inherit;background:none;border:0;margin:0;padding:0;cursor:pointer;display:flex}
60
+ .pw-tab>.pw-c{flex:1 1 auto}
61
+ .pw-switch{display:flex;flex-direction:column;gap:12px}
62
+ .pw-switchcontent{display:flex;flex-direction:column}
63
+ .pw-switchrow{display:flex;align-items:center;justify-content:space-between;gap:12px;text-align:start}
64
+ .pw-toggle{flex:none;width:51px;height:31px;border-radius:999px;border:0;padding:2px;cursor:pointer;background:var(--pw-off);transition:background-color .2s ease}
65
+ .pw-toggle[aria-checked=true]{background:var(--pw-tint)}
66
+ .pw-toggle i{display:block;width:27px;height:27px;border-radius:50%;background:#fff;box-shadow:0 2px 4px #0003;transition:transform .2s ease}
67
+ .pw-toggle[aria-checked=true] i{transform:translateX(20px)}
68
+ .pw-carousel{display:flex;flex-direction:column;gap:12px;min-width:0}
69
+ .pw-track{display:flex;overflow-x:auto;scroll-snap-type:x mandatory;scrollbar-width:none;scroll-behavior:smooth;padding-inline:var(--pw-peek);scroll-padding-inline:var(--pw-peek);gap:var(--pw-gap)}
70
+ .pw-track::-webkit-scrollbar{display:none}
71
+ .pw-track>.pw-c{flex:none;width:100%;scroll-snap-align:center}
72
+ .pw-dots{display:flex;justify-content:center;gap:var(--pw-dot-gap)}
73
+ .pw-dots button{border:0;padding:0;cursor:pointer;width:var(--pw-dot);height:var(--pw-dot);border-radius:999px;background:var(--pw-dot-c);transition:width .25s ease,background-color .25s ease}
74
+ .pw-dots.bars button{width:calc(var(--pw-dot) * 3)}
75
+ .pw-dots button[aria-current=true]{background:var(--pw-dot-on)}
76
+ .pw-dots.dots button[aria-current=true]{width:calc(var(--pw-dot) * 2.5)}
77
+ .pw-html{display:block;width:100%;border:0;pointer-events:none;background:transparent}
78
+ .pw-spacer{flex:1 1 0}
79
+ .pw-stack:not(.h):not(.z)>.greedy-h,.pw-pkg>.greedy-h,button.pw-c>.greedy-h{align-self:stretch}
80
+ .pw-stack.h>.greedy-h{flex:1 1 0}
81
+ .pw-stack.z>.greedy-h{justify-self:stretch}
82
+ .pw-stack:not(.h):not(.z)>.greedy-v,.pw-pkg>.greedy-v{flex:1 1 auto}
83
+ .pw-stack.h>.greedy-v,.pw-stack.z>.greedy-v{align-self:stretch}
84
+ .pw-layer{position:absolute;inset:0;z-index:5;display:flex;flex-direction:column;justify-content:flex-end;background:#0007}
85
+ .pw-sheet{max-height:92%;overflow-y:auto;border-radius:16px 16px 0 0;display:flex;flex-direction:column;outline:none;padding-bottom:env(safe-area-inset-bottom,0px)}
86
+ .pw-sheet>.pw-c{flex:1 0 auto}
87
+ .pw-grab{width:36px;height:5px;border-radius:3px;background:currentColor;opacity:.25;margin:8px auto 0;flex:none}
88
+ [data-pw-highlight]{outline:2px solid #2E7CF6!important;outline-offset:-1px}
89
+ [data-pw-hover]:not([data-pw-highlight]){outline:1px dashed #2E7CF6aa!important;outline-offset:-1px}
90
+ .pw-editing button,.pw-editing .pw-pkg,.pw-editing a{cursor:default}
91
+ @media (prefers-reduced-motion:reduce){.pw2 *{transition:none!important;scroll-behavior:auto!important}}
92
+ `,ye=s=>{if(typeof s!="string"||s.length>2048)return!1;try{let t=new URL(s);return t.protocol==="https:"&&t.hostname!==""&&t.username===""&&t.password===""}catch{return!1}},bn=s=>`${String(s.product)}.${String(s.plan)}`,Te=s=>{let[t,n]=s.split(".");return{product:t??"",plan:n??""}},_=s=>`${Number(s)||0}px`,ft=s=>`${s/16}rem`,vn=0;function gt(s,t,n){let i=s.ownerDocument,p=i.defaultView,l=`pw${++vn}`,f=i.createElement("div");f.setAttribute("data-palbase-paywall",""),f.style.display="block",f.style.height="100%";let y=f.attachShadow({mode:"open"});kn(i,y,wn);let g=i.createElement("div");g.className="pw2";let h=i.createElement("div");h.className="pw2-head";let w=i.createElement("div");w.className="pw2-body";let v=i.createElement("div");v.className="pw2-foot";let M=i.createElement("div");g.append(h,w,v),y.append(g),s.replaceChildren(f);let x={...t},R={openedAt:Date.now(),...t.state},b,T=new Map,C=new Map,K=!1,be=null,ve,Oe=!1,Fe=i.defaultView?.ResizeObserver,Ce=typeof Fe=="function"?new Fe(()=>{g.classList.toggle("pw2-large",Ne()>=pt),xe()}):null;Ce?.observe(g);let He=()=>xe();i.fonts?.addEventListener?.("loadingdone",He);let je=null,ke=p?.matchMedia?.("(prefers-reduced-motion: reduce)"),re=()=>x.reduceMotion??ke?.matches??!1,H=()=>!!n.editor,le={...dn,...n.labels};function G(){let e=R.now??Date.now();b=dt(x.definition,{locale:x.locale,appearance:x.appearance,platform:x.platform??"web",packages:x.packages,eligible:x.eligible??[],...R.selected?{selected:R.selected}:{},tabs:R.tabs??{},switches:R.switches??{},openedSecondsAgo:Math.max(0,Math.floor((e-(R.openedAt??e))/1e3)),now:e});let c=b.tree.theme.colors;g.style.background=c.background??"",g.style.color=c.text??"",g.classList.toggle("pw-editing",H()),g.classList.toggle("pw2-large",Ne()>=pt),g.lang=b.language,g.dir=fn.has(b.language.split("-")[0]??"")?"rtl":"ltr",C=new Map,Pe(h,b.tree.header,"vertical"),Pe(w,b.tree.root,"vertical"),Pe(v,b.tree.footer,"vertical"),h.hidden=!b.tree.header,v.hidden=!b.tree.footer,w.classList.toggle("pw2-top",!b.tree.header),w.classList.toggle("pw2-bottom",!b.tree.footer),Nt();for(let[o,r]of T)C.has(o)||r.cleanup.forEach(a=>a());T=C,be&&We(be);for(let o of T.values())o.type==="custom_html"&&qe(o.el);xe(),clearTimeout(ve),Oe||=f.isConnected,R.now===void 0&&Object.keys(b.countdowns).length>0&&(ve=setTimeout(()=>{Oe&&!f.isConnected||G()},1e3-Date.now()%1e3+5))}function Ne(){let e=i.documentElement,c=e&&p?parseFloat(p.getComputedStyle(e).fontSize):NaN;return Number.isFinite(c)?c:16}function xe(){let e=[];for(let o of T.values()){if(o.type!=="text")continue;let r=o.el,a=r.dataset.pwFit??r.style.fontSize;if(!a||(r.style.fontSize=a,delete r.dataset.pwFit,!/^\S+$/.test(r.textContent??"")))continue;let d=r.parentElement,u=d&&p?p.getComputedStyle(d):null,k=d&&u?d.clientWidth-parseFloat(u.paddingLeft||"0")-parseFloat(u.paddingRight||"0"):1/0,A=Math.min(r.clientWidth,k);e.push({e:r,base:a,k:A<=0||r.scrollWidth<=A+.5?1:Math.max(.6,A/r.scrollWidth)})}let c=o=>o.closest(".pw-stack.h");for(let o of e){let r=Math.min(o.k,...e.filter(a=>a!==o&&a.base===o.base&&c(a.e)&&c(a.e)===c(o.e)).map(a=>a.k));r>=1||(o.e.dataset.pwFit=o.base,o.e.style.fontSize=`calc(${o.base} * ${r.toFixed(3)})`)}}function Pe(e,c,o){let r=c?U(c,o,{inControl:!1,inSheet:!1,inFooter:e===v}):null;V(e,r?[r]:[])}function U(e,c,o){let r=b.pathOf(e)??"",a=vt(e),d=T.get(r),u;if(d&&d.type===e.type&&d.key===a&&d.axis===c&&!C.has(r))u=d;else{let A=xt(e,r,c,o);if(!A)return null;u={el:A.el,type:e.type,key:a,styleKey:"",axis:c,slots:A.slots,cleanup:A.cleanup??[]},u.el.classList.add("pw-c"),u.el.dataset.pwPath=r,u.el.dataset.pwType=e.type,e.id&&(u.el.dataset.pwId=e.id),d&&d.cleanup.forEach(L=>L()),Ot(u.el,e)}let k=`${JSON.stringify(e.style??null)}|${c}`;return u.styleKey!==k&&(De(u.el,e,c),u.styleKey=k),C.set(r,u),$t(u,e),Tt(u,e,o),u.el}function vt(e){let c=new Set(["style",...yn[e.type]??[],...mn[e.type]??[]]),o={};for(let[r,a]of Object.entries(e))c.has(r)||(o[r]=a);return e.type==="tabs"&&(o.tabs=e.tabs.map(r=>r.id)),e.type==="carousel"&&(o.pages=e.pages.length),e.type==="stack"&&(o.greedy=e.children.some(r=>r.type==="spacer"&&typeof r.size!="number")),(e.type==="image"||e.type==="video"||e.type==="custom_html")&&(o.asset=kt(e)),JSON.stringify(o)}function kt(e){let c=ie(e.src);return c?(x.assets?.[c]?.url??x.assets?.[c]?.html?.length??"none").toString():""}function P(e,c){let o=i.createElement(e);return c&&(o.className=c),o}function xt(e,c,o,r){let a=e;switch(e.type){case"stack":{let d=P("div",`pw-stack${a.axis==="horizontal"?" h":a.axis==="z"?" z":""}${a.scroll?" scroll":""}`);return a.axis!=="z"&&a.children.some(u=>u.type==="spacer"&&typeof u.size!="number")&&d.classList.add(a.axis==="horizontal"?"greedy-h":"greedy-v"),d.style.gap=_(a.spacing),a.axis==="z"?d.style.placeItems=a.align==="stretch"?"stretch":String(a.align??"center"):(d.style.alignItems=gn[String(a.align)]??"center",d.style.justifyContent=hn[String(a.distribution)]??"flex-start"),{el:d,slots:{children:d}}}case"text":return{el:Pt(a,r),slots:{}};case"icon":{let d=ue[String(a.name)];if(!d)return null;let u=P("span","pw-icon");return u.style.color=String(a.color??""),u.append(fe(i,d,Number(a.size)||24)),u.setAttribute("aria-hidden","true"),{el:u,slots:{}}}case"image":return At(a);case"video":return St(a);case"features":{let d=P("ul","pw-features");d.style.gap=_(a.spacing);for(let u of a.items??[]){let k=P("li","pw-feature"),A=ue[u.icon];if(A){let z=fe(i,A,22);z.style.color=String(a.icon_color),z.style.flex="none",k.append(z)}let L=P("span");L.textContent=u.text,L.style.color=String(a.color),k.append(L),d.append(k)}return{el:d,slots:{}}}case"timeline":{let d=P("ol","pw-timeline");d.style.gap=_(a.spacing),d.style.setProperty("--pw-gap",_(a.spacing)),d.style.setProperty("--pw-line-w",_(a.line_width));for(let u of a.items??[]){let k=P("li","pw-step"),A=P("span","pw-dot");A.style.background=u.color??String(a.line_color),A.style.color=String(a.icon_color);let L=ue[u.icon];L&&A.append(fe(i,L,18)),A.setAttribute("aria-hidden","true");let z=P("span","pw-line");z.style.background=String(a.line_color),z.setAttribute("aria-hidden","true");let D=P("span");D.style.color=String(a.color);let B=P("span","pw-step-title");if(B.textContent=u.title,D.append(B),u.text){let $=P("span","pw-step-text");$.style.display="block",$.textContent=u.text,D.append($)}k.append(A,D,z),d.append(k)}return{el:d,slots:{}}}case"spacer":{let d=P("div","pw-spacer");return d.setAttribute("aria-hidden","true"),typeof a.size=="number"&&(d.style.flex="none",o==="horizontal"?d.style.width=_(a.size):d.style.height=_(a.size)),{el:d,slots:{}}}case"divider":{let d=P("div","pw-divider");return d.setAttribute("role","separator"),d.style.background=String(a.color),d.style.alignSelf="stretch",d.style.flex="none",o==="horizontal"?(d.setAttribute("aria-orientation","vertical"),d.style.width=_(a.thickness)):d.style.height=_(a.thickness),{el:d,slots:{}}}case"button":return Rt(a,r);case"purchase_button":{let d=P("button","pw-buy");return d.type="button",d.addEventListener("click",()=>{Ve(d,()=>jt(d.dataset.package??""))}),{el:d,slots:{content:d}}}case"package":{let d=P("div","pw-pkg");return d.setAttribute("role","radio"),d.addEventListener("click",()=>Re(d)),d.addEventListener("keydown",u=>Ft(u,d)),{el:d,slots:{children:d}}}case"tabs":return _t(a,c);case"switch":return Et(a,c);case"carousel":return Lt(a);case"countdown":{let d=P("div","pw-countdown");return d.setAttribute("role","timer"),d.setAttribute("aria-live","off"),{el:d,slots:{content:d}}}case"custom_html":{let d=x.assets?.[ie(a.src)??""];if(!d?.html)return null;let u=P("iframe","pw-html");return u.setAttribute("sandbox","allow-scripts"),u.setAttribute("aria-hidden","true"),u.setAttribute("title",""),u.tabIndex=-1,u.srcdoc=d.html,typeof a.height=="number"?u.style.height=_(a.height):typeof a.height=="string"&&a.height.endsWith("%")?u.style.height=a.height:a.height==="fill"&&(u.style.flex="1 1 0"),u.addEventListener("load",()=>qe(u)),{el:u,slots:{}}}default:return null}}function Pt(e,c){let o=String(e.text_style??"body"),r=c.inControl?"span":o==="large_title"?"h1":o==="title"||o==="title2"?"h2":o==="title3"?"h3":"p",a=P(r,"pw-text");c.inControl&&(a.style.display="block"),a.style.fontFamily=Mt(e.font);let d=typeof e.size=="number"?e.size:16;if(c.inFooter?(a.style.setProperty("--pw-fs",ft(d)),a.style.setProperty("--pw-fs-max",`${Number((d*pn).toFixed(2))}px`)):a.style.fontSize=ft(d),typeof e.weight=="number"&&(a.style.fontWeight=String(e.weight)),typeof e.line_height=="number"&&(a.style.lineHeight=String(e.line_height)),typeof e.letter_spacing=="number"&&e.letter_spacing!==0&&(a.style.letterSpacing=_(e.letter_spacing)),a.style.textAlign=String(e.align??"center"),e.uppercase===!0&&(a.style.textTransform="uppercase"),typeof e.max_lines=="number"&&(a.classList.add("pw-clamp"),a.style.setProperty("-webkit-line-clamp",String(e.max_lines))),typeof e.color=="string"?a.style.color=e.color:e.color&&typeof e.color=="object"&&(a.classList.add("pw-grad"),a.style.backgroundImage=Ae(e.color)??""),Array.isArray(e.spans))for(let u of e.spans){let k=u.link==="terms"?x.links?.terms:u.link==="privacy"?x.links?.privacy:u.link,A=ye(k)&&!c.inControl,L=P(A?"a":"span");L.textContent=String(u.text),u.bold&&(L.style.fontWeight="700"),u.italic&&(L.style.fontStyle="italic");let z=[u.underline?"underline":"",u.strikethrough?"line-through":""].filter(Boolean).join(" ");z&&(L.style.textDecoration=z),typeof u.color=="string"&&u.color!==""&&(L.style.color=u.color),A&&ye(k)&&(L.href=k,L.target="_blank",L.rel="noopener noreferrer",L.addEventListener("click",D=>{H()||!n.onLink||(D.preventDefault(),n.onLink(k))})),a.append(L)}else a.textContent=String(e.text??"");return a}function Mt(e){if(typeof e!="string")return ne.system;let c=ie(e);if(c){let o=x.assets?.[c]?.family;return o?`"${o}", ${ne.system}`:ne.system}return ne[e]??ne.system}function Z(e){let c=ie(e);return c?x.assets?.[c]?.url||void 0:ye(e)?e:void 0}function At(e){let c=P("div","pw-img");typeof e.aspect=="number"&&(c.style.aspectRatio=String(e.aspect));let o=Z(e.src),r=e.mask;if(r?.shape==="circle")c.style.borderRadius="50%";else if(r?.shape==="rect"&&r.radius)c.style.borderRadius=_(r.radius);else if(r?.shape==="convex")c.style.setProperty("border-end-start-radius",`50% ${_(r.depth)}`),c.style.setProperty("border-end-end-radius",`50% ${_(r.depth)}`);else if(r?.shape==="concave"){let a=`radial-gradient(ellipse 50% ${_(r.depth)} at 50% 100%, transparent 98%, #000 100%)`;c.style.setProperty("-webkit-mask-image",a),c.style.setProperty("mask-image",a)}if(o){let a=P("img");a.src=o,a.decoding="async",a.style.objectFit=e.fit==="fill"?"cover":"contain",e.decorative===!0?(a.alt="",c.setAttribute("aria-hidden","true")):a.alt=String(e.alt??""),a.addEventListener("error",()=>a.style.visibility="hidden"),c.append(a)}if(e.overlay&&typeof e.overlay=="object"){let a=P("div","pw-overlay");a.style.backgroundImage=Ae(e.overlay)??"",c.append(a)}return{el:c,slots:{}}}function St(e){let c=P("div","pw-img");typeof e.aspect=="number"&&(c.style.aspectRatio=String(e.aspect));let o=Z(e.src);if(o){let r=P("video");r.src=o;let a=Z(e.poster);a&&(r.poster=a),r.muted=e.mute!==!1,r.loop=e.loop!==!1,r.playsInline=!0,r.controls=e.controls===!0,r.preload="auto",r.style.objectFit=e.fit==="fit"?"contain":"cover",r.autoplay=e.autoplay!==!1&&!re()&&!H(),typeof e.alt=="string"?r.setAttribute("aria-label",e.alt):r.setAttribute("aria-hidden","true"),c.append(r)}return{el:c,slots:{}}}function Rt(e,c){let o=e.action??{},r,a=o.type==="restore"||o.type==="offer_code";switch(o.type){case"close":c.inSheet?r=()=>pe(null):n.onClose&&(r=()=>n.onClose());break;case"restore":n.onRestore&&(r=()=>n.onRestore());break;case"offer_code":n.onOfferCode&&(x.platform??"web")!=="web"&&(r=()=>n.onOfferCode());break;case"open_url":case"terms":case"privacy":{let u=o.type==="open_url"?o.url:o.type==="terms"?x.links?.terms:x.links?.privacy;ye(u)&&(r=()=>n.onLink?n.onLink(u):void p?.open(u,"_blank","noopener,noreferrer"));break}case"sheet":o.sheet&&(r=()=>pe(o.sheet));break;case"select_package":o.package&&(r=()=>Se(o.package));break}if(!r&&!H())return null;let d=P("button");return d.type="button",o.type==="close"&&d.setAttribute("aria-label",le.close),d.addEventListener("click",()=>{!r||H()||(a?Ve(d,r):r())}),{el:d,slots:{content:d}}}function _t(e,c){let o=P("div","pw-tabs"),r=P("div","pw-tablist");r.setAttribute("role","tablist");let a=P("div","pw-tabpanel");a.setAttribute("role","tabpanel"),a.id=`${l}-${c}-panel`;let d={content:a},u=e.tabs.map(k=>k.id);return u.forEach((k,A)=>{let L=P("button","pw-tab");L.type="button",L.setAttribute("role","tab"),L.id=`${l}-${c}-tab-${A}`,L.setAttribute("aria-controls",a.id),L.dataset.tab=k,L.addEventListener("click",()=>Je(c,k)),L.addEventListener("keydown",z=>{let D=z.key==="ArrowRight"?A+1:z.key==="ArrowLeft"?A-1:z.key==="Home"?0:z.key==="End"?u.length-1:-2;if(D===-2)return;z.preventDefault();let B=u[(D+u.length)%u.length];Je(c,B),r.querySelector(`[data-tab="${B}"]`)?.focus()}),r.append(L),d[`label:${k}`]=L}),o.append(r,a),d.bar=r,{el:o,slots:d}}function Et(e,c){let o=P("div","pw-switch"),r=P("div","pw-switchrow"),a=P("span","pw-switchlabel");a.id=`${l}-${c}-label`;let d=P("button","pw-toggle");d.type="button",d.setAttribute("role","switch"),d.setAttribute("aria-labelledby",a.id),d.append(P("i")),d.addEventListener("click",()=>Ht(c,d.getAttribute("aria-checked")!=="true")),r.append(a,d);let u=P("div","pw-switchcontent");return o.append(r,u),{el:o,slots:{content:u,label:a,toggle:d}}}function Lt(e){let c=P("div","pw-carousel");c.setAttribute("role","region"),c.setAttribute("aria-roledescription","carousel");let o=P("div","pw-track");o.tabIndex=0,o.style.setProperty("--pw-peek",_(e.peek)),o.style.setProperty("--pw-gap",_(e.spacing)),typeof e.height=="number"&&(o.style.minHeight=_(e.height));let r=e.indicator??{},a=P("div",`pw-dots ${r.style??"dots"}`);a.style.setProperty("--pw-dot",_(r.size??8)),a.style.setProperty("--pw-dot-gap",_(r.spacing??6)),a.style.setProperty("--pw-dot-c",r.color??"#8888"),a.style.setProperty("--pw-dot-on",r.active_color??"currentColor"),r.style==="none"&&(a.hidden=!0),c.append(o,a);let d=()=>[...o.children].filter($=>$ instanceof(p?.HTMLElement??HTMLElement)),u=()=>{let $=d(),j=o.scrollLeft+o.clientWidth/2,O=0;return $.forEach((I,It)=>{Math.abs(I.offsetLeft+I.offsetWidth/2-j)<Math.abs(($[O]?.offsetLeft??0)+($[O]?.offsetWidth??0)/2-j)&&(O=It)}),O},k=$=>{let j=d();if(j.length===0)return;let O=e.loop?($+j.length)%j.length:Math.max(0,Math.min(j.length-1,$)),I=j[O];o.scrollTo?.({left:I.offsetLeft-(o.clientWidth-I.offsetWidth)/2,behavior:re()?"auto":"smooth"}),A(O)},A=$=>{[...a.children].forEach((j,O)=>j.setAttribute("aria-current",String(O===$)))};o.addEventListener("scroll",()=>A(u()),{passive:!0}),o.addEventListener("keydown",$=>{$.key!=="ArrowRight"&&$.key!=="ArrowLeft"||($.preventDefault(),k(u()+($.key==="ArrowRight"?1:-1)))});let L=!1,z=()=>L=!0,D=()=>L=!1;c.addEventListener("pointerenter",z),c.addEventListener("pointerleave",D),c.addEventListener("focusin",z),c.addEventListener("focusout",D);let B=[];if(typeof e.auto_advance_ms=="number"){let $=setInterval(()=>{if(L||re()||H())return;let j=d(),O=u();!e.loop&&O>=j.length-1||k(O+1)},e.auto_advance_ms);B.push(()=>clearInterval($))}return c.pwDots=$=>{a.children.length!==$&&(a.replaceChildren(...Array.from({length:$},(j,O)=>{let I=P("button");return I.type="button",I.setAttribute("aria-label",le.page(O+1,$)),I.addEventListener("click",()=>k(O)),I})),A(u()))},{el:c,slots:{pages:o},cleanup:B}}function $t(e,c){let o=c;switch(c.type){case"package":{let r=bn(o),d=!!x.packages[r]?.price;e.el.dataset.package=r,e.el.setAttribute("aria-checked",String(o.selected===!0)),e.el.setAttribute("aria-disabled",String(!d));break}case"purchase_button":{let r=String(o.package);e.el.dataset.package=r,e.el.disabled=K||!x.packages[r]?.price;break}case"switch":{let r=e.slots.toggle;r.setAttribute("aria-checked",String(o.on===!0)),r.style.setProperty("--pw-tint",String(o.tint??"")),r.style.setProperty("--pw-off",`color-mix(in srgb, ${b.tree.theme.colors.muted??"#888888"} 45%, transparent)`),e.slots.label.textContent=String(o.label??""),e.slots.label.hidden=o.label===void 0;break}case"tabs":{for(let r of o.tabs){let a=e.slots[`label:${r.id}`];a.setAttribute("aria-selected",String(r.selected)),a.tabIndex=r.selected?0:-1,r.selected&&e.slots.content.setAttribute("aria-labelledby",a.id)}o.bar&&De(e.slots.bar,{type:"stack",style:o.bar},"vertical");break}}}function Tt(e,c,o){let r=c,a={...o,inControl:o.inControl||c.type==="button"||c.type==="purchase_button"||c.type==="package"};switch(c.type){case"stack":case"package":{let d=c.type==="stack"?String(r.axis??"vertical"):"vertical",u=r.children.map(A=>[A,U(A,d,a)]).filter(A=>A[1]!==null),k=u.map(A=>A[1]);V(e.slots.children,k),zt(d,u),c.type==="stack"&&ce(e.el,k);break}case"button":case"purchase_button":{let d=r.content?U(r.content,"vertical",a):null;V(e.slots.content,d?[d]:[]);break}case"countdown":case"switch":{let d=r.content?U(r.content,"vertical",a):null;V(e.slots.content,d?[d]:[]),ce(e.slots.content,d?[d]:[]);break}case"tabs":{for(let u of r.tabs){let k=u.label?U(u.label,"vertical",{...a,inControl:!0}):null;V(e.slots[`label:${u.id}`],k?[k]:[])}let d=r.content?U(r.content,"vertical",a):null;V(e.slots.content,d?[d]:[]),ce(e.slots.content,d?[d]:[]);break}case"carousel":{let d=r.pages.map(u=>U(u,"page",a)).filter(Boolean);d.forEach((u,k)=>{u.setAttribute("role","group"),u.setAttribute("aria-roledescription","slide"),u.setAttribute("aria-label",le.page(k+1,d.length))}),V(e.slots.pages,d),ce(e.slots.pages,d),e.el.pwDots?.(d.length);break}}}function zt(e,c){let o=e==="horizontal"?"width":e==="vertical"?"height":null;if(!o)return;let r=u=>u?o==="width"?u.leading+u.trailing:u.top+u.bottom:0,a=c.filter(([u])=>u.style?.[o]==="fill"),d=Math.max(0,...a.map(([u])=>r(u.style?.padding)+r(u.style?.margin)));for(let[u,k]of a)k.style.flexBasis=_(d-r(u.style?.margin))}function ce(e,c){let o=c.filter(a=>a.dataset.pwType==="package");if(o.length===0){e.getAttribute("role")==="radiogroup"&&e.removeAttribute("role");return}e.setAttribute("role","radiogroup"),e.setAttribute("aria-label",le.packages);let r=o.find(a=>a.getAttribute("aria-checked")==="true")??o[0];for(let a of o)a.tabIndex=a===r?0:-1}function V(e,c){let o=()=>[...e.children].filter(a=>a.dataset?.pwPath!==void 0),r=o();for(let a of r)c.includes(a)||a.remove();r=o(),c.forEach((a,d)=>{r[d]!==a&&(e.insertBefore(a,r[d]??null),r=o())})}let Me=new WeakMap;function E(e,c,o){e.style.setProperty(c,o),Me.get(e).push(c)}function De(e,c,o){for(let u of Me.get(e)??[])e.style.removeProperty(u);Me.set(e,[]);for(let u of[...e.children])u.classList.contains("pw-bgvideo")&&u.remove();let r=c.style;if(c.type==="image"&&e.classList.toggle("natural",typeof c.aspect!="number"&&(r?.height===void 0||r.height==="fit")),!r)return;let a=(u,k)=>{k&&(E(e,`${u}-block-start`,_(k.top)),E(e,`${u}-block-end`,_(k.bottom)),E(e,`${u}-inline-start`,_(k.leading)),E(e,`${u}-inline-end`,_(k.trailing)))};a("padding",r.padding),a("margin",r.margin),Ie(e,"width",r.width,o),typeof r.height=="number"&&un.has(c.type)?(E(e,"min-height",_(r.height)),o==="vertical"&&E(e,"flex","none")):Ie(e,"height",r.height,o),typeof r.max_width=="number"&&E(e,"max-width",_(r.max_width));let d=r.background;if(d){if(d.type==="color")E(e,"background-color",d.color);else if(d.type==="linear"||d.type==="radial")E(e,"background-image",Ae(d)??"");else if(d.type==="image"){let u=Z(d.src);u&&(E(e,"background-image",`url("${u.replace(/"/g,"%22")}")`),E(e,"background-size",d.fit==="fit"?"contain":"cover"),E(e,"background-position","center"),E(e,"background-repeat","no-repeat"))}else if(d.type==="video"){let u=Z(d.src);if(u){let k=P("video","pw-bgvideo");k.src=u;let A=Z(d.poster);A&&(k.poster=A),k.muted=!0,k.loop=d.loop!==!1,k.playsInline=!0,k.autoplay=!re()&&!H(),k.setAttribute("aria-hidden","true"),E(e,"isolation","isolate"),e.prepend(k)}}}if(r.border&&c.type==="custom_html"?E(e,"border",`${_(r.border.width)} solid ${r.border.color??"transparent"}`):r.border&&(E(e,"--pw-bw",_(r.border.width)),E(e,"--pw-bc",r.border.color??"transparent")),r.corners){let u=r.corners;E(e,"border-start-start-radius",_(u.top_leading)),E(e,"border-start-end-radius",_(u.top_trailing)),E(e,"border-end-start-radius",_(u.bottom_leading)),E(e,"border-end-end-radius",_(u.bottom_trailing)),(c.type==="image"||c.type==="video"||d?.type==="image"||d?.type==="video")&&E(e,"overflow","hidden")}r.shadow&&E(e,"box-shadow",`${_(r.shadow.x)} ${_(r.shadow.y)} ${_(r.shadow.radius)} ${r.shadow.color}`),typeof r.opacity=="number"&&r.opacity!==1&&E(e,"opacity",String(r.opacity))}function Ie(e,c,o,r){if(o==null||o==="")return;if(r==="page"){c==="height"&&E(e,"height",o==="fill"?"100%":typeof o=="number"?_(o):o==="fit"?"fit-content":String(o));return}let a=r==="horizontal"?"width":r==="vertical"?"height":null;o==="fill"?c===a?(E(e,"flex","1 1 0"),E(e,`min-${c}`,"0")):r==="z"?E(e,c,"100%"):(E(e,"align-self","stretch"),E(e,c,"auto")):o==="fit"?(c===a&&E(e,"flex","0 0 auto"),E(e,c,"fit-content")):(E(e,c,typeof o=="number"?_(o):String(o)),c===a&&E(e,"flex","none"))}function Ae(e){let c=o=>o.map(r=>`${r.color} ${(r.at*100).toFixed(2)}%`).join(", ");if(e.type==="linear")return`linear-gradient(${e.angle}deg, ${c(e.stops)})`;if(e.type==="radial"){let o=`${(e.radius*100).toFixed(2)}%`;return`radial-gradient(ellipse ${o} ${o} at ${(e.center_x*100).toFixed(2)}% ${(e.center_y*100).toFixed(2)}%, ${c(e.stops)})`}}function Ot(e,c){let o=c.animation;if(!o||x.animate===!1||re()||typeof e.animate!="function")return;let r=24,d={fade:{opacity:0},slide_up:{opacity:0,transform:`translateY(${r}px)`},slide_down:{opacity:0,transform:`translateY(-${r}px)`},slide_leading:{opacity:0,transform:`translateX(-${r}px)`},slide_trailing:{opacity:0,transform:`translateX(${r}px)`},scale:{opacity:0,transform:"scale(0.92)"}}[o.type];d&&e.animate([d,{opacity:1,transform:"none"}],{duration:o.duration_ms,delay:o.delay_ms,easing:ut[o.easing]??ut.ease_out,fill:"backwards"})}function de(){n.onState?.({...R}),G()}function Se(e){R.selected===e&&b.tree.selected===e||(R.selected=e,de(),n.onSelect?.(Te(e)))}function Re(e){H()||e.getAttribute("aria-disabled")==="true"||Se(e.dataset.package??"")}function Ft(e,c){if(e.key===" "||e.key==="Enter"){e.preventDefault(),Re(c);return}let o=e.key==="ArrowDown"||e.key==="ArrowRight"?1:e.key==="ArrowUp"||e.key==="ArrowLeft"?-1:0;if(o===0)return;e.preventDefault();let r=c.closest("[role=radiogroup]"),d=(r?[...r.children].filter(A=>A.dataset.pwType==="package"):[c]).filter(A=>A.getAttribute("aria-disabled")!=="true"),u=d.indexOf(c),k=d[(u+o+d.length)%d.length];k&&(Re(k),(T.get(k.dataset.pwPath??"")?.el??k).focus())}function Je(e,c){if(H())return;R.tabs={...R.tabs,[e]:c};let o=Ct(e,c);o&&(R.selected=o),de()}function Ct(e,c){return Ue(e)?.tabs?.find(r=>r.id===c)?.package}function Ht(e,c){if(H())return;R.switches={...R.switches,[e]:c};let o=Ue(e),r=c?o?.on_package:o?.off_package;r&&(R.selected=r),de()}function Ue(e){let c=x.definition;for(let o of e.match(/[^.[\]]+/g)??[])c=c?.[/^\d+$/.test(o)?Number(o):o];return c}async function Ve(e,c){if(!(H()||K)){K=!0,e.disabled=!0,e.setAttribute("aria-busy","true");try{await c()}finally{K=!1,e.removeAttribute("aria-busy"),e.disabled=!1;for(let o of T.values())o.type==="purchase_button"&&(o.el.disabled=!x.packages[o.el.dataset.package??""]?.price)}}}async function jt(e){x.packages[e]?.price&&await n.onPurchase(Te(e))}function pe(e){H()&&e!==null&&R.sheet===e||(e&&!R.sheet&&(je=y.activeElement??null),R.sheet=e,de(),e||je?.focus())}function Nt(){let e=R.sheet,c=e?b.tree.sheets?.[e]:void 0;if(!c){M.remove();return}M.className="pw-layer";let o=M.firstElementChild;if(!o){o=P("div","pw-sheet"),o.setAttribute("role","dialog"),o.setAttribute("aria-modal","true"),o.tabIndex=-1;let a=P("div","pw-grab");a.setAttribute("aria-hidden","true"),o.append(a),M.append(o),M.addEventListener("click",d=>{d.target===M&&!H()&&pe(null)}),o.addEventListener("keydown",d=>Dt(d,o))}o.style.background=b.tree.theme.colors.background??"",o.setAttribute("aria-label",b.sheetTitles[e]??"");let r=U(c,"vertical",{inControl:!1,inSheet:!0});V(o,r?[r]:[]),M.isConnected||(g.append(M),queueMicrotask(()=>(Be(o)[0]??o).focus()))}function Be(e){return[...e.querySelectorAll('button:not([disabled]), a[href], [tabindex]:not([tabindex="-1"])')].filter(c=>!c.hidden)}function Dt(e,c){if(e.key==="Escape"){e.preventDefault(),pe(null);return}if(e.key!=="Tab")return;let o=Be(c);if(o.length===0){e.preventDefault();return}let r=o[0],a=o[o.length-1],d=y.activeElement;e.shiftKey&&d===r?(e.preventDefault(),a.focus()):!e.shiftKey&&d===a&&(e.preventDefault(),r.focus())}function qe(e){try{e.contentWindow?.postMessage({type:"palbase.paywall",package:b.tree.selected,locale:b.language,appearance:x.appearance},"*")}catch{}}function We(e){for(let c of y.querySelectorAll("[data-pw-highlight]"))c.removeAttribute("data-pw-highlight");be=e,e&&T.get(e)?.el.setAttribute("data-pw-highlight","")}let Ke=e=>e.composedPath().find(c=>c instanceof(p?.HTMLElement??HTMLElement)&&c.dataset.pwPath!==void 0);g.addEventListener("click",e=>{if(!n.editor)return;let c=Ke(e);c&&(e.preventDefault(),e.stopPropagation(),n.editor.onPick(c.dataset.pwPath))},!0),g.addEventListener("pointerover",e=>{if(n.editor){for(let c of y.querySelectorAll("[data-pw-hover]"))c.removeAttribute("data-pw-hover");Ke(e)?.setAttribute("data-pw-hover","")}}),g.addEventListener("pointerleave",()=>{for(let e of y.querySelectorAll("[data-pw-hover]"))e.removeAttribute("data-pw-hover")});let Xe=()=>G();return ke?.addEventListener?.("change",Xe),G(),{get selected(){return Te(b.tree.selected)},get state(){return{...R}},select(e){Se(e)},update(e){x={...x,...e},e.state&&Object.assign(R,e.state),G()},highlight(e){We(e)},replay(){for(let e of T.values())e.cleanup.forEach(c=>c());T=new Map;for(let e of[h,w,v])e.replaceChildren();G()},destroy(){clearTimeout(ve),Ce?.disconnect(),i.fonts?.removeEventListener?.("loadingdone",He),ke?.removeEventListener?.("change",Xe);for(let e of T.values())e.cleanup.forEach(c=>c());f.remove()}}}function kn(s,t,n){let i=s.defaultView;try{if(i&&"adoptedStyleSheets"in t&&typeof i.CSSStyleSheet=="function"){let l=new i.CSSStyleSheet;l.replaceSync(n),t.adoptedStyleSheets=[l];return}}catch{}let p=s.createElement("style");p.textContent=n,t.append(p)}var ht={version:"0.3.2"};var yt=`palbase-js/${ht.version}`;var we=class{placement;source;definition;assets;offerings;shown;deps;exposed=!1;constructor(t,n,i,p,l,f,y={}){this.placement=t,this.source=n,this.definition=i,this.assets=y,this.offerings=p,this.shown=l,this.deps=f}packages(t){return rt(An(this.offerings,ct(this.definition),t),t)}render(t,n){let i=n.locale??globalThis.navigator?.language??this.definition.default_locale,p=n.appearance===void 0?Pn():void 0,l=this.packages(i),f=gt(t,{definition:this.definition,locale:i,appearance:n.appearance??(p?.matches?"dark":"light"),platform:"web",packages:l,eligible:Object.entries(l).filter(([,h])=>h.trial).map(([h])=>h),links:n.links,assets:this.assets},{onPurchase:async h=>{try{let w=await this.deps.checkout({product:h.product,plan:h.plan,successUrl:n.successUrl,cancelUrl:n.cancelUrl});n.onCheckout?n.onCheckout(w,h):globalThis.location.assign(w)}catch(w){if(!n.onError)throw w;n.onError(w,h)}},onClose:n.onClose,onLink:n.onLink,labels:n.labels}),y=h=>f.update({appearance:h.matches?"dark":"light"});p?.addEventListener?.("change",y),!this.exposed&&this.shown&&(this.exposed=!0,this.deps.expose(this));let g=f.destroy.bind(f);return f.destroy=()=>{p?.removeEventListener?.("change",y),g()},f}};function Pn(){try{return globalThis.matchMedia?.("(prefers-color-scheme: dark)")}catch{return}}function Mn(s,t){if(!s)return;let n=t.split("-")[0];return s[t]?.name??s[n]?.name??Object.values(s).find(i=>i.name)?.name}function An(s,t,n){let i=[];for(let p of t){let[l,f]=p.split("."),y=s.products.find(w=>w.key===l),g=y?.channels.web,h=g?.plans.find(w=>w.key===f);!y||!g||!h||i.push({key:p,productName:Mn(g.locales,n)??y.key,price:{amount:h.price.amount,currency:h.price.currency},period:h.period,intro:h.intro})}return i}var Sn={en:{cta:"Continue",terms:"Terms",privacy:"Privacy"},tr:{cta:"Devam et",terms:"Ko\u015Fullar",privacy:"Gizlilik"},de:{cta:"Weiter",terms:"Bedingungen",privacy:"Datenschutz"},es:{cta:"Continuar",terms:"T\xE9rminos",privacy:"Privacidad"},fr:{cta:"Continuer",terms:"Conditions",privacy:"Confidentialit\xE9"},it:{cta:"Continua",terms:"Termini",privacy:"Privacy"},pt:{cta:"Continuar",terms:"Termos",privacy:"Privacidade"},nl:{cta:"Doorgaan",terms:"Voorwaarden",privacy:"Privacy"},ja:{cta:"\u7D9A\u3051\u308B",terms:"\u5229\u7528\u898F\u7D04",privacy:"\u30D7\u30E9\u30A4\u30D0\u30B7\u30FC"}},mt=s=>({type:"button",action:{type:s},content:{type:"text",text:{t:s},size:"caption",color:"muted"}});function Rn(s){let t=s.products.flatMap(n=>(n.channels.web?.plans??[]).map(i=>({product:n.key,plan:i.key}))).slice(0,6);return t.length===0?null:{schema:2,name:"Default",default_locale:"en",locales:Sn,theme:{colors:{light:{background:"#FFFFFF",surface:"#F2F2F7",text:"#111114",muted:"#6B6B70",accent:"#111114",on_accent:"#FFFFFF",stroke:"#E5E5EA"},dark:{background:"#000000",surface:"#1C1C1E",text:"#F5F5F7",muted:"#9A9AA0",accent:"#F5F5F7",on_accent:"#000000",stroke:"#2C2C2E"}},typography:{headline:{size:17,weight:600,text_style:"headline"},caption:{size:13,weight:400,text_style:"footnote"}},radii:{card:14},spacing:{sm:8,md:16,lg:24}},root:{type:"stack",spacing:"md",align:"stretch",style:{padding:"lg"},children:[{type:"stack",axis:"horizontal",children:[{type:"spacer"},{type:"button",action:{type:"close"},content:{type:"icon",name:"close",color:"muted",size:22}}]},{type:"spacer"},{type:"stack",spacing:"sm",align:"stretch",children:t.map(({product:n,plan:i})=>({type:"package",product:n,plan:i,style:{padding:"md",corners:"card",background:"surface",border:{width:1,color:"stroke"}},states:{selected:{border:{width:2,color:"accent"}}},children:[{type:"stack",axis:"horizontal",spacing:"sm",children:[{type:"stack",align:"start",spacing:2,children:[{type:"text",text:"{{product_name}}",size:"headline",align:"start"},{type:"text",text:"{{period}}",size:"caption",color:"muted",align:"start"}]},{type:"spacer"},{type:"text",text:"{{price}}",size:"headline"}]}]}))},{type:"purchase_button",style:{padding:"md",corners:"card",background:"accent"},content:{type:"text",text:{t:"cta"},size:"headline",color:"on_accent"}},{type:"stack",axis:"horizontal",spacing:"md",distribution:"center",children:[mt("terms"),mt("privacy")]}]}}}function se(){try{return globalThis.localStorage}catch{return}}function _n(s){try{let t=se()?.getItem(s);if(!t)return;let n=JSON.parse(t),i=n?.answer;return typeof i!="object"||i===null||typeof i.paywall_id!="string"||typeof i.version!="number"||typeof i.definition!="object"||i.definition===null||typeof i.offerings!="object"||i.definition.schema!==2?void 0:{etag:typeof n.etag=="string"?n.etag:void 0,answer:i}}catch{return}}function me(s,t){try{t?se()?.setItem(s,JSON.stringify(t)):se()?.removeItem(s)}catch{}}var wt=()=>globalThis.crypto?.randomUUID?globalThis.crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,bt;function En(s){let t=`palbase.installation.${s}`;try{let n=se()?.getItem(t);if(n&&/^[A-Za-z0-9._:-]{1,128}$/.test(n))return n;let i=wt();if(se()?.setItem(t,i),se()?.getItem(t)===i)return i}catch{}return bt??=wt(),bt}async function Zn(s,t,n,i,p={}){let{signal:l,fetch:f}=p,y=tt(p.attributes),g=`palbase.paywall.${t}.${n}`,h=En(t),v={checkout:i,expose:async b=>{if(b.shown)try{let T={paywall_id:b.shown.paywallId,version:b.shown.version,...b.shown.variant!==void 0?{variant:b.shown.variant}:{},...b.shown.ruleId!==void 0?{rule_id:b.shown.ruleId}:{}};await s.recordPaywallExposure({path:{placement:n},headers:{"X-Palbase-Installation":h},body:T})}catch{}}},M=async(b,T)=>new we(n,T,b.definition,b.offerings,{paywallId:b.paywall_id,version:b.version,...b.variant!==void 0?{variant:b.variant}:{},...b.rule_id!==void 0?{ruleId:b.rule_id}:{}},v,await Ge(b.assets??[],{signal:l,...f?{fetch:f}:{}})),x=_n(g),R;try{R=await s.getPlacementPaywall({path:{placement:n},query:{channel:"web"},headers:{"X-Palbase-Paywall-Schema":2,"X-Palbase-Installation":h,"X-Platform":"web","X-Palbase-SDK":yt,...p.appVersion?{"X-Palbase-Client-Version":p.appVersion}:{},...p.locale?{"Accept-Language":p.locale}:{},...y!==void 0?{"X-Palbase-Attributes":y}:{},...x?.etag?{"If-None-Match":x.etag}:{}},signal:l})}catch(b){if(b instanceof oe&&b.status===404||b instanceof oe&&b.status===400&&b.code.startsWith("invalid_"))return me(g,void 0),ze(s,n,v,l);if(x&&!l?.aborted)return M(x.answer,"cache");throw b}return R.status===200?(me(g,{etag:R.headers.get("etag")??void 0,answer:R.data}),M(R.data,"server")):R.status===304&&x?M(x.answer,"server"):(me(g,void 0),ze(s,n,v,l))}async function ze(s,t,n,i){let p=(await s.getOfferings({query:{channel:"web"},signal:i})).data,l=Rn(p);return l?new we(t,"default",l,p,void 0,n):null}export{Ut as a,ie as b,Ge as c,qt as d,Yt as e,tt as f,_e as g,st as h,Qt as i,rt as j,ue as k,he as l,Fn as m,cn as n,ct as o,Cn as p,dt as q,gt as r,we as s,Rn as t,Zn as u};