palbase 0.76.0 → 0.77.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 (76) hide show
  1. package/dist/ai/index.js +2 -2
  2. package/dist/ai-sdk/index.js +2 -2
  3. package/dist/backend/engine.js +2 -2
  4. package/dist/backend/env.js +1 -1
  5. package/dist/backend/index.js +3 -3
  6. package/dist/backend/stack.js +1 -1
  7. package/dist/backend/test.js +2 -2
  8. package/dist/chunks/{A3I7H7QN.js → 34HGL5FX.js} +1 -1
  9. package/dist/chunks/{ALT62XIG.js → 4M4GEXJS.js} +2 -2
  10. package/dist/chunks/{2NEPN2ZZ.js → 6WCN7VAZ.js} +2 -2
  11. package/dist/chunks/{ZCMCYI2D.js → 7RTPVUIH.js} +2 -2
  12. package/dist/chunks/{5RNXCTOO.js → AUOFL6RB.js} +2 -2
  13. package/dist/chunks/{KEGVHELA.js → BDHVYVWT.js} +1 -1
  14. package/dist/chunks/CYNLRAAW.js +2 -0
  15. package/dist/chunks/{5YJZAPY2.js → DENZSXKJ.js} +2 -2
  16. package/dist/chunks/ES24JS2D.js +2 -0
  17. package/dist/chunks/{Q4UWBIJ6.js → F6OGRDZB.js} +2 -2
  18. package/dist/chunks/{D6NOE76D.js → FE7ZBADH.js} +1 -1
  19. package/dist/chunks/{SVWF7ABJ.js → FN5763FR.js} +2 -2
  20. package/dist/chunks/{DKYFIOWM.js → G3PH5T6N.js} +1 -1
  21. package/dist/chunks/{ISMWEEGW.js → GFBWGJW3.js} +1 -1
  22. package/dist/chunks/{EXLA3A7O.js → IZVBCAKH.js} +2 -2
  23. package/dist/chunks/{TGQGGUE6.js → JOVXELK5.js} +2 -2
  24. package/dist/chunks/KLK7HZZ7.js +18 -0
  25. package/dist/chunks/{MKVIRNSJ.js → ONLXIZ6E.js} +2 -2
  26. package/dist/chunks/{BRDO3ZPT.js → QWXF6KWI.js} +1 -1
  27. package/dist/chunks/{UHN63FGH.js → RQJ4MX2H.js} +2 -2
  28. package/dist/chunks/{PGQNRJ2C.js → RRS7TQKX.js} +2 -2
  29. package/dist/chunks/{33XOVYAU.js → U4VX7NKX.js} +4 -4
  30. package/dist/chunks/{UOW74IHY.js → VOLGPAPR.js} +2 -2
  31. package/dist/chunks/{3CN6HGTW.js → WXT24CE5.js} +1 -1
  32. package/dist/chunks/{TUK6NH2Q.js → ZZNNCI6A.js} +2 -2
  33. package/dist/cli.js +241 -187
  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/ai/src/ai.d.ts +6 -2
  52. package/types/ai/src/chats.d.ts +22 -10
  53. package/types/ai/src/index.d.ts +2 -2
  54. package/types/ai/src/pools.d.ts +15 -24
  55. package/types/cloud/src/generated/project.d.ts +3 -3
  56. package/types/cloud/src/generated/studio.d.ts +4 -6
  57. package/types/internal/src/ai-machines.d.ts +120 -0
  58. package/types/internal/src/chat.d.ts +1 -1
  59. package/types/internal/src/modules/ai.d.ts +186 -77
  60. package/types/internal/src/modules/analytics.d.ts +5 -1
  61. package/types/internal/src/modules/auth.d.ts +3 -28
  62. package/types/internal/src/modules/commerce.d.ts +92 -13
  63. package/types/internal/src/modules/events.d.ts +2 -2
  64. package/types/internal/src/modules/iap.d.ts +2 -2
  65. package/types/internal/src/modules/journeys.d.ts +2 -2
  66. package/types/internal/src/modules/machines.d.ts +33 -33
  67. package/types/internal/src/modules/notify.d.ts +2 -2
  68. package/types/internal/src/modules/payments.d.ts +83 -14
  69. package/types/internal/src/modules/stores.d.ts +3 -3
  70. package/types/internal/src/modules/workspaces.d.ts +5 -5
  71. package/types/web/src/ai-machines.d.ts +76 -0
  72. package/types/web/src/chat.d.ts +1 -1
  73. package/types/web/src/index.d.ts +2 -0
  74. package/types/web/src/templates.d.ts +8 -0
  75. package/dist/chunks/3VGWTVKI.js +0 -2
  76. package/dist/chunks/YRYPXVAJ.js +0 -18
@@ -1,2 +1,2 @@
1
- /*! palbase 0.76.0 — Palbase SDK License (see LICENSE) */
2
- import{b}from"./BRDO3ZPT.js";import{a as k,b as A}from"./ISMWEEGW.js";import{randomBytes as _}from"node:crypto";async function N(){let n={keys:[{id:"k1",key:_(32).toString("base64url"),activates_at:new Date(0).toISOString()}],lookup:_(32).toString("base64url")},e=new b({fetch:async()=>n});return await e.load(),e.close(),e}var f=class extends Error{status;error;data;body;constructor(e,a,l,d){let u=d!==null&&typeof d=="object"?d:{},o=u.error??String(l);super(`${e} ${a} \u2192 ${l} ${o}${u.error_description?`: ${u.error_description}`:""}`),this.name="TestApiError",this.status=l,this.error=o,this.data=u.data,this.body=u}};function x(n,e){if(!n)throw new Error(`${e} is not set: the test client has nowhere to send its requests \u2014 \`palbase test\` sets it, as the platform's test run does`);return n}function B(n){let e=n.split(".")[1];if(!e)return null;try{let a=JSON.parse(Buffer.from(e,"base64url").toString("utf8"));return typeof a.exp=="number"?a.exp-Math.floor(Date.now()/1e3):null}catch{return null}}function L(n){try{return JSON.parse(n)}catch{return n}}function $(n){let e=x(n.baseUrl,"PALBASE_TEST_BASE_URL").replace(/\/+$/,""),a=n.apiKey||void 0,l=(n.authUrl??e).replace(/\/+$/,""),d=n.fetch??fetch,u=[],o=null;async function c(r,t,s,i,T={},O=!0){let g={...T.headers},m=h=>Object.keys(g).some(R=>R.toLowerCase()===h);a!==void 0&&!m("apikey")&&(g.apikey=a),o&&O&&!m("authorization")&&(g.authorization=`Bearer ${o}`),i!==void 0&&!m("content-type")&&(g["content-type"]="application/json");let I=Date.now(),p=await d(`${r}${s}`,{method:t,headers:g,body:i===void 0?void 0:JSON.stringify(i)}),E=await p.text(),S=E?L(E):void 0;if(u.push({method:t,path:s,status:p.status,ms:Date.now()-I}),!p.ok){let h=p.status===401&&o?B(o):null;throw h!==null&&h<=0?new f(t,s,p.status,{error:"access_token_expired",error_description:`this run's access token expired ${-h}s ago: a test user's token is made for one run \u2014 run the tests again (\`palbase test\` makes new ones)`}):new f(t,s,p.status,S)}return S}let y={requests:u,get:(r,t)=>c(e,"GET",r,void 0,t),post:(r,t,s)=>c(e,"POST",r,t,s),patch:(r,t,s)=>c(e,"PATCH",r,t,s),put:(r,t,s)=>c(e,"PUT",r,t,s),delete:(r,t)=>c(e,"DELETE",r,void 0,t),query:(r,t,s)=>c(e,"QUERY",r,t,s),async signInAs(r){let t=n.identities?.[r];if(!t){let s=Object.keys(n.identities??{});throw s.length===0?new Error(`no test user named ${JSON.stringify(r)}: this run has no test users \u2014 none were named (the machine's test users, or \`palbase test --users <names>\`), or they could not be made: the run's log says which`):new Error(`no test user named ${JSON.stringify(r)} \u2014 this run has: ${s.join(", ")}. A run makes the test users its machine names (palbase machines:update <machine> --test-users <names>) or \`palbase test --users <names>\` names`)}return t.accessToken?(o=t.accessToken,{id:t.id??"",email:t.email}):y.signIn(t)},async signIn(r){if(a===void 0)throw new Error("PALBASE_TEST_API_KEY is not set: a sign-in at the project's auth is made with a publishable key of the project's (palbase apps:sdkconfig shows one) \u2014 a run's test users come with their tokens: api.signInAs(name)");let t=i=>c(l,"POST","/auth/login",r,i?{headers:i}:{},!1),s;try{s=await t()}catch(i){let T=i instanceof f&&i.status===403?k(i.body):null;if(!T)throw i;s=await t(await A(T))}return o=s.access_token,s.user??{id:""}},async signOut(){await c(l,"POST","/auth/logout",void 0),o=null},asAnonymous(){o=null}};return y}function P(n){if(!n)return{};let e;try{e=JSON.parse(n)}catch{throw new Error("PALBASE_TEST_IDENTITIES is set but is not JSON: the run that started these tests handed over a broken set of test users")}if(e===null||typeof e!="object"||Array.isArray(e))throw new Error("PALBASE_TEST_IDENTITIES is not an object of test users by name");return e}var j={get stack(){return!!process.env.PALBASE_TEST_BASE_URL},minted(n){return Object.prototype.hasOwnProperty.call(P(process.env.PALBASE_TEST_IDENTITIES),n)}},w,q=new Proxy({},{get(n,e){return w??=$({baseUrl:process.env.PALBASE_TEST_BASE_URL??"",apiKey:process.env.PALBASE_TEST_API_KEY??"",authUrl:process.env.PALBASE_TEST_AUTH_URL,identities:P(process.env.PALBASE_TEST_IDENTITIES)}),Reflect.get(w,e,w)}});export{N as a,f as b,$ as c,j as d,q as e};
1
+ /*! palbase 0.77.0 — Palbase SDK License (see LICENSE) */
2
+ import{b}from"./QWXF6KWI.js";import{a as k,b as A}from"./GFBWGJW3.js";import{randomBytes as _}from"node:crypto";async function N(){let n={keys:[{id:"k1",key:_(32).toString("base64url"),activates_at:new Date(0).toISOString()}],lookup:_(32).toString("base64url")},e=new b({fetch:async()=>n});return await e.load(),e.close(),e}var f=class extends Error{status;error;data;body;constructor(e,a,l,d){let u=d!==null&&typeof d=="object"?d:{},o=u.error??String(l);super(`${e} ${a} \u2192 ${l} ${o}${u.error_description?`: ${u.error_description}`:""}`),this.name="TestApiError",this.status=l,this.error=o,this.data=u.data,this.body=u}};function x(n,e){if(!n)throw new Error(`${e} is not set: the test client has nowhere to send its requests \u2014 \`palbase test\` sets it, as the platform's test run does`);return n}function B(n){let e=n.split(".")[1];if(!e)return null;try{let a=JSON.parse(Buffer.from(e,"base64url").toString("utf8"));return typeof a.exp=="number"?a.exp-Math.floor(Date.now()/1e3):null}catch{return null}}function L(n){try{return JSON.parse(n)}catch{return n}}function $(n){let e=x(n.baseUrl,"PALBASE_TEST_BASE_URL").replace(/\/+$/,""),a=n.apiKey||void 0,l=(n.authUrl??e).replace(/\/+$/,""),d=n.fetch??fetch,u=[],o=null;async function c(r,t,s,i,T={},O=!0){let g={...T.headers},m=h=>Object.keys(g).some(R=>R.toLowerCase()===h);a!==void 0&&!m("apikey")&&(g.apikey=a),o&&O&&!m("authorization")&&(g.authorization=`Bearer ${o}`),i!==void 0&&!m("content-type")&&(g["content-type"]="application/json");let I=Date.now(),p=await d(`${r}${s}`,{method:t,headers:g,body:i===void 0?void 0:JSON.stringify(i)}),E=await p.text(),S=E?L(E):void 0;if(u.push({method:t,path:s,status:p.status,ms:Date.now()-I}),!p.ok){let h=p.status===401&&o?B(o):null;throw h!==null&&h<=0?new f(t,s,p.status,{error:"access_token_expired",error_description:`this run's access token expired ${-h}s ago: a test user's token is made for one run \u2014 run the tests again (\`palbase test\` makes new ones)`}):new f(t,s,p.status,S)}return S}let y={requests:u,get:(r,t)=>c(e,"GET",r,void 0,t),post:(r,t,s)=>c(e,"POST",r,t,s),patch:(r,t,s)=>c(e,"PATCH",r,t,s),put:(r,t,s)=>c(e,"PUT",r,t,s),delete:(r,t)=>c(e,"DELETE",r,void 0,t),query:(r,t,s)=>c(e,"QUERY",r,t,s),async signInAs(r){let t=n.identities?.[r];if(!t){let s=Object.keys(n.identities??{});throw s.length===0?new Error(`no test user named ${JSON.stringify(r)}: this run has no test users \u2014 none were named (the machine's test users, or \`palbase test --users <names>\`), or they could not be made: the run's log says which`):new Error(`no test user named ${JSON.stringify(r)} \u2014 this run has: ${s.join(", ")}. A run makes the test users its machine names (palbase machines:update <machine> --test-users <names>) or \`palbase test --users <names>\` names`)}return t.accessToken?(o=t.accessToken,{id:t.id??"",email:t.email}):y.signIn(t)},async signIn(r){if(a===void 0)throw new Error("PALBASE_TEST_API_KEY is not set: a sign-in at the project's auth is made with a publishable key of the project's (palbase apps:sdkconfig shows one) \u2014 a run's test users come with their tokens: api.signInAs(name)");let t=i=>c(l,"POST","/auth/login",r,i?{headers:i}:{},!1),s;try{s=await t()}catch(i){let T=i instanceof f&&i.status===403?k(i.body):null;if(!T)throw i;s=await t(await A(T))}return o=s.access_token,s.user??{id:""}},async signOut(){await c(l,"POST","/auth/logout",void 0),o=null},asAnonymous(){o=null}};return y}function P(n){if(!n)return{};let e;try{e=JSON.parse(n)}catch{throw new Error("PALBASE_TEST_IDENTITIES is set but is not JSON: the run that started these tests handed over a broken set of test users")}if(e===null||typeof e!="object"||Array.isArray(e))throw new Error("PALBASE_TEST_IDENTITIES is not an object of test users by name");return e}var j={get stack(){return!!process.env.PALBASE_TEST_BASE_URL},minted(n){return Object.prototype.hasOwnProperty.call(P(process.env.PALBASE_TEST_IDENTITIES),n)}},w,q=new Proxy({},{get(n,e){return w??=$({baseUrl:process.env.PALBASE_TEST_BASE_URL??"",apiKey:process.env.PALBASE_TEST_API_KEY??"",authUrl:process.env.PALBASE_TEST_AUTH_URL,identities:P(process.env.PALBASE_TEST_IDENTITIES)}),Reflect.get(w,e,w)}});export{N as a,f as b,$ as c,j as d,q as e};
@@ -1,2 +1,2 @@
1
- /*! palbase 0.76.0 — Palbase SDK License (see LICENSE) */
1
+ /*! palbase 0.77.0 — Palbase SDK License (see LICENSE) */
2
2
  var d=Object.defineProperty;var e=(c,a)=>{for(var b in a)d(c,b,{get:a[b],enumerable:!0})};export{e as a};
@@ -1,2 +1,2 @@
1
- /*! palbase 0.76.0 — Palbase SDK License (see LICENSE) */
2
- import{b as c,f as u}from"./UOW74IHY.js";var l={attempts:3,maxWaitSeconds:30},y=new Set([429,502,503,504]);function x(e,t=l){let r=t.sleep??h;return{async send(o){let n=p(o),a=n.body,m=!a||a.kind!=="raw"||u(a.value),f=(n.method==="GET"||n.method==="HEAD"||n.idempotent===!0)&&m;for(let i=1;;i++)try{return await e.send(n)}catch(s){if(!f||i>=t.attempts||!(s instanceof c)||n.signal?.aborted)throw s;let d=b(s,i,t.maxWaitSeconds);if(d===void 0)throw s;await r(d*1e3,n.signal)}}}}function p(e){return e.idempotent?Object.entries(e.headers??{}).some(([r,o])=>r.toLowerCase()==="idempotency-key"&&o!==void 0&&o!==null&&o!=="")?e:{...e,headers:{...e.headers,"Idempotency-Key":w()}}:e}function b(e,t,r){return y.has(e.status)||e.code==="network_error"?e.retryAfter!==void 0?e.retryAfter<=r?e.retryAfter:void 0:Math.min(.5*2**(t-1),r)*(.8+Math.random()*.4):void 0}function h(e,t){return new Promise((r,o)=>{if(t?.aborted)return o(t.reason);let n=()=>{clearTimeout(a),o(t?.reason)},a=setTimeout(()=>{t?.removeEventListener("abort",n),r()},e);t?.addEventListener("abort",n,{once:!0})})}function w(){if(typeof crypto.randomUUID=="function")return crypto.randomUUID();let e=crypto.getRandomValues(new Uint8Array(16));e[6]=e[6]&15|64,e[8]=e[8]&63|128;let t=[...e].map(r=>r.toString(16).padStart(2,"0")).join("");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}export{l as a,x as b,b as c,w as d};
1
+ /*! palbase 0.77.0 — Palbase SDK License (see LICENSE) */
2
+ import{b as c,f as u}from"./VOLGPAPR.js";var l={attempts:3,maxWaitSeconds:30},y=new Set([429,502,503,504]);function x(e,t=l){let r=t.sleep??h;return{async send(o){let n=p(o),a=n.body,m=!a||a.kind!=="raw"||u(a.value),f=(n.method==="GET"||n.method==="HEAD"||n.idempotent===!0)&&m;for(let i=1;;i++)try{return await e.send(n)}catch(s){if(!f||i>=t.attempts||!(s instanceof c)||n.signal?.aborted)throw s;let d=b(s,i,t.maxWaitSeconds);if(d===void 0)throw s;await r(d*1e3,n.signal)}}}}function p(e){return e.idempotent?Object.entries(e.headers??{}).some(([r,o])=>r.toLowerCase()==="idempotency-key"&&o!==void 0&&o!==null&&o!=="")?e:{...e,headers:{...e.headers,"Idempotency-Key":w()}}:e}function b(e,t,r){return y.has(e.status)||e.code==="network_error"?e.retryAfter!==void 0?e.retryAfter<=r?e.retryAfter:void 0:Math.min(.5*2**(t-1),r)*(.8+Math.random()*.4):void 0}function h(e,t){return new Promise((r,o)=>{if(t?.aborted)return o(t.reason);let n=()=>{clearTimeout(a),o(t?.reason)},a=setTimeout(()=>{t?.removeEventListener("abort",n),r()},e);t?.addEventListener("abort",n,{once:!0})})}function w(){if(typeof crypto.randomUUID=="function")return crypto.randomUUID();let e=crypto.getRandomValues(new Uint8Array(16));e[6]=e[6]&15|64,e[8]=e[8]&63|128;let t=[...e].map(r=>r.toString(16).padStart(2,"0")).join("");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}export{l as a,x as b,b as c,w as d};
@@ -1,4 +1,4 @@
1
- /*! palbase 0.76.0 — Palbase SDK License (see LICENSE) */
1
+ /*! palbase 0.77.0 — Palbase SDK License (see LICENSE) */
2
2
  var Rt=d=>[...new Uint8Array(d)].map(t=>t.toString(16).padStart(2,"0")).join(""),_t=d=>`pw-font-${d}`;function ne(d){return(typeof d=="string"?/^asset:([0-9a-f-]{36})$/.exec(d):null)?.[1]}async function an(d,t={}){let l={},a=t.fetch??((c,p)=>globalThis.fetch(c,p));return await Promise.all(d.map(async c=>{try{if(!/^https:\/\//.test(c.url))return;let p=await a(c.url,{signal:t.signal,credentials:"omit"});if(!p.ok)return;let g=await p.arrayBuffer();if(g.byteLength!==c.bytes&&c.bytes>0||Rt(await globalThis.crypto.subtle.digest("SHA-256",g))!==c.sha256.toLowerCase())return;let b=At(c.kind,new Uint8Array(g));if(b===void 0)return;let y=await Et(c,g,b,t);y&&(l[c.id]=y)}catch{}})),l}var C=(d,t,l=0)=>d.length>=l+t.length&&t.every((a,c)=>d[l+c]===a),W=d=>[...d].map(t=>t.charCodeAt(0));function At(d,t){switch(d){case"image":return C(t,[137,80,78,71,13,10,26,10])?"image/png":C(t,[255,216,255])?"image/jpeg":C(t,W("RIFF"))&&C(t,W("WEBP"),8)?"image/webp":void 0;case"video":return C(t,W("ftyp"),4)?C(t,W("qt "),8)?"video/quicktime":"video/mp4":C(t,[26,69,223,163])?"video/webm":void 0;case"font":return C(t,W("wOF2"))?"font/woff2":C(t,W("wOFF"))?"font/woff":C(t,W("OTTO"))?"font/otf":C(t,[0,1,0,0])||C(t,W("true"))?"font/ttf":void 0;case"html":return C(t,[80,75,3,4])||C(t,[80,75,5,6])?"application/zip":void 0;default:return}}async function Et(d,t,l,a){switch(d.kind){case"image":case"video":return{kind:d.kind,url:URL.createObjectURL(new Blob([t],{type:l}))};case"font":{let c=_t(d.id),p=globalThis.FontFace,g=a.fonts??globalThis.document?.fonts;if(!p||!g)return;let h=new p(c,t,{display:"block"});return await h.load(),g.add(h),{kind:"font",url:"",family:c}}case"html":{let c=await Lt(new Uint8Array(t)),p=Ot(c);return p===void 0?void 0:{kind:"html",url:"",html:p}}}}async function Lt(d){let t=new DataView(d.buffer,d.byteOffset,d.byteLength),l=-1;for(let h=d.length-22;h>=Math.max(0,d.length-22-65535);h--)if(t.getUint32(h,!0)===101010256){l=h;break}if(l<0)throw new Error("not a zip");let a=t.getUint16(l+10,!0),c=t.getUint32(l+16,!0),p=new Map,g=0;for(let h=0;h<a;h++){if(t.getUint32(c,!0)!==33639248)throw new Error("a broken zip");let b=t.getUint16(c+10,!0),y=t.getUint32(c+20,!0),m=t.getUint32(c+24,!0),v=t.getUint16(c+28,!0),A=t.getUint16(c+30,!0),P=t.getUint16(c+32,!0),R=t.getUint32(c+42,!0),x=new TextDecoder().decode(d.subarray(c+46,c+46+v));if(c+=46+v+A+P,x.endsWith("/"))continue;if(x.startsWith("/")||x.split("/").includes(".."))throw new Error("a path leaving the zip");if(g+=m,p.size>=200||g>20971520)throw new Error("a zip too large");let T=R+30+t.getUint16(R+26,!0)+t.getUint16(R+28,!0),O=d.subarray(T,T+y);if(b===0)p.set(x,O);else if(b===8)p.set(x,await Pt(O));else throw new Error("a zip entry compressed another way")}return p}async function Pt(d){let t=new Response(new Uint8Array(d)).body.pipeThrough(new DecompressionStream("deflate-raw"));return new Uint8Array(await new Response(t).arrayBuffer())}var Tt={html:"text/html",css:"text/css",js:"text/javascript",mjs:"text/javascript",json:"application/json",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",webp:"image/webp",gif:"image/gif",svg:"image/svg+xml",mp4:"video/mp4",webm:"video/webm",woff2:"font/woff2",woff:"font/woff",ttf:"font/ttf",otf:"font/otf"};function qe(d,t){let l=Tt[d.split(".").pop()?.toLowerCase()??""]??"application/octet-stream",a="";for(let c=0;c<t.length;c+=32768)a+=String.fromCharCode(...t.subarray(c,c+32768));return`data:${l};base64,${btoa(a)}`}var $t="default-src 'none'; img-src data:; media-src data:; font-src data:; style-src 'unsafe-inline' data:; script-src 'unsafe-inline' data:";function Ot(d){let t=d.get("index.html");if(!t)return;let l=new TextDecoder().decode(t),a=y=>new TextDecoder().decode(d.get(y)),c=y=>{let m=y.replace(/^\.\//,"").split(/[?#]/)[0];return d.has(m)?m:void 0},p=y=>y.replace(/url\(\s*(['"]?)([^'")]+)\1\s*\)/g,(m,v,A)=>{let P=c(A);return P?`url("${qe(P,d.get(P))}")`:m}),g=globalThis.DOMParser;if(!g)return;let h=new g().parseFromString(l,"text/html");for(let y of[...h.querySelectorAll('link[rel~="stylesheet"][href]')]){let m=c(y.getAttribute("href")),v=h.createElement("style");v.textContent=m?p(a(m)):"",y.replaceWith(v)}for(let y of[...h.querySelectorAll("style")])y.textContent=p(y.textContent??"");for(let y of[...h.querySelectorAll("[src], [href], [poster]")])for(let m of["src","href","poster"]){let v=y.getAttribute(m);if(v===null)continue;let A=c(v);A?y.setAttribute(m,qe(A,d.get(A))):/^(https?:)?\/\//i.test(v)&&y.removeAttribute(m)}for(let y of[...h.querySelectorAll("[style]")])y.setAttribute("style",p(y.getAttribute("style")??""));let b=h.createElement("meta");return b.setAttribute("http-equiv","Content-Security-Policy"),b.setAttribute("content",$t),h.head.prepend(b),`<!doctype html>${h.documentElement.outerHTML}`}var K=(d,t,l)=>`M${d-l} ${t}a${l} ${l} 0 1 0 ${2*l} 0a${l} ${l} 0 1 0 ${-2*l} 0`,de={ad_free:["M3 7h18v10H3z","M4 4l16 16"],bell:["M6 16v-5a6 6 0 0 1 12 0v5l2 2H4z","M10 21a2 2 0 0 0 4 0"],bolt:["M13 2L4 14h7l-1 8 9-12h-7z"],book:["M5 4h11a3 3 0 0 1 3 3v13H8a3 3 0 0 1-3-3z","M5 17a3 3 0 0 1 3-3h11"],chart:["M3 20h18","M6 20v-8","M11 20V5","M16 20v-6","M21 20V9"],chat:["M4 5h16v11H9l-5 4z"],check:["M5 12l5 5 9-10"],check_circle:[K(12,12,9),"M8 12l3 3 5-6"],clock:[K(12,12,9),"M12 7v5l3 2"],cloud:["M7 18a4 4 0 0 1-.5-7.97A6 6 0 0 1 18 9a4.5 4.5 0 0 1-.5 9z"],crown:["M3 8l4 4 5-7 5 7 4-4-2 11H5z"],download:["M12 4v11","M7 10l5 5 5-5","M4 20h16"],gift:["M3 9h18v4H3z","M5 13v8h14v-8","M12 9v12","M12 9C10 5 6 5 6 7.5S12 9 12 9zm0 0c2-4 6-4 6-1.5S12 9 12 9z"],globe:[K(12,12,9),"M3 12h18","M12 3a14 14 0 0 1 0 18a14 14 0 0 1 0-18z"],heart:["M12 20s-7-4.5-9-9a4.5 4.5 0 0 1 9-3 4.5 4.5 0 0 1 9 3c-2 4.5-9 9-9 9z"],infinity:["M7 9a3 3 0 1 0 0 6c3 0 7-6 10-6a3 3 0 1 1 0 6c-3 0-7-6-10-6z"],lock_open:["M5 11h14v10H5z","M8 11V7a4 4 0 0 1 7.5-2"],music:["M9 18V5l11-2v13",K(6,18,3),K(17,16,3)],people:[K(9,8,3.5),"M2 20a7 7 0 0 1 14 0","M16 4.5a3.5 3.5 0 0 1 0 7","M18 14a6 6 0 0 1 4 6"],person:[K(12,8,4),"M4 21a8 8 0 0 1 16 0"],photo:["M3 5h18v14H3z",K(8.5,9.5,1.5),"M3 17l5-5 4 4 3-3 6 6"],shield:["M12 3l8 3v6c0 5-3.5 8-8 9-4.5-1-8-4-8-9V6z"],sparkles:["M12 3l1.8 5.2L19 10l-5.2 1.8L12 17l-1.8-5.2L5 10l5.2-1.8z","M19 15l.8 2.2L22 18l-2.2.8L19 21l-.8-2.2L16 18l2.2-.8z"],star:["M12 3l2.8 5.7 6.2.9-4.5 4.4 1 6.2L12 17.3l-5.5 2.9 1-6.2L3 9.6l6.2-.9z"],video:["M3 6h12v12H3z","M15 10l6-3v10l-6-3z"],arrow_right:["M4 12h15","M13 6l6 6-6 6"],calendar:["M4 6h16v15H4z","M4 10h16","M8 3v5","M16 3v5"],close:["M6 6l12 12","M18 6L6 18"],lock:["M5 11h14v10H5z","M8 11V7a4 4 0 0 1 8 0v4"],play:["M7 4l13 8-13 8z"],quote:["M5 17c3 0 4-2 4-5V7H4v5h3","M15 17c3 0 4-2 4-5V7h-5v5h3"],trophy:["M7 4h10v5a5 5 0 0 1-10 0z","M7 6H4v2a3 3 0 0 0 3 3","M17 6h3v2a3 3 0 0 1-3 3","M12 14v4","M8 21h8","M9 18h6v3H9z"]};var Be="http://www.w3.org/2000/svg";function pe(d,t,l){let a=d.createElementNS(Be,"svg");a.setAttribute("viewBox","0 0 24 24"),a.setAttribute("width",String(l)),a.setAttribute("height",String(l)),a.setAttribute("fill","none"),a.setAttribute("stroke","currentColor"),a.setAttribute("stroke-width","2"),a.setAttribute("stroke-linecap","round"),a.setAttribute("stroke-linejoin","round"),a.setAttribute("aria-hidden","true"),a.setAttribute("focusable","false");for(let c of t){let p=d.createElementNS(Be,"path");p.setAttribute("d",c),a.append(p)}return a}var dn=2,pn=2,f=(d,t=!1)=>({kind:"value",value:"plain",def:d,required:t}),j=d=>({kind:"value",value:"color",def:d}),We=d=>({kind:"value",value:"spacing",def:d}),zt=d=>({kind:"value",value:"radius",def:d}),G=(d=!1)=>({kind:"text",required:d}),Me=(d,t=!1)=>({kind:"list",item:d,required:t}),se=(d,t=!1)=>({kind:"object",item:d,required:t}),Ke=(d=!1)=>({kind:"component",required:d}),Re={kind:"components"},Ge={stack:{axis:f("vertical"),spacing:We(0),align:f("center"),distribution:f("start"),scroll:f(!1),children:Re},text:{text:G(),spans:Me("span"),font:f(),size:f(),weight:f(),line_height:f(),letter_spacing:f(),color:{kind:"value",value:"textColor",def:"text"},align:f("center"),max_lines:f(),uppercase:f(!1)},image:{src:f(void 0,!0),fit:f("fit"),aspect:f(),mask:se("mask"),overlay:{kind:"value",value:"textColor"},alt:G(),decorative:f(!1)},icon:{name:f(void 0,!0),color:j("accent"),size:f(24)},video:{src:f(void 0,!0),poster:f(),autoplay:f(!0),loop:f(!0),mute:f(!0),controls:f(!1),fit:f("fill"),aspect:f(),alt:G()},button:{action:se("action",!0),content:Ke(!0)},purchase_button:{content:Ke(!0),package:f()},package:{product:f(void 0,!0),plan:f(void 0,!0),selected:f(!1),offer:f(),children:Re},tabs:{},switch:{},carousel:{pages:Re,peek:f(0),spacing:f(8),loop:f(!1),auto_advance_ms:f(),indicator:se("indicator"),height:f("")},countdown:{},timeline:{items:Me("timeline_item",!0),line_color:j("accent"),line_width:f(2),icon_color:j("on_accent"),color:j("text"),spacing:f(16)},features:{items:Me("feature",!0),icon_color:j("accent"),color:j("text"),spacing:f(12)},spacer:{size:We()},divider:{color:j("muted"),thickness:f(1)},custom_html:{src:f(void 0,!0),height:f("",!0)}},Ht={style:{padding:{kind:"edges"},margin:{kind:"edges"},width:f(""),height:f(""),max_width:f(),background:{kind:"fill"},border:se("border"),corners:{kind:"corners"},shadow:se("shadow"),opacity:f(1)},border:{width:f(),color:j("")},shadow:{color:j(""),radius:f(0),x:f(0),y:f(0)},linear:{type:f(""),angle:f(180),stops:f()},radial:{type:f(""),center_x:f(.5),center_y:f(.5),radius:f(.5),stops:f()},image_fill:{type:f(""),src:f(),fit:f("fill")},video_fill:{type:f(""),src:f(),poster:f(),loop:f(!0)},animation:{type:f(""),duration_ms:f(300),delay_ms:f(0),easing:f("ease_out")},action:{type:f(""),url:f(),sheet:f(),package:f()},mask:{shape:f(""),radius:zt(0),depth:f(16)},span:{text:G(!0),bold:f(!1),italic:f(!1),underline:f(!1),strikethrough:f(!1),color:j(""),link:f()},timeline_item:{icon:f(void 0,!0),title:G(!0),text:G(),color:j("")},feature:{icon:f(void 0,!0),text:G(!0)},indicator:{style:f("dots"),color:j("muted"),active_color:j("accent"),size:f(8),spacing:f(6)},typography:{font:f("system"),size:f(),weight:f(400),line_height:f(),letter_spacing:f(0),text_style:f("body")}},Xe=new Set(["package","purchase_button"]),Ct={action:{type:f(""),url:f(),link:f(),sheet:f(),placement:f(),name:f(),value:f(),offer:f(),code:G(),dismiss:f(!0)},presentation:{type:f(""),position:f("bottom"),auto_dismiss_seconds:f(),dismissible:f(!0),backdrop:j("#00000080")}},jt={modal:["type","dismissible","backdrop"],fullscreen:["type"],banner:["type","position","auto_dismiss_seconds","dismissible"],slide_in:["type","position","auto_dismiss_seconds","dismissible"],toast:["type","position","auto_dismiss_seconds","dismissible"],card:["type"]},Ft={linear:"linear",radial:"radial",image:"image_fill",video:"video_fill"},Nt=["top","bottom","leading","trailing"],Dt=["top_leading","top_trailing","bottom_leading","bottom_trailing"],Jt=Object.keys(Ge),un=Jt.filter(d=>!Xe.has(d)),Ye=/\{\{\s*([^{}]*?)\s*\}\}/g,Q=(d,t)=>typeof d=="object"&&d!==null&&Object.hasOwn(d,t),M=d=>typeof d=="object"&&d!==null&&!Array.isArray(d)?d:{},I=d=>Array.isArray(d)?d:[],X=(d,t)=>d??t;function It(d){let t="";for(let l of new TextEncoder().encode(d)){let a=String.fromCharCode(l);t+=/^[A-Za-z0-9._~-]$/.test(a)?a:`%${l.toString(16).toUpperCase().padStart(2,"0")}`}return t}function Vt(d){let t=Math.floor(d/86400),l=Math.floor(d%86400/3600),a=Math.floor(d%3600/60),c=d%60,p=h=>String(h).padStart(2,"0");return{countdown:t>0?`${t}d ${p(l)}:${p(a)}:${p(c)}`:l>0?`${l}:${p(a)}:${p(c)}`:`${p(a)}:${p(c)}`,days:String(t),hours:p(l),minutes:p(a),seconds:p(c)}}function fn(d){let t=[],l=c=>{if(Array.isArray(c))return c.forEach(l);if(typeof c!="object"||c===null)return;let p=c;if(p.type==="package"&&typeof p.product=="string"&&typeof p.plan=="string"){let g=`${p.product}.${p.plan}`;t.includes(g)||t.push(g)}for(let g of Object.keys(p).sort())l(p[g])},a=d;for(let c of["header","root","footer"])l(a[c]);for(let c of Object.keys(M(a.sheets)).sort())l(M(M(a.sheets)[c]).root);return t}function Ut(d){let t=new Map,l=c=>{if(Array.isArray(c))return c.forEach(l);if(typeof c!="object"||c===null)return;let p=c;if(p.type==="package"&&typeof p.offer=="string"){let g=`${p.product}.${p.plan}`;t.has(g)||t.set(g,p.offer)}for(let g of Object.keys(p).sort())l(p[g])},a=d;for(let c of["header","root","footer","sheets"])l(a[c]);return t}function gn(d,t){return Ae(d,t).tree}function Ae(d,t){return new ue("paywall",d,t).resolve()}function hn(d,t){return Ee(d,t).tree}function Ee(d,t){let{variables:l,...a}=t;return new ue("message",d,{...a,packages:{"":{...l}}}).resolve()}var ue=class{kind;d;opts;lang;texts={};palette;typography={};radii;spacing;packages;offers;selected="";tab="";paths=new WeakMap;tabsShown={};switchesOn={};countdowns={};constructor(t,l,a){this.kind=t,this.d=l,this.opts=a,this.offers=Ut(l);let c={};for(let[y,m]of Object.entries(a.packages??{})){let v={...m};this.open(y)||(m.price!==void 0?v.offer_price=m.price:delete v.offer_price),c[y]=v}this.packages=c;let p=M(this.d.locales),g=String(this.d.default_locale??""),h=a.locale;Q(p,h)||(h=h.split("-")[0]??"",Q(p,h)||(h=g)),this.lang=h;for(let y of[g,h])for(let[m,v]of Object.entries(M(p[y])))typeof v=="string"&&(this.texts[m]=v);let b=M(this.d.theme);this.palette=M(M(b.colors)[a.appearance]);for(let[y,m]of Object.entries(M(b.typography))){let v={};for(let[A,P]of Object.entries(this.objectFields("typography"))){let R=X(M(m)[A],P.def);R!=null&&(v[A]=R)}this.typography[y]=v}this.radii=M(b.radii),this.spacing=M(b.spacing)}open(t){let l=this.offers.get(t);return l!==void 0&&(this.opts.offers??[]).includes(l)}fields(t){if(!(this.kind==="message"&&Xe.has(t)))return Ge[t]}objectFields(t){return(this.kind==="message"?Ct[t]:void 0)??Ht[t]??{}}resolve(){let[t,l]=this.initialState();this.tab=t,this.selected=this.kind==="paywall"?l:"";let a={theme:{colors:this.palette,typography:this.typography,radii:this.radii,spacing:this.spacing}};this.kind==="paywall"&&(a.selected=l);let c=this.d.presentation;if(typeof c=="object"&&c!==null){let g=this.item("presentation",M(c),void 0)??{},h=jt[String(M(c).type)]??[];for(let b of Object.keys(g))h.includes(b)||delete g[b];a.presentation=g}for(let g of["header","root","footer"]){let h=this.d[g];if(typeof h=="object"&&h!==null){let b=this.component(M(h),g,"",!1);b&&(a[g]=b)}}let p={};if(typeof this.d.sheets=="object"&&this.d.sheets!==null){let g={};for(let[h,b]of Object.entries(M(this.d.sheets))){let y=this.component(M(M(b).root),`sheets.${h}.root`,"",!1);y&&(g[h]=y);let m=this.text(M(b).title,this.packages[this.selected]);m!==null&&(p[h]=m)}a.sheets=g}return{tree:a,pathOf:g=>this.paths.get(g),tabs:this.tabsShown,switches:this.switchesOn,sheetTitles:p,countdowns:this.countdowns,language:this.lang}}switchOn(t,l){return this.opts.switches&&Object.hasOwn(this.opts.switches,l)?this.opts.switches[l]:this.opts.switch?this.opts.switch==="on":t.default===!0}tabShown(t,l){let c=I(t.tabs).map(M).map(g=>String(g.id)),p=this.opts.tabs?.[l];return p!==void 0&&c.includes(p)?p:this.opts.tab?this.opts.tab:typeof t.default=="string"&&t.default!==""?t.default:c[0]??""}initialState(){let t="",l="",a="",c="",p=(h,b)=>{if(Array.isArray(h)){h.forEach((m,v)=>p(m,`${b}[${v}]`));return}if(typeof h!="object"||h===null)return;let y=h;switch(y.type){case"package":{let m=`${y.product}.${y.plan}`;a===""&&(a=m),y.selected===!0&&l===""&&(l=m);break}case"switch":{let m=this.switchOn(y,b),v=m?y.on_package:y.off_package;typeof v=="string"&&c===""&&(c=v),p(m?y.on:y.off,`${b}.${m?"on":"off"}`);return}case"tabs":{let m=this.tabShown(y,b);t===""&&(t=m),I(y.tabs).forEach((v,A)=>{let P=M(v);P.id===m&&(typeof P.package=="string"&&c===""&&(c=P.package),p(P.content,`${b}.tabs[${A}].content`))});return}}for(let m of Object.keys(y).sort())m!=="sheets"&&p(y[m],b===""?m:`${b}.${m}`)};for(let h of["header","root","footer"])p(this.d[h],h);let g=this.opts.selected||c||l||a;return[t,g]}holds(t,l){let a=l||this.selected;for(let[c,p]of Object.entries(t))switch(c){case"selected_package":if(!I(p).includes(this.selected))return!1;break;case"intro_eligible":if((this.opts.eligible??[]).includes(a)!==p)return!1;break;case"offer_open":if(this.open(a)!==p)return!1;break;case"platform":if(!I(p).includes(this.opts.platform))return!1;break;case"locale":if(!I(p).includes(this.opts.locale)&&!I(p).includes(this.lang))return!1;break;case"appearance":if(p!==this.opts.appearance)return!1;break;case"tab":if(p!==this.tab)return!1;break}return!0}component(t,l,a,c){if(typeof t.visible=="object"&&t.visible!==null&&!this.holds(M(t.visible),a))return null;let p=String(t.type),g=a,h=c;p==="package"&&(g=`${t.product}.${t.plan}`,h=g===this.selected);let b={type:p};this.paths.set(b,l),Q(t,"id")&&(b.id=t.id);let y={...M(t.style)};h&&Object.assign(y,M(M(t.states).selected)),Object.keys(y).length>0&&(b.style=this.style(y)),typeof t.animation=="object"&&t.animation!==null&&(b.animation=this.defaults(M(t.animation),this.objectFields("animation")));let m=this.packages[g||this.selected];switch(p){case"tabs":return this.tabs(t,b,l,g);case"switch":return this.switchOf(t,b,l,g,h);case"countdown":return this.countdown(t,b,l,g,h);case"purchase_button":{let v=typeof t.package=="string"?t.package:this.selected;b.package=v,this.open(v)&&(b.offer=this.offers.get(v));let A=this.component(M(t.content),`${l}.content`,v,h);return A?(b.content=A,b):null}case"package":b.product=t.product,b.plan=t.plan,b.selected=h,typeof t.offer=="string"&&(this.opts.offers??[]).includes(t.offer)&&(b.offer=t.offer)}for(let[v,A]of Object.entries(this.fields(p)??{})){if(p==="package"&&(v==="product"||v==="plan"||v==="selected"||v==="offer"))continue;let P=t[v],R=Q(t,v);switch(A.kind){case"component":{if(!R)continue;let x=this.component(M(P),`${l}.${v}`,g,h);if(!x&&A.required)return null;x&&(b[v]=x);break}case"components":{let x=[];I(P).forEach((T,O)=>{let V=this.component(M(T),`${l}.${v}[${O}]`,g,h);V&&x.push(V)}),b[v]=x;break}case"text":{let x=this.text(P,m);if(x!==null)b[v]=x;else if(A.required||p==="text"&&v==="text"&&R)return null;break}case"list":{let x=[];for(let T of I(P)){let O=this.item(A.item,M(T),m);O&&x.push(O)}if(p==="text"&&x.length===0&&R)return null;R&&(b[v]=x);break}case"object":{if(R){let x=this.object(M(P),A.item,m);if(x===null&&A.required)return null;b[v]=x}else v==="indicator"&&(b[v]=this.object({},A.item,m));break}case"value":{let x=this.value(X(P,A.def),A);x!=null&&x!==""&&(b[v]=x);break}}}return p==="text"&&this.typeStyle(b),b}typeStyle(t){if(typeof t.size!="string"){t.size!==void 0&&t.size!==null&&(t.text_style="body");return}let l=this.typography[t.size];for(let a of["font","weight","line_height","letter_spacing","text_style"])!Q(t,a)&&l?.[a]!==void 0&&l?.[a]!==null&&(t[a]=l[a]);t.size=l?.size??null}tabs(t,l,a,c){let p=this.tabShown(t,a);this.tabsShown[a]=p;let g=[];return I(t.tabs).forEach((h,b)=>{let y=M(h),m=y.id===p,v=this.component(M(y.label),`${a}.tabs[${b}].label`,c,m);if(g.push({id:y.id,selected:m,label:v}),m){let A=this.component(M(y.content),`${a}.tabs[${b}].content`,c,!1);A&&(l.content=A)}}),l.tabs=g,typeof t.bar=="object"&&t.bar!==null&&(l.bar=this.style(M(t.bar))),l}switchOf(t,l,a,c,p){let g=this.switchOn(t,a);this.switchesOn[a]=g,l.on=g;let h=this.text(t.label,this.packages[c||this.selected]);h!==null&&(l.label=h),l.tint=this.color(String(X(t.tint,"accent")));let b=g?"on":"off",y=this.component(M(t[b]),`${a}.${b}`,c,p);return y&&(l.content=y),l}countdown(t,l,a,c,p){let g=M(t.target),h=this.opts.now??Date.now(),b;if(typeof g.after_open_seconds=="number"?b=Math.trunc(g.after_open_seconds)-(this.opts.openedSecondsAgo??0):b=Math.trunc((Date.parse(String(g.at))-h)/1e3),b>0){l.state="counting",l.remaining_seconds=b,this.countdowns[a]=b;let y=this.packages,m={};for(let[A,P]of Object.entries(y))m[A]={...P,...Vt(b)};this.packages=m;let v=this.component(M(t.counting),`${a}.counting`,c,p);return v&&(l.content=v),this.packages=y,l}if(l.state="ended",l.remaining_seconds=0,typeof t.ended=="object"&&t.ended!==null){let y=this.component(M(t.ended),`${a}.ended`,c,p);y&&(l.content=y)}return l}item(t,l,a){let c={};for(let[p,g]of Object.entries(this.objectFields(t))){let h=l[p];if(g.kind==="text"){let b=this.text(h,a);if(b!==null)c[p]=b;else if(g.required)return null}else{let b=g.def,y=this.value(X(h,b),g);y!=null&&(Q(l,p)||b!=null&&b!=="")&&(c[p]=y)}}return c}object(t,l,a){if(l==="style")return this.style(t);let c=this.item(l,t,a)??{};if(l==="action")for(let p of["url","link"]){if(typeof c[p]!="string")continue;let g=qt(c[p],a);if(g===null)return null;c[p]=g}return c}defaults(t,l){let a={};for(let[c,p]of Object.entries(l)){let g=X(t[c],p.def);g!=null&&g!==""&&(a[c]=g)}return a}style(t){let l={};for(let[a,c]of Object.entries(t)){let p=this.objectFields("style")[a];if(!p){l[a]=c;continue}switch(p.kind){case"edges":l[a]=this.sides(c,Nt,this.spacing);break;case"corners":l[a]=this.sides(c,Dt,this.radii);break;case"fill":l[a]=this.fill(c);break;case"object":{let g=M(c),h={};for(let[b,y]of Object.entries(this.objectFields(p.item))){let m=X(g[b],y.def);m!=null&&m!==""&&(h[b]=this.value(m,y))}l[a]=h;break}default:l[a]=c}}return l}sides(t,l,a){let c={};for(let p of l){let g=typeof t=="object"&&t!==null?X(M(t)[p],0):t;c[p]=_e(g,a)}return c}fill(t){if(typeof t=="string")return{type:"color",color:this.color(t)};let l=M(t),a=this.defaults(l,this.objectFields(Ft[String(l.type)]??""));return Array.isArray(l.stops)&&(a.stops=l.stops.map(c=>({color:this.color(String(M(c).color)),at:M(c).at}))),a}value(t,l){if(l.kind!=="value")return t;switch(l.value){case"color":return typeof t=="string"&&t!==""?this.color(t):t;case"textColor":return typeof t=="string"?this.color(t):t==null?t:this.fill(t);case"spacing":return _e(t,this.spacing);case"radius":return _e(t,this.radii);default:return t}}color(t){let l=Object.hasOwn(this.palette,t)?this.palette[t]:void 0;return typeof l=="string"?l:t}text(t,l){let a;if(typeof t=="string")a=t;else if(typeof t=="object"&&t!==null&&!Array.isArray(t)){let p=t.t;a=typeof p=="string"&&Object.hasOwn(this.texts,p)?this.texts[p]:""}else return null;let c=!1;return a=a.replace(Ye,(p,g)=>{let h=l&&Object.hasOwn(l,g)?l[g]:void 0;return typeof h!="string"||h===""?(c=!0,""):h}),c||a.trim()===""?null:a}};function qt(d,t){let l=!1,a=d.replace(Ye,(c,p)=>{let g=t&&Object.hasOwn(t,p)?t[p]:void 0;return typeof g!="string"||g===""?(l=!0,""):It(g)});return l?null:a}function _e(d,t){return typeof d=="string"?Object.hasOwn(t,d)?t[d]:null:d}var Bt={packages:"Choose a plan",close:"Close",restore:"Restore purchases",page:(d,t)=>`${d} of ${t}`},ee={system:'-apple-system, BlinkMacSystemFont, "SF Pro Text", system-ui, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif',rounded:'ui-rounded, "SF Pro Rounded", Nunito, "Varela Round", system-ui, -apple-system, sans-serif',serif:'ui-serif, "New York", "Iowan Old Style", Georgia, "Times New Roman", serif',mono:'ui-monospace, "SF Mono", Menlo, Consolas, "Liberation Mono", monospace'},Wt=1.35,Ze=20,Kt=new Set(["button","purchase_button","package","text"]),Gt=new Set(["ar","he","fa","ur","ps","yi","dv","ug","ku","sd"]),Qe={ease_out:"cubic-bezier(0.16, 1, 0.3, 1)",ease_in_out:"cubic-bezier(0.65, 0, 0.35, 1)",spring:"cubic-bezier(0.34, 1.56, 0.64, 1)"},Xt={start:"flex-start",center:"center",end:"flex-end",stretch:"stretch"},Yt={start:"flex-start",center:"center",end:"flex-end",space_between:"space-between",space_around:"space-around",space_evenly:"space-evenly"},Zt={stack:["children"],package:["children"],button:["content"],purchase_button:["content"],tabs:["tabs","content"],switch:["content"],carousel:["pages"],countdown:["content"]},Qt={package:["selected"],purchase_button:["package"],switch:["on"],countdown:["state","remaining_seconds"]},en=`
3
3
  :host{display:block;height:100%}
4
4
  .pw2{position:relative;box-sizing:border-box;display:flex;flex-direction:column;height:100%;overflow:hidden;font-family:${ee.system};font-size:1rem;line-height:1.3;-webkit-font-smoothing:antialiased;-webkit-text-size-adjust:100%;text-rendering:optimizeLegibility}
@@ -1,2 +1,2 @@
1
- /*! palbase 0.76.0 — Palbase SDK License (see LICENSE) */
1
+ /*! palbase 0.77.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};
@@ -1,2 +1,2 @@
1
- /*! palbase 0.76.0 — Palbase SDK License (see LICENSE) */
2
- import{a as g,f as y,g as w}from"./TGQGGUE6.js";import"./A3I7H7QN.js";import"./D6NOE76D.js";import{pathToFileURL as z}from"node:url";import{z as c}from"zod";async function S(r){let l=new Map,t=new Map;for(let s of r){let o=`${s.className}.${s.method}`,i=t.get(s.className);if(i!==void 0&&i!==s.file)throw new Error(`two controllers are named ${s.className} (${i}, ${s.file}): the contract tells routes apart by their class's name \u2014 rename one`);t.set(s.className,s.file),l.set(o,{returns:await x(s),throws:s.throws})}return s=>l.get(`${s.controller.name}.${s.fn}`)}async function x(r){let l=`${r.file} \u2014 ${r.className}.${r.method}`;switch(r.returns.kind){case"void":return{kind:"void"};case"raw":return{kind:"raw"};case"schema":{let s=(await import(z(r.returns.file).href))[r.returns.exportName];if(!k(s))throw new Error(`${l}: its return type names ${r.returns.exportName}, which ${r.returns.file} exports as no schema (a zod, valibot or arktype schema)`);if(w(y(s)))throw new Error(`${l}: ${r.returns.exportName} marks an encrypted field (encrypted()) \u2014 an answer's is encrypt(value) in what the handler returns, its type Encrypted<T>, which the contract reads`);return{kind:"json",schema:s,array:r.returns.array}}case"expression":{let t=$(r.returns.expression,l);if(!k(t))throw new Error(`${l}: the schema made of its return type is not one`);return{kind:"json",schema:t,array:!1}}}}function $(r,l){let t=0,s=()=>{for(;t<r.length&&/\s/.test(r[t]);)t++},o=e=>{throw new Error(`${l}: invalid inferred return schema (${e}) at offset ${t}`)},i=e=>(s(),r.startsWith(e,t)?(t+=e.length,!0):!1),n=e=>{i(e)||o(`expected ${JSON.stringify(e)}`)},f=()=>{s(),r[t]!=='"'&&o("expected string literal");let e=t+1;for(;e<r.length;){let d=r[e];if(d==="\\"){e+=2;continue}if(d==='"'){let h=r.slice(t,e+1);return t=e+1,JSON.parse(h)}e++}return o("unterminated string literal")},p=()=>{if(s(),r[t]==='"')return f();if(r.startsWith("true",t)&&!/[A-Za-z0-9_$]/.test(r[t+4]??""))return t+=4,!0;if(r.startsWith("false",t)&&!/[A-Za-z0-9_$]/.test(r[t+5]??""))return t+=5,!1;let e=/^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?/.exec(r.slice(t));return e?(t+=e[0].length,Number(e[0])):o("expected literal value")},u=()=>{s();let e;if(i("encrypted(")){let d=u();n(")"),e=g(d)}else if(i("z.")){let d=t;for(;t<r.length&&/[A-Za-z0-9_]/.test(r[t]);)t++;let h=r.slice(d,t);switch(n("("),h){case"string":n(")"),e=c.string();break;case"number":n(")"),e=c.number();break;case"boolean":n(")"),e=c.boolean();break;case"null":n(")"),e=c.null();break;case"undefined":n(")"),e=c.undefined();break;case"literal":{let a=p();n(")"),e=c.literal(a);break}case"array":{let a=u();n(")"),e=c.array(a);break}case"union":{n("[");let a=[];if(!i("]")){do a.push(u());while(i(","));n("]")}n(")"),a.length<2&&o("z.union requires at least two alternatives"),e=c.union(a);break}case"record":{let a=u();n(",");let m=u();n(")"),e=c.record(a,m);break}case"object":{n("{");let a={};if(!i("}")){do{let m=f();n(":"),a[m]=u()}while(i(","));n("}")}n(")"),e=c.object(a);break}default:return o(`unsupported z.${h}`)}}else return o("expected z.* or encrypted(...)");for(;i(".");){let d=t;for(;t<r.length&&/[A-Za-z0-9_]/.test(r[t]);)t++;let h=r.slice(d,t);switch(n("("),h){case"strict":n(")"),e=e.strict();break;case"nullable":n(")"),e=e.nullable();break;case"optional":n(")"),e=e.optional();break;case"length":{let a=p();if(typeof a!="number"||!Number.isInteger(a)||a<0)return o("expected non-negative integer for .length()");n(")"),e=e.length(a);break}case"regex":{n("new RegExp(");let a=f();n(")"),n(")"),e=e.regex(new RegExp(a));break}default:return o(`unsupported modifier .${h}()`)}}return e},b=u();return s(),t!==r.length&&o("unexpected trailing tokens"),b}function k(r){return typeof r=="object"&&r!==null&&typeof r["~standard"]?.validate=="function"}export{S as routeContracts};
1
+ /*! palbase 0.77.0 — Palbase SDK License (see LICENSE) */
2
+ import{a as g,f as y,g as w}from"./JOVXELK5.js";import"./34HGL5FX.js";import"./FE7ZBADH.js";import{pathToFileURL as z}from"node:url";import{z as c}from"zod";async function S(r){let l=new Map,t=new Map;for(let s of r){let o=`${s.className}.${s.method}`,i=t.get(s.className);if(i!==void 0&&i!==s.file)throw new Error(`two controllers are named ${s.className} (${i}, ${s.file}): the contract tells routes apart by their class's name \u2014 rename one`);t.set(s.className,s.file),l.set(o,{returns:await x(s),throws:s.throws})}return s=>l.get(`${s.controller.name}.${s.fn}`)}async function x(r){let l=`${r.file} \u2014 ${r.className}.${r.method}`;switch(r.returns.kind){case"void":return{kind:"void"};case"raw":return{kind:"raw"};case"schema":{let s=(await import(z(r.returns.file).href))[r.returns.exportName];if(!k(s))throw new Error(`${l}: its return type names ${r.returns.exportName}, which ${r.returns.file} exports as no schema (a zod, valibot or arktype schema)`);if(w(y(s)))throw new Error(`${l}: ${r.returns.exportName} marks an encrypted field (encrypted()) \u2014 an answer's is encrypt(value) in what the handler returns, its type Encrypted<T>, which the contract reads`);return{kind:"json",schema:s,array:r.returns.array}}case"expression":{let t=$(r.returns.expression,l);if(!k(t))throw new Error(`${l}: the schema made of its return type is not one`);return{kind:"json",schema:t,array:!1}}}}function $(r,l){let t=0,s=()=>{for(;t<r.length&&/\s/.test(r[t]);)t++},o=e=>{throw new Error(`${l}: invalid inferred return schema (${e}) at offset ${t}`)},i=e=>(s(),r.startsWith(e,t)?(t+=e.length,!0):!1),n=e=>{i(e)||o(`expected ${JSON.stringify(e)}`)},f=()=>{s(),r[t]!=='"'&&o("expected string literal");let e=t+1;for(;e<r.length;){let d=r[e];if(d==="\\"){e+=2;continue}if(d==='"'){let h=r.slice(t,e+1);return t=e+1,JSON.parse(h)}e++}return o("unterminated string literal")},p=()=>{if(s(),r[t]==='"')return f();if(r.startsWith("true",t)&&!/[A-Za-z0-9_$]/.test(r[t+4]??""))return t+=4,!0;if(r.startsWith("false",t)&&!/[A-Za-z0-9_$]/.test(r[t+5]??""))return t+=5,!1;let e=/^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?/.exec(r.slice(t));return e?(t+=e[0].length,Number(e[0])):o("expected literal value")},u=()=>{s();let e;if(i("encrypted(")){let d=u();n(")"),e=g(d)}else if(i("z.")){let d=t;for(;t<r.length&&/[A-Za-z0-9_]/.test(r[t]);)t++;let h=r.slice(d,t);switch(n("("),h){case"string":n(")"),e=c.string();break;case"number":n(")"),e=c.number();break;case"boolean":n(")"),e=c.boolean();break;case"null":n(")"),e=c.null();break;case"undefined":n(")"),e=c.undefined();break;case"literal":{let a=p();n(")"),e=c.literal(a);break}case"array":{let a=u();n(")"),e=c.array(a);break}case"union":{n("[");let a=[];if(!i("]")){do a.push(u());while(i(","));n("]")}n(")"),a.length<2&&o("z.union requires at least two alternatives"),e=c.union(a);break}case"record":{let a=u();n(",");let m=u();n(")"),e=c.record(a,m);break}case"object":{n("{");let a={};if(!i("}")){do{let m=f();n(":"),a[m]=u()}while(i(","));n("}")}n(")"),e=c.object(a);break}default:return o(`unsupported z.${h}`)}}else return o("expected z.* or encrypted(...)");for(;i(".");){let d=t;for(;t<r.length&&/[A-Za-z0-9_]/.test(r[t]);)t++;let h=r.slice(d,t);switch(n("("),h){case"strict":n(")"),e=e.strict();break;case"nullable":n(")"),e=e.nullable();break;case"optional":n(")"),e=e.optional();break;case"length":{let a=p();if(typeof a!="number"||!Number.isInteger(a)||a<0)return o("expected non-negative integer for .length()");n(")"),e=e.length(a);break}case"regex":{n("new RegExp(");let a=f();n(")"),n(")"),e=e.regex(new RegExp(a));break}default:return o(`unsupported modifier .${h}()`)}}return e},b=u();return s(),t!==r.length&&o("unexpected trailing tokens"),b}function k(r){return typeof r=="object"&&r!==null&&typeof r["~standard"]?.validate=="function"}export{S as routeContracts};
@@ -1,2 +1,2 @@
1
- /*! palbase 0.76.0 — Palbase SDK License (see LICENSE) */
2
- import{b as d,m as k}from"./A3I7H7QN.js";function S(n){let o=n.meta;if(typeof o!="function")throw new TypeError("encrypted() takes a zod schema: z.string(), z.number(), z.object(\u2026)");return o.call(n,{[d]:!0})}var p=class{value;constructor(o){this.value=o}toJSON(){throw new TypeError("an encrypt() value is sealed by the engine, in a route's answer: it is never JSON of its own")}},m=0;function $(n){if(n===void 0)throw new TypeError("encrypt() takes a JSON value: undefined is none");if(n instanceof p)throw new TypeError("encrypt() of an encrypt() value: one is enough");return m++,new p(n)}function j(){return m}function O(n){let o=[],s=new Set,f=(t,a)=>{if(t instanceof p){if(o.push(a),g(t.value,new Set))throw new TypeError(`${a}: an encrypt() value holds another \u2014 encrypt the whole, or its parts`);return t.value}if(typeof t!="object"||t===null||s.has(t))return t;if(Array.isArray(t)){s.add(t);let r=t.map((c,e)=>f(c,`${a}/${e}`));return s.delete(t),r}let y=Object.getPrototypeOf(t);if(y!==Object.prototype&&y!==null)return t;s.add(t);let i={};for(let[r,c]of Object.entries(t))i[r]=f(c,`${a}/${k(r)}`);return s.delete(t),i};return{value:f(n,"/response"),pointers:o}}function g(n,o){return n instanceof p?!0:typeof n!="object"||n===null||o.has(n)?!1:(o.add(n),Object.values(n).some(s=>g(s,o)))}function v(n,o,s){let f=new Set,l=n,t=l?.$defs??{},a=(i,r,c)=>{if(typeof i!="object"||i===null)return;let e=i;if(typeof e.$ref=="string"){if(c.has(e.$ref))return;let u=new Set(c).add(e.$ref);e.$ref==="#"?a(l,r,u):e.$ref.startsWith("#/$defs/")&&a(t[e.$ref.slice(8)],r,u)}if(e[d]===!0){f.add(r);return}for(let u of["anyOf","oneOf","allOf"])if(Array.isArray(e[u]))for(let w of e[u])a(w,r,c);if(typeof e.properties=="object"&&e.properties!==null)for(let[u,w]of Object.entries(e.properties))a(w,`${r}/${k(u)}`,c);typeof e.items=="object"&&e.items!==null&&a(e.items,`${r}/*`,c);for(let u of["additionalProperties","patternProperties","prefixItems"])if(e[u]!==void 0&&y(e[u]))throw new TypeError(`${s}: an encrypted field is a named property \u2014 not every key of a record, nor a tuple's place`)},y=i=>{if(h(i))return!0;let r=typeof i=="object"&&i!==null?i.$ref:void 0;return typeof r=="string"&&h(r==="#"?l:t[r.slice(8)])};return a(n,o,new Set),[...f]}function T(n){let s=n["~standard"].jsonSchema?.input;if(typeof s!="function")return{};try{return s({target:"draft-2020-12",libraryOptions:{unrepresentable:"any"}})}catch{return{}}}function h(n){return JSON.stringify(n??null).includes(`"${d}":true`)}export{S as a,$ as b,j as c,O as d,v as e,T as f,h as g};
1
+ /*! palbase 0.77.0 — Palbase SDK License (see LICENSE) */
2
+ import{b as d,m as k}from"./34HGL5FX.js";function S(n){let o=n.meta;if(typeof o!="function")throw new TypeError("encrypted() takes a zod schema: z.string(), z.number(), z.object(\u2026)");return o.call(n,{[d]:!0})}var p=class{value;constructor(o){this.value=o}toJSON(){throw new TypeError("an encrypt() value is sealed by the engine, in a route's answer: it is never JSON of its own")}},m=0;function $(n){if(n===void 0)throw new TypeError("encrypt() takes a JSON value: undefined is none");if(n instanceof p)throw new TypeError("encrypt() of an encrypt() value: one is enough");return m++,new p(n)}function j(){return m}function O(n){let o=[],s=new Set,f=(t,a)=>{if(t instanceof p){if(o.push(a),g(t.value,new Set))throw new TypeError(`${a}: an encrypt() value holds another \u2014 encrypt the whole, or its parts`);return t.value}if(typeof t!="object"||t===null||s.has(t))return t;if(Array.isArray(t)){s.add(t);let r=t.map((c,e)=>f(c,`${a}/${e}`));return s.delete(t),r}let y=Object.getPrototypeOf(t);if(y!==Object.prototype&&y!==null)return t;s.add(t);let i={};for(let[r,c]of Object.entries(t))i[r]=f(c,`${a}/${k(r)}`);return s.delete(t),i};return{value:f(n,"/response"),pointers:o}}function g(n,o){return n instanceof p?!0:typeof n!="object"||n===null||o.has(n)?!1:(o.add(n),Object.values(n).some(s=>g(s,o)))}function v(n,o,s){let f=new Set,l=n,t=l?.$defs??{},a=(i,r,c)=>{if(typeof i!="object"||i===null)return;let e=i;if(typeof e.$ref=="string"){if(c.has(e.$ref))return;let u=new Set(c).add(e.$ref);e.$ref==="#"?a(l,r,u):e.$ref.startsWith("#/$defs/")&&a(t[e.$ref.slice(8)],r,u)}if(e[d]===!0){f.add(r);return}for(let u of["anyOf","oneOf","allOf"])if(Array.isArray(e[u]))for(let w of e[u])a(w,r,c);if(typeof e.properties=="object"&&e.properties!==null)for(let[u,w]of Object.entries(e.properties))a(w,`${r}/${k(u)}`,c);typeof e.items=="object"&&e.items!==null&&a(e.items,`${r}/*`,c);for(let u of["additionalProperties","patternProperties","prefixItems"])if(e[u]!==void 0&&y(e[u]))throw new TypeError(`${s}: an encrypted field is a named property \u2014 not every key of a record, nor a tuple's place`)},y=i=>{if(h(i))return!0;let r=typeof i=="object"&&i!==null?i.$ref:void 0;return typeof r=="string"&&h(r==="#"?l:t[r.slice(8)])};return a(n,o,new Set),[...f]}function T(n){let s=n["~standard"].jsonSchema?.input;if(typeof s!="function")return{};try{return s({target:"draft-2020-12",libraryOptions:{unrepresentable:"any"}})}catch{return{}}}function h(n){return JSON.stringify(n??null).includes(`"${d}":true`)}export{S as a,$ as b,j as c,O as d,v as e,T as f,h as g};
@@ -0,0 +1,18 @@
1
+ /*! palbase 0.77.0 — Palbase SDK License (see LICENSE) */
2
+ import{a as le,d as Je}from"./CYNLRAAW.js";import{a as w,d as Fe,e as Ke,f as He}from"./6WCN7VAZ.js";import{a as ze}from"./BDHVYVWT.js";import{a as Ve}from"./ES24JS2D.js";import{a as Be,b as Ge,c as Le}from"./FN5763FR.js";import{b as I,d as De}from"./VOLGPAPR.js";async function*Qe(e,t={}){let i=e.getReader(),s=new TextDecoder,a="",d="",u=[],o,r=()=>{i.cancel().catch(()=>{})};t.signal?.addEventListener("abort",r,{once:!0});try{if(t.signal?.aborted)return;for(;;){let{done:n,value:l}=await i.read();if(n||t.signal?.aborted)return;t.onBytes?.(),a+=s.decode(l,{stream:!0});for(let c=a.indexOf(`
3
+ `);c>=0;c=a.indexOf(`
4
+ `)){let f=a.slice(0,a[c-1]==="\r"?c-1:c);a=a.slice(c+1),f===""?(d!==""&&(yield o===void 0?{event:d,data:u.join(`
5
+ `)}:{event:d,data:u.join(`
6
+ `),id:o}),d="",u=[],o=void 0):f.startsWith("event:")?d=ve(f,6):f.startsWith("data:")?u.push(ve(f,5)):f.startsWith("id:")&&(o=ve(f,3))}}}finally{t.signal?.removeEventListener("abort",r);try{await i.cancel()}catch{}}}function ve(e,t){let i=e.slice(t);return i.startsWith(" ")?i.slice(1):i}var tn=/\s/;function de(e,t){for(;t<e.length&&tn.test(e[t]);)t++;return t}function Xe(e,t){let i="";for(let s=t+1;s<e.length;s++){let a=e[s];if(a==='"')return{value:i,complete:!0,empty:!1,at:s+1};if(a!=="\\"){i+=a;continue}let d=e[s+1];if(d===void 0)break;if(d==="u"){let u=e.slice(s+2,s+6);if(u.length<4)break;i+=String.fromCharCode(Number.parseInt(u,16)),s+=5;continue}i+={n:`
7
+ `,t:" ",r:"\r",b:"\b",f:"\f"}[d]??d,s++}return{value:i,complete:!1,empty:!1,at:e.length}}function Ae(e,t){t=de(e,t);let i=e[t];if(i===void 0)return{value:void 0,complete:!1,empty:!0,at:t};if(i==='"')return Xe(e,t);if(i==="{")return nn(e,t);if(i==="[")return rn(e,t);let s=t;for(;s<e.length&&/[-+0-9.A-Za-z]/.test(e[s]);)s++;if(s===e.length)return{value:void 0,complete:!1,empty:!0,at:s};try{return{value:JSON.parse(e.slice(t,s)),complete:!0,empty:!1,at:s}}catch{return{value:void 0,complete:!1,empty:!0,at:e.length}}}function nn(e,t){let i={},s=t+1;for(;;){if(s=de(e,s),e[s]==="}")return{value:i,complete:!0,empty:!1,at:s+1};if(e[s]===","){s++;continue}if(e[s]!=='"')return{value:i,complete:!1,empty:!1,at:e.length};let a=Xe(e,s);if(!a.complete)return{value:i,complete:!1,empty:!1,at:e.length};if(s=de(e,a.at),e[s]!==":")return{value:i,complete:!1,empty:!1,at:e.length};let d=Ae(e,s+1);if(d.empty||Object.defineProperty(i,a.value,{value:d.value,enumerable:!0,writable:!0,configurable:!0}),!d.complete)return{value:i,complete:!1,empty:!1,at:e.length};s=d.at}}function rn(e,t){let i=[],s=t+1;for(;;){if(s=de(e,s),e[s]==="]")return{value:i,complete:!0,empty:!1,at:s+1};if(e[s]===","){s++;continue}if(s>=e.length)return{value:i,complete:!1,empty:!1,at:s};let a=Ae(e,s);if(a.empty||i.push(a.value),!a.complete)return{value:i,complete:!1,empty:!1,at:e.length};s=a.at}}function xe(e){let t=Ae(e,0);return t.empty?void 0:t.value}var T=class extends Error{path;constructor(t,i){super(`${t}: ${i}`),this.name="AISchemaError",this.path=t}},sn=new Set(["type","properties","required","additionalProperties","items","enum","description","title","minimum","maximum","minLength","maxLength","minItems","maxItems"]),on=new Set(["format","pattern","exclusiveMinimum","exclusiveMaximum","multipleOf","uniqueItems","contentEncoding","contentMediaType","default","examples","readOnly","writeOnly","deprecated","$comment"]),an=new Set(["object","array","string","integer","number","boolean"]),Ye=12,Ze=512,ln=/^[A-Za-z][A-Za-z0-9_-]{0,63}$/;function K(e,t="answer"){if(!ln.test(t))throw new T(t||"(name)","a schema name starts with a letter and holds letters, digits, _ and -, 64 at most");let i=e?.["~standard"];if(!i||i.version!==1||typeof i.validate!="function")throw new T(t,"not a Standard Schema: pass a zod (4.2+), valibot or arktype schema");if(!i.jsonSchema||typeof i.jsonSchema.output!="function")throw new T(t,`${i.vendor}'s schema cannot say itself as JSON Schema; use a version that implements Standard JSON Schema`);let s;try{s=i.jsonSchema.output({target:"draft-2020-12",libraryOptions:{unrepresentable:"throw"}})}catch(u){throw new T(t,`the schema has a part JSON Schema cannot say (${u.message}): a function, a transform, a date \u2014 give the model a string and convert it after`)}if(s.type!=="object")throw new T(t,"the answer is an object: wrap the value in z.object({ \u2026 })");let d=_e(s,t,0,{properties:0});return{name:t,json:d,async check(u){let o=await i.validate(u);if(o.issues){let r=o.issues[0],n=(r?.path??[]).map(l=>String(typeof l=="object"?l.key:l)).join(".");throw new T(n?`${t}.${n}`:t,`the model's answer does not match the schema: ${r?.message??"invalid"}`)}return o.value}}}function _e(e,t,i,s){if(i>Ye)throw new T(t,`nests deeper than ${Ye} levels, the most the provider takes`);for(let u of["anyOf","oneOf","allOf"])if(u in e)throw new T(t,dn(e[u])??"is a union of several shapes: the provider holds a model to one shape per field \u2014 use an enum, or one object with every field");for(let u of["$ref","$defs","definitions","$dynamicRef"])if(u in e)throw new T(t,"refers to another schema (a recursive or shared type): the provider takes no references \u2014 write the shape out, a bounded number of levels deep");if(e.type==="object"&&("propertyNames"in e||"patternProperties"in e||e.additionalProperties!==void 0&&e.additionalProperties!==!1))throw new T(t,"accepts fields it does not name (a record, passthrough or catchall): the provider holds a model only to the fields named \u2014 name them");for(let u of["prefixItems","patternProperties","propertyNames","not","if","then","else","dependentRequired","dependentSchemas","const","minProperties","maxProperties","contains","unevaluatedProperties","unevaluatedItems"])if(u in e)throw new T(t,`uses ${u}, which the provider cannot hold a model to`);if(Array.isArray(e.type))throw new T(t,`may be ${e.type.join(" or ")}: one type per field \u2014 a nullable field is not expressible; give it a value that means "none" (an empty string, an enum member)`);let a=e.type;if(typeof a!="string"&&!("enum"in e))throw new T(t,"has no type: the provider holds a model only to a typed value");if(typeof a=="string"&&!an.has(a))throw new T(t,`is of type ${a}, which the provider does not take`);let d={};for(let[u,o]of Object.entries(e))if(!(u==="$schema"||u==="id"||u==="$id")&&!on.has(u)){if(!sn.has(u))throw new T(t,`uses ${u}, which the provider cannot hold a model to`);d[u]=o}if("enum"in e&&typeof a!="string"){let u=e.enum,o=new Set(u.map(r=>r===null?"null":typeof r));if(o.size!==1||o.has("null"))throw new T(t,"an enum of values of several types (or with null): one type per field");d.type=o.has("string")?"string":o.has("boolean")?"boolean":"number"}if(a==="object"){let u=e.properties??{},o=Object.keys(u);if(o.length===0)throw new T(t,"is an object with no fields (a record, or any object): the provider holds a model only to named fields \u2014 name them");if(e.additionalProperties!==void 0&&e.additionalProperties!==!1)throw new T(t,"accepts fields it does not name (passthrough, catchall, record): the provider holds a model only to the fields named");if(s.properties+=o.length,s.properties>Ze)throw new T(t,`the schema has more than ${Ze} fields in all, the most the provider takes`);let r=new Set(e.required??[]),n={};for(let l of o){if(!r.has(l))throw new T(`${t}.${l}`,'is optional: the provider makes the model write every field \u2014 make it required (give it a value that means "none"), or leave it out of the schema');n[l]=_e(u[l],`${t}.${l}`,i+1,s)}d.properties=n,d.required=o,d.additionalProperties=!1}if(a==="array"){let u=e.items;if(!u||typeof u!="object"||Array.isArray(u))throw new T(t,"is a list with no one shape for its items: the provider takes a list of one shape");d.items=_e(u,`${t}[]`,i+1,s)}return d}function dn(e){if(Array.isArray(e)&&e.length===2&&e.some(t=>t?.type==="null"))return'is nullable: the provider makes the model write a value of one type \u2014 drop .nullable() and give it a value that means "none"'}var un=new Set(["image/png","image/jpeg","image/webp","image/gif"]);function te(e){return Array.isArray(e)&&e.length>0&&e.every(et)?e.map(tt):et(e)?[tt(e)]:e==null?[{type:"text",text:""}]:typeof e=="string"?[{type:"text",text:e}]:[{type:"text",text:JSON.stringify(e)??String(e)}]}function et(e){if(typeof e!="object"||e===null)return!1;let t=e;return t.type==="text"?typeof t.text=="string":t.type==="image"?(typeof t.mediaType=="string"||typeof t.media_type=="string")&&(typeof t.data=="string"||t.data instanceof Uint8Array):t.type===void 0&&typeof t.mediaType=="string"&&t.bytes instanceof Uint8Array}function tt(e){if("type"in e&&e.type==="text")return{type:"text",text:e.text};let t="bytes"in e||"mediaType"in e?e.mediaType:e.media_type;if(!un.has(t))throw new TypeError(`a tool's picture is image/png, image/jpeg, image/webp or image/gif (got ${JSON.stringify(t)})`);let i="bytes"in e?e.bytes:e.data;return{type:"image",media_type:t,data:typeof i=="string"?i:cn(i)}}function cn(e){let t="";for(let i=0;i<e.length;i+=32768)t+=String.fromCharCode(...e.subarray(i,i+32768));return btoa(t)}var gt=Symbol.for("palbase.ai.deferred"),nt=60,rt=86400;function ft(e={}){let t=e?.expiresInSeconds;if(t!==void 0&&(!Number.isInteger(t)||t<nt||t>rt))throw new TypeError(`ai.deferred: expiresInSeconds is how long the call waits for its answer, ${nt} to ${rt} seconds (got ${String(t)})`);return Object.freeze({[gt]:!0,...t!==void 0?{expiresInSeconds:t}:{}})}function pn(e){return typeof e=="object"&&e!==null&&e[gt]===!0}var mt=Symbol.for("palbase.ai.reply"),gn=/^[A-Za-z0-9_.:-]{1,160}$/;function re(e,t){if(typeof e!="object"||e===null)throw new TypeError(`${t}: workspaceTree is the tree the tool's writes left the workspace at ({ manifestId, seq }), either or both`);let{manifestId:i,seq:s}=e,a={};if(i!==void 0){if(typeof i!="string"||!gn.test(i))throw new TypeError(`${t}: workspaceTree.manifestId is a tree's id (got ${JSON.stringify(i)})`);a.manifest_id=i}if(s!==void 0){if(!Number.isSafeInteger(s)||s<1)throw new TypeError(`${t}: workspaceTree.seq is a place in the workspace's history, a whole number from 1 (got ${String(s)})`);a.seq=s}if(a.manifest_id===void 0&&a.seq===void 0)throw new TypeError(`${t}: workspaceTree names the tree \u2014 its manifestId, its seq, or both`);return a}function ht(e,t){let i=re(t?.workspaceTree,"ai.answer");return Object.freeze({[mt]:!0,output:e,workspaceTree:Object.freeze({...i.manifest_id!==void 0?{manifestId:i.manifest_id}:{},...i.seq!==void 0?{seq:i.seq}:{}})})}function fn(e){return typeof e=="object"&&e!==null&&e[mt]===!0}var mn=Symbol.for("palbase.ai.declared"),hn=Symbol.for("palbase.ai.tool_error"),Ee=class extends Error{workspaceTree;constructor(t,i){if(super(t),this.name="ToolError",Object.defineProperty(this,hn,{value:!0}),i?.workspaceTree!==void 0){let s=re(i.workspaceTree,"ToolError");this.workspaceTree=Object.freeze({...s.manifest_id!==void 0?{manifestId:s.manifest_id}:{},...s.seq!==void 0?{seq:s.seq}:{}})}}};function ue(){let e=globalThis,t=e[mn]??={tools:new Map,clientTools:new Map,agents:new Map,twice:new Set};return t.clientTools??=new Map,t}function Pe(e,t,i,s,a=(d,u)=>d===u){let d=e.get(i);d===void 0?e.set(i,s):a(d,s)||ue().twice.add(`${t}:${i}`)}var yt=/^[A-Za-z][A-Za-z0-9_-]{0,63}$/,j=/^[a-z][a-z0-9_-]{0,63}$/,ce=/^[A-Za-z0-9_.:-]{1,160}$/,wt=128,yn=/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}\p{Cs}]/u,bt=`${wt} bytes at most, no control, format (bidi, zero-width) or line-separator character`;function Tt(e){return typeof e=="string"&&new TextEncoder().encode(e).byteLength<=wt&&!yn.test(e)}function kt(e,t){if(e===void 0)return{type:"object",properties:{}};let i=e?.["~standard"];if(!i||i.version!==1||typeof i.validate!="function")throw new TypeError(`${t}: input is a Standard Schema \u2014 a zod (4.2+), valibot or arktype object schema`);if(!i.jsonSchema||typeof i.jsonSchema.output!="function")throw new TypeError(`${t}: ${i.vendor}'s schema cannot say itself as JSON Schema; use a version that implements Standard JSON Schema`);let s;try{s=i.jsonSchema.output({target:"draft-2020-12",libraryOptions:{unrepresentable:"throw"}})}catch(o){throw new TypeError(`${t}: the input has a part JSON Schema cannot say (${o.message}) \u2014 a function, a transform, a date: take a string and convert it in run`)}if(s.type!=="object")throw new TypeError(`${t}: a tool takes an object \u2014 wrap the input in z.object({ \u2026 })`);let a=JSON.stringify(s);if(/"\$(ref|defs|dynamicRef)"/.test(a))throw new TypeError(`${t}: the input refers to another schema (a recursive or shared type) \u2014 write the shape out`);let{$schema:d,...u}=s;return u}function St(e){let t=`ai.tool(${JSON.stringify(e?.name??null)})`;if(typeof e?.name!="string"||!yt.test(e.name))throw new TypeError(`${t}: name is letters, digits, _ and -, starting with a letter, at most 64`);if(typeof e.description!="string"||e.description.trim()==="")throw new TypeError(`${t}: description says what it does \u2014 the agent reads it to choose`);if(typeof e.run!="function")throw new TypeError(`${t}: run(input, ctx) is what a call does`);if(e.machine!==void 0&&!j.test(e.machine))throw new TypeError(`${t}: machine is the name of one of the project's machines`);if(e.input===void 0)throw new TypeError(`${t}: input is what it takes \u2014 z.object({}) for nothing`);let i=kt(e.input,t),s=e.input["~standard"],a=e.run,d={source:"backend",name:e.name,description:e.description,input:e.input,parameters:i,approval:e.approval===!0,...e.machine!==void 0?{machine:e.machine}:{},async call(o,r){let n=await s.validate(o);if(n.issues){let c=n.issues[0],f=(c?.path??[]).map(C=>String(typeof C=="object"?C.key:C)).join(".");return{output:[{type:"text",text:`the input does not match ${e.name}'s schema${f?` at ${f}`:""}: ${c?.message??"invalid"}`}],is_error:!0}}let l=await a(n.value,r);if(pn(l))return r.chatId===""?{output:[{type:"text",text:`${e.name} answers later, and a one-shot answer waits for no call: it answers at once, or in a chat`}],is_error:!0}:{deferred:!0,...l.expiresInSeconds!==void 0?{expires_in_seconds:l.expiresInSeconds}:{}};if(fn(l)){let c={output:te(l.output),is_error:!1};return l.workspaceTree!==void 0&&(c.workspace_tree=re(l.workspaceTree,t)),c}return{output:te(l),is_error:!1}}};Object.freeze(d);let u=ue();return u.clientTools.has(d.name)&&u.twice.add(`tool:${d.name}`),Pe(u.tools,"tool",d.name,d),d}function vt(e){let t=`ai.clientTool(${JSON.stringify(e?.name??null)})`;if(typeof e?.name!="string"||!yt.test(e.name))throw new TypeError(`${t}: name is letters, digits, _ and -, starting with a letter, at most 64`);if(typeof e.description!="string"||e.description.trim()==="")throw new TypeError(`${t}: description says what it does \u2014 the agent reads it to choose`);let i=Object.freeze({source:"client",name:e.name,description:e.description,parameters:kt(e.input,t),approval:e.approval===!0}),s=ue();return s.tools.has(i.name)&&s.twice.add(`tool:${i.name}`),Pe(s.clientTools,"tool",i.name,i,(a,d)=>JSON.stringify(a)===JSON.stringify(d)),i}function At(e,t,i={}){let s=`ai.agent(${JSON.stringify(e??null)})`;if(typeof e!="string"||!j.test(e))throw new TypeError(`${s}: name is lowercase letters, digits, _ and -, starting with a letter, at most 64`);if(typeof t!="function")throw new TypeError(`${s}: the agent is a function of the turn's context that returns its definition`);let a=i??{};if(a.machine!==void 0&&!j.test(a.machine))throw new TypeError(`${s}: machine is the name of one of the project's machines`);let d=a.description===void 0?void 0:xt(a.description,s),u={kind:"agent",name:e,...d!==void 0?{description:d}:{},...a.machine!==void 0?{machine:a.machine}:{},async resolve(o){let r=await t(o),n=pe(r,`${s} for chat ${o.chatId}`);if(n.backend!==void 0)throw new TypeError(`${s}: a backend's agent is its definition \u2014 it names no other backend`);return n.description===void 0&&d!==void 0&&(n.description=d),{definition:n,tools:wn(r)}}};return Object.freeze(u),Pe(ue().agents,"agent",e,u),u}function se(e){return typeof e=="object"&&e!==null&&e.kind==="agent"?e:void 0}function wn(e){return[...e.tools??[],...(e.subagents??[]).flatMap(i=>i.tools??[])].filter(i=>i.source==="backend")}var st=["web.search","web.fetch","workspace.fetch_archive"];function ne(e,t){if(typeof e!="object"||e===null)throw new TypeError(`${t}: a tool is ai.tool(\u2026), ai.clientTool(\u2026), { source: 'https', name }, { source: 'mcp', name } or { source: 'platform', name }`);let i=e.approval===!0?{approval:!0}:{};switch(e.source){case"backend":if(typeof e.call!="function")throw new TypeError(`${t}: a backend tool is made with ai.tool({ name, description, input, run })`);return{source:"backend",name:e.name,description:e.description,parameters:e.parameters,...i,...e.machine!==void 0?{machine:e.machine}:{}};case"client":return{source:"client",name:e.name,description:e.description,parameters:e.parameters,...i};case"https":if(typeof e.name!="string"||!j.test(e.name))throw new TypeError(`${t}: { source: 'https', name } names an endpoint the project put`);return{source:"https",name:e.name,...i};case"mcp":if(typeof e.name!="string"||!j.test(e.name))throw new TypeError(`${t}: { source: 'mcp', name } names an MCP server the project put`);return{source:"mcp",name:e.name,...i,...e.only!==void 0?{only:[...e.only]}:{}};case"platform":{let s=Object.keys(e).filter(a=>a!=="source"&&a!=="name");if(typeof e.name!="string"||!st.includes(e.name))throw new TypeError(`${t}: { source: 'platform', name } names one of the platform's tools: ${st.join(", ")}`);if(s.length>0)throw new TypeError(`${t}: the platform's ${e.name} is given by its name alone (not ${s.join(", ")})`);return{source:"platform",name:e.name}}default:throw new TypeError(`${t}: a tool's source is backend, client, https, mcp or platform (got ${JSON.stringify(e.source)})`)}}var ot=1e4,at=["none","minimal","low","medium","high","xhigh","max"],bn=1e8,Tn=/^[A-Za-z]{2,8}(-[A-Za-z0-9]{1,8})*$/,it=1024,kn=/^[A-Z][A-Z0-9_]{0,127}$/,lt=64,H=32768,dt=65536;function Ce(e){return typeof e=="string"&&kn.test(e)&&!e.startsWith("PALAI_")}var ut=e=>new TextEncoder().encode(e).byteLength,ct=32,Sn=["header","query","body"];function Ie(e,t){let i={};if(e.hosts!==void 0){if(!Array.isArray(e.hosts)||e.hosts.length>ct)throw new TypeError(`${t}: hosts is a list of ${ct} hosts at most (api.stripe.com, *.stripe.com); [] takes them all away`);e.hosts.forEach((s,a)=>{if(typeof s!="string"||s==="")throw new TypeError(`${t}: hosts[${a}] is a host, as text (api.stripe.com, *.stripe.com)`)}),i.hosts=[...e.hosts]}if(e.inject!==void 0){if(!Array.isArray(e.inject)||e.inject.length===0)throw new TypeError(`${t}: inject is where in a request it may be put \u2014 header, query, body \u2014 at least one`);e.inject.forEach((s,a)=>{if(typeof s!="string"||!Sn.includes(s))throw new TypeError(`${t}: inject[${a}] is header, query or body (a secret never goes over plain http)`)}),i.inject=[...e.inject]}if(e.open!==void 0){if(typeof e.open!="boolean")throw new TypeError(`${t}: open is true (the agent reads it as it is) or false (sealed)`);i.open=e.open}if(e.secret!==void 0){if(typeof e.secret!="boolean")throw new TypeError(`${t}: secret is true (the default) or false (a plain variable the agent reads as it is)`);i.secret=e.secret}if(e.acknowledgeOpen!==void 0){if(typeof e.acknowledgeOpen!="boolean")throw new TypeError(`${t}: acknowledgeOpen is true, said with open: true or with secret: false`);i.acknowledge_open=e.acknowledgeOpen}if(e.acknowledgeGuessable!==void 0){if(typeof e.acknowledgeGuessable!="boolean")throw new TypeError(`${t}: acknowledgeGuessable is true, said with a sealed value a person may have chosen`);i.acknowledge_guessable=e.acknowledgeGuessable}return i}var vn={person_required:"where a secret goes \u2014 its hosts, inject, open, secret \u2014 is changed without its value by a person alone: an owner or an admin of the organization signed in to Studio (AI \u203A Secrets) or to the CLI as themselves (palbase login), never a key or a token, the project's secret key included. Or say it again with its value",secret_unusable:"a sealed secret's value is 8 bytes or more on one line \u2014 no CR, LF or NUL: a value that is no secret is { secret: false }, one the agent may read as it is { open: true, acknowledgeOpen: true }",secret_guessable:"the value looks like one a person chose (fewer than 16 characters, or one kind of character only), and the proxy hides a sealed value an allowed host echoes back, which lets an agent confirm a guess there: use a random key, say acknowledgeGuessable: true to keep it sealed anyway, or make it open",open_not_acknowledged:"an open secret, and a secret made no secret (secret: false), is read by the agent as it is \u2014 anyone who can drive the project's agents can get its value: say acknowledgeOpen: true to say you read this"};function An(e,t){if(!(e instanceof I))return e;let i=vn[e.code];return i?new I({op:e.op,status:e.status,code:e.code,message:`${t}: ${i} (the platform: ${e.message}; ${e.op}: ${e.status} ${e.code})`,requestId:e.requestId,retryAfter:e.retryAfter,body:e.body,cause:e}):e}function U(e,t){return e.catch(i=>{throw An(i,t)})}var pt=["value","hosts","inject","open","secret","acknowledgeOpen","acknowledgeGuessable"];function xn(e,t){let i={};if(e.env!==void 0){if(typeof e.env!="object"||e.env===null||Array.isArray(e.env))throw new TypeError(`${t}: env is the agent's own variables, { NAME: value }`);let s=Object.entries(e.env);if(s.length>lt)throw new TypeError(`${t}: env names ${lt} variables at most`);let a={},d=u=>typeof u=="string"&&ut(u)<=H&&!u.includes("\0");for(let[u,o]of s){if(!Ce(u))throw new TypeError(`${t}: env: ${JSON.stringify(u.slice(0,140))} is no variable's name \u2014 upper-case letters, digits and _, a letter first, at most 128, and not PALAI_\u2026, the engine's own`);if(typeof o=="object"&&o!==null&&!Array.isArray(o)){let r=Object.keys(o).find(l=>!pt.includes(l));if(r!==void 0)throw new TypeError(`${t}: env.${u}: ${JSON.stringify(r.slice(0,64))} is not one of ${pt.join(", ")}`);let n=o;if(n.value!==void 0&&!d(n.value))throw new TypeError(`${t}: env.${u}.value is text of ${H} bytes at most, no NUL ('' keeps the value it has)`);a[u]={...n.value!==void 0?{value:n.value}:{},...Ie(n,`${t}: env.${u}`)};continue}if(!d(o))throw new TypeError(`${t}: env.${u} is text of ${H} bytes at most, no NUL ('' keeps the value it has), or { value, hosts, inject, open, secret, acknowledgeOpen, acknowledgeGuessable }`);a[u]=o}i.env=a}if(e.setup!==void 0){if(typeof e.setup!="string"||ut(e.setup)>dt||e.setup.includes("\0"))throw new TypeError(`${t}: setup is a shell script of ${dt} bytes at most, no NUL`);i.setup=e.setup}return i}function xt(e,t){if(typeof e!="string"||e.trim()===""||e.length>it)throw new TypeError(`${t}: description says what the agent is for, in a sentence or two (${it} characters at most)`);return e}function _n(e,t){let i=e?.prepared;if(i!==void 0&&typeof i=="object"&&i!==null&&typeof i.json=="object")return i.json;if(typeof e!="object"||e===null||!("~standard"in e))throw new TypeError(`${t}: output is the shape of its one-shot answers \u2014 a zod (valibot, arktype) object schema, or ai.schema(name, schema)`);return K(e,"output").json}function Oe(e,t){if(!Number.isInteger(e)||e<1||e>ot)throw new TypeError(`${t}: maxToolCalls is a whole number, 1 to ${ot} (got ${String(e)})`);return e}function Re(e,t){let i={};if(e.effort!==void 0){if(typeof e.effort!="string"||!at.includes(e.effort))throw new TypeError(`${t}: effort is one of ${at.join(", ")} \u2014 which a model takes is its catalogue entry's (ai.models())`);i.effort=e.effort}if(e.contextWindow!==void 0){if(!Number.isInteger(e.contextWindow)||e.contextWindow<1||e.contextWindow>bn)throw new TypeError(`${t}: contextWindow is a number of tokens (got ${String(e.contextWindow)})`);i.context_window=e.contextWindow}if(e.thinking!==void 0){if(e.thinking!=="visible"&&e.thinking!=="hidden")throw new TypeError(`${t}: thinking is visible (the model's reasoning in the chat's stream) or hidden`);i.thinking=e.thinking}if(e.toolOutputs!==void 0){if(e.toolOutputs!=="aged"&&e.toolOutputs!=="window")throw new TypeError(`${t}: toolOutputs is aged (a tool's output is cut to its first and last lines once it is four messages old) or window (only once the conversation fills the turn's window)`);i.tool_outputs=e.toolOutputs}return i}function pe(e,t){if(typeof e!="object"||e===null)throw new TypeError(`${t}: a definition is { description, instructions, model, tools, subagents, advisor, maxToolCalls, effort, contextWindow, thinking, toolOutputs, language, env, setup, output }`);let i={};if(e.description!==void 0&&(i.description=xt(e.description,t)),e.instructions!==void 0&&(i.instructions=e.instructions),e.model!==void 0&&(i.model=e.model),e.maxToolCalls!==void 0&&(i.max_tool_calls=Oe(e.maxToolCalls,t)),Object.assign(i,Re(e,t)),e.language!==void 0){if(typeof e.language!="string"||e.language.length>35||!Tn.test(e.language))throw new TypeError(`${t}: language is the language of the person the turn works for, as a BCP 47 tag (tr, en-GB)`);i.language=e.language}if(Object.assign(i,xn(e,t)),e.output!==void 0&&(i.output=_n(e.output,t)),e.tools!==void 0&&(i.tools=e.tools.map(s=>ne(s,t))),e.subagents!==void 0){for(let s of e.subagents){let a=(s?.tools??[]).find(d=>d?.source==="platform");if(a)throw new TypeError(`${t} subagent ${s.name}: the platform's ${a.name} is the agent's tool \u2014 its subagents work with the agent's`)}i.subagents=e.subagents.map(s=>({name:s.name,description:s.description,...s.instructions!==void 0?{instructions:s.instructions}:{},...s.model!==void 0?{model:s.model}:{},...s.required!==void 0?{required:s.required}:{},...Re(s,`${t} subagent ${s.name}`),...s.tools!==void 0?{tools:s.tools.map(a=>ne(a,`${t} subagent ${s.name}`))}:{}}))}return e.advisor!==void 0&&(i.advisor=En(e.advisor,`${t} advisor`)),i}function En(e,t){if(typeof e!="object"||e===null)throw new TypeError(`${t}: an advisor is { model, instructions, effort, tools }`);let i={};if(e.model!==void 0&&(i.model=e.model),e.instructions!==void 0){if(typeof e.instructions!="string"||new TextEncoder().encode(e.instructions).length>64*1024)throw new TypeError(`${t}: instructions is text, 64 KiB at most`);i.instructions=e.instructions}let{effort:s}=Re({effort:e.effort},t);if(s!==void 0&&(i.effort=s),e.tools!==void 0){if(!Array.isArray(e.tools)||e.tools.length>32)throw new TypeError(`${t}: tools is 32 MCP servers at most`);i.tools=e.tools.map(a=>{if(a?.source!=="mcp")throw new TypeError(`${t}: the advisor reads; its tools are MCP servers' ({ source: 'mcp', name }), whose tools it is given when they say they only read`);if(a.approval===!0)throw new TypeError(`${t}: nothing the advisor reads waits for a person (approval)`);return ne(a,t)})}return i}function G(e,t,i){if(typeof e!="string"||!ce.test(e))throw new TypeError(`${t}: ${i} (got ${JSON.stringify(e)})`);return e}var ge="the pool is one of the project's runner pools, by its id or its name";function _t(e){return{id:e.id,name:e.name,os:e.os,arch:e.arch,...e.created_at!==void 0?{createdAt:e.created_at}:{},...e.machines!==void 0?{machines:e.machines}:{},...e.capacity_total!==void 0?{capacityTotal:e.capacity_total}:{},...e.capacity_used!==void 0?{capacityUsed:e.capacity_used}:{},...e.waiting!==void 0?{waiting:e.waiting}:{}}}function Et(e){return{id:e.id,...e.label?{label:e.label}:{},...e.created_at!==void 0?{createdAt:e.created_at}:{},...e.expires_at!==void 0?{expiresAt:e.expires_at}:{},...e.last_used_at?{lastUsedAt:e.last_used_at}:{},...e.revoked_at?{revokedAt:e.revoked_at}:{}}}function Rn(e){return{id:e.id,...e.owner?{owner:e.owner}:{},state:e.state,capacity:e.capacity,used:e.used,...e.label?{label:e.label}:{},...e.os?{os:e.os}:{},...e.arch?{arch:e.arch}:{},idleSince:e.idle_since??null,lastSeenAt:e.last_seen_at??null,registeredAt:e.registered_at??null,...e.harnesses!==void 0?{harnesses:e.harnesses.map(le)}:{}}}var fe=e=>({key:e.key,secret:e.secret,hosts:e.hosts??[],inject:e.inject??[],open:e.open===!0,updatedAt:e.updated_at}),$e=e=>({requestId:e.request_id,key:e.key,agent:e.agent??null,origin:e.origin??null,host:e.host,domain:e.domain??e.host,status:e.status,asks:e.asks,firstAskedAt:e.first_asked_at,lastAskedAt:e.last_asked_at,decidedAt:e.decided_at??null}),Pn=e=>({allowanceId:e.allowance_id,origin:e.origin??"kept",agent:e.agent,key:e.key,host:e.host,domain:e.domain??e.host,allowedAt:e.allowed_at,allowedBy:e.allowed_by}),Rt="the ask is one env.hostRequests.list says, by its id (shr_\u2026)",Cn="an open secret is read by the agent as it is: anyone who can drive the project's agents \u2014 an app's user where the project lets them, a prompt the agent reads \u2014 can get its value. Say acknowledgeOpen: true with open: true to say you read this";function Pt(e,t,i){if(typeof t!="object"||t===null)throw new TypeError(`${i}(${JSON.stringify(e)}): options are { secret, hosts, inject, open, acknowledgeOpen, acknowledgeGuessable }`);let s=Ie(t,`${i}(${JSON.stringify(e)})`);if(t.open===!0&&t.acknowledgeOpen!==!0)throw new TypeError(`${i}(${JSON.stringify(e)}): ${Cn}`);return s}function me(e,t){if(!Ce(e))throw new TypeError(`${t}: ${JSON.stringify(typeof e=="string"?e.slice(0,140):e)} is no variable's name \u2014 upper-case letters, digits and _, a letter first, at most 128, and not PALAI_\u2026, the engine's own`);return e}function Ct(e){let t={async create(a){if(typeof a?.name!="string"||!j.test(a.name))throw new TypeError("pools.create: name is lowercase letters, digits, _ and -, a letter first, at most 64 \u2014 the project's once");if(a.os!=="linux"&&a.os!=="macos")throw new TypeError("pools.create: os is its machines' operating system, linux or macos (a pool is of one type)");if(a.arch!=="amd64"&&a.arch!=="arm64")throw new TypeError("pools.create: arch is its machines' architecture, amd64 or arm64 (a pool is of one type)");return _t((await e.createPool({body:{name:a.name,os:a.os,arch:a.arch},signal:a.signal})).data)},async list(a={}){return(await e.listPools({signal:a.signal})).data.pools.map(_t)},async delete(a,d={}){await e.deletePool({path:{pool:G(a,"pools.delete",ge)},signal:d.signal})},async state(a,d={}){let u=(await e.getPoolState({path:{pool:G(a,"pools.state",ge)},signal:d.signal})).data;return{pool:{id:u.pool.id,name:u.pool.name,os:u.pool.os,arch:u.pool.arch},capacityTotal:u.capacity_total,capacityUsed:u.capacity_used,waiting:u.waiting,oldestWaitingSince:u.oldest_waiting_since??null,machines:u.machines.map(Rn)}},keys:{async create(a,d={}){let u={};if(d.label!==void 0){if(!Tt(d.label))throw new TypeError(`pools.keys.create: label is what the key is for, ${bt}`);u.label=d.label}let o=(await e.createPoolKey({path:{pool:G(a,"pools.keys.create",ge)},body:u,signal:d.signal})).data;if(typeof o.key!="string"||o.key==="")throw new I({op:"createPoolKey",status:502,code:"no_key",message:`the key ${o.id} was minted but not said: revoke it (pools.keys.revoke) and mint another`});return{...Et(o),key:o.key,...o.enroll_url?{enrollUrl:o.enroll_url}:{},...o.enroll?{enroll:{url:o.enroll.url,...o.enroll.server_name?{serverName:o.enroll.server_name}:{},...o.enroll.ca_certificate?{caCertificate:o.enroll.ca_certificate}:{}}}:{}}},async list(a,d={}){return(await e.listPoolKeys({path:{pool:G(a,"pools.keys.list",ge)},signal:d.signal})).data.keys.map(Et)},async revoke(a,d={}){await e.revokePoolKey({path:{key:G(a,"pools.keys.revoke","the key is a pool's key by its id (pools.keys.list)")},signal:d.signal})}}},i=Je(e,"server","the machine is a pool's machine by its id (pools.state(pool).machines), or one of a user's (machines.list({ owner }))");return{pools:t,machines:i,env:{async set(a,d,u={}){me(a,"env.set");let o=`env.set(${JSON.stringify(a)})`;if(typeof d!="string"||d===""||new TextEncoder().encode(d).byteLength>H||d.includes("\0"))throw new TypeError(`${o}: the value is text of 1 to ${H} bytes, no NUL \u2014 to change what a variable says of itself and keep its value: env.update`);let r={value:d,...Pt(a,u,"env.set")};return fe((await U(e.putEnv({path:{key:a},body:r,signal:u.signal}),o)).data)},async update(a,d){me(a,"env.update");let u=Pt(a,d,"env.update");if(Object.keys(u).every(o=>o.startsWith("acknowledge_")))throw new TypeError(`env.update(${JSON.stringify(a)}): say what changes \u2014 secret, hosts, inject or open (its value: env.set)`);return fe((await U(e.putEnv({path:{key:a},body:u,signal:d.signal}),`env.update(${JSON.stringify(a)})`)).data)},async unset(a,d={}){await e.deleteEnv({path:{key:me(a,"env.unset")},signal:d.signal})},async list(a={}){return(await e.listEnv({signal:a.signal})).data.variables.map(fe)},async allowHost(a,d,u={}){if(me(a,"env.allowHost"),typeof d!="string"||d===""||d.length>253)throw new TypeError(`env.allowHost(${JSON.stringify(a)}): the host is an exact DNS name (api.stripe.com) or *. and one (*.stripe.com), as text`);return fe((await U(e.allowEnvHost({path:{key:a},body:{host:d},signal:u.signal}),`env.allowHost(${JSON.stringify(a)})`)).data)},hostRequests:{async list(a={}){if(a.status!==void 0&&!["asked","allowed","dismissed"].includes(a.status))throw new TypeError("env.hostRequests.list: status is asked (the default), allowed or dismissed");let d=a.status!==void 0?{status:a.status}:void 0;return(await e.listEnvHostRequests({...d?{query:d}:{},signal:a.signal})).data.requests.map($e)},async allow(a,d={}){let u=G(a,"env.hostRequests.allow",Rt);return $e((await U(e.allowEnvHostRequest({path:{request_id:u},signal:d.signal}),`env.hostRequests.allow(${JSON.stringify(u)})`)).data)},async dismiss(a,d={}){let u=G(a,"env.hostRequests.dismiss",Rt);return $e((await U(e.dismissEnvHostRequest({path:{request_id:u},signal:d.signal}),`env.hostRequests.dismiss(${JSON.stringify(u)})`)).data)}},allowances:{async list(a={}){return(await e.listEnvAllowances({signal:a.signal})).data.allowances.map(Pn)},async remove(a,d={}){let u=G(a,"env.allowances.remove","the allowance is one env.allowances.list says, by its id (sha_\u2026)");await U(e.deleteEnvAllowance({path:{allowance_id:u},signal:d.signal}),`env.allowances.remove(${JSON.stringify(u)})`)}}}}}function J(e,t){if(typeof e!="string"||!j.test(e))throw new TypeError(`${t}: an agent's name is lowercase letters, digits, _ and -, starting with a letter, at most 64 (got ${JSON.stringify(e)})`);return e}function It(e,t){if(!Number.isSafeInteger(e)||e<1)throw new TypeError(`${t}: revision is the draft's revision as it was read (Agent's revision), a whole number from 1 (got ${String(e)})`);return e}function Ot(e,t){let i={approve:e};return t.reason!==void 0&&(i.reason=t.reason),t.as!==void 0&&(i.as=t.as),i}var In=/^[a-z][a-z0-9-]{1,62}$/,$t=4,Mt=8;function On(e){let t={},i=(s,a)=>{if(typeof s?.bucket!="string"||!In.test(s.bucket))throw new TypeError(`chats.send: ${a}'s bucket is one of the project's buckets, by its name`);if(typeof s.path!="string"||s.path===""||s.path.length>1024)throw new TypeError(`chats.send: ${a}'s path is its path in the bucket (1024 characters at most)`);return{bucket:s.bucket,path:s.path}};if(e.images!==void 0){if(!Array.isArray(e.images)||e.images.length>$t)throw new TypeError(`chats.send: images are ${$t} at most \u2014 as many as the model is shown at once`);t.images=e.images.map((s,a)=>i(s,`images[${a}]`))}if(e.files!==void 0){if(!Array.isArray(e.files)||e.files.length>Mt)throw new TypeError(`chats.send: files are ${Mt} at most`);t.files=e.files.map((s,a)=>{let d=i(s,`files[${a}]`);if(s.filename!==void 0){if(typeof s.filename!="string"||s.filename===""||s.filename.length>255)throw new TypeError(`chats.send: files[${a}].filename is its name in the workspace (255 characters at most)`);d.filename=s.filename}if(s.contentType!==void 0){if(typeof s.contentType!="string"||s.contentType===""||s.contentType.length>128)throw new TypeError(`chats.send: files[${a}].contentType is a media type (application/pdf)`);d.content_type=s.contentType}return d})}return t}function $n(e){if(!e)return;let t={};return e.mode!==void 0&&(t.mode=e.mode),e.wake_phrases!==void 0&&(t.wakePhrases=e.wake_phrases),e.idle_close_seconds!==void 0&&(t.idleCloseSeconds=e.idle_close_seconds),t}function Mn(e){let t={type:e?.type??"webrtc"};e?.sdp!==void 0&&(t.sdp=e.sdp),e?.call_id!==void 0&&(t.callId=e.call_id),e?.identity!==void 0&&(t.identity=e.identity),e?.name!==void 0&&(t.name=e.name),e?.room!==void 0&&(t.room=e.room),e?.media_url!==void 0&&(t.mediaUrl=e.media_url);let i=$n(e?.activation);return i!==void 0&&(t.activation=i),e?.gate_open!==void 0&&(t.gateOpen=e.gate_open),t}function he(e){let t={id:e.id,chatId:e.chat_id,userId:e.user_id,transport:Mn(e.transport),delegation:e.delegation,status:e.status,seconds:e.seconds,startedAt:e.started_at,closedAt:e.closed_at,closeReason:e.close_reason??""};return e.model!==void 0&&(t.model=e.model),t}var qn=["speak","tell","know","instruct","activate","deactivate"];function qt(){return"cm_"+crypto.randomUUID()}async function oe(e,t,i=4){for(let s=1;;s++)try{return await e()}catch(a){if(s>=i||!(a instanceof I)||a.status===429||t?.aborted)throw a;let d=Le(a,s,30);if(d===void 0)throw a;await new Promise((u,o)=>{let r=setTimeout(u,d*1e3);t?.addEventListener("abort",()=>(clearTimeout(r),o(t.reason)),{once:!0})})}}function Me(e){return{id:e.id,chatId:e.chat_id,objective:e.objective,rubric:e.rubric,status:e.status,stopCode:e.stop_code,stopReason:e.stop_reason,phase:e.phase,setBy:e.set_by,maxTurns:e.max_turns,budget:e.budget===null?null:{maxCostUsd:e.budget.max_cost_usd},usage:{turns:e.usage.turns,verifications:e.usage.verifications,costUsd:e.usage.cost_usd,costIsLowerBound:e.usage.cost_is_lower_bound,activeSeconds:e.usage.active_seconds},achievedAt:e.achieved_at,createdAt:e.created_at,updatedAt:e.updated_at}}var jt=e=>({user_id:e.userId,...e.name!==void 0?{name:e.name}:{},...e.email!==void 0?{email:e.email}:{},...e.owner!==void 0?{owner:e.owner}:{}}),jn=/^[a-z0-9][a-z0-9_-]{0,62}$/;function ye(e,t){if(typeof e!="string"||!jn.test(e))throw new TypeError(`${t}: environment name must match ^[a-z0-9][a-z0-9_-]{0,62}$ (got ${JSON.stringify(e)})`);return e}function Un(e){return{runId:e.run_id,responseId:e.response_id,parentRunId:e.parent_run_id??null,subagent:e.subagent,model:e.model,state:e.state,inputTokens:e.input_tokens,outputTokens:e.output_tokens,cacheReadTokens:e.cache_read_tokens,cacheWriteTokens:e.cache_write_tokens,costNanoUsd:e.cost_nano_usd,usd:e.usd,unpriced:e.unpriced}}function qe(e,t){if(typeof e!="object"||e===null||typeof e.compute!="object"||e.compute===null||typeof e.executor!="object"||e.executor===null)throw new TypeError(`${t}: target requires { compute, executor }`);let i=e.compute;if(!["serverless","cloud","pool","machine"].includes(i.kind))throw new TypeError(`${t}: target.compute.kind must be serverless, cloud, pool, or machine`);let s=e.executor;if(s.kind!=="palbase"&&s.kind!=="acp")throw new TypeError(`${t}: target.executor.kind must be palbase or acp`);if(s.kind==="acp"&&s.harness!=="claude-code"&&s.harness!=="codex"&&s.harness!=="gemini-cli")throw new TypeError(`${t}: target.executor.harness must be claude-code, codex, or gemini-cli when executor.kind is acp`);return{compute:{kind:i.kind,...i.poolId!==void 0?{pool_id:i.poolId}:{},...i.machineId!==void 0?{machine_id:i.machineId}:{},...i.environment!==void 0?{environment:i.environment}:{}},executor:{kind:s.kind,...s.harness!==void 0?{harness:s.harness}:{},...s.model!==void 0?{model:s.model}:{},...s.effort!==void 0?{effort:s.effort}:{}}}}function we(e){return{compute:{kind:e.compute.kind,...e.compute.pool_id!==void 0?{poolId:e.compute.pool_id}:{},...e.compute.machine_id!==void 0?{machineId:e.compute.machine_id}:{},...e.compute.environment!==void 0?{environment:e.compute.environment}:{}},executor:{kind:e.executor.kind,...e.executor.harness!==void 0?{harness:e.executor.harness}:{},...e.executor.model!==void 0?{model:e.executor.model}:{},...e.executor.effort!==void 0?{effort:e.executor.effort}:{}}}}function Ut(e,t){if(!Number.isSafeInteger(e.afterOfflineSeconds)||e.afterOfflineSeconds<30||e.afterOfflineSeconds>86400)throw new TypeError(`${t}: autoFailover.afterOfflineSeconds must be an integer between 30 and 86400`);return{after_offline_seconds:e.afterOfflineSeconds,to:qe(e.to,`${t}: autoFailover.to`),...e.requireWorkspaceCleanBeforeCut!==void 0?{require_workspace_clean_before_cut:e.requireWorkspaceCleanBeforeCut}:{}}}function Nn(e){return e?{afterOfflineSeconds:e.after_offline_seconds,to:we(e.to),...e.require_workspace_clean_before_cut!==void 0?{requireWorkspaceCleanBeforeCut:e.require_workspace_clean_before_cut}:{}}:null}function Nt(e){return{chatId:e.chat_id,target:we(e.target),targetGeneration:e.target_generation,...e.workspace_id!==void 0?{workspaceId:e.workspace_id}:{},workspaceSeq:e.workspace_seq,...e.machine_status!==void 0?{machineStatus:e.machine_status}:{},...e.machine_name!==void 0?{machineName:e.machine_name}:{},...e.harnesses!==void 0?{harnesses:e.harnesses.map(le)}:{},autoFailover:Nn(e.auto_failover),failoverAt:e.failover_at??null,...e.pending_handoff!==void 0?{pendingHandoff:{to:we(e.pending_handoff.to),reason:e.pending_handoff.reason,...e.pending_handoff.idempotency_key!==void 0?{idempotencyKey:e.pending_handoff.idempotency_key}:{},requestedAt:e.pending_handoff.requested_at}}:{}}}function Wn(e){return{chatId:e.chat_id,targetGeneration:e.target_generation,target:we(e.target),workspaceSeq:e.workspace_seq,activeRunAction:e.active_run_action,...e.resumed_response_id!==void 0?{resumedResponseId:e.resumed_response_id}:{}}}function Wt(e){return{clients:e.clients,userMessagesPerMinute:e.user_messages_per_minute,historyLimitBytes:e.history_limit_bytes,historyBytes:e.history_bytes,monthlyBudgetUsd:e.monthly_budget_usd??null,openSecretsForAppUsers:e.open_secrets_for_app_users===!0,allowClientHandoff:e.allow_client_handoff===!0,autoPipeChats:e.auto_pipe_chats===!0,userMachines:e.user_machines===!0,userMachineLimit:e.user_machine_limit??3}}function Dn(e){return new Proxy(e,{get(t,i){let s=t[i];return typeof s=="function"?(...a)=>w(s.apply(t,a)):s}})}function Dt(e){let t=Dn(e);return{chats:{async create(o){let r=typeof o.agent=="string"||o.agent===void 0?o.agent:se(o.agent)?.name;if(o.agent!==void 0&&r===void 0)throw new TypeError("chats.create: agent is one of the project's agents by name (name@N for a version), or a backend's ai.agent");if(r===void 0&&o.definition===void 0)throw new TypeError("chats.create: an agent (one of the project's, by name) or a definition of the chat's own");let n={agent:r??"assistant"};if(o.definition!==void 0&&(n.definition=pe(o.definition,"chats.create")),o.title!==void 0&&(n.title=o.title),o.metadata!==void 0&&(n.metadata=o.metadata),o.members!==void 0&&(n.members=o.members.map(jt)),o.pool!==void 0){if(typeof o.pool!="string"||!ce.test(o.pool))throw new TypeError("chats.create: pool is one of the project's runner pools (ai.pools), by its id or its name");n.pool=o.pool}if(o.workspaceId!==void 0){if(typeof o.workspaceId!="string"||o.workspaceId==="")throw new TypeError("chats.create: workspaceId is a workspaces module id (ws_\u2026)");n.workspace_id=o.workspaceId}return o.target!==void 0&&(n.target=qe(o.target,"chats.create")),o.autoFailover!==void 0&&(n.auto_failover=o.autoFailover===null?null:Ut(o.autoFailover,"chats.create")),o.live!==void 0&&(n.live=o.live),(await(o.definition!==void 0?U(t.createChat({body:n,signal:o.signal}),"chats.create"):t.createChat({body:n,signal:o.signal}))).data},async get(o,r={}){return(await t.getChat({path:{chat_id:o},signal:r.signal})).data},async list(o={}){let r=o.metadata===void 0?void 0:Object.entries(o.metadata).map(([l,c])=>`${l}:${c}`),n=(await t.listChats({query:{member:o.member,limit:o.limit,cursor:o.cursor,metadata:r,...o.status!==void 0?{status:o.status}:{}},signal:o.signal})).data;return n.next_cursor===void 0?{chats:n.chats}:{chats:n.chats,nextCursor:n.next_cursor}},async handoff(o,r){if(r?.when!==void 0&&r.when!=="idle"&&r.when!=="after_turn"&&r.when!=="now")throw new TypeError("chats.handoff: when must be idle, after_turn, or now");if(r?.graceSeconds!==void 0&&(!Number.isSafeInteger(r.graceSeconds)||r.graceSeconds<1||r.graceSeconds>60))throw new TypeError("chats.handoff: graceSeconds must be an integer between 1 and 60");let n={to:qe(r.to,"chats.handoff"),...r.when!==void 0?{when:r.when}:{},...r.graceSeconds!==void 0?{grace_seconds:r.graceSeconds}:{},idempotency_key:r.idempotencyKey??`ho_${crypto.randomUUID()}`};return Wn((await oe(()=>t.handoffChat({path:{chat_id:o},body:n,signal:r.signal}),r.signal)).data)},async execution(o,r={}){return Nt((await t.getChatExecution({path:{chat_id:o},signal:r.signal})).data)},async updateExecution(o,r){let n={};return r.autoFailover!==void 0&&(n.auto_failover=r.autoFailover===null?null:Ut(r.autoFailover,"chats.updateExecution")),r.model!==void 0&&(n.model=r.model),r.effort!==void 0&&(n.effort=r.effort),Nt((await t.patchChatExecution({path:{chat_id:o},body:n,signal:r.signal})).data)},async delete(o){await t.deleteChat({path:{chat_id:o}})},members:{async put(o,r,n){let l={};return n.name!==void 0&&(l.name=n.name),n.email!==void 0&&(l.email=n.email),n.owner!==void 0&&(l.owner=n.owner),(await t.putChatMember({path:{chat_id:o,user_id:r},body:l})).data},async delete(o,r){await t.deleteChatMember({path:{chat_id:o,user_id:r}})}},async send(o,r){let n={client_id:r.clientId??qt(),text:r.text};return r.delivery!==void 0&&(n.delivery=r.delivery),r.as!==void 0&&(n.as=r.as),r.budget!==void 0&&(n.budget={max_cost_usd:r.budget.maxCostUsd}),r.metadata!==void 0&&(n.metadata=r.metadata),r.context!==void 0&&(n.context=r.context),Object.assign(n,On(r)),oe(async()=>(await t.sendChatMessage({path:{chat_id:o},body:n,signal:r.signal})).data,r.signal)},async turnCost(o,r,n={}){let l=(await t.getChatTurnCost({path:{chat_id:o,response_id:r},signal:n.signal})).data,c={chatId:l.chat_id,responseId:l.response_id,inputTokens:l.input_tokens,outputTokens:l.output_tokens,costNanoUsd:l.cost_nano_usd,usd:l.usd,unpriced:l.unpriced,final:l.final,runs:l.runs.map(Un)};return l.advisor&&(c.advisor={inputTokens:l.advisor.input_tokens,outputTokens:l.advisor.output_tokens,cacheReadTokens:l.advisor.cache_read_tokens,cacheWriteTokens:l.advisor.cache_write_tokens,costNanoUsd:l.advisor.cost_nano_usd,usd:l.advisor.usd,unpriced:l.advisor.unpriced}),c},async artifacts(o,r,n={}){return(await t.listChatTurnArtifacts({path:{chat_id:o,response_id:r},signal:n.signal})).data.artifacts.map(c=>({id:c.id,mediaType:c.media_type,...c.logical_type?{logicalType:c.logical_type}:{},sizeBytes:c.size_bytes,checksum:c.checksum,createdAt:c.created_at}))},async artifact(o,r,n,l={}){return(await t.getChatTurnArtifact({path:{chat_id:o,response_id:r,artifact_id:n},signal:l.signal})).data},async messages(o,r={}){let n=(await t.listChatMessages({path:{chat_id:o},query:{limit:r.limit,cursor:r.cursor},signal:r.signal})).data;return n.next_cursor===void 0?{messages:n.messages}:{messages:n.messages,nextCursor:n.next_cursor}},async parts(o,r={}){if(r.cursor!==void 0&&r.before!==void 0)throw new TypeError("chats.parts: cursor (where a page left off) or before (the oldest part the app's channel holds, by its id), not both");if(r.before!==void 0&&(!Number.isSafeInteger(r.before)||r.before<1))throw new TypeError(`chats.parts: before is a part's id \u2014 its journal sequence, a whole number from 1 (got ${String(r.before)})`);if(r.limit!==void 0&&r.turns!==void 0)throw new TypeError("chats.parts: limit (events) or turns (turns), not both");if(r.turns!==void 0&&(!Number.isSafeInteger(r.turns)||r.turns<1||r.turns>20))throw new TypeError(`chats.parts: turns is how many of the chat's turns a page reads back to, 1 to 20 (got ${String(r.turns)})`);let n=(await t.listChatParts({path:{chat_id:o},query:{limit:r.limit,turns:r.turns,cursor:r.cursor,before:r.before},signal:r.signal})).data;return{parts:n.parts.map(c=>({type:c.type,...c.id!==void 0?{id:c.id}:{},partId:c.part_id,data:c.data})),...n.next_cursor!==void 0?{nextCursor:n.next_cursor}:{},...n.turns!==void 0?{turns:n.turns}:{}}},async toolCall(o,r,n={}){let l=(await t.getChatToolCall({path:{chat_id:o,call_id:r},signal:n.signal})).data;return{callId:l.call_id,name:l.name,status:l.status,runId:l.run_id,responseId:l.response_id,input:l.input,output:l.output,outputBytes:l.output_bytes,imageCount:l.image_count,isError:l.is_error}},async toolCalls(o,r){if(typeof r?.turn!="string"||r.turn==="")throw new TypeError("chats.toolCalls: turn is the turn's responseId \u2014 a message's, or a turn's or an agent part's");let n=(await t.listTurnToolCalls({path:{chat_id:o},query:{turn:r.turn,limit:r.limit,cursor:r.cursor},signal:r.signal})).data,l=n.tool_calls.map(c=>({callId:c.call_id,name:c.name,state:c.state,createdAt:c.created_at,updatedAt:c.updated_at,arguments:c.arguments,...c.result!==void 0?{result:c.result}:{}}));return n.next_cursor===void 0?{toolCalls:l}:{toolCalls:l,nextCursor:n.next_cursor}},events(o){if(typeof o!="string"||!/^chat_[0-9a-f]{32}$/.test(o))throw new TypeError(`chats.events(id): a chat's id, chat_ and 32 hex digits (got ${JSON.stringify(o)})`);return Object.freeze({kind:"ai.chat",chatId:o,async pipe(r,n={}){await t.putChatPipe({path:{chat_id:o},body:{topic:r},signal:n.signal})},async unpipe(r={}){await t.deleteChatPipe({path:{chat_id:o},signal:r.signal})}})},async stop(o,r={}){return(await t.stopChat({path:{chat_id:o},...r.as!==void 0?{body:{as:r.as}}:{},signal:r.signal})).data.stopped},async approve(o,r,n={}){return(await t.decideChatApproval({path:{chat_id:o,approval_id:r},body:Ot(!0,n)})).data},async deny(o,r,n={}){return(await t.decideChatApproval({path:{chat_id:o,approval_id:r},body:Ot(!1,n)})).data},async answer(o,r,n,l={}){let c={output:te(n)};l.isError&&(c.is_error=!0),l.as!==void 0&&(c.as=l.as),l.workspaceTree!==void 0&&(c.workspace_tree=re(l.workspaceTree,"chats.answer"));try{return await oe(()=>t.answerChatToolCall({path:{chat_id:o,call_id:r},body:c})),!0}catch(f){if(f instanceof I&&f.status===409)return!1;throw f}},async sendToSubagent(o,r,n,l={}){let c={client_id:l.clientId??qt(),text:n};l.as!==void 0&&(c.as=l.as);let f=await oe(async()=>(await t.sendSubagentMessage({path:{chat_id:o,run_id:r},body:c})).data);return{runId:f.run_id,clientId:f.client_id}},async stopSubagent(o,r,n={}){return{runId:(await oe(async()=>(await t.stopSubagent({path:{chat_id:o,run_id:r},body:n.as!==void 0?{as:n.as}:{},signal:n.signal})).data,n.signal)).run_id}},async fork(o,r){if(typeof r?.beforeMessage!="string"||r.beforeMessage==="")throw new TypeError("chats.fork: beforeMessage is the id of the message the fork is cut before (a message's id, msg_\u2026)");let n={before_message:r.beforeMessage};return r.title!==void 0&&(n.title=r.title),r.members!==void 0&&(n.members=r.members.map(jt)),(await t.forkChat({path:{chat_id:o},body:n,signal:r.signal})).data},goal:{async set(o,r){let n={objective:r.objective};return r.rubric!==void 0&&(n.rubric=r.rubric),r.maxTurns!==void 0&&(n.max_turns=r.maxTurns),r.budget!==void 0&&(n.budget={max_cost_usd:r.budget.maxCostUsd}),r.as!==void 0&&(n.as=r.as),Me((await t.setChatGoal({path:{chat_id:o},body:n,signal:r.signal})).data)},async get(o,r={}){return Me((await t.getChatGoal({path:{chat_id:o},query:r.as!==void 0?{as:r.as}:void 0,signal:r.signal})).data)},async update(o,r){let n={};return r.status!==void 0&&(n.status=r.status),r.reason!==void 0&&(n.reason=r.reason),r.objective!==void 0&&(n.objective=r.objective),r.rubric!==void 0&&(n.rubric=r.rubric),r.maxTurns!==void 0&&(n.max_turns=r.maxTurns),r.budget!==void 0&&(n.budget=r.budget===null?null:{max_cost_usd:r.budget.maxCostUsd}),r.as!==void 0&&(n.as=r.as),Me((await t.updateChatGoal({path:{chat_id:o},body:n,signal:r.signal})).data)},async clear(o,r={}){await t.clearChatGoal({path:{chat_id:o},query:r.as!==void 0?{as:r.as}:void 0,signal:r.signal})}},voice:{async start(o,r){if(r?.delegation!==void 0&&r.delegation!=="chat"&&r.delegation!=="events")throw new TypeError("chats.voice.start: delegation is chat (a turn of the chat) or events (ai.voice.delegated)");let n=r?.transport;if(!n||n.type!=="webrtc"&&n.type!=="call")throw new TypeError("chats.voice.start: transport is { type: 'webrtc', sdp } or { type: 'call', callId, ... }");let l;if(n.type==="webrtc"){if(typeof n.sdp!="string"||!n.sdp.startsWith("v="))throw new TypeError("chats.voice.start: transport.sdp is the app's WebRTC offer (an SDP, v=0 \u2026): its peer connection's localDescription.sdp");l={type:"webrtc",sdp:n.sdp}}else{if(typeof n.callId!="string"||n.callId.trim()==="")throw new TypeError("chats.voice.start: transport.callId is the Palbase Calls room ID to join");if(l={type:"call",call_id:n.callId},n.identity!==void 0&&(l.identity=n.identity),n.name!==void 0&&(l.name=n.name),n.activation!==void 0){let C={};n.activation.mode!==void 0&&(C.mode=n.activation.mode),n.activation.wakePhrases!==void 0&&(C.wake_phrases=n.activation.wakePhrases),n.activation.idleCloseSeconds!==void 0&&(C.idle_close_seconds=n.activation.idleCloseSeconds),l.activation=C}}let c={transport:l};r.model!==void 0&&(c.model=r.model),r.voice!==void 0&&(c.voice=r.voice),r.delegation!==void 0&&(c.delegation=r.delegation),r.as!==void 0&&(c.as=r.as),r.instructions!==void 0&&(c.instructions=r.instructions),r.context!==void 0&&(c.context=r.context);let f=(await t.startChatVoice({path:{chat_id:o},body:c,signal:r.signal})).data;if(n.type==="webrtc"&&(typeof f.transport?.sdp!="string"||f.transport.sdp===""))throw new I({op:"startChatVoice",status:502,code:"no_answer",message:"the voice was started but its WebRTC answer was not given"});return he(f)},async get(o,r,n={}){return he((await t.getChatVoice({path:{chat_id:o,voice_id:r},query:n.as!==void 0?{as:n.as}:void 0,signal:n.signal})).data)},async command(o,r,n){if(!qn.includes(n?.type))throw new TypeError("chats.voice.command: type is speak (say this exactly), tell (say it in your own words), know (keep it in mind), instruct (behave so), activate or deactivate");if(n.type!=="activate"&&n.type!=="deactivate"&&(typeof n.text!="string"||n.text===""))throw new TypeError("chats.voice.command: text is what the voice is given");if(n.delegationId!==void 0&&n.type!=="speak"&&n.type!=="tell")throw new TypeError("chats.voice.command: delegationId names the request a speak or a tell answers");if(n.interrupt!==void 0&&(typeof n.interrupt!="boolean"||n.type!=="speak"))throw new TypeError("chats.voice.command: interrupt is a speak's: it cuts what the voice is saying");let c={type:n.type};return n.text!==void 0&&(c.text=n.text),n.delegationId!==void 0&&(c.delegation_id=n.delegationId),n.interrupt===!0&&(c.interrupt=!0),n.as!==void 0&&(c.as=n.as),he((await t.commandChatVoice({path:{chat_id:o,voice_id:r},body:c,signal:n.signal})).data)},async close(o,r,n={}){return he((await t.closeChatVoice({path:{chat_id:o,voice_id:r},query:n.as!==void 0?{as:n.as}:void 0,signal:n.signal})).data)}}},agents:{async list(o={}){return(await t.listAgents({signal:o.signal})).data.agents},async get(o,r={}){return(await t.getAgent({path:{name:J(o,"agents.get")},signal:r.signal})).data},async saveDraft(o,r,n={}){let l=`agents.saveDraft(${JSON.stringify(o)})`;if(J(o,"agents.saveDraft"),se(r))throw new TypeError(`${l}: a backend's ai.agent is its code's \u2014 its build's contract names it, and its chats ask its machine; it has no draft to save`);if(r===void 0)throw new TypeError(`${l}: its definition \u2014 { instructions, model, tools, \u2026 }`);let c=pe(r,l);return(await U(t.putAgent({path:{name:o},...n.revision!==void 0?{query:{revision:It(n.revision,l)}}:{},body:c,signal:n.signal}),l)).data},async publish(o,r={}){let n=`agents.publish(${JSON.stringify(o)})`;J(o,"agents.publish");let l=r.revision!==void 0?{revision:It(r.revision,n)}:{};return(await t.publishAgent({path:{name:o},body:l,signal:r.signal})).data},async rollback(o,r,n={}){if(J(o,"agents.rollback"),!Number.isSafeInteger(r)||r<1)throw new TypeError(`agents.rollback(${JSON.stringify(o)}): version is one it had \u2014 a whole number from 1 (got ${String(r)})`);return(await U(t.rollbackAgent({path:{name:o},body:{version:r},signal:n.signal}),`agents.rollback(${JSON.stringify(o)})`)).data},async versions(o,r={}){J(o,"agents.versions");let n=(await t.listAgentVersions({path:{name:o},query:{limit:r.limit,cursor:r.cursor},signal:r.signal})).data;return n.next_cursor===void 0?{versions:n.versions,publishedVersion:n.published_version}:{versions:n.versions,publishedVersion:n.published_version,nextCursor:n.next_cursor}},async delete(o,r={}){await t.deleteAgent({path:{name:J(o,"agents.delete")},signal:r.signal})},async tools(o={}){return(await t.listTools({signal:o.signal})).data.tools}},endpoints:{async put(o,r){let n={kind:r.kind,url:r.url};if(r.description!==void 0&&(n.description=r.description),r.parameters!==void 0&&(n.parameters=r.parameters),r.approval!==void 0&&(n.approval=r.approval),r.workspace!==void 0){if(typeof r.workspace!="boolean")throw new TypeError("endpoints.put: workspace is true for an endpoint of the project's own that reads or writes a chat's workspace, false (the default) for any other");n.workspace=r.workspace}return(await t.putEndpoint({path:{name:o},body:n})).data},async list(){return(await t.listEndpoints({})).data.endpoints},async delete(o){await t.deleteEndpoint({path:{name:o}})}},settings:{async get(){return Wt((await t.getSettings({})).data)},async put(o){let r={};if(o.clients!==void 0&&(r.clients=o.clients),o.userMessagesPerMinute!==void 0&&(r.user_messages_per_minute=o.userMessagesPerMinute),o.historyLimitBytes!==void 0&&(r.history_limit_bytes=o.historyLimitBytes),o.openSecretsForAppUsers!==void 0){if(typeof o.openSecretsForAppUsers!="boolean")throw new TypeError("settings.put: openSecretsForAppUsers is true (an app's users' work has the project's open secrets) or false");r.open_secrets_for_app_users=o.openSecretsForAppUsers}if(o.allowClientHandoff!==void 0){if(typeof o.allowClientHandoff!="boolean")throw new TypeError("settings.put: allowClientHandoff is true or false");r.allow_client_handoff=o.allowClientHandoff}if(o.autoPipeChats!==void 0){if(typeof o.autoPipeChats!="boolean")throw new TypeError("settings.put: autoPipeChats is true or false");r.auto_pipe_chats=o.autoPipeChats}if(o.userMachines!==void 0){if(typeof o.userMachines!="boolean")throw new TypeError("settings.put: userMachines is true (the app's users enrol machines of their own) or false");r.user_machines=o.userMachines}if(o.userMachineLimit!==void 0){if(!Number.isInteger(o.userMachineLimit)||o.userMachineLimit<1||o.userMachineLimit>20)throw new TypeError("settings.put: userMachineLimit is how many machines one user holds at most, a whole number from 1 to 20");r.user_machine_limit=o.userMachineLimit}try{return Wt((await t.putSettings({body:r})).data)}catch(n){throw o.openSecretsForAppUsers!==void 0&&n instanceof I&&n.code==="person_required"?new I({op:n.op,status:n.status,code:n.code,requestId:n.requestId,body:n.body,cause:n,message:`settings.put: whether an app's users' work has the project's open secrets is a person's to say \u2014 an owner or an admin of the organization signed in to Studio (AI \u203A Settings) or to the CLI as themselves (palbase ai:settings:set --open-secrets-for-app-users), never a key or a token, the project's secret key included (${n.op}: ${n.status} ${n.code})`}):o.allowClientHandoff!==void 0&&n instanceof I&&n.code==="person_required"?new I({op:n.op,status:n.status,code:n.code,requestId:n.requestId,body:n.body,cause:n,message:`settings.put: enabling client-triggered session handoffs is a person's to say \u2014 an owner or an admin of the organization signed in to Studio (AI \u203A Settings) or to the CLI as themselves, never a key or a token (${n.op}: ${n.status} ${n.code})`}):n}}},environments:{async list(o={}){return(await t.listEnvironments({signal:o.signal})).data.environments},async create(o,r={}){return ye(o?.name,"environments.create"),(await t.createEnvironment({body:o,signal:r.signal})).data},async get(o,r={}){return(await t.getEnvironment({path:{name:ye(o,"environments.get")},signal:r.signal})).data},async put(o,r,n={}){return(await t.putEnvironment({path:{name:ye(o,"environments.put")},body:r,signal:n.signal})).data},async delete(o,r={}){await t.deleteEnvironment({path:{name:ye(o,"environments.delete")},signal:r.signal})}}}}var L=class extends Error{runId;stepKey;waitId;constructor(t,i,s){super(`workflow run ${t} parked on step ${i} (wait ${s})`),this.name="WorkflowParkedError",this.runId=t,this.stepKey=i,this.waitId=s}};function Vt(e){let t={async create(n,l={}){return(await w(e.createTrigger({body:n,signal:l.signal}))).data},async list(n={}){return(await w(e.listTriggers({signal:n.signal}))).data.triggers??[]},async get(n,l={}){return(await w(e.getTrigger({path:{trigger_id:n},signal:l.signal}))).data},async update(n,l,c={}){return(await w(e.updateTrigger({path:{trigger_id:n},body:l,signal:c.signal}))).data},async delete(n,l={}){await w(e.deleteTrigger({path:{trigger_id:n},signal:l.signal}))},async test(n,l={},c={}){return(await w(e.testTrigger({path:{trigger_id:n},body:l,signal:c.signal}))).data}},i={async list(n={}){return(await w(e.listWaits({query:{status:n.status,owner_id:n.ownerId},signal:n.signal}))).data.waits??[]},async get(n,l={}){return(await w(e.getWait({path:{wait_id:n},signal:l.signal}))).data},async signal(n,l={},c={}){return(await w(e.signalWait({path:{wait_id:n},body:{payload:l},signal:c.signal}))).data},async cancel(n,l={}){return(await w(e.cancelWait({path:{wait_id:n},signal:l.signal}))).data}},s={async create(n,l={}){return(await w(e.createWorkflowRun({body:n,signal:l.signal}))).data},async list(n={}){return(await w(e.listWorkflowRuns({query:{workflow_name:n.workflowName,status:n.status},signal:n.signal}))).data.runs??[]},async get(n,l={}){return(await w(e.getWorkflowRun({path:{run_id:n},signal:l.signal}))).data},async recordStep(n,l,c,f={}){return(await w(e.recordWorkflowStep({path:{run_id:n,step_key:l},body:c,signal:f.signal}))).data},async complete(n,l,c={}){return(await w(e.completeWorkflowRun({path:{run_id:n},body:l,signal:c.signal}))).data},async replay(n,l={}){return(await w(e.replayWorkflowRun({path:{run_id:n},body:{from_step:l.fromStep},signal:l.signal}))).data},async stopTree(n,l={}){return(await w(e.stopRunTree({path:{root_id:n},signal:l.signal}))).data}},a={async put(n,l,c,f={}){return(await w(e.putMemory({path:{namespace:n,key:l},body:c,signal:f.signal}))).data},async get(n,l,c={}){return(await w(e.getMemory({path:{namespace:n,key:l},signal:c.signal}))).data},async delete(n,l,c={}){await w(e.deleteMemory({path:{namespace:n,key:l},signal:c.signal}))},async search(n,l={}){return(await w(e.searchMemory({body:n,signal:l.signal}))).data.results??[]}},d={async members(n,l={}){return(await w(e.listActorGroupMembers({path:{group_id:n},signal:l.signal}))).data.members??[]},async addMember(n,l,c={}){return(await w(e.addActorGroupMember({path:{group_id:n},body:{chat_id:l,role:c.role},signal:c.signal}))).data.members??[]},async broadcast(n,l,c={}){return(await w(e.broadcastActorGroup({path:{group_id:n},body:l,signal:c.signal}))).data}},u={async setUserCredential(n,l,c,f={}){return(await w(e.putMcpUserCredential({path:{name:n,user_id:l},body:c,signal:f.signal}))).data},async deleteUserCredential(n,l,c={}){await w(e.deleteMcpUserCredential({path:{name:n,user_id:l},signal:c.signal}))},async startOAuth(n,l,c={}){return(await w(e.startMcpoAuth({path:{name:n},query:{user_id:l,redirect_uri:c.redirectUri},signal:c.signal}))).data}};function o(n,l){return{name:n,async run(c,f={}){let C=f.runId?await s.get(f.runId,{signal:f.signal}):await s.create({workflow_name:n,root_run_id:f.rootRunId,parent_run_id:f.parentRunId,depth:f.depth,input:c??{},metadata:f.metadata,root_budget_usd:f.rootBudgetUsd,max_depth:f.maxDepth,max_concurrent_children:f.maxConcurrentChildren,max_total_steps:f.maxTotalSteps},{signal:f.signal}),R=C.id,k=new Map;for(let m of C.steps??[])m.step_key&&k.set(m.step_key,m);let M={runId:R,async do(m,$){let _=k.get(m);if(_&&_.status==="completed")return _.output;let A=await $(),q=await s.recordStep(R,m,{kind:"do",status:"completed",output:A},{signal:f.signal});return k.set(m,q),q.output},async parallel(m,$){let _=k.get(m);if(_&&_.status==="completed")return _.output;let A=Object.entries($),q=await Promise.all(A.map(async([Te,ke])=>[Te,await ke()])),be=Object.fromEntries(q),ie=await s.recordStep(R,m,{kind:"parallel",status:"completed",output:be},{signal:f.signal});return k.set(m,ie),ie.output},async sleep(m,$){let _=k.get(m);if(_&&_.status==="completed")return;let A=await s.recordStep(R,m,{kind:"sleep",sleep_seconds:$},{signal:f.signal});if(k.set(m,A),A.status!=="completed")throw new L(R,m,A.wait_id??"")},async waitForEvent(m,$,_={}){let A=k.get(m);if(A&&A.status==="completed")return A.output;let q=await s.recordStep(R,m,{kind:"wait_event",match_topic:$,match_filter:_.filter,timeout_seconds:_.timeoutSeconds},{signal:f.signal});if(k.set(m,q),q.status!=="completed")throw new L(R,m,q.wait_id??"");return q.output},async waitForApproval(m,$={}){let _=k.get(m);if(_&&_.status==="completed")return _.output;let A=await s.recordStep(R,m,{kind:"wait_approval",approval_id:$.approvalId,timeout_seconds:$.timeoutSeconds},{signal:f.signal});if(k.set(m,A),A.status!=="completed")throw new L(R,m,A.wait_id??"");return A.output}};try{let m=await l(c,M);return await s.complete(R,{status:"completed",output:m??{}},{signal:f.signal}),{runId:R,status:"completed",output:m}}catch(m){if(m instanceof L)return{runId:R,status:"waiting",waitId:m.waitId};throw await s.complete(R,{status:"failed",error:m instanceof Error?m.message:String(m)},{signal:f.signal}).catch(()=>{}),m}}}}function r(n,l){let c=l.maxSteps??100,f=o(n,async(C,R)=>{let k={...C},M=l.start;for(let m=0;m<c&&M&&M!=="END";m++){let $=l.nodes[M];if(!$)throw new Error(`graph ${n}: unknown node "${M}"`);let _=await R.do(`${m}:${M}`,()=>$(k,R));k={...k,..._};let A=l.edges[M];if(!A)break;M=typeof A=="function"?A(k):A}return k});return{name:n,async run(C,R){let k=await f.run(C,R);return{runId:k.runId,status:k.status,state:k.output,waitId:k.waitId}}}}return{triggers:t,waits:i,workflows:s,memory:a,groups:d,mcpAuth:u,workflow:o,graph:r}}function Bt(e){return{templates:{async list(s={}){return(await e.listTemplates({signal:s.signal})).data.templates},async get(s,a={}){return(await e.getTemplate({path:{name:s},signal:a.signal})).data},async save(s,a,d={}){return(await e.putTemplate({path:{name:s},body:a,signal:d.signal})).data},async publish(s,a={}){return(await e.publishTemplate({path:{name:s},body:a.version!==void 0?{version:a.version}:{},signal:a.signal})).data},async rollback(s,a={}){return(await e.rollbackTemplate({path:{name:s},body:a.version!==void 0?{version:a.version}:{},signal:a.signal})).data},async versions(s,a={}){return(await e.listTemplateVersions({path:{name:s},signal:a.signal})).data.versions},async delete(s,a={}){await e.deleteTemplate({path:{name:s},signal:a.signal})}},userQuotas:{async listSpend(s={}){let a=(await e.listUserSpend({query:{user_id:s.userId,template_name:s.templateName,period_kind:s.periodKind,period_key:s.periodKey},signal:s.signal})).data;return{periodKind:a.period_kind,periodKey:a.period_key,items:a.items}},async get(s,a={}){return(await e.getUserQuota({path:{user_id:s},signal:a.signal})).data},async set(s,a,d={}){return(await e.putUserQuota({path:{user_id:s},body:a,signal:d.signal})).data},async delete(s,a={}){await e.deleteUserQuota({path:{user_id:s},signal:a.signal})}}}}var Vn=/^pb_[a-z0-9]+_s/;function Gt(e){let t=globalThis;return t.process?.env?.[e]??t.Deno?.env?.get(e)}function je(){return"ai_"+crypto.randomUUID()}function Ue(e){if(e.prepared)return e;let t=e;return{name:"answer",schema:t,prepared:K(t,"answer")}}var Lt=4,Bn=/^[a-z][a-z0-9-]{1,62}$/,Ft=["image/png","image/jpeg","image/webp","image/gif"],Kt=5<<20,Ht=6<<20;function Xt(e){let t="";for(let i=0;i<e.length;i+=32768)t+=String.fromCharCode(...e.subarray(i,i+32768));return btoa(t)}function Gn(e){return e.length%4!==0||!/^[A-Za-z0-9+/]*={0,2}$/.test(e)?-1:e.length/4*3-(e.endsWith("==")?2:e.endsWith("=")?1:0)}function Ln(e){if(!Array.isArray(e))throw new TypeError("images is a list of { bucket, path } (a file of the project's storage), { url } (an https address) or { mediaType, data } (its bytes)");if(e.length>Lt)throw new TypeError(`a question takes ${Lt} pictures at most (got ${e.length})`);let t=0;return e.map((i,s)=>{let a=i??{};if("bytes"in a||i instanceof Uint8Array)throw new TypeError(`images[${s}]: a picture's bytes are { mediaType, data } \u2014 or, in the project's storage, { bucket, path }`);if("data"in a||"mediaType"in a){if(a.bucket!==void 0||a.path!==void 0||a.url!==void 0)throw new TypeError(`images[${s}] is { bucket, path }, { url } or { mediaType, data }: one of them`);if(typeof a.mediaType!="string"||!Ft.includes(a.mediaType))throw new TypeError(`images[${s}].mediaType is the picture's type: ${Ft.join(", ")}`);let d=a.data instanceof Uint8Array?Xt(a.data):a.data,u=typeof d=="string"?Gn(d):-1;if(u<0)throw new TypeError(`images[${s}].data is the picture's bytes: base64, or a Uint8Array`);if(u===0||u>Kt)throw new TypeError(`images[${s}] is ${u} bytes: a picture given by its bytes is 1 byte to ${Kt>>20} MiB`);if(t+=u,t>Ht)throw new TypeError(`the pictures given by their bytes are ${Ht>>20} MiB at most together: put a larger one in the project's storage and give { bucket, path }`);return{media_type:a.mediaType,data:d}}if(typeof a.url=="string"){if(a.bucket!==void 0||a.path!==void 0)throw new TypeError(`images[${s}] is { bucket, path } or { url }, not both`);let d;try{d=new URL(a.url)}catch{throw new TypeError(`images[${s}].url is not an address: ${JSON.stringify(a.url.slice(0,80))}`)}if(d.protocol!=="https:"||a.url.length>2048)throw new TypeError(`images[${s}].url is an https address of 2048 characters at most`);return{url:a.url}}if(typeof a.bucket!="string"||!Bn.test(a.bucket)||typeof a.path!="string"||a.path==="")throw new TypeError(`images[${s}] is { bucket, path } \u2014 a file of the project's storage \u2014 { url } or { mediaType, data }`);return{bucket:a.bucket,path:a.path}})}var Fn=/^[a-z][a-z0-9_-]{0,63}(@[1-9][0-9]{0,8})?$/;function Yt(e){let t=typeof e=="string"?e:se(e)?.name;if(typeof t!="string"||!Fn.test(t))throw new TypeError(`agent is one of the project's agents by name (support), name@N for its version N (support@3), or a backend's ai.agent (got ${JSON.stringify(typeof e=="string"?e:typeof e)})`);return t}function ae(e,t={},i){if(e.prompt===void 0&&e.messages===void 0)throw new TypeError("ask a model something: prompt, or messages");let s={...t};if(e.agent!==void 0&&(s.agent=Yt(e.agent)),e.prompt!==void 0&&(s.input=e.prompt),e.messages!==void 0&&(s.messages=e.messages),e.instructions!==void 0&&(s.instructions=e.instructions),e.model!==void 0&&(s.model=e.model),e.metadata!==void 0&&(s.metadata=e.metadata),e.images!==void 0&&(s.images=Ln(e.images)),e.tools!==void 0&&(s.tools=e.tools.map((a,d)=>{if(a?.source==="client")throw new TypeError(`tools[${d}]: ${a.name} is a client tool \u2014 an app answers it, in a chat; a one-shot answer has no app to wait for`);if(a?.source==="platform")throw new TypeError(`tools[${d}]: the platform's ${a.name} is a chat's agent's tool \u2014 a one-shot answer is given none`);let u=ne(a,`tools[${d}]`);return u.source==="backend"&&u.machine===void 0&&i!==void 0&&(u.machine=i),u})),e.maxToolCalls!==void 0){if(!e.tools?.length)throw new TypeError("maxToolCalls bounds the calls of the tools given: give tools");s.max_tool_calls=Oe(e.maxToolCalls,"ask")}return s}function Jt(e,t){if(e.output===null||e.output===void 0)throw new T(t,"the answer is text, not a document: the agent has no output (the shape of its one-shot answers) \u2014 give it one, give generate a schema, or ask() it");return e.output}var D=class extends Error{code;response;constructor(t){super(t.error?.message??`the response ended ${t.status}`),this.name="AIResponseError",this.code=t.error?.code??t.status,this.response=t}};function Kn(e){let t=Uint8Array.from(atob(e),a=>a.charCodeAt(0)),i=new DataView(t.buffer,t.byteOffset,t.byteLength),s=new Array(t.byteLength/4);for(let a=0;a<s.length;a++)s[a]=i.getFloat32(a*4,!0);return s}async function zt(e){let t,i;return e instanceof Uint8Array?(t=e,i=Qt(t)):typeof Blob<"u"&&e instanceof Blob?(t=new Uint8Array(await e.arrayBuffer()),i=e.type||Qt(t)):(t=e.bytes,i=e.mediaType),{media_type:i,data:Xt(t)}}function Qt(e){return e[0]===137&&e[1]===80?"image/png":e[0]===255&&e[1]===216?"image/jpeg":e[8]===87&&e[9]===69&&e[10]===66&&e[11]===80?"image/webp":"application/octet-stream"}function Hn(e){let t=e.url??Gt("PALBASE_URL"),i=e.secretKey??Gt("PALBASE_SECRET_KEY");if(typeof t!="string"||t==="")throw new TypeError("url is the project address (https://<ref>.<domain>) \u2014 or set PALBASE_URL");if(typeof i!="string"||!Vn.test(i))throw new TypeError("secretKey is the project secret key (pb_<ref>_s\u2026) \u2014 or set PALBASE_SECRET_KEY; a model call is billed to the project, so it is never made with a publishable key");let s=Ge(De({baseUrl:t,credentials:{secretKey:i},fetch:e.fetch}),e.retry??Be);return Ve.client(s)}function Jn(e){return new Proxy({},{get:(t,i)=>e.ai[i]})}function zn(e={}){if(ze())throw new TypeError("palbase/ai runs on a server: it speaks with the project secret key, which never goes into a browser or a mobile app \u2014 call your backend, and let it ask the model");if(e.machine!==void 0&&!j.test(e.machine))throw new TypeError("machine is the name of one of the project's machines");let t=e.server?Jn(e.server):Hn(e),i=e.resumeFor??12e4;async function s(p,g,y=je()){return w(t.createResponse({headers:{"Idempotency-Key":y},body:p,signal:g}))}async function a(p,g={}){return(await t.getResponse({path:{response_id:p},signal:g.signal})).data}async function d(p,g,y,E,b){let S=0,P=p,N=je(),z=()=>Date.now()+i,Q=z();for(let X=0;;X++)try{if(P||(g===null?P=(await s({...b,stream:!0},E,N)).data:P=(await t.followResponse({path:{response_id:g},query:{offset:S},signal:E})).data),!P.body)throw new Error("the stream has no body");for await(let v of Qe(P.body)){let O=JSON.parse(v.data);switch(v.event){case"response":g===null&&(g=O.id,y.admitted(O));break;case"delta":{let F=O.offset+Fe(O.text);if(F>S){let Se=O.offset>=S?O.text:He(O.text,S-O.offset);y.delta(S,Se),S=F}Q=z();break}case"reset":O.offset<S&&(S=O.offset,y.reset(S));break;case"terminal":return O}}throw new Error("the stream ended before its answer did")}catch(v){if(P=null,E?.aborted||v instanceof I&&v.status>0&&v.status<500&&v.status!==429||g===null&&!(v instanceof I)||Date.now()>Q)throw v;await new Promise(O=>setTimeout(O,Math.min(250*2**Math.min(X,4),4e3)))}}function u(p){if(p.status!=="completed")throw new D(p);return p.text??""}function o(p,g){let y=ae(p,g?{schema:g.prepared.json,schema_name:g.name}:{},e.machine),E=[],b=!1,S,P=null,N=()=>{let h=P;P=null,h?.()},z,Q,X=new Promise((h,x)=>{z=h,Q=x});X.catch(()=>{});let v="",O=d(null,null,{admitted:h=>z(h.id),delta:(h,x)=>{v+=x,E.push(x),N()},reset:h=>{let x=Ke(v,h);v=v.slice(0,x),E.push("\0reset:"+x),N()}},p.signal,y).then(h=>{let x=h.status==="completed"?h.text??"":"";return x.length>v.length&&x.startsWith(v)&&(E.push(x.slice(v.length)),v=x),b=!0,N(),h},h=>{throw b=!0,S=h,Q(h),N(),h});O.catch(()=>{});async function*F(){for(let h=0;;h++){for(;h>=E.length;){if(b){if(S)throw S;return}await new Promise(x=>P=x)}yield E[h]}}async function*Se(){for await(let h of F())h.startsWith("\0reset:")||(yield h)}async function*en(){let h="",x="";for await(let Z of F()){Z.startsWith("\0reset:")?h=h.slice(0,Number(Z.slice(7))):h+=Z;let V=xe(h);if(V===void 0)continue;let B=JSON.stringify(V);B!==x&&(x=B,yield V)}}let Y=O.then(h=>{if(h.status!=="completed")throw new D(h);return h});Y.catch(()=>{});let Ne=g?Y.then(h=>g.prepared.check(h.output)):Promise.reject(new TypeError("object is a schema stream's"));Ne.catch(()=>{});let We=Y.then(h=>h.text??v);return We.catch(()=>{}),{id:X,response:Y,text:We,get textStream(){return Se()},get partialObjectStream(){return en()},object:Ne,toResponse(h={}){let x=new TextEncoder,Z=new ReadableStream({async start(B){try{for await(let ee of F())ee.startsWith("\0reset:")?B.enqueue(x.encode(`event: reset
8
+ data: ${JSON.stringify({offset:Number(ee.slice(7))})}
9
+
10
+ `)):B.enqueue(x.encode(`data: ${JSON.stringify({text:ee})}
11
+
12
+ `));let W=await Y;B.enqueue(x.encode(`event: done
13
+ data: ${JSON.stringify({id:W.id,text:W.text,output:W.output,usage:W.usage})}
14
+
15
+ `))}catch(W){let ee=W instanceof D||W instanceof I?W.code:"stream_failed";B.enqueue(x.encode(`event: error
16
+ data: ${JSON.stringify({code:ee})}
17
+
18
+ `))}finally{B.close()}}}),V=new Headers(h.headers);return V.set("content-type","text/event-stream"),V.set("cache-control","no-store"),V.set("x-accel-buffering","no"),new globalThis.Response(Z,{...h,headers:V})}}}async function r(p,g){return d(null,null,{admitted:()=>{},delta:()=>{},reset:()=>{}},p.signal,ae(p,g,e.machine))}let{chats:n,agents:l,endpoints:c,settings:f,environments:C}=Dt(t),{pools:R,machines:k,env:M}=Ct(t),{triggers:m,waits:$,workflows:_,memory:A,groups:q,mcpAuth:be,workflow:ie,graph:Te}=Vt(t),{templates:ke,userQuotas:Zt}=Bt(t);return{module:t,chats:n,agents:l,endpoints:c,settings:f,environments:C,pools:R,machines:k,env:M,triggers:m,waits:$,workflows:_,memory:A,groups:q,mcpAuth:be,workflow:ie,graph:Te,templates:ke,userQuotas:Zt,tool:St,clientTool:vt,deferred:ft,answer:ht,agent:At,async ask(p,g={}){let y=typeof p=="string"?{...g,prompt:p}:p;return u(await r(y,{}))},async generate(p){if(p.schema===void 0){if(p.agent===void 0)throw new TypeError("generate: a schema \u2014 the answer's shape \u2014 or an agent whose output is");if(p.background){let P=(await s(ae(p,{background:!0},e.machine),p.signal)).data;return{id:P.id,status:P.status}}let b=await r(p,{});if(b.status!=="completed")throw new D(b);return Jt(b,Yt(p.agent))}let g=Ue(p.schema),y={schema:g.prepared.json,schema_name:g.name};if(p.background){let S=(await s(ae(p,{...y,background:!0},e.machine),p.signal)).data;return{id:S.id,status:S.status}}let E=await r(p,y);if(E.status!=="completed")throw new D(E);return g.prepared.check(E.output)},stream(p){return o(p,p.schema?Ue(p.schema):void 0)},async start(p){let g=(await s(ae(p,{background:!0},e.machine),p.signal)).data;return{id:g.id,status:g.status}},schema(p,g){return{name:p,schema:g,prepared:K(g,p)}},response:a,async result(p,g){let y=await a(p);if(y.status!=="completed")throw new D(y);return g===void 0?Jt(y,"the response"):Ue(g).prepared.check(y.output)},async cancel(p){return(await t.cancelResponse({path:{response_id:p}})).data},async embed(p,g={}){let y=Array.isArray(p)?p:[p],E=[];for(let b=0;b<y.length;b+=1024){let S=await w(t.createEmbeddings({body:{input:y.slice(b,b+1024),model:g.model,dimensions:g.dimensions},signal:g.signal}));for(let P of S.data.vectors)E.push(Kn(P))}return Array.isArray(p)?E:E[0]},async image(p){let g={prompt:p.prompt};for(let b of["model","size","quality","background","format","count"])p[b]!==void 0&&(g[b]=p[b]);p.references?.length&&(g.references=await Promise.all(p.references.map(zt))),p.mask&&(g.mask=await zt(p.mask));let y=(await w(t.createImage({headers:{"Idempotency-Key":je()},body:g,signal:p.signal}))).data;for(let b=0;y.status==="running";b++){if(await new Promise(S=>setTimeout(S,Math.min(500+b*250,3e3))),p.signal?.aborted)throw p.signal.reason;y=(await t.getImage({path:{image_id:y.id},signal:p.signal})).data}if(y.status!=="completed")throw new Error(`the image failed: ${y.error?.code??"image_failed"}: ${y.error?.message??""}`);let E=await Promise.all(y.files.map(async b=>{let P=(await t.getImageFile({path:{image_id:y.id,position:b.position},signal:p.signal})).data;return{mediaType:b.media_type,bytes:new Uint8Array(await P.arrayBuffer())}}));return{id:y.id,model:y.model,pictures:E,costNanoUSD:y.usage?.cost_nano_usd??0,save(b,S,P=0){let N=E[P];if(!N)throw new RangeError(`the job made ${E.length} picture(s)`);return b.upload(S,N.bytes,{contentType:N.mediaType})}}},videos:{async create(p,g={}){return(await w(t.createVideo({body:p,signal:g.signal}))).data},async get(p,g={}){return(await t.getVideo({path:{video_id:p},signal:g.signal})).data},async cancel(p,g={}){return(await t.cancelVideo({path:{video_id:p},signal:g.signal})).data}},audio:{async transcribe(p,g={}){return(await w(t.createAudioTranscription({body:p,signal:g.signal}))).data},async speak(p,g={}){let y=(await w(t.createAudioSpeech({body:p,signal:g.signal}))).data;return{mediaType:y.headers.get("content-type")??"audio/mpeg",bytes:new Uint8Array(await y.arrayBuffer())}},async speakStream(p,g={}){return(await w(t.createAudioSpeech({body:p,signal:g.signal}))).data}},async models(){return(await t.listModels({})).data},async usage(p={}){let g=p.metadata===void 0?void 0:JSON.stringify(p.metadata),y=(await t.listUsage({query:{kind:p.kind,limit:p.limit,cursor:p.cursor,metadata:g}})).data;return{usage:y.usage,nextCursor:y.next_cursor}},async spend(p={}){return(await t.getSpend({signal:p.signal})).data},async connectProvider(p,g){return(await t.connectProvider({path:{provider:p},body:{key:g}})).data},async disconnectProvider(p){await t.disconnectProvider({path:{provider:p}})}}}export{xe as a,T as b,K as c,Ee as d,L as e,D as f,zn as g};
@@ -1,4 +1,4 @@
1
- /*! palbase 0.76.0 — Palbase SDK License (see LICENSE) */
2
- import{g as m}from"./YRYPXVAJ.js";import{AsyncLocalStorage as O}from"node:async_hooks";function h(n,e){return new Proxy(e,{get(s,t,i){if(c.getStore()?.services===void 0)return Reflect.get(s,t,i);let o=R(n,t,s),r=o[t];return typeof r=="function"?r.bind(o):r}})}function R(n,e,s){let t=c.getStore()?.services;if(t===void 0)return s;let i=t[n];if(i!==void 0)return i;if(n==="Log"||typeof e=="symbol"||e==="then")return s;throw new Error(`${n}.${String(e)} was read, but this test did not provide ${n}. Pass it: withServices({ ${n}: \u2026 }, () => \u2026)`)}var P=Symbol.for("palbase.backend.requestScope"),c=globalThis[P]??=new O,d,w,E,G={get ai(){if(!d)throw new Error("Palbase.ai is called before the app is served (serve() binds it)");return d.ai}};function H(n){d=n}function F(n){w=n}var T=h("Gateways",{to(n,e){if(!w)throw new Error("Palbase.gateways is reached before the app is served (createApp() binds it)");return w.to(n,e)}}),Z=new Proxy({},{get(n,e){if(e==="gateways")return T;if(e==="ai")return E??=m({server:G});if(!d)throw new Error(`Palbase.${String(e)} is reached before the app is served (serve() binds it)`);return d[e]}}),B=new Proxy({},{get(n,e){let s=c.getStore(),t=s?.database;if(!t)throw new Error(s?.services?`Database.${String(e)} was read, and this test gave no Database: withServices({ Database: fake.raw }, \u2026)`:s?`Database.${String(e)}: this app declares no database \u2014 PalbaseFactory.create(\u2026, { db: { schemas } })`:`Database.${String(e)} is reached outside a request: it is the request's transaction, reached from a handler, a service it calls or an @On`);let i=t[e];return typeof i=="function"?i.bind(t):i}});function l(n,e,s){let t={time:new Date().toISOString(),level:n,msg:e},i=c.getStore();if(i&&(t.request_id=i.requestId),s)for(let[r,a]of Object.entries(s))t[r]=a instanceof Error?{name:a.name,message:a.message,stack:a.stack}:a;let o=k(t);n==="error"||n==="warn"?process.stderr.write(`${o}
1
+ /*! palbase 0.77.0 — Palbase SDK License (see LICENSE) */
2
+ import{g as m}from"./KLK7HZZ7.js";import{AsyncLocalStorage as O}from"node:async_hooks";function h(n,e){return new Proxy(e,{get(s,t,i){if(c.getStore()?.services===void 0)return Reflect.get(s,t,i);let o=R(n,t,s),r=o[t];return typeof r=="function"?r.bind(o):r}})}function R(n,e,s){let t=c.getStore()?.services;if(t===void 0)return s;let i=t[n];if(i!==void 0)return i;if(n==="Log"||typeof e=="symbol"||e==="then")return s;throw new Error(`${n}.${String(e)} was read, but this test did not provide ${n}. Pass it: withServices({ ${n}: \u2026 }, () => \u2026)`)}var P=Symbol.for("palbase.backend.requestScope"),c=globalThis[P]??=new O,d,w,E,G={get ai(){if(!d)throw new Error("Palbase.ai is called before the app is served (serve() binds it)");return d.ai}};function H(n){d=n}function F(n){w=n}var T=h("Gateways",{to(n,e){if(!w)throw new Error("Palbase.gateways is reached before the app is served (createApp() binds it)");return w.to(n,e)}}),Z=new Proxy({},{get(n,e){if(e==="gateways")return T;if(e==="ai")return E??=m({server:G});if(!d)throw new Error(`Palbase.${String(e)} is reached before the app is served (serve() binds it)`);return d[e]}}),B=new Proxy({},{get(n,e){let s=c.getStore(),t=s?.database;if(!t)throw new Error(s?.services?`Database.${String(e)} was read, and this test gave no Database: withServices({ Database: fake.raw }, \u2026)`:s?`Database.${String(e)}: this app declares no database \u2014 PalbaseFactory.create(\u2026, { db: { schemas } })`:`Database.${String(e)} is reached outside a request: it is the request's transaction, reached from a handler, a service it calls or an @On`);let i=t[e];return typeof i=="function"?i.bind(t):i}});function l(n,e,s){let t={time:new Date().toISOString(),level:n,msg:e},i=c.getStore();if(i&&(t.request_id=i.requestId),s)for(let[r,a]of Object.entries(s))t[r]=a instanceof Error?{name:a.name,message:a.message,stack:a.stack}:a;let o=k(t);n==="error"||n==="warn"?process.stderr.write(`${o}
3
3
  `):process.stdout.write(`${o}
4
4
  `)}function k(n){try{return JSON.stringify(n)}catch{let e=new WeakSet;try{return JSON.stringify(n,(s,t)=>{if(typeof t=="bigint")return t.toString();if(typeof t=="object"&&t!==null){if(e.has(t))return"[circular]";e.add(t)}return t})}catch{return JSON.stringify({time:n.time,level:n.level,msg:n.msg,request_id:n.request_id,unwritable:"a field of this line could not be written"})}}}var v=h("Log",{debug:(n,e)=>l("debug",n,e),info:(n,e)=>l("info",n,e),warn:(n,e)=>l("warn",n,e),error:(n,e)=>l("error",n,e)});var L=512,_=8,q=64,D=/^[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$/,S={"i-klingon":"tlh","en-gb-oed":"en-GB-oxendict","sgn-be-fr":"sfb","zh-cmn-hans":"cmn-Hans","zh-yue":"yue","hy-arevela":"hy-arevela"};function $(n){let e=n.indexOf("-");return e>0?n.slice(0,e):n}function j(n){let e=n.split("-"),s=(e[0]??"").toLowerCase();return s==="mo"&&e.length===1?"ro-MD":s==="tl"?(e[0]="fil",e.join("-")):s==="sh"?(e[0]="sr",e.length>1&&/^[A-Za-z]{4}$/.test(e[1]??"")||e.splice(1,0,"Latn"),e.join("-")):n}function I(n){let e=n.trim().replaceAll("_","-");if(e===""||e==="*"||e.length>q)return;let s=e.toLowerCase(),t=Object.hasOwn(S,s)?S[s]:void 0;if(t===void 0){try{t=Intl.getCanonicalLocales(j(e))[0]}catch{return}if(t===void 0)return}let i=$(t);if(!(i===""||i==="und"||i==="mul"))return t}function z(n){let e=n.split("-"),s=e.findIndex((r,a)=>a>0&&r.length===1),t=s>0?e.slice(0,s):e,i=[],o=r=>{i.includes(r)||i.push(r)};for(let r=t.length;r>1||r===t.length;r--)o(t.slice(0,r).join("-"));if(!t.slice(1).some(r=>/^[A-Za-z]{4}$/.test(r)))try{let r=new Intl.Locale(t.join("-")).maximize().script;r&&o(`${t[0]}-${r}`)}catch{}return o(t[0]),i}function Y(n,e){let s=[],t=i=>{i!==""&&!s.includes(i)&&s.push(i)};if(n!==null&&n.length<=L){let i=[];for(let o of n.split(",")){let r=o.trim();if(r==="")continue;let a=1,f=r.indexOf(";");if(f>=0){let A=r.slice(f+1);r=r.slice(0,f).trim();for(let p of A.split(";")){let b=p.indexOf("=");if(b<0||p.slice(0,b).trim().toLowerCase()!=="q")continue;let y=p.slice(b+1).trim(),g=D.test(y)?Number(y):Number.NaN;a=Number.isFinite(g)&&g>=0&&g<=1?g:0}}a>0&&i.push({tag:r,q:a,at:i.length})}i.sort((o,r)=>r.q-o.q||o.at-r.at);for(let{tag:o}of i.slice(0,_)){let r=I(o);if(r!==void 0)for(let a of z(r))t(a)}}return e!==void 0&&e!==""&&t(e),s}function N(n,e,s){let t=n.strings??{},i=Object.hasOwn(t,e)?t[e]:null;for(let o of s){if(o===n.source)break;let r=i!=null&&Object.hasOwn(i,o)?i[o]:void 0;if(typeof r=="string"&&r!=="")return{text:r,locale:o}}return{text:e,locale:n.source}}var C=/\{\{\s*([A-Za-z_][A-Za-z0-9_]*)\s*\}\}/g;function x(n,e){return n.replace(C,(s,t,i,o)=>{if(o[i-1]==="{"||o[i+s.length]==="}")return s;let r=e!==void 0&&Object.hasOwn(e,t)?e[t]:void 0;return r==null?"":String(r)})}var u;function W(n){u=n===void 0?void 0:{root:n,said:!1}}function Q(n,e){let s=c.getStore(),t=s?.strings;if(t===void 0)return u&&!u.said&&s?.services===void 0&&(u.said=!0,v.warn(`[palbase] t(): the app has no palbase/strings (looked in ${u.root}) \u2014 every sentence is said as it is written. \`npx palbase strings\` starts the table; an image takes it with COPY palbase ./palbase`)),x(n,e);let{text:i,locale:o}=N(t,n,s?.locales??[t.source]),r=s?.usedLocales;return r!==void 0&&!r.includes(o)&&r.push(o),x(i,e)}export{h as a,R as b,c,H as d,F as e,Z as f,B as g,v as h,Y as i,W as j,Q as k};
@@ -1,2 +1,2 @@
1
- /*! palbase 0.76.0 — Palbase SDK License (see LICENSE) */
1
+ /*! palbase 0.77.0 — Palbase SDK License (see LICENSE) */
2
2
  var s=class extends Error{code;constructor(t,e){super(e),this.name="FieldError",this.code=t}},f="pbe1.",g="pbl1.",k=6e4,p="[A-Za-z_][A-Za-z0-9_$]{0,62}",w=new RegExp(`^${p}\\.${p}(\\.${p})?$`);function v(o){return w.test(o)}var h=class{crypto;keys=new Map;lookupKey;timer;opts;now;constructor(t){this.opts=t,this.now=t.now??Date.now}get loaded(){return this.lookupKey!==void 0}async load(t){this.crypto??=await import("node:crypto"),this.take(await this.opts.fetch(t)),this.timer===void 0&&(this.timer=setInterval(()=>{this.opts.fetch().then(e=>this.take(e),()=>{})},k),this.timer.unref?.())}close(){clearInterval(this.timer),this.timer=void 0}take(t){let e=new Map;for(let r of t.keys)e.set(r.id,{id:r.id,key:Buffer.from(r.key,"base64url"),activatesAt:Date.parse(r.activates_at)});this.keys=e,this.lookupKey=Buffer.from(t.lookup,"base64url")}ready(){if(this.crypto===void 0||this.lookupKey===void 0)throw new s("not_loaded","the project's field keys are not loaded: await palbase.fields.load() at startup");return this.crypto}currentKey(){this.ready();let t;for(let e of this.keys.values())e.activatesAt<=this.now()&&(t===void 0||e.activatesAt>=t.activatesAt)&&(t=e);if(t===void 0)throw new s("unknown_key","the project has no field key in force");return t.id}encrypt(t,e){let r=this.ready();l(t);let n=this.currentKey(),i=r.randomBytes(12);return b(r,this.keys.get(n).key,i,n,t,e)}decrypt(t,e){let r=this.ready();if(l(t),!e.startsWith(f))throw new s("not_encrypted",`${t} holds a value that is not encrypted`);let n=e.slice(f.length),i=n.indexOf("."),a=i<0?n:n.slice(0,i),u=this.keys.get(a);if(u===void 0)throw new s("unknown_key",`${t} was sealed with field key ${a}, which this project does not hold`);let c=Buffer.from(n.slice(i+1),"base64url");if(i<0||c.length<28||c.toString("base64url")!==n.slice(i+1))throw new s("unopenable",`${t} holds a value that does not open here`);try{let d=r.createDecipheriv("aes-256-gcm",u.key,c.subarray(0,12));return d.setAAD(y(t)),d.setAuthTag(c.subarray(c.length-16)),Buffer.concat([d.update(c.subarray(12,c.length-16)),d.final()]).toString("utf8")}catch{throw new s("unopenable",`${t} holds a value that does not open here: tampered, or another column's`)}}isEncrypted(t){return t.startsWith(f)}lookup(t,e){let r=this.ready();return l(t),m(r,this.lookupKey,t,e)}};function l(o){if(!v(o))throw new TypeError(`a field's address is table.column, or schema.table.column, not ${JSON.stringify(o)}`)}function y(o){return Buffer.from(`pbe1\0${o}`,"utf8")}function b(o,t,e,r,n,i){let a=o.createCipheriv("aes-256-gcm",t,e);a.setAAD(y(n));let u=Buffer.concat([e,a.update(i,"utf8"),a.final(),a.getAuthTag()]);return`${f}${r}.${u.toString("base64url")}`}function m(o,t,e,r){let n=o.createHmac("sha256",t);return n.update(`pbl1\0${e}\0`,"utf8"),n.update(r,"utf8"),`${g}${n.digest("base64url")}`}export{s as a,h as b};