palbase 0.73.0 → 0.73.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/README.md +1 -1
  2. package/dist/ai/index.js +2 -2
  3. package/dist/ai-sdk/index.js +2 -2
  4. package/dist/backend/engine.js +2 -2
  5. package/dist/backend/env.js +1 -1
  6. package/dist/backend/index.js +3 -3
  7. package/dist/backend/stack.js +1 -1
  8. package/dist/backend/test.js +2 -2
  9. package/dist/chunks/{DIQMCEMJ.js → 2TKZTIMD.js} +2 -2
  10. package/dist/chunks/{YMIK6HLK.js → 3KCV4F4F.js} +2 -2
  11. package/dist/chunks/{PAQCJT7M.js → 4E4ABCSD.js} +2 -2
  12. package/dist/chunks/{IICQMY2Z.js → 5N5GHLUU.js} +2 -2
  13. package/dist/chunks/{EKOEK6LR.js → 5N6QKGPA.js} +2 -2
  14. package/dist/chunks/{MVKZWEHL.js → AXANFT2A.js} +2 -2
  15. package/dist/chunks/{P36C47FS.js → DNSLYLU6.js} +1 -1
  16. package/dist/chunks/{3DUDNEMM.js → GTKPHG5F.js} +2 -2
  17. package/dist/chunks/{757A6AR6.js → GWWU2FJ7.js} +2 -2
  18. package/dist/chunks/{PEQZDT6P.js → HRWVZ4PC.js} +2 -2
  19. package/dist/chunks/{LCDNCPQW.js → HYPCFC4K.js} +1 -1
  20. package/dist/chunks/{P4NZ4NZD.js → IVJOWYRE.js} +2 -2
  21. package/dist/chunks/{5OOA4R4H.js → MB7MHOQO.js} +1 -1
  22. package/dist/chunks/{VEL7X2G3.js → MFSC4OJV.js} +2 -2
  23. package/dist/chunks/{76W5ZO2L.js → SEICTPQP.js} +2 -2
  24. package/dist/chunks/{JG4V6LNY.js → SQNAPFXW.js} +2 -2
  25. package/dist/chunks/{4XSSQAES.js → SS2RVI27.js} +1 -1
  26. package/dist/chunks/{UFP6GLLW.js → TR2IPX2A.js} +2 -2
  27. package/dist/chunks/{25HECIZY.js → U3H6HER3.js} +1 -1
  28. package/dist/chunks/{SRN7N2WX.js → UOJVMV42.js} +2 -2
  29. package/dist/chunks/{SMECWMF7.js → UXHNXE3J.js} +2 -2
  30. package/dist/chunks/{CY6KUFZW.js → VCL3SAQL.js} +2 -2
  31. package/dist/chunks/{J7ZNBBRN.js → W2KD2I4Q.js} +1 -1
  32. package/dist/chunks/{J7Z2PYL4.js → YU3GFTZV.js} +1 -1
  33. package/dist/cli.js +8 -8
  34. package/dist/cloud/index.js +2 -2
  35. package/dist/refuse/ai-sdk.js +1 -1
  36. package/dist/refuse/ai.js +1 -1
  37. package/dist/refuse/backend.js +1 -1
  38. package/dist/refuse/cloud.js +1 -1
  39. package/dist/refuse/server.js +1 -1
  40. package/dist/server/index.js +2 -2
  41. package/dist/server/testing.js +2 -2
  42. package/dist/web/index.js +2 -2
  43. package/dist/web/message.js +2 -2
  44. package/dist/web/palbe.js +2 -2
  45. package/dist/web/payments-ui.js +2 -2
  46. package/dist/web/paywall.js +2 -2
  47. package/dist/web/push-sw.js +1 -1
  48. package/dist/web/ssr.js +2 -2
  49. package/dist/web/vite.js +2 -2
  50. package/package.json +2 -2
package/README.md CHANGED
@@ -83,7 +83,7 @@ import { PalbaseCloud } from "palbase/cloud";
83
83
 
84
84
  const cloud = new PalbaseCloud({ token: process.env.PALBASE_TOKEN }); // an access token, pbo_…, pbe_… or an account token, pbu_…
85
85
 
86
- await cloud.billing.steer({ path: { id: org, ref }, body: { plan: "pay_as_you_go" } }); // charged monthly, to the payment account that pays for the org
86
+ await cloud.billing.steer({ path: { id: org, project }, body: { plan: "pay_as_you_go" } }); // charged monthly, to the payment account that pays for the org
87
87
  const { data } = await cloud.project(ref).auth.adminListUsers({ query: { limit: 50 } });
88
88
  ```
89
89
 
package/dist/ai/index.js CHANGED
@@ -1,2 +1,2 @@
1
- /*! palbase 0.73.0 — Palbase SDK License (see LICENSE) */
2
- import{a,b,c,d,e,f,g}from"../chunks/CY6KUFZW.js";import"../chunks/VEL7X2G3.js";import"../chunks/25HECIZY.js";import"../chunks/SMECWMF7.js";import"../chunks/YMIK6HLK.js";import"../chunks/PEQZDT6P.js";import"../chunks/J7ZNBBRN.js";import"../chunks/P36C47FS.js";export{f as AIResponseError,b as AISchemaError,d as ToolError,e as WorkflowParkedError,g as createAI,a as partial,c as prepare};
1
+ /*! palbase 0.73.1 — Palbase SDK License (see LICENSE) */
2
+ import{a,b,c,d,e,f,g}from"../chunks/VCL3SAQL.js";import"../chunks/MFSC4OJV.js";import"../chunks/U3H6HER3.js";import"../chunks/UXHNXE3J.js";import"../chunks/3KCV4F4F.js";import"../chunks/HRWVZ4PC.js";import"../chunks/W2KD2I4Q.js";import"../chunks/DNSLYLU6.js";export{f as AIResponseError,b as AISchemaError,d as ToolError,e as WorkflowParkedError,g as createAI,a as partial,c as prepare};
@@ -1,4 +1,4 @@
1
- /*! palbase 0.73.0 — Palbase SDK License (see LICENSE) */
2
- import"../chunks/P36C47FS.js";function M(s){return typeof process<"u"&&process.env?process.env[s]??"":""}function j(s){let a=(s??M("PALBASE_URL")).trim().replace(/\/+$/,"");if(!a)throw new Error("@palbase/ai-sdk: url or PALBASE_URL is required");return a.endsWith("/ai/v1")?a:`${a}/ai/v1`}function N(s){let a=(s??M("PALBASE_SECRET_KEY")).trim();if(!a)throw new Error("@palbase/ai-sdk: apiKey or PALBASE_SECRET_KEY is required");return a}function x(s,a,t){let u={apikey:s,Authorization:`Bearer ${s}`,"Content-Type":"application/json",...a};return t?.sessionId&&(u["X-Palbase-Session-Id"]=t.sessionId),t?.agent&&(u["X-Palbase-Agent"]=t.agent),t?.userId&&(u["X-Palbase-User-Id"]=t.userId),t?.workspaceId&&(u["X-Palbase-Workspace-Id"]=t.workspaceId),t?.fallbacks?.length&&(u["X-Palbase-Fallbacks"]=t.fallbacks.join(",")),u}function I(s){let a=[];for(let t of s){if(typeof t.content=="string"){a.push({role:t.role,content:t.content});continue}if(t.role==="tool"){for(let g of t.content)a.push({role:"tool",tool_call_id:g.toolCallId??"",content:typeof g.output=="string"?g.output:JSON.stringify(g.output??"")});continue}let u=[],k=[];for(let g of t.content)g.type==="text"&&g.text&&u.push(g.text),g.type==="tool-call"&&k.push({id:g.toolCallId??"",type:"function",function:{name:g.toolName??"",arguments:typeof g.input=="string"?g.input:JSON.stringify(g.input??{})}});let T={role:t.role,content:u.join(`
1
+ /*! palbase 0.73.1 — Palbase SDK License (see LICENSE) */
2
+ import"../chunks/DNSLYLU6.js";function M(s){return typeof process<"u"&&process.env?process.env[s]??"":""}function j(s){let a=(s??M("PALBASE_URL")).trim().replace(/\/+$/,"");if(!a)throw new Error("@palbase/ai-sdk: url or PALBASE_URL is required");return a.endsWith("/ai/v1")?a:`${a}/ai/v1`}function N(s){let a=(s??M("PALBASE_SECRET_KEY")).trim();if(!a)throw new Error("@palbase/ai-sdk: apiKey or PALBASE_SECRET_KEY is required");return a}function x(s,a,t){let u={apikey:s,Authorization:`Bearer ${s}`,"Content-Type":"application/json",...a};return t?.sessionId&&(u["X-Palbase-Session-Id"]=t.sessionId),t?.agent&&(u["X-Palbase-Agent"]=t.agent),t?.userId&&(u["X-Palbase-User-Id"]=t.userId),t?.workspaceId&&(u["X-Palbase-Workspace-Id"]=t.workspaceId),t?.fallbacks?.length&&(u["X-Palbase-Fallbacks"]=t.fallbacks.join(",")),u}function I(s){let a=[];for(let t of s){if(typeof t.content=="string"){a.push({role:t.role,content:t.content});continue}if(t.role==="tool"){for(let g of t.content)a.push({role:"tool",tool_call_id:g.toolCallId??"",content:typeof g.output=="string"?g.output:JSON.stringify(g.output??"")});continue}let u=[],k=[];for(let g of t.content)g.type==="text"&&g.text&&u.push(g.text),g.type==="tool-call"&&k.push({id:g.toolCallId??"",type:"function",function:{name:g.toolName??"",arguments:typeof g.input=="string"?g.input:JSON.stringify(g.input??{})}});let T={role:t.role,content:u.join(`
3
3
  `)};k.length>0&&(T.tool_calls=k),a.push(T)}return a}function R(s){switch(s){case"stop":return"stop";case"length":return"length";case"tool_calls":return"tool-calls";case"error":return"error";default:return"unknown"}}function L(s={}){let a=j(s.url),t=N(s.apiKey),u=s.fetch??globalThis.fetch,k=(l,c)=>({specificationVersion:"v2",provider:"palbase",modelId:l,async doGenerate(e){let n={model:l,messages:I(e.prompt),stream:!1};e.maxOutputTokens!==void 0&&(n.max_tokens=e.maxOutputTokens),e.temperature!==void 0&&(n.temperature=e.temperature),e.topP!==void 0&&(n.top_p=e.topP),e.tools?.length&&(n.tools=e.tools.map(i=>({type:"function",function:{name:i.name,description:i.description,parameters:i.inputSchema??{type:"object",properties:{}}}})));let o=await u(`${a}/chat/completions`,{method:"POST",headers:x(t,{...s.headers,...e.headers},c),body:JSON.stringify(n),signal:e.abortSignal});if(!o.ok)throw new Error(`Palbase AI HTTP ${o.status}: ${await o.text()}`);let d=await o.json(),r=d.choices?.[0],p=[];r?.message?.content&&p.push({type:"text",text:r.message.content});for(let i of r?.message?.tool_calls??[])p.push({type:"tool-call",toolCallId:i.id,toolName:i.function.name,input:i.function.arguments});let m=d.usage?.prompt_tokens??0,f=d.usage?.completion_tokens??0;return{content:p,finishReason:R(r?.finish_reason),usage:{inputTokens:m,outputTokens:f,totalTokens:d.usage?.total_tokens??m+f},warnings:[]}},async doStream(e){let n={model:l,messages:I(e.prompt),stream:!0,stream_options:{include_usage:!0}};e.maxOutputTokens!==void 0&&(n.max_tokens=e.maxOutputTokens),e.temperature!==void 0&&(n.temperature=e.temperature),e.topP!==void 0&&(n.top_p=e.topP),e.tools?.length&&(n.tools=e.tools.map(b=>({type:"function",function:{name:b.name,description:b.description,parameters:b.inputSchema??{type:"object",properties:{}}}})));let o=await u(`${a}/chat/completions`,{method:"POST",headers:x(t,{...s.headers,...e.headers},c),body:JSON.stringify(n),signal:e.abortSignal});if(!o.ok||!o.body)throw new Error(`Palbase AI stream HTTP ${o.status}: ${await o.text()}`);let d=o.body.getReader(),r=new TextDecoder,p="",m="stop",f={inputTokens:0,outputTokens:0,totalTokens:0},i=new Map;return{stream:new ReadableStream({async pull(b){for(;;){let v=p.indexOf(`
4
4
  `);if(v>=0){let S=p.slice(0,v).trim();if(p=p.slice(v+1),!S.startsWith("data:"))continue;let A=S.slice(5).trim();if(A==="[DONE]"){for(let P of i.values())b.enqueue({type:"tool-call",toolCallId:P.id,toolName:P.name,input:P.args});i.clear(),b.enqueue({type:"finish",finishReason:m,usage:f}),b.close();return}try{let P=JSON.parse(A);if(P.usage){let h=P.usage.prompt_tokens??0,y=P.usage.completion_tokens??0;f={inputTokens:h,outputTokens:y,totalTokens:P.usage.total_tokens??h+y}}for(let h of P.choices??[]){h.finish_reason&&(m=R(h.finish_reason)),h.delta?.content&&b.enqueue({type:"text-delta",id:P.id??"text_0",delta:h.delta.content});for(let y of h.delta?.tool_calls??[]){let _=i.get(y.index)??{id:"",name:"",args:""};y.id&&(_.id=y.id),y.function?.name&&(_.name=y.function.name),y.function?.arguments&&(_.args+=y.function.arguments),i.set(y.index,_)}}}catch{}continue}let{value:$,done:C}=await d.read();if(C){for(let S of i.values())b.enqueue({type:"tool-call",toolCallId:S.id,toolName:S.name,input:S.args});b.enqueue({type:"finish",finishReason:m,usage:f}),b.close();return}p+=r.decode($,{stream:!0})}}})}}}),T=l=>({specificationVersion:"v2",provider:"palbase",modelId:l,maxEmbeddingsPerCall:1024,async doEmbed({values:c,abortSignal:e}){let n=await u(`${a}/embeddings`,{method:"POST",headers:x(t,s.headers),body:JSON.stringify({model:l,input:c}),signal:e});if(!n.ok)throw new Error(`Palbase AI embeddings HTTP ${n.status}: ${await n.text()}`);let o=await n.json();return{embeddings:(o.data??[]).map(d=>d.embedding),usage:{tokens:o.usage?.prompt_tokens??o.usage?.total_tokens??0}}}}),g=l=>({specificationVersion:"v2",provider:"palbase",modelId:l,async doGenerate({prompt:c,n:e=1,size:n,abortSignal:o}){let d=await u(`${a}/images/generations`,{method:"POST",headers:x(t,s.headers),body:JSON.stringify({model:l,prompt:c,n:e,size:n,response_format:"b64_json"}),signal:o});if(!d.ok)throw new Error(`Palbase AI images HTTP ${d.status}: ${await d.text()}`);return{images:((await d.json()).data??[]).map(p=>p.b64_json??p.url??""),warnings:[]}}}),E=l=>({specificationVersion:"v1",provider:"palbase",modelId:l,async doGenerate({audio:c,mediaType:e,language:n,diarization:o,abortSignal:d}){let r=new FormData;r.set("model",l),n&&r.set("language",n),o&&r.set("diarization","true"),r.set("file",new Blob([new Uint8Array(c)],{type:e}),"audio.wav");let p=x(t,s.headers);delete p["Content-Type"];let m=await u(`${a}/audio/transcriptions`,{method:"POST",headers:p,body:r,signal:d});if(!m.ok)throw new Error(`Palbase AI transcription HTTP ${m.status}: ${await m.text()}`);let f=await m.json();return{text:f.text,language:f.language,durationInSeconds:f.duration_seconds,segments:(f.segments??[]).map(i=>({speaker:i.speaker,startSecond:i.start,endSecond:i.end,text:i.text}))}}}),O=l=>({specificationVersion:"v1",provider:"palbase",modelId:l,async doGenerate({text:c,voice:e,outputFormat:n,speed:o,abortSignal:d}){let r=await u(`${a}/audio/speech`,{method:"POST",headers:x(t,s.headers),body:JSON.stringify({model:l,input:c,voice:e,response_format:n??"mp3",speed:o}),signal:d});if(!r.ok)throw new Error(`Palbase AI speech HTTP ${r.status}: ${await r.text()}`);return{audio:new Uint8Array(await r.arrayBuffer()),mediaType:r.headers.get("content-type")??"audio/mpeg"}}}),w=((l,c)=>k(l,c));return w.languageModel=k,w.textEmbeddingModel=T,w.image=g,w.transcription=E,w.speech=O,w}export{L as createPalbase};
@@ -1,2 +1,2 @@
1
- /*! palbase 0.73.0 — Palbase SDK License (see LICENSE) */
2
- import{ha as w,la as h}from"../chunks/3DUDNEMM.js";import"../chunks/757A6AR6.js";import"../chunks/PAQCJT7M.js";import"../chunks/CY6KUFZW.js";import"../chunks/VEL7X2G3.js";import"../chunks/76W5ZO2L.js";import"../chunks/5OOA4R4H.js";import"../chunks/25HECIZY.js";import"../chunks/SMECWMF7.js";import"../chunks/J7Z2PYL4.js";import"../chunks/YMIK6HLK.js";import"../chunks/PEQZDT6P.js";import"../chunks/J7ZNBBRN.js";import"../chunks/P36C47FS.js";import{binding as R,createDatabase as v}from"palgres";var y=new WeakMap;function q(p,e,a){if(!a?.schemas?.length)throw new TypeError("createRequestDatabase(sql, identity, { schemas }): the engine compiles each call against the app's schemas \u2014 pass the schema files' default exports");let u=a.schemas,n=y.get(p);n||y.set(p,n=new Map);let r=n.get(u);r||n.set(u,r=new Map);let o=e.role===e.serviceRole?"service":e.role==="anon"?"anon":"authenticated",g=o==="service"?{service:e.serviceRole}:{[o]:e.role,service:e.serviceRole},f=`${o}\0${e.role}\0${e.serviceRole}`,i=r.get(f);i||(i=v({sql:p,schemas:u,binding:R(0,!0),roles:g,...a.fields!==void 0?{fields:a.fields}:{}}),r.set(f,i));let b=JSON.parse(e.claimsJson),m=i.then(s=>s.request({role:o,claims:b},{diagnostics:a.diagnostics,signal:a.signal})),d=s=>new Proxy(()=>{},{apply:async(t,D,c)=>{let l=(await m).client;return s(l).apply(l,c)}});return{client:new Proxy({},{get(s,t){if(t!=="then")return t==="diagnostics"?()=>null:t==="asService"?()=>new Proxy({},{get:(D,c)=>c==="then"?void 0:d(l=>l.asService()[c])}):d(D=>D[t])}}),commit:async()=>(await m).commit(),rollback:async s=>(await m).rollback(s)}}export{w as createApp,q as createRequestDatabase,h as makeMemoryCache};
1
+ /*! palbase 0.73.1 — Palbase SDK License (see LICENSE) */
2
+ import{ha as w,la as h}from"../chunks/GTKPHG5F.js";import"../chunks/GWWU2FJ7.js";import"../chunks/4E4ABCSD.js";import"../chunks/VCL3SAQL.js";import"../chunks/MFSC4OJV.js";import"../chunks/SEICTPQP.js";import"../chunks/MB7MHOQO.js";import"../chunks/U3H6HER3.js";import"../chunks/UXHNXE3J.js";import"../chunks/YU3GFTZV.js";import"../chunks/3KCV4F4F.js";import"../chunks/HRWVZ4PC.js";import"../chunks/W2KD2I4Q.js";import"../chunks/DNSLYLU6.js";import{binding as R,createDatabase as v}from"palgres";var y=new WeakMap;function q(p,e,a){if(!a?.schemas?.length)throw new TypeError("createRequestDatabase(sql, identity, { schemas }): the engine compiles each call against the app's schemas \u2014 pass the schema files' default exports");let u=a.schemas,n=y.get(p);n||y.set(p,n=new Map);let r=n.get(u);r||n.set(u,r=new Map);let o=e.role===e.serviceRole?"service":e.role==="anon"?"anon":"authenticated",g=o==="service"?{service:e.serviceRole}:{[o]:e.role,service:e.serviceRole},f=`${o}\0${e.role}\0${e.serviceRole}`,i=r.get(f);i||(i=v({sql:p,schemas:u,binding:R(0,!0),roles:g,...a.fields!==void 0?{fields:a.fields}:{}}),r.set(f,i));let b=JSON.parse(e.claimsJson),m=i.then(s=>s.request({role:o,claims:b},{diagnostics:a.diagnostics,signal:a.signal})),d=s=>new Proxy(()=>{},{apply:async(t,D,c)=>{let l=(await m).client;return s(l).apply(l,c)}});return{client:new Proxy({},{get(s,t){if(t!=="then")return t==="diagnostics"?()=>null:t==="asService"?()=>new Proxy({},{get:(D,c)=>c==="then"?void 0:d(l=>l.asService()[c])}):d(D=>D[t])}}),commit:async()=>(await m).commit(),rollback:async s=>(await m).rollback(s)}}export{w as createApp,q as createRequestDatabase,h as makeMemoryCache};
@@ -1 +1 @@
1
- /*! palbase 0.73.0 — Palbase SDK License (see LICENSE) */
1
+ /*! palbase 0.73.1 — Palbase SDK License (see LICENSE) */
@@ -1,5 +1,5 @@
1
- /*! palbase 0.73.0 — Palbase SDK License (see LICENSE) */
2
- import{$ as It,A as $,B as ut,C as dt,D as pt,E as gt,F as mt,G as ft,H as ht,I as bt,J as yt,K as wt,L as kt,M as Pt,N as St,O as vt,P as Rt,Q as At,R as Et,S as _t,T as Ot,U as xt,V as Tt,W as Ct,X as se,Y as Bt,Z as Ft,_ as Lt,a as Z,aa as $t,b as ee,ba as Mt,c as te,ca as Dt,d as Ne,da as Ut,e as qe,ea as jt,f as Ke,fa as M,g as We,ga as Wt,h as Ve,ha as D,i as Ge,ia as G,j as He,ja as Vt,k as ze,ka as Gt,l as Je,m as Ye,n as Qe,o as Xe,p as Ze,q as et,r as tt,s as nt,t as rt,u as st,v as at,w as ot,x as it,y as lt,z as ct}from"../chunks/3DUDNEMM.js";import{a as Nt,b as qt}from"../chunks/757A6AR6.js";import{a as oe}from"../chunks/LCDNCPQW.js";import{a as v,b as ne,c as re,f as c,g as V,h as p,j as ae,k as Kt}from"../chunks/PAQCJT7M.js";import"../chunks/CY6KUFZW.js";import"../chunks/VEL7X2G3.js";import{E as Q,F as X,d as C,j as Ue,k as je,l as Y,m as I}from"../chunks/76W5ZO2L.js";import"../chunks/5OOA4R4H.js";import"../chunks/25HECIZY.js";import{t as De}from"../chunks/SMECWMF7.js";import"../chunks/J7Z2PYL4.js";import"../chunks/YMIK6HLK.js";import{b as O,c as W}from"../chunks/PEQZDT6P.js";import"../chunks/J7ZNBBRN.js";import"../chunks/P36C47FS.js";import"reflect-metadata";import{existsSync as z,writeFileSync as $n,writeSync as Mn}from"node:fs";import{createServer as Dn}from"node:http";import{dirname as x,join as J,resolve as Oe}from"node:path";import{Readable as Un}from"node:stream";var Ht=2e3,zt=1e4,Jt=/^[A-Za-z0-9_-]{1,64}$/,Yt=512,U=class{linesPerSecond;batchSize;flushMs;maxPending;sendMs;shutdownMs;now;tokens;refilled;unlogged=0;unloggedSince;pending=[];timer;sending;inFlight;pausedUntil=0;lastSendWarning=0;sink;constructor(e,n={}){this.sink=e,this.linesPerSecond=n.linesPerSecond??10,this.batchSize=Math.min(100,n.batchSize??100),this.flushMs=n.flushMs??2e3,this.maxPending=n.maxPending??2e3,this.sendMs=n.sendMs??zt,this.shutdownMs=n.shutdownMs??Ht,this.now=n.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,n,r=new Promise(a=>n=a),s=setTimeout(()=>{e=!0,n()},this.shutdownMs);try{for(;!e&&(this.pending.length>0||this.sending)&&(await Promise.race([this.sending??this.send(),r]),!(this.now()<this.pausedUntil)););}finally{clearTimeout(s)}e&&this.letGo()}letGo(){let e=this.inFlight,n=(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`))),n>0&&p.warn(`[palbase] request traces were not sent to analytics within the ${this.shutdownMs} ms a flush waits; ${n} dropped`)}log(e){let n=this.now();if(this.tokens=Math.min(this.linesPerSecond,this.tokens+(n-this.refilled)/1e3*this.linesPerSecond),this.refilled=n,this.unlogged>0&&n-this.unloggedSince>=6e4&&(p.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=n),this.tokens<1){this.unlogged===0&&(this.unloggedSince=n),this.unlogged++;return}this.tokens-=1;let r=e.status>=500?"error":e.status>=400&&e.status!==499?"warn":"info",s=Math.round(e.durationMs*10)/10;p[r](`${e.method} ${e.path} ${e.status} ${s}ms`,{route:e.endpoint,status:e.status,duration_ms:s,...e.userId?{user_id:e.userId}:{}})}trace(e){this.pending.length>=this.maxPending&&this.pending.shift(),this.pending.push({request_id:Jt.test(e.requestId)?e.requestId:e.requestId.replace(/[^A-Za-z0-9_-]/g,"_").slice(0,64)||"unnamed",source:"backend",endpoint:e.endpoint.slice(0,Yt),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),n=this.sink,r={call:new AbortController,traces:e.length,letGo:!1};this.inFlight=r;let s=setTimeout(()=>r.call.abort(new Error(`analytics did not answer in ${this.sendMs} ms`)),this.sendMs);return s.unref?.(),this.sending=(async()=>{try{await n.sendTraceBatch({body:{traces:e},signal:r.call.signal})}catch(a){if(r.letGo)return;let l=a.status,i=l??(r.call.signal.aborted?`no answer in ${this.sendMs} ms`:"unreachable"),d=a.retryAfter;this.pausedUntil=this.now()+(typeof d=="number"&&d>0?d*1e3:l===429?1e3:5e3),this.now()-this.lastSendWarning>6e4&&(this.lastSendWarning=this.now(),p.warn(`[palbase] request traces were not sent to analytics (${i}); ${e.length} dropped`,{error:a}))}finally{if(clearTimeout(s),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 Qt}from"node:crypto";import{readFileSync as Xt}from"node:fs";import{bind as Zt,bunDriver as en,createDatabase as tn,pooledBinding as nn,sayRunning as rn,envBlock as sn,createSearchWorker as an,cutOff as on,forgetUserIn as ln,MigrationOpen as cn,MigrationRefused as un,Migrator as ue,VersionNotMigrated as dn}from"palgres";import{toModel as pn}from"palgres/dsl";var gn=["start","complete","rollback","plan","status","types"],mn=/^(deploy|cli:[^\u0000-\u001f\u007f]{1,200})$/u;function de(t){let e=t.PALBASE_DB_MIGRATE;if(!(e===void 0||e==="")){if(!gn.includes(e))throw new Error(`[palbase] PALBASE_DB_MIGRATE is start, complete, rollback, plan, status or types, not ${e}`);return e}}function pe(t){let e=Array.isArray(t.schemas)?t.schemas:[t.schemas];for(let n of e)if(n.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 ge(t){let e=t.access;if(e===void 0||typeof e=="string")return e;try{return Xt(e,"utf8")}catch(n){throw new Error(`[palbase] db.access: ${e.href} could not be read (${n instanceof Error?n.message:String(n)}) \u2014 it is the file the app's access schema is in`)}}function F(t){let e=ge(t);return pn(pe(t),e===void 0?{}:{access:e})}function fn(t){return t.tables.some(e=>e.search!==void 0)}function N(t){return t.access!==void 0||t.tables.some(e=>!e.ignored&&e.columns.some(n=>n.user!==void 0&&!n.ignored))}function me(t){let e=t.PALBASE_DB_CONNECTIONS;if(e===void 0||e==="")return 31;let n=Number(e);if(!Number.isSafeInteger(n)||n<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 n}function hn(t,e){if(t.url!==void 0||t.driver!==void 0)return;let n=e.PALBASE_DB_POOLED_URL;return n===void 0||n===""?void 0:n}function bn(t){let e=t.PALBASE_DB_POOLED_CONNECTIONS;if(e===void 0||e==="")return 12;let n=Number(e);if(!Number.isSafeInteger(n)||n<4)throw new Error(`[palbase] PALBASE_DB_POOLED_CONNECTIONS is how many pooled connections the app keeps open, 4 at least \u2014 not ${e}`);return n}var yn=2,wn=5e3;async function kn(t,e,n=wn){let r=await t.reserve();try{await r.unsafe(e)}catch(o){throw r.release(),o}let s=r,a=!1,l=!1,i=async()=>{if(s!==void 0)try{await s.unsafe("SELECT 1");return}catch{s.release(),s=void 0}let o=await t.reserve();try{await o.unsafe(e)}catch(g){throw o.release(),g}a?o.release():s=o},d=setInterval(()=>{l||a||(l=!0,i().catch(o=>p.warn(`[palbase] database: the session that says this version runs could not be opened again (${o instanceof Error?o.message:String(o)}) \u2014 tried again in ${n/1e3} s`)).finally(()=>{l=!1}))},n);return d.unref?.(),{stop(){a=!0,clearInterval(d),s?.release(),s=void 0}}}function Pn(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 H(t,e){if(t.driver)return t.driver;let n=globalThis.Bun;if(!n)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 r=e-1;return s=>{let a=new n.SQL({url:s,prepare:!1,max:r}),l=new n.SQL({url:s,prepare:!1,max:1});return{pool:{reserve:()=>a.reserve(),unsafe:(i,d)=>a.unsafe(i,d),begin:i=>a.begin(i)},engine:en(a,l),poolSize:r,close:async()=>{await a.close({timeout:ie}),await l.close({timeout:ie})}}}}async function fe(t){return t==="rollback"?(p.info("[palbase] migrate rollback: this app declares no database; nothing of it to take back"),await B(t,{state:"none"}),0):(p.error(`[palbase] migrate ${t}: this app declares no database \u2014 PalbaseFactory.create(\u2026, { db: { schemas } })`),1)}async function he(t,e){if(!t)return p.error("[palbase] db types: this app declares no database \u2014 PalbaseFactory.create(\u2026, { db: { schemas } })"),1;let n=Array.isArray(t.schemas)?t.schemas:[t.schemas],r=ge(t);return await B("types",sn(n,{module:"palbase/backend/env",...r===void 0?{}:{access:r}}),e),0}async function be(t,e,n){let r=e.PALBASE_DB_OWNER_URL;if(!r)return p.error("[palbase] PALBASE_DB_MIGRATE without PALBASE_DB_OWNER_URL: a migration runs as the tables' owner"),1;let s=e.PALBASE_DB_MIGRATION_BY||"deploy";if(!mn.test(s))return p.error("[palbase] PALBASE_DB_MIGRATION_BY is deploy, or cli:<who>"),1;let a=H(t,me(e)),l=a(r),i,d=o=>p.error(`[palbase] migrate ${n}: ${o}`);try{let o=F(t),g=new ue(l.pool,{log:f=>{/ is held by others | held by writers/.test(f)&&(i=f.trim()),p.info(f)},shadow:f=>{let k=new URL(r);k.pathname=`/${f}`;let y=a(k.toString());return{reserve:()=>y.pool.reserve(),end:()=>y.close()}},openedBy:s,fields:()=>Sn(e)});if(n==="plan"){let f=await g.plan(o);return await B(n,f),f.refusals.length>0?1:0}if(n==="status")return await B(n,await g.status()),0;let m=n==="start"?await vn(g,o,s):n==="complete"?await g.complete():await g.rollback();return p.info(`[palbase] migrate ${n}: done`,{result:m}),await B(n,m),0}catch(o){return o instanceof un?(p.error(`[palbase] migrate ${n}: refused`,{refusals:o.refusals}),d(`refused \u2014 ${o.refusals.join("; ")}`),1):on(o)?(p.error(`[palbase] migrate ${n}: cut off; run again, it goes on from where it stopped`,{error:o}),d(`cut off \u2014 ${i??le(o)}`),75):(p.error(`[palbase] migrate ${n}: failed`,{error:o}),d(`failed \u2014 ${le(o)}`),1)}finally{await l.close().catch(()=>{})}}async function Sn(t){let e=t.PALBASE_URL,n=t.PALBASE_SECRET_KEY;if(!e||!n)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 r=C({url:e,secretKey:n}).fields;return await r.load(),r.close(),r}async function vn(t,e,n){try{return await t.start(e)}catch(r){if(!(r instanceof cn)||n!=="deploy"||!r.openedBy?.startsWith("cli:"))throw r;return p.warn(`[palbase] migrate start: the migration ${r.openedBy} opened (version ${r.to}) gives way to this release \u2014 rolled back first`),await t.rollback(),await t.start(e)}}var Rn=(t,e)=>{process.stdout.write(t,()=>e())};function B(t,e,n=Rn){return new Promise(r=>n(`${JSON.stringify({palbase_migrate:t,result:e})}
1
+ /*! palbase 0.73.1 — Palbase SDK License (see LICENSE) */
2
+ import{$ as It,A as $,B as ut,C as dt,D as pt,E as gt,F as mt,G as ft,H as ht,I as bt,J as yt,K as wt,L as kt,M as Pt,N as St,O as vt,P as Rt,Q as At,R as Et,S as _t,T as Ot,U as xt,V as Tt,W as Ct,X as se,Y as Bt,Z as Ft,_ as Lt,a as Z,aa as $t,b as ee,ba as Mt,c as te,ca as Dt,d as Ne,da as Ut,e as qe,ea as jt,f as Ke,fa as M,g as We,ga as Wt,h as Ve,ha as D,i as Ge,ia as G,j as He,ja as Vt,k as ze,ka as Gt,l as Je,m as Ye,n as Qe,o as Xe,p as Ze,q as et,r as tt,s as nt,t as rt,u as st,v as at,w as ot,x as it,y as lt,z as ct}from"../chunks/GTKPHG5F.js";import{a as Nt,b as qt}from"../chunks/GWWU2FJ7.js";import{a as oe}from"../chunks/HYPCFC4K.js";import{a as v,b as ne,c as re,f as c,g as V,h as p,j as ae,k as Kt}from"../chunks/4E4ABCSD.js";import"../chunks/VCL3SAQL.js";import"../chunks/MFSC4OJV.js";import{E as Q,F as X,d as C,j as Ue,k as je,l as Y,m as I}from"../chunks/SEICTPQP.js";import"../chunks/MB7MHOQO.js";import"../chunks/U3H6HER3.js";import{t as De}from"../chunks/UXHNXE3J.js";import"../chunks/YU3GFTZV.js";import"../chunks/3KCV4F4F.js";import{b as O,c as W}from"../chunks/HRWVZ4PC.js";import"../chunks/W2KD2I4Q.js";import"../chunks/DNSLYLU6.js";import"reflect-metadata";import{existsSync as z,writeFileSync as $n,writeSync as Mn}from"node:fs";import{createServer as Dn}from"node:http";import{dirname as x,join as J,resolve as Oe}from"node:path";import{Readable as Un}from"node:stream";var Ht=2e3,zt=1e4,Jt=/^[A-Za-z0-9_-]{1,64}$/,Yt=512,U=class{linesPerSecond;batchSize;flushMs;maxPending;sendMs;shutdownMs;now;tokens;refilled;unlogged=0;unloggedSince;pending=[];timer;sending;inFlight;pausedUntil=0;lastSendWarning=0;sink;constructor(e,n={}){this.sink=e,this.linesPerSecond=n.linesPerSecond??10,this.batchSize=Math.min(100,n.batchSize??100),this.flushMs=n.flushMs??2e3,this.maxPending=n.maxPending??2e3,this.sendMs=n.sendMs??zt,this.shutdownMs=n.shutdownMs??Ht,this.now=n.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,n,r=new Promise(a=>n=a),s=setTimeout(()=>{e=!0,n()},this.shutdownMs);try{for(;!e&&(this.pending.length>0||this.sending)&&(await Promise.race([this.sending??this.send(),r]),!(this.now()<this.pausedUntil)););}finally{clearTimeout(s)}e&&this.letGo()}letGo(){let e=this.inFlight,n=(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`))),n>0&&p.warn(`[palbase] request traces were not sent to analytics within the ${this.shutdownMs} ms a flush waits; ${n} dropped`)}log(e){let n=this.now();if(this.tokens=Math.min(this.linesPerSecond,this.tokens+(n-this.refilled)/1e3*this.linesPerSecond),this.refilled=n,this.unlogged>0&&n-this.unloggedSince>=6e4&&(p.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=n),this.tokens<1){this.unlogged===0&&(this.unloggedSince=n),this.unlogged++;return}this.tokens-=1;let r=e.status>=500?"error":e.status>=400&&e.status!==499?"warn":"info",s=Math.round(e.durationMs*10)/10;p[r](`${e.method} ${e.path} ${e.status} ${s}ms`,{route:e.endpoint,status:e.status,duration_ms:s,...e.userId?{user_id:e.userId}:{}})}trace(e){this.pending.length>=this.maxPending&&this.pending.shift(),this.pending.push({request_id:Jt.test(e.requestId)?e.requestId:e.requestId.replace(/[^A-Za-z0-9_-]/g,"_").slice(0,64)||"unnamed",source:"backend",endpoint:e.endpoint.slice(0,Yt),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),n=this.sink,r={call:new AbortController,traces:e.length,letGo:!1};this.inFlight=r;let s=setTimeout(()=>r.call.abort(new Error(`analytics did not answer in ${this.sendMs} ms`)),this.sendMs);return s.unref?.(),this.sending=(async()=>{try{await n.sendTraceBatch({body:{traces:e},signal:r.call.signal})}catch(a){if(r.letGo)return;let l=a.status,i=l??(r.call.signal.aborted?`no answer in ${this.sendMs} ms`:"unreachable"),d=a.retryAfter;this.pausedUntil=this.now()+(typeof d=="number"&&d>0?d*1e3:l===429?1e3:5e3),this.now()-this.lastSendWarning>6e4&&(this.lastSendWarning=this.now(),p.warn(`[palbase] request traces were not sent to analytics (${i}); ${e.length} dropped`,{error:a}))}finally{if(clearTimeout(s),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 Qt}from"node:crypto";import{readFileSync as Xt}from"node:fs";import{bind as Zt,bunDriver as en,createDatabase as tn,pooledBinding as nn,sayRunning as rn,envBlock as sn,createSearchWorker as an,cutOff as on,forgetUserIn as ln,MigrationOpen as cn,MigrationRefused as un,Migrator as ue,VersionNotMigrated as dn}from"palgres";import{toModel as pn}from"palgres/dsl";var gn=["start","complete","rollback","plan","status","types"],mn=/^(deploy|cli:[^\u0000-\u001f\u007f]{1,200})$/u;function de(t){let e=t.PALBASE_DB_MIGRATE;if(!(e===void 0||e==="")){if(!gn.includes(e))throw new Error(`[palbase] PALBASE_DB_MIGRATE is start, complete, rollback, plan, status or types, not ${e}`);return e}}function pe(t){let e=Array.isArray(t.schemas)?t.schemas:[t.schemas];for(let n of e)if(n.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 ge(t){let e=t.access;if(e===void 0||typeof e=="string")return e;try{return Xt(e,"utf8")}catch(n){throw new Error(`[palbase] db.access: ${e.href} could not be read (${n instanceof Error?n.message:String(n)}) \u2014 it is the file the app's access schema is in`)}}function F(t){let e=ge(t);return pn(pe(t),e===void 0?{}:{access:e})}function fn(t){return t.tables.some(e=>e.search!==void 0)}function N(t){return t.access!==void 0||t.tables.some(e=>!e.ignored&&e.columns.some(n=>n.user!==void 0&&!n.ignored))}function me(t){let e=t.PALBASE_DB_CONNECTIONS;if(e===void 0||e==="")return 31;let n=Number(e);if(!Number.isSafeInteger(n)||n<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 n}function hn(t,e){if(t.url!==void 0||t.driver!==void 0)return;let n=e.PALBASE_DB_POOLED_URL;return n===void 0||n===""?void 0:n}function bn(t){let e=t.PALBASE_DB_POOLED_CONNECTIONS;if(e===void 0||e==="")return 12;let n=Number(e);if(!Number.isSafeInteger(n)||n<4)throw new Error(`[palbase] PALBASE_DB_POOLED_CONNECTIONS is how many pooled connections the app keeps open, 4 at least \u2014 not ${e}`);return n}var yn=2,wn=5e3;async function kn(t,e,n=wn){let r=await t.reserve();try{await r.unsafe(e)}catch(o){throw r.release(),o}let s=r,a=!1,l=!1,i=async()=>{if(s!==void 0)try{await s.unsafe("SELECT 1");return}catch{s.release(),s=void 0}let o=await t.reserve();try{await o.unsafe(e)}catch(g){throw o.release(),g}a?o.release():s=o},d=setInterval(()=>{l||a||(l=!0,i().catch(o=>p.warn(`[palbase] database: the session that says this version runs could not be opened again (${o instanceof Error?o.message:String(o)}) \u2014 tried again in ${n/1e3} s`)).finally(()=>{l=!1}))},n);return d.unref?.(),{stop(){a=!0,clearInterval(d),s?.release(),s=void 0}}}function Pn(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 H(t,e){if(t.driver)return t.driver;let n=globalThis.Bun;if(!n)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 r=e-1;return s=>{let a=new n.SQL({url:s,prepare:!1,max:r}),l=new n.SQL({url:s,prepare:!1,max:1});return{pool:{reserve:()=>a.reserve(),unsafe:(i,d)=>a.unsafe(i,d),begin:i=>a.begin(i)},engine:en(a,l),poolSize:r,close:async()=>{await a.close({timeout:ie}),await l.close({timeout:ie})}}}}async function fe(t){return t==="rollback"?(p.info("[palbase] migrate rollback: this app declares no database; nothing of it to take back"),await B(t,{state:"none"}),0):(p.error(`[palbase] migrate ${t}: this app declares no database \u2014 PalbaseFactory.create(\u2026, { db: { schemas } })`),1)}async function he(t,e){if(!t)return p.error("[palbase] db types: this app declares no database \u2014 PalbaseFactory.create(\u2026, { db: { schemas } })"),1;let n=Array.isArray(t.schemas)?t.schemas:[t.schemas],r=ge(t);return await B("types",sn(n,{module:"palbase/backend/env",...r===void 0?{}:{access:r}}),e),0}async function be(t,e,n){let r=e.PALBASE_DB_OWNER_URL;if(!r)return p.error("[palbase] PALBASE_DB_MIGRATE without PALBASE_DB_OWNER_URL: a migration runs as the tables' owner"),1;let s=e.PALBASE_DB_MIGRATION_BY||"deploy";if(!mn.test(s))return p.error("[palbase] PALBASE_DB_MIGRATION_BY is deploy, or cli:<who>"),1;let a=H(t,me(e)),l=a(r),i,d=o=>p.error(`[palbase] migrate ${n}: ${o}`);try{let o=F(t),g=new ue(l.pool,{log:f=>{/ is held by others | held by writers/.test(f)&&(i=f.trim()),p.info(f)},shadow:f=>{let k=new URL(r);k.pathname=`/${f}`;let y=a(k.toString());return{reserve:()=>y.pool.reserve(),end:()=>y.close()}},openedBy:s,fields:()=>Sn(e)});if(n==="plan"){let f=await g.plan(o);return await B(n,f),f.refusals.length>0?1:0}if(n==="status")return await B(n,await g.status()),0;let m=n==="start"?await vn(g,o,s):n==="complete"?await g.complete():await g.rollback();return p.info(`[palbase] migrate ${n}: done`,{result:m}),await B(n,m),0}catch(o){return o instanceof un?(p.error(`[palbase] migrate ${n}: refused`,{refusals:o.refusals}),d(`refused \u2014 ${o.refusals.join("; ")}`),1):on(o)?(p.error(`[palbase] migrate ${n}: cut off; run again, it goes on from where it stopped`,{error:o}),d(`cut off \u2014 ${i??le(o)}`),75):(p.error(`[palbase] migrate ${n}: failed`,{error:o}),d(`failed \u2014 ${le(o)}`),1)}finally{await l.close().catch(()=>{})}}async function Sn(t){let e=t.PALBASE_URL,n=t.PALBASE_SECRET_KEY;if(!e||!n)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 r=C({url:e,secretKey:n}).fields;return await r.load(),r.close(),r}async function vn(t,e,n){try{return await t.start(e)}catch(r){if(!(r instanceof cn)||n!=="deploy"||!r.openedBy?.startsWith("cli:"))throw r;return p.warn(`[palbase] migrate start: the migration ${r.openedBy} opened (version ${r.to}) gives way to this release \u2014 rolled back first`),await t.rollback(),await t.start(e)}}var Rn=(t,e)=>{process.stdout.write(t,()=>e())};function B(t,e,n=Rn){return new Promise(r=>n(`${JSON.stringify({palbase_migrate:t,result:e})}
3
3
  `,r))}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 An(t,e){try{return await new ue(t).plan(e)}catch{return}}var ce="palbase.idempotency_keys.response_body";function En(t,e){let n=null,r=!1,s=async()=>{let i=e.currentKey();if(!(r||i===n)){r=!0;try{let d=await t.reseal();n=i;let o=d.reduce((g,m)=>g+m.resealed,0);o>0&&p.info(`[palbase] fields: ${o} value(s) sealed again with key ${i}`,{report:d})}catch(d){p.warn(`[palbase] fields: sealing again with key ${i} stopped; tried again in a minute`,{error:d})}finally{r=!1}}},a=setTimeout(s,1e4),l=setInterval(s,6e4);for(let i of[a,l])i.unref?.();return()=>{clearTimeout(a),clearInterval(l)}}var j=class extends Error{digest;plan;constructor(e,n){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>)`,...n?_n(n):[" palbase db:plan says what it would change"]].join(`
5
5
  `)),this.name="SchemaNotPushed",this.digest=e,this.plan=n}};function _n(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 n of t.changes)e.push(` + ${n}`);for(let n of t.refusals)e.push(` \u2717 ${n}`);return e}var On=8e4;async function ye(t,e,n,r){let s=t.url??e.PALBASE_DB_URL;if(!s)throw new Error("[palbase] db.url / PALBASE_DB_URL is the database the app connects to");let a=pe(t),l=F(t),i=hn(t,e),d=H(t,i===void 0?me(e):yn)(s),o,g;try{let m=!1,f=b=>{m||(m=!0,p.warn(`[palbase] database: not answering yet (${b instanceof Error?b.message:String(b)}) \u2014 waiting for it, as one waking does`))},k=await Zt(d.engine,l,{waitMs:r.onPlatform?On:0,onUnreachable:f}).catch(async b=>{throw r.onPlatform||!(b instanceof dn)?b:new j(b.digest,await An(d.pool,l))});i!==void 0&&(g=await kn(d.pool,rn(k)),o=H(t,bn(e))(i));let y=o??d,R=Qt("sha256",n).update("palgres page cursor").digest("hex"),w=t.embed??r.embed,h=r.fields,A=await tn({sql:y.engine,schemas:a,binding:o===void 0?k:nn(k),...o===void 0?{}:{prepare:!1},cursorSecret:R,admission:Pn(y.poolSize),embed:w,log:b=>p.warn(`[palbase] ${b}`),fields:async()=>(await h.load(),h)}),E=h.loaded?En(A,h):()=>{},_=fn(l)?an({sql:y.engine,embed:w,log:b=>p.info(`[palbase] ${b}`)}):void 0;return{model:l,binding:k,app:A,requests:t.requests??"caller",forget:(b,P)=>ln({attempt:S=>P.$attempt(S)},k,l,b),..._?{search:_}:{},keptAnswers:{seal:b=>h.loaded?h.encrypt(ce,b):b,open:async b=>h.isEncrypted(b)?(h.loaded||await h.load(),h.decrypt(ce,b)):b},close:async()=>{E(),h.close(),await o?.close(),g?.stop(),await d.close()}}}catch(m){throw await o?.close().catch(()=>{}),g?.stop(),await d.close(),m}}function xn(t){let e=Buffer.from(t,"base64"),n=new Array(e.byteLength/4);for(let r=0;r<n.length;r++)n[r]=e.readFloatLE(r*4);return n}function we(t){return async({texts:e,model:n,dimensions:r})=>{let{data:s}=await t.ai.createEmbeddings({body:{input:e,model:n,dimensions:r}});return{model:s.model,vectors:s.vectors.map(xn)}}}var Tn=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function ke(t,e,n){let r=[],s=t.url??e.PALBASE_URL??"",a="";try{let g=new URL(s);a=g.origin,g.protocol!=="https:"&&g.hostname!=="localhost"&&g.hostname!=="127.0.0.1"&&r.push("palbase.url / PALBASE_URL is https://<ref>.<domain>"),(g.pathname!=="/"||g.search||g.hash)&&r.push("palbase.url / PALBASE_URL is the project origin alone")}catch{r.push("palbase.url / PALBASE_URL is the project address, https://<ref>.<domain>")}let l=t.projectId??e.PALBASE_PROJECT_ID??"";Tn.test(l)||r.push("palbase.projectId / PALBASE_PROJECT_ID is the project id (a UUID)");let i=t.secretKey??e.PALBASE_SECRET_KEY??"";/^pb_[a-z0-9]+_s/.test(i)||r.push("palbase.secretKey / PALBASE_SECRET_KEY is the project secret key (pb_<ref>_s\u2026), kept in the project's Secrets");let d=(t.platformSecret??e.PALBASE_PLATFORM_SECRET)||void 0;d!==void 0&&!/^[0-9a-f]{64}$/.test(d)&&r.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 o=(t.webhookSecret??e.PALBASE_WEBHOOK_SECRET)||void 0;if(n.needsWebhookSecret&&(d!==void 0||o!==void 0)&&!/^whsec_[0-9a-f]{64}$/.test(o??"")&&r.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"),r.length>0)throw new Error(`[palbase] the app cannot start:
@@ -9,4 +9,4 @@ ${r.join(`
9
9
  `)}
10
10
  `}async function ve(t,e,n=Bn){let r=Buffer.from(e,"utf8");for(let s=0;s<r.length;)try{s+=n(t,r,s,r.length-s)}catch(a){if(a.code!=="EAGAIN")throw a;await new Promise(l=>setTimeout(l,5))}}var Re=2e4,Ae=5e3,jn=15e3,Nn="/_palbase/health";function qn(t){let e=new Set,n=r=>{if(e.has(r))return!1;e.add(r);let s=$(r,Z);return s?s.providers.some(a=>$(a,ee)!==void 0&&$(a,te)===void 0)||s.imports.some(n):!1};return t.some(n)}var Kn={async create(t,e={}){let n=Array.isArray(t)?t:[t],r=e.env??process.env,s=de(r);if(s!==void 0){let P=s==="types"?await he(e.db):e.db?await be(e.db,r,s):await fe(s);throw process.exit(P),new q(P)}let a=r.PALBASE_CONTRACT_OUT;if(a){let P;try{await _e(Ee(r)),P=await Wn(n,e,r)}catch(S){throw Mn(2,`[palbase] the contract: ${S instanceof Error?S.message:String(S)}
11
11
  `),process.exit(1),new L}throw a==="/dev/stdout"?await ve(1,Se(P)):$n(a,`${P}
12
- `),process.exit(0),new L}let l=Ee(r),i=await _e(l);i&&p.info(`[palbase] strings: ${i.source} and ${i.locales.length-1} other language(s), ${Object.keys(i.strings).length} sentence(s), from ${l}/palbase/strings`),ae(i?void 0:l);let d=e.db?F(e.db):void 0,o=await X({env:r,url:e.palbase?.url,secretKey:e.palbase?.secretKey});o&&p.info(`[palbase] secrets: ${o.loaded.length} from the project's ${o.set} set${o.kept.length>0?`; ${o.kept.join(", ")} kept as the environment gives them`:""}`),o&&o.refused.length>0&&p.warn(`[palbase] secrets not set \u2014 names a process reads as its own, not the app's: ${o.refused.map(P=>JSON.stringify(P)).join(", ")}`);let g=qn(n)||d!==void 0&&N(d),m=ke(e.palbase??{},r,{needsWebhookSecret:g});g&&m.webhookSecret===void 0&&p.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=C({url:m.url,secretKey:m.secretKey}),k=e.port??Number(r.PORT??"8080");if(!Number.isInteger(k)||k<0||k>65535)throw new Error(`[palbase] PORT is a port number, not ${String(e.port??r.PORT)}`);let y=e.db?await ye(e.db,r,m.secretKey,{onPlatform:m.platformSecret!==void 0,embed:we(f),fields:f.fields}):void 0;y&&p.info(`[palbase] database: version ${y.binding.version}`);let R=y&&N(y.model)?{"user.deleted":[P=>Vn(y,P)]}:void 0,w=m.platformSecret===void 0?void 0:{secret:m.platformSecret},h=e.requestTelemetry===!1?void 0:new U(f.analytics),A=()=>D({modules:n,verifier:new I({issuer:m.url,projectId:m.projectId,standing:Y({url:m.url,secretKey:m.secretKey})}),server:f,webhookSecret:m.webhookSecret,env:r,projectId:m.projectId,telemetry:h,auth:e.auth,tokens:e.tokens,rateLimit:e.rateLimit,maxBodyBytes:e.bodyLimit,cors:zn(e.cors,r.PALBASE_WEB_ORIGINS),platform:w,events:R,database:y&&{app:y.app,requests:y.requests,keptAnswers:y.keptAnswers},strings:i}),E=A(),_=e.boot?.attempts??5,b=e.boot?.backoffMs??1e3;for(let P=1;;P++)try{await E.start();break}catch(S){if(P>=_)throw p.error(`[palbase] the app did not start after ${_} attempts`,{error:S}),S;p.warn(`[palbase] the app did not start (attempt ${P} of ${_}); trying again in ${b} ms`,{error:S}),await new Promise(Me=>setTimeout(Me,b)),b*=2,E=A()}return Gn(E,f,k,e.host??"0.0.0.0",e.exitOnFatal??!0,y)}};function Ee(t){let e=t.PALBASE_CONTRACT_ENTRY??process.argv[1];if(!e)return process.cwd();let n=x(Oe(e));for(;!z(J(n,"package.json"))&&x(n)!==n;)n=x(n);return z(J(n,"package.json"))?n:process.cwd()}async function _e(t){try{return await oe(t)}catch(e){throw new Error(`[palbase] the app's strings: ${e instanceof Error?e.message:String(e)}`)}}async function Wn(t,e,n){let r=Oe(n.PALBASE_CONTRACT_ENTRY??process.argv[1]??"");if(!/\.[cm]?tsx?$/.test(r))throw new Error(`the contract is read from the app's TypeScript source, and this run's entry is ${r||"none"}: start it from its source (bun run src/main.ts), or name the source's entry in PALBASE_CONTRACT_ENTRY`);let s=x(r);for(;!z(J(s,"package.json"))&&x(s)!==s;)s=x(s);let{analyzeProject:a}=await import("../chunks/MVKZWEHL.js"),{routeContracts:l}=await import("../chunks/JG4V6LNY.js"),i=a(s,r);for(let g of i.warnings)p.warn(`[palbase] the contract: ${g}`);let d="https://contract.palbase.invalid",o=D({modules:t,verifier:new I({issuer:d,projectId:"contract",standing:()=>Promise.reject(new Error("the contract run serves nothing"))}),server:C({url:d,secretKey:"pb_contract_s"}),env:n,projectId:"contract",auth:e.auth,tokens:e.tokens,rateLimit:e.rateLimit,maxBodyBytes:e.bodyLimit,cors:e.cors,contractOnly:{database:e.db!==void 0,routes:await l(i.routes),errors:se()},events:e.db&&N(F(e.db))?{"user.deleted":[]}:void 0});return JSON.stringify(o.contract())}var L=class extends Error{constructor(){super("[palbase] the contract run ended"),this.name="ContractRunEnded"}},q=class extends Error{code;constructor(e){super(`[palbase] the migration run ended with ${e}`),this.name="MigrationRunEnded",this.code=e}};async function Vn(t,e){let n=e.data?.user_id;if(typeof n!="string"||n==="")throw new Error("[palbase] user.deleted without a user_id");let r=await t.forget(n,V.$asService());p.info(`[palbase] user ${n} deleted: ${r.deleted} row(s) gone, ${r.detached} forgot them${r.relationships===void 0?"":`, ${r.relationships} relationship(s) of the access schema taken back`}`)}async function Gn(t,e,n,r,s,a){let l,i={on:!1},d=(w,h)=>new URL(w.url).pathname===Nn&&w.method==="GET"?Promise.resolve(i.on?Response.json({ok:!1,stopping:!0},{status:503}):Response.json({ok:!0})):t.handle(w,h),o=Dn((w,h)=>{Hn(d,w,h,i).finally(()=>{i.on&&o.closeIdleConnections()})});o.keepAliveTimeout=29e4,o.headersTimeout=3e5;try{await new Promise((w,h)=>{o.once("error",h),o.listen(n,r,()=>w())})}catch(w){throw await t.stop(),await a?.close(),w}let g=o.address().port;p.info(`[palbase] serving ${t.routes.length} route(s) on :${g}`,{routes:t.routes}),a?.search?.start();let m=w=>l??=(async()=>{p.info("[palbase] stopping: finishing the requests in flight"),i.on=!0;let h=new Promise(E=>o.close(()=>E()));o.closeIdleConnections();let A=setTimeout(()=>o.closeAllConnections(),w);await h,clearTimeout(A),process.off("SIGINT",y),process.off("uncaughtException",R),process.off("unhandledRejection",R);try{await t.stop(),await a?.search?.stop(),await a?.close()}finally{process.off("SIGTERM",y)}})(),f=()=>m(Re),k=!1,y=()=>{if(k){p.info("[palbase] stopping: told to stop again; the requests in flight are still being finished");return}k=!0;let w=setTimeout(()=>{p.error("[palbase] stopping took longer than it is given; the process ends"),process.exit(1)},Re+jn);w.unref(),f().then(()=>{clearTimeout(w),process.exit(0)},h=>{clearTimeout(w),p.error("[palbase] stopping failed; the process ends",{error:h}),process.exit(1)})},R=w=>{p.error("[palbase] the app crashed; stopping so the machine starts it again",{error:w});let h=setTimeout(()=>process.exit(1),Ae+1e3);m(Ae).finally(()=>{clearTimeout(h),process.exit(1)})};return process.on("SIGTERM",y),process.once("SIGINT",y),s&&(process.on("uncaughtException",R),process.on("unhandledRejection",R)),{routes:t.routes,palbase:e,port:g,handle:d,close:f}}async function Hn(t,e,n,r){try{let s=e.url??"/",a;try{if(!s.startsWith("/"))throw new TypeError("the request target is not a path");a=new URL(`http://localhost${s}`)}catch{n.statusCode=400,n.end();return}let l=new Headers;for(let[m,f]of Object.entries(e.headers))if(f!==void 0)if(Array.isArray(f))for(let k of f)l.append(m,k);else l.set(m,f);let i=e.method!=="GET"&&e.method!=="HEAD",d=new AbortController;n.on("close",()=>{n.writableFinished||d.abort(new Error("the client closed the connection"))});let o=new Request(a,{method:e.method,headers:l,body:i?Un.toWeb(e):void 0,duplex:"half",signal:d.signal}),g=await t(o,{remoteAddress:e.socket.remoteAddress,target:s});if(n.statusCode=g.status,g.headers.forEach((m,f)=>n.setHeader(f,m)),r.on&&n.setHeader("connection","close"),g.body)for await(let m of g.body)n.write(m);n.end()}catch(s){p.error("[palbase] the request could not be answered",{error:s}),n.headersSent||(n.statusCode=500),n.end()}}function zn(t,e,n=r=>console.warn(r)){let r=(e??"").split(",").map(i=>i.trim()).filter(i=>i!=="");if(r.length===0||t?.origins==="*")return t;let s=r.filter(i=>G(i)),a=r.filter(i=>!G(i));a.length>0&&n(`[palbase] the project's web origins ${a.map(i=>JSON.stringify(i)).join(", ")} are not CORS origins (https://host[:port], http only for localhost): browsers there are not let in`);let l=[...new Set([...t?.origins??[],...s])];return l.length===0?t:{...t,origins:l}}import{bigint as cs,boolean as us,check as ds,date as ps,defineSchema as gs,defineTable as ms,enumType as fs,foreignKey as hs,index as bs,integer as ys,jsonb as ws,numeric as ks,ownedByUser as Ps,policy as Ss,raw as vs,sqlType as Rs,text as As,timestamp as Es,userRef as _s,uuid as Os}from"palgres/dsl";import{AccessRefused as Ts}from"palgres";import{increment as Bs,now as Fs}from"palgres";function T(t){if(t instanceof O)return{data:null,error:{code:t.code,message:t.message},status:t.status};throw t}async function u(t,e){try{let n=await t();return{data:await e(n.data),error:null,status:n.status}}catch(n){return T(n)}}var Jn=v("Secrets",{async get(t){if(Q(t))return null;let e=process.env[t];return typeof e=="string"&&e!==""?e:null}}),Yn=100,Qn=1e3,Xn=168*3600,Zn={s:1,m:60,h:3600,d:86400};function er(t){let e=String(t).trim();if(!/^(\d+(\.\d+)?[dhms])+$/.test(e))return;let n=0;for(let[,r,,s]of e.matchAll(/(\d+(\.\d+)?)([dhms])/g))n+=Math.round(Number(r)*Zn[s]*1e3);return Math.ceil(n/1e3)}function Ie(t,e,n){let r="getPublicUrl",s;try{s=String(e).split("/").map(l=>W(r,"path",l)).join("%2F")}catch(l){throw l instanceof O&&l.code==="invalid_path_parameter"?new O({op:r,status:0,code:"invalid_path_parameter",message:`${r}: the object path ${JSON.stringify(e)} has an empty, "." or ".." segment: storage keeps no such object`}):l}let a=`${c.url}/storage/public/${W(r,"bucket",t)}/${s}`;return n?`${a}?variant=${encodeURIComponent(n)}`:a}function xe(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,Ie(t.bucket,t.path,e)]))}}function tr(t){return{async upload(e,n,r){let s=r?.contentType??(n instanceof Blob&&n.type!==""?n.type:void 0);try{let a=await c.storage.putObject({path:{bucket:t,path:e},headers:r?.upsert?void 0:{"If-None-Match":"*"},body:n,contentType:s});return{data:xe(a.data),error:null,status:a.status}}catch(a){return a instanceof O&&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}:T(a)}},async download(e){try{let n=await c.storage.getObject({path:{bucket:t,path:e}});if(n.status===304)throw new Error("storage answered 304 to a read that sent no entity tag");let r=n.data;try{return{data:await r.blob(),error:null,status:n.status}}catch(s){return{data:null,error:{code:"network_error",message:`the object's bytes stopped arriving: ${s instanceof Error?s.message:String(s)}`},status:0}}}catch(n){return T(n)}},getPublicUrl(e,n){return Ie(t,e,n?.variant)},async createSignedUrl(e,n){let r=er(n?.expiresIn);return r===void 0||r<1||r>Xn?{data:null,error:{code:"bad_request",message:`expiresIn is a duration from 1s to 7d, like "15m", "1h" or "7d" (got ${JSON.stringify(n?.expiresIn)})`},status:400}:u(()=>c.storage.createSignedUrl({path:{bucket:t},body:{path:e,expires_in:r}}),s=>({signedUrl:s.url,expiresAt:s.expires_at}))},async list(e,n){let r=n?.limit??Yn,s=n?.offset??0;if(!Number.isInteger(r)||r<0||!Number.isInteger(s)||s<0)return{data:null,error:{code:"bad_request",message:"limit and offset are whole numbers, 0 or more"},status:400};let a=[],l,i=200;try{for(;a.length<r;){let d=Math.max(1,Math.min(Qn,s+r-a.length)),o=await c.storage.listObjects({path:{bucket:t},query:{...e?{prefix:e}:{},limit:d,...l?{cursor:l}:{}}});i=o.status;for(let g of o.data.objects)s>0?s--:a.length<r&&a.push(xe(g));if(l=o.data.next_cursor,!l)break}}catch(d){return T(d)}return{data:a,error:null,status:i}},async remove(e){let n=[];for(let r of e){try{await c.storage.deleteObject({path:{bucket:t,path:r}})}catch(s){return T(s)}n.push({path:r,name:r,bucket:t,size:0,contentType:"",checksum:"",variants:{}})}return{data:n,error:null,status:200}},move(e,n){return u(()=>c.storage.moveObject({path:{bucket:t},body:{from:e,to:n}}),()=>{})},copy(e,n){return u(()=>c.storage.copyObject({path:{bucket:t},body:{from:e,to:n}}),()=>{})}}}var nr={bucket:tr},Te=t=>ne("Storage",t,nr),rr={bucket:t=>Te("bucket").bucket(t),buckets:new Proxy({},{get:(t,e)=>typeof e=="string"?Te("buckets").bucket(e):void 0})},sr=v("Notifications",{push:{send(t){let{to:e,...n}=t,r=typeof e=="string"?{user_ids:[e]}:Array.isArray(e)?{user_ids:e}:{topic:e.topic};return u(()=>c.notify.sendPush({body:{...n,to:r}}),s=>({message_ids:s.message_ids,recipients:s.message_ids.length,skipped_user_ids:s.skipped_user_ids}))}},email:{async send(t){let{to:e,templateSlug:n,...r}=t,s={...r,...n!==void 0?{template:n}:{}};if(!Array.isArray(e))return u(()=>c.notify.sendEmail({body:{...s,to:e}}),i=>({...i.message_id!==void 0?{message_id:i.message_id}:{},...i.skipped?{skipped:!0}:{}}));let a=[],l=202;for(let i of e)try{let d=await c.notify.sendEmail({body:{...s,to:i}});l=d.status,a.push(d.data.message_id??null)}catch(d){return T(d)}return{data:{message_ids:a},error:null,status:l}}}}),Ce=t=>typeof t=="boolean"?t:t!=null&&t!==0&&t!=="",Be=t=>typeof t=="string"?{name:t}:null,Fe=t=>t==="override"?"user":t,ar=t=>t!==null&&typeof t=="object"&&!Array.isArray(t)&&"userId"in t;function $e(){return re.getStore()?.userId}function K(t){let e=t&&"userId"in t?t.userId??void 0:$e();return u(()=>e?c.flags.getUserValues({path:{user_id:e}}):c.flags.getValues(),n=>n.values??{})}var Le={setOverrideForUser:(t,e,n)=>u(()=>c.flags.putUserValue({path:{user_id:t,key:e},body:{value:n}}),r=>({key:r.key,value:r.value,source:Fe(r.source)})),setOverridesForUser:(t,e)=>u(()=>c.flags.putUserValues({path:{user_id:t},body:{values:e}}),n=>({values:n.values??{}})),clearOverrideForUser:(t,e)=>u(()=>c.flags.deleteUserValue({path:{user_id:t,key:e}}),n=>({key:n.key,value:n.value,source:Fe(n.source)})),clearAllOverridesForUser:t=>u(()=>c.flags.deleteUserValues({path:{user_id:t}}),e=>({deleted:e.deleted})),batchSetOverrides:t=>u(()=>c.flags.batchUserValues({body:{operations:t.map(e=>({user_id:e.userId,values:e.values}))}}),e=>({applied:e.applied}))},or=v("Flags",{async isEnabled(t,e){let n=r=>(p.warn(`[palbase] flag "${t}" could not be read (${r}): treating it as off`),!1);try{let r=await K(e);return r.error?n(`${r.error.code}: ${r.error.message}`):Ce(r.data[t])}catch(r){return n(r instanceof Error?r.message:String(r))}},async getVariant(t,e){let n=await K(e);return n.error?{data:null,error:n.error,status:n.status}:{data:Be(n.data[t]),error:null,status:n.status}},async getAll(t){let e=await K(t);return e.error?{data:null,error:e.error,status:e.status}:{data:Object.entries(e.data).map(([n,r])=>{let s=Be(r);return{name:n,enabled:Ce(r),...s?{variant:s}:{}}}),error:null,status:e.status}},async get(t,e,n){let r,s=!1,a;n!==void 0?(r=e,s=!0,a=n):ar(e)?a=e:e!==void 0&&(r=e,s=!0);let l=await K(a);if(l.error)return s?{data:r??null,error:null,status:l.status}:{data:null,error:l.error,status:l.status};let i=l.data[t];return{data:i===void 0?r??null:i,error:null,status:l.status}},async setOverride(t,e){let n=$e();return n?Le.setOverrideForUser(n,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 Le}}),ir=v("Realtime",{broadcast(t,e,n){return u(()=>c.realtime.broadcast({body:{messages:[{topic:t,event:e,payload:n??{}}]}}),()=>{})},state:{set(t,e,n){return u(()=>c.realtime.writeState({body:{ops:[{topic:t,key:e,value:n}]}}),()=>{})},clear(t,e){return u(()=>c.realtime.writeState({body:{ops:[{topic:t,key:e,delete:!0}]}}),()=>{})}}}),lr=v("Commerce",{getSettings(){return u(()=>c.commerce.getCommerceSettings({}),t=>t)},listStores(t){return u(()=>c.commerce.listStores({query:t}),e=>e)},listProducts(t){return u(()=>c.commerce.listProducts({query:t}),e=>e)},createQuickProduct(t){return u(()=>c.commerce.createQuickProduct({body:t}),e=>e)},getOrder(t){return u(()=>c.commerce.getOrder({path:{order_id:t}}),e=>e)},listOrders(t){return u(()=>c.commerce.listOrders({query:t}),e=>e)},listStoreOrders(t){return u(()=>c.commerce.listStoreOrders({query:t}),e=>e)},adjustInventory(t){return u(()=>c.commerce.adjustInventory({body:t}),e=>e)},recomputeBuyBox(t){return u(()=>c.commerce.recomputeVariantBuyBox({path:{variant_id:t}}),e=>e)}}),cr=v("Promotions",{listRules(t){return u(()=>c.commerce.listPromotionRules({query:t}),e=>e)},createRule(t){return u(()=>c.commerce.createPromotionRule({body:t}),e=>e)},evaluate(t){return u(()=>c.commerce.evaluatePromotions({body:t}),e=>e)},hold(t){return u(()=>c.commerce.holdPromotions({body:t}),e=>e)},commitHold(t,e={}){return u(()=>c.commerce.commitPromotionHold({path:{hold_id:t},body:e}),n=>n)},releaseHold(t){return u(()=>c.commerce.releasePromotionHold({path:{hold_id:t}}),e=>e)},reverseRedemption(t){return u(()=>c.commerce.reversePromotionRedemption({path:{redemption_id:t}}),e=>e)}}),ur=v("Campaigns",{listBroadcasts(){return u(()=>c.campaigns.listBroadcasts({}),t=>t)},createBroadcast(t){return u(()=>c.campaigns.createBroadcast({body:t}),e=>e)},startBroadcast(t){return u(()=>c.campaigns.startBroadcast({path:{id:t}}),e=>e)},pauseBroadcast(t){return u(()=>c.campaigns.pauseBroadcast({path:{id:t}}),e=>e)},cancelBroadcast(t){return u(()=>c.campaigns.cancelBroadcast({path:{id:t}}),e=>e)},getBroadcastStats(t){return u(()=>c.campaigns.getBroadcastStats({path:{id:t}}),e=>e)},recordConversion(t){return u(()=>c.campaigns.recordBroadcastConversion({body:t}),e=>e)},listOnSite(){return u(()=>c.campaigns.listOnSiteCampaigns({}),t=>t)},createOnSite(t){return u(()=>c.campaigns.createOnSiteCampaign({body:t}),e=>e)},listTrackingLinks(){return u(()=>c.campaigns.listTrackingLinks({}),t=>t)},createTrackingLink(t){return u(()=>c.campaigns.createTrackingLink({body:t}),e=>e)},attributeLinkConversion(t){return u(()=>c.campaigns.attributeLinkConversion({body:t}),e=>e)}}),dr=v("Journeys",{list(t){return u(()=>c.journeys.listJourneys({query:t}),e=>e)},get(t){return u(()=>c.journeys.getJourney({path:{key:t}}),e=>e)},validate(t){return u(()=>c.journeys.validateJourney({body:{definition:t}}),e=>e)},publish(t){return u(()=>c.journeys.publishJourney({path:{key:t}}),e=>e)},stop(t){return u(()=>c.journeys.stopJourney({path:{key:t}}),e=>e)},listBlueprints(){return u(()=>c.journeys.listBlueprints({}),t=>t)},listStoreBlueprints(t){return u(()=>c.journeys.listStoreBlueprints({path:{store_id:t}}),e=>e)},activateStoreBlueprint(t,e){return u(()=>c.journeys.activateStoreBlueprint({path:{store_id:t},body:e}),n=>n)},deleteStoreBlueprint(t,e){return u(()=>c.journeys.deleteStoreBlueprint({path:{store_id:t,key:e}}),()=>{})}});import{z as Ns}from"zod";export{Ts as AccessRefused,rt as AttestedDevice,je as AuthUnavailable,Pt as Authorize,Ft as BadRequest,ze as Body,Vt as CACHE_MAX_TTL,Gt as Cache,ur as Campaigns,yt as ChatPart,nt as Client,lr as Commerce,Lt as Conflict,L as ContractRunEnded,Ne as Controller,lt as Cron,V as Database,It as DeadlockDetected,Ge as Delete,Ot as DiError,De as EVENT_TYPES,or as Flags,Ct as Forbidden,kt as Gateway,wt as GatewayRefusal,qe as Get,Ye as Headers,$t as HttpError,at as Injectable,dr as Journeys,p as Log,Wt as MAX_BODY_BYTES,q as MigrationRunEnded,ot as Module,Mt as NotFound,sr as Notifications,it as On,vt as OnConnect,Rt as OnDisconnect,At as OnEmpty,St as OnFirst,Ze as OptionalUser,xt as PalError,c as Palbase,O as PalbaseError,Kn as PalbaseFactory,Qe as Param,Ve as Patch,Ke as Post,cr as Promotions,We as Put,He as Query,Je as QueryParams,ir as Realtime,et as Req,tt as RequestId,st as Resolve,j as SchemaNotPushed,Jn as Secrets,Dt as SerializationFailure,rr as Storage,Et as Subscribe,gt as Task,pt as TaskFailure,mt as Tasks,ft as TestUserTemplate,Ue as TokenError,I as TokenVerifier,Ut as TooManyRequests,Tt as Unauthorized,jt as UniqueViolation,ht as Upload,bt as UploadedObject,Xe as User,ct as Webhook,cs as bigint,us as boolean,ds as check,D as createApp,ps as date,Bt as defineError,gs as defineSchema,ms as defineTable,qt as encrypt,Nt as encrypted,fs as enumType,hs as foreignKey,ut as getRegisteredControllers,dt as getRoutes,_t as getWebhookManifest,Bs as increment,bs as index,ys as integer,ws as jsonb,Fs as now,ks as numeric,Ps as ownedByUser,Ss as policy,vs as raw,Rs as sqlType,Kt as t,As as text,Es as timestamp,_s as userRef,Os as uuid,Ns as z};
12
+ `),process.exit(0),new L}let l=Ee(r),i=await _e(l);i&&p.info(`[palbase] strings: ${i.source} and ${i.locales.length-1} other language(s), ${Object.keys(i.strings).length} sentence(s), from ${l}/palbase/strings`),ae(i?void 0:l);let d=e.db?F(e.db):void 0,o=await X({env:r,url:e.palbase?.url,secretKey:e.palbase?.secretKey});o&&p.info(`[palbase] secrets: ${o.loaded.length} from the project's ${o.set} set${o.kept.length>0?`; ${o.kept.join(", ")} kept as the environment gives them`:""}`),o&&o.refused.length>0&&p.warn(`[palbase] secrets not set \u2014 names a process reads as its own, not the app's: ${o.refused.map(P=>JSON.stringify(P)).join(", ")}`);let g=qn(n)||d!==void 0&&N(d),m=ke(e.palbase??{},r,{needsWebhookSecret:g});g&&m.webhookSecret===void 0&&p.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=C({url:m.url,secretKey:m.secretKey}),k=e.port??Number(r.PORT??"8080");if(!Number.isInteger(k)||k<0||k>65535)throw new Error(`[palbase] PORT is a port number, not ${String(e.port??r.PORT)}`);let y=e.db?await ye(e.db,r,m.secretKey,{onPlatform:m.platformSecret!==void 0,embed:we(f),fields:f.fields}):void 0;y&&p.info(`[palbase] database: version ${y.binding.version}`);let R=y&&N(y.model)?{"user.deleted":[P=>Vn(y,P)]}:void 0,w=m.platformSecret===void 0?void 0:{secret:m.platformSecret},h=e.requestTelemetry===!1?void 0:new U(f.analytics),A=()=>D({modules:n,verifier:new I({issuer:m.url,projectId:m.projectId,standing:Y({url:m.url,secretKey:m.secretKey})}),server:f,webhookSecret:m.webhookSecret,env:r,projectId:m.projectId,telemetry:h,auth:e.auth,tokens:e.tokens,rateLimit:e.rateLimit,maxBodyBytes:e.bodyLimit,cors:zn(e.cors,r.PALBASE_WEB_ORIGINS),platform:w,events:R,database:y&&{app:y.app,requests:y.requests,keptAnswers:y.keptAnswers},strings:i}),E=A(),_=e.boot?.attempts??5,b=e.boot?.backoffMs??1e3;for(let P=1;;P++)try{await E.start();break}catch(S){if(P>=_)throw p.error(`[palbase] the app did not start after ${_} attempts`,{error:S}),S;p.warn(`[palbase] the app did not start (attempt ${P} of ${_}); trying again in ${b} ms`,{error:S}),await new Promise(Me=>setTimeout(Me,b)),b*=2,E=A()}return Gn(E,f,k,e.host??"0.0.0.0",e.exitOnFatal??!0,y)}};function Ee(t){let e=t.PALBASE_CONTRACT_ENTRY??process.argv[1];if(!e)return process.cwd();let n=x(Oe(e));for(;!z(J(n,"package.json"))&&x(n)!==n;)n=x(n);return z(J(n,"package.json"))?n:process.cwd()}async function _e(t){try{return await oe(t)}catch(e){throw new Error(`[palbase] the app's strings: ${e instanceof Error?e.message:String(e)}`)}}async function Wn(t,e,n){let r=Oe(n.PALBASE_CONTRACT_ENTRY??process.argv[1]??"");if(!/\.[cm]?tsx?$/.test(r))throw new Error(`the contract is read from the app's TypeScript source, and this run's entry is ${r||"none"}: start it from its source (bun run src/main.ts), or name the source's entry in PALBASE_CONTRACT_ENTRY`);let s=x(r);for(;!z(J(s,"package.json"))&&x(s)!==s;)s=x(s);let{analyzeProject:a}=await import("../chunks/AXANFT2A.js"),{routeContracts:l}=await import("../chunks/SQNAPFXW.js"),i=a(s,r);for(let g of i.warnings)p.warn(`[palbase] the contract: ${g}`);let d="https://contract.palbase.invalid",o=D({modules:t,verifier:new I({issuer:d,projectId:"contract",standing:()=>Promise.reject(new Error("the contract run serves nothing"))}),server:C({url:d,secretKey:"pb_contract_s"}),env:n,projectId:"contract",auth:e.auth,tokens:e.tokens,rateLimit:e.rateLimit,maxBodyBytes:e.bodyLimit,cors:e.cors,contractOnly:{database:e.db!==void 0,routes:await l(i.routes),errors:se()},events:e.db&&N(F(e.db))?{"user.deleted":[]}:void 0});return JSON.stringify(o.contract())}var L=class extends Error{constructor(){super("[palbase] the contract run ended"),this.name="ContractRunEnded"}},q=class extends Error{code;constructor(e){super(`[palbase] the migration run ended with ${e}`),this.name="MigrationRunEnded",this.code=e}};async function Vn(t,e){let n=e.data?.user_id;if(typeof n!="string"||n==="")throw new Error("[palbase] user.deleted without a user_id");let r=await t.forget(n,V.$asService());p.info(`[palbase] user ${n} deleted: ${r.deleted} row(s) gone, ${r.detached} forgot them${r.relationships===void 0?"":`, ${r.relationships} relationship(s) of the access schema taken back`}`)}async function Gn(t,e,n,r,s,a){let l,i={on:!1},d=(w,h)=>new URL(w.url).pathname===Nn&&w.method==="GET"?Promise.resolve(i.on?Response.json({ok:!1,stopping:!0},{status:503}):Response.json({ok:!0})):t.handle(w,h),o=Dn((w,h)=>{Hn(d,w,h,i).finally(()=>{i.on&&o.closeIdleConnections()})});o.keepAliveTimeout=29e4,o.headersTimeout=3e5;try{await new Promise((w,h)=>{o.once("error",h),o.listen(n,r,()=>w())})}catch(w){throw await t.stop(),await a?.close(),w}let g=o.address().port;p.info(`[palbase] serving ${t.routes.length} route(s) on :${g}`,{routes:t.routes}),a?.search?.start();let m=w=>l??=(async()=>{p.info("[palbase] stopping: finishing the requests in flight"),i.on=!0;let h=new Promise(E=>o.close(()=>E()));o.closeIdleConnections();let A=setTimeout(()=>o.closeAllConnections(),w);await h,clearTimeout(A),process.off("SIGINT",y),process.off("uncaughtException",R),process.off("unhandledRejection",R);try{await t.stop(),await a?.search?.stop(),await a?.close()}finally{process.off("SIGTERM",y)}})(),f=()=>m(Re),k=!1,y=()=>{if(k){p.info("[palbase] stopping: told to stop again; the requests in flight are still being finished");return}k=!0;let w=setTimeout(()=>{p.error("[palbase] stopping took longer than it is given; the process ends"),process.exit(1)},Re+jn);w.unref(),f().then(()=>{clearTimeout(w),process.exit(0)},h=>{clearTimeout(w),p.error("[palbase] stopping failed; the process ends",{error:h}),process.exit(1)})},R=w=>{p.error("[palbase] the app crashed; stopping so the machine starts it again",{error:w});let h=setTimeout(()=>process.exit(1),Ae+1e3);m(Ae).finally(()=>{clearTimeout(h),process.exit(1)})};return process.on("SIGTERM",y),process.once("SIGINT",y),s&&(process.on("uncaughtException",R),process.on("unhandledRejection",R)),{routes:t.routes,palbase:e,port:g,handle:d,close:f}}async function Hn(t,e,n,r){try{let s=e.url??"/",a;try{if(!s.startsWith("/"))throw new TypeError("the request target is not a path");a=new URL(`http://localhost${s}`)}catch{n.statusCode=400,n.end();return}let l=new Headers;for(let[m,f]of Object.entries(e.headers))if(f!==void 0)if(Array.isArray(f))for(let k of f)l.append(m,k);else l.set(m,f);let i=e.method!=="GET"&&e.method!=="HEAD",d=new AbortController;n.on("close",()=>{n.writableFinished||d.abort(new Error("the client closed the connection"))});let o=new Request(a,{method:e.method,headers:l,body:i?Un.toWeb(e):void 0,duplex:"half",signal:d.signal}),g=await t(o,{remoteAddress:e.socket.remoteAddress,target:s});if(n.statusCode=g.status,g.headers.forEach((m,f)=>n.setHeader(f,m)),r.on&&n.setHeader("connection","close"),g.body)for await(let m of g.body)n.write(m);n.end()}catch(s){p.error("[palbase] the request could not be answered",{error:s}),n.headersSent||(n.statusCode=500),n.end()}}function zn(t,e,n=r=>console.warn(r)){let r=(e??"").split(",").map(i=>i.trim()).filter(i=>i!=="");if(r.length===0||t?.origins==="*")return t;let s=r.filter(i=>G(i)),a=r.filter(i=>!G(i));a.length>0&&n(`[palbase] the project's web origins ${a.map(i=>JSON.stringify(i)).join(", ")} are not CORS origins (https://host[:port], http only for localhost): browsers there are not let in`);let l=[...new Set([...t?.origins??[],...s])];return l.length===0?t:{...t,origins:l}}import{bigint as cs,boolean as us,check as ds,date as ps,defineSchema as gs,defineTable as ms,enumType as fs,foreignKey as hs,index as bs,integer as ys,jsonb as ws,numeric as ks,ownedByUser as Ps,policy as Ss,raw as vs,sqlType as Rs,text as As,timestamp as Es,userRef as _s,uuid as Os}from"palgres/dsl";import{AccessRefused as Ts}from"palgres";import{increment as Bs,now as Fs}from"palgres";function T(t){if(t instanceof O)return{data:null,error:{code:t.code,message:t.message},status:t.status};throw t}async function u(t,e){try{let n=await t();return{data:await e(n.data),error:null,status:n.status}}catch(n){return T(n)}}var Jn=v("Secrets",{async get(t){if(Q(t))return null;let e=process.env[t];return typeof e=="string"&&e!==""?e:null}}),Yn=100,Qn=1e3,Xn=168*3600,Zn={s:1,m:60,h:3600,d:86400};function er(t){let e=String(t).trim();if(!/^(\d+(\.\d+)?[dhms])+$/.test(e))return;let n=0;for(let[,r,,s]of e.matchAll(/(\d+(\.\d+)?)([dhms])/g))n+=Math.round(Number(r)*Zn[s]*1e3);return Math.ceil(n/1e3)}function Ie(t,e,n){let r="getPublicUrl",s;try{s=String(e).split("/").map(l=>W(r,"path",l)).join("%2F")}catch(l){throw l instanceof O&&l.code==="invalid_path_parameter"?new O({op:r,status:0,code:"invalid_path_parameter",message:`${r}: the object path ${JSON.stringify(e)} has an empty, "." or ".." segment: storage keeps no such object`}):l}let a=`${c.url}/storage/public/${W(r,"bucket",t)}/${s}`;return n?`${a}?variant=${encodeURIComponent(n)}`:a}function xe(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,Ie(t.bucket,t.path,e)]))}}function tr(t){return{async upload(e,n,r){let s=r?.contentType??(n instanceof Blob&&n.type!==""?n.type:void 0);try{let a=await c.storage.putObject({path:{bucket:t,path:e},headers:r?.upsert?void 0:{"If-None-Match":"*"},body:n,contentType:s});return{data:xe(a.data),error:null,status:a.status}}catch(a){return a instanceof O&&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}:T(a)}},async download(e){try{let n=await c.storage.getObject({path:{bucket:t,path:e}});if(n.status===304)throw new Error("storage answered 304 to a read that sent no entity tag");let r=n.data;try{return{data:await r.blob(),error:null,status:n.status}}catch(s){return{data:null,error:{code:"network_error",message:`the object's bytes stopped arriving: ${s instanceof Error?s.message:String(s)}`},status:0}}}catch(n){return T(n)}},getPublicUrl(e,n){return Ie(t,e,n?.variant)},async createSignedUrl(e,n){let r=er(n?.expiresIn);return r===void 0||r<1||r>Xn?{data:null,error:{code:"bad_request",message:`expiresIn is a duration from 1s to 7d, like "15m", "1h" or "7d" (got ${JSON.stringify(n?.expiresIn)})`},status:400}:u(()=>c.storage.createSignedUrl({path:{bucket:t},body:{path:e,expires_in:r}}),s=>({signedUrl:s.url,expiresAt:s.expires_at}))},async list(e,n){let r=n?.limit??Yn,s=n?.offset??0;if(!Number.isInteger(r)||r<0||!Number.isInteger(s)||s<0)return{data:null,error:{code:"bad_request",message:"limit and offset are whole numbers, 0 or more"},status:400};let a=[],l,i=200;try{for(;a.length<r;){let d=Math.max(1,Math.min(Qn,s+r-a.length)),o=await c.storage.listObjects({path:{bucket:t},query:{...e?{prefix:e}:{},limit:d,...l?{cursor:l}:{}}});i=o.status;for(let g of o.data.objects)s>0?s--:a.length<r&&a.push(xe(g));if(l=o.data.next_cursor,!l)break}}catch(d){return T(d)}return{data:a,error:null,status:i}},async remove(e){let n=[];for(let r of e){try{await c.storage.deleteObject({path:{bucket:t,path:r}})}catch(s){return T(s)}n.push({path:r,name:r,bucket:t,size:0,contentType:"",checksum:"",variants:{}})}return{data:n,error:null,status:200}},move(e,n){return u(()=>c.storage.moveObject({path:{bucket:t},body:{from:e,to:n}}),()=>{})},copy(e,n){return u(()=>c.storage.copyObject({path:{bucket:t},body:{from:e,to:n}}),()=>{})}}}var nr={bucket:tr},Te=t=>ne("Storage",t,nr),rr={bucket:t=>Te("bucket").bucket(t),buckets:new Proxy({},{get:(t,e)=>typeof e=="string"?Te("buckets").bucket(e):void 0})},sr=v("Notifications",{push:{send(t){let{to:e,...n}=t,r=typeof e=="string"?{user_ids:[e]}:Array.isArray(e)?{user_ids:e}:{topic:e.topic};return u(()=>c.notify.sendPush({body:{...n,to:r}}),s=>({message_ids:s.message_ids,recipients:s.message_ids.length,skipped_user_ids:s.skipped_user_ids}))}},email:{async send(t){let{to:e,templateSlug:n,...r}=t,s={...r,...n!==void 0?{template:n}:{}};if(!Array.isArray(e))return u(()=>c.notify.sendEmail({body:{...s,to:e}}),i=>({...i.message_id!==void 0?{message_id:i.message_id}:{},...i.skipped?{skipped:!0}:{}}));let a=[],l=202;for(let i of e)try{let d=await c.notify.sendEmail({body:{...s,to:i}});l=d.status,a.push(d.data.message_id??null)}catch(d){return T(d)}return{data:{message_ids:a},error:null,status:l}}}}),Ce=t=>typeof t=="boolean"?t:t!=null&&t!==0&&t!=="",Be=t=>typeof t=="string"?{name:t}:null,Fe=t=>t==="override"?"user":t,ar=t=>t!==null&&typeof t=="object"&&!Array.isArray(t)&&"userId"in t;function $e(){return re.getStore()?.userId}function K(t){let e=t&&"userId"in t?t.userId??void 0:$e();return u(()=>e?c.flags.getUserValues({path:{user_id:e}}):c.flags.getValues(),n=>n.values??{})}var Le={setOverrideForUser:(t,e,n)=>u(()=>c.flags.putUserValue({path:{user_id:t,key:e},body:{value:n}}),r=>({key:r.key,value:r.value,source:Fe(r.source)})),setOverridesForUser:(t,e)=>u(()=>c.flags.putUserValues({path:{user_id:t},body:{values:e}}),n=>({values:n.values??{}})),clearOverrideForUser:(t,e)=>u(()=>c.flags.deleteUserValue({path:{user_id:t,key:e}}),n=>({key:n.key,value:n.value,source:Fe(n.source)})),clearAllOverridesForUser:t=>u(()=>c.flags.deleteUserValues({path:{user_id:t}}),e=>({deleted:e.deleted})),batchSetOverrides:t=>u(()=>c.flags.batchUserValues({body:{operations:t.map(e=>({user_id:e.userId,values:e.values}))}}),e=>({applied:e.applied}))},or=v("Flags",{async isEnabled(t,e){let n=r=>(p.warn(`[palbase] flag "${t}" could not be read (${r}): treating it as off`),!1);try{let r=await K(e);return r.error?n(`${r.error.code}: ${r.error.message}`):Ce(r.data[t])}catch(r){return n(r instanceof Error?r.message:String(r))}},async getVariant(t,e){let n=await K(e);return n.error?{data:null,error:n.error,status:n.status}:{data:Be(n.data[t]),error:null,status:n.status}},async getAll(t){let e=await K(t);return e.error?{data:null,error:e.error,status:e.status}:{data:Object.entries(e.data).map(([n,r])=>{let s=Be(r);return{name:n,enabled:Ce(r),...s?{variant:s}:{}}}),error:null,status:e.status}},async get(t,e,n){let r,s=!1,a;n!==void 0?(r=e,s=!0,a=n):ar(e)?a=e:e!==void 0&&(r=e,s=!0);let l=await K(a);if(l.error)return s?{data:r??null,error:null,status:l.status}:{data:null,error:l.error,status:l.status};let i=l.data[t];return{data:i===void 0?r??null:i,error:null,status:l.status}},async setOverride(t,e){let n=$e();return n?Le.setOverrideForUser(n,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 Le}}),ir=v("Realtime",{broadcast(t,e,n){return u(()=>c.realtime.broadcast({body:{messages:[{topic:t,event:e,payload:n??{}}]}}),()=>{})},state:{set(t,e,n){return u(()=>c.realtime.writeState({body:{ops:[{topic:t,key:e,value:n}]}}),()=>{})},clear(t,e){return u(()=>c.realtime.writeState({body:{ops:[{topic:t,key:e,delete:!0}]}}),()=>{})}}}),lr=v("Commerce",{getSettings(){return u(()=>c.commerce.getCommerceSettings({}),t=>t)},listStores(t){return u(()=>c.commerce.listStores({query:t}),e=>e)},listProducts(t){return u(()=>c.commerce.listProducts({query:t}),e=>e)},createQuickProduct(t){return u(()=>c.commerce.createQuickProduct({body:t}),e=>e)},getOrder(t){return u(()=>c.commerce.getOrder({path:{order_id:t}}),e=>e)},listOrders(t){return u(()=>c.commerce.listOrders({query:t}),e=>e)},listStoreOrders(t){return u(()=>c.commerce.listStoreOrders({query:t}),e=>e)},adjustInventory(t){return u(()=>c.commerce.adjustInventory({body:t}),e=>e)},recomputeBuyBox(t){return u(()=>c.commerce.recomputeVariantBuyBox({path:{variant_id:t}}),e=>e)}}),cr=v("Promotions",{listRules(t){return u(()=>c.commerce.listPromotionRules({query:t}),e=>e)},createRule(t){return u(()=>c.commerce.createPromotionRule({body:t}),e=>e)},evaluate(t){return u(()=>c.commerce.evaluatePromotions({body:t}),e=>e)},hold(t){return u(()=>c.commerce.holdPromotions({body:t}),e=>e)},commitHold(t,e={}){return u(()=>c.commerce.commitPromotionHold({path:{hold_id:t},body:e}),n=>n)},releaseHold(t){return u(()=>c.commerce.releasePromotionHold({path:{hold_id:t}}),e=>e)},reverseRedemption(t){return u(()=>c.commerce.reversePromotionRedemption({path:{redemption_id:t}}),e=>e)}}),ur=v("Campaigns",{listBroadcasts(){return u(()=>c.campaigns.listBroadcasts({}),t=>t)},createBroadcast(t){return u(()=>c.campaigns.createBroadcast({body:t}),e=>e)},startBroadcast(t){return u(()=>c.campaigns.startBroadcast({path:{id:t}}),e=>e)},pauseBroadcast(t){return u(()=>c.campaigns.pauseBroadcast({path:{id:t}}),e=>e)},cancelBroadcast(t){return u(()=>c.campaigns.cancelBroadcast({path:{id:t}}),e=>e)},getBroadcastStats(t){return u(()=>c.campaigns.getBroadcastStats({path:{id:t}}),e=>e)},recordConversion(t){return u(()=>c.campaigns.recordBroadcastConversion({body:t}),e=>e)},listOnSite(){return u(()=>c.campaigns.listOnSiteCampaigns({}),t=>t)},createOnSite(t){return u(()=>c.campaigns.createOnSiteCampaign({body:t}),e=>e)},listTrackingLinks(){return u(()=>c.campaigns.listTrackingLinks({}),t=>t)},createTrackingLink(t){return u(()=>c.campaigns.createTrackingLink({body:t}),e=>e)},attributeLinkConversion(t){return u(()=>c.campaigns.attributeLinkConversion({body:t}),e=>e)}}),dr=v("Journeys",{list(t){return u(()=>c.journeys.listJourneys({query:t}),e=>e)},get(t){return u(()=>c.journeys.getJourney({path:{key:t}}),e=>e)},validate(t){return u(()=>c.journeys.validateJourney({body:{definition:t}}),e=>e)},publish(t){return u(()=>c.journeys.publishJourney({path:{key:t}}),e=>e)},stop(t){return u(()=>c.journeys.stopJourney({path:{key:t}}),e=>e)},listBlueprints(){return u(()=>c.journeys.listBlueprints({}),t=>t)},listStoreBlueprints(t){return u(()=>c.journeys.listStoreBlueprints({path:{store_id:t}}),e=>e)},activateStoreBlueprint(t,e){return u(()=>c.journeys.activateStoreBlueprint({path:{store_id:t},body:e}),n=>n)},deleteStoreBlueprint(t,e){return u(()=>c.journeys.deleteStoreBlueprint({path:{store_id:t,key:e}}),()=>{})}});import{z as Ns}from"zod";export{Ts as AccessRefused,rt as AttestedDevice,je as AuthUnavailable,Pt as Authorize,Ft as BadRequest,ze as Body,Vt as CACHE_MAX_TTL,Gt as Cache,ur as Campaigns,yt as ChatPart,nt as Client,lr as Commerce,Lt as Conflict,L as ContractRunEnded,Ne as Controller,lt as Cron,V as Database,It as DeadlockDetected,Ge as Delete,Ot as DiError,De as EVENT_TYPES,or as Flags,Ct as Forbidden,kt as Gateway,wt as GatewayRefusal,qe as Get,Ye as Headers,$t as HttpError,at as Injectable,dr as Journeys,p as Log,Wt as MAX_BODY_BYTES,q as MigrationRunEnded,ot as Module,Mt as NotFound,sr as Notifications,it as On,vt as OnConnect,Rt as OnDisconnect,At as OnEmpty,St as OnFirst,Ze as OptionalUser,xt as PalError,c as Palbase,O as PalbaseError,Kn as PalbaseFactory,Qe as Param,Ve as Patch,Ke as Post,cr as Promotions,We as Put,He as Query,Je as QueryParams,ir as Realtime,et as Req,tt as RequestId,st as Resolve,j as SchemaNotPushed,Jn as Secrets,Dt as SerializationFailure,rr as Storage,Et as Subscribe,gt as Task,pt as TaskFailure,mt as Tasks,ft as TestUserTemplate,Ue as TokenError,I as TokenVerifier,Ut as TooManyRequests,Tt as Unauthorized,jt as UniqueViolation,ht as Upload,bt as UploadedObject,Xe as User,ct as Webhook,cs as bigint,us as boolean,ds as check,D as createApp,ps as date,Bt as defineError,gs as defineSchema,ms as defineTable,qt as encrypt,Nt as encrypted,fs as enumType,hs as foreignKey,ut as getRegisteredControllers,dt as getRoutes,_t as getWebhookManifest,Bs as increment,bs as index,ys as integer,ws as jsonb,Fs as now,ks as numeric,Ps as ownedByUser,Ss as policy,vs as raw,Rs as sqlType,Kt as t,As as text,Es as timestamp,_s as userRef,Os as uuid,Ns as z};
@@ -1 +1 @@
1
- /*! palbase 0.73.0 — Palbase SDK License (see LICENSE) */
1
+ /*! palbase 0.73.1 — Palbase SDK License (see LICENSE) */
@@ -1,2 +1,2 @@
1
- /*! palbase 0.73.0 — Palbase SDK License (see LICENSE) */
2
- import{b as l,c as g,d as f,e as m}from"../chunks/EKOEK6LR.js";import{a as u}from"../chunks/LCDNCPQW.js";import{c,i as p}from"../chunks/PAQCJT7M.js";import"../chunks/CY6KUFZW.js";import"../chunks/VEL7X2G3.js";import"../chunks/5OOA4R4H.js";import"../chunks/25HECIZY.js";import"../chunks/SMECWMF7.js";import"../chunks/YMIK6HLK.js";import"../chunks/PEQZDT6P.js";import"../chunks/J7ZNBBRN.js";import"../chunks/P36C47FS.js";import"reflect-metadata";import{randomUUID as y}from"node:crypto";import{createFakeClient as w,typedDatabase as h}from"palgres/testing";function b(s,t,e){if(e?.acceptLanguage!==void 0&&e.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:n,...o}=s,a=e?.strings;return c.run({requestId:`test_${y()}`,database:n===void 0?void 0:d(n),services:o,...a!==void 0?{strings:a,locales:p(e?.acceptLanguage??null,a.source),usedLocales:[]}:{}},t)}function T(){let s=new Map,t=new Map,e=[],n=a=>{if(s.has(a))return s.get(a);if(t.has(a))return t.get(a);if(e.includes(a)){let r=[...e.slice(e.indexOf(a)),a].map(i=>i.name??String(i));throw new TypeError(`isolated(): ${r.join(" \u2192 ")} needs itself to be built \u2014 give one of them with .with(Token, value)`)}e.push(a);try{let r=Reflect.getMetadata("design:paramtypes",a)??[],i=new a(...r.map(n));return t.set(a,i),i}finally{e.pop()}},o={with(a,r){return s.set(a,r),o},get:a=>n(a)};return o}var k="a database in memory keeps rows, not relationships, and answers no access question \u2014 give it the schema (fakeDatabase({ access: <the schema file's text> })), or test what asks Database.$access against Postgres; the schema itself is held to its expectations with `palbase access:test`";function d(s){let t=s.access;return h(s,t===void 0?{unanswered:k}:{access:t.names,via:t.via,as:"authenticated"})}function v(s={}){let t=w(s);return{db:d(t),raw:t,queries:t.queries,seed:(e,n)=>t.seed(e,n),inserted:e=>t.inserted(e),updated:e=>t.updated(e),deleted:e=>t.deleted(e),signedInAs(e){if(!t.access)throw new TypeError("fakeDatabase().signedInAs: this database was made without an access schema \u2014 fakeDatabase({ access: <the schema file's text> })");t.access.signedInAs(e)}}}export{l as TestApiError,m as api,g as createTestApi,v as fakeDatabase,T as isolated,u as loadStringsTable,f as testRun,b as withServices};
1
+ /*! palbase 0.73.1 — Palbase SDK License (see LICENSE) */
2
+ import{b as l,c as g,d as f,e as m}from"../chunks/5N6QKGPA.js";import{a as u}from"../chunks/HYPCFC4K.js";import{c,i as p}from"../chunks/4E4ABCSD.js";import"../chunks/VCL3SAQL.js";import"../chunks/MFSC4OJV.js";import"../chunks/MB7MHOQO.js";import"../chunks/U3H6HER3.js";import"../chunks/UXHNXE3J.js";import"../chunks/3KCV4F4F.js";import"../chunks/HRWVZ4PC.js";import"../chunks/W2KD2I4Q.js";import"../chunks/DNSLYLU6.js";import"reflect-metadata";import{randomUUID as y}from"node:crypto";import{createFakeClient as w,typedDatabase as h}from"palgres/testing";function b(s,t,e){if(e?.acceptLanguage!==void 0&&e.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:n,...o}=s,a=e?.strings;return c.run({requestId:`test_${y()}`,database:n===void 0?void 0:d(n),services:o,...a!==void 0?{strings:a,locales:p(e?.acceptLanguage??null,a.source),usedLocales:[]}:{}},t)}function T(){let s=new Map,t=new Map,e=[],n=a=>{if(s.has(a))return s.get(a);if(t.has(a))return t.get(a);if(e.includes(a)){let r=[...e.slice(e.indexOf(a)),a].map(i=>i.name??String(i));throw new TypeError(`isolated(): ${r.join(" \u2192 ")} needs itself to be built \u2014 give one of them with .with(Token, value)`)}e.push(a);try{let r=Reflect.getMetadata("design:paramtypes",a)??[],i=new a(...r.map(n));return t.set(a,i),i}finally{e.pop()}},o={with(a,r){return s.set(a,r),o},get:a=>n(a)};return o}var k="a database in memory keeps rows, not relationships, and answers no access question \u2014 give it the schema (fakeDatabase({ access: <the schema file's text> })), or test what asks Database.$access against Postgres; the schema itself is held to its expectations with `palbase access:test`";function d(s){let t=s.access;return h(s,t===void 0?{unanswered:k}:{access:t.names,via:t.via,as:"authenticated"})}function v(s={}){let t=w(s);return{db:d(t),raw:t,queries:t.queries,seed:(e,n)=>t.seed(e,n),inserted:e=>t.inserted(e),updated:e=>t.updated(e),deleted:e=>t.deleted(e),signedInAs(e){if(!t.access)throw new TypeError("fakeDatabase().signedInAs: this database was made without an access schema \u2014 fakeDatabase({ access: <the schema file's text> })");t.access.signedInAs(e)}}}export{l as TestApiError,m as api,g as createTestApi,v as fakeDatabase,T as isolated,u as loadStringsTable,f as testRun,b as withServices};
@@ -1,5 +1,5 @@
1
- /*! palbase 0.73.0 — Palbase SDK License (see LICENSE) */
2
- import{p as R,t as Y,u as k}from"./4XSSQAES.js";var $=40,z=`
1
+ /*! palbase 0.73.1 — Palbase SDK License (see LICENSE) */
2
+ import{p as R,t as Y,u as k}from"./SS2RVI27.js";var $=40,z=`
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.73.0 — Palbase SDK License (see LICENSE) */
2
- import{b as c,f as u}from"./PEQZDT6P.js";var l={attempts:3,maxWaitSeconds:30},y=new Set([429,502,503,504]);function x(e,t=l){let r=t.sleep??h;return{async send(o){let n=p(o),a=n.body,m=!a||a.kind!=="raw"||u(a.value),f=(n.method==="GET"||n.method==="HEAD"||n.idempotent===!0)&&m;for(let i=1;;i++)try{return await e.send(n)}catch(s){if(!f||i>=t.attempts||!(s instanceof c)||n.signal?.aborted)throw s;let d=b(s,i,t.maxWaitSeconds);if(d===void 0)throw s;await r(d*1e3,n.signal)}}}}function p(e){return e.idempotent?Object.entries(e.headers??{}).some(([r,o])=>r.toLowerCase()==="idempotency-key"&&o!==void 0&&o!==null&&o!=="")?e:{...e,headers:{...e.headers,"Idempotency-Key":w()}}:e}function b(e,t,r){return y.has(e.status)||e.code==="network_error"?e.retryAfter!==void 0?e.retryAfter<=r?e.retryAfter:void 0:Math.min(.5*2**(t-1),r)*(.8+Math.random()*.4):void 0}function h(e,t){return new Promise((r,o)=>{if(t?.aborted)return o(t.reason);let n=()=>{clearTimeout(a),o(t?.reason)},a=setTimeout(()=>{t?.removeEventListener("abort",n),r()},e);t?.addEventListener("abort",n,{once:!0})})}function w(){if(typeof crypto.randomUUID=="function")return crypto.randomUUID();let e=crypto.getRandomValues(new Uint8Array(16));e[6]=e[6]&15|64,e[8]=e[8]&63|128;let t=[...e].map(r=>r.toString(16).padStart(2,"0")).join("");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}export{l as a,x as b,b as c,w as d};
1
+ /*! palbase 0.73.1 — Palbase SDK License (see LICENSE) */
2
+ import{b as c,f as u}from"./HRWVZ4PC.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,4 +1,4 @@
1
- /*! palbase 0.73.0 — Palbase SDK License (see LICENSE) */
2
- import{g as m}from"./CY6KUFZW.js";import{AsyncLocalStorage as O}from"node:async_hooks";function h(n,e){return new Proxy(e,{get(s,t,i){if(c.getStore()?.services===void 0)return Reflect.get(s,t,i);let o=R(n,t,s),r=o[t];return typeof r=="function"?r.bind(o):r}})}function R(n,e,s){let t=c.getStore()?.services;if(t===void 0)return s;let i=t[n];if(i!==void 0)return i;if(n==="Log"||typeof e=="symbol"||e==="then")return s;throw new Error(`${n}.${String(e)} was read, but this test did not provide ${n}. Pass it: withServices({ ${n}: \u2026 }, () => \u2026)`)}var P=Symbol.for("palbase.backend.requestScope"),c=globalThis[P]??=new O,d,w,E,G={get ai(){if(!d)throw new Error("Palbase.ai is called before the app is served (serve() binds it)");return d.ai}};function H(n){d=n}function F(n){w=n}var T=h("Gateways",{to(n,e){if(!w)throw new Error("Palbase.gateways is reached before the app is served (createApp() binds it)");return w.to(n,e)}}),Z=new Proxy({},{get(n,e){if(e==="gateways")return T;if(e==="ai")return E??=m({server:G});if(!d)throw new Error(`Palbase.${String(e)} is reached before the app is served (serve() binds it)`);return d[e]}}),B=new Proxy({},{get(n,e){let s=c.getStore(),t=s?.database;if(!t)throw new Error(s?.services?`Database.${String(e)} was read, and this test gave no Database: withServices({ Database: fake.raw }, \u2026)`:s?`Database.${String(e)}: this app declares no database \u2014 PalbaseFactory.create(\u2026, { db: { schemas } })`:`Database.${String(e)} is reached outside a request: it is the request's transaction, reached from a handler, a service it calls or an @On`);let i=t[e];return typeof i=="function"?i.bind(t):i}});function l(n,e,s){let t={time:new Date().toISOString(),level:n,msg:e},i=c.getStore();if(i&&(t.request_id=i.requestId),s)for(let[r,a]of Object.entries(s))t[r]=a instanceof Error?{name:a.name,message:a.message,stack:a.stack}:a;let o=k(t);n==="error"||n==="warn"?process.stderr.write(`${o}
1
+ /*! palbase 0.73.1 — Palbase SDK License (see LICENSE) */
2
+ import{g as m}from"./VCL3SAQL.js";import{AsyncLocalStorage as O}from"node:async_hooks";function h(n,e){return new Proxy(e,{get(s,t,i){if(c.getStore()?.services===void 0)return Reflect.get(s,t,i);let o=R(n,t,s),r=o[t];return typeof r=="function"?r.bind(o):r}})}function R(n,e,s){let t=c.getStore()?.services;if(t===void 0)return s;let i=t[n];if(i!==void 0)return i;if(n==="Log"||typeof e=="symbol"||e==="then")return s;throw new Error(`${n}.${String(e)} was read, but this test did not provide ${n}. Pass it: withServices({ ${n}: \u2026 }, () => \u2026)`)}var P=Symbol.for("palbase.backend.requestScope"),c=globalThis[P]??=new O,d,w,E,G={get ai(){if(!d)throw new Error("Palbase.ai is called before the app is served (serve() binds it)");return d.ai}};function H(n){d=n}function F(n){w=n}var T=h("Gateways",{to(n,e){if(!w)throw new Error("Palbase.gateways is reached before the app is served (createApp() binds it)");return w.to(n,e)}}),Z=new Proxy({},{get(n,e){if(e==="gateways")return T;if(e==="ai")return E??=m({server:G});if(!d)throw new Error(`Palbase.${String(e)} is reached before the app is served (serve() binds it)`);return d[e]}}),B=new Proxy({},{get(n,e){let s=c.getStore(),t=s?.database;if(!t)throw new Error(s?.services?`Database.${String(e)} was read, and this test gave no Database: withServices({ Database: fake.raw }, \u2026)`:s?`Database.${String(e)}: this app declares no database \u2014 PalbaseFactory.create(\u2026, { db: { schemas } })`:`Database.${String(e)} is reached outside a request: it is the request's transaction, reached from a handler, a service it calls or an @On`);let i=t[e];return typeof i=="function"?i.bind(t):i}});function l(n,e,s){let t={time:new Date().toISOString(),level:n,msg:e},i=c.getStore();if(i&&(t.request_id=i.requestId),s)for(let[r,a]of Object.entries(s))t[r]=a instanceof Error?{name:a.name,message:a.message,stack:a.stack}:a;let o=k(t);n==="error"||n==="warn"?process.stderr.write(`${o}
3
3
  `):process.stdout.write(`${o}
4
4
  `)}function k(n){try{return JSON.stringify(n)}catch{let e=new WeakSet;try{return JSON.stringify(n,(s,t)=>{if(typeof t=="bigint")return t.toString();if(typeof t=="object"&&t!==null){if(e.has(t))return"[circular]";e.add(t)}return t})}catch{return JSON.stringify({time:n.time,level:n.level,msg:n.msg,request_id:n.request_id,unwritable:"a field of this line could not be written"})}}}var v=h("Log",{debug:(n,e)=>l("debug",n,e),info:(n,e)=>l("info",n,e),warn:(n,e)=>l("warn",n,e),error:(n,e)=>l("error",n,e)});var L=512,_=8,q=64,D=/^[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$/,S={"i-klingon":"tlh","en-gb-oed":"en-GB-oxendict","sgn-be-fr":"sfb","zh-cmn-hans":"cmn-Hans","zh-yue":"yue","hy-arevela":"hy-arevela"};function $(n){let e=n.indexOf("-");return e>0?n.slice(0,e):n}function j(n){let e=n.split("-"),s=(e[0]??"").toLowerCase();return s==="mo"&&e.length===1?"ro-MD":s==="tl"?(e[0]="fil",e.join("-")):s==="sh"?(e[0]="sr",e.length>1&&/^[A-Za-z]{4}$/.test(e[1]??"")||e.splice(1,0,"Latn"),e.join("-")):n}function I(n){let e=n.trim().replaceAll("_","-");if(e===""||e==="*"||e.length>q)return;let s=e.toLowerCase(),t=Object.hasOwn(S,s)?S[s]:void 0;if(t===void 0){try{t=Intl.getCanonicalLocales(j(e))[0]}catch{return}if(t===void 0)return}let i=$(t);if(!(i===""||i==="und"||i==="mul"))return t}function z(n){let e=n.split("-"),s=e.findIndex((r,a)=>a>0&&r.length===1),t=s>0?e.slice(0,s):e,i=[],o=r=>{i.includes(r)||i.push(r)};for(let r=t.length;r>1||r===t.length;r--)o(t.slice(0,r).join("-"));if(!t.slice(1).some(r=>/^[A-Za-z]{4}$/.test(r)))try{let r=new Intl.Locale(t.join("-")).maximize().script;r&&o(`${t[0]}-${r}`)}catch{}return o(t[0]),i}function Y(n,e){let s=[],t=i=>{i!==""&&!s.includes(i)&&s.push(i)};if(n!==null&&n.length<=L){let i=[];for(let o of n.split(",")){let r=o.trim();if(r==="")continue;let a=1,f=r.indexOf(";");if(f>=0){let A=r.slice(f+1);r=r.slice(0,f).trim();for(let p of A.split(";")){let b=p.indexOf("=");if(b<0||p.slice(0,b).trim().toLowerCase()!=="q")continue;let y=p.slice(b+1).trim(),g=D.test(y)?Number(y):Number.NaN;a=Number.isFinite(g)&&g>=0&&g<=1?g:0}}a>0&&i.push({tag:r,q:a,at:i.length})}i.sort((o,r)=>r.q-o.q||o.at-r.at);for(let{tag:o}of i.slice(0,_)){let r=I(o);if(r!==void 0)for(let a of z(r))t(a)}}return e!==void 0&&e!==""&&t(e),s}function N(n,e,s){let t=n.strings??{},i=Object.hasOwn(t,e)?t[e]:null;for(let o of s){if(o===n.source)break;let r=i!=null&&Object.hasOwn(i,o)?i[o]:void 0;if(typeof r=="string"&&r!=="")return{text:r,locale:o}}return{text:e,locale:n.source}}var C=/\{\{\s*([A-Za-z_][A-Za-z0-9_]*)\s*\}\}/g;function x(n,e){return n.replace(C,(s,t,i,o)=>{if(o[i-1]==="{"||o[i+s.length]==="}")return s;let r=e!==void 0&&Object.hasOwn(e,t)?e[t]:void 0;return r==null?"":String(r)})}var u;function W(n){u=n===void 0?void 0:{root:n,said:!1}}function Q(n,e){let s=c.getStore(),t=s?.strings;if(t===void 0)return u&&!u.said&&s?.services===void 0&&(u.said=!0,v.warn(`[palbase] t(): the app has no palbase/strings (looked in ${u.root}) \u2014 every sentence is said as it is written. \`npx palbase strings\` starts the table; an image takes it with COPY palbase ./palbase`)),x(n,e);let{text:i,locale:o}=N(t,n,s?.locales??[t.source]),r=s?.usedLocales;return r!==void 0&&!r.includes(o)&&r.push(o),x(i,e)}export{h as a,R as b,c,H as d,F as e,Z as f,B as g,v as h,Y as i,W as j,Q as k};
@@ -1,2 +1,2 @@
1
- /*! palbase 0.73.0 — Palbase SDK License (see LICENSE) */
2
- import{c as O,g as w,l as F,m as _,s as D}from"./4XSSQAES.js";import{b as h}from"./PEQZDT6P.js";var M=20,R=2048,S=256,z=/^[A-Za-z][A-Za-z0-9_.-]{0,39}$/,m=e=>new h({op:"GetPlacementPaywall",status:0,code:"invalid_attributes",message:e});function j(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>M)throw m(`${n.length} attributes: at most ${M}`);let t=[];for(let i of n){if(!z.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=j(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>R)throw m(`the attributes are ${a.length} bytes: at most ${R}`);return a}function v(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 E(e){try{return new Intl.NumberFormat("en",{style:"currency",currency:e}).resolvedOptions().maximumFractionDigits??2}catch{return 2}}function x(e,n,t){let a=e/10**E(n);try{return new Intl.NumberFormat(t,{style:"currency",currency:n}).format(a)}catch{return`${a.toFixed(E(n))} ${n}`}}function L(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 X={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 U(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=X[n.split("-")[0].toLowerCase()];return a?a(t):t}function K(e,n){try{return new Intl.NumberFormat(n,{style:"percent",maximumFractionDigits:0}).format(e)}catch{return`${Math.round(e*100)}%`}}function I(e,n){let t=new Map,a=new Map;for(let r of e){let s=v(r.period);if(!s)continue;let l=r.price.amount/s.months;t.set(r.key,l),a.set(r.price.currency,Math.max(a.get(r.price.currency)??0,l))}let i={};for(let r of e){let s={product_name:r.productName,price:x(r.price.amount,r.price.currency,n)},l=v(r.period);if(l){s.period=L(l,n),s.price_per_month=x(Math.round(t.get(r.key)),r.price.currency,n);let o=a.get(r.price.currency)??0,u=o>0?Math.floor((1-t.get(r.key)/o)*100)/100:0;u>=.01&&(s.savings=K(u,n))}let f=r.intro?.mode==="free_trial"?v(r.intro.duration):null;f&&(s.trial=U(f,n)),r.offer&&(s.offer_price=x(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.73.0"};var C=`palbase-js/${V.version}`;var b=class{placement;source;definition;assets;offerings;offers;shown;deps;exposed=!1;constructor(n,t,a,i,r,s,l={},f=[]){this.placement=n,this.source=t,this.definition=a,this.assets=l,this.offerings=i,this.offers=f,this.shown=r,this.deps=s}packages(n){return I(q(this.offerings,F(this.definition),n,W(this.definition,this.offers)),n)}render(n,t){let a=t.locale??globalThis.navigator?.language??this.definition.default_locale,i=t.appearance===void 0?H():void 0,r=this.packages(a),s=D(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 u=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(u,o):globalThis.location.assign(u)}catch(u){if(!t.onError)throw u;t.onError(u,o)}},onClose:t.onClose,onLink:t.onLink,labels:t.labels}),l=o=>s.update({appearance:o.matches?"dark":"light"});i?.addEventListener?.("change",l),!this.exposed&&this.shown&&(this.exposed=!0,this.deps.expose(this));let f=s.destroy.bind(s);return s.destroy=()=>{i?.removeEventListener?.("change",l),f()},s}};function H(){try{return globalThis.matchMedia?.("(prefers-color-scheme: dark)")}catch{return}}function J(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 q(e,n,t,a=new Map){let i=[];for(let r of n){let[s,l]=r.split("."),f=e.products.find(d=>d.key===s),o=f?.channels.web,u=o?.plans.find(d=>d.key===l);if(!f||!o||!u)continue;let p=a.get(r),g=p?.discount?p.discount.percent:p?.trial?100:void 0;i.push({key:r,productName:J(o.locales,t)??f.key,price:{amount:u.price.amount,currency:u.price.currency},period:u.period,intro:u.intro,...g!==void 0?{offer:{percentOff:g}}:{}})}return i}function W(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 Y={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 G(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:Y,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 $(){try{return globalThis.localStorage}catch{return}}function Q(e){try{let n=$()?.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?$()?.setItem(e,JSON.stringify(n)):$()?.removeItem(e)}catch{}}async function de(e,n,t,a,i,r={}){let{signal:s,fetch:l}=r,f=T(r.attributes),o=`palbase.paywall.${n}.${t}`,p={checkout:i,expose:async c=>{if(c.shown)try{let k={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":a},body:k})}catch{}}},g=async(c,k)=>new b(t,k,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 O(c.assets??[],{signal:s,...l?{fetch:l}:{}}),c.offers??[]),d=Q(o),y;try{y=await e.getPlacementPaywall({path:{placement:t},query:{channel:"web"},headers:{"X-Palbase-Paywall-Schema":2,"X-Palbase-Installation":a,"X-Platform":"web","X-Palbase-SDK":C,...r.appVersion?{"X-Palbase-Client-Version":r.appVersion}:{},...r.app?{"X-Palbase-App":r.app}:{},...r.locale?{"Accept-Language":r.locale}:{},...f!==void 0?{"X-Palbase-Attributes":f}:{},...d?.etag?{"If-None-Match":d.etag}:{}},signal:s})}catch(c){if(c instanceof h&&c.status===404||c instanceof h&&c.status===400&&c.code.startsWith("invalid_"))return P(o,void 0),A(e,t,p,s);if(d&&!s?.aborted)return g(d.answer,"cache");throw c}return y.status===200?(P(o,{etag:y.headers.get("etag")??void 0,answer:y.data}),g(y.data,"server")):y.status===304&&d?g(d.answer,"server"):(P(o,void 0),A(e,t,p,s))}async function A(e,n,t,a){let i=(await e.getOfferings({query:{channel:"web"},signal:a})).data,r=G(i);return r?new b(n,"default",r,i,void 0,t):null}export{T as a,v as b,x as c,L as d,I as e,b as f,G as g,de as h};
1
+ /*! palbase 0.73.1 — Palbase SDK License (see LICENSE) */
2
+ import{c as O,g as w,l as F,m as _,s as D}from"./SS2RVI27.js";import{b as h}from"./HRWVZ4PC.js";var M=20,R=2048,S=256,z=/^[A-Za-z][A-Za-z0-9_.-]{0,39}$/,m=e=>new h({op:"GetPlacementPaywall",status:0,code:"invalid_attributes",message:e});function j(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>M)throw m(`${n.length} attributes: at most ${M}`);let t=[];for(let i of n){if(!z.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=j(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>R)throw m(`the attributes are ${a.length} bytes: at most ${R}`);return a}function v(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 E(e){try{return new Intl.NumberFormat("en",{style:"currency",currency:e}).resolvedOptions().maximumFractionDigits??2}catch{return 2}}function x(e,n,t){let a=e/10**E(n);try{return new Intl.NumberFormat(t,{style:"currency",currency:n}).format(a)}catch{return`${a.toFixed(E(n))} ${n}`}}function L(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 X={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 U(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=X[n.split("-")[0].toLowerCase()];return a?a(t):t}function K(e,n){try{return new Intl.NumberFormat(n,{style:"percent",maximumFractionDigits:0}).format(e)}catch{return`${Math.round(e*100)}%`}}function I(e,n){let t=new Map,a=new Map;for(let r of e){let s=v(r.period);if(!s)continue;let l=r.price.amount/s.months;t.set(r.key,l),a.set(r.price.currency,Math.max(a.get(r.price.currency)??0,l))}let i={};for(let r of e){let s={product_name:r.productName,price:x(r.price.amount,r.price.currency,n)},l=v(r.period);if(l){s.period=L(l,n),s.price_per_month=x(Math.round(t.get(r.key)),r.price.currency,n);let o=a.get(r.price.currency)??0,u=o>0?Math.floor((1-t.get(r.key)/o)*100)/100:0;u>=.01&&(s.savings=K(u,n))}let f=r.intro?.mode==="free_trial"?v(r.intro.duration):null;f&&(s.trial=U(f,n)),r.offer&&(s.offer_price=x(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.73.1"};var C=`palbase-js/${V.version}`;var b=class{placement;source;definition;assets;offerings;offers;shown;deps;exposed=!1;constructor(n,t,a,i,r,s,l={},f=[]){this.placement=n,this.source=t,this.definition=a,this.assets=l,this.offerings=i,this.offers=f,this.shown=r,this.deps=s}packages(n){return I(q(this.offerings,F(this.definition),n,W(this.definition,this.offers)),n)}render(n,t){let a=t.locale??globalThis.navigator?.language??this.definition.default_locale,i=t.appearance===void 0?H():void 0,r=this.packages(a),s=D(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 u=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(u,o):globalThis.location.assign(u)}catch(u){if(!t.onError)throw u;t.onError(u,o)}},onClose:t.onClose,onLink:t.onLink,labels:t.labels}),l=o=>s.update({appearance:o.matches?"dark":"light"});i?.addEventListener?.("change",l),!this.exposed&&this.shown&&(this.exposed=!0,this.deps.expose(this));let f=s.destroy.bind(s);return s.destroy=()=>{i?.removeEventListener?.("change",l),f()},s}};function H(){try{return globalThis.matchMedia?.("(prefers-color-scheme: dark)")}catch{return}}function J(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 q(e,n,t,a=new Map){let i=[];for(let r of n){let[s,l]=r.split("."),f=e.products.find(d=>d.key===s),o=f?.channels.web,u=o?.plans.find(d=>d.key===l);if(!f||!o||!u)continue;let p=a.get(r),g=p?.discount?p.discount.percent:p?.trial?100:void 0;i.push({key:r,productName:J(o.locales,t)??f.key,price:{amount:u.price.amount,currency:u.price.currency},period:u.period,intro:u.intro,...g!==void 0?{offer:{percentOff:g}}:{}})}return i}function W(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 Y={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 G(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:Y,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 $(){try{return globalThis.localStorage}catch{return}}function Q(e){try{let n=$()?.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?$()?.setItem(e,JSON.stringify(n)):$()?.removeItem(e)}catch{}}async function de(e,n,t,a,i,r={}){let{signal:s,fetch:l}=r,f=T(r.attributes),o=`palbase.paywall.${n}.${t}`,p={checkout:i,expose:async c=>{if(c.shown)try{let k={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":a},body:k})}catch{}}},g=async(c,k)=>new b(t,k,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 O(c.assets??[],{signal:s,...l?{fetch:l}:{}}),c.offers??[]),d=Q(o),y;try{y=await e.getPlacementPaywall({path:{placement:t},query:{channel:"web"},headers:{"X-Palbase-Paywall-Schema":2,"X-Palbase-Installation":a,"X-Platform":"web","X-Palbase-SDK":C,...r.appVersion?{"X-Palbase-Client-Version":r.appVersion}:{},...r.app?{"X-Palbase-App":r.app}:{},...r.locale?{"Accept-Language":r.locale}:{},...f!==void 0?{"X-Palbase-Attributes":f}:{},...d?.etag?{"If-None-Match":d.etag}:{}},signal:s})}catch(c){if(c instanceof h&&c.status===404||c instanceof h&&c.status===400&&c.code.startsWith("invalid_"))return P(o,void 0),A(e,t,p,s);if(d&&!s?.aborted)return g(d.answer,"cache");throw c}return y.status===200?(P(o,{etag:y.headers.get("etag")??void 0,answer:y.data}),g(y.data,"server")):y.status===304&&d?g(d.answer,"server"):(P(o,void 0),A(e,t,p,s))}async function A(e,n,t,a){let i=(await e.getOfferings({query:{channel:"web"},signal:a})).data,r=G(i);return r?new b(n,"default",r,i,void 0,t):null}export{T as a,v as b,x as c,L as d,I as e,b as f,G as g,de as h};
@@ -1,2 +1,2 @@
1
- /*! palbase 0.73.0 — Palbase SDK License (see LICENSE) */
2
- import{b}from"./5OOA4R4H.js";import{a as k,b as A}from"./J7ZNBBRN.js";import{randomBytes as _}from"node:crypto";async function N(){let n={keys:[{id:"k1",key:_(32).toString("base64url"),activates_at:new Date(0).toISOString()}],lookup:_(32).toString("base64url")},e=new b({fetch:async()=>n});return await e.load(),e.close(),e}var f=class extends Error{status;error;data;body;constructor(e,a,l,d){let u=d!==null&&typeof d=="object"?d:{},o=u.error??String(l);super(`${e} ${a} \u2192 ${l} ${o}${u.error_description?`: ${u.error_description}`:""}`),this.name="TestApiError",this.status=l,this.error=o,this.data=u.data,this.body=u}};function x(n,e){if(!n)throw new Error(`${e} is not set: the test client has nowhere to send its requests \u2014 \`palbase test\` sets it, as the platform's test run does`);return n}function B(n){let e=n.split(".")[1];if(!e)return null;try{let a=JSON.parse(Buffer.from(e,"base64url").toString("utf8"));return typeof a.exp=="number"?a.exp-Math.floor(Date.now()/1e3):null}catch{return null}}function L(n){try{return JSON.parse(n)}catch{return n}}function $(n){let e=x(n.baseUrl,"PALBASE_TEST_BASE_URL").replace(/\/+$/,""),a=n.apiKey||void 0,l=(n.authUrl??e).replace(/\/+$/,""),d=n.fetch??fetch,u=[],o=null;async function c(r,t,s,i,T={},O=!0){let g={...T.headers},m=h=>Object.keys(g).some(R=>R.toLowerCase()===h);a!==void 0&&!m("apikey")&&(g.apikey=a),o&&O&&!m("authorization")&&(g.authorization=`Bearer ${o}`),i!==void 0&&!m("content-type")&&(g["content-type"]="application/json");let I=Date.now(),p=await d(`${r}${s}`,{method:t,headers:g,body:i===void 0?void 0:JSON.stringify(i)}),E=await p.text(),S=E?L(E):void 0;if(u.push({method:t,path:s,status:p.status,ms:Date.now()-I}),!p.ok){let h=p.status===401&&o?B(o):null;throw h!==null&&h<=0?new f(t,s,p.status,{error:"access_token_expired",error_description:`this run's access token expired ${-h}s ago: a test user's token is made for one run \u2014 run the tests again (\`palbase test\` makes new ones)`}):new f(t,s,p.status,S)}return S}let y={requests:u,get:(r,t)=>c(e,"GET",r,void 0,t),post:(r,t,s)=>c(e,"POST",r,t,s),patch:(r,t,s)=>c(e,"PATCH",r,t,s),put:(r,t,s)=>c(e,"PUT",r,t,s),delete:(r,t)=>c(e,"DELETE",r,void 0,t),query:(r,t,s)=>c(e,"QUERY",r,t,s),async signInAs(r){let t=n.identities?.[r];if(!t){let s=Object.keys(n.identities??{});throw s.length===0?new Error(`no test user named ${JSON.stringify(r)}: this run has no test users \u2014 none were named (the machine's test users, or \`palbase test --users <names>\`), or they could not be made: the run's log says which`):new Error(`no test user named ${JSON.stringify(r)} \u2014 this run has: ${s.join(", ")}. A run makes the test users its machine names (palbase machines:update <machine> --test-users <names>) or \`palbase test --users <names>\` names`)}return t.accessToken?(o=t.accessToken,{id:t.id??"",email:t.email}):y.signIn(t)},async signIn(r){if(a===void 0)throw new Error("PALBASE_TEST_API_KEY is not set: a sign-in at the project's auth is made with a publishable key of the project's (palbase apps:sdkconfig shows one) \u2014 a run's test users come with their tokens: api.signInAs(name)");let t=i=>c(l,"POST","/auth/login",r,i?{headers:i}:{},!1),s;try{s=await t()}catch(i){let T=i instanceof f&&i.status===403?k(i.body):null;if(!T)throw i;s=await t(await A(T))}return o=s.access_token,s.user??{id:""}},async signOut(){await c(l,"POST","/auth/logout",void 0),o=null},asAnonymous(){o=null}};return y}function P(n){if(!n)return{};let e;try{e=JSON.parse(n)}catch{throw new Error("PALBASE_TEST_IDENTITIES is set but is not JSON: the run that started these tests handed over a broken set of test users")}if(e===null||typeof e!="object"||Array.isArray(e))throw new Error("PALBASE_TEST_IDENTITIES is not an object of test users by name");return e}var j={get stack(){return!!process.env.PALBASE_TEST_BASE_URL},minted(n){return Object.prototype.hasOwnProperty.call(P(process.env.PALBASE_TEST_IDENTITIES),n)}},w,q=new Proxy({},{get(n,e){return w??=$({baseUrl:process.env.PALBASE_TEST_BASE_URL??"",apiKey:process.env.PALBASE_TEST_API_KEY??"",authUrl:process.env.PALBASE_TEST_AUTH_URL,identities:P(process.env.PALBASE_TEST_IDENTITIES)}),Reflect.get(w,e,w)}});export{N as a,f as b,$ as c,j as d,q as e};
1
+ /*! palbase 0.73.1 — Palbase SDK License (see LICENSE) */
2
+ import{b}from"./MB7MHOQO.js";import{a as k,b as A}from"./W2KD2I4Q.js";import{randomBytes as _}from"node:crypto";async function N(){let n={keys:[{id:"k1",key:_(32).toString("base64url"),activates_at:new Date(0).toISOString()}],lookup:_(32).toString("base64url")},e=new b({fetch:async()=>n});return await e.load(),e.close(),e}var f=class extends Error{status;error;data;body;constructor(e,a,l,d){let u=d!==null&&typeof d=="object"?d:{},o=u.error??String(l);super(`${e} ${a} \u2192 ${l} ${o}${u.error_description?`: ${u.error_description}`:""}`),this.name="TestApiError",this.status=l,this.error=o,this.data=u.data,this.body=u}};function x(n,e){if(!n)throw new Error(`${e} is not set: the test client has nowhere to send its requests \u2014 \`palbase test\` sets it, as the platform's test run does`);return n}function B(n){let e=n.split(".")[1];if(!e)return null;try{let a=JSON.parse(Buffer.from(e,"base64url").toString("utf8"));return typeof a.exp=="number"?a.exp-Math.floor(Date.now()/1e3):null}catch{return null}}function L(n){try{return JSON.parse(n)}catch{return n}}function $(n){let e=x(n.baseUrl,"PALBASE_TEST_BASE_URL").replace(/\/+$/,""),a=n.apiKey||void 0,l=(n.authUrl??e).replace(/\/+$/,""),d=n.fetch??fetch,u=[],o=null;async function c(r,t,s,i,T={},O=!0){let g={...T.headers},m=h=>Object.keys(g).some(R=>R.toLowerCase()===h);a!==void 0&&!m("apikey")&&(g.apikey=a),o&&O&&!m("authorization")&&(g.authorization=`Bearer ${o}`),i!==void 0&&!m("content-type")&&(g["content-type"]="application/json");let I=Date.now(),p=await d(`${r}${s}`,{method:t,headers:g,body:i===void 0?void 0:JSON.stringify(i)}),E=await p.text(),S=E?L(E):void 0;if(u.push({method:t,path:s,status:p.status,ms:Date.now()-I}),!p.ok){let h=p.status===401&&o?B(o):null;throw h!==null&&h<=0?new f(t,s,p.status,{error:"access_token_expired",error_description:`this run's access token expired ${-h}s ago: a test user's token is made for one run \u2014 run the tests again (\`palbase test\` makes new ones)`}):new f(t,s,p.status,S)}return S}let y={requests:u,get:(r,t)=>c(e,"GET",r,void 0,t),post:(r,t,s)=>c(e,"POST",r,t,s),patch:(r,t,s)=>c(e,"PATCH",r,t,s),put:(r,t,s)=>c(e,"PUT",r,t,s),delete:(r,t)=>c(e,"DELETE",r,void 0,t),query:(r,t,s)=>c(e,"QUERY",r,t,s),async signInAs(r){let t=n.identities?.[r];if(!t){let s=Object.keys(n.identities??{});throw s.length===0?new Error(`no test user named ${JSON.stringify(r)}: this run has no test users \u2014 none were named (the machine's test users, or \`palbase test --users <names>\`), or they could not be made: the run's log says which`):new Error(`no test user named ${JSON.stringify(r)} \u2014 this run has: ${s.join(", ")}. A run makes the test users its machine names (palbase machines:update <machine> --test-users <names>) or \`palbase test --users <names>\` names`)}return t.accessToken?(o=t.accessToken,{id:t.id??"",email:t.email}):y.signIn(t)},async signIn(r){if(a===void 0)throw new Error("PALBASE_TEST_API_KEY is not set: a sign-in at the project's auth is made with a publishable key of the project's (palbase apps:sdkconfig shows one) \u2014 a run's test users come with their tokens: api.signInAs(name)");let t=i=>c(l,"POST","/auth/login",r,i?{headers:i}:{},!1),s;try{s=await t()}catch(i){let T=i instanceof f&&i.status===403?k(i.body):null;if(!T)throw i;s=await t(await A(T))}return o=s.access_token,s.user??{id:""}},async signOut(){await c(l,"POST","/auth/logout",void 0),o=null},asAnonymous(){o=null}};return y}function P(n){if(!n)return{};let e;try{e=JSON.parse(n)}catch{throw new Error("PALBASE_TEST_IDENTITIES is set but is not JSON: the run that started these tests handed over a broken set of test users")}if(e===null||typeof e!="object"||Array.isArray(e))throw new Error("PALBASE_TEST_IDENTITIES is not an object of test users by name");return e}var j={get stack(){return!!process.env.PALBASE_TEST_BASE_URL},minted(n){return Object.prototype.hasOwnProperty.call(P(process.env.PALBASE_TEST_IDENTITIES),n)}},w,q=new Proxy({},{get(n,e){return w??=$({baseUrl:process.env.PALBASE_TEST_BASE_URL??"",apiKey:process.env.PALBASE_TEST_API_KEY??"",authUrl:process.env.PALBASE_TEST_AUTH_URL,identities:P(process.env.PALBASE_TEST_IDENTITIES)}),Reflect.get(w,e,w)}});export{N as a,f as b,$ as c,j as d,q as e};
@@ -1,5 +1,5 @@
1
- /*! palbase 0.73.0 — Palbase SDK License (see LICENSE) */
2
- import"./P36C47FS.js";import{realpathSync as Je}from"node:fs";import{resolve as ge}from"node:path";import vt from"typescript";import{existsSync as he,readFileSync as be}from"node:fs";import{createRequire as Qe}from"node:module";import{dirname as re,join as G,relative as We,resolve as xe,sep as ne}from"node:path";var b=class extends Error{constructor(t){super(t),this.name="ContractAnalysisError"}},Z=new Set(["palbase/backend","@palbase/backend","palgres"]),Ge=new Set(["Get","Post","Put","Patch","Delete","Query","Upload"]);function we(e){if(typeof e.createProgram!="function"||typeof e.getDecorators!="function"||typeof e.readConfigFile!="function")throw new b(`the contract is read with TypeScript's compiler API, and the TypeScript given (v${e.version??"unknown"}) has none \u2014 TypeScript 7 is the Go-native compiler, whose package exposes version metadata only`)}var Ze={bun:"bun-types",node:"@types/node"},He=Qe(import.meta.url);function Xe(e,t,n){if(!n.types)return{types:void 0,files:[]};let r=[],s=[];for(let i of n.types){let o=Ze[i],a=e.resolveTypeReferenceDirective(i,G(t,"tsconfig.json"),n,e.sys).resolvedTypeReferenceDirective,c;if(!a&&o)try{c=He.resolve(`${o}/package.json`)}catch{c=void 0}if(!c){r.push(i);continue}let l=JSON.parse(be(c,"utf8"));s.push(G(re(c),l.types??l.typings??"index.d.ts"))}return{types:r,files:s}}function ke(e,t){we(e);let n=G(t,"tsconfig.json"),r={target:e.ScriptTarget.ES2022,module:e.ModuleKind.ESNext,moduleResolution:e.ModuleResolutionKind.Bundler,experimentalDecorators:!0,allowImportingTsExtensions:!0},s=[];if(he(n)){let i=e.readConfigFile(n,e.sys.readFile);if(i.error)throw new b(`${n}: ${e.flattenDiagnosticMessageText(i.error.messageText,`
1
+ /*! palbase 0.73.1 — Palbase SDK License (see LICENSE) */
2
+ import"./DNSLYLU6.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()";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);return 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.73.0 — Palbase SDK License (see LICENSE) */
1
+ /*! palbase 0.73.1 — 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};