palbase 0.41.3 → 0.42.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/ai/index.js +2 -2
- package/dist/backend/engine.js +2 -2
- package/dist/backend/env.js +1 -1
- package/dist/backend/index.js +3 -3
- package/dist/backend/stack.js +1 -1
- package/dist/backend/test.js +2 -2
- package/dist/chunks/{SAEDHCLG.js → 3B26HF2E.js} +1 -1
- package/dist/chunks/{DZ42B54P.js → 4FY2JOIE.js} +2 -2
- package/dist/chunks/{J2V2M7AR.js → 6RAP4AII.js} +2 -2
- package/dist/chunks/{TR4QVM6S.js → AQV3OQRL.js} +2 -2
- package/dist/chunks/{SHLEYBMA.js → DS4WQJZM.js} +2 -2
- package/dist/chunks/{W7HXA3GG.js → DY65FDLF.js} +1 -1
- package/dist/chunks/{TODHBOYI.js → EEYIFP7R.js} +2 -2
- package/dist/chunks/{23GI3WXJ.js → I6WTPZ6G.js} +2 -2
- package/dist/chunks/{RSSGWX2P.js → L3OT55MV.js} +2 -2
- package/dist/chunks/{PHTKXJQC.js → L3W75GPJ.js} +2 -2
- package/dist/chunks/{I2XPZKQA.js → LOINJWR3.js} +2 -2
- package/dist/chunks/{QYQ7DJGF.js → MS4WUVDW.js} +1 -1
- package/dist/chunks/{CYOZ3JBE.js → OYA6Z4VI.js} +1 -1
- package/dist/chunks/{SSCQX6RH.js → POCZ4Q2I.js} +1 -1
- package/dist/chunks/{ZSPTBM6M.js → QG2BSVEO.js} +3 -3
- package/dist/chunks/{HAP72KDI.js → QQKGUVDV.js} +2 -2
- package/dist/chunks/{AIFN5SFN.js → RNDFA3AQ.js} +2 -2
- package/dist/chunks/{WAOH3WJH.js → RVXJJALR.js} +2 -2
- package/dist/chunks/{EOTFJUMQ.js → SMINGDYN.js} +2 -2
- package/dist/chunks/{Y6OOWIMM.js → TUMSSUUS.js} +1 -1
- package/dist/chunks/{AOH3QHRO.js → UGFLMEVH.js} +2 -2
- package/dist/chunks/{FMCESDD6.js → VBROMD5X.js} +1 -1
- package/dist/chunks/{KQ2J6PEQ.js → VXH23FMT.js} +2 -2
- package/dist/cli.js +118 -118
- package/dist/cloud/index.js +2 -2
- package/dist/refuse/ai.js +1 -1
- package/dist/refuse/backend.js +1 -1
- package/dist/refuse/cloud.js +1 -1
- package/dist/refuse/server.js +1 -1
- package/dist/server/index.js +2 -2
- package/dist/server/testing.js +2 -2
- package/dist/web/index.js +2 -2
- package/dist/web/message.js +2 -2
- package/dist/web/palbe.js +2 -2
- package/dist/web/paywall.js +2 -2
- package/dist/web/push-sw.js +1 -1
- package/dist/web/ssr.js +2 -2
- package/dist/web/vite.js +2 -2
- package/package.json +2 -2
- package/types/internal/src/modules/machines.d.ts +74 -22
package/dist/ai/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
2
|
-
import{a,b,c,d,e,f}from"../chunks/
|
|
1
|
+
/*! palbase 0.42.0 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{a,b,c,d,e,f}from"../chunks/RNDFA3AQ.js";import"../chunks/LOINJWR3.js";import"../chunks/MS4WUVDW.js";import"../chunks/SMINGDYN.js";import"../chunks/6RAP4AII.js";import"../chunks/DS4WQJZM.js";import"../chunks/TUMSSUUS.js";import"../chunks/DY65FDLF.js";export{e as AIResponseError,b as AISchemaError,d as ToolError,f as createAI,a as partial,c as prepare};
|
package/dist/backend/engine.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
2
|
-
import{ia as w,ma as h}from"../chunks/
|
|
1
|
+
/*! palbase 0.42.0 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{ia as w,ma as h}from"../chunks/UGFLMEVH.js";import"../chunks/I6WTPZ6G.js";import"../chunks/L3W75GPJ.js";import"../chunks/RNDFA3AQ.js";import"../chunks/LOINJWR3.js";import"../chunks/RVXJJALR.js";import"../chunks/POCZ4Q2I.js";import"../chunks/OYA6Z4VI.js";import"../chunks/MS4WUVDW.js";import"../chunks/SMINGDYN.js";import"../chunks/6RAP4AII.js";import"../chunks/DS4WQJZM.js";import"../chunks/TUMSSUUS.js";import"../chunks/DY65FDLF.js";import{binding as R,createDatabase as v}from"palgres";var y=new WeakMap;function q(p,e,a){if(!a?.schemas?.length)throw new TypeError("createRequestDatabase(sql, identity, { schemas }): the engine compiles each call against the app's schemas \u2014 pass the schema files' default exports");let u=a.schemas,n=y.get(p);n||y.set(p,n=new Map);let r=n.get(u);r||n.set(u,r=new Map);let o=e.role===e.serviceRole?"service":e.role==="anon"?"anon":"authenticated",g=o==="service"?{service:e.serviceRole}:{[o]:e.role,service:e.serviceRole},f=`${o}\0${e.role}\0${e.serviceRole}`,i=r.get(f);i||(i=v({sql:p,schemas:u,binding:R(0,!0),roles:g,...a.fields!==void 0?{fields:a.fields}:{}}),r.set(f,i));let b=JSON.parse(e.claimsJson),m=i.then(s=>s.request({role:o,claims:b},{diagnostics:a.diagnostics,signal:a.signal})),d=s=>new Proxy(()=>{},{apply:async(t,D,c)=>{let l=(await m).client;return s(l).apply(l,c)}});return{client:new Proxy({},{get(s,t){if(t!=="then")return t==="diagnostics"?()=>null:t==="asService"?()=>new Proxy({},{get:(D,c)=>c==="then"?void 0:d(l=>l.asService()[c])}):d(D=>D[t])}}),commit:async()=>(await m).commit(),rollback:async s=>(await m).rollback(s)}}export{w as createApp,q as createRequestDatabase,h as makeMemoryCache};
|
package/dist/backend/env.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
1
|
+
/*! palbase 0.42.0 — Palbase SDK License (see LICENSE) */
|
package/dist/backend/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
2
|
-
import{$ as $t,A as ut,B as F,C as pt,D as ht,E as ft,F as mt,G as gt,H as bt,I as yt,J as wt,K as Pt,L as St,M as vt,N as At,O as kt,P as Et,Q as Tt,R as xt,S as Rt,T as _t,U as Ot,V as Ct,W as Bt,X as Ft,Y as se,Z as Mt,_ as It,a as X,aa as Lt,b as Z,ba as Dt,c as ee,ca as Ut,d as qe,da as jt,e as We,ea as Nt,f as Ke,fa as qt,g as Ve,ga as M,h as Ge,ha as Gt,i as ze,ia as I,j as He,ja as G,k as Ye,ka as zt,l as Je,la as Ht,m as Qe,n as Xe,o as Ze,p as et,q as tt,r as rt,s as st,t as nt,u as at,v as ot,w as it,x as lt,y as ct,z as dt}from"../chunks/AOH3QHRO.js";import{a as Wt,b as Kt}from"../chunks/23GI3WXJ.js";import{a as ae}from"../chunks/FMCESDD6.js";import{a as _,b as te,c as re,f as g,g as V,h as d,j as ne,k as Vt}from"../chunks/PHTKXJQC.js";import"../chunks/AIFN5SFN.js";import"../chunks/I2XPZKQA.js";import{d as R,j as je,k as Ne,l as Y,m as B,t as J,u as Q}from"../chunks/WAOH3WJH.js";import"../chunks/SSCQX6RH.js";import"../chunks/CYOZ3JBE.js";import"../chunks/QYQ7DJGF.js";import{p as Ue}from"../chunks/EOTFJUMQ.js";import"../chunks/J2V2M7AR.js";import{b as E,c as K}from"../chunks/SHLEYBMA.js";import"../chunks/Y6OOWIMM.js";import"../chunks/W7HXA3GG.js";import"reflect-metadata";import{existsSync as z,writeFileSync as Rr,writeSync as _r}from"node:fs";import{createServer as Or}from"node:http";import{dirname as T,join as H,resolve as _e}from"node:path";import{Readable as Cr}from"node:stream";var Yt=2e3,Jt=1e4,Qt=/^[A-Za-z0-9_-]{1,64}$/,Xt=512,$=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??Jt,this.shutdownMs=r.shutdownMs??Yt,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:Qt.test(e.requestId)?e.requestId:e.requestId.replace(/[^A-Za-z0-9_-]/g,"_").slice(0,64)||"unnamed",source:"backend",endpoint:e.endpoint.slice(0,Xt),method:e.method,status:e.status,duration_ms:Math.max(0,Math.round(e.durationMs)),timestamp:this.now(),...e.userId?{distinct_id:e.userId}:{}}),this.pending.length>=this.batchSize&&!this.sending?this.send():!this.timer&&!this.sending&&this.schedule(this.flushMs)}schedule(e){this.timer=setTimeout(()=>{this.send()},e),this.timer.unref?.()}send(){if(this.timer&&clearTimeout(this.timer),this.timer=void 0,this.sending||this.pending.length===0||this.now()<this.pausedUntil||!this.sink)return this.sending??Promise.resolve();let e=this.pending.splice(0,this.batchSize),r=this.sink,s={call:new AbortController,traces:e.length,letGo:!1};this.inFlight=s;let n=setTimeout(()=>s.call.abort(new Error(`analytics did not answer in ${this.sendMs} ms`)),this.sendMs);return n.unref?.(),this.sending=(async()=>{try{await r.sendTraceBatch({body:{traces:e},signal:s.call.signal})}catch(a){if(s.letGo)return;let i=a.status,o=i??(s.call.signal.aborted?`no answer in ${this.sendMs} ms`:"unreachable"),c=a.retryAfter;this.pausedUntil=this.now()+(typeof c=="number"&&c>0?c*1e3:i===429?1e3:5e3),this.now()-this.lastSendWarning>6e4&&(this.lastSendWarning=this.now(),d.warn(`[palbase] request traces were not sent to analytics (${o}); ${e.length} dropped`,{error:a}))}finally{if(clearTimeout(n),this.sending=void 0,this.inFlight=void 0,this.pending.length>0){let a=Math.max(0,this.pausedUntil-this.now());this.schedule(this.pending.length>=this.batchSize?a:Math.max(a,this.flushMs))}}})(),this.sending}};import{createHmac as Zt}from"node:crypto";import{bind as er,bunDriver as tr,createDatabase as rr,envBlock as sr,createSearchWorker as nr,cutOff as ar,forgetUserIn as or,MigrationOpen as ir,MigrationRefused as lr,Migrator as de,renewingBunPool as oe,VersionNotMigrated as cr}from"palgres";import{toModel as ue}from"palgres/dsl";var dr=["start","complete","rollback","plan","status","types"],ur=/^(deploy|cli:[^\u0000-\u001f\u007f]{1,200})$/u;function pe(t){let e=t.PALBASE_DB_MIGRATE;if(!(e===void 0||e==="")){if(!dr.includes(e))throw new Error(`[palbase] PALBASE_DB_MIGRATE is start, complete, rollback, plan, status or types, not ${e}`);return e}}function he(t){let e=Array.isArray(t.schemas)?t.schemas:[t.schemas];for(let r of e)if(r.name===M.name)throw new Error(`[palbase] db.schemas: the ${M.name} schema is the framework's own (its tables are migrated with the app's) \u2014 name the app's schema otherwise`);return[...e,M]}function D(t){return ue(he(t))}function pr(t){return t.tables.some(e=>e.search!==void 0)}function U(t){return t.tables.some(e=>!e.ignored&&e.columns.some(r=>r.user!==void 0&&!r.ignored))}function fe(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 hr(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 ie=5;function me(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=oe(()=>new r.SQL({url:n,prepare:!1,max:s})),i=oe(()=>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:tr(a,i),poolSize:s,close:async()=>{await a.close({timeout:ie}),await i.close({timeout:ie})}}}}async function ge(t){return t==="rollback"?(d.info("[palbase] migrate rollback: this app declares no database; nothing of it to take back"),await O(t,{state:"none"}),0):(d.error(`[palbase] migrate ${t}: this app declares no database \u2014 PalbaseFactory.create(\u2026, { db: { schemas } })`),1)}async function be(t,e){if(!t)return d.error("[palbase] db types: this app declares no database \u2014 PalbaseFactory.create(\u2026, { db: { schemas } })"),1;let r=Array.isArray(t.schemas)?t.schemas:[t.schemas];return await O("types",sr(r,{module:"palbase/backend/env"}),e),0}async function ye(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(!ur.test(n))return d.error("[palbase] PALBASE_DB_MIGRATION_BY is deploy, or cli:<who>"),1;let a=me(t,fe(e)),i=a(s),o,c=l=>d.error(`[palbase] migrate ${r}: ${l}`);try{let l=D(t),u=new de(i.pool,{log:f=>{/ is held by others | held by writers/.test(f)&&(o=f.trim()),d.info(f)},shadow:f=>{let m=new URL(s);m.pathname=`/${f}`;let y=a(m.toString());return{reserve:()=>y.pool.reserve(),end:()=>y.close()}},openedBy:n,fields:()=>fr(e)});if(r==="plan"){let f=await u.plan(l);return await O(r,f),f.refusals.length>0?1:0}if(r==="status")return await O(r,await u.status()),0;let h=r==="start"?await mr(u,l,n):r==="complete"?await u.complete():await u.rollback();return d.info(`[palbase] migrate ${r}: done`,{result:h}),await O(r,h),0}catch(l){return l instanceof lr?(d.error(`[palbase] migrate ${r}: refused`,{refusals:l.refusals}),c(`refused \u2014 ${l.refusals.join("; ")}`),1):ar(l)?(d.error(`[palbase] migrate ${r}: cut off; run again, it goes on from where it stopped`,{error:l}),c(`cut off \u2014 ${o??le(l)}`),75):(d.error(`[palbase] migrate ${r}: failed`,{error:l}),c(`failed \u2014 ${le(l)}`),1)}finally{await i.close().catch(()=>{})}}async function fr(t){let e=t.PALBASE_URL,r=t.PALBASE_SECRET_KEY;if(!e||!r)throw new Error("[palbase] this migration seals or opens an encrypted column's rows: it reads the project's field keys with PALBASE_URL and PALBASE_SECRET_KEY");let s=R({url:e,secretKey:r}).fields;return await s.load(),s.close(),s}async function mr(t,e,r){try{return await t.start(e)}catch(s){if(!(s instanceof ir)||r!=="deploy"||!s.openedBy?.startsWith("cli:"))throw s;return d.warn(`[palbase] migrate start: the migration ${s.openedBy} opened (version ${s.to}) gives way to this release \u2014 rolled back first`),await t.rollback(),await t.start(e)}}var gr=(t,e)=>{process.stdout.write(t,()=>e())};function O(t,e,r=gr){return new Promise(s=>r(`${JSON.stringify({palbase_migrate:t,result:e})}
|
|
1
|
+
/*! palbase 0.42.0 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{$ as $t,A as ut,B as F,C as pt,D as ht,E as ft,F as mt,G as gt,H as bt,I as yt,J as wt,K as Pt,L as St,M as vt,N as At,O as kt,P as Et,Q as Tt,R as xt,S as Rt,T as _t,U as Ot,V as Ct,W as Bt,X as Ft,Y as se,Z as Mt,_ as It,a as X,aa as Lt,b as Z,ba as Dt,c as ee,ca as Ut,d as qe,da as jt,e as We,ea as Nt,f as Ke,fa as qt,g as Ve,ga as M,h as Ge,ha as Gt,i as ze,ia as I,j as He,ja as G,k as Ye,ka as zt,l as Je,la as Ht,m as Qe,n as Xe,o as Ze,p as et,q as tt,r as rt,s as st,t as nt,u as at,v as ot,w as it,x as lt,y as ct,z as dt}from"../chunks/UGFLMEVH.js";import{a as Wt,b as Kt}from"../chunks/I6WTPZ6G.js";import{a as ae}from"../chunks/VBROMD5X.js";import{a as _,b as te,c as re,f as g,g as V,h as d,j as ne,k as Vt}from"../chunks/L3W75GPJ.js";import"../chunks/RNDFA3AQ.js";import"../chunks/LOINJWR3.js";import{d as R,j as je,k as Ne,l as Y,m as B,t as J,u as Q}from"../chunks/RVXJJALR.js";import"../chunks/POCZ4Q2I.js";import"../chunks/OYA6Z4VI.js";import"../chunks/MS4WUVDW.js";import{p as Ue}from"../chunks/SMINGDYN.js";import"../chunks/6RAP4AII.js";import{b as E,c as K}from"../chunks/DS4WQJZM.js";import"../chunks/TUMSSUUS.js";import"../chunks/DY65FDLF.js";import"reflect-metadata";import{existsSync as z,writeFileSync as Rr,writeSync as _r}from"node:fs";import{createServer as Or}from"node:http";import{dirname as T,join as H,resolve as _e}from"node:path";import{Readable as Cr}from"node:stream";var Yt=2e3,Jt=1e4,Qt=/^[A-Za-z0-9_-]{1,64}$/,Xt=512,$=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??Jt,this.shutdownMs=r.shutdownMs??Yt,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:Qt.test(e.requestId)?e.requestId:e.requestId.replace(/[^A-Za-z0-9_-]/g,"_").slice(0,64)||"unnamed",source:"backend",endpoint:e.endpoint.slice(0,Xt),method:e.method,status:e.status,duration_ms:Math.max(0,Math.round(e.durationMs)),timestamp:this.now(),...e.userId?{distinct_id:e.userId}:{}}),this.pending.length>=this.batchSize&&!this.sending?this.send():!this.timer&&!this.sending&&this.schedule(this.flushMs)}schedule(e){this.timer=setTimeout(()=>{this.send()},e),this.timer.unref?.()}send(){if(this.timer&&clearTimeout(this.timer),this.timer=void 0,this.sending||this.pending.length===0||this.now()<this.pausedUntil||!this.sink)return this.sending??Promise.resolve();let e=this.pending.splice(0,this.batchSize),r=this.sink,s={call:new AbortController,traces:e.length,letGo:!1};this.inFlight=s;let n=setTimeout(()=>s.call.abort(new Error(`analytics did not answer in ${this.sendMs} ms`)),this.sendMs);return n.unref?.(),this.sending=(async()=>{try{await r.sendTraceBatch({body:{traces:e},signal:s.call.signal})}catch(a){if(s.letGo)return;let i=a.status,o=i??(s.call.signal.aborted?`no answer in ${this.sendMs} ms`:"unreachable"),c=a.retryAfter;this.pausedUntil=this.now()+(typeof c=="number"&&c>0?c*1e3:i===429?1e3:5e3),this.now()-this.lastSendWarning>6e4&&(this.lastSendWarning=this.now(),d.warn(`[palbase] request traces were not sent to analytics (${o}); ${e.length} dropped`,{error:a}))}finally{if(clearTimeout(n),this.sending=void 0,this.inFlight=void 0,this.pending.length>0){let a=Math.max(0,this.pausedUntil-this.now());this.schedule(this.pending.length>=this.batchSize?a:Math.max(a,this.flushMs))}}})(),this.sending}};import{createHmac as Zt}from"node:crypto";import{bind as er,bunDriver as tr,createDatabase as rr,envBlock as sr,createSearchWorker as nr,cutOff as ar,forgetUserIn as or,MigrationOpen as ir,MigrationRefused as lr,Migrator as de,renewingBunPool as oe,VersionNotMigrated as cr}from"palgres";import{toModel as ue}from"palgres/dsl";var dr=["start","complete","rollback","plan","status","types"],ur=/^(deploy|cli:[^\u0000-\u001f\u007f]{1,200})$/u;function pe(t){let e=t.PALBASE_DB_MIGRATE;if(!(e===void 0||e==="")){if(!dr.includes(e))throw new Error(`[palbase] PALBASE_DB_MIGRATE is start, complete, rollback, plan, status or types, not ${e}`);return e}}function he(t){let e=Array.isArray(t.schemas)?t.schemas:[t.schemas];for(let r of e)if(r.name===M.name)throw new Error(`[palbase] db.schemas: the ${M.name} schema is the framework's own (its tables are migrated with the app's) \u2014 name the app's schema otherwise`);return[...e,M]}function D(t){return ue(he(t))}function pr(t){return t.tables.some(e=>e.search!==void 0)}function U(t){return t.tables.some(e=>!e.ignored&&e.columns.some(r=>r.user!==void 0&&!r.ignored))}function fe(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 hr(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 ie=5;function me(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=oe(()=>new r.SQL({url:n,prepare:!1,max:s})),i=oe(()=>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:tr(a,i),poolSize:s,close:async()=>{await a.close({timeout:ie}),await i.close({timeout:ie})}}}}async function ge(t){return t==="rollback"?(d.info("[palbase] migrate rollback: this app declares no database; nothing of it to take back"),await O(t,{state:"none"}),0):(d.error(`[palbase] migrate ${t}: this app declares no database \u2014 PalbaseFactory.create(\u2026, { db: { schemas } })`),1)}async function be(t,e){if(!t)return d.error("[palbase] db types: this app declares no database \u2014 PalbaseFactory.create(\u2026, { db: { schemas } })"),1;let r=Array.isArray(t.schemas)?t.schemas:[t.schemas];return await O("types",sr(r,{module:"palbase/backend/env"}),e),0}async function ye(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(!ur.test(n))return d.error("[palbase] PALBASE_DB_MIGRATION_BY is deploy, or cli:<who>"),1;let a=me(t,fe(e)),i=a(s),o,c=l=>d.error(`[palbase] migrate ${r}: ${l}`);try{let l=D(t),u=new de(i.pool,{log:f=>{/ is held by others | held by writers/.test(f)&&(o=f.trim()),d.info(f)},shadow:f=>{let m=new URL(s);m.pathname=`/${f}`;let y=a(m.toString());return{reserve:()=>y.pool.reserve(),end:()=>y.close()}},openedBy:n,fields:()=>fr(e)});if(r==="plan"){let f=await u.plan(l);return await O(r,f),f.refusals.length>0?1:0}if(r==="status")return await O(r,await u.status()),0;let h=r==="start"?await mr(u,l,n):r==="complete"?await u.complete():await u.rollback();return d.info(`[palbase] migrate ${r}: done`,{result:h}),await O(r,h),0}catch(l){return l instanceof lr?(d.error(`[palbase] migrate ${r}: refused`,{refusals:l.refusals}),c(`refused \u2014 ${l.refusals.join("; ")}`),1):ar(l)?(d.error(`[palbase] migrate ${r}: cut off; run again, it goes on from where it stopped`,{error:l}),c(`cut off \u2014 ${o??le(l)}`),75):(d.error(`[palbase] migrate ${r}: failed`,{error:l}),c(`failed \u2014 ${le(l)}`),1)}finally{await i.close().catch(()=>{})}}async function fr(t){let e=t.PALBASE_URL,r=t.PALBASE_SECRET_KEY;if(!e||!r)throw new Error("[palbase] this migration seals or opens an encrypted column's rows: it reads the project's field keys with PALBASE_URL and PALBASE_SECRET_KEY");let s=R({url:e,secretKey:r}).fields;return await s.load(),s.close(),s}async function mr(t,e,r){try{return await t.start(e)}catch(s){if(!(s instanceof ir)||r!=="deploy"||!s.openedBy?.startsWith("cli:"))throw s;return d.warn(`[palbase] migrate start: the migration ${s.openedBy} opened (version ${s.to}) gives way to this release \u2014 rolled back first`),await t.rollback(),await t.start(e)}}var gr=(t,e)=>{process.stdout.write(t,()=>e())};function O(t,e,r=gr){return new Promise(s=>r(`${JSON.stringify({palbase_migrate:t,result:e})}
|
|
3
3
|
`,s))}function le(t){return(t instanceof Error?t.message:String(t)).split(`
|
|
4
4
|
`)[0].slice(0,300)||(t instanceof Error?t.name:"unknown")}async function br(t,e){try{return await new de(t).plan(e)}catch{return}}var ce="palbase.idempotency_keys.response_body";function yr(t,e){let r=null,s=!1,n=async()=>{let o=e.currentKey();if(!(s||o===r)){s=!0;try{let c=await t.reseal();r=o;let l=c.reduce((u,h)=>u+h.resealed,0);l>0&&d.info(`[palbase] fields: ${l} value(s) sealed again with key ${o}`,{report:c})}catch(c){d.warn(`[palbase] fields: sealing again with key ${o} stopped; tried again in a minute`,{error:c})}finally{s=!1}}},a=setTimeout(n,1e4),i=setInterval(n,6e4);for(let o of[a,i])o.unref?.();return()=>{clearTimeout(a),clearInterval(i)}}var L=class extends Error{digest;plan;constructor(e,r){super([`[palbase] this schema (${e}) has no version in the database yet: palbase db:push tries it there (a database of your own: palbase db:push --url <its address>)`,...r?wr(r):[" palbase db:plan says what it would change"]].join(`
|
|
5
5
|
`)),this.name="SchemaNotPushed",this.digest=e,this.plan=r}};function wr(t){let e=[t.adoption?` takes the database over as version 1${t.to>1?`, then version 1 \u2192 ${t.to}`:""}`:` version ${t.from??"none"} \u2192 ${t.to}`];t.changes.length===0&&t.refusals.length===0&&e.push(" nothing to change");for(let r of t.changes)e.push(` + ${r}`);for(let r of t.refusals)e.push(` \u2717 ${r}`);return e}var Pr=8e4;async function we(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=he(t),i=ue(a),o=me(t,fe(e))(n);try{let c=!1,l=p=>{c||(c=!0,d.warn(`[palbase] database: not answering yet (${p instanceof Error?p.message:String(p)}) \u2014 waiting for it, as one waking does`))},u=await er(o.engine,i,{waitMs:s.onPlatform?Pr:0,onUnreachable:l}).catch(async p=>{throw s.onPlatform||!(p instanceof cr)?p:new L(p.digest,await br(o.pool,i))}),h=Zt("sha256",r).update("palgres page cursor").digest("hex"),f=t.embed??s.embed,m=s.fields,y=await rr({sql:o.engine,schemas:a,binding:u,cursorSecret:h,admission:hr(o.poolSize),embed:f,log:p=>d.warn(`[palbase] ${p}`),fields:async()=>(await m.load(),m)}),S=m.loaded?yr(y,m):()=>{},b=pr(i)?nr({sql:o.engine,embed:f,log:p=>d.info(`[palbase] ${p}`)}):void 0;return{model:i,binding:u,app:y,requests:t.requests??"caller",forget:(p,k)=>or({attempt:v=>k.$attempt(v)},u,i,p),...b?{search:b}:{},keptAnswers:{seal:p=>m.loaded?m.encrypt(ce,p):p,open:async p=>m.isEncrypted(p)?(m.loaded||await m.load(),m.decrypt(ce,p)):p},close:async()=>{S(),m.close(),await o.close()}}}catch(c){throw await o.close(),c}}function Sr(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 Pe(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(Sr)}}}var vr=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function Se(t,e,r){let s=[],n=t.url??e.PALBASE_URL??"",a="";try{let u=new URL(n);a=u.origin,u.protocol!=="https:"&&u.hostname!=="localhost"&&u.hostname!=="127.0.0.1"&&s.push("palbase.url / PALBASE_URL is https://<ref>.<domain>"),(u.pathname!=="/"||u.search||u.hash)&&s.push("palbase.url / PALBASE_URL is the project origin alone")}catch{s.push("palbase.url / PALBASE_URL is the project address, https://<ref>.<domain>")}let i=t.projectId??e.PALBASE_PROJECT_ID??"";vr.test(i)||s.push("palbase.projectId / PALBASE_PROJECT_ID is the project id (a UUID)");let o=t.secretKey??e.PALBASE_SECRET_KEY??"";/^pb_[a-z0-9]+_s/.test(o)||s.push("palbase.secretKey / PALBASE_SECRET_KEY is the project secret key (pb_<ref>_s\u2026), kept in the project's Secrets");let c=(t.platformSecret??e.PALBASE_PLATFORM_SECRET)||void 0;c!==void 0&&!/^[0-9a-f]{64}$/.test(c)&&s.push("palbase.platformSecret / PALBASE_PLATFORM_SECRET is the key the platform signs its calls to this machine with (64 hex characters): the platform sets it, unset off the platform");let l=(t.webhookSecret??e.PALBASE_WEBHOOK_SECRET)||void 0;if(r.needsWebhookSecret&&(c!==void 0||l!==void 0)&&!/^whsec_[0-9a-f]{64}$/.test(l??"")&&s.push("palbase.webhookSecret / PALBASE_WEBHOOK_SECRET is the project's webhook endpoint secret (whsec_\u2026): the platform delivers this app events \u2014 its @On handlers', or user.deleted for the users its tables keep"),s.length>0)throw new Error(`[palbase] the app cannot start:
|
|
@@ -9,4 +9,4 @@ ${s.join(`
|
|
|
9
9
|
`)}
|
|
10
10
|
`}function ke(t,e,r=kr){let s=Buffer.from(e,"utf8"),n=new Int32Array(new SharedArrayBuffer(4));for(let a=0;a<s.length;)try{a+=r(t,s,a,s.length-a)}catch(i){if(i.code!=="EAGAIN")throw i;Atomics.wait(n,0,0,5)}}var Ee=2e4,Te=5e3,Br=15e3,Fr="/_palbase/health";function Mr(t){let e=new Set,r=s=>{if(e.has(s))return!1;e.add(s);let n=F(s,X);return n?n.providers.some(a=>F(a,Z)!==void 0&&F(a,ee)===void 0)||n.imports.some(r):!1};return t.some(r)}var Ir={async create(t,e={}){let r=Array.isArray(t)?t:[t],s=e.env??process.env,n=pe(s);if(n!==void 0){let w=n==="types"?await be(e.db):e.db?await ye(e.db,s,n):await ge(n);throw process.exit(w),new j(w)}let a=s.PALBASE_CONTRACT_OUT;if(a){let w;try{await Re(xe(s)),w=await $r(r,e,s)}catch(A){throw _r(2,`[palbase] the contract: ${A instanceof Error?A.message:String(A)}
|
|
11
11
|
`),process.exit(1),new C}throw a==="/dev/stdout"?ke(1,Ae(w)):Rr(a,`${w}
|
|
12
|
-
`),process.exit(0),new C}let i=xe(s),o=await Re(i);o&&d.info(`[palbase] strings: ${o.source} and ${o.locales.length-1} other language(s), ${Object.keys(o.strings).length} sentence(s), from ${i}/palbase/strings`),ne(o?void 0:i);let c=e.db?D(e.db):void 0,l=await Q({env:s,url:e.palbase?.url,secretKey:e.palbase?.secretKey});l&&d.info(`[palbase] secrets: ${l.loaded.length} from the project's ${l.set} set${l.kept.length>0?`; ${l.kept.join(", ")} kept as the environment gives them`:""}`),l&&l.refused.length>0&&d.warn(`[palbase] secrets not set \u2014 names a process reads as its own, not the app's: ${l.refused.map(w=>JSON.stringify(w)).join(", ")}`);let u=Mr(r)||c!==void 0&&U(c),h=Se(e.palbase??{},s,{needsWebhookSecret:u});u&&h.webhookSecret===void 0&&d.warn("[palbase] events: none is delivered here \u2014 the platform delivers them to the app's machine, not to this computer; its @On handlers (and forgetting a deleted user's rows) run there. Set PALBASE_WEBHOOK_SECRET to take a delivery forwarded here");let f=R({url:h.url,secretKey:h.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 y=e.db?await we(e.db,s,h.secretKey,{onPlatform:h.platformSecret!==void 0,embed:Pe(f),fields:f.fields}):void 0;y&&d.info(`[palbase] database: version ${y.binding.version}`);let S=y&&U(y.model)?{"user.deleted":[w=>Lr(y,w)]}:void 0,b=h.platformSecret===void 0?void 0:{secret:h.platformSecret},p=e.requestTelemetry===!1?void 0:new $(f.analytics),k=()=>I({modules:r,verifier:new B({issuer:h.url,projectId:h.projectId,standing:Y({url:h.url,secretKey:h.secretKey})}),server:f,webhookSecret:h.webhookSecret,env:s,projectId:h.projectId,telemetry:p,auth:e.auth,tokens:e.tokens,rateLimit:e.rateLimit,maxBodyBytes:e.bodyLimit,cors:jr(e.cors,s.PALBASE_WEB_ORIGINS),platform:b,events:S,database:y&&{app:y.app,requests:y.requests,keptAnswers:y.keptAnswers},strings:o}),v=k(),q=e.boot?.attempts??5,W=e.boot?.backoffMs??1e3;for(let w=1;;w++)try{await v.start();break}catch(A){if(w>=q)throw d.error(`[palbase] the app did not start after ${q} attempts`,{error:A}),A;d.warn(`[palbase] the app did not start (attempt ${w} of ${q}); trying again in ${W} ms`,{error:A}),await new Promise(De=>setTimeout(De,W)),W*=2,v=k()}return Dr(v,f,m,e.host??"0.0.0.0",e.exitOnFatal??!0,y)}};function xe(t){let e=t.PALBASE_CONTRACT_ENTRY??process.argv[1];if(!e)return process.cwd();let r=T(_e(e));for(;!z(H(r,"package.json"))&&T(r)!==r;)r=T(r);return z(H(r,"package.json"))?r:process.cwd()}async function Re(t){try{return await ae(t)}catch(e){throw new Error(`[palbase] the app's strings: ${e instanceof Error?e.message:String(e)}`)}}async function $r(t,e,r){let s=_e(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=T(s);for(;!z(H(n,"package.json"))&&T(n)!==n;)n=T(n);let{analyzeProject:a}=await import("../chunks/DZ42B54P.js"),{routeContracts:i}=await import("../chunks/HAP72KDI.js"),o=a(n,s);for(let u of o.warnings)d.warn(`[palbase] the contract: ${u}`);let c="https://contract.palbase.invalid",l=I({modules:t,verifier:new B({issuer:c,projectId:"contract",standing:()=>Promise.reject(new Error("the contract run serves nothing"))}),server:R({url:c,secretKey:"pb_contract_s"}),env:r,projectId:"contract",auth:e.auth,tokens:e.tokens,rateLimit:e.rateLimit,maxBodyBytes:e.bodyLimit,cors:e.cors,contractOnly:{database:e.db!==void 0,routes:await i(o.routes),errors:se()},events:e.db&&U(D(e.db))?{"user.deleted":[]}:void 0});return JSON.stringify(l.contract())}var C=class extends Error{constructor(){super("[palbase] the contract run ended"),this.name="ContractRunEnded"}},j=class extends Error{code;constructor(e){super(`[palbase] the migration run ended with ${e}`),this.name="MigrationRunEnded",this.code=e}};async function Lr(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,V.$asService());d.info(`[palbase] user ${r} deleted: ${s.deleted} row(s) gone, ${s.detached} forgot them`)}async function Dr(t,e,r,s,n,a){let i,o={on:!1},c=(b,p)=>new URL(b.url).pathname===Fr&&b.method==="GET"?Promise.resolve(o.on?Response.json({ok:!1,stopping:!0},{status:503}):Response.json({ok:!0})):t.handle(b,p),l=Or((b,p)=>{Ur(c,b,p,o).finally(()=>{o.on&&l.closeIdleConnections()})});l.keepAliveTimeout=29e4,l.headersTimeout=3e5;try{await new Promise((b,p)=>{l.once("error",p),l.listen(r,s,()=>b())})}catch(b){throw await t.stop(),await a?.close(),b}let u=l.address().port;d.info(`[palbase] serving ${t.routes.length} route(s) on :${u}`,{routes:t.routes}),a?.search?.start();let h=b=>i??=(async()=>{d.info("[palbase] stopping: finishing the requests in flight"),o.on=!0;let p=new Promise(v=>l.close(()=>v()));l.closeIdleConnections();let k=setTimeout(()=>l.closeAllConnections(),b);await p,clearTimeout(k),process.off("SIGINT",y),process.off("uncaughtException",S),process.off("unhandledRejection",S);try{await t.stop(),await a?.search?.stop(),await a?.close()}finally{process.off("SIGTERM",y)}})(),f=()=>h(Ee),m=!1,y=()=>{if(m){d.info("[palbase] stopping: told to stop again; the requests in flight are still being finished");return}m=!0;let b=setTimeout(()=>{d.error("[palbase] stopping took longer than it is given; the process ends"),process.exit(1)},Ee+Br);b.unref(),f().then(()=>{clearTimeout(b),process.exit(0)},p=>{clearTimeout(b),d.error("[palbase] stopping failed; the process ends",{error:p}),process.exit(1)})},S=b=>{d.error("[palbase] the app crashed; stopping so the machine starts it again",{error:b});let p=setTimeout(()=>process.exit(1),Te+1e3);h(Te).finally(()=>{clearTimeout(p),process.exit(1)})};return process.on("SIGTERM",y),process.once("SIGINT",y),n&&(process.on("uncaughtException",S),process.on("unhandledRejection",S)),{routes:t.routes,palbase:e,port:u,handle:c,close:f}}async function Ur(t,e,r,s){try{let n=e.url??"/",a;try{if(!n.startsWith("/"))throw new TypeError("the request target is not a path");a=new URL(`http://localhost${n}`)}catch{r.statusCode=400,r.end();return}let i=new Headers;for(let[h,f]of Object.entries(e.headers))if(f!==void 0)if(Array.isArray(f))for(let m of f)i.append(h,m);else i.set(h,f);let o=e.method!=="GET"&&e.method!=="HEAD",c=new AbortController;r.on("close",()=>{r.writableFinished||c.abort(new Error("the client closed the connection"))});let l=new Request(a,{method:e.method,headers:i,body:o?Cr.toWeb(e):void 0,duplex:"half",signal:c.signal}),u=await t(l,{remoteAddress:e.socket.remoteAddress,target:n});if(r.statusCode=u.status,u.headers.forEach((h,f)=>r.setHeader(f,h)),s.on&&r.setHeader("connection","close"),u.body)for await(let h of u.body)r.write(h);r.end()}catch(n){d.error("[palbase] the request could not be answered",{error:n}),r.headersSent||(r.statusCode=500),r.end()}}function jr(t,e,r=s=>console.warn(s)){let s=(e??"").split(",").map(o=>o.trim()).filter(o=>o!=="");if(s.length===0||t?.origins==="*")return t;let n=s.filter(o=>G(o)),a=s.filter(o=>!G(o));a.length>0&&r(`[palbase] the project's web origins ${a.map(o=>JSON.stringify(o)).join(", ")} are not CORS origins (https://host[:port], http only for localhost): browsers there are not let in`);let i=[...new Set([...t?.origins??[],...n])];return i.length===0?t:{...t,origins:i}}import{bigint as Js,boolean as Qs,check as Xs,date as Zs,defineSchema as en,defineTable as tn,enumType as rn,foreignKey as sn,index as nn,integer as an,jsonb as on,numeric as ln,ownedByUser as cn,policy as dn,raw as un,sqlType as pn,text as hn,timestamp as fn,userRef as mn,uuid as gn}from"palgres/dsl";import{increment as yn,now as wn}from"palgres";function x(t){if(t instanceof E)return{data:null,error:{code:t.code,message:t.message},status:t.status};throw t}async function P(t,e){try{let r=await t();return{data:await e(r.data),error:null,status:r.status}}catch(r){return x(r)}}var Nr=_("Secrets",{async get(t){if(J(t))return null;let e=process.env[t];return typeof e=="string"&&e!==""?e:null}}),qr=100,Wr=1e3,Kr=168*3600,Vr={s:1,m:60,h:3600,d:86400};function Gr(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)*Vr[n]*1e3);return Math.ceil(r/1e3)}function $e(t,e,r){let s="getPublicUrl",n;try{n=String(e).split("/").map(i=>K(s,"path",i)).join("%2F")}catch(i){throw i instanceof E&&i.code==="invalid_path_parameter"?new E({op:s,status:0,code:"invalid_path_parameter",message:`${s}: the object path ${JSON.stringify(e)} has an empty, "." or ".." segment: storage keeps no such object`}):i}let a=`${g.url}/storage/public/${K(s,"bucket",t)}/${n}`;return r?`${a}?variant=${encodeURIComponent(r)}`:a}function Oe(t){return{path:t.path,name:t.path,bucket:t.bucket,size:t.size,contentType:t.content_type,checksum:t.checksum_sha256,...t.width!==void 0?{width:t.width}:{},...t.height!==void 0?{height:t.height}:{},...t.thumbhash!==void 0?{thumbhash:t.thumbhash}:{},variants:Object.fromEntries(Object.keys(t.variants??{}).map(e=>[e,$e(t.bucket,t.path,e)]))}}function zr(t){return{async upload(e,r,s){let n=s?.contentType??(r instanceof Blob&&r.type!==""?r.type:void 0);try{let a=await g.storage.putObject({path:{bucket:t,path:e},headers:s?.upsert?void 0:{"If-None-Match":"*"},body:r,contentType:n});return{data:Oe(a.data),error:null,status:a.status}}catch(a){return a instanceof E&&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}:x(a)}},async download(e){try{let r=await g.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 x(r)}},getPublicUrl(e,r){return $e(t,e,r?.variant)},async createSignedUrl(e,r){let s=Gr(r?.expiresIn);return s===void 0||s<1||s>Kr?{data:null,error:{code:"bad_request",message:`expiresIn is a duration from 1s to 7d, like "15m", "1h" or "7d" (got ${JSON.stringify(r?.expiresIn)})`},status:400}:P(()=>g.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??qr,n=r?.offset??0;if(!Number.isInteger(s)||s<0||!Number.isInteger(n)||n<0)return{data:null,error:{code:"bad_request",message:"limit and offset are whole numbers, 0 or more"},status:400};let a=[],i,o=200;try{for(;a.length<s;){let c=Math.max(1,Math.min(Wr,n+s-a.length)),l=await g.storage.listObjects({path:{bucket:t},query:{...e?{prefix:e}:{},limit:c,...i?{cursor:i}:{}}});o=l.status;for(let u of l.data.objects)n>0?n--:a.length<s&&a.push(Oe(u));if(i=l.data.next_cursor,!i)break}}catch(c){return x(c)}return{data:a,error:null,status:o}},async remove(e){let r=[];for(let s of e){try{await g.storage.deleteObject({path:{bucket:t,path:s}})}catch(n){return x(n)}r.push({path:s,name:s,bucket:t,size:0,contentType:"",checksum:"",variants:{}})}return{data:r,error:null,status:200}},move(e,r){return P(()=>g.storage.moveObject({path:{bucket:t},body:{from:e,to:r}}),()=>{})},copy(e,r){return P(()=>g.storage.copyObject({path:{bucket:t},body:{from:e,to:r}}),()=>{})}}}var Hr={bucket:zr},Ce=t=>te("Storage",t,Hr),Yr={bucket:t=>Ce("bucket").bucket(t),buckets:new Proxy({},{get:(t,e)=>typeof e=="string"?Ce("buckets").bucket(e):void 0})},Jr=_("Notifications",{push:{send(t){let{to:e,...r}=t,s=typeof e=="string"?{user_ids:[e]}:Array.isArray(e)?{user_ids:e}:{topic:e.topic};return P(()=>g.notify.sendPush({body:{...r,to:s}}),n=>({message_ids:n.message_ids,recipients:n.message_ids.length,skipped_user_ids:n.skipped_user_ids}))}},email:{async send(t){let{to:e,templateSlug:r,...s}=t,n={...s,...r!==void 0?{template:r}:{}};if(!Array.isArray(e))return P(()=>g.notify.sendEmail({body:{...n,to:e}}),o=>({...o.message_id!==void 0?{message_id:o.message_id}:{},...o.skipped?{skipped:!0}:{}}));let a=[],i=202;for(let o of e)try{let c=await g.notify.sendEmail({body:{...n,to:o}});i=c.status,a.push(c.data.message_id??null)}catch(c){return x(c)}return{data:{message_ids:a},error:null,status:i}}}}),Be=t=>typeof t=="boolean"?t:t!=null&&t!==0&&t!=="",Fe=t=>typeof t=="string"?{name:t}:null,Me=t=>t==="override"?"user":t,Qr=t=>t!==null&&typeof t=="object"&&!Array.isArray(t)&&"userId"in t;function Le(){return re.getStore()?.userId}function N(t){let e=t&&"userId"in t?t.userId??void 0:Le();return P(()=>e?g.flags.getUserValues({path:{user_id:e}}):g.flags.getValues(),r=>r.values??{})}var Ie={setOverrideForUser:(t,e,r)=>P(()=>g.flags.putUserValue({path:{user_id:t,key:e},body:{value:r}}),s=>({key:s.key,value:s.value,source:Me(s.source)})),setOverridesForUser:(t,e)=>P(()=>g.flags.putUserValues({path:{user_id:t},body:{values:e}}),r=>({values:r.values??{}})),clearOverrideForUser:(t,e)=>P(()=>g.flags.deleteUserValue({path:{user_id:t,key:e}}),r=>({key:r.key,value:r.value,source:Me(r.source)})),clearAllOverridesForUser:t=>P(()=>g.flags.deleteUserValues({path:{user_id:t}}),e=>({deleted:e.deleted})),batchSetOverrides:t=>P(()=>g.flags.batchUserValues({body:{operations:t.map(e=>({user_id:e.userId,values:e.values}))}}),e=>({applied:e.applied}))},Xr=_("Flags",{async isEnabled(t,e){let r=s=>(d.warn(`[palbase] flag "${t}" could not be read (${s}): treating it as off`),!1);try{let s=await N(e);return s.error?r(`${s.error.code}: ${s.error.message}`):Be(s.data[t])}catch(s){return r(s instanceof Error?s.message:String(s))}},async getVariant(t,e){let r=await N(e);return r.error?{data:null,error:r.error,status:r.status}:{data:Fe(r.data[t]),error:null,status:r.status}},async getAll(t){let e=await N(t);return e.error?{data:null,error:e.error,status:e.status}:{data:Object.entries(e.data).map(([r,s])=>{let n=Fe(s);return{name:r,enabled:Be(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):Qr(e)?a=e:e!==void 0&&(s=e,n=!0);let i=await N(a);if(i.error)return n?{data:s??null,error:null,status:i.status}:{data:null,error:i.error,status:i.status};let o=i.data[t];return{data:o===void 0?s??null:o,error:null,status:i.status}},async setOverride(t,e){let r=Le();return r?Ie.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 Ie}}),Zr=_("Realtime",{broadcast(t,e,r){return P(()=>g.realtime.broadcast({body:{messages:[{topic:t,event:e,payload:r??{}}]}}),()=>{})},state:{set(t,e,r){return P(()=>g.realtime.writeState({body:{ops:[{topic:t,key:e,value:r}]}}),()=>{})},clear(t,e){return P(()=>g.realtime.writeState({body:{ops:[{topic:t,key:e,delete:!0}]}}),()=>{})}}});import{z as xn}from"zod";export{at as AttestedDevice,Ne as AuthUnavailable,At as Authorize,It as BadRequest,Ye as Body,zt as CACHE_MAX_TTL,Ht as Cache,Pt as ChatPart,nt as Client,$t as Conflict,C as ContractRunEnded,qe as Controller,dt as Cron,V as Database,Lt as DeadlockDetected,ze as Delete,Ot as DiError,Ue as EVENT_TYPES,Xr as Flags,Ft as Forbidden,vt as Gateway,St as GatewayRefusal,We as Get,Qe as Headers,Dt as HttpError,it as Injectable,d as Log,Gt as MAX_BODY_BYTES,j as MigrationRunEnded,lt as Module,Ut as NotFound,Jr as Notifications,ct as On,Et as OnConnect,Tt as OnDisconnect,xt as OnEmpty,kt as OnFirst,et as OptionalUser,Ct as PalError,g as Palbase,E as PalbaseError,Ir as PalbaseFactory,Xe as Param,Ge as Patch,Ke as Post,Ve as Put,He as Query,Je as QueryParams,Zr as Realtime,tt as Req,rt as RequestId,ot as Resolve,L as SchemaNotPushed,Nr as Secrets,jt as SerializationFailure,Yr as Storage,Rt as Subscribe,mt as Task,ft as TaskFailure,gt as Tasks,bt as TestUserTemplate,je as TokenError,B as TokenVerifier,Nt as TooManyRequests,st as TraceId,Bt as Unauthorized,qt as UniqueViolation,yt as Upload,wt as UploadedObject,Ze as User,ut as Webhook,Js as bigint,Qs as boolean,Xs as check,I as createApp,Zs as date,Mt as defineError,en as defineSchema,tn as defineTable,Kt as encrypt,Wt as encrypted,rn as enumType,sn as foreignKey,pt as getRegisteredControllers,ht as getRoutes,_t as getWebhookManifest,yn as increment,nn as index,an as integer,on as jsonb,wn as now,ln as numeric,cn as ownedByUser,dn as policy,un as raw,pn as sqlType,Vt as t,hn as text,fn as timestamp,mn as userRef,gn as uuid,xn as z};
|
|
12
|
+
`),process.exit(0),new C}let i=xe(s),o=await Re(i);o&&d.info(`[palbase] strings: ${o.source} and ${o.locales.length-1} other language(s), ${Object.keys(o.strings).length} sentence(s), from ${i}/palbase/strings`),ne(o?void 0:i);let c=e.db?D(e.db):void 0,l=await Q({env:s,url:e.palbase?.url,secretKey:e.palbase?.secretKey});l&&d.info(`[palbase] secrets: ${l.loaded.length} from the project's ${l.set} set${l.kept.length>0?`; ${l.kept.join(", ")} kept as the environment gives them`:""}`),l&&l.refused.length>0&&d.warn(`[palbase] secrets not set \u2014 names a process reads as its own, not the app's: ${l.refused.map(w=>JSON.stringify(w)).join(", ")}`);let u=Mr(r)||c!==void 0&&U(c),h=Se(e.palbase??{},s,{needsWebhookSecret:u});u&&h.webhookSecret===void 0&&d.warn("[palbase] events: none is delivered here \u2014 the platform delivers them to the app's machine, not to this computer; its @On handlers (and forgetting a deleted user's rows) run there. Set PALBASE_WEBHOOK_SECRET to take a delivery forwarded here");let f=R({url:h.url,secretKey:h.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 y=e.db?await we(e.db,s,h.secretKey,{onPlatform:h.platformSecret!==void 0,embed:Pe(f),fields:f.fields}):void 0;y&&d.info(`[palbase] database: version ${y.binding.version}`);let S=y&&U(y.model)?{"user.deleted":[w=>Lr(y,w)]}:void 0,b=h.platformSecret===void 0?void 0:{secret:h.platformSecret},p=e.requestTelemetry===!1?void 0:new $(f.analytics),k=()=>I({modules:r,verifier:new B({issuer:h.url,projectId:h.projectId,standing:Y({url:h.url,secretKey:h.secretKey})}),server:f,webhookSecret:h.webhookSecret,env:s,projectId:h.projectId,telemetry:p,auth:e.auth,tokens:e.tokens,rateLimit:e.rateLimit,maxBodyBytes:e.bodyLimit,cors:jr(e.cors,s.PALBASE_WEB_ORIGINS),platform:b,events:S,database:y&&{app:y.app,requests:y.requests,keptAnswers:y.keptAnswers},strings:o}),v=k(),q=e.boot?.attempts??5,W=e.boot?.backoffMs??1e3;for(let w=1;;w++)try{await v.start();break}catch(A){if(w>=q)throw d.error(`[palbase] the app did not start after ${q} attempts`,{error:A}),A;d.warn(`[palbase] the app did not start (attempt ${w} of ${q}); trying again in ${W} ms`,{error:A}),await new Promise(De=>setTimeout(De,W)),W*=2,v=k()}return Dr(v,f,m,e.host??"0.0.0.0",e.exitOnFatal??!0,y)}};function xe(t){let e=t.PALBASE_CONTRACT_ENTRY??process.argv[1];if(!e)return process.cwd();let r=T(_e(e));for(;!z(H(r,"package.json"))&&T(r)!==r;)r=T(r);return z(H(r,"package.json"))?r:process.cwd()}async function Re(t){try{return await ae(t)}catch(e){throw new Error(`[palbase] the app's strings: ${e instanceof Error?e.message:String(e)}`)}}async function $r(t,e,r){let s=_e(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=T(s);for(;!z(H(n,"package.json"))&&T(n)!==n;)n=T(n);let{analyzeProject:a}=await import("../chunks/4FY2JOIE.js"),{routeContracts:i}=await import("../chunks/QQKGUVDV.js"),o=a(n,s);for(let u of o.warnings)d.warn(`[palbase] the contract: ${u}`);let c="https://contract.palbase.invalid",l=I({modules:t,verifier:new B({issuer:c,projectId:"contract",standing:()=>Promise.reject(new Error("the contract run serves nothing"))}),server:R({url:c,secretKey:"pb_contract_s"}),env:r,projectId:"contract",auth:e.auth,tokens:e.tokens,rateLimit:e.rateLimit,maxBodyBytes:e.bodyLimit,cors:e.cors,contractOnly:{database:e.db!==void 0,routes:await i(o.routes),errors:se()},events:e.db&&U(D(e.db))?{"user.deleted":[]}:void 0});return JSON.stringify(l.contract())}var C=class extends Error{constructor(){super("[palbase] the contract run ended"),this.name="ContractRunEnded"}},j=class extends Error{code;constructor(e){super(`[palbase] the migration run ended with ${e}`),this.name="MigrationRunEnded",this.code=e}};async function Lr(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,V.$asService());d.info(`[palbase] user ${r} deleted: ${s.deleted} row(s) gone, ${s.detached} forgot them`)}async function Dr(t,e,r,s,n,a){let i,o={on:!1},c=(b,p)=>new URL(b.url).pathname===Fr&&b.method==="GET"?Promise.resolve(o.on?Response.json({ok:!1,stopping:!0},{status:503}):Response.json({ok:!0})):t.handle(b,p),l=Or((b,p)=>{Ur(c,b,p,o).finally(()=>{o.on&&l.closeIdleConnections()})});l.keepAliveTimeout=29e4,l.headersTimeout=3e5;try{await new Promise((b,p)=>{l.once("error",p),l.listen(r,s,()=>b())})}catch(b){throw await t.stop(),await a?.close(),b}let u=l.address().port;d.info(`[palbase] serving ${t.routes.length} route(s) on :${u}`,{routes:t.routes}),a?.search?.start();let h=b=>i??=(async()=>{d.info("[palbase] stopping: finishing the requests in flight"),o.on=!0;let p=new Promise(v=>l.close(()=>v()));l.closeIdleConnections();let k=setTimeout(()=>l.closeAllConnections(),b);await p,clearTimeout(k),process.off("SIGINT",y),process.off("uncaughtException",S),process.off("unhandledRejection",S);try{await t.stop(),await a?.search?.stop(),await a?.close()}finally{process.off("SIGTERM",y)}})(),f=()=>h(Ee),m=!1,y=()=>{if(m){d.info("[palbase] stopping: told to stop again; the requests in flight are still being finished");return}m=!0;let b=setTimeout(()=>{d.error("[palbase] stopping took longer than it is given; the process ends"),process.exit(1)},Ee+Br);b.unref(),f().then(()=>{clearTimeout(b),process.exit(0)},p=>{clearTimeout(b),d.error("[palbase] stopping failed; the process ends",{error:p}),process.exit(1)})},S=b=>{d.error("[palbase] the app crashed; stopping so the machine starts it again",{error:b});let p=setTimeout(()=>process.exit(1),Te+1e3);h(Te).finally(()=>{clearTimeout(p),process.exit(1)})};return process.on("SIGTERM",y),process.once("SIGINT",y),n&&(process.on("uncaughtException",S),process.on("unhandledRejection",S)),{routes:t.routes,palbase:e,port:u,handle:c,close:f}}async function Ur(t,e,r,s){try{let n=e.url??"/",a;try{if(!n.startsWith("/"))throw new TypeError("the request target is not a path");a=new URL(`http://localhost${n}`)}catch{r.statusCode=400,r.end();return}let i=new Headers;for(let[h,f]of Object.entries(e.headers))if(f!==void 0)if(Array.isArray(f))for(let m of f)i.append(h,m);else i.set(h,f);let o=e.method!=="GET"&&e.method!=="HEAD",c=new AbortController;r.on("close",()=>{r.writableFinished||c.abort(new Error("the client closed the connection"))});let l=new Request(a,{method:e.method,headers:i,body:o?Cr.toWeb(e):void 0,duplex:"half",signal:c.signal}),u=await t(l,{remoteAddress:e.socket.remoteAddress,target:n});if(r.statusCode=u.status,u.headers.forEach((h,f)=>r.setHeader(f,h)),s.on&&r.setHeader("connection","close"),u.body)for await(let h of u.body)r.write(h);r.end()}catch(n){d.error("[palbase] the request could not be answered",{error:n}),r.headersSent||(r.statusCode=500),r.end()}}function jr(t,e,r=s=>console.warn(s)){let s=(e??"").split(",").map(o=>o.trim()).filter(o=>o!=="");if(s.length===0||t?.origins==="*")return t;let n=s.filter(o=>G(o)),a=s.filter(o=>!G(o));a.length>0&&r(`[palbase] the project's web origins ${a.map(o=>JSON.stringify(o)).join(", ")} are not CORS origins (https://host[:port], http only for localhost): browsers there are not let in`);let i=[...new Set([...t?.origins??[],...n])];return i.length===0?t:{...t,origins:i}}import{bigint as Js,boolean as Qs,check as Xs,date as Zs,defineSchema as en,defineTable as tn,enumType as rn,foreignKey as sn,index as nn,integer as an,jsonb as on,numeric as ln,ownedByUser as cn,policy as dn,raw as un,sqlType as pn,text as hn,timestamp as fn,userRef as mn,uuid as gn}from"palgres/dsl";import{increment as yn,now as wn}from"palgres";function x(t){if(t instanceof E)return{data:null,error:{code:t.code,message:t.message},status:t.status};throw t}async function P(t,e){try{let r=await t();return{data:await e(r.data),error:null,status:r.status}}catch(r){return x(r)}}var Nr=_("Secrets",{async get(t){if(J(t))return null;let e=process.env[t];return typeof e=="string"&&e!==""?e:null}}),qr=100,Wr=1e3,Kr=168*3600,Vr={s:1,m:60,h:3600,d:86400};function Gr(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)*Vr[n]*1e3);return Math.ceil(r/1e3)}function $e(t,e,r){let s="getPublicUrl",n;try{n=String(e).split("/").map(i=>K(s,"path",i)).join("%2F")}catch(i){throw i instanceof E&&i.code==="invalid_path_parameter"?new E({op:s,status:0,code:"invalid_path_parameter",message:`${s}: the object path ${JSON.stringify(e)} has an empty, "." or ".." segment: storage keeps no such object`}):i}let a=`${g.url}/storage/public/${K(s,"bucket",t)}/${n}`;return r?`${a}?variant=${encodeURIComponent(r)}`:a}function Oe(t){return{path:t.path,name:t.path,bucket:t.bucket,size:t.size,contentType:t.content_type,checksum:t.checksum_sha256,...t.width!==void 0?{width:t.width}:{},...t.height!==void 0?{height:t.height}:{},...t.thumbhash!==void 0?{thumbhash:t.thumbhash}:{},variants:Object.fromEntries(Object.keys(t.variants??{}).map(e=>[e,$e(t.bucket,t.path,e)]))}}function zr(t){return{async upload(e,r,s){let n=s?.contentType??(r instanceof Blob&&r.type!==""?r.type:void 0);try{let a=await g.storage.putObject({path:{bucket:t,path:e},headers:s?.upsert?void 0:{"If-None-Match":"*"},body:r,contentType:n});return{data:Oe(a.data),error:null,status:a.status}}catch(a){return a instanceof E&&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}:x(a)}},async download(e){try{let r=await g.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 x(r)}},getPublicUrl(e,r){return $e(t,e,r?.variant)},async createSignedUrl(e,r){let s=Gr(r?.expiresIn);return s===void 0||s<1||s>Kr?{data:null,error:{code:"bad_request",message:`expiresIn is a duration from 1s to 7d, like "15m", "1h" or "7d" (got ${JSON.stringify(r?.expiresIn)})`},status:400}:P(()=>g.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??qr,n=r?.offset??0;if(!Number.isInteger(s)||s<0||!Number.isInteger(n)||n<0)return{data:null,error:{code:"bad_request",message:"limit and offset are whole numbers, 0 or more"},status:400};let a=[],i,o=200;try{for(;a.length<s;){let c=Math.max(1,Math.min(Wr,n+s-a.length)),l=await g.storage.listObjects({path:{bucket:t},query:{...e?{prefix:e}:{},limit:c,...i?{cursor:i}:{}}});o=l.status;for(let u of l.data.objects)n>0?n--:a.length<s&&a.push(Oe(u));if(i=l.data.next_cursor,!i)break}}catch(c){return x(c)}return{data:a,error:null,status:o}},async remove(e){let r=[];for(let s of e){try{await g.storage.deleteObject({path:{bucket:t,path:s}})}catch(n){return x(n)}r.push({path:s,name:s,bucket:t,size:0,contentType:"",checksum:"",variants:{}})}return{data:r,error:null,status:200}},move(e,r){return P(()=>g.storage.moveObject({path:{bucket:t},body:{from:e,to:r}}),()=>{})},copy(e,r){return P(()=>g.storage.copyObject({path:{bucket:t},body:{from:e,to:r}}),()=>{})}}}var Hr={bucket:zr},Ce=t=>te("Storage",t,Hr),Yr={bucket:t=>Ce("bucket").bucket(t),buckets:new Proxy({},{get:(t,e)=>typeof e=="string"?Ce("buckets").bucket(e):void 0})},Jr=_("Notifications",{push:{send(t){let{to:e,...r}=t,s=typeof e=="string"?{user_ids:[e]}:Array.isArray(e)?{user_ids:e}:{topic:e.topic};return P(()=>g.notify.sendPush({body:{...r,to:s}}),n=>({message_ids:n.message_ids,recipients:n.message_ids.length,skipped_user_ids:n.skipped_user_ids}))}},email:{async send(t){let{to:e,templateSlug:r,...s}=t,n={...s,...r!==void 0?{template:r}:{}};if(!Array.isArray(e))return P(()=>g.notify.sendEmail({body:{...n,to:e}}),o=>({...o.message_id!==void 0?{message_id:o.message_id}:{},...o.skipped?{skipped:!0}:{}}));let a=[],i=202;for(let o of e)try{let c=await g.notify.sendEmail({body:{...n,to:o}});i=c.status,a.push(c.data.message_id??null)}catch(c){return x(c)}return{data:{message_ids:a},error:null,status:i}}}}),Be=t=>typeof t=="boolean"?t:t!=null&&t!==0&&t!=="",Fe=t=>typeof t=="string"?{name:t}:null,Me=t=>t==="override"?"user":t,Qr=t=>t!==null&&typeof t=="object"&&!Array.isArray(t)&&"userId"in t;function Le(){return re.getStore()?.userId}function N(t){let e=t&&"userId"in t?t.userId??void 0:Le();return P(()=>e?g.flags.getUserValues({path:{user_id:e}}):g.flags.getValues(),r=>r.values??{})}var Ie={setOverrideForUser:(t,e,r)=>P(()=>g.flags.putUserValue({path:{user_id:t,key:e},body:{value:r}}),s=>({key:s.key,value:s.value,source:Me(s.source)})),setOverridesForUser:(t,e)=>P(()=>g.flags.putUserValues({path:{user_id:t},body:{values:e}}),r=>({values:r.values??{}})),clearOverrideForUser:(t,e)=>P(()=>g.flags.deleteUserValue({path:{user_id:t,key:e}}),r=>({key:r.key,value:r.value,source:Me(r.source)})),clearAllOverridesForUser:t=>P(()=>g.flags.deleteUserValues({path:{user_id:t}}),e=>({deleted:e.deleted})),batchSetOverrides:t=>P(()=>g.flags.batchUserValues({body:{operations:t.map(e=>({user_id:e.userId,values:e.values}))}}),e=>({applied:e.applied}))},Xr=_("Flags",{async isEnabled(t,e){let r=s=>(d.warn(`[palbase] flag "${t}" could not be read (${s}): treating it as off`),!1);try{let s=await N(e);return s.error?r(`${s.error.code}: ${s.error.message}`):Be(s.data[t])}catch(s){return r(s instanceof Error?s.message:String(s))}},async getVariant(t,e){let r=await N(e);return r.error?{data:null,error:r.error,status:r.status}:{data:Fe(r.data[t]),error:null,status:r.status}},async getAll(t){let e=await N(t);return e.error?{data:null,error:e.error,status:e.status}:{data:Object.entries(e.data).map(([r,s])=>{let n=Fe(s);return{name:r,enabled:Be(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):Qr(e)?a=e:e!==void 0&&(s=e,n=!0);let i=await N(a);if(i.error)return n?{data:s??null,error:null,status:i.status}:{data:null,error:i.error,status:i.status};let o=i.data[t];return{data:o===void 0?s??null:o,error:null,status:i.status}},async setOverride(t,e){let r=Le();return r?Ie.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 Ie}}),Zr=_("Realtime",{broadcast(t,e,r){return P(()=>g.realtime.broadcast({body:{messages:[{topic:t,event:e,payload:r??{}}]}}),()=>{})},state:{set(t,e,r){return P(()=>g.realtime.writeState({body:{ops:[{topic:t,key:e,value:r}]}}),()=>{})},clear(t,e){return P(()=>g.realtime.writeState({body:{ops:[{topic:t,key:e,delete:!0}]}}),()=>{})}}});import{z as xn}from"zod";export{at as AttestedDevice,Ne as AuthUnavailable,At as Authorize,It as BadRequest,Ye as Body,zt as CACHE_MAX_TTL,Ht as Cache,Pt as ChatPart,nt as Client,$t as Conflict,C as ContractRunEnded,qe as Controller,dt as Cron,V as Database,Lt as DeadlockDetected,ze as Delete,Ot as DiError,Ue as EVENT_TYPES,Xr as Flags,Ft as Forbidden,vt as Gateway,St as GatewayRefusal,We as Get,Qe as Headers,Dt as HttpError,it as Injectable,d as Log,Gt as MAX_BODY_BYTES,j as MigrationRunEnded,lt as Module,Ut as NotFound,Jr as Notifications,ct as On,Et as OnConnect,Tt as OnDisconnect,xt as OnEmpty,kt as OnFirst,et as OptionalUser,Ct as PalError,g as Palbase,E as PalbaseError,Ir as PalbaseFactory,Xe as Param,Ge as Patch,Ke as Post,Ve as Put,He as Query,Je as QueryParams,Zr as Realtime,tt as Req,rt as RequestId,ot as Resolve,L as SchemaNotPushed,Nr as Secrets,jt as SerializationFailure,Yr as Storage,Rt as Subscribe,mt as Task,ft as TaskFailure,gt as Tasks,bt as TestUserTemplate,je as TokenError,B as TokenVerifier,Nt as TooManyRequests,st as TraceId,Bt as Unauthorized,qt as UniqueViolation,yt as Upload,wt as UploadedObject,Ze as User,ut as Webhook,Js as bigint,Qs as boolean,Xs as check,I as createApp,Zs as date,Mt as defineError,en as defineSchema,tn as defineTable,Kt as encrypt,Wt as encrypted,rn as enumType,sn as foreignKey,pt as getRegisteredControllers,ht as getRoutes,_t as getWebhookManifest,yn as increment,nn as index,an as integer,on as jsonb,wn as now,ln as numeric,cn as ownedByUser,dn as policy,un as raw,pn as sqlType,Vt as t,hn as text,fn as timestamp,mn as userRef,gn as uuid,xn as z};
|
package/dist/backend/stack.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
1
|
+
/*! palbase 0.42.0 — Palbase SDK License (see LICENSE) */
|
package/dist/backend/test.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
2
|
-
import{a as u}from"../chunks/
|
|
1
|
+
/*! palbase 0.42.0 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{a as u}from"../chunks/VBROMD5X.js";import{c as p,i as c}from"../chunks/L3W75GPJ.js";import"../chunks/RNDFA3AQ.js";import{b as l,c as g,d as f,e as y}from"../chunks/L3OT55MV.js";import"../chunks/LOINJWR3.js";import"../chunks/POCZ4Q2I.js";import"../chunks/MS4WUVDW.js";import"../chunks/SMINGDYN.js";import"../chunks/6RAP4AII.js";import"../chunks/DS4WQJZM.js";import"../chunks/TUMSSUUS.js";import"../chunks/DY65FDLF.js";import"reflect-metadata";import{randomUUID as m}from"node:crypto";import{createFakeClient as w,typedDatabase as d}from"palgres/testing";function T(t,n,a){if(a?.acceptLanguage!==void 0&&a.strings===void 0)throw new TypeError("withServices: acceptLanguage chooses among the languages of a strings table, and none was given \u2014 { strings: await loadStringsTable(appRoot), acceptLanguage }");let{Database:r,...o}=t,e=a?.strings;return p.run({requestId:`test_${m()}`,database:r===void 0?void 0:d(r),services:o,...e!==void 0?{strings:e,locales:c(a?.acceptLanguage??null,e.source),usedLocales:[]}:{}},n)}function b(){let t=new Map,n=new Map,a=[],r=e=>{if(t.has(e))return t.get(e);if(n.has(e))return n.get(e);if(a.includes(e)){let s=[...a.slice(a.indexOf(e)),e].map(i=>i.name??String(i));throw new TypeError(`isolated(): ${s.join(" \u2192 ")} needs itself to be built \u2014 give one of them with .with(Token, value)`)}a.push(e);try{let s=Reflect.getMetadata("design:paramtypes",e)??[],i=new e(...s.map(r));return n.set(e,i),i}finally{a.pop()}},o={with(e,s){return t.set(e,s),o},get:e=>r(e)};return o}function h(){let t=w();return{db:d(t),raw:t,queries:t.queries,seed:(n,a)=>t.seed(n,a),inserted:n=>t.inserted(n),updated:n=>t.updated(n),deleted:n=>t.deleted(n)}}export{l as TestApiError,y as api,g as createTestApi,h as fakeDatabase,b as isolated,u as loadStringsTable,f as testRun,T as withServices};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
1
|
+
/*! palbase 0.42.0 — Palbase SDK License (see LICENSE) */
|
|
2
2
|
var Rt=d=>[...new Uint8Array(d)].map(t=>t.toString(16).padStart(2,"0")).join(""),At=d=>`pw-font-${d}`;function ne(d){return(typeof d=="string"?/^asset:([0-9a-f-]{36})$/.exec(d):null)?.[1]}async function an(d,t={}){let a={},l=t.fetch??((c,p)=>globalThis.fetch(c,p));return await Promise.all(d.map(async c=>{try{if(!/^https:\/\//.test(c.url))return;let p=await l(c.url,{signal:t.signal,credentials:"omit"});if(!p.ok)return;let g=await p.arrayBuffer();if(g.byteLength!==c.bytes&&c.bytes>0||Rt(await globalThis.crypto.subtle.digest("SHA-256",g))!==c.sha256.toLowerCase())return;let w=_t(c.kind,new Uint8Array(g));if(w===void 0)return;let y=await Et(c,g,w,t);y&&(a[c.id]=y)}catch{}})),a}var C=(d,t,a=0)=>d.length>=a+t.length&&t.every((l,c)=>d[a+c]===l),W=d=>[...d].map(t=>t.charCodeAt(0));function _t(d,t){switch(d){case"image":return C(t,[137,80,78,71,13,10,26,10])?"image/png":C(t,[255,216,255])?"image/jpeg":C(t,W("RIFF"))&&C(t,W("WEBP"),8)?"image/webp":void 0;case"video":return C(t,W("ftyp"),4)?C(t,W("qt "),8)?"video/quicktime":"video/mp4":C(t,[26,69,223,163])?"video/webm":void 0;case"font":return C(t,W("wOF2"))?"font/woff2":C(t,W("wOFF"))?"font/woff":C(t,W("OTTO"))?"font/otf":C(t,[0,1,0,0])||C(t,W("true"))?"font/ttf":void 0;case"html":return C(t,[80,75,3,4])||C(t,[80,75,5,6])?"application/zip":void 0;default:return}}async function Et(d,t,a,l){switch(d.kind){case"image":case"video":return{kind:d.kind,url:URL.createObjectURL(new Blob([t],{type:a}))};case"font":{let c=At(d.id),p=globalThis.FontFace,g=l.fonts??globalThis.document?.fonts;if(!p||!g)return;let h=new p(c,t,{display:"block"});return await h.load(),g.add(h),{kind:"font",url:"",family:c}}case"html":{let c=await Lt(new Uint8Array(t)),p=Ot(c);return p===void 0?void 0:{kind:"html",url:"",html:p}}}}async function Lt(d){let t=new DataView(d.buffer,d.byteOffset,d.byteLength),a=-1;for(let h=d.length-22;h>=Math.max(0,d.length-22-65535);h--)if(t.getUint32(h,!0)===101010256){a=h;break}if(a<0)throw new Error("not a zip");let l=t.getUint16(a+10,!0),c=t.getUint32(a+16,!0),p=new Map,g=0;for(let h=0;h<l;h++){if(t.getUint32(c,!0)!==33639248)throw new Error("a broken zip");let w=t.getUint16(c+10,!0),y=t.getUint32(c+20,!0),m=t.getUint32(c+24,!0),v=t.getUint16(c+28,!0),_=t.getUint16(c+30,!0),P=t.getUint16(c+32,!0),R=t.getUint32(c+42,!0),x=new TextDecoder().decode(d.subarray(c+46,c+46+v));if(c+=46+v+_+P,x.endsWith("/"))continue;if(x.startsWith("/")||x.split("/").includes(".."))throw new Error("a path leaving the zip");if(g+=m,p.size>=200||g>20971520)throw new Error("a zip too large");let T=R+30+t.getUint16(R+26,!0)+t.getUint16(R+28,!0),O=d.subarray(T,T+y);if(w===0)p.set(x,O);else if(w===8)p.set(x,await Pt(O));else throw new Error("a zip entry compressed another way")}return p}async function Pt(d){let t=new Response(new Uint8Array(d)).body.pipeThrough(new DecompressionStream("deflate-raw"));return new Uint8Array(await new Response(t).arrayBuffer())}var Tt={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 qe(d,t){let a=Tt[d.split(".").pop()?.toLowerCase()??""]??"application/octet-stream",l="";for(let c=0;c<t.length;c+=32768)l+=String.fromCharCode(...t.subarray(c,c+32768));return`data:${a};base64,${btoa(l)}`}var $t="default-src 'none'; img-src data:; media-src data:; font-src data:; style-src 'unsafe-inline' data:; script-src 'unsafe-inline' data:";function Ot(d){let t=d.get("index.html");if(!t)return;let a=new TextDecoder().decode(t),l=y=>new TextDecoder().decode(d.get(y)),c=y=>{let m=y.replace(/^\.\//,"").split(/[?#]/)[0];return d.has(m)?m:void 0},p=y=>y.replace(/url\(\s*(['"]?)([^'")]+)\1\s*\)/g,(m,v,_)=>{let P=c(_);return P?`url("${qe(P,d.get(P))}")`:m}),g=globalThis.DOMParser;if(!g)return;let h=new g().parseFromString(a,"text/html");for(let y of[...h.querySelectorAll('link[rel~="stylesheet"][href]')]){let m=c(y.getAttribute("href")),v=h.createElement("style");v.textContent=m?p(l(m)):"",y.replaceWith(v)}for(let y of[...h.querySelectorAll("style")])y.textContent=p(y.textContent??"");for(let y of[...h.querySelectorAll("[src], [href], [poster]")])for(let m of["src","href","poster"]){let v=y.getAttribute(m);if(v===null)continue;let _=c(v);_?y.setAttribute(m,qe(_,d.get(_))):/^(https?:)?\/\//i.test(v)&&y.removeAttribute(m)}for(let y of[...h.querySelectorAll("[style]")])y.setAttribute("style",p(y.getAttribute("style")??""));let w=h.createElement("meta");return w.setAttribute("http-equiv","Content-Security-Policy"),w.setAttribute("content",$t),h.head.prepend(w),`<!doctype html>${h.documentElement.outerHTML}`}var K=(d,t,a)=>`M${d-a} ${t}a${a} ${a} 0 1 0 ${2*a} 0a${a} ${a} 0 1 0 ${-2*a} 0`,de={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:[K(12,12,9),"M8 12l3 3 5-6"],clock:[K(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:[K(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",K(6,18,3),K(17,16,3)],people:[K(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:[K(12,8,4),"M4 21a8 8 0 0 1 16 0"],photo:["M3 5h18v14H3z",K(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 Be="http://www.w3.org/2000/svg";function pe(d,t,a){let l=d.createElementNS(Be,"svg");l.setAttribute("viewBox","0 0 24 24"),l.setAttribute("width",String(a)),l.setAttribute("height",String(a)),l.setAttribute("fill","none"),l.setAttribute("stroke","currentColor"),l.setAttribute("stroke-width","2"),l.setAttribute("stroke-linecap","round"),l.setAttribute("stroke-linejoin","round"),l.setAttribute("aria-hidden","true"),l.setAttribute("focusable","false");for(let c of t){let p=d.createElementNS(Be,"path");p.setAttribute("d",c),l.append(p)}return l}var dn=2,pn=2,f=(d,t=!1)=>({kind:"value",value:"plain",def:d,required:t}),j=d=>({kind:"value",value:"color",def:d}),We=d=>({kind:"value",value:"spacing",def:d}),zt=d=>({kind:"value",value:"radius",def:d}),X=(d=!1)=>({kind:"text",required:d}),Me=(d,t=!1)=>({kind:"list",item:d,required:t}),se=(d,t=!1)=>({kind:"object",item:d,required:t}),Ke=(d=!1)=>({kind:"component",required:d}),Re={kind:"components"},Ge={stack:{axis:f("vertical"),spacing:We(0),align:f("center"),distribution:f("start"),scroll:f(!1),children:Re},text:{text:X(),spans:Me("span"),font:f(),size:f(),weight:f(),line_height:f(),letter_spacing:f(),color:{kind:"value",value:"textColor",def:"text"},align:f("center"),max_lines:f(),uppercase:f(!1)},image:{src:f(void 0,!0),fit:f("fit"),aspect:f(),mask:se("mask"),overlay:{kind:"value",value:"textColor"},alt:X(),decorative:f(!1)},icon:{name:f(void 0,!0),color:j("accent"),size:f(24)},video:{src:f(void 0,!0),poster:f(),autoplay:f(!0),loop:f(!0),mute:f(!0),controls:f(!1),fit:f("fill"),aspect:f(),alt:X()},button:{action:se("action",!0),content:Ke(!0)},purchase_button:{content:Ke(!0),package:f()},package:{product:f(void 0,!0),plan:f(void 0,!0),selected:f(!1),offer:f(),children:Re},tabs:{},switch:{},carousel:{pages:Re,peek:f(0),spacing:f(8),loop:f(!1),auto_advance_ms:f(),indicator:se("indicator"),height:f("")},countdown:{},timeline:{items:Me("timeline_item",!0),line_color:j("accent"),line_width:f(2),icon_color:j("on_accent"),color:j("text"),spacing:f(16)},features:{items:Me("feature",!0),icon_color:j("accent"),color:j("text"),spacing:f(12)},spacer:{size:We()},divider:{color:j("muted"),thickness:f(1)},custom_html:{src:f(void 0,!0),height:f("",!0)}},Ht={style:{padding:{kind:"edges"},margin:{kind:"edges"},width:f(""),height:f(""),max_width:f(),background:{kind:"fill"},border:se("border"),corners:{kind:"corners"},shadow:se("shadow"),opacity:f(1)},border:{width:f(),color:j("")},shadow:{color:j(""),radius:f(0),x:f(0),y:f(0)},linear:{type:f(""),angle:f(180),stops:f()},radial:{type:f(""),center_x:f(.5),center_y:f(.5),radius:f(.5),stops:f()},image_fill:{type:f(""),src:f(),fit:f("fill")},video_fill:{type:f(""),src:f(),poster:f(),loop:f(!0)},animation:{type:f(""),duration_ms:f(300),delay_ms:f(0),easing:f("ease_out")},action:{type:f(""),url:f(),sheet:f(),package:f()},mask:{shape:f(""),radius:zt(0),depth:f(16)},span:{text:X(!0),bold:f(!1),italic:f(!1),underline:f(!1),strikethrough:f(!1),color:j(""),link:f()},timeline_item:{icon:f(void 0,!0),title:X(!0),text:X(),color:j("")},feature:{icon:f(void 0,!0),text:X(!0)},indicator:{style:f("dots"),color:j("muted"),active_color:j("accent"),size:f(8),spacing:f(6)},typography:{font:f("system"),size:f(),weight:f(400),line_height:f(),letter_spacing:f(0),text_style:f("body")}},Xe=new Set(["package","purchase_button"]),Ct={action:{type:f(""),url:f(),link:f(),sheet:f(),placement:f(),name:f(),value:f(),offer:f(),dismiss:f(!0)},presentation:{type:f(""),position:f("bottom"),auto_dismiss_seconds:f(),dismissible:f(!0),backdrop:j("#00000080")}},jt={modal:["type","dismissible","backdrop"],fullscreen:["type"],banner:["type","position","auto_dismiss_seconds","dismissible"],card:["type"]},Ft={linear:"linear",radial:"radial",image:"image_fill",video:"video_fill"},Nt=["top","bottom","leading","trailing"],Dt=["top_leading","top_trailing","bottom_leading","bottom_trailing"],Jt=Object.keys(Ge),un=Jt.filter(d=>!Xe.has(d)),Ye=/\{\{\s*([^{}]*?)\s*\}\}/g,Q=(d,t)=>typeof d=="object"&&d!==null&&Object.hasOwn(d,t),M=d=>typeof d=="object"&&d!==null&&!Array.isArray(d)?d:{},I=d=>Array.isArray(d)?d:[],G=(d,t)=>d??t;function It(d){let t="";for(let a of new TextEncoder().encode(d)){let l=String.fromCharCode(a);t+=/^[A-Za-z0-9._~-]$/.test(l)?l:`%${a.toString(16).toUpperCase().padStart(2,"0")}`}return t}function Vt(d){let t=Math.floor(d/86400),a=Math.floor(d%86400/3600),l=Math.floor(d%3600/60),c=d%60,p=h=>String(h).padStart(2,"0");return{countdown:t>0?`${t}d ${p(a)}:${p(l)}:${p(c)}`:a>0?`${a}:${p(l)}:${p(c)}`:`${p(l)}:${p(c)}`,days:String(t),hours:p(a),minutes:p(l),seconds:p(c)}}function fn(d){let t=[],a=c=>{if(Array.isArray(c))return c.forEach(a);if(typeof c!="object"||c===null)return;let p=c;if(p.type==="package"&&typeof p.product=="string"&&typeof p.plan=="string"){let g=`${p.product}.${p.plan}`;t.includes(g)||t.push(g)}for(let g of Object.keys(p).sort())a(p[g])},l=d;for(let c of["header","root","footer"])a(l[c]);for(let c of Object.keys(M(l.sheets)).sort())a(M(M(l.sheets)[c]).root);return t}function Ut(d){let t=new Map,a=c=>{if(Array.isArray(c))return c.forEach(a);if(typeof c!="object"||c===null)return;let p=c;if(p.type==="package"&&typeof p.offer=="string"){let g=`${p.product}.${p.plan}`;t.has(g)||t.set(g,p.offer)}for(let g of Object.keys(p).sort())a(p[g])},l=d;for(let c of["header","root","footer","sheets"])a(l[c]);return t}function gn(d,t){return _e(d,t).tree}function _e(d,t){return new ue("paywall",d,t).resolve()}function hn(d,t){return Ee(d,t).tree}function Ee(d,t){let{variables:a,...l}=t;return new ue("message",d,{...l,packages:{"":{...a}}}).resolve()}var ue=class{kind;d;opts;lang;texts={};palette;typography={};radii;spacing;packages;offers;selected="";tab="";paths=new WeakMap;tabsShown={};switchesOn={};countdowns={};constructor(t,a,l){this.kind=t,this.d=a,this.opts=l,this.offers=Ut(a);let c={};for(let[y,m]of Object.entries(l.packages??{})){let v={...m};this.open(y)||(m.price!==void 0?v.offer_price=m.price:delete v.offer_price),c[y]=v}this.packages=c;let p=M(this.d.locales),g=String(this.d.default_locale??""),h=l.locale;Q(p,h)||(h=h.split("-")[0]??"",Q(p,h)||(h=g)),this.lang=h;for(let y of[g,h])for(let[m,v]of Object.entries(M(p[y])))typeof v=="string"&&(this.texts[m]=v);let w=M(this.d.theme);this.palette=M(M(w.colors)[l.appearance]);for(let[y,m]of Object.entries(M(w.typography))){let v={};for(let[_,P]of Object.entries(this.objectFields("typography"))){let R=G(M(m)[_],P.def);R!=null&&(v[_]=R)}this.typography[y]=v}this.radii=M(w.radii),this.spacing=M(w.spacing)}open(t){let a=this.offers.get(t);return a!==void 0&&(this.opts.offers??[]).includes(a)}fields(t){if(!(this.kind==="message"&&Xe.has(t)))return Ge[t]}objectFields(t){return(this.kind==="message"?Ct[t]:void 0)??Ht[t]??{}}resolve(){let[t,a]=this.initialState();this.tab=t,this.selected=this.kind==="paywall"?a:"";let l={theme:{colors:this.palette,typography:this.typography,radii:this.radii,spacing:this.spacing}};this.kind==="paywall"&&(l.selected=a);let c=this.d.presentation;if(typeof c=="object"&&c!==null){let g=this.item("presentation",M(c),void 0)??{},h=jt[String(M(c).type)]??[];for(let w of Object.keys(g))h.includes(w)||delete g[w];l.presentation=g}for(let g of["header","root","footer"]){let h=this.d[g];if(typeof h=="object"&&h!==null){let w=this.component(M(h),g,"",!1);w&&(l[g]=w)}}let p={};if(typeof this.d.sheets=="object"&&this.d.sheets!==null){let g={};for(let[h,w]of Object.entries(M(this.d.sheets))){let y=this.component(M(M(w).root),`sheets.${h}.root`,"",!1);y&&(g[h]=y);let m=this.text(M(w).title,this.packages[this.selected]);m!==null&&(p[h]=m)}l.sheets=g}return{tree:l,pathOf:g=>this.paths.get(g),tabs:this.tabsShown,switches:this.switchesOn,sheetTitles:p,countdowns:this.countdowns,language:this.lang}}switchOn(t,a){return this.opts.switches&&Object.hasOwn(this.opts.switches,a)?this.opts.switches[a]:this.opts.switch?this.opts.switch==="on":t.default===!0}tabShown(t,a){let c=I(t.tabs).map(M).map(g=>String(g.id)),p=this.opts.tabs?.[a];return p!==void 0&&c.includes(p)?p:this.opts.tab?this.opts.tab:typeof t.default=="string"&&t.default!==""?t.default:c[0]??""}initialState(){let t="",a="",l="",c="",p=(h,w)=>{if(Array.isArray(h)){h.forEach((m,v)=>p(m,`${w}[${v}]`));return}if(typeof h!="object"||h===null)return;let y=h;switch(y.type){case"package":{let m=`${y.product}.${y.plan}`;l===""&&(l=m),y.selected===!0&&a===""&&(a=m);break}case"switch":{let m=this.switchOn(y,w),v=m?y.on_package:y.off_package;typeof v=="string"&&c===""&&(c=v),p(m?y.on:y.off,`${w}.${m?"on":"off"}`);return}case"tabs":{let m=this.tabShown(y,w);t===""&&(t=m),I(y.tabs).forEach((v,_)=>{let P=M(v);P.id===m&&(typeof P.package=="string"&&c===""&&(c=P.package),p(P.content,`${w}.tabs[${_}].content`))});return}}for(let m of Object.keys(y).sort())m!=="sheets"&&p(y[m],w===""?m:`${w}.${m}`)};for(let h of["header","root","footer"])p(this.d[h],h);let g=this.opts.selected||c||a||l;return[t,g]}holds(t,a){let l=a||this.selected;for(let[c,p]of Object.entries(t))switch(c){case"selected_package":if(!I(p).includes(this.selected))return!1;break;case"intro_eligible":if((this.opts.eligible??[]).includes(l)!==p)return!1;break;case"offer_open":if(this.open(l)!==p)return!1;break;case"platform":if(!I(p).includes(this.opts.platform))return!1;break;case"locale":if(!I(p).includes(this.opts.locale)&&!I(p).includes(this.lang))return!1;break;case"appearance":if(p!==this.opts.appearance)return!1;break;case"tab":if(p!==this.tab)return!1;break}return!0}component(t,a,l,c){if(typeof t.visible=="object"&&t.visible!==null&&!this.holds(M(t.visible),l))return null;let p=String(t.type),g=l,h=c;p==="package"&&(g=`${t.product}.${t.plan}`,h=g===this.selected);let w={type:p};this.paths.set(w,a),Q(t,"id")&&(w.id=t.id);let y={...M(t.style)};h&&Object.assign(y,M(M(t.states).selected)),Object.keys(y).length>0&&(w.style=this.style(y)),typeof t.animation=="object"&&t.animation!==null&&(w.animation=this.defaults(M(t.animation),this.objectFields("animation")));let m=this.packages[g||this.selected];switch(p){case"tabs":return this.tabs(t,w,a,g);case"switch":return this.switchOf(t,w,a,g,h);case"countdown":return this.countdown(t,w,a,g,h);case"purchase_button":{let v=typeof t.package=="string"?t.package:this.selected;w.package=v,this.open(v)&&(w.offer=this.offers.get(v));let _=this.component(M(t.content),`${a}.content`,v,h);return _?(w.content=_,w):null}case"package":w.product=t.product,w.plan=t.plan,w.selected=h,typeof t.offer=="string"&&(this.opts.offers??[]).includes(t.offer)&&(w.offer=t.offer)}for(let[v,_]of Object.entries(this.fields(p)??{})){if(p==="package"&&(v==="product"||v==="plan"||v==="selected"||v==="offer"))continue;let P=t[v],R=Q(t,v);switch(_.kind){case"component":{if(!R)continue;let x=this.component(M(P),`${a}.${v}`,g,h);if(!x&&_.required)return null;x&&(w[v]=x);break}case"components":{let x=[];I(P).forEach((T,O)=>{let V=this.component(M(T),`${a}.${v}[${O}]`,g,h);V&&x.push(V)}),w[v]=x;break}case"text":{let x=this.text(P,m);if(x!==null)w[v]=x;else if(_.required||p==="text"&&v==="text"&&R)return null;break}case"list":{let x=[];for(let T of I(P)){let O=this.item(_.item,M(T),m);O&&x.push(O)}if(p==="text"&&x.length===0&&R)return null;R&&(w[v]=x);break}case"object":{if(R){let x=this.object(M(P),_.item,m);if(x===null&&_.required)return null;w[v]=x}else v==="indicator"&&(w[v]=this.object({},_.item,m));break}case"value":{let x=this.value(G(P,_.def),_);x!=null&&x!==""&&(w[v]=x);break}}}return p==="text"&&this.typeStyle(w),w}typeStyle(t){if(typeof t.size!="string"){t.size!==void 0&&t.size!==null&&(t.text_style="body");return}let a=this.typography[t.size];for(let l of["font","weight","line_height","letter_spacing","text_style"])!Q(t,l)&&a?.[l]!==void 0&&a?.[l]!==null&&(t[l]=a[l]);t.size=a?.size??null}tabs(t,a,l,c){let p=this.tabShown(t,l);this.tabsShown[l]=p;let g=[];return I(t.tabs).forEach((h,w)=>{let y=M(h),m=y.id===p,v=this.component(M(y.label),`${l}.tabs[${w}].label`,c,m);if(g.push({id:y.id,selected:m,label:v}),m){let _=this.component(M(y.content),`${l}.tabs[${w}].content`,c,!1);_&&(a.content=_)}}),a.tabs=g,typeof t.bar=="object"&&t.bar!==null&&(a.bar=this.style(M(t.bar))),a}switchOf(t,a,l,c,p){let g=this.switchOn(t,l);this.switchesOn[l]=g,a.on=g;let h=this.text(t.label,this.packages[c||this.selected]);h!==null&&(a.label=h),a.tint=this.color(String(G(t.tint,"accent")));let w=g?"on":"off",y=this.component(M(t[w]),`${l}.${w}`,c,p);return y&&(a.content=y),a}countdown(t,a,l,c,p){let g=M(t.target),h=this.opts.now??Date.now(),w;if(typeof g.after_open_seconds=="number"?w=Math.trunc(g.after_open_seconds)-(this.opts.openedSecondsAgo??0):w=Math.trunc((Date.parse(String(g.at))-h)/1e3),w>0){a.state="counting",a.remaining_seconds=w,this.countdowns[l]=w;let y=this.packages,m={};for(let[_,P]of Object.entries(y))m[_]={...P,...Vt(w)};this.packages=m;let v=this.component(M(t.counting),`${l}.counting`,c,p);return v&&(a.content=v),this.packages=y,a}if(a.state="ended",a.remaining_seconds=0,typeof t.ended=="object"&&t.ended!==null){let y=this.component(M(t.ended),`${l}.ended`,c,p);y&&(a.content=y)}return a}item(t,a,l){let c={};for(let[p,g]of Object.entries(this.objectFields(t))){let h=a[p];if(g.kind==="text"){let w=this.text(h,l);if(w!==null)c[p]=w;else if(g.required)return null}else{let w=g.def,y=this.value(G(h,w),g);y!=null&&(Q(a,p)||w!=null&&w!=="")&&(c[p]=y)}}return c}object(t,a,l){if(a==="style")return this.style(t);let c=this.item(a,t,l)??{};if(a==="action")for(let p of["url","link"]){if(typeof c[p]!="string")continue;let g=qt(c[p],l);if(g===null)return null;c[p]=g}return c}defaults(t,a){let l={};for(let[c,p]of Object.entries(a)){let g=G(t[c],p.def);g!=null&&g!==""&&(l[c]=g)}return l}style(t){let a={};for(let[l,c]of Object.entries(t)){let p=this.objectFields("style")[l];if(!p){a[l]=c;continue}switch(p.kind){case"edges":a[l]=this.sides(c,Nt,this.spacing);break;case"corners":a[l]=this.sides(c,Dt,this.radii);break;case"fill":a[l]=this.fill(c);break;case"object":{let g=M(c),h={};for(let[w,y]of Object.entries(this.objectFields(p.item))){let m=G(g[w],y.def);m!=null&&m!==""&&(h[w]=this.value(m,y))}a[l]=h;break}default:a[l]=c}}return a}sides(t,a,l){let c={};for(let p of a){let g=typeof t=="object"&&t!==null?G(M(t)[p],0):t;c[p]=Ae(g,l)}return c}fill(t){if(typeof t=="string")return{type:"color",color:this.color(t)};let a=M(t),l=this.defaults(a,this.objectFields(Ft[String(a.type)]??""));return Array.isArray(a.stops)&&(l.stops=a.stops.map(c=>({color:this.color(String(M(c).color)),at:M(c).at}))),l}value(t,a){if(a.kind!=="value")return t;switch(a.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 Ae(t,this.spacing);case"radius":return Ae(t,this.radii);default:return t}}color(t){let a=Object.hasOwn(this.palette,t)?this.palette[t]:void 0;return typeof a=="string"?a:t}text(t,a){let l;if(typeof t=="string")l=t;else if(typeof t=="object"&&t!==null&&!Array.isArray(t)){let p=t.t;l=typeof p=="string"&&Object.hasOwn(this.texts,p)?this.texts[p]:""}else return null;let c=!1;return l=l.replace(Ye,(p,g)=>{let h=a&&Object.hasOwn(a,g)?a[g]:void 0;return typeof h!="string"||h===""?(c=!0,""):h}),c||l.trim()===""?null:l}};function qt(d,t){let a=!1,l=d.replace(Ye,(c,p)=>{let g=t&&Object.hasOwn(t,p)?t[p]:void 0;return typeof g!="string"||g===""?(a=!0,""):It(g)});return a?null:l}function Ae(d,t){return typeof d=="string"?Object.hasOwn(t,d)?t[d]:null:d}var Bt={packages:"Choose a plan",close:"Close",restore:"Restore purchases",page:(d,t)=>`${d} of ${t}`},ee={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'},Wt=1.35,Ze=20,Kt=new Set(["button","purchase_button","package","text"]),Gt=new Set(["ar","he","fa","ur","ps","yi","dv","ug","ku","sd"]),Qe={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)"},Xt={start:"flex-start",center:"center",end:"flex-end",stretch:"stretch"},Yt={start:"flex-start",center:"center",end:"flex-end",space_between:"space-between",space_around:"space-around",space_evenly:"space-evenly"},Zt={stack:["children"],package:["children"],button:["content"],purchase_button:["content"],tabs:["tabs","content"],switch:["content"],carousel:["pages"],countdown:["content"]},Qt={package:["selected"],purchase_button:["package"],switch:["on"],countdown:["state","remaining_seconds"]},en=`
|
|
3
3
|
:host{display:block;height:100%}
|
|
4
4
|
.pw2{position:relative;box-sizing:border-box;display:flex;flex-direction:column;height:100%;overflow:hidden;font-family:${ee.system};font-size:1rem;line-height:1.3;-webkit-font-smoothing:antialiased;-webkit-text-size-adjust:100%;text-rendering:optimizeLegibility}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
2
|
-
import"./
|
|
1
|
+
/*! palbase 0.42.0 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import"./DY65FDLF.js";import{realpathSync as Je}from"node:fs";import{resolve as ge}from"node:path";import vt from"typescript";import{existsSync as he,readFileSync as be}from"node:fs";import{createRequire as Qe}from"node:module";import{dirname as re,join as G,relative as We,resolve as xe,sep as ne}from"node:path";var b=class extends Error{constructor(t){super(t),this.name="ContractAnalysisError"}},Z=new Set(["palbase/backend","@palbase/backend","palgres"]),Ge=new Set(["Get","Post","Put","Patch","Delete","Query","Upload"]);function we(e){if(typeof e.createProgram!="function"||typeof e.getDecorators!="function"||typeof e.readConfigFile!="function")throw new b(`the contract is read with TypeScript's compiler API, and the TypeScript given (v${e.version??"unknown"}) has none \u2014 TypeScript 7 is the Go-native compiler, whose package exposes version metadata only`)}var Ze={bun:"bun-types",node:"@types/node"},He=Qe(import.meta.url);function Xe(e,t,n){if(!n.types)return{types:void 0,files:[]};let r=[],s=[];for(let i of n.types){let o=Ze[i],a=e.resolveTypeReferenceDirective(i,G(t,"tsconfig.json"),n,e.sys).resolvedTypeReferenceDirective,c;if(!a&&o)try{c=He.resolve(`${o}/package.json`)}catch{c=void 0}if(!c){r.push(i);continue}let l=JSON.parse(be(c,"utf8"));s.push(G(re(c),l.types??l.typings??"index.d.ts"))}return{types:r,files:s}}function ke(e,t){we(e);let n=G(t,"tsconfig.json"),r={target:e.ScriptTarget.ES2022,module:e.ModuleKind.ESNext,moduleResolution:e.ModuleResolutionKind.Bundler,experimentalDecorators:!0,allowImportingTsExtensions:!0},s=[];if(he(n)){let i=e.readConfigFile(n,e.sys.readFile);if(i.error)throw new b(`${n}: ${e.flattenDiagnosticMessageText(i.error.messageText,`
|
|
3
3
|
`)}`);let o=e.parseJsonConfigFileContent(i.config,e.sys,t);r=o.options,s=o.fileNames.filter(c=>/\.d\.[cm]?ts$/.test(c));let a=Xe(e,t,r);r={...r,types:a.types},s=[...s,...a.files]}return{options:{...r,strictNullChecks:!0,noEmit:!0,skipLibCheck:!0},ambient:s}}function Ee(e,t,n,r,s){we(e);let i=e.createProgram([...new Set(n)],r,s);return{ts:e,root:t,program:i,checker:i.getTypeChecker(),packages:new Map}}function $(e,t){let n=xe(t);return!n.includes(`${ne}node_modules${ne}`)&&!/\.d\.[cm]?ts$/.test(n)&&(n===e.root||n.startsWith(e.root+ne))}function v(e,t){return!!t&&$(e,t.getSourceFile().fileName)}function Ce(e,t){let n=[],r=re(xe(t)),s=null;for(;;){let i=e.packages.get(r);if(i!==void 0){s=i;break}n.push(r);let o=G(r,"package.json");if(he(o)){try{let c=JSON.parse(be(o,"utf8")).name;s=typeof c=="string"?c:null}catch{s=null}break}let a=re(r);if(a===r)break;r=a}for(let i of n)e.packages.set(i,s);return s}function se(e,t){if($(e,t))return!1;let n=Ce(e,t)??"";return n==="palbase"?/[\\/]types[\\/]backend[\\/]/.test(t):Z.has(n)}function ie(e,t){if($(e,t))return!1;let n=Ce(e,t)??"";return Z.has(n)||n==="palbase"||n.startsWith("@palbase/")}function O(e,t){let n=t.getSourceFile(),{line:r}=n.getLineAndCharacterOfPosition(t.getStart(n));return`${We(e.root,n.fileName)}:${r+1}`}function T(e,t){for(;t;){if(e.isParenthesizedExpression(t)||e.isAsExpression(t)||e.isNonNullExpression(t)||e.isAwaitExpression(t)||e.isTypeAssertionExpression(t)||e.isSatisfiesExpression(t)){t=t.expression;continue}return t}return t}function H(e,t){if(t&&t.flags&e.ts.SymbolFlags.Alias){let n=e.checker.getAliasedSymbol(t);if(n&&n.declarations)return n}return t}function L(e,t){let n=H(e,e.checker.getSymbolAtLocation(t));return n&&(n.valueDeclaration||n.declarations&&n.declarations[0])||null}function ye(e,t){let n=t;for(;n&&!e.isImportDeclaration(n)&&!e.isExportDeclaration(n);)n=n.parent;return n&&(e.isImportDeclaration(n)||e.isExportDeclaration(n))&&n.moduleSpecifier&&e.isStringLiteral(n.moduleSpecifier)?n.moduleSpecifier.text:null}function I(e,t){let n=e.ts;if(t=T(n,t),!t)return null;if(n.isPropertyAccessExpression(t)){let i=e.checker.getSymbolAtLocation(t.expression);return i&&(i.declarations||[]).some(a=>n.isNamespaceImport(a)&&Z.has(ye(n,a)??""))?t.name.text:null}if(!n.isIdentifier(t))return null;let r=e.checker.getSymbolAtLocation(t),s=new Set;for(;r&&!s.has(r);){s.add(r);for(let i of r.declarations||[]){if((n.isImportSpecifier(i)||n.isExportSpecifier(i))&&Z.has(ye(n,i)??""))return(i.propertyName||i.name).text;if(se(e,i.getSourceFile().fileName))return r.name}if(!(r.flags&n.SymbolFlags.Alias))return null;r=e.checker.getImmediateAliasedSymbol(r)}return null}function Te(e,t){let n=t.expression;return I(e,e.ts.isCallExpression(n)?n.expression:n)}function P(e,t){return t&&(e.isIdentifier(t)||e.isPrivateIdentifier(t)||e.isStringLiteral(t)||e.isNumericLiteral(t))?t.text:null}function X(e,t){let n=e.ts,r=[];for(let s of t.statements){if(!n.isClassDeclaration(s)||!(n.getDecorators(s)||[]).some(o=>Te(e,o)==="Controller"))continue;if(!s.name)throw new b(`${O(e,s)} \u2014 a @Controller class needs a name \u2014 its routes' errors are bound to it by name`);let i=[];for(let o of s.members)if(!(!n.isMethodDeclaration(o)||!o.body)&&(n.getDecorators(o)||[]).some(a=>Ge.has(Te(e,a)??""))){if(P(n,o.name)===null)throw new b(`${O(e,o)} \u2014 a route method needs a plain name; the contract reaches it by name`);i.push(o)}r.push({cls:s,routes:i})}return r}var Ye=new Set([2307,2580,2582,2583,2584,2591,2592,2593,2688,2867,2868,7016]);function et(e){let t=e.getSymbol();return t?.getName()==="Response"&&(t.declarations??[]).length>0&&(t.declarations??[]).every(n=>n.getSourceFile().isDeclarationFile)}function Ne(e){let{ts:t,program:n,checker:r}=e,s=!1;return function(o,a){let c=o.getSourceFile().fileName,l=o.name.getText(o.getSourceFile()),u=d=>{throw new b(`${c} \u2014 ${a}.${l}: cannot infer a safe response contract (${d}). Use a named Zod return schema for this response; any/unknown is never emitted as a successful contract.`)};if(!s){let d=[];for(let p of n.getSourceFiles()){if(d.length>=5)break;p.isDeclarationFile||n.isSourceFileFromExternalLibrary(p)||/[\\/]node_modules[\\/]/.test(p.fileName)||ie(e,p.fileName)||d.push(...n.getSemanticDiagnostics(p).filter(x=>x.category===t.DiagnosticCategory.Error&&!Ye.has(x.code)))}d.length&&u(t.formatDiagnostics(d.slice(0,5),{getCanonicalFileName:p=>p,getCurrentDirectory:()=>e.root,getNewLine:()=>`
|
|
4
4
|
`})),s=!0}let m=r.getSignatureFromDeclaration(o),g=m&&r.getAwaitedType(r.getReturnTypeOfSignature(m));if(!g)return u("unresolved return type");if(g.flags&(t.TypeFlags.Void|t.TypeFlags.Undefined))return{kind:"void"};if(et(g))return{kind:"raw"};function y(d){let p=d.getSymbol();if(p?.getName()!=="Encrypted"||!(p.declarations??[]).some(S=>ie(e,S.getSourceFile().fileName)))return;let x=r.getTypeArguments(d);return x.length===1?x[0]:void 0}let f=new Set,V=0;function h(d,p){if(++V>2e3||f.size>24)return u(`${p}: contract is too large; name its schema`);let x=d.flags,S=t.TypeFlags;if(x&(S.Any|S.Unknown|S.Never|S.TypeParameter))return u(`${p}: ${r.typeToString(d)}`);let pe=y(d);if(pe)return`encrypted(${h(pe,p)})`;let Se=w=>{let k=r.getPropertiesOfType(w);if(!(w.flags&S.Object)||k.length!==1||k[0].name!=="__pg"||!(k[0].flags&t.SymbolFlags.Optional)||r.getIndexInfosOfType(w).length)return!1;let N=r.getTypeOfSymbolAtLocation(k[0],o);return(N.isUnion()?N.types:[N]).every(E=>E.flags&(S.StringLiteral|S.Undefined))};if(d.isIntersection()){let w=d.types.filter(k=>!Se(k));if(w.length===1&&w.length<d.types.length)return h(w[0],p)}if(Se(d))return u(`${p}: unknown PostgreSQL payload; name its response schema`);if(x&S.StringLiteral)return`z.literal(${JSON.stringify(d.value)})`;if(x&S.NumberLiteral)return`z.literal(${JSON.stringify(d.value)})`;if(x&S.BooleanLiteral)return`z.literal(${r.typeToString(d)==="true"})`;if(x&S.String)return"z.string()";if(x&S.TemplateLiteral){let w=d;if(w.types.length>8||!w.types.every(E=>E.flags&S.String))return u(`${p}: template literal requires an explicit schema`);let k=E=>E.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),N="^"+k(w.texts[0]);for(let E of w.texts.slice(1,-1))if(E){let te=k(E);N+=`(?:(?!${te})[\\s\\S])*${te}`}return N+="[\\s\\S]*"+k(w.texts.at(-1))+"$(?![\\s\\S])",N.length>4096?u(`${p}: template pattern is too large`):`z.string().regex(new RegExp(${JSON.stringify(N)}))`}if(x&S.Number)return"z.number().finite()";if(x&S.Boolean)return"z.boolean()";if(x&S.Null)return"z.null()";if(x&S.Undefined)return"z.undefined()";if(f.has(d))return u(`${p}: recursive response`);f.add(d);try{if(d.isUnion()){if(d.types.length>32)return u(`${p}: union has more than 32 alternatives`);let A=d.types.some(M=>M.flags&S.Null),W=d.types.some(M=>M.flags&S.Undefined),j=d.types.filter(M=>!(M.flags&(S.Null|S.Undefined)));return(j.length===0?A?"z.null()":"z.undefined()":j.length===1?h(j[0],p):`z.union([${j.map(M=>h(M,p)).join(",")}])`)+(A&&j.length?".nullable()":"")+(W?".optional()":"")}if(r.isTupleType(d))return u(`${p}: tuple requires an explicit schema`);if(r.isArrayType(d)){let A=r.getTypeArguments(d)[0];return A.flags&S.Never?"z.array(z.string()).length(0)":`z.array(${h(A,`${p}[]`)})`}let w=d.isIntersection()&&d.types.every(A=>A.flags&S.Object);if(!(x&S.Object)&&!w||d.getCallSignatures().length||d.getConstructSignatures().length)return u(`${p}: non-JSON type ${r.typeToString(d)}`);let k=d.symbol?.declarations?.[0];if(k&&(t.isClassDeclaration(k)||t.isClassExpression(k)))return u(`${p}: class instance ${r.typeToString(d)}`);let N=r.getPropertiesOfType(d),E=r.getIndexInfosOfType(d);return E.length?E.length!==1||!(E[0].keyType.flags&S.String)||N.length?u(`${p}: mixed or non-string index signature`):`z.record(z.string(), ${h(E[0].type,`${p}.*`)})`:N.length?`z.object({${N.map(A=>{if(A.escapedName.toString().startsWith("__@"))return u(`${p}: symbol property`);let W=A.getName(),j=h(r.getTypeOfSymbolAtLocation(A,o),`${p}.${W}`);return`${JSON.stringify(W)}:${j}${A.flags&t.SymbolFlags.Optional?".optional()":""}`}).join(",")}}).strict()`:u(`${p}: empty structural type`)}finally{f.delete(d)}}return{kind:"expression",expression:h(g,"return")}}}import{resolve as tt}from"node:path";var oe=Symbol("not a named schema");function Ae(e,t,n,r){let{ts:s}=e,i=r.getSourceFile(),o=r.name.getText(i),a=f=>new b(`${i.fileName} \u2014 ${n}.${o}: ${f}`);function c(f){if(s.isTypeReferenceNode(f)&&f.typeName.getText(i)==="Promise"&&f.typeArguments&&f.typeArguments.length===1)return c(f.typeArguments[0]);if(f.kind===s.SyntaxKind.VoidKeyword||f.kind===s.SyntaxKind.UndefinedKeyword)return null;let V=s.isArrayTypeNode(f)?f.elementType:s.isTypeReferenceNode(f)&&f.typeName.getText(i)==="Array"&&f.typeArguments&&f.typeArguments.length===1?f.typeArguments[0]:void 0,h=l(V??f);return h===oe?h:{...h,isArray:V!==void 0}}function l(f){if(s.isTypeReferenceNode(f)&&!f.typeArguments)return{typeName:f.typeName.getText(i),node:f.typeName};if(s.isTypeReferenceNode(f)&&f.typeArguments&&f.typeArguments.length===1){let V=f.typeName.getText(i);if(/^(z\.)?(infer|output|input)$/.test(V)){let h=f.typeArguments[0];if(s.isTypeQueryNode(h))return{typeName:h.exprName.getText(i),node:h.exprName};if(s.isTypeReferenceNode(h)&&!h.typeArguments)return{typeName:h.typeName.getText(i),node:h.typeName}}}if(f.kind===s.SyntaxKind.VoidKeyword)throw a("void cannot appear inside an array/Promise here");return oe}let u=()=>t(r,n);if(!r.type)return u();let m=c(r.type);if(m===null)return{kind:"void"};if(m===oe)return u();let g=nt(e,m.node);if(!g)return u();let y=rt(e,g.symbol);return y?{kind:"schema",...y,array:m.isArray}:u()}function nt(e,t){let{ts:n,checker:r}=e,s=r.getSymbolAtLocation(n.isQualifiedName(t)?t.right:t),i=H(e,s);if(!i||!(i.flags&n.SymbolFlags.Variable))return null;let o=i.valueDeclaration;return!o||!n.isVariableDeclaration(o)||!r.getTypeOfSymbolAtLocation(i,o).getProperty("~standard")?null:{symbol:i}}function rt(e,t){let n=t.valueDeclaration?.getSourceFile();if(!n||n.isDeclarationFile)return null;let r=e.checker.getSymbolAtLocation(n);if(!r)return null;let s=e.checker.getExportsOfModule(r).filter(i=>H(e,i)===t).map(i=>i.name);return s.length===0?null:{file:tt(n.fileName),exportName:s.includes(t.name)?t.name:s[0]}}var ue={BadRequest:{code:"bad_request",status:400,codeArg:null},Unauthorized:{code:"unauthorized",status:401,codeArg:1},Forbidden:{code:"forbidden",status:403,codeArg:1},NotFound:{code:"not_found",status:404,codeArg:1},Conflict:{code:"conflict",status:409,codeArg:1},UniqueViolation:{code:"unique_violation",status:409,codeArg:2},SerializationFailure:{code:"serialization_failure",status:409,codeArg:null},DeadlockDetected:{code:"deadlock_detected",status:409,codeArg:null},TooManyRequests:{code:"too_many_requests",status:429,codeArg:null}},st=new Set(["HttpError","PalError"]),it=[{member:"page",container:null,error:{name:"BadRequest",code:"bad_request",status:400}},{member:"$page",container:null,error:{name:"BadRequest",code:"bad_request",status:400}},{member:"update",container:/^RepositoryOf(\$\d+)?$/,error:{name:"NotFound",code:"not_found",status:404}},{member:"update",container:/^RepositoryOf(\$\d+)?$/,error:{name:"BadRequest",code:"bad_request",status:400}},{member:"updateScoped",container:/^RepositoryOf(\$\d+)?$/,error:{name:"BadRequest",code:"bad_request",status:400}}],ot=new Map([["expectOne",0],["expectNone",0],["expectAtLeast",1],["expectAtMost",1]]);function $e(e){let t={...e,ids:new WeakMap,nextId:1,providerSet:null,concrete:null,summaries:new Map,warnings:new Map,statusOf:null,round:0,cyclic:!1,grew:!1};return{analyze(n){let r;for(;t.round+=1,t.cyclic=!1,t.grew=!1,r=At(t,n),!(!t.cyclic||!t.grew););for(let s of t.summaries.values())s.final=!0;return r},warnings(){return[...t.warnings.values()]}}}function at(e,t,n){throw new b(`${O(e,t)} \u2014 ${n}`)}function q(e,t){let n=e.ids.get(t);return n||(n=e.nextId++,e.ids.set(t,n)),n}function de(e,t){return(e.getCombinedModifierFlags(t)&e.ModifierFlags.Static)!==0}function Fe(e,t){return(e.getCombinedModifierFlags(t)&e.ModifierFlags.Abstract)!==0}function F(e,t){return!!t&&(e.isClassDeclaration(t)||e.isClassExpression(t))}function Oe(e,t){if(!t)return null;if(F(e,t))return t;if((e.isVariableDeclaration(t)||e.isPropertyDeclaration(t)||e.isPropertyAssignment(t))&&t.initializer){let n=T(e,t.initializer);if(e.isClassExpression(n))return n}return null}function ct(e,t){if(t.name)return t.name.text;let n=t.parent;if(n&&(e.isVariableDeclaration(n)||e.isPropertyDeclaration(n)||e.isPropertyAssignment(n))&&n.name&&P(e,n.name))return P(e,n.name)??void 0}function _(e,t){let n=e.ts,r=T(n,t);if(!r)return null;let s=Oe(n,L(e,n.isPropertyAccessExpression(r)?r.name:r));return s&&v(e,s)?s:null}function J(e,t){let n=e.ts,r=(t.heritageClauses||[]).find(i=>i.token===n.SyntaxKind.ExtendsKeyword),s=r&&r.types[0]&&r.types[0].expression;return s?_(e,s):null}function Re(e,t,n){for(let r=J(e,t);r;r=J(e,r))if(r===n)return!0;return!1}function U(e,t,n,r){let s=e.ts;for(let i=t;i;i=J(e,i))for(let o of i.members)if(!(P(s,o.name)!==n||de(s,o)!==r)){if((s.isMethodDeclaration(o)||s.isGetAccessorDeclaration(o))&&o.body)return{fn:o,owner:i};if(s.isPropertyDeclaration(o)&&o.initializer){let a=T(s,o.initializer);if(s.isArrowFunction(a)||s.isFunctionExpression(a))return{fn:a,owner:i}}}return null}function lt(e){let t=e.ts;if(e.providerSet)return e.providerSet;let n=new Set;for(let r of e.program.getSourceFiles())if($(e,r.fileName)){for(let s of r.statements)if(t.isClassDeclaration(s))for(let i of t.getDecorators(s)||[]){let o=i.expression;if(!t.isCallExpression(o)||I(e,o.expression)!=="Module")continue;let a=T(t,o.arguments[0]);if(!(!a||!t.isObjectLiteralExpression(a)))for(let c of a.properties){if(!t.isPropertyAssignment(c)||P(t,c.name)!=="providers")continue;let l=T(t,c.initializer);if(t.isArrayLiteralExpression(l))for(let u of l.elements){let m=_(e,u);m&&n.add(m)}}}}return e.providerSet=n,n}function ve(e){let t=e.ts;if(e.concrete)return e.concrete;let n=[],r=s=>{F(t,s)&&!Fe(t,s)&&n.push(s),t.forEachChild(s,r)};for(let s of e.program.getSourceFiles())$(e,s.fileName)&&r(s);return e.concrete=n,n}function ze(e,t){let n=t.name?e.checker.getSymbolAtLocation(t.name):t.symbol;return n?e.checker.getDeclaredTypeOfSymbol(n):null}function ut(e,t){let n=t&&(t.getSymbol()||t.aliasSymbol),r=n&&(n.declarations||[]).find(s=>F(e.ts,s));return r&&F(e.ts,r)&&v(e,r)?r:null}function ae(e,t){return t.type?e.checker.getTypeFromTypeNode(t.type):e.checker.getTypeAtLocation(t.name||t)}function Q(e,t,n){let r=e.ts;if(!t)return;if(t.isUnion()){for(let l of t.types)Q(e,l,n);return}let s=r.TypeFlags,i=s.StringLike|s.NumberLike|s.BigIntLike|s.BooleanLike|s.EnumLike|s.ESSymbolLike|s.VoidLike|s.Null;if(t.flags&(s.Any|s.Unknown|i))return;let o=t.getSymbol();if(!o)return;let a=(o.declarations||[]).find(l=>F(r,l));if(a&&F(r,a)){if(!v(e,a))return;Fe(r,a)||n.add(a);for(let l of ve(e))Re(e,l,a)&&n.add(l);return}if((o.declarations||[]).some(l=>v(e,l)))for(let l of ve(e)){let u=ze(e,l);u&&e.checker.isTypeAssignableTo(u,t)&&n.add(l)}}function fe(e,t,n){let r=ut(e,t);if(r){let s=lt(e);if(s.has(r)){n.add(r);return}let i=[...s].filter(o=>o!==r&&Re(e,o,r));if(i.length===1){n.add(i[0]);return}}Q(e,t,n)}function ft(e,t){for(let n=e;n;n=n.parent)if(n===t)return!0;return!1}function je(e,t){return t.fn&&ft(e,t.fn)?t:{receiver:null,owner:null,fn:null}}function C(e,t,n,r=new Set){let s=e.ts,i=new Set;if(t=T(s,t),!t)return i;let o=`${q(e,t)}@${n.receiver?q(e,n.receiver):0}`;if(r.has(o))return i;r.add(o);let a=c=>{for(let l of c)i.add(l)};if(s.isNewExpression(t)){let c=_(e,t.expression);return c&&i.add(c),i}if(t.kind===s.SyntaxKind.ThisKeyword)return n.receiver&&i.add(n.receiver),i;if(s.isConditionalExpression(t))return a(C(e,t.whenTrue,n,r)),a(C(e,t.whenFalse,n,r)),i;if(s.isBinaryExpression(t)){let c=t.operatorToken.kind,l=s.SyntaxKind;if(c===l.QuestionQuestionToken||c===l.BarBarToken||c===l.AmpersandAmpersandToken)return a(C(e,t.left,n,r)),a(C(e,t.right,n,r)),i;if(c===l.CommaToken||c===l.EqualsToken)return a(C(e,t.right,n,r)),i}if(s.isCallExpression(t)){for(let c of ee(e,t,n))for(let l of Y(s,c.fn))a(C(e,l,c.ctx,r));if(i.size>0)return i}else if(s.isIdentifier(t)||s.isPropertyAccessExpression(t)){let c=L(e,s.isPropertyAccessExpression(t)?t.name:t);if(c&&s.isVariableDeclaration(c))return c.initializer&&a(C(e,c.initializer,je(c,n),r)),(!((s.getCombinedNodeFlags(c)&s.NodeFlags.Const)!==0)||!c.initializer)&&Q(e,ae(e,c),i),i;if(c&&s.isParameter(c)){let l=ae(e,c);return c.parent&&s.isConstructorDeclaration(c.parent)?fe(e,l,i):Q(e,l,i),i}if(c&&s.isPropertyDeclaration(c))return c.initializer?a(C(e,c.initializer,{receiver:c.parent,owner:c.parent,fn:null},r)):fe(e,ae(e,c),i),i;if(c&&s.isGetAccessorDeclaration(c)&&c.body){for(let l of Y(s,c))a(C(e,l,{receiver:c.parent,owner:c.parent,fn:c},r));if(i.size>0)return i}if(c&&s.isPropertyAssignment(c)&&(a(C(e,c.initializer,{receiver:null,owner:null,fn:null},r)),i.size>0))return i}return Q(e,e.checker.getTypeAtLocation(t),i),i}function Y(e,t){if(e.isArrowFunction(t)&&!e.isBlock(t.body))return[t.body];let n=e.isFunctionLike(t)?t.body:void 0;if(!n)return[];let r=[],s=i=>{if(e.isReturnStatement(i)){i.expression&&r.push(i.expression);return}e.isFunctionLike(i)||F(e,i)||e.forEachChild(i,s)};return e.forEachChild(n,s),r}function Me(e,t){return e.isPropertyAccessExpression(t)?t.name.text:e.isElementAccessExpression(t)&&e.isStringLiteralLike(t.argumentExpression)?t.argumentExpression.text:null}function Ie(e,t){return e.isPropertyAccessExpression(t)?t.name:t.argumentExpression}function dt(e,t){let n=e.ts,r=Me(n,t);if(r===null)return[];let s=e.checker.getSymbolAtLocation(Ie(n,t)),i=new Map;for(let o of s&&s.declarations||[]){if(!se(e,o.getSourceFile().fileName))continue;let a=o.parent,c=a&&a.name&&n.isIdentifier(a.name)?a.name.text:"";for(let l of it)l.member===r&&(!l.container||l.container.test(c))&&i.set(l.error.code,l.error)}return[...i.values()]}function mt(e,t){let n=e.checker.getSymbolAtLocation(Ie(e.ts,t));return n?(n.declarations||[]).some(r=>v(e,r)):!0}function Be(e,t,n){let r=e.ts,s=[];for(let i=t;i;i=J(e,i)){for(let a of i.members){if(!r.isPropertyDeclaration(a)||!a.initializer||de(r,a))continue;let c=T(r,a.initializer);r.isArrowFunction(c)||r.isFunctionExpression(c)||s.push({fn:a.initializer,ctx:{receiver:n,owner:i,fn:null}})}let o=i.members.find(a=>r.isConstructorDeclaration(a)&&!!a.body);if(o){s.push({fn:o,ctx:{receiver:n,owner:i,fn:o}});break}}return s}function ee(e,t,n){let r=e.ts,s=T(r,t.expression);if(s.kind===r.SyntaxKind.SuperKeyword){let c=n.owner&&J(e,n.owner);return c?Be(e,c,n.receiver):[]}let i=Me(r,s);if(i!==null){let c=s,l=T(r,c.expression);if(l.kind===r.SyntaxKind.SuperKeyword){let g=n.owner&&J(e,n.owner),y=g&&U(e,g,i,!1);return y?[{fn:y.fn,ctx:{receiver:n.receiver,owner:y.owner,fn:y.fn}}]:[]}let u=r.isIdentifier(l)||r.isPropertyAccessExpression(l)?_(e,l):null;if(u){let g=U(e,u,i,!0);return g?[{fn:g.fn,ctx:{receiver:null,owner:g.owner,fn:g.fn}}]:[]}if(!mt(e,c))return[];let m=[];for(let g of C(e,l,n)){let y=U(e,g,i,!1);y&&m.push({fn:y.fn,ctx:{receiver:g,owner:y.owner,fn:y.fn}})}if(m.length>0)return m}let o=e.checker.getResolvedSignature(t),a=o&&o.declaration;if(a&&!r.isJSDocSignature(a)&&a.body&&v(e,a)){let c=a,l=c.parent&&F(r,c.parent)?c.parent:null,u=l&&!de(r,c)?l:null;return[{fn:c,ctx:{receiver:u,owner:l,fn:c}}]}return[]}function De(e,t,n){let r=e.ts,s=T(r,t);if(!s)return[];if(r.isPropertyAccessExpression(s)){let i=L(e,s.name);if(!(i&&v(e,i)&&(r.isMethodDeclaration(i)||r.isPropertyDeclaration(i))))return[];let a=[];for(let c of C(e,s.expression,n)){let l=U(e,c,s.name.text,!1);l&&a.push({fn:l.fn,ctx:{receiver:c,owner:l.owner,fn:l.fn}})}return a}if(r.isIdentifier(s)){let i=L(e,s);if(!i||!v(e,i))return[];if(r.isFunctionDeclaration(i)&&i.body)return[{fn:i,ctx:{receiver:null,owner:null,fn:i}}];if(r.isVariableDeclaration(i)&&i.initializer){let o=T(r,i.initializer);if(r.isArrowFunction(o)||r.isFunctionExpression(o))return[{fn:o,ctx:{receiver:null,owner:null,fn:o}}]}}return[]}function K(e,t,n){let r=e.ts,s=T(r,t);if(!s)return null;if(n==="string"&&(r.isStringLiteral(s)||r.isNoSubstitutionTemplateLiteral(s)))return[s.text];if(n==="number"&&r.isNumericLiteral(s))return[Number(s.text)];let i=e.checker.getTypeAtLocation(s),o=[];for(let a of i.isUnion()?i.types:[i])if(n==="string"&&a.isStringLiteral())o.push(a.value);else if(n==="number"&&a.isNumberLiteral())o.push(a.value);else return null;return o.length>0?[...new Set(o)]:null}function Le(e,t,n){let r=O(e,t);e.warnings.has(r)||e.warnings.set(r,`${r} \u2014 ${n}`)}function gt(e,t){let n=T(e,t);return!n||e.isIdentifier(n)&&n.text==="undefined"||n.kind===e.SyntaxKind.VoidExpression}function Pe(e){let t=e.split(/[^A-Za-z0-9]+/).filter(Boolean).map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join("");return/^[A-Za-z]/.test(t)?t:`E${t}`}function Ke(e,t,n,r,s){if(st.has(t)){let c=K(e,n[0],"number"),l=K(e,n[1],"string");return!l||!c||c.length!==1?(Le(e,r,`new ${t}(status, code, \u2026) with a code or status decided at runtime cannot be typed; clients receive it as their untyped case. To type it, give the code and status literal types (or declare it with defineError)`),[]):l.map(u=>({name:s&&l.length===1?s:Pe(u),code:u,status:c[0]}))}let i=Object.prototype.hasOwnProperty.call(ue,t)?ue[t]:null;if(!i)return[];let o=[i.code];if(i.codeArg!==null&&n.length>i.codeArg&&!gt(e.ts,n[i.codeArg])&&(o=K(e,n[i.codeArg],"string"),!o))return Le(e,r,`new ${t}(\u2026) with a code decided at runtime cannot be typed; clients receive it as their untyped case. To type it, give the code a literal type (or declare it with defineError)`),[];let a=o;return a.map(c=>({name:s&&a.length===1?s:c===i.code?t:Pe(c),code:c,status:i.status}))}function me(e,t){let n=e.ts,r=t.initializer&&T(n,t.initializer);return r&&n.isCallExpression(r)&&I(e,r.expression)==="defineError"?r:null}function _e(e,t,n){let r=K(e,n.arguments[0],"string"),s=K(e,n.arguments[1],"number"),i=r&&r.length===1?r[0]:null,o=s&&s.length===1?s[0]:null;return(i===null||o===null)&&at(e,n,`defineError(...) for "${t.name.getText()}" declares a typed error, so its code and status must be known when the project is built (a literal, or a constant of literal type)`),{name:t.name.getText(),code:i,status:o}}function pt(e,t){let n=null,r=s=>{if(!(n||e.isFunctionLike(s))){if(e.isCallExpression(s)&&s.expression.kind===e.SyntaxKind.SuperKeyword){n=s;return}e.forEachChild(s,r)}};return t.body&&e.forEachChild(t.body,r),n}function Ve(e,t,n,r){let s=e.ts,i=(t.heritageClauses||[]).find(f=>f.token===s.SyntaxKind.ExtendsKeyword),o=i&&i.types[0]&&i.types[0].expression;if(!o)return[];let a=t.members.find(f=>s.isConstructorDeclaration(f)&&!!f.body),c=n,l=r;if(a){let f=pt(s,a);if(!f)return[];c=f.arguments,l=f}let u=ct(s,t),m=I(e,o);if(m)return Ke(e,m,c,l,u);let g=L(e,o);if(g&&s.isVariableDeclaration(g)){let f=me(e,g);return f?[{..._e(e,g,f),name:u||g.name.getText()}]:[]}let y=_(e,o);if(y){let f=Ve(e,y,c,l);return f.length===1&&u?[{...f[0],name:u}]:f}return[]}function St(e,t){let n=e.ts,r=t.arguments||[],s=I(e,t.expression);if(s)return Ke(e,s,r,t);let i=T(n,t.expression),o=L(e,n.isPropertyAccessExpression(i)?i.name:i);if(!o)return[];if(n.isVariableDeclaration(o)){let c=me(e,o);if(c)return[_e(e,o,c)]}let a=Oe(n,o);return a&&v(e,a)?Ve(e,a,r,t):[]}function z(e,t,n,r,s,i,o=new Set){let a=e.ts;if(t=T(a,t),!t)return;let c=`${q(e,t)}@${n.receiver?q(e,n.receiver):0}`;if(!o.has(c)){if(o.add(c),a.isNewExpression(t)){let l=O(e,t);R(e,r,s,i,St(e,t).map(u=>({...u,site:l})));return}if(a.isConditionalExpression(t)){z(e,t.whenTrue,n,r,s,i,o),z(e,t.whenFalse,n,r,s,i,o);return}if(a.isBinaryExpression(t)){let l=a.SyntaxKind,u=t.operatorToken.kind;(u===l.QuestionQuestionToken||u===l.BarBarToken)&&z(e,t.left,n,r,s,i,o),z(e,t.right,n,r,s,i,o);return}if(a.isCallExpression(t)){for(let l of ee(e,t,n))for(let u of Y(a,l.fn))z(e,u,l.ctx,r,s,i,o);return}if(a.isIdentifier(t)||a.isPropertyAccessExpression(t)){let l=L(e,a.isPropertyAccessExpression(t)?t.name:t);if(l&&(a.isVariableDeclaration(l)||a.isPropertyDeclaration(l))&&l.initializer){let u=a.isVariableDeclaration(l)?je(l,n):n;z(e,l.initializer,u,r,s,i,o)}}}}function ce(e,t){let n=e.ts;if(!n.isFunctionLike(t))return!1;if((n.getCombinedModifierFlags(t)&n.ModifierFlags.Async)!==0)return!0;let r=e.checker.getSignatureFromDeclaration(t);if(!r)return!1;let s=e.checker.getReturnTypeOfSignature(r),i=e.checker.getPromisedTypeOfPromise;return i?i.call(e.checker,s)!==void 0:e.checker.getAwaitedType(s)!==s}function yt(e,t,n){let r=null;for(let s=t.parent;s&&s!==n;s=s.parent)e.isFunctionLike(s)&&(e.getCombinedModifierFlags(s)&e.ModifierFlags.Async)!==0&&(r=s);return r}function Tt(e,t,n){for(let r=t.parent;r&&r!==n;r=r.parent)if(e.isAwaitExpression(r)||e.isForOfStatement(r)&&r.awaitModifier)return!0;return!1}function ht(e,t,n,r){for(let s=t.scopes.length-1;s>=0;s--){let i=t.scopes[s],o=yt(e.ts,n,i.node),a=r||o!==null;if(i.kind==="try"){if(!a||Tt(e.ts,o||n,i.node))return i.sink}else if(i.kind==="settle"){if(a)return null}else if(i.kind==="catch"&&a&&!i.rethrows)return null}return t.root}function bt(e){let t=e.ts;if(e.statusOf)return e.statusOf;let n=new Map;for(let[s,i]of Object.entries(ue))n.set(i.code,{status:i.status,site:`palbase/backend ${s}`});let r=s=>{if(t.isVariableDeclaration(s)&&t.isIdentifier(s.name)){let i=me(e,s),o=i&&K(e,i.arguments[0],"string"),a=i&&K(e,i.arguments[1],"number");o&&a&&o.length===1&&a.length===1&&!n.has(o[0])&&n.set(o[0],{status:a[0],site:O(e,s)})}t.forEachChild(s,r)};for(let s of e.program.getSourceFiles())$(e,s.fileName)&&r(s);return e.statusOf=n,n}function xt(e,t){let n=bt(e),r=n.get(t.code);if(!r){n.set(t.code,{status:t.status,site:t.site});return}if(r.status!==t.status)throw new b(`"${t.code}" is thrown with status ${t.status} (${t.site}) but the code carries status ${r.status} (${r.site}) \u2014 a client matches an error by its code, so one code carries one status. Throw the code's own class, or give the error its own code`)}function R(e,t,n,r,s){for(let o of s)xt(e,o);let i=ht(e,t,n,r);if(i)for(let o of s)i.has(o.code)||i.set(o.code,o)}function Ue(e,t,n){if(!n)return!1;let r=!1,s=o=>{let a=!1,c=l=>{a||(e.isIdentifier(l)&&l.text===n?a=!0:e.forEachChild(l,c))};return c(o),a},i=o=>{r||e.isFunctionLike(o)&&o!==t||(e.isThrowStatement(o)&&o.expression&&s(o.expression)?r=!0:e.forEachChild(o,i))};return i(t),r}function wt(e,t){let n=T(e,t);if(n&&(e.isArrowFunction(n)||e.isFunctionExpression(n))){let r=n.parameters[0];return r?e.isIdentifier(r.name)?e.isBlock(n.body)?Ue(e,n.body,r.name.text):!1:!0:!1}return!0}function kt(e,t,n){let r=e.ts;if(!r.isPropertyAccessExpression(t)||t.name.text!==n)return!1;let s=T(r,t.expression);if(!r.isIdentifier(s)||s.text!=="Promise")return!1;let i=L(e,s);return!i||!v(e,i)}function B(e,t,n){let r=e.ts,s=`${q(e,t)}@${n.receiver?q(e,n.receiver):0}`,i=e.summaries.get(s);if(i&&(i.final||i.round===e.round))return i.busy&&(e.cyclic=!0),i.errors;i={errors:i?new Map(i.errors):new Map,busy:!0,round:e.round,final:!1},e.summaries.set(s,i);let o=i.errors.size,a={root:i.errors,scopes:[]};if(r.isFunctionLike(t)){let c=t;for(let l of c.parameters||[])l.initializer&&D(e,l.initializer,n,a);c.body&&D(e,c.body,n,a)}else D(e,t,n,a);return i.busy=!1,i.errors.size!==o&&(e.grew=!0),i.errors}function le(e,t){return{root:e.root,scopes:[...e.scopes,t]}}function D(e,t,n,r){let s=e.ts;if(s.isTryStatement(t)){let o=new Map;D(e,t.tryBlock,n,le(r,{kind:"try",node:t.tryBlock,sink:o}));let a=t.catchClause;(!a||(a.variableDeclaration&&s.isIdentifier(a.variableDeclaration.name)?Ue(s,a.block,a.variableDeclaration.name.text):a.variableDeclaration))&&R(e,r,t,!1,[...o.values()]),a&&D(e,a.block,n,r),t.finallyBlock&&D(e,t.finallyBlock,n,r);return}if(s.isThrowStatement(t))t.expression&&z(e,t.expression,n,r,t,!1);else if(s.isCallExpression(t)){let o=T(s,t.expression);if(kt(e,o,"allSettled")){D(e,t.expression,n,r);let u=le(r,{kind:"settle",node:t});for(let m of t.arguments)D(e,m,n,u);return}let a=s.isPropertyAccessExpression(o)?o.name.text==="catch"?0:o.name.text==="then"&&t.arguments.length>1?1:-1:-1;if(a>=0){let u=o,m=wt(s,t.arguments[a]);D(e,u.expression,n,le(r,{kind:"catch",node:u.expression,rethrows:m}));for(let g of t.arguments)D(e,g,n,r);return}let c=s.isPropertyAccessExpression(o)?ot.get(o.name.text):void 0;c!==void 0&&t.arguments[c]&&z(e,t.arguments[c],n,r,t,!0);let l=dt(e,o);if(l.length>0){let u=O(e,t);R(e,r,t,!0,l.map(m=>({...m,site:u})))}for(let u of ee(e,t,n))R(e,r,t,ce(e,u.fn),[...B(e,u.fn,u.ctx).values()]);for(let u of t.arguments)for(let m of De(e,u,n))R(e,r,u,ce(e,m.fn),[...B(e,m.fn,m.ctx).values()])}else if(s.isNewExpression(t)){let o=_(e,t.expression);if(o)for(let a of Be(e,o,o))R(e,r,t,!1,[...B(e,a.fn,a.ctx).values()]);for(let a of t.arguments||[])for(let c of De(e,a,n))R(e,r,a,ce(e,c.fn),[...B(e,c.fn,c.ctx).values()])}else if(s.isPropertyAccessExpression(t)&&!(t.parent&&s.isCallExpression(t.parent)&&t.parent.expression===t)){let o=L(e,t.name);if(o&&s.isGetAccessorDeclaration(o)&&o.body&&v(e,o))for(let a of C(e,t.expression,n)){let c=U(e,a,t.name.text,!1);c&&R(e,r,t,!1,[...B(e,c.fn,{receiver:a,owner:c.owner,fn:c.fn}).values()])}}if(F(s,t))return;let i=s.isFunctionExpression(t)||s.isFunctionDeclaration(t)?{receiver:null,owner:null,fn:t}:n;s.forEachChild(t,o=>D(e,o,i,r))}function qe(e,t,n){let r=e.ts;if(n.has(t))return[];if(n.add(t),I(e,t.expression)==="Resolve")return[t];let s=[];for(let i of ee(e,t,{receiver:null,owner:null,fn:null}))for(let o of Y(r,i.fn)){let a=T(r,o);r.isCallExpression(a)&&s.push(...qe(e,a,n))}return s}function Et(e,t){let n=e.ts,r=[];for(let s of t.parameters)for(let i of n.getDecorators(s)||[]){let o=T(n,i.expression);if(n.isCallExpression(o))for(let a of qe(e,o,new Set)){let c=_(e,a.arguments[0]);if(!c)continue;let l=new Set;fe(e,ze(e,c),l);for(let u of l){let m=U(e,u,"resolve",!1);m&&r.push({fn:m.fn,ctx:{receiver:u,owner:m.owner,fn:m.fn}})}}}return r}function Ct(e){return e.charAt(0).toLowerCase()+e.slice(1)}function Nt(e,t,n){let r=new Map;for(let i of Et(e,n))for(let o of B(e,i.fn,i.ctx).values())r.has(o.code)||r.set(o.code,o);for(let i of B(e,n,{receiver:t,owner:t,fn:n}).values())r.has(i.code)||r.set(i.code,i);let s=new Map;for(let i of r.values()){let o=Ct(i.name),a=s.get(o);if(a)throw new b(`${t.name.text}.${P(e.ts,n.name)} can throw two errors named "${i.name}" \u2014 "${a.code}" (${a.site}) and "${i.code}" (${i.site}). Every client names an error case after it; give one of them its own defineError`);s.set(o,i)}return[...r.values()].map(({name:i,code:o,status:a})=>({name:i,code:o,status:a}))}function At(e,t){let n=[];for(let{cls:r,routes:s}of X(e,t)){let i={};for(let o of s)i[P(e.ts,o.name)]=Nt(e,r,o);n.push({className:r.name.text,ops:i})}return n}function Gt(e,t,n={}){let r=n.typescript??vt,s=Je(ge(e)),{options:i,ambient:o}=ke(r,s);return Dt(Ee(r,s,[Je(ge(t)),...o],i))}function Dt(e){let t=e.ts,n=Ne(e),r=$e(e),s=[],i=e.program.getSourceFiles().filter(a=>$(e,a.fileName)).sort((a,c)=>a.fileName<c.fileName?-1:a.fileName>c.fileName?1:0),o=[];for(let a of i){let c=X(e,a);if(c.length===0)continue;let l=new Map;for(let{cls:u,routes:m}of c)for(let g of m)try{l.set(`${u.name.text}.${P(t,g.name)}`,Ae(e,n,u.name.text,g))}catch(y){if(!(y instanceof b))throw y;o.push(y.message)}if(!(o.length>0))for(let{className:u,ops:m}of r.analyze(a))for(let[g,y]of Object.entries(m))s.push({file:ge(a.fileName),className:u,method:g,returns:l.get(`${u}.${g}`),throws:y})}if(o.length===1)throw new b(o[0]);if(o.length>1)throw new b(`${o.length} routes have no contract:
|
|
5
5
|
${o.map(a=>`- ${a}`).join(`
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
2
|
-
import{b as c,f as u}from"./
|
|
1
|
+
/*! palbase 0.42.0 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{b as c,f as u}from"./DS4WQJZM.js";var l={attempts:3,maxWaitSeconds:30},y=new Set([429,502,503,504]);function x(e,t=l){let r=t.sleep??h;return{async send(o){let n=p(o),a=n.body,m=!a||a.kind!=="raw"||u(a.value),f=(n.method==="GET"||n.method==="HEAD"||n.idempotent===!0)&&m;for(let i=1;;i++)try{return await e.send(n)}catch(s){if(!f||i>=t.attempts||!(s instanceof c)||n.signal?.aborted)throw s;let d=b(s,i,t.maxWaitSeconds);if(d===void 0)throw s;await r(d*1e3,n.signal)}}}}function p(e){return e.idempotent?Object.entries(e.headers??{}).some(([r,o])=>r.toLowerCase()==="idempotency-key"&&o!==void 0&&o!==null&&o!=="")?e:{...e,headers:{...e.headers,"Idempotency-Key":w()}}:e}function b(e,t,r){return y.has(e.status)||e.code==="network_error"?e.retryAfter!==void 0?e.retryAfter<=r?e.retryAfter:void 0:Math.min(.5*2**(t-1),r)*(.8+Math.random()*.4):void 0}function h(e,t){return new Promise((r,o)=>{if(t?.aborted)return o(t.reason);let n=()=>{clearTimeout(a),o(t?.reason)},a=setTimeout(()=>{t?.removeEventListener("abort",n),r()},e);t?.addEventListener("abort",n,{once:!0})})}function w(){if(typeof crypto.randomUUID=="function")return crypto.randomUUID();let e=crypto.getRandomValues(new Uint8Array(16));e[6]=e[6]&15|64,e[8]=e[8]&63|128;let t=[...e].map(r=>r.toString(16).padStart(2,"0")).join("");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}export{l as a,x as b,b as c,w as d};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
2
|
-
import{p as R,t as k,u as H}from"./
|
|
1
|
+
/*! palbase 0.42.0 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{p as R,t as k,u as H}from"./3B26HF2E.js";var N=40,V=`
|
|
3
3
|
:host{display:contents}
|
|
4
4
|
.pm-modal,.pm-full{position:fixed;inset:0;width:100%;height:100%;max-width:none;max-height:none;margin:0;border:0;background:transparent;color:inherit;overflow:hidden;display:flex;flex-direction:column}
|
|
5
5
|
.pm-modal::backdrop,.pm-full::backdrop{background:transparent}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
2
|
-
import{a as g,b}from"./
|
|
1
|
+
/*! palbase 0.42.0 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{a as g,b}from"./TUMSSUUS.js";var A=Symbol.for("palbase.data"),T=globalThis,m=T[A]??=new WeakSet;function S(t){return t instanceof Date||ArrayBuffer.isView(t)||t instanceof ArrayBuffer}function k(t){let e=[t];for(;e.length>0;){let n=e.pop();if(!(typeof n!="object"||n===null||m.has(n)||S(n))){m.add(n);for(let a of Array.isArray(n)?n:Object.values(n))e.push(a)}}return t}var l=class extends Error{status;code;requestId;retryAfter;body;op;get isNetworkError(){return this.code==="network_error"}constructor(e){super(e.message,e.cause===void 0?void 0:{cause:e.cause}),this.name="PalbaseError",this.op=e.op,this.status=e.status,this.code=e.code,this.requestId=e.requestId,this.retryAfter=e.retryAfter,this.body=e.body}};function C(t,e,n){let a=String(n);if(a===""||a==="."||a==="..")throw new l({op:t,status:0,code:"invalid_path_parameter",message:`${t}: ${e} cannot be ${a===""?"empty":JSON.stringify(a)}`});return encodeURIComponent(a)}var x=new Set(["apikey","authorization"]),q=64*1024;function W(t){let e=E(t.baseUrl),n=t.fetch??globalThis.fetch,a=t.solveProofOfWork??!0,u=async(r,o)=>{let d=v(e,r),s=new Headers;for(let[h,y]of Object.entries(r.headers??{}))y!=null&&!x.has(h.toLowerCase())&&s.set(h,String(y));for(let[h,y]of Object.entries(o))s.set(h,y);await j(r,t.credentials,s),s.has("accept")||s.set("accept","application/json");let f={method:r.method,headers:s,redirect:"manual",signal:r.signal,...r.keepalive?{keepalive:!0}:{}};r.body&&r.body.value!==void 0&&(s.set("content-type",r.body.contentType),f.body=L(r.body.kind,r.body.value),R(f.body)||(f.duplex="half"));let i;try{i=r.onUploadProgress&&t.xmlHttpRequest?await $(t.xmlHttpRequest,r.op,d,f,r.onUploadProgress):await n(d,f)}catch(h){throw r.signal?.aborted||h instanceof l?h:new l({op:r.op,status:0,code:"network_error",message:`${r.op}: the request did not reach ${e.origin}`,cause:h})}let c=r.answers[i.status]??(r.ownResponse&&i.status>=200&&i.status<300?"raw":void 0);if(c===void 0)throw i.status>=200&&i.status<300?(await i.body?.cancel(),new l({op:r.op,status:i.status,code:"undeclared_answer",message:`${r.op}: the server answered ${i.status}, which its contract does not declare; the request may have taken effect`})):await O(r.op,i);let p;switch(c){case"json":try{p=k(await i.json())}catch(h){throw new l({op:r.op,status:i.status,code:"invalid_json",message:`${r.op}: the answer is not JSON`,cause:h})}break;case"raw":p=i;break;default:await i.body?.cancel(),p=void 0}return{status:i.status,data:p,headers:i.headers}};return{async send(r){try{return await u(r,{})}catch(o){let d=a&&o instanceof l&&o.status===403?g(o.body):null,s=r.body?.value;if(!d||r.body?.kind==="raw"&&!R(s))throw o;let f=o,i;try{i=await b(d,{signal:r.signal})}catch(c){throw r.signal?.aborted?c:new l({op:r.op,status:403,code:"pow_unsolved",message:`${r.op}: ${c instanceof Error?c.message:String(c)}`,requestId:f.requestId,body:f.body,cause:c})}return u(r,i)}}}}function $(t,e,n,a,u){return new Promise((r,o)=>{let d=a.signal;if(d?.aborted)return o(d.reason);let s=new t,f=()=>s.abort();d?.addEventListener("abort",f,{once:!0});let i=c=>{d?.removeEventListener("abort",f),c()};s.open(a.method??"GET",n.href),s.responseType="arraybuffer",new Headers(a.headers).forEach((c,p)=>s.setRequestHeader(p,c)),s.upload&&(s.upload.onprogress=c=>{c.lengthComputable&&u(c.loaded,c.total)}),s.onload=()=>i(()=>{if(s.responseURL!==""&&s.responseURL!==n.href){o(new l({op:e,status:0,code:"undeclared_redirect",message:`${e}: the server redirected; the answer is another address's, and was not read`}));return}if(s.status<200||s.status>599)return o(new TypeError(`${e}: answered ${s.status}`));let c=s.status===204||s.status===205||s.status===304;r(new Response(c?null:s.response,{status:s.status,statusText:s.statusText,headers:U(s.getAllResponseHeaders())}))}),s.onerror=()=>i(()=>o(new TypeError(`${e}: the request failed`))),s.onabort=()=>i(()=>o(d?.reason??new DOMException("The request was aborted","AbortError"))),s.send(a.body)})}function U(t){let e=new Headers;for(let n of t.split(/\r?\n/)){let a=n.indexOf(":");if(!(a<=0))try{e.append(n.slice(0,a).trim(),n.slice(a+1).trim())}catch{}}return e}function E(t){let e;try{e=new URL(t)}catch{throw new TypeError(`baseUrl ${JSON.stringify(t)} is not an absolute URL`)}let n=e.hostname==="localhost"||e.hostname.endsWith(".localhost")||e.hostname==="127.0.0.1"||e.hostname==="[::1]";if(e.protocol!=="https:"&&!(e.protocol==="http:"&&n))throw new TypeError(`baseUrl must be https (http only for a loopback address): ${e.origin}`);if(e.username||e.password||e.search||e.hash)throw new TypeError("baseUrl carries no user, query or fragment");if(e.pathname!=="/"&&e.pathname!=="")throw new TypeError("baseUrl is the project origin alone, with no path");return e}function v(t,e){if(!e.path.startsWith("/")||e.path.startsWith("//"))throw new l({op:e.op,status:0,code:"invalid_path",message:`${e.op}: path ${JSON.stringify(e.path)} is not absolute`});let n=new URL(e.path+P(e.query),t);if(n.origin!==t.origin)throw new l({op:e.op,status:0,code:"invalid_path",message:`${e.op}: path leaves the project's origin`});return n}async function j(t,e,n){if(t.auth.length===0)return;let a=t.auth.some(o=>o.includes("userJWT"))?await e.accessToken?.():void 0,u=o=>{switch(o){case"ApiKeyAuth":return!!(e.publishableKey??e.secretKey);case"SecretKeyAuth":case"AdminAuth":return!!(e.secretKey??e.token);case"PalbaseBearer":return!!e.token;case"userJWT":return!!a&&!e.token;default:return!1}},r=t.auth.filter(o=>o.every(u)).reduce((o,d)=>o===void 0||d.length>o.length?d:o,void 0);if(!r)throw new l({op:t.op,status:0,code:"missing_credential",message:`${t.op} needs one of: ${t.auth.map(o=>o.length===0?"nothing":o.join(" + ")).join(" | ")}`});for(let o of r)o==="ApiKeyAuth"?n.set("apikey",e.publishableKey??e.secretKey):(o==="SecretKeyAuth"||o==="AdminAuth"||o==="PalbaseBearer")&&e.token?n.set("authorization",`Bearer ${e.token}`):o==="SecretKeyAuth"||o==="AdminAuth"?n.set("apikey",e.secretKey):o==="userJWT"&&n.set("authorization",`Bearer ${a}`)}function L(t,e){switch(t){case"json":return JSON.stringify(e);case"form":{let n=new URLSearchParams;for(let[a,u]of Object.entries(e))w(n,a,u);return n}case"raw":return e}}function R(t){return!!(t==null||typeof t=="string"||t instanceof URLSearchParams||t instanceof Blob||t instanceof FormData||t instanceof ArrayBuffer||ArrayBuffer.isView(t))}function P(t){if(!t)return"";let e=new URLSearchParams;for(let[a,u]of Object.entries(t))w(e,a,u);let n=e.toString();return n===""?"":`?${n}`}function w(t,e,n){if(n!=null){if(Array.isArray(n)){for(let a of n)w(t,e,a);return}if(n instanceof Date){t.append(e,n.toISOString());return}t.append(e,typeof n=="object"?JSON.stringify(n):String(n))}}async function O(t,e){let n=await B(e,q).catch(()=>""),a;try{a=n===""?void 0:JSON.parse(n)}catch{a=n}let u=_(a)?a:void 0,r=Number(e.headers.get("retry-after")),o=e.status>=300&&e.status<400;return new l({op:t,status:e.status,code:u?.error??(o?"undeclared_redirect":`http_${e.status}`),message:u?.error_description??(o?`${t}: the server redirected (${e.status}); the request was not followed, its credentials stay here`:`${t}: ${e.status} ${e.statusText}`.trim()),requestId:u?.request_id??e.headers.get("x-request-id")??void 0,retryAfter:u?.retry_after??(Number.isFinite(r)&&r>0?r:void 0),body:a})}async function B(t,e){if(!t.body)return"";let n=t.body.getReader(),a=[],u=0;for(;u<e;){let{done:d,value:s}=await n.read();if(d)break;a.push(s),u+=s.byteLength}await n.cancel().catch(()=>{});let r=new Uint8Array(Math.min(u,e)),o=0;for(let d of a){let s=Math.min(d.byteLength,r.byteLength-o);if(r.set(d.subarray(0,s),o),o+=s,o>=r.byteLength)break}return new TextDecoder().decode(r)}function _(t){return typeof t=="object"&&t!==null&&typeof t.error=="string"}export{k as a,l as b,C as c,W as d,E as e,R as f};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
1
|
+
/*! palbase 0.42.0 — Palbase SDK License (see LICENSE) */
|
|
2
2
|
var d=Object.defineProperty;var e=(c,a)=>{for(var b in a)d(c,b,{get:a[b],enumerable:!0})};export{e as a};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
2
|
-
import{c as D,g as b,l as O,m as _,s as F}from"./SAEDHCLG.js";import{b as w}from"./SHLEYBMA.js";var I=20,M=2048,S=256,j=/^[A-Za-z][A-Za-z0-9_.-]{0,39}$/,m=e=>new w({op:"GetPlacementPaywall",status:0,code:"invalid_attributes",message:e});function L(e){let n='"';for(let t=0;t<e.length;t++){let a=e.charCodeAt(t);a===34?n+='\\"':a===92?n+="\\\\":a>=32&&a<=126?n+=e[t]:n+=`\\u${a.toString(16).padStart(4,"0")}`}return`${n}"`}function T(e){let n=Object.keys(e??{}).sort((i,r)=>i<r?-1:i>r?1:0);if(n.length===0)return;if(n.length>I)throw m(`${n.length} attributes: at most ${I}`);let t=[];for(let i of n){if(!j.test(i))throw m(`the attribute ${JSON.stringify(i)}: a key is a letter, then letters, digits and _ . -, at most 40`);let r=e[i],s;if(typeof r=="string"){if(new TextEncoder().encode(r).length>S)throw m(`the attribute ${JSON.stringify(i)} is over ${S} bytes`);s=L(r)}else if(typeof r=="number"){if(!Number.isFinite(r))throw m(`the attribute ${JSON.stringify(i)} is no number`);s=String(Object.is(r,-0)?0:r)}else if(typeof r=="boolean")s=r?"true":"false";else throw m(`the attribute ${JSON.stringify(i)}: a value is a text, a number or a boolean`);t.push(`"${i}":${s}`)}let a=`{${t.join(",")}}`;if(a.length>M)throw m(`the attributes are ${a.length} bytes: at most ${M}`);return a}function x(e){let n=/^P(\d+)([DWMY])$/.exec(e??"");if(!n)return null;let t=Number(n[1]);if(!Number.isSafeInteger(t)||t<1)return null;switch(n[2]){case"D":return{count:t,unit:"day",months:t*12/365};case"W":return{count:t,unit:"week",months:t*12/52};case"M":return{count:t,unit:"month",months:t};default:return{count:t,unit:"year",months:t*12}}}function R(e){try{return new Intl.NumberFormat("en",{style:"currency",currency:e}).resolvedOptions().maximumFractionDigits??2}catch{return 2}}function $(e,n,t){let a=e/10**R(n);try{return new Intl.NumberFormat(t,{style:"currency",currency:n}).format(a)}catch{return`${a.toFixed(R(n))} ${n}`}}function X(e,n){try{let t=new Intl.NumberFormat(n,{style:"unit",unit:e.unit,unitDisplay:"long"});return e.count>1?t.format(e.count):t.formatToParts(1).filter(i=>i.type==="unit").map(i=>i.value).join("").trim()||t.format(1)}catch{return e.count>1?`${e.count} ${e.unit}s`:e.unit}}var K={en:e=>`${e} free`,tr:e=>`${e} \xFCcretsiz`,de:e=>`${e} kostenlos`,es:e=>`${e} gratis`,it:e=>`${e} gratis`,nl:e=>`${e} gratis`,pt:e=>`${e} gr\xE1tis`,sv:e=>`${e} gratis`,da:e=>`${e} gratis`,nb:e=>`${e} gratis`};function B(e,n){let t;try{t=new Intl.NumberFormat(n,{style:"unit",unit:e.unit,unitDisplay:"long"}).format(e.count)}catch{t=`${e.count} ${e.unit}${e.count>1?"s":""}`}let a=K[n.split("-")[0].toLowerCase()];return a?a(t):t}function H(e,n){try{return new Intl.NumberFormat(n,{style:"percent",maximumFractionDigits:0}).format(e)}catch{return`${Math.round(e*100)}%`}}function E(e,n){let t=new Map,a=new Map;for(let r of e){let s=x(r.period);if(!s)continue;let u=r.price.amount/s.months;t.set(r.key,u),a.set(r.price.currency,Math.max(a.get(r.price.currency)??0,u))}let i={};for(let r of e){let s={product_name:r.productName,price:$(r.price.amount,r.price.currency,n)},u=x(r.period);if(u){s.period=X(u,n),s.price_per_month=$(Math.round(t.get(r.key)),r.price.currency,n);let o=a.get(r.price.currency)??0,d=o>0?Math.floor((1-t.get(r.key)/o)*100)/100:0;d>=.01&&(s.savings=H(d,n))}let l=r.intro?.mode==="free_trial"?x(r.intro.duration):null;l&&(s.trial=B(l,n)),r.offer&&(s.offer_price=$(Math.floor((r.price.amount*(100-r.offer.percentOff)+50)/100),r.price.currency,n)),i[r.key]=s}return i}var V={version:"0.41.3"};var C=`palbase-js/${V.version}`;var k=class{placement;source;definition;assets;offerings;offers;shown;deps;exposed=!1;constructor(n,t,a,i,r,s,u={},l=[]){this.placement=n,this.source=t,this.definition=a,this.assets=u,this.offerings=i,this.offers=l,this.shown=r,this.deps=s}packages(n){return E(Y(this.offerings,O(this.definition),n,Z(this.definition,this.offers)),n)}render(n,t){let a=t.locale??globalThis.navigator?.language??this.definition.default_locale,i=t.appearance===void 0?q():void 0,r=this.packages(a),s=F(n,{definition:this.definition,locale:a,appearance:t.appearance??(i?.matches?"dark":"light"),platform:"web",packages:r,eligible:Object.entries(r).filter(([,o])=>o.trial).map(([o])=>o),offers:this.offers.filter(o=>o.web).map(o=>o.key),links:t.links,assets:this.assets},{onPurchase:async o=>{try{let d=await this.deps.checkout({product:o.product,plan:o.plan,successUrl:t.successUrl,cancelUrl:t.cancelUrl,...o.offer!==void 0?{offer:o.offer}:{}});t.onCheckout?t.onCheckout(d,o):globalThis.location.assign(d)}catch(d){if(!t.onError)throw d;t.onError(d,o)}},onClose:t.onClose,onLink:t.onLink,labels:t.labels}),u=o=>s.update({appearance:o.matches?"dark":"light"});i?.addEventListener?.("change",u),!this.exposed&&this.shown&&(this.exposed=!0,this.deps.expose(this));let l=s.destroy.bind(s);return s.destroy=()=>{i?.removeEventListener?.("change",u),l()},s}};function q(){try{return globalThis.matchMedia?.("(prefers-color-scheme: dark)")}catch{return}}function W(e,n){if(!e)return;let t=n.split("-")[0];return e[n]?.name??e[t]?.name??Object.values(e).find(a=>a.name)?.name}function Y(e,n,t,a=new Map){let i=[];for(let r of n){let[s,u]=r.split("."),l=e.products.find(f=>f.key===s),o=l?.channels.web,d=o?.plans.find(f=>f.key===u);if(!l||!o||!d)continue;let p=a.get(r),g=p?.discount?p.discount.percent:p?.trial?100:void 0;i.push({key:r,productName:W(o.locales,t)??l.key,price:{amount:d.price.amount,currency:d.price.currency},period:d.period,intro:d.intro,...g!==void 0?{offer:{percentOff:g}}:{}})}return i}function Z(e,n){let t=new Map;for(let[a,i]of _(e)){let r=n.find(s=>s.key===i);r?.web&&t.set(a,r)}return t}var G={en:{cta:"Continue",terms:"Terms",privacy:"Privacy"},tr:{cta:"Devam et",terms:"Ko\u015Fullar",privacy:"Gizlilik"},de:{cta:"Weiter",terms:"Bedingungen",privacy:"Datenschutz"},es:{cta:"Continuar",terms:"T\xE9rminos",privacy:"Privacidad"},fr:{cta:"Continuer",terms:"Conditions",privacy:"Confidentialit\xE9"},it:{cta:"Continua",terms:"Termini",privacy:"Privacy"},pt:{cta:"Continuar",terms:"Termos",privacy:"Privacidade"},nl:{cta:"Doorgaan",terms:"Voorwaarden",privacy:"Privacy"},ja:{cta:"\u7D9A\u3051\u308B",terms:"\u5229\u7528\u898F\u7D04",privacy:"\u30D7\u30E9\u30A4\u30D0\u30B7\u30FC"}},N=e=>({type:"button",action:{type:e},content:{type:"text",text:{t:e},size:"caption",color:"muted"}});function Q(e){let n=e.products.flatMap(t=>(t.channels.web?.plans??[]).map(a=>({product:t.key,plan:a.key}))).slice(0,6);return n.length===0?null:{schema:2,name:"Default",default_locale:"en",locales:G,theme:{colors:{light:{background:"#FFFFFF",surface:"#F2F2F7",text:"#111114",muted:"#6B6B70",accent:"#111114",on_accent:"#FFFFFF",stroke:"#E5E5EA"},dark:{background:"#000000",surface:"#1C1C1E",text:"#F5F5F7",muted:"#9A9AA0",accent:"#F5F5F7",on_accent:"#000000",stroke:"#2C2C2E"}},typography:{headline:{size:17,weight:600,text_style:"headline"},caption:{size:13,weight:400,text_style:"footnote"}},radii:{card:14},spacing:{sm:8,md:16,lg:24}},root:{type:"stack",spacing:"md",align:"stretch",style:{padding:"lg"},children:[{type:"stack",axis:"horizontal",children:[{type:"spacer"},{type:"button",action:{type:"close"},content:{type:"icon",name:"close",color:"muted",size:22}}]},{type:"spacer"},{type:"stack",spacing:"sm",align:"stretch",children:n.map(({product:t,plan:a})=>({type:"package",product:t,plan:a,style:{padding:"md",corners:"card",background:"surface",border:{width:1,color:"stroke"}},states:{selected:{border:{width:2,color:"accent"}}},children:[{type:"stack",axis:"horizontal",spacing:"sm",children:[{type:"stack",align:"start",spacing:2,children:[{type:"text",text:"{{product_name}}",size:"headline",align:"start"},{type:"text",text:"{{period}}",size:"caption",color:"muted",align:"start"}]},{type:"spacer"},{type:"text",text:"{{price}}",size:"headline"}]}]}))},{type:"purchase_button",style:{padding:"md",corners:"card",background:"accent"},content:{type:"text",text:{t:"cta"},size:"headline",color:"on_accent"}},{type:"stack",axis:"horizontal",spacing:"md",distribution:"center",children:[N("terms"),N("privacy")]}]}}}function h(){try{return globalThis.localStorage}catch{return}}function ee(e){try{let n=h()?.getItem(e);if(!n)return;let t=JSON.parse(n),a=t?.answer;return typeof a!="object"||a===null||typeof a.paywall_id!="string"||typeof a.version!="number"||typeof a.definition!="object"||a.definition===null||typeof a.offerings!="object"||a.definition.schema!==2?void 0:{etag:typeof t.etag=="string"?t.etag:void 0,answer:a}}catch{return}}function P(e,n){try{n?h()?.setItem(e,JSON.stringify(n)):h()?.removeItem(e)}catch{}}var z=()=>globalThis.crypto?.randomUUID?globalThis.crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,U;function te(e){let n=`palbase.installation.${e}`;try{let t=h()?.getItem(n);if(t&&/^[A-Za-z0-9._:-]{1,128}$/.test(t))return t;let a=z();if(h()?.setItem(n,a),h()?.getItem(n)===a)return a}catch{}return U??=z(),U}async function ye(e,n,t,a,i={}){let{signal:r,fetch:s}=i,u=T(i.attributes),l=`palbase.paywall.${n}.${t}`,o=te(n),p={checkout:a,expose:async c=>{if(c.shown)try{let v={paywall_id:c.shown.paywallId,version:c.shown.version,...c.shown.variant!==void 0?{variant:c.shown.variant}:{},...c.shown.ruleId!==void 0?{rule_id:c.shown.ruleId}:{}};await e.recordPaywallExposure({path:{placement:t},headers:{"X-Palbase-Installation":o},body:v})}catch{}}},g=async(c,v)=>new k(t,v,c.definition,c.offerings,{paywallId:c.paywall_id,version:c.version,...c.variant!==void 0?{variant:c.variant}:{},...c.rule_id!==void 0?{ruleId:c.rule_id}:{}},p,await D(c.assets??[],{signal:r,...s?{fetch:s}:{}}),c.offers??[]),f=ee(l),y;try{y=await e.getPlacementPaywall({path:{placement:t},query:{channel:"web"},headers:{"X-Palbase-Paywall-Schema":2,"X-Palbase-Installation":o,"X-Platform":"web","X-Palbase-SDK":C,...i.appVersion?{"X-Palbase-Client-Version":i.appVersion}:{},...i.app?{"X-Palbase-App":i.app}:{},...i.locale?{"Accept-Language":i.locale}:{},...u!==void 0?{"X-Palbase-Attributes":u}:{},...f?.etag?{"If-None-Match":f.etag}:{}},signal:r})}catch(c){if(c instanceof w&&c.status===404||c instanceof w&&c.status===400&&c.code.startsWith("invalid_"))return P(l,void 0),A(e,t,p,r);if(f&&!r?.aborted)return g(f.answer,"cache");throw c}return y.status===200?(P(l,{etag:y.headers.get("etag")??void 0,answer:y.data}),g(y.data,"server")):y.status===304&&f?g(f.answer,"server"):(P(l,void 0),A(e,t,p,r))}async function A(e,n,t,a){let i=(await e.getOfferings({query:{channel:"web"},signal:a})).data,r=Q(i);return r?new k(n,"default",r,i,void 0,t):null}export{T as a,x as b,$ as c,X as d,E as e,k as f,Q as g,ye as h};
|
|
1
|
+
/*! palbase 0.42.0 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{c as D,g as b,l as O,m as _,s as F}from"./3B26HF2E.js";import{b as w}from"./DS4WQJZM.js";var I=20,M=2048,S=256,j=/^[A-Za-z][A-Za-z0-9_.-]{0,39}$/,m=e=>new w({op:"GetPlacementPaywall",status:0,code:"invalid_attributes",message:e});function L(e){let n='"';for(let t=0;t<e.length;t++){let a=e.charCodeAt(t);a===34?n+='\\"':a===92?n+="\\\\":a>=32&&a<=126?n+=e[t]:n+=`\\u${a.toString(16).padStart(4,"0")}`}return`${n}"`}function T(e){let n=Object.keys(e??{}).sort((i,r)=>i<r?-1:i>r?1:0);if(n.length===0)return;if(n.length>I)throw m(`${n.length} attributes: at most ${I}`);let t=[];for(let i of n){if(!j.test(i))throw m(`the attribute ${JSON.stringify(i)}: a key is a letter, then letters, digits and _ . -, at most 40`);let r=e[i],s;if(typeof r=="string"){if(new TextEncoder().encode(r).length>S)throw m(`the attribute ${JSON.stringify(i)} is over ${S} bytes`);s=L(r)}else if(typeof r=="number"){if(!Number.isFinite(r))throw m(`the attribute ${JSON.stringify(i)} is no number`);s=String(Object.is(r,-0)?0:r)}else if(typeof r=="boolean")s=r?"true":"false";else throw m(`the attribute ${JSON.stringify(i)}: a value is a text, a number or a boolean`);t.push(`"${i}":${s}`)}let a=`{${t.join(",")}}`;if(a.length>M)throw m(`the attributes are ${a.length} bytes: at most ${M}`);return a}function x(e){let n=/^P(\d+)([DWMY])$/.exec(e??"");if(!n)return null;let t=Number(n[1]);if(!Number.isSafeInteger(t)||t<1)return null;switch(n[2]){case"D":return{count:t,unit:"day",months:t*12/365};case"W":return{count:t,unit:"week",months:t*12/52};case"M":return{count:t,unit:"month",months:t};default:return{count:t,unit:"year",months:t*12}}}function R(e){try{return new Intl.NumberFormat("en",{style:"currency",currency:e}).resolvedOptions().maximumFractionDigits??2}catch{return 2}}function $(e,n,t){let a=e/10**R(n);try{return new Intl.NumberFormat(t,{style:"currency",currency:n}).format(a)}catch{return`${a.toFixed(R(n))} ${n}`}}function X(e,n){try{let t=new Intl.NumberFormat(n,{style:"unit",unit:e.unit,unitDisplay:"long"});return e.count>1?t.format(e.count):t.formatToParts(1).filter(i=>i.type==="unit").map(i=>i.value).join("").trim()||t.format(1)}catch{return e.count>1?`${e.count} ${e.unit}s`:e.unit}}var K={en:e=>`${e} free`,tr:e=>`${e} \xFCcretsiz`,de:e=>`${e} kostenlos`,es:e=>`${e} gratis`,it:e=>`${e} gratis`,nl:e=>`${e} gratis`,pt:e=>`${e} gr\xE1tis`,sv:e=>`${e} gratis`,da:e=>`${e} gratis`,nb:e=>`${e} gratis`};function B(e,n){let t;try{t=new Intl.NumberFormat(n,{style:"unit",unit:e.unit,unitDisplay:"long"}).format(e.count)}catch{t=`${e.count} ${e.unit}${e.count>1?"s":""}`}let a=K[n.split("-")[0].toLowerCase()];return a?a(t):t}function H(e,n){try{return new Intl.NumberFormat(n,{style:"percent",maximumFractionDigits:0}).format(e)}catch{return`${Math.round(e*100)}%`}}function E(e,n){let t=new Map,a=new Map;for(let r of e){let s=x(r.period);if(!s)continue;let u=r.price.amount/s.months;t.set(r.key,u),a.set(r.price.currency,Math.max(a.get(r.price.currency)??0,u))}let i={};for(let r of e){let s={product_name:r.productName,price:$(r.price.amount,r.price.currency,n)},u=x(r.period);if(u){s.period=X(u,n),s.price_per_month=$(Math.round(t.get(r.key)),r.price.currency,n);let o=a.get(r.price.currency)??0,d=o>0?Math.floor((1-t.get(r.key)/o)*100)/100:0;d>=.01&&(s.savings=H(d,n))}let l=r.intro?.mode==="free_trial"?x(r.intro.duration):null;l&&(s.trial=B(l,n)),r.offer&&(s.offer_price=$(Math.floor((r.price.amount*(100-r.offer.percentOff)+50)/100),r.price.currency,n)),i[r.key]=s}return i}var V={version:"0.42.0"};var C=`palbase-js/${V.version}`;var k=class{placement;source;definition;assets;offerings;offers;shown;deps;exposed=!1;constructor(n,t,a,i,r,s,u={},l=[]){this.placement=n,this.source=t,this.definition=a,this.assets=u,this.offerings=i,this.offers=l,this.shown=r,this.deps=s}packages(n){return E(Y(this.offerings,O(this.definition),n,Z(this.definition,this.offers)),n)}render(n,t){let a=t.locale??globalThis.navigator?.language??this.definition.default_locale,i=t.appearance===void 0?q():void 0,r=this.packages(a),s=F(n,{definition:this.definition,locale:a,appearance:t.appearance??(i?.matches?"dark":"light"),platform:"web",packages:r,eligible:Object.entries(r).filter(([,o])=>o.trial).map(([o])=>o),offers:this.offers.filter(o=>o.web).map(o=>o.key),links:t.links,assets:this.assets},{onPurchase:async o=>{try{let d=await this.deps.checkout({product:o.product,plan:o.plan,successUrl:t.successUrl,cancelUrl:t.cancelUrl,...o.offer!==void 0?{offer:o.offer}:{}});t.onCheckout?t.onCheckout(d,o):globalThis.location.assign(d)}catch(d){if(!t.onError)throw d;t.onError(d,o)}},onClose:t.onClose,onLink:t.onLink,labels:t.labels}),u=o=>s.update({appearance:o.matches?"dark":"light"});i?.addEventListener?.("change",u),!this.exposed&&this.shown&&(this.exposed=!0,this.deps.expose(this));let l=s.destroy.bind(s);return s.destroy=()=>{i?.removeEventListener?.("change",u),l()},s}};function q(){try{return globalThis.matchMedia?.("(prefers-color-scheme: dark)")}catch{return}}function W(e,n){if(!e)return;let t=n.split("-")[0];return e[n]?.name??e[t]?.name??Object.values(e).find(a=>a.name)?.name}function Y(e,n,t,a=new Map){let i=[];for(let r of n){let[s,u]=r.split("."),l=e.products.find(f=>f.key===s),o=l?.channels.web,d=o?.plans.find(f=>f.key===u);if(!l||!o||!d)continue;let p=a.get(r),g=p?.discount?p.discount.percent:p?.trial?100:void 0;i.push({key:r,productName:W(o.locales,t)??l.key,price:{amount:d.price.amount,currency:d.price.currency},period:d.period,intro:d.intro,...g!==void 0?{offer:{percentOff:g}}:{}})}return i}function Z(e,n){let t=new Map;for(let[a,i]of _(e)){let r=n.find(s=>s.key===i);r?.web&&t.set(a,r)}return t}var G={en:{cta:"Continue",terms:"Terms",privacy:"Privacy"},tr:{cta:"Devam et",terms:"Ko\u015Fullar",privacy:"Gizlilik"},de:{cta:"Weiter",terms:"Bedingungen",privacy:"Datenschutz"},es:{cta:"Continuar",terms:"T\xE9rminos",privacy:"Privacidad"},fr:{cta:"Continuer",terms:"Conditions",privacy:"Confidentialit\xE9"},it:{cta:"Continua",terms:"Termini",privacy:"Privacy"},pt:{cta:"Continuar",terms:"Termos",privacy:"Privacidade"},nl:{cta:"Doorgaan",terms:"Voorwaarden",privacy:"Privacy"},ja:{cta:"\u7D9A\u3051\u308B",terms:"\u5229\u7528\u898F\u7D04",privacy:"\u30D7\u30E9\u30A4\u30D0\u30B7\u30FC"}},N=e=>({type:"button",action:{type:e},content:{type:"text",text:{t:e},size:"caption",color:"muted"}});function Q(e){let n=e.products.flatMap(t=>(t.channels.web?.plans??[]).map(a=>({product:t.key,plan:a.key}))).slice(0,6);return n.length===0?null:{schema:2,name:"Default",default_locale:"en",locales:G,theme:{colors:{light:{background:"#FFFFFF",surface:"#F2F2F7",text:"#111114",muted:"#6B6B70",accent:"#111114",on_accent:"#FFFFFF",stroke:"#E5E5EA"},dark:{background:"#000000",surface:"#1C1C1E",text:"#F5F5F7",muted:"#9A9AA0",accent:"#F5F5F7",on_accent:"#000000",stroke:"#2C2C2E"}},typography:{headline:{size:17,weight:600,text_style:"headline"},caption:{size:13,weight:400,text_style:"footnote"}},radii:{card:14},spacing:{sm:8,md:16,lg:24}},root:{type:"stack",spacing:"md",align:"stretch",style:{padding:"lg"},children:[{type:"stack",axis:"horizontal",children:[{type:"spacer"},{type:"button",action:{type:"close"},content:{type:"icon",name:"close",color:"muted",size:22}}]},{type:"spacer"},{type:"stack",spacing:"sm",align:"stretch",children:n.map(({product:t,plan:a})=>({type:"package",product:t,plan:a,style:{padding:"md",corners:"card",background:"surface",border:{width:1,color:"stroke"}},states:{selected:{border:{width:2,color:"accent"}}},children:[{type:"stack",axis:"horizontal",spacing:"sm",children:[{type:"stack",align:"start",spacing:2,children:[{type:"text",text:"{{product_name}}",size:"headline",align:"start"},{type:"text",text:"{{period}}",size:"caption",color:"muted",align:"start"}]},{type:"spacer"},{type:"text",text:"{{price}}",size:"headline"}]}]}))},{type:"purchase_button",style:{padding:"md",corners:"card",background:"accent"},content:{type:"text",text:{t:"cta"},size:"headline",color:"on_accent"}},{type:"stack",axis:"horizontal",spacing:"md",distribution:"center",children:[N("terms"),N("privacy")]}]}}}function h(){try{return globalThis.localStorage}catch{return}}function ee(e){try{let n=h()?.getItem(e);if(!n)return;let t=JSON.parse(n),a=t?.answer;return typeof a!="object"||a===null||typeof a.paywall_id!="string"||typeof a.version!="number"||typeof a.definition!="object"||a.definition===null||typeof a.offerings!="object"||a.definition.schema!==2?void 0:{etag:typeof t.etag=="string"?t.etag:void 0,answer:a}}catch{return}}function P(e,n){try{n?h()?.setItem(e,JSON.stringify(n)):h()?.removeItem(e)}catch{}}var z=()=>globalThis.crypto?.randomUUID?globalThis.crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,U;function te(e){let n=`palbase.installation.${e}`;try{let t=h()?.getItem(n);if(t&&/^[A-Za-z0-9._:-]{1,128}$/.test(t))return t;let a=z();if(h()?.setItem(n,a),h()?.getItem(n)===a)return a}catch{}return U??=z(),U}async function ye(e,n,t,a,i={}){let{signal:r,fetch:s}=i,u=T(i.attributes),l=`palbase.paywall.${n}.${t}`,o=te(n),p={checkout:a,expose:async c=>{if(c.shown)try{let v={paywall_id:c.shown.paywallId,version:c.shown.version,...c.shown.variant!==void 0?{variant:c.shown.variant}:{},...c.shown.ruleId!==void 0?{rule_id:c.shown.ruleId}:{}};await e.recordPaywallExposure({path:{placement:t},headers:{"X-Palbase-Installation":o},body:v})}catch{}}},g=async(c,v)=>new k(t,v,c.definition,c.offerings,{paywallId:c.paywall_id,version:c.version,...c.variant!==void 0?{variant:c.variant}:{},...c.rule_id!==void 0?{ruleId:c.rule_id}:{}},p,await D(c.assets??[],{signal:r,...s?{fetch:s}:{}}),c.offers??[]),f=ee(l),y;try{y=await e.getPlacementPaywall({path:{placement:t},query:{channel:"web"},headers:{"X-Palbase-Paywall-Schema":2,"X-Palbase-Installation":o,"X-Platform":"web","X-Palbase-SDK":C,...i.appVersion?{"X-Palbase-Client-Version":i.appVersion}:{},...i.app?{"X-Palbase-App":i.app}:{},...i.locale?{"Accept-Language":i.locale}:{},...u!==void 0?{"X-Palbase-Attributes":u}:{},...f?.etag?{"If-None-Match":f.etag}:{}},signal:r})}catch(c){if(c instanceof w&&c.status===404||c instanceof w&&c.status===400&&c.code.startsWith("invalid_"))return P(l,void 0),A(e,t,p,r);if(f&&!r?.aborted)return g(f.answer,"cache");throw c}return y.status===200?(P(l,{etag:y.headers.get("etag")??void 0,answer:y.data}),g(y.data,"server")):y.status===304&&f?g(f.answer,"server"):(P(l,void 0),A(e,t,p,r))}async function A(e,n,t,a){let i=(await e.getOfferings({query:{channel:"web"},signal:a})).data,r=Q(i);return r?new k(n,"default",r,i,void 0,t):null}export{T as a,x as b,$ as c,X as d,E as e,k as f,Q as g,ye as h};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
2
|
-
import{b as d,m as k}from"./
|
|
1
|
+
/*! palbase 0.42.0 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{b as d,m as k}from"./OYA6Z4VI.js";function S(n){let o=n.meta;if(typeof o!="function")throw new TypeError("encrypted() takes a zod schema: z.string(), z.number(), z.object(\u2026)");return o.call(n,{[d]:!0})}var p=class{value;constructor(o){this.value=o}toJSON(){throw new TypeError("an encrypt() value is sealed by the engine, in a route's answer: it is never JSON of its own")}},m=0;function $(n){if(n===void 0)throw new TypeError("encrypt() takes a JSON value: undefined is none");if(n instanceof p)throw new TypeError("encrypt() of an encrypt() value: one is enough");return m++,new p(n)}function j(){return m}function O(n){let o=[],s=new Set,f=(t,a)=>{if(t instanceof p){if(o.push(a),g(t.value,new Set))throw new TypeError(`${a}: an encrypt() value holds another \u2014 encrypt the whole, or its parts`);return t.value}if(typeof t!="object"||t===null||s.has(t))return t;if(Array.isArray(t)){s.add(t);let r=t.map((c,e)=>f(c,`${a}/${e}`));return s.delete(t),r}let y=Object.getPrototypeOf(t);if(y!==Object.prototype&&y!==null)return t;s.add(t);let i={};for(let[r,c]of Object.entries(t))i[r]=f(c,`${a}/${k(r)}`);return s.delete(t),i};return{value:f(n,"/response"),pointers:o}}function g(n,o){return n instanceof p?!0:typeof n!="object"||n===null||o.has(n)?!1:(o.add(n),Object.values(n).some(s=>g(s,o)))}function v(n,o,s){let f=new Set,l=n,t=l?.$defs??{},a=(i,r,c)=>{if(typeof i!="object"||i===null)return;let e=i;if(typeof e.$ref=="string"){if(c.has(e.$ref))return;let u=new Set(c).add(e.$ref);e.$ref==="#"?a(l,r,u):e.$ref.startsWith("#/$defs/")&&a(t[e.$ref.slice(8)],r,u)}if(e[d]===!0){f.add(r);return}for(let u of["anyOf","oneOf","allOf"])if(Array.isArray(e[u]))for(let w of e[u])a(w,r,c);if(typeof e.properties=="object"&&e.properties!==null)for(let[u,w]of Object.entries(e.properties))a(w,`${r}/${k(u)}`,c);typeof e.items=="object"&&e.items!==null&&a(e.items,`${r}/*`,c);for(let u of["additionalProperties","patternProperties","prefixItems"])if(e[u]!==void 0&&y(e[u]))throw new TypeError(`${s}: an encrypted field is a named property \u2014 not every key of a record, nor a tuple's place`)},y=i=>{if(h(i))return!0;let r=typeof i=="object"&&i!==null?i.$ref:void 0;return typeof r=="string"&&h(r==="#"?l:t[r.slice(8)])};return a(n,o,new Set),[...f]}function T(n){let s=n["~standard"].jsonSchema?.input;if(typeof s!="function")return{};try{return s({target:"draft-2020-12",libraryOptions:{unrepresentable:"any"}})}catch{return{}}}function h(n){return JSON.stringify(n??null).includes(`"${d}":true`)}export{S as a,$ as b,j as c,O as d,v as e,T as f,h as g};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
2
|
-
import{b}from"./
|
|
1
|
+
/*! palbase 0.42.0 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{b}from"./POCZ4Q2I.js";import{a as k,b as A}from"./TUMSSUUS.js";import{randomBytes as _}from"node:crypto";async function N(){let n={keys:[{id:"k1",key:_(32).toString("base64url"),activates_at:new Date(0).toISOString()}],lookup:_(32).toString("base64url")},e=new b({fetch:async()=>n});return await e.load(),e.close(),e}var f=class extends Error{status;error;data;body;constructor(e,a,l,d){let u=d!==null&&typeof d=="object"?d:{},o=u.error??String(l);super(`${e} ${a} \u2192 ${l} ${o}${u.error_description?`: ${u.error_description}`:""}`),this.name="TestApiError",this.status=l,this.error=o,this.data=u.data,this.body=u}};function x(n,e){if(!n)throw new Error(`${e} is not set: the test client has nowhere to send its requests \u2014 \`palbase test\` sets it, as the platform's test run does`);return n}function B(n){let e=n.split(".")[1];if(!e)return null;try{let a=JSON.parse(Buffer.from(e,"base64url").toString("utf8"));return typeof a.exp=="number"?a.exp-Math.floor(Date.now()/1e3):null}catch{return null}}function L(n){try{return JSON.parse(n)}catch{return n}}function $(n){let e=x(n.baseUrl,"PALBASE_TEST_BASE_URL").replace(/\/+$/,""),a=n.apiKey||void 0,l=(n.authUrl??e).replace(/\/+$/,""),d=n.fetch??fetch,u=[],o=null;async function c(r,t,s,i,T={},O=!0){let g={...T.headers},m=h=>Object.keys(g).some(R=>R.toLowerCase()===h);a!==void 0&&!m("apikey")&&(g.apikey=a),o&&O&&!m("authorization")&&(g.authorization=`Bearer ${o}`),i!==void 0&&!m("content-type")&&(g["content-type"]="application/json");let I=Date.now(),p=await d(`${r}${s}`,{method:t,headers:g,body:i===void 0?void 0:JSON.stringify(i)}),E=await p.text(),S=E?L(E):void 0;if(u.push({method:t,path:s,status:p.status,ms:Date.now()-I}),!p.ok){let h=p.status===401&&o?B(o):null;throw h!==null&&h<=0?new f(t,s,p.status,{error:"access_token_expired",error_description:`this run's access token expired ${-h}s ago: a test user's token is made for one run \u2014 run the tests again (\`palbase test\` makes new ones)`}):new f(t,s,p.status,S)}return S}let y={requests:u,get:(r,t)=>c(e,"GET",r,void 0,t),post:(r,t,s)=>c(e,"POST",r,t,s),patch:(r,t,s)=>c(e,"PATCH",r,t,s),put:(r,t,s)=>c(e,"PUT",r,t,s),delete:(r,t)=>c(e,"DELETE",r,void 0,t),query:(r,t,s)=>c(e,"QUERY",r,t,s),async signInAs(r){let t=n.identities?.[r];if(!t){let s=Object.keys(n.identities??{});throw s.length===0?new Error(`no test user named ${JSON.stringify(r)}: this run has no test users \u2014 none were named (the machine's test users, or \`palbase test --users <names>\`), or they could not be made: the run's log says which`):new Error(`no test user named ${JSON.stringify(r)} \u2014 this run has: ${s.join(", ")}. A run makes the test users its machine names (palbase machines:update <machine> --test-users <names>) or \`palbase test --users <names>\` names`)}return t.accessToken?(o=t.accessToken,{id:t.id??"",email:t.email}):y.signIn(t)},async signIn(r){if(a===void 0)throw new Error("PALBASE_TEST_API_KEY is not set: a sign-in at the project's auth is made with a publishable key of the project's (palbase apps:sdkconfig shows one) \u2014 a run's test users come with their tokens: api.signInAs(name)");let t=i=>c(l,"POST","/auth/login",r,i?{headers:i}:{},!1),s;try{s=await t()}catch(i){let T=i instanceof f&&i.status===403?k(i.body):null;if(!T)throw i;s=await t(await A(T))}return o=s.access_token,s.user??{id:""}},async signOut(){await c(l,"POST","/auth/logout",void 0),o=null},asAnonymous(){o=null}};return y}function P(n){if(!n)return{};let e;try{e=JSON.parse(n)}catch{throw new Error("PALBASE_TEST_IDENTITIES is set but is not JSON: the run that started these tests handed over a broken set of test users")}if(e===null||typeof e!="object"||Array.isArray(e))throw new Error("PALBASE_TEST_IDENTITIES is not an object of test users by name");return e}var j={get stack(){return!!process.env.PALBASE_TEST_BASE_URL},minted(n){return Object.prototype.hasOwnProperty.call(P(process.env.PALBASE_TEST_IDENTITIES),n)}},w,q=new Proxy({},{get(n,e){return w??=$({baseUrl:process.env.PALBASE_TEST_BASE_URL??"",apiKey:process.env.PALBASE_TEST_API_KEY??"",authUrl:process.env.PALBASE_TEST_AUTH_URL,identities:P(process.env.PALBASE_TEST_IDENTITIES)}),Reflect.get(w,e,w)}});export{N as a,f as b,$ as c,j as d,q as e};
|