palbase 0.73.0 → 0.74.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) 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/4DNFXRTX.js +2 -0
  10. package/dist/chunks/{LCDNCPQW.js → 53XWB3UV.js} +1 -1
  11. package/dist/chunks/{J7ZNBBRN.js → 5NLCEWSD.js} +1 -1
  12. package/dist/chunks/{3DUDNEMM.js → 7HDSHHGM.js} +2 -2
  13. package/dist/chunks/{5OOA4R4H.js → AFO74GQQ.js} +1 -1
  14. package/dist/chunks/{P4NZ4NZD.js → AKM627JB.js} +2 -2
  15. package/dist/chunks/{IICQMY2Z.js → BBXGUP7G.js} +2 -2
  16. package/dist/chunks/{EKOEK6LR.js → CVBLXV6M.js} +2 -2
  17. package/dist/chunks/{YMIK6HLK.js → DFIAGTHU.js} +2 -2
  18. package/dist/chunks/FKDQMWI7.js +23 -0
  19. package/dist/chunks/{757A6AR6.js → FYZAVXD4.js} +2 -2
  20. package/dist/chunks/{P36C47FS.js → IIQ6QEL2.js} +1 -1
  21. package/dist/chunks/{25HECIZY.js → IJBBBAXY.js} +1 -1
  22. package/dist/chunks/{DIQMCEMJ.js → MKKBGO2H.js} +2 -2
  23. package/dist/chunks/OS567PDL.js +2 -0
  24. package/dist/chunks/{CY6KUFZW.js → PF52QMPW.js} +2 -2
  25. package/dist/chunks/{MVKZWEHL.js → QJPQVLNV.js} +2 -2
  26. package/dist/chunks/{VEL7X2G3.js → RK4CTF2F.js} +2 -2
  27. package/dist/chunks/{JG4V6LNY.js → SS3YF6MP.js} +2 -2
  28. package/dist/chunks/{PAQCJT7M.js → U5LDOZB5.js} +2 -2
  29. package/dist/chunks/{J7Z2PYL4.js → WNPRCDLR.js} +1 -1
  30. package/dist/chunks/{4XSSQAES.js → YDHRQOAN.js} +1 -1
  31. package/dist/chunks/{SRN7N2WX.js → YOCX3MXN.js} +2 -2
  32. package/dist/chunks/{PEQZDT6P.js → ZRNXABQJ.js} +2 -2
  33. package/dist/cli.js +162 -162
  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
  51. package/types/cloud/src/generated/project.d.ts +1 -1
  52. package/types/internal/src/modules/commerce.d.ts +2810 -533
  53. package/types/internal/src/modules/events.d.ts +2 -2
  54. package/types/server/src/commerce.d.ts +172 -3
  55. package/types/server/src/index.d.ts +1 -1
  56. package/types/web/src/commerce.d.ts +460 -20
  57. package/types/web/src/index.d.ts +1 -1
  58. package/types/web/src/session.d.ts +15 -1
  59. package/types/web/src/ssr.d.ts +1 -1
  60. package/dist/chunks/76W5ZO2L.js +0 -2
  61. package/dist/chunks/SMECWMF7.js +0 -2
  62. package/dist/chunks/UFP6GLLW.js +0 -23
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.74.0 — Palbase SDK License (see LICENSE) */
2
+ import{a,b,c,d,e,f,g}from"../chunks/PF52QMPW.js";import"../chunks/RK4CTF2F.js";import"../chunks/IJBBBAXY.js";import"../chunks/OS567PDL.js";import"../chunks/DFIAGTHU.js";import"../chunks/ZRNXABQJ.js";import"../chunks/5NLCEWSD.js";import"../chunks/IIQ6QEL2.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.74.0 — Palbase SDK License (see LICENSE) */
2
+ import"../chunks/IIQ6QEL2.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.74.0 — Palbase SDK License (see LICENSE) */
2
+ import{ha as w,la as h}from"../chunks/7HDSHHGM.js";import"../chunks/FYZAVXD4.js";import"../chunks/U5LDOZB5.js";import"../chunks/PF52QMPW.js";import"../chunks/RK4CTF2F.js";import"../chunks/4DNFXRTX.js";import"../chunks/AFO74GQQ.js";import"../chunks/IJBBBAXY.js";import"../chunks/OS567PDL.js";import"../chunks/WNPRCDLR.js";import"../chunks/DFIAGTHU.js";import"../chunks/ZRNXABQJ.js";import"../chunks/5NLCEWSD.js";import"../chunks/IIQ6QEL2.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.74.0 — 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.74.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/7HDSHHGM.js";import{a as Nt,b as qt}from"../chunks/FYZAVXD4.js";import{a as oe}from"../chunks/53XWB3UV.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/U5LDOZB5.js";import"../chunks/PF52QMPW.js";import"../chunks/RK4CTF2F.js";import{F as Q,G as X,d as C,j as Ue,k as je,l as Y,m as I}from"../chunks/4DNFXRTX.js";import"../chunks/AFO74GQQ.js";import"../chunks/IJBBBAXY.js";import{t as De}from"../chunks/OS567PDL.js";import"../chunks/WNPRCDLR.js";import"../chunks/DFIAGTHU.js";import{b as O,c as W}from"../chunks/ZRNXABQJ.js";import"../chunks/5NLCEWSD.js";import"../chunks/IIQ6QEL2.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/QJPQVLNV.js"),{routeContracts:l}=await import("../chunks/SS3YF6MP.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.74.0 — 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.74.0 — Palbase SDK License (see LICENSE) */
2
+ import{b as l,c as g,d as f,e as m}from"../chunks/CVBLXV6M.js";import{a as u}from"../chunks/53XWB3UV.js";import{c,i as p}from"../chunks/U5LDOZB5.js";import"../chunks/PF52QMPW.js";import"../chunks/RK4CTF2F.js";import"../chunks/AFO74GQQ.js";import"../chunks/IJBBBAXY.js";import"../chunks/OS567PDL.js";import"../chunks/DFIAGTHU.js";import"../chunks/ZRNXABQJ.js";import"../chunks/5NLCEWSD.js";import"../chunks/IIQ6QEL2.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};
@@ -0,0 +1,2 @@
1
+ /*! palbase 0.74.0 — Palbase SDK License (see LICENSE) */
2
+ import{b as C}from"./AFO74GQQ.js";import{a as ue}from"./IJBBBAXY.js";import{a as D,b as j,c as U,d as I,e as K,f as q,g as F,h as $,i as N,j as V,k as J,l as z,m as Y,n as G,o as X,p as Z,q as Q,r as ee,s as te}from"./OS567PDL.js";import{a as w,c as oe,d as se,e as ie,f as ae,h as ce,i as pe,j as M,k as le,l as de,o as A}from"./WNPRCDLR.js";import{a as ne,b as re}from"./DFIAGTHU.js";import{b as T,d as b}from"./ZRNXABQJ.js";var h=class extends Error{status=400;code;data;constructor(e,n,r={}){super(n),this.name="TransitRefusal",this.code=e,this.data=r}},Le=6e4,Be=1e3;function O(t){return/^t[1-9][0-9]{0,5}$/.test(t)?Number(t.slice(1)):0}var S=class{keys=new Map;retired=new Set;order=[];project;timer;fetchedAt=0;heldFrom=0;fetching;opts;now;sleep;constructor(e){this.opts=e,this.now=e.now??Date.now,this.sleep=e.sleep??(n=>new Promise(r=>setTimeout(r,n)))}get loaded(){return this.project!==void 0}get projectId(){if(this.project===void 0)throw new Error("the project's transit keys are not loaded: await palbase.transit.load() at startup");return this.project}current(){return this.order[0]}async load(e){await this.refresh(e),this.timer===void 0&&(this.timer=setInterval(()=>{this.refresh().catch(()=>{})},Le),this.timer.unref?.())}close(){clearInterval(this.timer),this.timer=void 0}refresh(e){return this.fetching??=(async()=>{let n=this.now();try{let r=await this.opts.fetch(e),o=new Map;for(let s of r.keys){let i=se(s.key);o.set(s.id,{privateKey:i,publicKey:this.keys.get(s.id)?.publicKey??await ie(i)})}this.keys=o,this.order=r.keys.map(s=>s.id),this.retired=new Set(r.retired),this.project=r.project,this.fetchedAt=this.now(),this.heldFrom=n}finally{this.fetching=void 0}})(),this.fetching}newest(){return Math.max(0,...this.order.map(O),...[...this.retired].map(O))}async key(e){let n=this.now();for(;O(e)>this.newest()&&this.heldFrom<n;){let s=this.fetchedAt+Be-this.now();if(s>0){await this.sleep(s);continue}await this.refresh()}let r=this.keys.get(e),o=this.current();if(this.retired.has(e))throw new h("encryption_key_retired",`the request is sealed to ${e}, retired: fetch the project's keys again`,{current:o});if(r===void 0)throw new h("encryption_key_unknown",`the request is sealed to ${e}, which the project has not made`,{current:o});return r}async request(e){if(e.header===void 0||e.header===null||e.header==="")throw new h("encryption_required",`this route carries encrypted fields: the request names its key in ${w}`,{field:w,current:this.current()});let n;try{n=ce(e.header).kid}catch{throw new h("encryption_unopenable",`${w} is not one`,{field:w})}let r=await this.key(n),o;try{o=ae(this.projectId,e.method,e.path,e.params??[])}catch{throw new h("encryption_unopenable","the request's path holds a value no key is sealed for",{field:w})}try{return new R(n,await pe(e.header,r.privateKey,r.publicKey,o))}catch(s){throw s instanceof oe?new h("encryption_unopenable","the request's key does not open: sealed for another project, route or path, or changed",{field:w}):s}}},R=class{kid;key;constructor(e,n){this.kid=e,this.key=n}async open(e,n,r){return A(e,n,r,async(o,s)=>{if(!le(s))throw new h("encryption_required",`${o} is an encrypted field: it came plain`,{field:o});try{return await de(this.key,o,s)}catch{throw new h("encryption_unopenable",`${o} does not open: changed, moved from another field, or another request's`,{field:o})}})}async seal(e,n){return A(e,"/response",n,(r,o)=>M(this.key,r,o))}sealField(e,n){return M(this.key,e,n)}};var De=/^pb_[a-z0-9]+_s/;function H(t){if(ue())throw new TypeError("palbase/server runs on a server: its secret key never goes into a browser or a mobile app \u2014 apps use palbase/web (or the native SDKs) with the publishable key");if(typeof t.secretKey!="string"||!De.test(t.secretKey))throw new TypeError("secretKey is the project secret key (pb_<ref>_s\u2026); a publishable key belongs in palbase/web");let e=re(b({baseUrl:t.url,credentials:{secretKey:t.secretKey},fetch:t.fetch,solveProofOfWork:t.solveProofOfWork??!1}),t.retry??ne),n=Z.client(e);return{ai:D.client(e),analytics:j.client(e),auth:U.client(e),cache:I.client(e),calls:K.client(e),fields:new C({fetch:async r=>(await n.getFieldKeys({signal:r})).data}),flags:$.client(e),iap:N.client(e),machines:J.client(e),messaging:z.client(e),notify:Y.client(e),payments:G.client(e),campaigns:q.client(e),commerce:F.client(e),journeys:V.client(e),realtime:X.client(e),secrets:n,storage:Q.client(e),stores:ee.client(e),workspaces:te.client(e),transit:new S({fetch:async r=>(await n.getTransitKeys({signal:r})).data}),transport:e,url:new URL(t.url).origin}}var u=class extends Error{code;constructor(e,n){super(n),this.name="WebhookSignatureError",this.code=e}},Ue=300,Ie=/^[0-9]{1,12}$/,Ke=/^[0-9a-f]{64}$/,ye=8,qe=/^whsec_[0-9A-Za-z]{32,}$/,Fe=1024*1024;async function me(t){if(typeof t.secret!="string"||!qe.test(t.secret))throw new TypeError("secret is the webhook endpoint secret (whsec_\u2026), not an API key");await he(t);let e;try{e=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(ge(t.body)))}catch{throw new u("invalid_body","the signed body is not JSON")}if(!Ye(e))throw new u("invalid_body","the signed body is not a Palbase event (id, type, project_id, created_at, data)");return e}async function he(t){if(typeof t.secret!="string"||t.secret==="")throw new TypeError("secret is the key the request was signed with");let e=ge(t.body),{t:n,v1:r}=fe(t),o=await crypto.subtle.importKey("raw",new TextEncoder().encode(t.secret),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),s=new Uint8Array(await crypto.subtle.sign("HMAC",o,ze(new TextEncoder().encode(`${n}.`),e))),i=!1;for(let p of r)Je(s,Ve(p))&&(i=!0);if(!i)throw new u("signature_mismatch","no v1 in Palbase-Signature is this body signed with this secret")}function fe(t){let e=t.toleranceSeconds??Ue;if(!Number.isFinite(e)||e<0)throw new TypeError(`toleranceSeconds is a number of seconds, 0 or more (got ${String(t.toleranceSeconds)})`);let n=(t.now??Date.now)();if(!Number.isFinite(n))throw new TypeError(`now() returns epoch milliseconds (got ${String(n)})`);let r=t.signature;if(typeof r!="string"||r.trim()==="")throw new u("missing_signature","the request carries no Palbase-Signature header");let o,s=[];for(let i of r.split(",")){let p=i.indexOf("=");if(p<=0)throw new u("malformed_signature","Palbase-Signature is t=<seconds>,v1=<hex>");let c=i.slice(0,p).trim(),a=i.slice(p+1).trim();if(c==="t"){if(o!==void 0||!Ie.test(a))throw new u("malformed_signature","Palbase-Signature carries one t, in unix seconds");o=a}else if(c==="v1"){if(!Ke.test(a))throw new u("malformed_signature","a v1 is 64 lowercase hex characters");if(s.length===ye)throw new u("malformed_signature",`Palbase-Signature carries at most ${ye} v1`);s.push(a)}}if(o===void 0||s.length===0)throw new u("malformed_signature","Palbase-Signature is t=<seconds>,v1=<hex>");if(Math.abs(n/1e3-Number(o))>e)throw new u("stale_timestamp",`the signature's time is more than ${e} s from now: an old delivery sent again is not taken`);return{t:o,v1:s}}async function $e(t,e,n={}){let r=await Ne(t,n.maxBytes??Fe);return me({toleranceSeconds:n.toleranceSeconds,now:n.now,secret:e,signature:t.headers.get("palbase-signature"),body:r})}async function Ne(t,e){let n=()=>new u("body_too_large",`the body is larger than ${e} bytes`),r=Number(t.headers.get("content-length")??"NaN");if(Number.isFinite(r)&&r>e)throw n();if(!t.body)return new Uint8Array(0);let o=t.body.getReader(),s=[],i=0;for(;;){let{done:a,value:l}=await o.read();if(a)break;if(i+=l.byteLength,i>e)throw await o.cancel().catch(()=>{}),n();s.push(l)}let p=new Uint8Array(i),c=0;for(let a of s)p.set(a,c),c+=a.byteLength;return p}function ge(t){if(typeof t=="string")return new TextEncoder().encode(t);if(t instanceof Uint8Array)return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);throw new TypeError("body is the raw request body (string or bytes): a parsed object is not what was signed \u2014 read the body before any JSON middleware")}function Ve(t){let e=new Uint8Array(t.length/2);for(let n=0;n<e.length;n++)e[n]=parseInt(t.slice(n*2,n*2+2),16);return e}function Je(t,e){if(t.byteLength!==e.byteLength)return!1;let n=0;for(let r=0;r<t.byteLength;r++)n|=t[r]^e[r];return n===0}function ze(t,e){let n=new Uint8Array(t.byteLength+e.byteLength);return n.set(t,0),n.set(e,t.byteLength),n}function Ye(t){if(typeof t!="object"||t===null)return!1;let e=t;return typeof e.id=="string"&&typeof e.type=="string"&&typeof e.project_id=="string"&&typeof e.created_at=="string"&&"data"in e}var we=60,Ge=60,Xe=8*1024,Ze=1e5;function W(t){let e=t instanceof Uint8Array?t:new Uint8Array(t),n="";for(let r of e)n+=String.fromCharCode(r);return btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function ve(t){let e=t.replace(/[\s=]+/g,"");if(!/^[A-Za-z0-9+/_-]*$/.test(e)||e.length%4===1)return;let n=atob(e.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(e.length/4)*4,"=")),r=new Uint8Array(n.length);for(let o=0;o<n.length;o++)r[o]=n.charCodeAt(o);return r}function ke(t){let e=ve(t);if(e)try{let n=JSON.parse(new TextDecoder().decode(e));return typeof n=="object"&&n!==null&&!Array.isArray(n)?n:void 0}catch{return}}var x=class{byKey=new Map;held=0;sweptAt=Number.NEGATIVE_INFINITY;max;constructor(e=Ze){this.max=e}spend(e,n){if(n>=e.until)throw new d("proof","the DPoP proof is not taken: it was checked too long ago");let r=this.byKey.get(e.jkt);if(r){this.forgetOld(e.jkt,r,n);let o=r.get(e.jti);if(o!==void 0&&o>n)throw new d("proof","the DPoP proof is not taken: it was used before");o!==void 0&&r.delete(e.jti)&&this.held--}this.held>=this.max&&this.makeRoom(n),r=this.byKey.get(e.jkt),r||(r=new Map,this.byKey.set(e.jkt,r)),r.set(e.jti,e.until),this.held++}forgetOld(e,n,r){for(let[o,s]of n){if(s>r)break;n.delete(o),this.held--}n.size===0&&this.byKey.delete(e)}makeRoom(e){if(e-this.sweptAt>=1e3){this.sweptAt=e;for(let[r,o]of this.byKey){for(let[s,i]of o)i>e||(o.delete(s),this.held--);o.size===0&&this.byKey.delete(r)}this.held=0;for(let r of this.byKey.values())this.held+=r.size}if(this.held<this.max)return;let n=[...this.byKey].sort((r,o)=>o[1].size-r[1].size);for(let[r,o]of n){if(this.held<=this.max*.9)break;this.byKey.delete(r),this.held-=o.size}}};async function Qe(t,e){let n=`{"crv":"P-256","kty":"EC","x":"${t}","y":"${e}"}`;return W(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(n)))}function Se(t){try{let e=new URL(t);return e.username!==""||e.password!==""?void 0:`${e.protocol}//${e.host}${e.pathname}`}catch{return}}async function be(t,e,n,r){let o=We=>{throw new d("proof",`the DPoP proof is not taken: ${We}`)},s=n.proof;if(!s)return o("there is none (a DPoP-bound token comes with a DPoP header)");if(s.length>Xe)return o("it is too long");let i=s.split(".");if(i.length!==3)return o("it is not a JWS of three parts");let p=ke(i[0]),c=ke(i[1]);if(!p||!c)return o("its header or claims are not base64url JSON");if(p.typ!=="dpop+jwt")return o("its typ is not dpop+jwt");if(p.alg!=="ES256")return o(`it is signed with ${String(p.alg)}; only ES256 is taken`);let a=p.jwk;if(!a||typeof a!="object"||a.kty!=="EC"||a.crv!=="P-256"||typeof a.x!="string"||typeof a.y!="string")return o("its header carries no P-256 public key");if("d"in a)return o("its header carries a private key");if(await Qe(a.x,a.y)!==e)return o("it is signed by a key the token does not name");let l;try{l=await crypto.subtle.importKey("jwk",{kty:"EC",crv:"P-256",x:a.x,y:a.y,ext:!0},{name:"ECDSA",namedCurve:"P-256"},!1,["verify"])}catch{return o("its key is not a P-256 point")}let y=ve(i[2]);if(!y||!await crypto.subtle.verify({name:"ECDSA",hash:"SHA-256"},l,y,new TextEncoder().encode(`${i[0]}.${i[1]}`)).catch(()=>!1))return o("its signature does not verify");if(typeof c.htm!="string"||c.htm.toUpperCase()!==n.method.toUpperCase())return o(`it is for ${String(c.htm)}, not ${n.method}`);let m=typeof c.htu=="string"?Se(c.htu):void 0,f=Se(n.url);if(!m||!f||m!==f)return o(`it is for ${String(c.htu)}, not ${f??n.url}`);let v=r/1e3;if(typeof c.iat!="number"||Math.abs(c.iat-v)>we)return o("it was not made within a minute of now");let Oe=W(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(t)));if(c.ath!==Oe)return o("it is not for this token (ath)");if(typeof c.jti!="string"||c.jti===""||c.jti.length>256)return o("it has no jti (or one longer than 256)");let He=W(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(c.jti)));return{jkt:e,jti:He,until:(c.iat+we+Ge)*1e3+1}}var d=class extends Error{reason;constructor(e,n){super(n),this.name="TokenError",this.reason=e}},k=class extends Error{constructor(e,n){super(e,n),this.name="AuthUnavailable"}},et=new Set(["invalid_api_key","missing_api_key","secret_key_in_browser"]);function tt(t){return async e=>{let n=b({baseUrl:t.url,credentials:{secretKey:t.secretKey,accessToken:()=>e},fetch:t.fetch});try{return await n.send({op:"SessionStanding",method:"GET",path:"/auth/session/standing",auth:[["ApiKeyAuth","userJWT"]],answers:{204:"empty"}}),!0}catch(r){if(r instanceof T&&r.status===401&&!et.has(r.code))return!1;throw new k("a session's standing could not be told",{cause:r})}}}var L={ES256:{kty:"EC",import:{name:"ECDSA",namedCurve:"P-256"},verify:{name:"ECDSA",hash:"SHA-256"}},PS256:{kty:"RSA",import:{name:"RSA-PSS",hash:"SHA-256"},verify:{name:"RSA-PSS",saltLength:32}}},Re=60,nt=16*1024,rt=10*6e4,ot=5e4,xe=t=>typeof t=="string"&&Object.hasOwn(L,t),B=class{issuer;projectId;fetchImpl;now;maxKeyAgeMs;refetchIntervalMs;fetchTimeoutMs;standing;standingTtlMs;standingStaleMs;standings=new Map;asking=new Map;keys=new Map;keysUntil=0;lastFetch=Number.NEGATIVE_INFINITY;lastFailure=void 0;inflight=null;seenProofs=new x;constructor(e){let n=new URL(e.issuer);if(n.origin!==e.issuer.replace(/\/$/,""))throw new TypeError(`issuer is the project's origin (https://<ref>.<domain>), not ${e.issuer}`);if(typeof e.projectId!="string"||e.projectId==="")throw new TypeError("projectId is the project id the tokens carry");if(this.issuer=n.origin,this.projectId=e.projectId,this.fetchImpl=e.fetch??globalThis.fetch,this.now=e.now??Date.now,this.maxKeyAgeMs=e.maxKeyAgeMs??60*6e4,this.refetchIntervalMs=e.refetchIntervalMs??3e4,this.fetchTimeoutMs=e.fetchTimeoutMs??5e3,typeof e.standing!="function")throw new TypeError("standing is how the verifier asks whether a token's session stands");this.standing=e.standing,this.standingTtlMs=e.standingTtlMs??1e3,this.standingStaleMs=e.standingStaleMs??15e3}async verify(e,n){if(typeof e!="string"||e.length===0||e.length>nt)throw new d("malformed","the token is not a JWT");let r=e.split(".");if(r.length!==3)throw new d("malformed","the token is not a JWS of three parts");let o=Ee(r[0]),s=Ee(r[1]);if(!o||!s)throw new d("malformed","the token header or claims are not base64url JSON");let i=o.alg;if(!xe(i))throw new d("algorithm",`the token is signed with ${String(i)}; only ES256 and PS256 are taken`);let p=o.kid;if(typeof p!="string"||p==="")throw new d("malformed","the token header names no kid");let c=await this.key(p);if(!c)throw new d("unknown_key",`no key ${p} in the project's key set`);if(c.alg!==i)throw new d("algorithm",`key ${p} is ${c.alg}, the token says ${i}`);let a=Pe(r[2]);if(!a)throw new d("malformed","the signature is not base64url");let l=new TextEncoder().encode(`${r[0]}.${r[1]}`);if(!await crypto.subtle.verify(L[c.alg].verify,c.key,a,l).catch(()=>!1))throw new d("signature","the signature does not verify");let g=this.check(s),m=s.cnf,f;if(m!==void 0){if(!n)throw new d("bound","the token is bound to a key (DPoP): it comes with the DPoP scheme and a proof, not as a Bearer");if(typeof m!="object"||m===null||typeof m.jkt!="string"||m.jkt==="")throw new d("bound","the token is bound to a key it does not name (cnf.jkt)");f=await be(e,m.jkt,n,this.now())}else if(n)throw new d("not_bound","the DPoP scheme came with a token bound to no key");if(!await this.stands(e,g.sessionId))throw new d("session_ended","the token's session has ended (signed out, revoked, or its user banned)");return f&&this.seenProofs.spend(f,this.now()),g}async verifyRequest(e){let n=e.headers instanceof Headers?e.headers:it(e.headers),r=n.get("authorization")??"";if(r==="")return null;let o=/^(bearer|dpop)\s+(\S+)$/i.exec(r);if(!o)throw new d("malformed","the Authorization header is not a Bearer or DPoP token");let s=o[1].toLowerCase()==="dpop",i=new URL(e.url,`http://${n.get("host")??"localhost"}`);return this.verify(o[2],s?{proof:n.get("dpop"),method:e.method,url:_e(n,i)}:void 0)}async stands(e,n){let r=this.now(),o=this.standings.get(n);if(o&&r<o.until)return o.live;let s=this.asking.get(n);s||(s=this.standing(e,n).finally(()=>this.asking.delete(n)),this.asking.set(n,s));let i;try{i=await s}catch(c){let a=this.standings.get(n),l=this.now();if(a&&l<a.at+this.standingStaleMs)return a.until=Math.min(l+this.standingTtlMs,a.at+this.standingStaleMs),a.live;throw new k("a session's standing cannot be read now",{cause:c})}let p=this.now();return this.standings.delete(n),this.standings.set(n,{live:i,at:p,until:p+this.standingTtlMs}),this.standings.size>ot&&this.standings.delete(this.standings.keys().next().value),i}check(e){if(e.iss!==this.issuer)throw new d("issuer",`the token was issued by ${String(e.iss)}, not this project`);if(!(Array.isArray(e.aud)?e.aud:[e.aud]).includes(this.issuer))throw new d("audience","the token is not meant for this project");if(e.project_id!==this.projectId)throw new d("project","the token names another project");let r=this.now()/1e3;if(typeof e.exp!="number"||e.exp+Re<=r)throw new d("expired","the token has expired");if(e.nbf!==void 0&&(typeof e.nbf!="number"||e.nbf-Re>r))throw new d("not_yet_valid","the token is not valid yet");if(typeof e.sub!="string"||e.sub===""||typeof e.auth_time!="number")throw new d("not_a_user","the token is not a user's");if(typeof e.session_id!="string"||e.session_id==="")throw new d("not_a_session","the token is no session's");let o=e.custom_claims;if(o!==void 0&&(typeof o!="object"||o===null||o.type!==void 0))throw new d("not_a_session","the token is a custom one (an exchange or an approval), not a session's");return{id:e.sub,email:typeof e.email=="string"?e.email:null,emailVerified:e.email_verified===!0,role:typeof e.role=="string"?e.role:null,sessionId:typeof e.session_id=="string"?e.session_id:null,claims:Object.freeze({...e})}}async key(e){let n=this.now();if(n>=this.keysUntil){let o=this.keys.size>0&&n<this.keysUntil+rt;if(this.lastFailure!==void 0&&n-this.lastFetch<this.refetchIntervalMs){if(!o)throw new k("the project's key set cannot be read now",{cause:this.lastFailure})}else try{await this.refresh()}catch(s){if(!o)throw s}}let r=this.keys.get(e);return!r&&n-this.lastFetch>=this.refetchIntervalMs&&(await this.refresh(),r=this.keys.get(e)),r}refresh(){if(this.inflight)return this.inflight;let e=this.load().finally(()=>{this.inflight=null});return this.inflight=e,e}async load(){this.lastFetch=this.now();let e,n;try{if(n=await this.fetchImpl(`${this.issuer}/.well-known/jwks.json`,{redirect:"error",headers:{accept:"application/json"},signal:AbortSignal.timeout(this.fetchTimeoutMs)}),!n.ok)throw new Error(`the project's key set answered ${n.status}`);e=await n.json()}catch(s){throw this.lastFailure=s,new k("the project's key set cannot be read now",{cause:s})}this.lastFailure=void 0;let r=new Map;for(let s of Array.isArray(e.keys)?e.keys:[]){let i=s.alg;if(typeof s.kid!="string"||!xe(i))continue;let p=L[i];if(s.kty!==p.kty||s.use!==void 0&&s.use!=="sig")continue;let{d:c,...a}=s;try{r.set(s.kid,{alg:i,key:await crypto.subtle.importKey("jwk",a,p.import,!1,["verify"])})}catch{}}this.keys=r;let o=at(n.headers.get("cache-control"))??this.maxKeyAgeMs;this.keysUntil=this.now()+Math.min(Math.max(o,this.refetchIntervalMs),this.maxKeyAgeMs)}};function _e(t,e){let n=t.get("x-forwarded-proto")?.split(",")[0]?.trim().toLowerCase(),r=n==="https"||n==="http"?n:e.protocol.slice(0,-1),o=t.get("host")??e.host;return st.test(o)?`${r}://${o}${e.pathname}`:""}var st=/^(?:[a-z0-9-]+(?:\.[a-z0-9-]+)*|\[[0-9a-f:.]+\])(?::[0-9]{1,5})?$/i;function it(t){let e=new Headers;for(let[n,r]of Object.entries(t))if(r!==void 0)for(let o of Array.isArray(r)?r:[r])e.append(n,o);return e}function at(t){let e=/(?:^|,)\s*max-age=(\d+)/i.exec(t??"");return e?Number(e[1])*1e3:void 0}function Pe(t){if(!/^[A-Za-z0-9_-]*$/.test(t)||t.length%4===1)return null;let e=atob(t.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(t.length/4)*4,"=")),n=new Uint8Array(e.length);for(let r=0;r<e.length;r++)n[r]=e.charCodeAt(r);return n}function Ee(t){let e=Pe(t);if(!e)return null;try{let n=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(e));return typeof n=="object"&&n!==null&&!Array.isArray(n)?n:null}catch{return null}}function ct(t,e,n=Date.now()){let r=Object.hasOwn(t.entitlements,e)?t.entitlements[e]:void 0;return r?.active?r.expires_at===null?!0:Date.parse(r.expires_at)>(typeof n=="number"?n:n.getTime()):!1}var E=class extends Error{receipt;constructor(e){super(`the reservation ${JSON.stringify(e.idempotency_key)} is ${e.status} already: its job is not run again (a new one is a new Idempotency-Key)`),this.name="ReservationSettled",this.receipt=e}};async function pt(t,e,n,r){let{idempotencyKey:o,amount:s,ttlSeconds:i,metadata:p}=n;if(typeof o!="string"||o==="")throw new TypeError("idempotencyKey names the reservation for good: a retry with it is the same hold, never a second");let c={amount:s,...n.credits!==void 0?{credits:n.credits}:{limit:n.limit},...i!==void 0?{ttl_seconds:i}:{},...p!==void 0?{metadata:p}:{}},a=(await t.iap.holdSpend({path:{customer_id:e},headers:{"Idempotency-Key":o},body:c})).data;if(a.status!=="held")throw new E(a);let l={customer_id:a.customer,spend_id:a.id},y;try{y=await r(a)}catch(g){throw await t.iap.releaseSpend({path:l}).catch(()=>{}),g}return await t.iap.commitSpend({path:l}),y}var lt=new Set(["provider_unavailable","authentication_required","three_ds_failed"]);function dt(t){return t!==void 0&&lt.has(t)}function ut(t,e){return{[Te]:!0,commitAmount:t,value:e}}var Te=Symbol("palbase.payments.settleWalletHold");function yt(t){return typeof t=="object"&&t!==null&&Te in t}var _=class extends Error{hold;constructor(e){super(`wallet hold ${JSON.stringify(e.id)} is already ${e.status}: the work is not run again (use a new Idempotency-Key for a new hold)`),this.name="WalletHoldSettled",this.hold=e}};async function mt(t,e,n){let{idempotencyKey:r,walletKey:o,amount:s,ttlSeconds:i,reference:p,metadata:c}=e;if(typeof r!="string"||r.trim()==="")throw new TypeError("idempotencyKey is required for withWalletHold so retries never reserve funds twice");if(!Number.isInteger(s)||s<=0)throw new TypeError("amount must be a positive integer in minor units");let a={wallet_key:o,amount:s,...e.customerId!==void 0?{customer_id:e.customerId}:{spend_token:e.spendToken},...i!==void 0?{ttl_seconds:i}:{},...p!==void 0?{reference:p}:{},...c!==void 0?{metadata:c}:{}},l=(await t.payments.createWalletHold({headers:{"Idempotency-Key":r},body:a})).data;if(l.status!=="held")throw new _(l);let y;try{y=await n(l)}catch(g){throw await t.payments.releaseWalletHold({path:{hold_id:l.id}}).catch(()=>{}),g}return yt(y)?(y.commitAmount<=0?await t.payments.releaseWalletHold({path:{hold_id:l.id}}):await t.payments.commitWalletHold({path:{hold_id:l.id},body:{amount:y.commitAmount}}),y.value):(await t.payments.commitWalletHold({path:{hold_id:l.id}}),y)}function ht(t){return t.type.startsWith("payments.")}function ft(t){return t.type.startsWith("commerce.")}function gt(t){return t.type.startsWith("promotions.")}var wt=300,kt=/^[0-9]{1,12}$/;function St(t){return typeof t=="string"?new TextEncoder().encode(t):t instanceof ArrayBuffer?new Uint8Array(t):t}function vt(t){if(t.startsWith("whsec_")){let e=t.slice(6);try{let n=atob(e),r=new Uint8Array(n.length);for(let o=0;o<n.length;o++)r[o]=n.charCodeAt(o);return r}catch{}}return new TextEncoder().encode(t)}function bt(t,e){if(t.length!==e.length)return!1;let n=0;for(let r=0;r<t.length;r++)n|=t[r]^e[r];return n===0}function Rt(t){try{let e=atob(t),n=new Uint8Array(e.length);for(let r=0;r<e.length;r++)n[r]=e.charCodeAt(r);return n}catch{return null}}async function Me(t){if(typeof t.secret!="string"||t.secret==="")throw new TypeError("secret is the commerce hook signing secret (whsec_\u2026)");let e=t.webhookId?.trim()??"",n=t.webhookTimestamp?.trim()??"",r=t.webhookSignature?.trim()??"";if(!e||!n||!r)throw new u("missing_signature","webhook-id, webhook-timestamp, and webhook-signature headers are required");if(!kt.test(n))throw new u("malformed_signature","webhook-timestamp must be unix seconds");let o=t.toleranceSeconds??wt,s=Math.floor((t.now?.()??Date.now())/1e3);if(Math.abs(s-Number(n))>o)throw new u("stale_timestamp",`webhook-timestamp ${n} is outside tolerance (${o}s)`);let i=St(t.body),p=new TextEncoder().encode(`${e}.${n}.`),c=new Uint8Array(p.length+i.length);c.set(p,0),c.set(i,p.length);let a=vt(t.secret),l=a.buffer.slice(a.byteOffset,a.byteOffset+a.byteLength),y=await crypto.subtle.importKey("raw",l,{name:"HMAC",hash:"SHA-256"},!1,["sign"]),g=new Uint8Array(await crypto.subtle.sign("HMAC",y,c)),m=!1;for(let f of r.split(/\s+/)){if(!f.startsWith("v1,"))continue;let v=Rt(f.slice(3));if(v&&bt(g,v)){m=!0;break}}if(!m)throw new u("signature_mismatch","no v1 signature in webhook-signature matches the payload")}function Ae(t){return async e=>{let n=new Uint8Array(await e.arrayBuffer()),r=e.headers.get("webhook-id")??"";try{await Me({secret:t.secret,webhookId:r,webhookTimestamp:e.headers.get("webhook-timestamp"),webhookSignature:e.headers.get("webhook-signature"),body:n,toleranceSeconds:t.toleranceSeconds,now:t.now})}catch(i){let p=i instanceof u?i.code:"signature_mismatch",c=i instanceof Error?i.message:"invalid hook signature";return new Response(JSON.stringify({error:p,error_description:c}),{status:401,headers:{"content-type":"application/json"}})}let o;try{o=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(n))}catch{return new Response(JSON.stringify({error:"invalid_body",error_description:"hook body is not valid JSON"}),{status:400,headers:{"content-type":"application/json"}})}let s=await t.handle({hookPoint:e.headers.get("x-palbase-hook-point")??"",webhookId:r,payload:o,request:e});return new Response(JSON.stringify(s),{status:200,headers:{"content-type":"application/json"}})}}var P=class extends Error{hookPoint;constructor(e){super(`expected x-palbase-hook-point "discovery.rank", got "${e}"`),this.hookPoint=e}};function xt(t){let e=Ae({secret:t.secret,toleranceSeconds:t.toleranceSeconds,now:t.now,handle:n=>{if(n.hookPoint!==""&&n.hookPoint!=="discovery.rank")throw new P(n.hookPoint);return t.handle(n)}});return async n=>{try{return await e(n)}catch(r){if(r instanceof P)return new Response(JSON.stringify({error:"invalid_hook_point",error_description:r.message}),{status:400,headers:{"content-type":"application/json"}});throw r}}}function Et(t){return t.type.startsWith("campaigns.")}function _t(t){return t.type.startsWith("journey.")}async function*Pt(t){let e,n=new Set;do{let r=(await t(e)).data;yield r;let o=r.next_cursor??void 0;if(o!==void 0&&n.has(o))throw new Error(`the listing answered a cursor it had answered before (${o})`);o!==void 0&&n.add(o),e=o}while(e)}var Tt=/^[A-Za-z_][A-Za-z0-9_]{0,127}$/,Mt=/^(PALBASE_|NODE_|BUN_|NPM_|LD_|DYLD_|GIT_|SSH_)|^(PATH|HOME|SHELL|USER|TMPDIR|TMP|TEMP|PWD|IFS|ENV|BASH_ENV|SSL_CERT_FILE|SSL_CERT_DIR|CURL_CA_BUNDLE|REQUESTS_CA_BUNDLE|NO_PROXY|ALL_PROXY|HTTP_PROXY|HTTPS_PROXY|PG\w*)$/i;function Ce(t){return!Tt.test(t)||Mt.test(t)||/_PROXY$/i.test(t)}var At=/^(PORT|PALBASE_(URL|PROJECT_ID|MACHINE|REPLICAS|SECRET_KEY|WEBHOOK_SECRET|PLATFORM_SECRET|CONTRACT_OUT|CONTRACT_ENTRY|WEB_ORIGINS|SECRETS|DB_[A-Z0-9_]+))$/;function Ct(t){return At.test(t)}async function Ot(t={}){let e=t.env??process.env,n=e.PALBASE_SECRETS;if(n===void 0||n==="")return;if(n==="production")throw new TypeError("PALBASE_SECRETS=production: a production secret's value is never read back \u2014 only the machines that start with it are given it. Run here with PALBASE_SECRETS=development (palbase env:pull writes it), and set a value for this computer with palbase secrets:set NAME --dev");if(n!=="development")throw new TypeError(`PALBASE_SECRETS is development, not ${n}`);let r=t.url??e.PALBASE_URL??"",o=t.secretKey??e.PALBASE_SECRET_KEY??"";if(r===""||o==="")throw new TypeError("PALBASE_SECRETS reads the project's Secrets with PALBASE_URL and PALBASE_SECRET_KEY: give both (palbase env:pull writes them)");let s=H({url:new URL(r).origin,secretKey:o,fetch:t.fetch}),{data:i}=await s.secrets.getEnvironmentValues({path:{environment:n}}),p=[],c=[],a=[];for(let[l,y]of Object.entries(i.values)){if(Ce(l)){a.push(l);continue}if(e[l]!==void 0&&e[l]!==""){c.push(l);continue}e[l]=y,p.push(l)}return{set:n,loaded:p.sort(),kept:c.sort(),refused:a.sort()}}export{h as a,S as b,R as c,H as d,u as e,me as f,he as g,fe as h,$e as i,d as j,k,tt as l,B as m,_e as n,ct as o,E as p,pt as q,dt as r,ut as s,_ as t,mt as u,ht as v,ft as w,gt as x,Me as y,Ae as z,xt as A,Et as B,_t as C,Pt as D,Ce as E,Ct as F,Ot as G};
@@ -1,2 +1,2 @@
1
- /*! palbase 0.73.0 — Palbase SDK License (see LICENSE) */
1
+ /*! palbase 0.74.0 — Palbase SDK License (see LICENSE) */
2
2
  import{lstat as E,mkdir as k,readdir as b,readFile as j,rename as F,rm as J,writeFile as R}from"node:fs/promises";import{join as $}from"node:path";var o="palbase/strings",g="_meta.json",m=3,S=r=>typeof r=="object"&&r!==null&&!Array.isArray(r);function w(r){try{return Intl.getCanonicalLocales(r)[0]}catch{return}}function O(r,t){try{return JSON.parse(r)}catch(n){throw new Error(`${t} is not JSON: ${n.message}`)}}async function M(r){let t=$(r,o);try{if(!(await E(t)).isDirectory())throw new Error(`${o} is not a directory: the strings live in a directory of their own`)}catch(e){if(e.code==="ENOENT")return;throw e}let n=new Map;for(let e of await b(t,{withFileTypes:!0}))if(!(e.name.startsWith(".")||!e.name.endsWith(".json"))){if(!e.isFile())throw new Error(`${o}/${e.name} is not a regular file`);n.set(e.name,await j($(t,e.name),"utf8"))}return n.size===0?void 0:n}async function N(r){let t=await M(r);if(t===void 0)return;let n=t.get(g);if(n===void 0)throw new Error(`${o}/${g} is missing: it names the source language, and without it the language files are not a table`);let e=O(n,`${o}/${g}`);if(!S(e))throw new Error(`${o}/${g}: not a JSON object`);let c=e.version;if(c!==m)throw new Error(`${o}/${g}: version ${JSON.stringify(c)} is not one this reads (${m})`);let s=e.source;if(typeof s!="string"||w(s)!==s)throw new Error(`${o}/${g}: source ${JSON.stringify(s)} is not a language tag as it is written (${w(String(s))??"en, en-US, zh-Hans"})`);let f=new Map;for(let u of[...t.keys()].sort()){if(u===g)continue;let i=u.slice(0,-5),a=`${o}/${u}`,l=w(i);if(l===void 0)throw new Error(`${a}: ${JSON.stringify(i)} is not a language tag`);if(l!==i)throw new Error(`${a}: the language is written ${l} \u2014 name the file ${l}.json`);if(i===s)throw new Error(`${a}: ${i} is the source language \u2014 its text is the key itself, and it has no file`);if(i==="und"||i==="root"||i.startsWith("x-"))throw new Error(`${a}: ${i} is no language a request names \u2014 name the file for one (en, de, pt-BR)`);let d=O(t.get(u),a);if(!S(d))throw new Error(`${a}: not a JSON object of "sentence": "translation"`);let h=new Map;for(let[p,y]of Object.entries(d)){if(typeof y!="string")throw new Error(`${a}: the translation of ${JSON.stringify(p)} is not a string`);h.set(p,y)}f.set(i,h)}return{format:c,source:s,languages:f}}async function P(r){let t=await N(r);if(t===void 0)return;let n={};Object.setPrototypeOf(n,null);for(let[e,c]of t.languages)for(let[s,f]of c)Object.hasOwn(n,s)||(n[s]={},Object.setPrototypeOf(n[s],null)),n[s][e]=f;return{source:t.source,locales:[t.source,...t.languages.keys()],strings:n}}export{P as a};
@@ -1,2 +1,2 @@
1
- /*! palbase 0.73.0 — Palbase SDK License (see LICENSE) */
1
+ /*! palbase 0.74.0 — Palbase SDK License (see LICENSE) */
2
2
  var u="X-PoW-Challenge-ID",c="X-PoW-Nonce";function m(e){if(typeof e!="object"||e===null)return null;let t=e;if(t.error!=="pow_required"||typeof t.challenge!="object"||t.challenge===null)return null;let{id:n,prefix:r,difficulty:o}=t.challenge;return typeof n!="string"||typeof r!="string"||typeof o!="number"||!Number.isInteger(o)||o<0?null:{id:n,prefix:r,difficulty:o}}function d(e){return 8*2**e}var s;async function l(){if(s)return s;let e=globalThis;if(e.process?.versions?.node!==void 0||e.process?.versions?.bun!==void 0)try{let r=(await import("node:crypto")).createHash;if(typeof r=="function")return s=o=>new Uint8Array(r("sha256").update(o).digest()),s}catch{}let t=new TextEncoder;return s=async n=>new Uint8Array(await crypto.subtle.digest("SHA-256",t.encode(n))),s}function p(e){let t=0;for(let n of e){if(n===0){t+=8;continue}return t+Math.clz32(n)-24}return t}var w=4096,g=typeof globalThis.setImmediate=="function"?()=>new Promise(e=>globalThis.setImmediate(e)):()=>new Promise(e=>setTimeout(e,0));async function y(e,t={}){if(e.difficulty>24)throw new Error(`proof-of-work: difficulty ${e.difficulty} is above auth's ceiling of 24`);let n=await l(),r=d(e.difficulty),o=Date.now()+(t.timeLimitMs??12e4);for(let i=0;i<r;i++){if(i%w===0&&i>0){if(await g(),t.signal?.aborted)throw t.signal.reason??new DOMException("proof-of-work aborted","AbortError");if(Date.now()>o)throw new Error(`proof-of-work: gave up on difficulty ${e.difficulty} after ${i} attempts`)}let f=n(e.prefix+i),a=f instanceof Uint8Array?f:await f;if(p(a)>=e.difficulty)return{[u]:e.id,[c]:String(i)}}throw new Error(`proof-of-work: no nonce for difficulty ${e.difficulty} within ${r} attempts`)}export{m as a,y as b};