palbase 0.11.1 → 0.13.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/ai/index.js +2 -2
- package/dist/backend/engine.js +2 -2
- package/dist/backend/env.js +1 -1
- package/dist/backend/index.js +11 -11
- package/dist/backend/stack.js +1 -1
- package/dist/backend/test.js +2 -2
- package/dist/chunks/{KNPQNBC2.js → 2J3RT5GV.js} +2 -2
- package/dist/chunks/2QE7TIVQ.js +6 -0
- package/dist/chunks/{BUAGC2PT.js → 3CFHP6H7.js} +1 -1
- package/dist/chunks/5MMZNWFL.js +21 -0
- package/dist/chunks/5U3YIYBP.js +13 -0
- package/dist/chunks/{43VM626B.js → 6SINT3YD.js} +1 -1
- package/dist/chunks/{EWBRYA7P.js → 7MBBS4BC.js} +2 -2
- package/dist/chunks/{26UTOC32.js → AZ3Z3ME2.js} +1 -1
- package/dist/chunks/BJL7ZBG7.js +2 -0
- package/dist/chunks/{LYEEW4UG.js → C2WFUOF7.js} +2 -2
- package/dist/chunks/{NGE3D2K4.js → C3UPTONG.js} +7 -7
- package/dist/chunks/CMDUL3VE.js +2 -0
- package/dist/chunks/{R3EIGCWV.js → EQ4HNSWU.js} +2 -2
- package/dist/chunks/{FVLHT7UQ.js → EWXQUZSU.js} +2 -2
- package/dist/chunks/{3VY3ZZCI.js → GXLUNOFZ.js} +1 -1
- package/dist/chunks/L4NDDBYW.js +2 -0
- package/dist/chunks/{7WIMZTYB.js → MERWSLS2.js} +2 -2
- package/dist/chunks/MYHRHZYN.js +2 -0
- package/dist/chunks/{S2KRJF6J.js → QRWMVBF4.js} +2 -2
- package/dist/chunks/{EEWP43KI.js → R26ROMEG.js} +1 -1
- package/dist/chunks/{ZZG7ICDG.js → SGCYJGSM.js} +2 -2
- package/dist/chunks/{3453XVQL.js → SGDOCWYB.js} +2 -2
- package/dist/chunks/{KW6ODEYS.js → W33A3OUV.js} +1 -1
- package/dist/cli.js +132 -131
- package/dist/refuse/ai.js +1 -1
- package/dist/refuse/backend.js +1 -1
- package/dist/refuse/server.js +1 -1
- package/dist/server/index.js +2 -2
- package/dist/server/testing.js +2 -2
- package/dist/web/index.js +2 -2
- package/dist/web/message.js +2 -2
- package/dist/web/palbe.js +2 -2
- package/dist/web/paywall.js +2 -2
- package/dist/web/push-sw.js +1 -1
- package/dist/web/ssr.js +2 -2
- package/dist/web/vite.js +2 -2
- package/package.json +2 -2
- package/types/ai/src/chats.d.ts +7 -0
- package/types/backend/src/index.d.ts +1 -0
- package/types/backend/src/transit.d.ts +39 -0
- package/types/internal/src/modules/ai.d.ts +8 -0
- package/types/internal/src/modules/purchases.d.ts +95 -11
- package/types/internal/src/modules/secrets.d.ts +148 -1
- package/types/internal/src/transit-marks.d.ts +51 -0
- package/types/internal/src/transit.d.ts +108 -0
- package/types/server/src/index.d.ts +1 -0
- package/types/server/src/server.d.ts +8 -0
- package/types/server/src/transit.d.ts +91 -0
- package/types/web/src/backend-transit.d.ts +23 -0
- package/types/web/src/backends.d.ts +8 -1
- package/types/web/src/index.d.ts +1 -0
- package/dist/chunks/AFFE3Q5O.js +0 -6
- package/dist/chunks/BUYFMLTF.js +0 -2
- package/dist/chunks/Q3S76MYJ.js +0 -2
- package/dist/chunks/V2FEPVVD.js +0 -13
- package/dist/chunks/WLAO2QSR.js +0 -20
|
@@ -1,18 +1,18 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
2
|
-
import{a as L,c as me,d as he,e as ye}from"./
|
|
1
|
+
/*! palbase 0.13.1 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{a as L,c as me,d as he,e as ye}from"./C2WFUOF7.js";import{a as we}from"./R26ROMEG.js";import{a as ue}from"./MERWSLS2.js";import{a as pe,b as ge,c as fe}from"./EQ4HNSWU.js";import{b as I,d as le}from"./2J3RT5GV.js";async function*be(e,t={}){let o=e.getReader(),a=new TextDecoder,i="",u="",l=[],m,s=()=>{o.cancel().catch(()=>{})};t.signal?.addEventListener("abort",s,{once:!0});try{if(t.signal?.aborted)return;for(;;){let{done:n,value:r}=await o.read();if(n||t.signal?.aborted)return;t.onBytes?.(),i+=a.decode(r,{stream:!0});for(let d=i.indexOf(`
|
|
3
3
|
`);d>=0;d=i.indexOf(`
|
|
4
4
|
`)){let p=i.slice(0,i[d-1]==="\r"?d-1:d);i=i.slice(d+1),p===""?(u!==""&&(yield m===void 0?{event:u,data:l.join(`
|
|
5
5
|
`)}:{event:u,data:l.join(`
|
|
6
6
|
`),id:m}),u="",l=[],m=void 0):p.startsWith("event:")?u=Y(p,6):p.startsWith("data:")?l.push(Y(p,5)):p.startsWith("id:")&&(m=Y(p,3))}}}finally{t.signal?.removeEventListener("abort",s);try{await o.cancel()}catch{}}}function Y(e,t){let o=e.slice(t);return o.startsWith(" ")?o.slice(1):o}var rt=/\s/;function q(e,t){for(;t<e.length&&rt.test(e[t]);)t++;return t}function ke(e,t){let o="";for(let a=t+1;a<e.length;a++){let i=e[a];if(i==='"')return{value:o,complete:!0,empty:!1,at:a+1};if(i!=="\\"){o+=i;continue}let u=e[a+1];if(u===void 0)break;if(u==="u"){let l=e.slice(a+2,a+6);if(l.length<4)break;o+=String.fromCharCode(Number.parseInt(l,16)),a+=5;continue}o+={n:`
|
|
7
|
-
`,t:" ",r:"\r",b:"\b",f:"\f"}[u]??u,a++}return{value:o,complete:!1,empty:!1,at:e.length}}function Q(e,t){t=q(e,t);let o=e[t];if(o===void 0)return{value:void 0,complete:!1,empty:!0,at:t};if(o==='"')return ke(e,t);if(o==="{")return at(e,t);if(o==="[")return st(e,t);let a=t;for(;a<e.length&&/[-+0-9.A-Za-z]/.test(e[a]);)a++;if(a===e.length)return{value:void 0,complete:!1,empty:!0,at:a};try{return{value:JSON.parse(e.slice(t,a)),complete:!0,empty:!1,at:a}}catch{return{value:void 0,complete:!1,empty:!0,at:e.length}}}function at(e,t){let o={},a=t+1;for(;;){if(a=q(e,a),e[a]==="}")return{value:o,complete:!0,empty:!1,at:a+1};if(e[a]===","){a++;continue}if(e[a]!=='"')return{value:o,complete:!1,empty:!1,at:e.length};let i=ke(e,a);if(!i.complete)return{value:o,complete:!1,empty:!1,at:e.length};if(a=q(e,i.at),e[a]!==":")return{value:o,complete:!1,empty:!1,at:e.length};let u=Q(e,a+1);if(u.empty||Object.defineProperty(o,i.value,{value:u.value,enumerable:!0,writable:!0,configurable:!0}),!u.complete)return{value:o,complete:!1,empty:!1,at:e.length};a=u.at}}function st(e,t){let o=[],a=t+1;for(;;){if(a=q(e,a),e[a]==="]")return{value:o,complete:!0,empty:!1,at:a+1};if(e[a]===","){a++;continue}if(a>=e.length)return{value:o,complete:!1,empty:!1,at:a};let i=Q(e,a);if(i.empty||o.push(i.value),!i.complete)return{value:o,complete:!1,empty:!1,at:e.length};a=i.at}}function ee(e){let t=Q(e,0);return t.empty?void 0:t.value}var b=class extends Error{path;constructor(t,o){super(`${t}: ${o}`),this.name="AISchemaError",this.path=t}},ot=new Set(["type","properties","required","additionalProperties","items","enum","description","title","minimum","maximum","minLength","maxLength","minItems","maxItems"]),it=new Set(["format","pattern","exclusiveMinimum","exclusiveMaximum","multipleOf","uniqueItems","contentEncoding","contentMediaType","default","examples","readOnly","writeOnly","deprecated","$comment"]),dt=new Set(["object","array","string","integer","number","boolean"]),Te=12,Se=512,ct=/^[A-Za-z][A-Za-z0-9_-]{0,63}$/;function z(e,t="answer"){if(!ct.test(t))throw new b(t||"(name)","a schema name starts with a letter and holds letters, digits, _ and -, 64 at most");let o=e?.["~standard"];if(!o||o.version!==1||typeof o.validate!="function")throw new b(t,"not a Standard Schema: pass a zod (4.2+), valibot or arktype schema");if(!o.jsonSchema||typeof o.jsonSchema.output!="function")throw new b(t,`${o.vendor}'s schema cannot say itself as JSON Schema; use a version that implements Standard JSON Schema`);let a;try{a=o.jsonSchema.output({target:"draft-2020-12",libraryOptions:{unrepresentable:"throw"}})}catch(l){throw new b(t,`the schema has a part JSON Schema cannot say (${l.message}): a function, a transform, a date \u2014 give the model a string and convert it after`)}if(a.type!=="object")throw new b(t,"the answer is an object: wrap the value in z.object({ \u2026 })");let u=te(a,t,0,{properties:0});return{name:t,json:u,async check(l){let m=await o.validate(l);if(m.issues){let s=m.issues[0],n=(s?.path??[]).map(r=>String(typeof r=="object"?r.key:r)).join(".");throw new b(n?`${t}.${n}`:t,`the model's answer does not match the schema: ${s?.message??"invalid"}`)}return m.value}}}function te(e,t,o,a){if(o>Te)throw new b(t,`nests deeper than ${Te} levels, the most the provider takes`);for(let l of["anyOf","oneOf","allOf"])if(l in e)throw new b(t,lt(e[l])??"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 l of["$ref","$defs","definitions","$dynamicRef"])if(l in e)throw new b(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 b(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 l of["prefixItems","patternProperties","propertyNames","not","if","then","else","dependentRequired","dependentSchemas","const","minProperties","maxProperties","contains","unevaluatedProperties","unevaluatedItems"])if(l in e)throw new b(t,`uses ${l}, which the provider cannot hold a model to`);if(Array.isArray(e.type))throw new b(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 i=e.type;if(typeof i!="string"&&!("enum"in e))throw new b(t,"has no type: the provider holds a model only to a typed value");if(typeof i=="string"&&!dt.has(i))throw new b(t,`is of type ${i}, which the provider does not take`);let u={};for(let[l,m]of Object.entries(e))if(!(l==="$schema"||l==="id"||l==="$id")&&!it.has(l)){if(!ot.has(l))throw new b(t,`uses ${l}, which the provider cannot hold a model to`);u[l]=m}if("enum"in e&&typeof i!="string"){let l=e.enum,m=new Set(l.map(s=>s===null?"null":typeof s));if(m.size!==1||m.has("null"))throw new b(t,"an enum of values of several types (or with null): one type per field");u.type=m.has("string")?"string":m.has("boolean")?"boolean":"number"}if(i==="object"){let l=e.properties??{},m=Object.keys(l);if(m.length===0)throw new b(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 b(t,"accepts fields it does not name (passthrough, catchall, record): the provider holds a model only to the fields named");if(a.properties+=m.length,a.properties>Se)throw new b(t,`the schema has more than ${Se} fields in all, the most the provider takes`);let s=new Set(e.required??[]),n={};for(let r of m){if(!s.has(r))throw new b(`${t}.${r}`,'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[r]=te(l[r],`${t}.${r}`,o+1,a)}u.properties=n,u.required=m,u.additionalProperties=!1}if(i==="array"){let l=e.items;if(!l||typeof l!="object"||Array.isArray(l))throw new b(t,"is a list with no one shape for its items: the provider takes a list of one shape");u.items=te(l,`${t}[]`,o+1,a)}return u}function lt(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 ut=new Set(["image/png","image/jpeg","image/webp","image/gif"]);function W(e){return Array.isArray(e)&&e.length>0&&e.every(xe)?e.map(Ae):xe(e)?[Ae(e)]:e==null?[{type:"text",text:""}]:typeof e=="string"?[{type:"text",text:e}]:[{type:"text",text:JSON.stringify(e)??String(e)}]}function xe(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 Ae(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(!ut.has(t))throw new TypeError(`a tool's picture is image/png, image/jpeg, image/webp or image/gif (got ${JSON.stringify(t)})`);let o="bytes"in e?e.bytes:e.data;return{type:"image",media_type:t,data:typeof o=="string"?o:pt(o)}}function pt(e){let t="";for(let o=0;o<e.length;o+=32768)t+=String.fromCharCode(...e.subarray(o,o+32768));return btoa(t)}var Ie=Symbol.for("palbase.ai.deferred"),ve=60,_e=86400;function $e(e={}){let t=e?.expiresInSeconds;if(t!==void 0&&(!Number.isInteger(t)||t<ve||t>_e))throw new TypeError(`ai.deferred: expiresInSeconds is how long the call waits for its answer, ${ve} to ${_e} seconds (got ${String(t)})`);return Object.freeze({[Ie]:!0,...t!==void 0?{expiresInSeconds:t}:{}})}function gt(e){return typeof e=="object"&&e!==null&&e[Ie]===!0}var ft=Symbol.for("palbase.ai.declared"),mt=Symbol.for("palbase.ai.tool_error"),ne=class extends Error{constructor(t){super(t),this.name="ToolError",Object.defineProperty(this,mt,{value:!0})}};function G(){let e=globalThis,t=e[ft]??={tools:new Map,agents:new Map,repos:new Map,twice:new Set};return t.repos??=new Map,t}function re(e,t,o,a){let i=e.get(o);i===void 0?e.set(o,a):i!==a&&G().twice.add(`${t}:${o}`)}var Me=/^[A-Za-z][A-Za-z0-9_-]{0,63}$/,_=/^[a-z][a-z0-9_-]{0,63}$/;function Oe(e,t){if(e===void 0)return{type:"object",properties:{}};let o=e?.["~standard"];if(!o||o.version!==1||typeof o.validate!="function")throw new TypeError(`${t}: input is a Standard Schema \u2014 a zod (4.2+), valibot or arktype object schema`);if(!o.jsonSchema||typeof o.jsonSchema.output!="function")throw new TypeError(`${t}: ${o.vendor}'s schema cannot say itself as JSON Schema; use a version that implements Standard JSON Schema`);let a;try{a=o.jsonSchema.output({target:"draft-2020-12",libraryOptions:{unrepresentable:"throw"}})}catch(m){throw new TypeError(`${t}: the input has a part JSON Schema cannot say (${m.message}) \u2014 a function, a transform, a date: take a string and convert it in run`)}if(a.type!=="object")throw new TypeError(`${t}: a tool takes an object \u2014 wrap the input in z.object({ \u2026 })`);let i=JSON.stringify(a);if(/"\$(ref|defs|dynamicRef)"/.test(i))throw new TypeError(`${t}: the input refers to another schema (a recursive or shared type) \u2014 write the shape out`);let{$schema:u,...l}=a;return l}function je(e){let t=`ai.tool(${JSON.stringify(e?.name??null)})`;if(typeof e?.name!="string"||!Me.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&&!_.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 o=Oe(e.input,t),a=e.input["~standard"],i=e.run,u={source:"backend",name:e.name,description:e.description,input:e.input,parameters:o,approval:e.approval===!0,...e.machine!==void 0?{machine:e.machine}:{},async call(l,m){let s=await a.validate(l);if(s.issues){let r=s.issues[0],d=(r?.path??[]).map(p=>String(typeof p=="object"?p.key:p)).join(".");return{output:[{type:"text",text:`the input does not match ${e.name}'s schema${d?` at ${d}`:""}: ${r?.message??"invalid"}`}],is_error:!0}}let n=await i(s.value,m);return gt(n)?m.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,...n.expiresInSeconds!==void 0?{expires_in_seconds:n.expiresInSeconds}:{}}:{output:W(n),is_error:!1}}};return Object.freeze(u),re(G().tools,"tool",u.name,u),u}function Be(e){let t=`ai.clientTool(${JSON.stringify(e?.name??null)})`;if(typeof e?.name!="string"||!Me.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`);return Object.freeze({source:"client",name:e.name,description:e.description,parameters:Oe(e.input,t),approval:e.approval===!0})}var ht=/^[A-Za-z0-9_.-]{1,100}\/[A-Za-z0-9_.-]{1,100}$/;function De(e){let t=e??{};if(typeof t.name!="string"||!_.test(t.name))throw new TypeError("ai.repo: name is lowercase letters, digits, _ and -, starting with a letter, at most 64");if(typeof t.repository!="string"||!ht.test(t.repository))throw new TypeError(`ai.repo(${JSON.stringify(t.name)}): repository is a GitHub repository, owner/name`);if(typeof t.token!="function")throw new TypeError(`ai.repo(${JSON.stringify(t.name)}): token is the function that gives a token for one clone or push`);if(t.machine!==void 0&&!_.test(t.machine))throw new TypeError(`ai.repo(${JSON.stringify(t.name)}): machine is the project's machine that gives its tokens`);let o=t.token,a={kind:"repo",name:t.name,repository:t.repository,defaultBranch:t.defaultBranch??"main",...t.machine!==void 0?{machine:t.machine}:{},async token(i){return await o(i)}};return re(G().repos,"repo",t.name,a),a}function Ne(e){if(typeof e!="function")throw new TypeError("ai.repoTokens(give): give is the function that gives a token for one clone or push of a repository put by name");let t=G();t.repoTokens===void 0?t.repoTokens=e:t.repoTokens!==e&&t.twice.add("repoTokens")}function Ue(e,t,o={}){let a=`ai.agent(${JSON.stringify(e??null)})`;if(typeof e!="string"||!_.test(e))throw new TypeError(`${a}: name is lowercase letters, digits, _ and -, starting with a letter, at most 64`);if(typeof t!="function")throw new TypeError(`${a}: the agent is a function of the turn's context that returns its definition`);if(o.machine!==void 0&&!_.test(o.machine))throw new TypeError(`${a}: machine is the name of one of the project's machines`);let i={kind:"agent",name:e,...o.machine!==void 0?{machine:o.machine}:{},async resolve(u){let l=await t(u),m=V(l,`${a} for chat ${u.chatId}`);if(m.backend!==void 0)throw new TypeError(`${a}: a backend's agent is its definition \u2014 it names no other backend`);return{definition:m,tools:yt(l)}}};return Object.freeze(i),re(G().agents,"agent",e,i),i}function F(e){return typeof e=="object"&&e!==null&&e.kind==="agent"?e:void 0}function yt(e){return[...e.tools??[],...(e.subagents??[]).flatMap(o=>o.tools??[])].filter(o=>o.source==="backend")}var Re=["web.search","web.fetch","workspace.fetch_archive"];function J(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 o=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,...o,...e.machine!==void 0?{machine:e.machine}:{}};case"client":return{source:"client",name:e.name,description:e.description,parameters:e.parameters,...o};case"https":if(typeof e.name!="string"||!_.test(e.name))throw new TypeError(`${t}: { source: 'https', name } names an endpoint the project put`);return{source:"https",name:e.name,...o};case"mcp":if(typeof e.name!="string"||!_.test(e.name))throw new TypeError(`${t}: { source: 'mcp', name } names an MCP server the project put`);return{source:"mcp",name:e.name,...o,...e.only!==void 0?{only:[...e.only]}:{}};case"platform":{let a=Object.keys(e).filter(i=>i!=="source"&&i!=="name");if(typeof e.name!="string"||!Re.includes(e.name))throw new TypeError(`${t}: { source: 'platform', name } names one of the platform's tools: ${Re.join(", ")}`);if(a.length>0)throw new TypeError(`${t}: the platform's ${e.name} is given by its name alone (not ${a.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 Ce=1e4,Ee=["none","minimal","low","medium","high","xhigh","max"],wt=1e8,bt=/^[A-Za-z]{2,8}(-[A-Za-z0-9]{1,8})*$/;function ae(e,t){if(!Number.isInteger(e)||e<1||e>Ce)throw new TypeError(`${t}: maxToolCalls is a whole number, 1 to ${Ce} (got ${String(e)})`);return e}function Pe(e,t){let o={};if(e.effort!==void 0){if(typeof e.effort!="string"||!Ee.includes(e.effort))throw new TypeError(`${t}: effort is one of ${Ee.join(", ")} \u2014 which a model takes is its catalogue entry's (ai.models())`);o.effort=e.effort}if(e.contextWindow!==void 0){if(!Number.isInteger(e.contextWindow)||e.contextWindow<1||e.contextWindow>wt)throw new TypeError(`${t}: contextWindow is a number of tokens (got ${String(e.contextWindow)})`);o.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`);o.thinking=e.thinking}return o}function V(e,t){if(typeof e!="object"||e===null)throw new TypeError(`${t}: a definition is { instructions, model, tools, subagents, maxToolCalls, effort, contextWindow, thinking, language }`);let o={};if(e.instructions!==void 0&&(o.instructions=e.instructions),e.model!==void 0&&(o.model=e.model),e.maxToolCalls!==void 0&&(o.max_tool_calls=ae(e.maxToolCalls,t)),Object.assign(o,Pe(e,t)),e.language!==void 0){if(typeof e.language!="string"||e.language.length>35||!bt.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)`);o.language=e.language}if(e.tools!==void 0&&(o.tools=e.tools.map(a=>J(a,t))),e.subagents!==void 0){for(let a of e.subagents){let i=(a?.tools??[]).find(u=>u?.source==="platform");if(i)throw new TypeError(`${t} subagent ${a.name}: the platform's ${i.name} is the agent's tool \u2014 its subagents work with the agent's`)}o.subagents=e.subagents.map(a=>({name:a.name,description:a.description,...a.instructions!==void 0?{instructions:a.instructions}:{},...a.model!==void 0?{model:a.model}:{},...a.required!==void 0?{required:a.required}:{},...Pe(a,`${t} subagent ${a.name}`),...a.tools!==void 0?{tools:a.tools.map(i=>J(i,`${t} subagent ${a.name}`))}:{}}))}return o}function Ge(e,t){let o={approve:e};return t.reason!==void 0&&(o.reason=t.reason),t.as!==void 0&&(o.as=t.as),o}var kt=/^[a-z][a-z0-9-]{1,62}$/,Le=4,qe=8;function Tt(e){let t={},o=(a,i)=>{if(typeof a?.bucket!="string"||!kt.test(a.bucket))throw new TypeError(`chats.send: ${i}'s bucket is one of the project's buckets, by its name`);if(typeof a.path!="string"||a.path===""||a.path.length>1024)throw new TypeError(`chats.send: ${i}'s path is its path in the bucket (1024 characters at most)`);return{bucket:a.bucket,path:a.path}};if(e.images!==void 0){if(!Array.isArray(e.images)||e.images.length>Le)throw new TypeError(`chats.send: images are ${Le} at most \u2014 as many as the model is shown at once`);t.images=e.images.map((a,i)=>o(a,`images[${i}]`))}if(e.files!==void 0){if(!Array.isArray(e.files)||e.files.length>qe)throw new TypeError(`chats.send: files are ${qe} at most`);t.files=e.files.map((a,i)=>{let u=o(a,`files[${i}]`);if(a.filename!==void 0){if(typeof a.filename!="string"||a.filename===""||a.filename.length>255)throw new TypeError(`chats.send: files[${i}].filename is its name in the workspace (255 characters at most)`);u.filename=a.filename}if(a.contentType!==void 0){if(typeof a.contentType!="string"||a.contentType===""||a.contentType.length>128)throw new TypeError(`chats.send: files[${i}].contentType is a media type (application/pdf)`);u.content_type=a.contentType}return u})}return t}function K(e){return{id:e.id,chatId:e.chat_id,userId:e.user_id,delegation:e.delegation,status:e.status,seconds:e.seconds,startedAt:e.started_at,closedAt:e.closed_at,closeReason:e.close_reason??""}}var St=["speak","tell","know","instruct"];function ze(){return"cm_"+crypto.randomUUID()}async function X(e,t,o=4){for(let a=1;;a++)try{return await e()}catch(i){if(a>=o||!(i instanceof I)||i.status===429||t?.aborted)throw i;let u=fe(i,a,30);if(u===void 0)throw i;await new Promise((l,m)=>{let s=setTimeout(l,u*1e3);t?.addEventListener("abort",()=>(clearTimeout(s),m(t.reason)),{once:!0})})}}function se(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 We=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}:{}}),xt=/^[A-Za-z0-9-]{1,64}$/,Je=16;function At(e){if(!Array.isArray(e)||e.length>Je)throw new TypeError(`chats.create: workspace.trailers are ${Je} at most, each { key, value }`);return e.map((t,o)=>{if(typeof t?.key!="string"||!xt.test(t.key))throw new TypeError(`chats.create: workspace.trailers[${o}].key is a git trailer's token: letters, digits and -, at most 64 (PalCore-Task, Co-authored-by)`);if(typeof t.value!="string"||t.value===""||/[\r\n]/.test(t.value)||new TextEncoder().encode(t.value).byteLength>512)throw new TypeError(`chats.create: workspace.trailers[${o}].value is one line of 512 bytes at most`);return{key:t.key,value:t.value}})}function vt(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 Fe(e){return{clients:e.clients,userMessagesPerMinute:e.user_messages_per_minute,historyLimitBytes:e.history_limit_bytes,historyBytes:e.history_bytes}}function _t(e){return new Proxy(e,{get(t,o){let a=t[o];return typeof a=="function"?(...i)=>L(a.apply(t,i)):a}})}function Ve(e){let t=_t(e),o={async create(s){let n=typeof s.agent=="string"||s.agent===void 0?s.agent:F(s.agent)?.name;if(s.agent!==void 0&&n===void 0)throw new TypeError("chats.create: agent is a named agent of the project, or a backend's ai.agent");if(n===void 0&&s.definition===void 0)throw new TypeError("chats.create: an agent (a named agent of the project) or a definition of the chat's own");let r={agent:n??"assistant"};return s.definition!==void 0&&(r.definition=V(s.definition,"chats.create")),s.title!==void 0&&(r.title=s.title),s.metadata!==void 0&&(r.metadata=s.metadata),s.members!==void 0&&(r.members=s.members.map(We)),s.workspace!==void 0&&(r.workspace={repos:s.workspace.repos.map(d=>({repo:typeof d.repo=="string"?d.repo:d.repo.name,...d.branch!==void 0?{branch:d.branch}:{}})),...s.workspace.autoPush!==void 0?{auto_push:s.workspace.autoPush}:{},...s.workspace.trailers!==void 0?{trailers:At(s.workspace.trailers)}:{}}),(await t.createChat({body:r,signal:s.signal})).data},async get(s,n={}){return(await t.getChat({path:{chat_id:s},signal:n.signal})).data},async list(s={}){let n=s.metadata===void 0?void 0:Object.entries(s.metadata).map(([d,p])=>`${d}:${p}`),r=(await t.listChats({query:{member:s.member,limit:s.limit,cursor:s.cursor,metadata:n},signal:s.signal})).data;return r.next_cursor===void 0?{chats:r.chats}:{chats:r.chats,nextCursor:r.next_cursor}},async delete(s){await t.deleteChat({path:{chat_id:s}})},members:{async put(s,n,r){let d={};return r.name!==void 0&&(d.name=r.name),r.email!==void 0&&(d.email=r.email),r.owner!==void 0&&(d.owner=r.owner),(await t.putChatMember({path:{chat_id:s,user_id:n},body:d})).data},async delete(s,n){await t.deleteChatMember({path:{chat_id:s,user_id:n}})}},async send(s,n){let r={client_id:n.clientId??ze(),text:n.text};return n.delivery!==void 0&&(r.delivery=n.delivery),n.as!==void 0&&(r.as=n.as),n.budget!==void 0&&(r.budget={max_cost_usd:n.budget.maxCostUsd}),n.metadata!==void 0&&(r.metadata=n.metadata),n.context!==void 0&&(r.context=n.context),Object.assign(r,Tt(n)),X(async()=>(await t.sendChatMessage({path:{chat_id:s},body:r,signal:n.signal})).data,n.signal)},async turnCost(s,n,r={}){let d=(await t.getChatTurnCost({path:{chat_id:s,response_id:n},signal:r.signal})).data;return{chatId:d.chat_id,responseId:d.response_id,inputTokens:d.input_tokens,outputTokens:d.output_tokens,costNanoUsd:d.cost_nano_usd,usd:d.usd,unpriced:d.unpriced,final:d.final,runs:d.runs.map(vt)}},async artifacts(s,n,r={}){return(await t.listChatTurnArtifacts({path:{chat_id:s,response_id:n},signal:r.signal})).data.artifacts.map(p=>({id:p.id,mediaType:p.media_type,...p.logical_type?{logicalType:p.logical_type}:{},sizeBytes:p.size_bytes,checksum:p.checksum,createdAt:p.created_at}))},async artifact(s,n,r,d={}){return(await t.getChatTurnArtifact({path:{chat_id:s,response_id:n,artifact_id:r},signal:d.signal})).data},async messages(s,n={}){let r=(await t.listChatMessages({path:{chat_id:s},query:{limit:n.limit,cursor:n.cursor},signal:n.signal})).data;return r.next_cursor===void 0?{messages:r.messages}:{messages:r.messages,nextCursor:r.next_cursor}},async parts(s,n={}){if(n.cursor!==void 0&&n.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(n.before!==void 0&&(!Number.isSafeInteger(n.before)||n.before<1))throw new TypeError(`chats.parts: before is a part's id \u2014 its journal sequence, a whole number from 1 (got ${String(n.before)})`);let r=(await t.listChatParts({path:{chat_id:s},query:{limit:n.limit,cursor:n.cursor,before:n.before},signal:n.signal})).data,d=r.parts.map(p=>({type:p.type,...p.id!==void 0?{id:p.id}:{},partId:p.part_id,data:p.data}));return r.next_cursor===void 0?{parts:d}:{parts:d,nextCursor:r.next_cursor}},async toolCall(s,n,r={}){let d=(await t.getChatToolCall({path:{chat_id:s,call_id:n},signal:r.signal})).data;return{callId:d.call_id,name:d.name,status:d.status,runId:d.run_id,responseId:d.response_id,input:d.input,output:d.output,outputBytes:d.output_bytes,imageCount:d.image_count,isError:d.is_error}},async toolCalls(s,n){if(typeof n?.turn!="string"||n.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 r=(await t.listTurnToolCalls({path:{chat_id:s},query:{turn:n.turn,limit:n.limit,cursor:n.cursor},signal:n.signal})).data,d=r.tool_calls.map(p=>({callId:p.call_id,name:p.name,state:p.state,createdAt:p.created_at,updatedAt:p.updated_at,arguments:p.arguments,...p.result!==void 0?{result:p.result}:{}}));return r.next_cursor===void 0?{toolCalls:d}:{toolCalls:d,nextCursor:r.next_cursor}},workspace:{async file(s,n,r={}){if(typeof n!="string"||n==="")throw new TypeError("chats.workspace.file: path is the file as the workspace's tree names it (repo/output/app/App.zip)");return(await t.getChatWorkspaceFile({path:{chat_id:s},query:{path:n,...r.manifest!==void 0?{manifest:r.manifest}:{}},signal:r.signal})).data},async addRepo(s,n){let r=typeof n?.repo=="string"?n.repo:n?.repo?.name;if(typeof r!="string"||!_.test(r))throw new TypeError("chats.workspace.addRepo: repo is the project's name for the repository (ai.repos.put), or its ai.repo");let d={repo:r};return n.branch!==void 0&&(d.branch=n.branch),(await t.addChatWorkspaceRepo({path:{chat_id:s},body:d,signal:n.signal})).data}},events(s){if(typeof s!="string"||!/^chat_[0-9a-f]{32}$/.test(s))throw new TypeError(`chats.events(id): a chat's id, chat_ and 32 hex digits (got ${JSON.stringify(s)})`);return Object.freeze({kind:"ai.chat",chatId:s,async pipe(n,r={}){await t.putChatPipe({path:{chat_id:s},body:{topic:n},signal:r.signal})},async unpipe(n={}){await t.deleteChatPipe({path:{chat_id:s},signal:n.signal})}})},async stop(s,n={}){return(await t.stopChat({path:{chat_id:s},...n.as!==void 0?{body:{as:n.as}}:{},signal:n.signal})).data.stopped},async approve(s,n,r={}){return(await t.decideChatApproval({path:{chat_id:s,approval_id:n},body:Ge(!0,r)})).data},async deny(s,n,r={}){return(await t.decideChatApproval({path:{chat_id:s,approval_id:n},body:Ge(!1,r)})).data},async answer(s,n,r,d={}){let p={output:W(r)};d.isError&&(p.is_error=!0),d.as!==void 0&&(p.as=d.as);try{return await X(()=>t.answerChatToolCall({path:{chat_id:s,call_id:n},body:p})),!0}catch(v){if(v instanceof I&&v.status===409)return!1;throw v}},async sendToSubagent(s,n,r,d={}){let p={client_id:d.clientId??ze(),text:r};d.as!==void 0&&(p.as=d.as);let v=await X(async()=>(await t.sendSubagentMessage({path:{chat_id:s,run_id:n},body:p})).data);return{runId:v.run_id,clientId:v.client_id}},async stopSubagent(s,n,r={}){return{runId:(await X(async()=>(await t.stopSubagent({path:{chat_id:s,run_id:n},body:r.as!==void 0?{as:r.as}:{},signal:r.signal})).data,r.signal)).run_id}},async fork(s,n){if(typeof n?.beforeMessage!="string"||n.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 r={before_message:n.beforeMessage};return n.title!==void 0&&(r.title=n.title),n.members!==void 0&&(r.members=n.members.map(We)),(await t.forkChat({path:{chat_id:s},body:r,signal:n.signal})).data},goal:{async set(s,n){let r={objective:n.objective};return n.rubric!==void 0&&(r.rubric=n.rubric),n.maxTurns!==void 0&&(r.max_turns=n.maxTurns),n.budget!==void 0&&(r.budget={max_cost_usd:n.budget.maxCostUsd}),n.as!==void 0&&(r.as=n.as),se((await t.setChatGoal({path:{chat_id:s},body:r,signal:n.signal})).data)},async get(s,n={}){return se((await t.getChatGoal({path:{chat_id:s},query:n.as!==void 0?{as:n.as}:void 0,signal:n.signal})).data)},async update(s,n){let r={};return n.status!==void 0&&(r.status=n.status),n.reason!==void 0&&(r.reason=n.reason),n.objective!==void 0&&(r.objective=n.objective),n.rubric!==void 0&&(r.rubric=n.rubric),n.maxTurns!==void 0&&(r.max_turns=n.maxTurns),n.budget!==void 0&&(r.budget=n.budget===null?null:{max_cost_usd:n.budget.maxCostUsd}),n.as!==void 0&&(r.as=n.as),se((await t.updateChatGoal({path:{chat_id:s},body:r,signal:n.signal})).data)},async clear(s,n={}){await t.clearChatGoal({path:{chat_id:s},query:n.as!==void 0?{as:n.as}:void 0,signal:n.signal})}},voice:{async start(s,n){if(typeof n?.sdp!="string"||!n.sdp.startsWith("v="))throw new TypeError("chats.voice.start: sdp is the app's WebRTC offer (an SDP, v=0 \u2026): its peer connection's localDescription.sdp");if(n.delegation!==void 0&&n.delegation!=="chat"&&n.delegation!=="events")throw new TypeError("chats.voice.start: delegation is chat (a turn of the chat) or events (ai.voice.delegated)");let r={sdp:n.sdp};n.voice!==void 0&&(r.voice=n.voice),n.delegation!==void 0&&(r.delegation=n.delegation),n.as!==void 0&&(r.as=n.as);let d=(await t.startChatVoice({path:{chat_id:s},body:r,signal:n.signal})).data;if(typeof d.sdp!="string"||d.sdp==="")throw new I({op:"startChatVoice",status:502,code:"no_answer",message:"the voice was started but its WebRTC answer was not given"});return{...K(d),sdp:d.sdp}},async get(s,n,r={}){return K((await t.getChatVoice({path:{chat_id:s,voice_id:n},query:r.as!==void 0?{as:r.as}:void 0,signal:r.signal})).data)},async command(s,n,r){if(!St.includes(r?.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) or instruct (behave so)");if(typeof r.text!="string"||r.text==="")throw new TypeError("chats.voice.command: text is what the voice is given");if(r.delegationId!==void 0&&r.type!=="speak"&&r.type!=="tell")throw new TypeError("chats.voice.command: delegationId names the request a speak or a tell answers");if(r.interrupt!==void 0&&(typeof r.interrupt!="boolean"||r.type!=="speak"))throw new TypeError("chats.voice.command: interrupt is a speak's: it cuts what the voice is saying");let d={type:r.type,text:r.text};return r.delegationId!==void 0&&(d.delegation_id=r.delegationId),r.interrupt===!0&&(d.interrupt=!0),r.as!==void 0&&(d.as=r.as),K((await t.commandChatVoice({path:{chat_id:s,voice_id:n},body:d,signal:r.signal})).data)},async close(s,n,r={}){return K((await t.closeChatVoice({path:{chat_id:s,voice_id:n},query:r.as!==void 0?{as:r.as}:void 0,signal:r.signal})).data)}}},a={async put(s,n){let r=typeof s=="string"?s:F(s)?.name,d=typeof s=="string"?n:s;if(typeof r!="string"||!_.test(r))throw new TypeError("agents.put: name is lowercase letters, digits, _ and -, starting with a letter, at most 64 \u2014 or a backend's ai.agent");if(d===void 0)throw new TypeError(`agents.put(${JSON.stringify(r)}): its definition, or a backend's ai.agent`);let p,v=F(d);if(v){if(v.name!==r)throw new TypeError(`agents.put(${JSON.stringify(r)}): the backend's agent is named ${JSON.stringify(v.name)} \u2014 its machine is asked for it by that name`);p={backend:v.machine??"backend"}}else p=V(d,`agents.put(${JSON.stringify(r)})`);return(await t.putAgent({path:{name:r},body:p})).data},async list(){return(await t.listAgents({})).data.agents},async delete(s){await t.deleteAgent({path:{name:s}})}},i={async put(s,n){let r={kind:n.kind,url:n.url};return n.description!==void 0&&(r.description=n.description),n.parameters!==void 0&&(r.parameters=n.parameters),n.approval!==void 0&&(r.approval=n.approval),(await t.putEndpoint({path:{name:s},body:r})).data},async list(){return(await t.listEndpoints({})).data.endpoints},async delete(s){await t.deleteEndpoint({path:{name:s}})}},u={async get(){return Fe((await t.getSettings({})).data)},async put(s){let n={};return s.clients!==void 0&&(n.clients=s.clients),s.userMessagesPerMinute!==void 0&&(n.user_messages_per_minute=s.userMessagesPerMinute),s.historyLimitBytes!==void 0&&(n.history_limit_bytes=s.historyLimitBytes),Fe((await t.putSettings({body:n})).data)}},l=s=>({name:s.name,repository:s.repository,defaultBranch:s.default_branch,backend:s.backend,createdAt:s.created_at});return{chats:o,agents:a,endpoints:i,settings:u,repos:{async put(s,n){let r=typeof s=="string"?s:s.name;if(typeof r!="string"||!_.test(r))throw new TypeError("repos.put: name is lowercase letters, digits, _ and -, starting with a letter, at most 64");let d=typeof s=="string"?{repository:n?.repository??"",...n?.defaultBranch?{default_branch:n.defaultBranch}:{},...n?.backend?{backend:n.backend}:{}}:{repository:s.repository,default_branch:s.defaultBranch,...s.machine?{backend:s.machine}:{}};return l((await t.putRepo({path:{name:r},body:d})).data)},async list(s={}){let n=(await t.listRepos({query:{limit:s.limit,cursor:s.cursor}})).data,r=n.repos.map(l);return n.next_cursor===void 0?{repos:r}:{repos:r,nextCursor:n.next_cursor}},async delete(s){await t.deleteRepo({path:{name:s}})}}}}var Rt=/^pb_[a-z0-9]+_s/;function Ke(e){let t=globalThis;return t.process?.env?.[e]??t.Deno?.env?.get(e)}function oe(){return"ai_"+crypto.randomUUID()}function ie(e){if(e.prepared)return e;let t=e;return{name:"answer",schema:t,prepared:z(t,"answer")}}var Xe=4,Ct=/^[a-z][a-z0-9-]{1,62}$/,Ze=["image/png","image/jpeg","image/webp","image/gif"],He=5<<20,Ye=6<<20;function tt(e){let t="";for(let o=0;o<e.length;o+=32768)t+=String.fromCharCode(...e.subarray(o,o+32768));return btoa(t)}function Et(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 Pt(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>Xe)throw new TypeError(`a question takes ${Xe} pictures at most (got ${e.length})`);let t=0;return e.map((o,a)=>{let i=o??{};if("bytes"in i||o instanceof Uint8Array)throw new TypeError(`images[${a}]: a picture's bytes are { mediaType, data } \u2014 or, in the project's storage, { bucket, path }`);if("data"in i||"mediaType"in i){if(i.bucket!==void 0||i.path!==void 0||i.url!==void 0)throw new TypeError(`images[${a}] is { bucket, path }, { url } or { mediaType, data }: one of them`);if(typeof i.mediaType!="string"||!Ze.includes(i.mediaType))throw new TypeError(`images[${a}].mediaType is the picture's type: ${Ze.join(", ")}`);let u=i.data instanceof Uint8Array?tt(i.data):i.data,l=typeof u=="string"?Et(u):-1;if(l<0)throw new TypeError(`images[${a}].data is the picture's bytes: base64, or a Uint8Array`);if(l===0||l>He)throw new TypeError(`images[${a}] is ${l} bytes: a picture given by its bytes is 1 byte to ${He>>20} MiB`);if(t+=l,t>Ye)throw new TypeError(`the pictures given by their bytes are ${Ye>>20} MiB at most together: put a larger one in the project's storage and give { bucket, path }`);return{media_type:i.mediaType,data:u}}if(typeof i.url=="string"){if(i.bucket!==void 0||i.path!==void 0)throw new TypeError(`images[${a}] is { bucket, path } or { url }, not both`);let u;try{u=new URL(i.url)}catch{throw new TypeError(`images[${a}].url is not an address: ${JSON.stringify(i.url.slice(0,80))}`)}if(u.protocol!=="https:"||i.url.length>2048)throw new TypeError(`images[${a}].url is an https address of 2048 characters at most`);return{url:i.url}}if(typeof i.bucket!="string"||!Ct.test(i.bucket)||typeof i.path!="string"||i.path==="")throw new TypeError(`images[${a}] is { bucket, path } \u2014 a file of the project's storage \u2014 { url } or { mediaType, data }`);return{bucket:i.bucket,path:i.path}})}function Z(e,t={},o){if(e.prompt===void 0&&e.messages===void 0)throw new TypeError("ask a model something: prompt, or messages");let a={...t};if(e.prompt!==void 0&&(a.input=e.prompt),e.messages!==void 0&&(a.messages=e.messages),e.instructions!==void 0&&(a.instructions=e.instructions),e.model!==void 0&&(a.model=e.model),e.metadata!==void 0&&(a.metadata=e.metadata),e.images!==void 0&&(a.images=Pt(e.images)),e.tools!==void 0&&(a.tools=e.tools.map((i,u)=>{if(i?.source==="client")throw new TypeError(`tools[${u}]: ${i.name} is a client tool \u2014 an app answers it, in a chat; a one-shot answer has no app to wait for`);if(i?.source==="platform")throw new TypeError(`tools[${u}]: the platform's ${i.name} is a chat's agent's tool \u2014 a one-shot answer is given none`);let l=J(i,`tools[${u}]`);return l.source==="backend"&&l.machine===void 0&&o!==void 0&&(l.machine=o),l})),e.maxToolCalls!==void 0){if(!e.tools?.length)throw new TypeError("maxToolCalls bounds the calls of the tools given: give tools");a.max_tool_calls=ae(e.maxToolCalls,"ask")}return a}var $=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 It(e){let t=Uint8Array.from(atob(e),i=>i.charCodeAt(0)),o=new DataView(t.buffer,t.byteOffset,t.byteLength),a=new Array(t.byteLength/4);for(let i=0;i<a.length;i++)a[i]=o.getFloat32(i*4,!0);return a}async function Qe(e){let t,o;return e instanceof Uint8Array?(t=e,o=et(t)):typeof Blob<"u"&&e instanceof Blob?(t=new Uint8Array(await e.arrayBuffer()),o=e.type||et(t)):(t=e.bytes,o=e.mediaType),{media_type:o,data:tt(t)}}function et(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 $t(e){let t=e.url??Ke("PALBASE_URL"),o=e.secretKey??Ke("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 o!="string"||!Rt.test(o))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 a=ge(le({baseUrl:t,credentials:{secretKey:o},fetch:e.fetch}),e.retry??pe);return ue.client(a)}function Mt(e){return new Proxy({},{get:(t,o)=>e.ai[o]})}function Ot(e={}){if(we())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&&!_.test(e.machine))throw new TypeError("machine is the name of one of the project's machines");let t=e.server?Mt(e.server):$t(e),o=e.resumeFor??12e4;async function a(c,g,h=oe()){return L(t.createResponse({headers:{"Idempotency-Key":h},body:c,signal:g}))}async function i(c,g={}){return(await t.getResponse({path:{response_id:c},signal:g.signal})).data}async function u(c,g,h,y,k){let T=0,x=c,R=oe(),O=()=>Date.now()+o,j=O();for(let B=0;;B++)try{if(x||(g===null?x=(await a({...k,stream:!0},y,R)).data:x=(await t.followResponse({path:{response_id:g},query:{offset:T},signal:y})).data),!x.body)throw new Error("the stream has no body");for await(let w of be(x.body)){let A=JSON.parse(w.data);switch(w.event){case"response":g===null&&(g=A.id,h.admitted(A));break;case"delta":{let M=A.offset+me(A.text);if(M>T){let H=A.offset>=T?A.text:ye(A.text,T-A.offset);h.delta(T,H),T=M}j=O();break}case"reset":A.offset<T&&(T=A.offset,h.reset(T));break;case"terminal":return A}}throw new Error("the stream ended before its answer did")}catch(w){if(x=null,y?.aborted||w instanceof I&&w.status>0&&w.status<500&&w.status!==429||g===null&&!(w instanceof I)||Date.now()>j)throw w;await new Promise(A=>setTimeout(A,Math.min(250*2**Math.min(B,4),4e3)))}}function l(c){if(c.status!=="completed")throw new $(c);return c.text??""}function m(c,g){let h=Z(c,g?{schema:g.prepared.json,schema_name:g.name}:{},e.machine),y=[],k=!1,T,x=null,R=()=>{let f=x;x=null,f?.()},O,j,B=new Promise((f,S)=>{O=f,j=S});B.catch(()=>{});let w="",A=u(null,null,{admitted:f=>O(f.id),delta:(f,S)=>{w+=S,y.push(S),R()},reset:f=>{let S=he(w,f);w=w.slice(0,S),y.push("\0reset:"+S),R()}},c.signal,h).then(f=>{let S=f.status==="completed"?f.text??"":"";return S.length>w.length&&S.startsWith(w)&&(y.push(S.slice(w.length)),w=S),k=!0,R(),f},f=>{throw k=!0,T=f,j(f),R(),f});A.catch(()=>{});async function*M(){for(let f=0;;f++){for(;f>=y.length;){if(k){if(T)throw T;return}await new Promise(S=>x=S)}yield y[f]}}async function*H(){for await(let f of M())f.startsWith("\0reset:")||(yield f)}async function*nt(){let f="",S="";for await(let N of M()){N.startsWith("\0reset:")?f=f.slice(0,Number(N.slice(7))):f+=N;let E=ee(f);if(E===void 0)continue;let P=JSON.stringify(E);P!==S&&(S=P,yield E)}}let D=A.then(f=>{if(f.status!=="completed")throw new $(f);return f});D.catch(()=>{});let de=g?D.then(f=>g.prepared.check(f.output)):Promise.reject(new TypeError("object is a schema stream's"));de.catch(()=>{});let ce=D.then(f=>f.text??w);return ce.catch(()=>{}),{id:B,response:D,text:ce,get textStream(){return H()},get partialObjectStream(){return nt()},object:de,toResponse(f={}){let S=new TextEncoder,N=new ReadableStream({async start(P){try{for await(let U of M())U.startsWith("\0reset:")?P.enqueue(S.encode(`event: reset
|
|
7
|
+
`,t:" ",r:"\r",b:"\b",f:"\f"}[u]??u,a++}return{value:o,complete:!1,empty:!1,at:e.length}}function Q(e,t){t=q(e,t);let o=e[t];if(o===void 0)return{value:void 0,complete:!1,empty:!0,at:t};if(o==='"')return ke(e,t);if(o==="{")return at(e,t);if(o==="[")return st(e,t);let a=t;for(;a<e.length&&/[-+0-9.A-Za-z]/.test(e[a]);)a++;if(a===e.length)return{value:void 0,complete:!1,empty:!0,at:a};try{return{value:JSON.parse(e.slice(t,a)),complete:!0,empty:!1,at:a}}catch{return{value:void 0,complete:!1,empty:!0,at:e.length}}}function at(e,t){let o={},a=t+1;for(;;){if(a=q(e,a),e[a]==="}")return{value:o,complete:!0,empty:!1,at:a+1};if(e[a]===","){a++;continue}if(e[a]!=='"')return{value:o,complete:!1,empty:!1,at:e.length};let i=ke(e,a);if(!i.complete)return{value:o,complete:!1,empty:!1,at:e.length};if(a=q(e,i.at),e[a]!==":")return{value:o,complete:!1,empty:!1,at:e.length};let u=Q(e,a+1);if(u.empty||Object.defineProperty(o,i.value,{value:u.value,enumerable:!0,writable:!0,configurable:!0}),!u.complete)return{value:o,complete:!1,empty:!1,at:e.length};a=u.at}}function st(e,t){let o=[],a=t+1;for(;;){if(a=q(e,a),e[a]==="]")return{value:o,complete:!0,empty:!1,at:a+1};if(e[a]===","){a++;continue}if(a>=e.length)return{value:o,complete:!1,empty:!1,at:a};let i=Q(e,a);if(i.empty||o.push(i.value),!i.complete)return{value:o,complete:!1,empty:!1,at:e.length};a=i.at}}function ee(e){let t=Q(e,0);return t.empty?void 0:t.value}var b=class extends Error{path;constructor(t,o){super(`${t}: ${o}`),this.name="AISchemaError",this.path=t}},ot=new Set(["type","properties","required","additionalProperties","items","enum","description","title","minimum","maximum","minLength","maxLength","minItems","maxItems"]),it=new Set(["format","pattern","exclusiveMinimum","exclusiveMaximum","multipleOf","uniqueItems","contentEncoding","contentMediaType","default","examples","readOnly","writeOnly","deprecated","$comment"]),dt=new Set(["object","array","string","integer","number","boolean"]),Te=12,xe=512,ct=/^[A-Za-z][A-Za-z0-9_-]{0,63}$/;function z(e,t="answer"){if(!ct.test(t))throw new b(t||"(name)","a schema name starts with a letter and holds letters, digits, _ and -, 64 at most");let o=e?.["~standard"];if(!o||o.version!==1||typeof o.validate!="function")throw new b(t,"not a Standard Schema: pass a zod (4.2+), valibot or arktype schema");if(!o.jsonSchema||typeof o.jsonSchema.output!="function")throw new b(t,`${o.vendor}'s schema cannot say itself as JSON Schema; use a version that implements Standard JSON Schema`);let a;try{a=o.jsonSchema.output({target:"draft-2020-12",libraryOptions:{unrepresentable:"throw"}})}catch(l){throw new b(t,`the schema has a part JSON Schema cannot say (${l.message}): a function, a transform, a date \u2014 give the model a string and convert it after`)}if(a.type!=="object")throw new b(t,"the answer is an object: wrap the value in z.object({ \u2026 })");let u=te(a,t,0,{properties:0});return{name:t,json:u,async check(l){let m=await o.validate(l);if(m.issues){let s=m.issues[0],n=(s?.path??[]).map(r=>String(typeof r=="object"?r.key:r)).join(".");throw new b(n?`${t}.${n}`:t,`the model's answer does not match the schema: ${s?.message??"invalid"}`)}return m.value}}}function te(e,t,o,a){if(o>Te)throw new b(t,`nests deeper than ${Te} levels, the most the provider takes`);for(let l of["anyOf","oneOf","allOf"])if(l in e)throw new b(t,lt(e[l])??"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 l of["$ref","$defs","definitions","$dynamicRef"])if(l in e)throw new b(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 b(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 l of["prefixItems","patternProperties","propertyNames","not","if","then","else","dependentRequired","dependentSchemas","const","minProperties","maxProperties","contains","unevaluatedProperties","unevaluatedItems"])if(l in e)throw new b(t,`uses ${l}, which the provider cannot hold a model to`);if(Array.isArray(e.type))throw new b(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 i=e.type;if(typeof i!="string"&&!("enum"in e))throw new b(t,"has no type: the provider holds a model only to a typed value");if(typeof i=="string"&&!dt.has(i))throw new b(t,`is of type ${i}, which the provider does not take`);let u={};for(let[l,m]of Object.entries(e))if(!(l==="$schema"||l==="id"||l==="$id")&&!it.has(l)){if(!ot.has(l))throw new b(t,`uses ${l}, which the provider cannot hold a model to`);u[l]=m}if("enum"in e&&typeof i!="string"){let l=e.enum,m=new Set(l.map(s=>s===null?"null":typeof s));if(m.size!==1||m.has("null"))throw new b(t,"an enum of values of several types (or with null): one type per field");u.type=m.has("string")?"string":m.has("boolean")?"boolean":"number"}if(i==="object"){let l=e.properties??{},m=Object.keys(l);if(m.length===0)throw new b(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 b(t,"accepts fields it does not name (passthrough, catchall, record): the provider holds a model only to the fields named");if(a.properties+=m.length,a.properties>xe)throw new b(t,`the schema has more than ${xe} fields in all, the most the provider takes`);let s=new Set(e.required??[]),n={};for(let r of m){if(!s.has(r))throw new b(`${t}.${r}`,'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[r]=te(l[r],`${t}.${r}`,o+1,a)}u.properties=n,u.required=m,u.additionalProperties=!1}if(i==="array"){let l=e.items;if(!l||typeof l!="object"||Array.isArray(l))throw new b(t,"is a list with no one shape for its items: the provider takes a list of one shape");u.items=te(l,`${t}[]`,o+1,a)}return u}function lt(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 ut=new Set(["image/png","image/jpeg","image/webp","image/gif"]);function W(e){return Array.isArray(e)&&e.length>0&&e.every(Se)?e.map(Ae):Se(e)?[Ae(e)]:e==null?[{type:"text",text:""}]:typeof e=="string"?[{type:"text",text:e}]:[{type:"text",text:JSON.stringify(e)??String(e)}]}function Se(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 Ae(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(!ut.has(t))throw new TypeError(`a tool's picture is image/png, image/jpeg, image/webp or image/gif (got ${JSON.stringify(t)})`);let o="bytes"in e?e.bytes:e.data;return{type:"image",media_type:t,data:typeof o=="string"?o:pt(o)}}function pt(e){let t="";for(let o=0;o<e.length;o+=32768)t+=String.fromCharCode(...e.subarray(o,o+32768));return btoa(t)}var Ie=Symbol.for("palbase.ai.deferred"),_e=60,ve=86400;function $e(e={}){let t=e?.expiresInSeconds;if(t!==void 0&&(!Number.isInteger(t)||t<_e||t>ve))throw new TypeError(`ai.deferred: expiresInSeconds is how long the call waits for its answer, ${_e} to ${ve} seconds (got ${String(t)})`);return Object.freeze({[Ie]:!0,...t!==void 0?{expiresInSeconds:t}:{}})}function gt(e){return typeof e=="object"&&e!==null&&e[Ie]===!0}var ft=Symbol.for("palbase.ai.declared"),mt=Symbol.for("palbase.ai.tool_error"),ne=class extends Error{constructor(t){super(t),this.name="ToolError",Object.defineProperty(this,mt,{value:!0})}};function G(){let e=globalThis,t=e[ft]??={tools:new Map,agents:new Map,repos:new Map,twice:new Set};return t.repos??=new Map,t}function re(e,t,o,a){let i=e.get(o);i===void 0?e.set(o,a):i!==a&&G().twice.add(`${t}:${o}`)}var Me=/^[A-Za-z][A-Za-z0-9_-]{0,63}$/,v=/^[a-z][a-z0-9_-]{0,63}$/;function Oe(e,t){if(e===void 0)return{type:"object",properties:{}};let o=e?.["~standard"];if(!o||o.version!==1||typeof o.validate!="function")throw new TypeError(`${t}: input is a Standard Schema \u2014 a zod (4.2+), valibot or arktype object schema`);if(!o.jsonSchema||typeof o.jsonSchema.output!="function")throw new TypeError(`${t}: ${o.vendor}'s schema cannot say itself as JSON Schema; use a version that implements Standard JSON Schema`);let a;try{a=o.jsonSchema.output({target:"draft-2020-12",libraryOptions:{unrepresentable:"throw"}})}catch(m){throw new TypeError(`${t}: the input has a part JSON Schema cannot say (${m.message}) \u2014 a function, a transform, a date: take a string and convert it in run`)}if(a.type!=="object")throw new TypeError(`${t}: a tool takes an object \u2014 wrap the input in z.object({ \u2026 })`);let i=JSON.stringify(a);if(/"\$(ref|defs|dynamicRef)"/.test(i))throw new TypeError(`${t}: the input refers to another schema (a recursive or shared type) \u2014 write the shape out`);let{$schema:u,...l}=a;return l}function je(e){let t=`ai.tool(${JSON.stringify(e?.name??null)})`;if(typeof e?.name!="string"||!Me.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&&!v.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 o=Oe(e.input,t),a=e.input["~standard"],i=e.run,u={source:"backend",name:e.name,description:e.description,input:e.input,parameters:o,approval:e.approval===!0,...e.machine!==void 0?{machine:e.machine}:{},async call(l,m){let s=await a.validate(l);if(s.issues){let r=s.issues[0],d=(r?.path??[]).map(p=>String(typeof p=="object"?p.key:p)).join(".");return{output:[{type:"text",text:`the input does not match ${e.name}'s schema${d?` at ${d}`:""}: ${r?.message??"invalid"}`}],is_error:!0}}let n=await i(s.value,m);return gt(n)?m.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,...n.expiresInSeconds!==void 0?{expires_in_seconds:n.expiresInSeconds}:{}}:{output:W(n),is_error:!1}}};return Object.freeze(u),re(G().tools,"tool",u.name,u),u}function Be(e){let t=`ai.clientTool(${JSON.stringify(e?.name??null)})`;if(typeof e?.name!="string"||!Me.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`);return Object.freeze({source:"client",name:e.name,description:e.description,parameters:Oe(e.input,t),approval:e.approval===!0})}var ht=/^[A-Za-z0-9_.-]{1,100}\/[A-Za-z0-9_.-]{1,100}$/;function De(e){let t=e??{};if(typeof t.name!="string"||!v.test(t.name))throw new TypeError("ai.repo: name is lowercase letters, digits, _ and -, starting with a letter, at most 64");if(typeof t.repository!="string"||!ht.test(t.repository))throw new TypeError(`ai.repo(${JSON.stringify(t.name)}): repository is a GitHub repository, owner/name`);if(typeof t.token!="function")throw new TypeError(`ai.repo(${JSON.stringify(t.name)}): token is the function that gives a token for one clone or push`);if(t.machine!==void 0&&!v.test(t.machine))throw new TypeError(`ai.repo(${JSON.stringify(t.name)}): machine is the project's machine that gives its tokens`);let o=t.token,a={kind:"repo",name:t.name,repository:t.repository,defaultBranch:t.defaultBranch??"main",...t.machine!==void 0?{machine:t.machine}:{},async token(i){return await o(i)}};return re(G().repos,"repo",t.name,a),a}function Ne(e){if(typeof e!="function")throw new TypeError("ai.repoTokens(give): give is the function that gives a token for one clone or push of a repository put by name");let t=G();t.repoTokens===void 0?t.repoTokens=e:t.repoTokens!==e&&t.twice.add("repoTokens")}function Ue(e,t,o={}){let a=`ai.agent(${JSON.stringify(e??null)})`;if(typeof e!="string"||!v.test(e))throw new TypeError(`${a}: name is lowercase letters, digits, _ and -, starting with a letter, at most 64`);if(typeof t!="function")throw new TypeError(`${a}: the agent is a function of the turn's context that returns its definition`);if(o.machine!==void 0&&!v.test(o.machine))throw new TypeError(`${a}: machine is the name of one of the project's machines`);let i={kind:"agent",name:e,...o.machine!==void 0?{machine:o.machine}:{},async resolve(u){let l=await t(u),m=V(l,`${a} for chat ${u.chatId}`);if(m.backend!==void 0)throw new TypeError(`${a}: a backend's agent is its definition \u2014 it names no other backend`);return{definition:m,tools:yt(l)}}};return Object.freeze(i),re(G().agents,"agent",e,i),i}function F(e){return typeof e=="object"&&e!==null&&e.kind==="agent"?e:void 0}function yt(e){return[...e.tools??[],...(e.subagents??[]).flatMap(o=>o.tools??[])].filter(o=>o.source==="backend")}var Re=["web.search","web.fetch","workspace.fetch_archive"];function J(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 o=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,...o,...e.machine!==void 0?{machine:e.machine}:{}};case"client":return{source:"client",name:e.name,description:e.description,parameters:e.parameters,...o};case"https":if(typeof e.name!="string"||!v.test(e.name))throw new TypeError(`${t}: { source: 'https', name } names an endpoint the project put`);return{source:"https",name:e.name,...o};case"mcp":if(typeof e.name!="string"||!v.test(e.name))throw new TypeError(`${t}: { source: 'mcp', name } names an MCP server the project put`);return{source:"mcp",name:e.name,...o,...e.only!==void 0?{only:[...e.only]}:{}};case"platform":{let a=Object.keys(e).filter(i=>i!=="source"&&i!=="name");if(typeof e.name!="string"||!Re.includes(e.name))throw new TypeError(`${t}: { source: 'platform', name } names one of the platform's tools: ${Re.join(", ")}`);if(a.length>0)throw new TypeError(`${t}: the platform's ${e.name} is given by its name alone (not ${a.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 Ce=1e4,Ee=["none","minimal","low","medium","high","xhigh","max"],wt=1e8,bt=/^[A-Za-z]{2,8}(-[A-Za-z0-9]{1,8})*$/;function ae(e,t){if(!Number.isInteger(e)||e<1||e>Ce)throw new TypeError(`${t}: maxToolCalls is a whole number, 1 to ${Ce} (got ${String(e)})`);return e}function Pe(e,t){let o={};if(e.effort!==void 0){if(typeof e.effort!="string"||!Ee.includes(e.effort))throw new TypeError(`${t}: effort is one of ${Ee.join(", ")} \u2014 which a model takes is its catalogue entry's (ai.models())`);o.effort=e.effort}if(e.contextWindow!==void 0){if(!Number.isInteger(e.contextWindow)||e.contextWindow<1||e.contextWindow>wt)throw new TypeError(`${t}: contextWindow is a number of tokens (got ${String(e.contextWindow)})`);o.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`);o.thinking=e.thinking}return o}function V(e,t){if(typeof e!="object"||e===null)throw new TypeError(`${t}: a definition is { instructions, model, tools, subagents, maxToolCalls, effort, contextWindow, thinking, language }`);let o={};if(e.instructions!==void 0&&(o.instructions=e.instructions),e.model!==void 0&&(o.model=e.model),e.maxToolCalls!==void 0&&(o.max_tool_calls=ae(e.maxToolCalls,t)),Object.assign(o,Pe(e,t)),e.language!==void 0){if(typeof e.language!="string"||e.language.length>35||!bt.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)`);o.language=e.language}if(e.tools!==void 0&&(o.tools=e.tools.map(a=>J(a,t))),e.subagents!==void 0){for(let a of e.subagents){let i=(a?.tools??[]).find(u=>u?.source==="platform");if(i)throw new TypeError(`${t} subagent ${a.name}: the platform's ${i.name} is the agent's tool \u2014 its subagents work with the agent's`)}o.subagents=e.subagents.map(a=>({name:a.name,description:a.description,...a.instructions!==void 0?{instructions:a.instructions}:{},...a.model!==void 0?{model:a.model}:{},...a.required!==void 0?{required:a.required}:{},...Pe(a,`${t} subagent ${a.name}`),...a.tools!==void 0?{tools:a.tools.map(i=>J(i,`${t} subagent ${a.name}`))}:{}}))}return o}function Ge(e,t){let o={approve:e};return t.reason!==void 0&&(o.reason=t.reason),t.as!==void 0&&(o.as=t.as),o}var kt=/^[a-z][a-z0-9-]{1,62}$/,Le=4,qe=8;function Tt(e){let t={},o=(a,i)=>{if(typeof a?.bucket!="string"||!kt.test(a.bucket))throw new TypeError(`chats.send: ${i}'s bucket is one of the project's buckets, by its name`);if(typeof a.path!="string"||a.path===""||a.path.length>1024)throw new TypeError(`chats.send: ${i}'s path is its path in the bucket (1024 characters at most)`);return{bucket:a.bucket,path:a.path}};if(e.images!==void 0){if(!Array.isArray(e.images)||e.images.length>Le)throw new TypeError(`chats.send: images are ${Le} at most \u2014 as many as the model is shown at once`);t.images=e.images.map((a,i)=>o(a,`images[${i}]`))}if(e.files!==void 0){if(!Array.isArray(e.files)||e.files.length>qe)throw new TypeError(`chats.send: files are ${qe} at most`);t.files=e.files.map((a,i)=>{let u=o(a,`files[${i}]`);if(a.filename!==void 0){if(typeof a.filename!="string"||a.filename===""||a.filename.length>255)throw new TypeError(`chats.send: files[${i}].filename is its name in the workspace (255 characters at most)`);u.filename=a.filename}if(a.contentType!==void 0){if(typeof a.contentType!="string"||a.contentType===""||a.contentType.length>128)throw new TypeError(`chats.send: files[${i}].contentType is a media type (application/pdf)`);u.content_type=a.contentType}return u})}return t}function K(e){return{id:e.id,chatId:e.chat_id,userId:e.user_id,delegation:e.delegation,status:e.status,seconds:e.seconds,startedAt:e.started_at,closedAt:e.closed_at,closeReason:e.close_reason??""}}var xt=["speak","tell","know","instruct"];function ze(){return"cm_"+crypto.randomUUID()}async function X(e,t,o=4){for(let a=1;;a++)try{return await e()}catch(i){if(a>=o||!(i instanceof I)||i.status===429||t?.aborted)throw i;let u=fe(i,a,30);if(u===void 0)throw i;await new Promise((l,m)=>{let s=setTimeout(l,u*1e3);t?.addEventListener("abort",()=>(clearTimeout(s),m(t.reason)),{once:!0})})}}function se(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 We=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}:{}}),St=/^[A-Za-z0-9-]{1,64}$/,Je=16;function At(e){if(!Array.isArray(e)||e.length>Je)throw new TypeError(`chats.create: workspace.trailers are ${Je} at most, each { key, value }`);return e.map((t,o)=>{if(typeof t?.key!="string"||!St.test(t.key))throw new TypeError(`chats.create: workspace.trailers[${o}].key is a git trailer's token: letters, digits and -, at most 64 (PalCore-Task, Co-authored-by)`);if(typeof t.value!="string"||t.value===""||/[\r\n]/.test(t.value)||new TextEncoder().encode(t.value).byteLength>512)throw new TypeError(`chats.create: workspace.trailers[${o}].value is one line of 512 bytes at most`);return{key:t.key,value:t.value}})}function _t(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 Fe(e){return{clients:e.clients,userMessagesPerMinute:e.user_messages_per_minute,historyLimitBytes:e.history_limit_bytes,historyBytes:e.history_bytes}}function vt(e){return new Proxy(e,{get(t,o){let a=t[o];return typeof a=="function"?(...i)=>L(a.apply(t,i)):a}})}function Ve(e){let t=vt(e),o={async create(s){let n=typeof s.agent=="string"||s.agent===void 0?s.agent:F(s.agent)?.name;if(s.agent!==void 0&&n===void 0)throw new TypeError("chats.create: agent is a named agent of the project, or a backend's ai.agent");if(n===void 0&&s.definition===void 0)throw new TypeError("chats.create: an agent (a named agent of the project) or a definition of the chat's own");let r={agent:n??"assistant"};return s.definition!==void 0&&(r.definition=V(s.definition,"chats.create")),s.title!==void 0&&(r.title=s.title),s.metadata!==void 0&&(r.metadata=s.metadata),s.members!==void 0&&(r.members=s.members.map(We)),s.workspace!==void 0&&(r.workspace={repos:s.workspace.repos.map(d=>({repo:typeof d.repo=="string"?d.repo:d.repo.name,...d.branch!==void 0?{branch:d.branch}:{}})),...s.workspace.autoPush!==void 0?{auto_push:s.workspace.autoPush}:{},...s.workspace.trailers!==void 0?{trailers:At(s.workspace.trailers)}:{}}),(await t.createChat({body:r,signal:s.signal})).data},async get(s,n={}){return(await t.getChat({path:{chat_id:s},signal:n.signal})).data},async list(s={}){let n=s.metadata===void 0?void 0:Object.entries(s.metadata).map(([d,p])=>`${d}:${p}`),r=(await t.listChats({query:{member:s.member,limit:s.limit,cursor:s.cursor,metadata:n},signal:s.signal})).data;return r.next_cursor===void 0?{chats:r.chats}:{chats:r.chats,nextCursor:r.next_cursor}},async delete(s){await t.deleteChat({path:{chat_id:s}})},members:{async put(s,n,r){let d={};return r.name!==void 0&&(d.name=r.name),r.email!==void 0&&(d.email=r.email),r.owner!==void 0&&(d.owner=r.owner),(await t.putChatMember({path:{chat_id:s,user_id:n},body:d})).data},async delete(s,n){await t.deleteChatMember({path:{chat_id:s,user_id:n}})}},async send(s,n){let r={client_id:n.clientId??ze(),text:n.text};return n.delivery!==void 0&&(r.delivery=n.delivery),n.as!==void 0&&(r.as=n.as),n.budget!==void 0&&(r.budget={max_cost_usd:n.budget.maxCostUsd}),n.metadata!==void 0&&(r.metadata=n.metadata),n.context!==void 0&&(r.context=n.context),Object.assign(r,Tt(n)),X(async()=>(await t.sendChatMessage({path:{chat_id:s},body:r,signal:n.signal})).data,n.signal)},async turnCost(s,n,r={}){let d=(await t.getChatTurnCost({path:{chat_id:s,response_id:n},signal:r.signal})).data;return{chatId:d.chat_id,responseId:d.response_id,inputTokens:d.input_tokens,outputTokens:d.output_tokens,costNanoUsd:d.cost_nano_usd,usd:d.usd,unpriced:d.unpriced,final:d.final,runs:d.runs.map(_t)}},async artifacts(s,n,r={}){return(await t.listChatTurnArtifacts({path:{chat_id:s,response_id:n},signal:r.signal})).data.artifacts.map(p=>({id:p.id,mediaType:p.media_type,...p.logical_type?{logicalType:p.logical_type}:{},sizeBytes:p.size_bytes,checksum:p.checksum,createdAt:p.created_at}))},async artifact(s,n,r,d={}){return(await t.getChatTurnArtifact({path:{chat_id:s,response_id:n,artifact_id:r},signal:d.signal})).data},async messages(s,n={}){let r=(await t.listChatMessages({path:{chat_id:s},query:{limit:n.limit,cursor:n.cursor},signal:n.signal})).data;return r.next_cursor===void 0?{messages:r.messages}:{messages:r.messages,nextCursor:r.next_cursor}},async parts(s,n={}){if(n.cursor!==void 0&&n.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(n.before!==void 0&&(!Number.isSafeInteger(n.before)||n.before<1))throw new TypeError(`chats.parts: before is a part's id \u2014 its journal sequence, a whole number from 1 (got ${String(n.before)})`);let r=(await t.listChatParts({path:{chat_id:s},query:{limit:n.limit,cursor:n.cursor,before:n.before},signal:n.signal})).data,d=r.parts.map(p=>({type:p.type,...p.id!==void 0?{id:p.id}:{},partId:p.part_id,data:p.data}));return r.next_cursor===void 0?{parts:d}:{parts:d,nextCursor:r.next_cursor}},async toolCall(s,n,r={}){let d=(await t.getChatToolCall({path:{chat_id:s,call_id:n},signal:r.signal})).data;return{callId:d.call_id,name:d.name,status:d.status,runId:d.run_id,responseId:d.response_id,input:d.input,output:d.output,outputBytes:d.output_bytes,imageCount:d.image_count,isError:d.is_error}},async toolCalls(s,n){if(typeof n?.turn!="string"||n.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 r=(await t.listTurnToolCalls({path:{chat_id:s},query:{turn:n.turn,limit:n.limit,cursor:n.cursor},signal:n.signal})).data,d=r.tool_calls.map(p=>({callId:p.call_id,name:p.name,state:p.state,createdAt:p.created_at,updatedAt:p.updated_at,arguments:p.arguments,...p.result!==void 0?{result:p.result}:{}}));return r.next_cursor===void 0?{toolCalls:d}:{toolCalls:d,nextCursor:r.next_cursor}},workspace:{async file(s,n,r={}){if(typeof n!="string"||n==="")throw new TypeError("chats.workspace.file: path is the file as the workspace's tree names it (repo/output/app/App.zip)");return(await t.getChatWorkspaceFile({path:{chat_id:s},query:{path:n,...r.manifest!==void 0?{manifest:r.manifest}:{}},signal:r.signal})).data},async addRepo(s,n){let r=typeof n?.repo=="string"?n.repo:n?.repo?.name;if(typeof r!="string"||!v.test(r))throw new TypeError("chats.workspace.addRepo: repo is the project's name for the repository (ai.repos.put), or its ai.repo");let d={repo:r};return n.branch!==void 0&&(d.branch=n.branch),(await t.addChatWorkspaceRepo({path:{chat_id:s},body:d,signal:n.signal})).data}},events(s){if(typeof s!="string"||!/^chat_[0-9a-f]{32}$/.test(s))throw new TypeError(`chats.events(id): a chat's id, chat_ and 32 hex digits (got ${JSON.stringify(s)})`);return Object.freeze({kind:"ai.chat",chatId:s,async pipe(n,r={}){await t.putChatPipe({path:{chat_id:s},body:{topic:n},signal:r.signal})},async unpipe(n={}){await t.deleteChatPipe({path:{chat_id:s},signal:n.signal})}})},async stop(s,n={}){return(await t.stopChat({path:{chat_id:s},...n.as!==void 0?{body:{as:n.as}}:{},signal:n.signal})).data.stopped},async approve(s,n,r={}){return(await t.decideChatApproval({path:{chat_id:s,approval_id:n},body:Ge(!0,r)})).data},async deny(s,n,r={}){return(await t.decideChatApproval({path:{chat_id:s,approval_id:n},body:Ge(!1,r)})).data},async answer(s,n,r,d={}){let p={output:W(r)};d.isError&&(p.is_error=!0),d.as!==void 0&&(p.as=d.as);try{return await X(()=>t.answerChatToolCall({path:{chat_id:s,call_id:n},body:p})),!0}catch(_){if(_ instanceof I&&_.status===409)return!1;throw _}},async sendToSubagent(s,n,r,d={}){let p={client_id:d.clientId??ze(),text:r};d.as!==void 0&&(p.as=d.as);let _=await X(async()=>(await t.sendSubagentMessage({path:{chat_id:s,run_id:n},body:p})).data);return{runId:_.run_id,clientId:_.client_id}},async stopSubagent(s,n,r={}){return{runId:(await X(async()=>(await t.stopSubagent({path:{chat_id:s,run_id:n},body:r.as!==void 0?{as:r.as}:{},signal:r.signal})).data,r.signal)).run_id}},async fork(s,n){if(typeof n?.beforeMessage!="string"||n.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 r={before_message:n.beforeMessage};return n.title!==void 0&&(r.title=n.title),n.members!==void 0&&(r.members=n.members.map(We)),(await t.forkChat({path:{chat_id:s},body:r,signal:n.signal})).data},goal:{async set(s,n){let r={objective:n.objective};return n.rubric!==void 0&&(r.rubric=n.rubric),n.maxTurns!==void 0&&(r.max_turns=n.maxTurns),n.budget!==void 0&&(r.budget={max_cost_usd:n.budget.maxCostUsd}),n.as!==void 0&&(r.as=n.as),se((await t.setChatGoal({path:{chat_id:s},body:r,signal:n.signal})).data)},async get(s,n={}){return se((await t.getChatGoal({path:{chat_id:s},query:n.as!==void 0?{as:n.as}:void 0,signal:n.signal})).data)},async update(s,n){let r={};return n.status!==void 0&&(r.status=n.status),n.reason!==void 0&&(r.reason=n.reason),n.objective!==void 0&&(r.objective=n.objective),n.rubric!==void 0&&(r.rubric=n.rubric),n.maxTurns!==void 0&&(r.max_turns=n.maxTurns),n.budget!==void 0&&(r.budget=n.budget===null?null:{max_cost_usd:n.budget.maxCostUsd}),n.as!==void 0&&(r.as=n.as),se((await t.updateChatGoal({path:{chat_id:s},body:r,signal:n.signal})).data)},async clear(s,n={}){await t.clearChatGoal({path:{chat_id:s},query:n.as!==void 0?{as:n.as}:void 0,signal:n.signal})}},voice:{async start(s,n){if(typeof n?.sdp!="string"||!n.sdp.startsWith("v="))throw new TypeError("chats.voice.start: sdp is the app's WebRTC offer (an SDP, v=0 \u2026): its peer connection's localDescription.sdp");if(n.delegation!==void 0&&n.delegation!=="chat"&&n.delegation!=="events")throw new TypeError("chats.voice.start: delegation is chat (a turn of the chat) or events (ai.voice.delegated)");let r={sdp:n.sdp};n.voice!==void 0&&(r.voice=n.voice),n.delegation!==void 0&&(r.delegation=n.delegation),n.as!==void 0&&(r.as=n.as),n.instructions!==void 0&&(r.instructions=n.instructions),n.context!==void 0&&(r.context=n.context);let d=(await t.startChatVoice({path:{chat_id:s},body:r,signal:n.signal})).data;if(typeof d.sdp!="string"||d.sdp==="")throw new I({op:"startChatVoice",status:502,code:"no_answer",message:"the voice was started but its WebRTC answer was not given"});return{...K(d),sdp:d.sdp}},async get(s,n,r={}){return K((await t.getChatVoice({path:{chat_id:s,voice_id:n},query:r.as!==void 0?{as:r.as}:void 0,signal:r.signal})).data)},async command(s,n,r){if(!xt.includes(r?.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) or instruct (behave so)");if(typeof r.text!="string"||r.text==="")throw new TypeError("chats.voice.command: text is what the voice is given");if(r.delegationId!==void 0&&r.type!=="speak"&&r.type!=="tell")throw new TypeError("chats.voice.command: delegationId names the request a speak or a tell answers");if(r.interrupt!==void 0&&(typeof r.interrupt!="boolean"||r.type!=="speak"))throw new TypeError("chats.voice.command: interrupt is a speak's: it cuts what the voice is saying");let d={type:r.type,text:r.text};return r.delegationId!==void 0&&(d.delegation_id=r.delegationId),r.interrupt===!0&&(d.interrupt=!0),r.as!==void 0&&(d.as=r.as),K((await t.commandChatVoice({path:{chat_id:s,voice_id:n},body:d,signal:r.signal})).data)},async close(s,n,r={}){return K((await t.closeChatVoice({path:{chat_id:s,voice_id:n},query:r.as!==void 0?{as:r.as}:void 0,signal:r.signal})).data)}}},a={async put(s,n){let r=typeof s=="string"?s:F(s)?.name,d=typeof s=="string"?n:s;if(typeof r!="string"||!v.test(r))throw new TypeError("agents.put: name is lowercase letters, digits, _ and -, starting with a letter, at most 64 \u2014 or a backend's ai.agent");if(d===void 0)throw new TypeError(`agents.put(${JSON.stringify(r)}): its definition, or a backend's ai.agent`);let p,_=F(d);if(_){if(_.name!==r)throw new TypeError(`agents.put(${JSON.stringify(r)}): the backend's agent is named ${JSON.stringify(_.name)} \u2014 its machine is asked for it by that name`);p={backend:_.machine??"backend"}}else p=V(d,`agents.put(${JSON.stringify(r)})`);return(await t.putAgent({path:{name:r},body:p})).data},async list(){return(await t.listAgents({})).data.agents},async delete(s){await t.deleteAgent({path:{name:s}})}},i={async put(s,n){let r={kind:n.kind,url:n.url};return n.description!==void 0&&(r.description=n.description),n.parameters!==void 0&&(r.parameters=n.parameters),n.approval!==void 0&&(r.approval=n.approval),(await t.putEndpoint({path:{name:s},body:r})).data},async list(){return(await t.listEndpoints({})).data.endpoints},async delete(s){await t.deleteEndpoint({path:{name:s}})}},u={async get(){return Fe((await t.getSettings({})).data)},async put(s){let n={};return s.clients!==void 0&&(n.clients=s.clients),s.userMessagesPerMinute!==void 0&&(n.user_messages_per_minute=s.userMessagesPerMinute),s.historyLimitBytes!==void 0&&(n.history_limit_bytes=s.historyLimitBytes),Fe((await t.putSettings({body:n})).data)}},l=s=>({name:s.name,repository:s.repository,defaultBranch:s.default_branch,backend:s.backend,createdAt:s.created_at});return{chats:o,agents:a,endpoints:i,settings:u,repos:{async put(s,n){let r=typeof s=="string"?s:s.name;if(typeof r!="string"||!v.test(r))throw new TypeError("repos.put: name is lowercase letters, digits, _ and -, starting with a letter, at most 64");let d=typeof s=="string"?{repository:n?.repository??"",...n?.defaultBranch?{default_branch:n.defaultBranch}:{},...n?.backend?{backend:n.backend}:{}}:{repository:s.repository,default_branch:s.defaultBranch,...s.machine?{backend:s.machine}:{}};return l((await t.putRepo({path:{name:r},body:d})).data)},async list(s={}){let n=(await t.listRepos({query:{limit:s.limit,cursor:s.cursor}})).data,r=n.repos.map(l);return n.next_cursor===void 0?{repos:r}:{repos:r,nextCursor:n.next_cursor}},async delete(s){await t.deleteRepo({path:{name:s}})}}}}var Rt=/^pb_[a-z0-9]+_s/;function Ke(e){let t=globalThis;return t.process?.env?.[e]??t.Deno?.env?.get(e)}function oe(){return"ai_"+crypto.randomUUID()}function ie(e){if(e.prepared)return e;let t=e;return{name:"answer",schema:t,prepared:z(t,"answer")}}var Xe=4,Ct=/^[a-z][a-z0-9-]{1,62}$/,Ze=["image/png","image/jpeg","image/webp","image/gif"],He=5<<20,Ye=6<<20;function tt(e){let t="";for(let o=0;o<e.length;o+=32768)t+=String.fromCharCode(...e.subarray(o,o+32768));return btoa(t)}function Et(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 Pt(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>Xe)throw new TypeError(`a question takes ${Xe} pictures at most (got ${e.length})`);let t=0;return e.map((o,a)=>{let i=o??{};if("bytes"in i||o instanceof Uint8Array)throw new TypeError(`images[${a}]: a picture's bytes are { mediaType, data } \u2014 or, in the project's storage, { bucket, path }`);if("data"in i||"mediaType"in i){if(i.bucket!==void 0||i.path!==void 0||i.url!==void 0)throw new TypeError(`images[${a}] is { bucket, path }, { url } or { mediaType, data }: one of them`);if(typeof i.mediaType!="string"||!Ze.includes(i.mediaType))throw new TypeError(`images[${a}].mediaType is the picture's type: ${Ze.join(", ")}`);let u=i.data instanceof Uint8Array?tt(i.data):i.data,l=typeof u=="string"?Et(u):-1;if(l<0)throw new TypeError(`images[${a}].data is the picture's bytes: base64, or a Uint8Array`);if(l===0||l>He)throw new TypeError(`images[${a}] is ${l} bytes: a picture given by its bytes is 1 byte to ${He>>20} MiB`);if(t+=l,t>Ye)throw new TypeError(`the pictures given by their bytes are ${Ye>>20} MiB at most together: put a larger one in the project's storage and give { bucket, path }`);return{media_type:i.mediaType,data:u}}if(typeof i.url=="string"){if(i.bucket!==void 0||i.path!==void 0)throw new TypeError(`images[${a}] is { bucket, path } or { url }, not both`);let u;try{u=new URL(i.url)}catch{throw new TypeError(`images[${a}].url is not an address: ${JSON.stringify(i.url.slice(0,80))}`)}if(u.protocol!=="https:"||i.url.length>2048)throw new TypeError(`images[${a}].url is an https address of 2048 characters at most`);return{url:i.url}}if(typeof i.bucket!="string"||!Ct.test(i.bucket)||typeof i.path!="string"||i.path==="")throw new TypeError(`images[${a}] is { bucket, path } \u2014 a file of the project's storage \u2014 { url } or { mediaType, data }`);return{bucket:i.bucket,path:i.path}})}function Z(e,t={},o){if(e.prompt===void 0&&e.messages===void 0)throw new TypeError("ask a model something: prompt, or messages");let a={...t};if(e.prompt!==void 0&&(a.input=e.prompt),e.messages!==void 0&&(a.messages=e.messages),e.instructions!==void 0&&(a.instructions=e.instructions),e.model!==void 0&&(a.model=e.model),e.metadata!==void 0&&(a.metadata=e.metadata),e.images!==void 0&&(a.images=Pt(e.images)),e.tools!==void 0&&(a.tools=e.tools.map((i,u)=>{if(i?.source==="client")throw new TypeError(`tools[${u}]: ${i.name} is a client tool \u2014 an app answers it, in a chat; a one-shot answer has no app to wait for`);if(i?.source==="platform")throw new TypeError(`tools[${u}]: the platform's ${i.name} is a chat's agent's tool \u2014 a one-shot answer is given none`);let l=J(i,`tools[${u}]`);return l.source==="backend"&&l.machine===void 0&&o!==void 0&&(l.machine=o),l})),e.maxToolCalls!==void 0){if(!e.tools?.length)throw new TypeError("maxToolCalls bounds the calls of the tools given: give tools");a.max_tool_calls=ae(e.maxToolCalls,"ask")}return a}var $=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 It(e){let t=Uint8Array.from(atob(e),i=>i.charCodeAt(0)),o=new DataView(t.buffer,t.byteOffset,t.byteLength),a=new Array(t.byteLength/4);for(let i=0;i<a.length;i++)a[i]=o.getFloat32(i*4,!0);return a}async function Qe(e){let t,o;return e instanceof Uint8Array?(t=e,o=et(t)):typeof Blob<"u"&&e instanceof Blob?(t=new Uint8Array(await e.arrayBuffer()),o=e.type||et(t)):(t=e.bytes,o=e.mediaType),{media_type:o,data:tt(t)}}function et(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 $t(e){let t=e.url??Ke("PALBASE_URL"),o=e.secretKey??Ke("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 o!="string"||!Rt.test(o))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 a=ge(le({baseUrl:t,credentials:{secretKey:o},fetch:e.fetch}),e.retry??pe);return ue.client(a)}function Mt(e){return new Proxy({},{get:(t,o)=>e.ai[o]})}function Ot(e={}){if(we())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&&!v.test(e.machine))throw new TypeError("machine is the name of one of the project's machines");let t=e.server?Mt(e.server):$t(e),o=e.resumeFor??12e4;async function a(c,g,h=oe()){return L(t.createResponse({headers:{"Idempotency-Key":h},body:c,signal:g}))}async function i(c,g={}){return(await t.getResponse({path:{response_id:c},signal:g.signal})).data}async function u(c,g,h,y,k){let T=0,S=c,R=oe(),O=()=>Date.now()+o,j=O();for(let B=0;;B++)try{if(S||(g===null?S=(await a({...k,stream:!0},y,R)).data:S=(await t.followResponse({path:{response_id:g},query:{offset:T},signal:y})).data),!S.body)throw new Error("the stream has no body");for await(let w of be(S.body)){let A=JSON.parse(w.data);switch(w.event){case"response":g===null&&(g=A.id,h.admitted(A));break;case"delta":{let M=A.offset+me(A.text);if(M>T){let H=A.offset>=T?A.text:ye(A.text,T-A.offset);h.delta(T,H),T=M}j=O();break}case"reset":A.offset<T&&(T=A.offset,h.reset(T));break;case"terminal":return A}}throw new Error("the stream ended before its answer did")}catch(w){if(S=null,y?.aborted||w instanceof I&&w.status>0&&w.status<500&&w.status!==429||g===null&&!(w instanceof I)||Date.now()>j)throw w;await new Promise(A=>setTimeout(A,Math.min(250*2**Math.min(B,4),4e3)))}}function l(c){if(c.status!=="completed")throw new $(c);return c.text??""}function m(c,g){let h=Z(c,g?{schema:g.prepared.json,schema_name:g.name}:{},e.machine),y=[],k=!1,T,S=null,R=()=>{let f=S;S=null,f?.()},O,j,B=new Promise((f,x)=>{O=f,j=x});B.catch(()=>{});let w="",A=u(null,null,{admitted:f=>O(f.id),delta:(f,x)=>{w+=x,y.push(x),R()},reset:f=>{let x=he(w,f);w=w.slice(0,x),y.push("\0reset:"+x),R()}},c.signal,h).then(f=>{let x=f.status==="completed"?f.text??"":"";return x.length>w.length&&x.startsWith(w)&&(y.push(x.slice(w.length)),w=x),k=!0,R(),f},f=>{throw k=!0,T=f,j(f),R(),f});A.catch(()=>{});async function*M(){for(let f=0;;f++){for(;f>=y.length;){if(k){if(T)throw T;return}await new Promise(x=>S=x)}yield y[f]}}async function*H(){for await(let f of M())f.startsWith("\0reset:")||(yield f)}async function*nt(){let f="",x="";for await(let N of M()){N.startsWith("\0reset:")?f=f.slice(0,Number(N.slice(7))):f+=N;let E=ee(f);if(E===void 0)continue;let P=JSON.stringify(E);P!==x&&(x=P,yield E)}}let D=A.then(f=>{if(f.status!=="completed")throw new $(f);return f});D.catch(()=>{});let de=g?D.then(f=>g.prepared.check(f.output)):Promise.reject(new TypeError("object is a schema stream's"));de.catch(()=>{});let ce=D.then(f=>f.text??w);return ce.catch(()=>{}),{id:B,response:D,text:ce,get textStream(){return H()},get partialObjectStream(){return nt()},object:de,toResponse(f={}){let x=new TextEncoder,N=new ReadableStream({async start(P){try{for await(let U of M())U.startsWith("\0reset:")?P.enqueue(x.encode(`event: reset
|
|
8
8
|
data: ${JSON.stringify({offset:Number(U.slice(7))})}
|
|
9
9
|
|
|
10
|
-
`)):P.enqueue(
|
|
10
|
+
`)):P.enqueue(x.encode(`data: ${JSON.stringify({text:U})}
|
|
11
11
|
|
|
12
|
-
`));let C=await D;P.enqueue(
|
|
12
|
+
`));let C=await D;P.enqueue(x.encode(`event: done
|
|
13
13
|
data: ${JSON.stringify({id:C.id,text:C.text,output:C.output,usage:C.usage})}
|
|
14
14
|
|
|
15
|
-
`))}catch(C){let U=C instanceof $||C instanceof I?C.code:"stream_failed";P.enqueue(
|
|
15
|
+
`))}catch(C){let U=C instanceof $||C instanceof I?C.code:"stream_failed";P.enqueue(x.encode(`event: error
|
|
16
16
|
data: ${JSON.stringify({code:U})}
|
|
17
17
|
|
|
18
|
-
`))}finally{P.close()}}}),E=new Headers(f.headers);return E.set("content-type","text/event-stream"),E.set("cache-control","no-store"),E.set("x-accel-buffering","no"),new globalThis.Response(N,{...f,headers:E})}}}async function s(c,g){return u(null,null,{admitted:()=>{},delta:()=>{},reset:()=>{}},c.signal,Z(c,g,e.machine))}let{chats:n,agents:r,endpoints:d,settings:p,repos:
|
|
18
|
+
`))}finally{P.close()}}}),E=new Headers(f.headers);return E.set("content-type","text/event-stream"),E.set("cache-control","no-store"),E.set("x-accel-buffering","no"),new globalThis.Response(N,{...f,headers:E})}}}async function s(c,g){return u(null,null,{admitted:()=>{},delta:()=>{},reset:()=>{}},c.signal,Z(c,g,e.machine))}let{chats:n,agents:r,endpoints:d,settings:p,repos:_}=Ve(t);return{module:t,chats:n,agents:r,endpoints:d,settings:p,repos:_,tool:je,clientTool:Be,deferred:$e,agent:Ue,repo:De,repoTokens:Ne,async ask(c,g={}){let h=typeof c=="string"?{...g,prompt:c}:c;return l(await s(h,{}))},async generate(c){let g=ie(c.schema),h={schema:g.prepared.json,schema_name:g.name};if(c.background){let T=(await a(Z(c,{...h,background:!0},e.machine),c.signal)).data;return{id:T.id,status:T.status}}let y=await s(c,h);if(y.status!=="completed")throw new $(y);return g.prepared.check(y.output)},stream(c){return m(c,c.schema?ie(c.schema):void 0)},async start(c){let g=(await a(Z(c,{background:!0},e.machine),c.signal)).data;return{id:g.id,status:g.status}},schema(c,g){return{name:c,schema:g,prepared:z(g,c)}},response:i,async result(c,g){let h=ie(g),y=await i(c);if(y.status!=="completed")throw new $(y);return h.prepared.check(y.output)},async cancel(c){return(await t.cancelResponse({path:{response_id:c}})).data},async embed(c,g={}){let h=Array.isArray(c)?c:[c],y=[];for(let k=0;k<h.length;k+=1024){let T=await t.createEmbeddings({body:{input:h.slice(k,k+1024),model:g.model,dimensions:g.dimensions},signal:g.signal});for(let S of T.data.vectors)y.push(It(S))}return Array.isArray(c)?y:y[0]},async image(c){let g={prompt:c.prompt};for(let k of["model","size","quality","background","format","count"])c[k]!==void 0&&(g[k]=c[k]);c.references?.length&&(g.references=await Promise.all(c.references.map(Qe))),c.mask&&(g.mask=await Qe(c.mask));let h=(await t.createImage({headers:{"Idempotency-Key":oe()},body:g,signal:c.signal})).data;for(let k=0;h.status==="running";k++){if(await new Promise(T=>setTimeout(T,Math.min(500+k*250,3e3))),c.signal?.aborted)throw c.signal.reason;h=(await t.getImage({path:{image_id:h.id},signal:c.signal})).data}if(h.status!=="completed")throw new Error(`the image failed: ${h.error?.code??"image_failed"}: ${h.error?.message??""}`);let y=await Promise.all(h.files.map(async k=>{let S=(await t.getImageFile({path:{image_id:h.id,position:k.position},signal:c.signal})).data;return{mediaType:k.media_type,bytes:new Uint8Array(await S.arrayBuffer())}}));return{id:h.id,model:h.model,pictures:y,costNanoUSD:h.usage?.cost_nano_usd??0,save(k,T,S=0){let R=y[S];if(!R)throw new RangeError(`the job made ${y.length} picture(s)`);return k.upload(T,R.bytes,{contentType:R.mediaType})}}},async models(){return(await t.listModels({})).data},async usage(c={}){let g=c.metadata===void 0?void 0:JSON.stringify(c.metadata),h=(await t.listUsage({query:{kind:c.kind,limit:c.limit,cursor:c.cursor,metadata:g}})).data;return{usage:h.usage,nextCursor:h.next_cursor}},async connectProvider(c,g){return(await t.connectProvider({path:{provider:c},body:{key:g}})).data},async disconnectProvider(c){await t.disconnectProvider({path:{provider:c}})}}}export{ee as a,b,z as c,ne as d,$ as e,Ot as f};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
/*! palbase 0.13.1 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
var K="pbt1.",E="Palbase-Encryption";var z="x-palbase-encrypted",o=class extends Error{code;constructor(t,n){super(n),this.name="TransitError",this.code=t}},h=new TextEncoder,P=new TextDecoder("utf-8",{fatal:!0}),l=()=>{let e=globalThis.crypto?.subtle;if(!e)throw new Error("encrypted fields need WebCrypto (crypto.subtle): a secure context \u2014 https, or localhost");return e};function y(e){return new Uint8Array(new ArrayBuffer(e))}function f(...e){let t=y(e.reduce((r,i)=>r+i.length,0)),n=0;for(let r of e)t.set(r,n),n+=r.length;return t}function d(e){return f(e)}function m(e,t){let n=y(t);for(let r=t-1;r>=0;r--)n[r]=e&255,e>>>=8;return n}function x(e){let t="";for(let n of e)t+=String.fromCharCode(n);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function w(e){let t=e.replace(/=+$/,"");if(!/^[A-Za-z0-9_-]*$/.test(t)||t.length%4===1)throw new o("malformed","not base64url");let n=atob(t.replace(/-/g,"+").replace(/_/g,"/")+"=".repeat((4-t.length%4)%4)),r=y(n.length);for(let i=0;i<n.length;i++)r[i]=n.charCodeAt(i);return r}var S=f(h.encode("KEM"),m(32,2)),g=f(h.encode("HPKE"),m(32,2),m(1,2),m(1,2)),v=h.encode("HPKE-v1"),X=16,H=12,T=32,$=Uint8Array.from([48,46,2,1,0,48,5,6,3,43,101,110,4,34,4,32]);async function N(e,t){let n=await l().importKey("raw",e.length===0?y(32):d(e),{name:"HMAC",hash:"SHA-256"},!1,["sign"]);return new Uint8Array(await l().sign("HMAC",n,d(t)))}async function k(e,t,n,r){return N(t,f(v,e,h.encode(n),r))}async function U(e,t,n,r,i){let a=f(m(i,2),v,e,h.encode(n),r),s=y(i),c=y(0);for(let u=1,p=0;p<i;u++)c=await N(t,f(c,a,Uint8Array.of(u))),s.set(c.subarray(0,Math.min(c.length,i-p)),p),p+=c.length;return s}async function j(e){if(e.length!==32)throw new o("malformed","an X25519 private key is 32 bytes");return l().importKey("pkcs8",f($,e),{name:"X25519"},!1,["deriveBits"])}async function C(e){if(e.length!==32)throw new o("malformed","an X25519 public key is 32 bytes");return l().importKey("raw",d(e),{name:"X25519"},!1,[])}async function O(e,t){return new Uint8Array(await l().deriveBits({name:"X25519",public:t},e,256))}async function R(e,t,n){let r=await k(S,y(0),"eae_prk",e);return U(S,r,"shared_secret",f(t,n),T)}async function _(e,t){let n=await k(g,y(0),"psk_id_hash",y(0)),r=await k(g,y(0),"info_hash",t),i=f(Uint8Array.of(0),n,r),a=await k(g,e,"secret",y(0));return{key:await U(g,a,"key",i,X),nonce:await U(g,a,"base_nonce",i,H)}}async function b(e,t,n,r,i){let a=await l().importKey("raw",d(t),"AES-GCM",!1,[e]);return new Uint8Array(await l()[e]({name:"AES-GCM",iv:d(n),additionalData:d(r)},a,d(i)))}async function V(e,t,n,r=y(0),i){let a,s;if(i)a=await j(i.privateKey),s=d(i.publicKey);else{let B=await l().generateKey({name:"X25519"},!0,["deriveBits"]);a=B.privateKey,s=new Uint8Array(await l().exportKey("raw",B.publicKey))}let c=await R(await O(a,await C(e)),s,e),{key:u,nonce:p}=await _(c,t);return{enc:s,ct:await b("encrypt",u,p,r,n)}}async function q(e,t,n,r,i,a=y(0)){if(n.length!==32)throw new o("malformed","an encapsulated X25519 key is 32 bytes");try{let s=await R(await O(await j(e),await C(n)),n,t),{key:c,nonce:u}=await _(s,r);return await b("decrypt",c,u,a,i)}catch{throw new o("unopenable","the request's key does not open with the project's key it names")}}async function Z(e){let t=await l().importKey("pkcs8",f($,e),{name:"X25519"},!0,["deriveBits"]),n=await l().exportKey("jwk",t);return w(n.x)}function Q(e,t,n,r=[]){if(r.some(i=>i.includes("\0")))throw new o("malformed","a path's value holds no NUL");return h.encode(["palbase-encryption","1",e,t.toUpperCase(),L(n),...r].join("\0"))}function L(e){return e.replace(/\{[^/{}]*\}/g,"{}")}async function Y(e,t,n,r={}){let i=r.key?d(r.key):crypto.getRandomValues(y(32)),{enc:a,ct:s}=await V(t,n,i,y(0),r.ephemeral);return{kid:e,key:i,header:`1.${e}.${x(a)}.${x(s)}`}}function J(e){let t=e.trim().split(".");if(t.length!==4||t[0]!=="1"||!/^t[1-9][0-9]{0,5}$/.test(t[1]))throw new o("malformed",`${E} is 1.<key id>.<enc>.<ct>`);let n=w(t[2]),r=w(t[3]);if(n.length!==32||r.length!==48)throw new o("malformed",`${E} carries a 32-byte encapsulated key and a sealed 32-byte key`);return{kid:t[1],enc:n,ct:r}}async function ee(e,t,n,r){let{enc:i,ct:a}=J(e),s=await q(t,n,i,r,a);if(s.length!==32)throw new o("unopenable","the request's key is not 32 bytes");return s}function I(e){return h.encode(`pbt1\0${e}`)}async function te(e,t,n,r){let i=r?d(r):crypto.getRandomValues(y(12)),a=JSON.stringify(n);if(a===void 0)throw new o("malformed",`${t}: an encrypted field holds a JSON value`);let s=await b("encrypt",e,i,I(t),h.encode(a));return K+x(f(i,s))}function F(e){return typeof e=="string"&&e.startsWith(K)}async function ne(e,t,n){if(!F(n))throw new o("unopenable",`${t} is not an encrypted field`);let r;try{r=w(n.slice(K.length))}catch{throw new o("unopenable",`${t} is not an encrypted field`)}if(r.length<28)throw new o("unopenable",`${t} is too short to be an encrypted field`);let i;try{i=await b("decrypt",e,r.subarray(0,12),I(t),r.subarray(12))}catch{throw new o("unopenable",`${t} does not open: changed, moved from another field, or another request's`)}try{return JSON.parse(P.decode(i))}catch{throw new o("unopenable",`${t} opens to no JSON value`)}}function D(e){return e.replace(/~/g,"~0").replace(/\//g,"~1").replace(/\*/g,"~2")}function G(e){return e.replace(/~2/g,"*").replace(/~1/g,"/").replace(/~0/g,"~")}var M=Symbol("items");function W(e,t){if(!(e!==t&&!e.startsWith(t+"/")))return e===t?[]:e.slice(t.length+1).split("/").map(n=>n==="*"?M:G(n))}async function re(e,t,n,r){let i=e;for(let a of n){let s=W(a,t);s!==void 0&&(i=await A(i,s,t,r))}return i}async function A(e,t,n,r){if(t.length===0)return e===void 0?void 0:r(n,e);let[i,...a]=t;if(i===M){if(!Array.isArray(e))return e;let c=[];for(let[u,p]of e.entries())c.push(await A(p,a,`${n}/${u}`,r));return c}if(Array.isArray(e)){if(!/^(0|[1-9][0-9]*)$/.test(i)||Number(i)>=e.length)return e;let c=[...e];return c[Number(i)]=await A(c[Number(i)],a,`${n}/${i}`,r),c}if(typeof e!="object"||e===null||Array.isArray(e)||!Object.hasOwn(e,i))return e;let s={...e};return s[i]=await A(s[i],a,`${n}/${D(i)}`,r),s}function ie(){return x(crypto.getRandomValues(y(16)))}async function se(e,t,n,r){let i,a=!1;try{i=w(e.payload);let u=await l().importKey("raw",w(t),{name:"Ed25519"},!1,["verify"]);a=await l().verify({name:"Ed25519"},u,w(e.signature),i)}catch{throw new o("unverified","the project's key list does not verify")}if(!a)throw new o("unverified","the project's key list is not signed with the project's key");let s;try{s=JSON.parse(P.decode(i))}catch{throw new o("unverified","the project's key list is no JSON")}if(s.v!==1||s.project!==n||typeof s.issued_at!="string"||!Array.isArray(s.keys)||s.keys.length===0)throw new o("unverified","the key list is not this project's, or holds no key");if(s.nonce!==r)throw new o("unverified","the key list was not asked for just now: its nonce is not the one sent");let c=s.keys.map(u=>{if(typeof u.kid!="string"||!/^t[1-9][0-9]{0,5}$/.test(u.kid)||typeof u.key!="string")throw new o("unverified","a key of the list is malformed");let p=w(u.key);if(p.length!==32)throw new o("unverified","a key of the list is not an X25519 public key");return{kid:u.kid,key:p}});return{project:s.project,issuedAt:s.issued_at,keys:c}}export{E as a,z as b,o as c,w as d,Z as e,Q as f,Y as g,J as h,ee as i,te as j,F as k,ne as l,D as m,G as n,re as o,ie as p,se as q};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
2
|
-
import{b as c,f as u}from"./
|
|
1
|
+
/*! palbase 0.13.1 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{b as c,f as u}from"./2J3RT5GV.js";var l={attempts:3,maxWaitSeconds:30},y=new Set([429,502,503,504]);function x(e,t=l){let r=t.sleep??h;return{async send(o){let n=p(o),a=n.body,m=!a||a.kind!=="raw"||u(a.value),f=(n.method==="GET"||n.method==="HEAD"||n.idempotent===!0)&&m;for(let i=1;;i++)try{return await e.send(n)}catch(s){if(!f||i>=t.attempts||!(s instanceof c)||n.signal?.aborted)throw s;let d=b(s,i,t.maxWaitSeconds);if(d===void 0)throw s;await r(d*1e3,n.signal)}}}}function p(e){return e.idempotent?Object.entries(e.headers??{}).some(([r,o])=>r.toLowerCase()==="idempotency-key"&&o!==void 0&&o!==null&&o!=="")?e:{...e,headers:{...e.headers,"Idempotency-Key":w()}}:e}function b(e,t,r){return y.has(e.status)||e.code==="network_error"?e.retryAfter!==void 0?e.retryAfter<=r?e.retryAfter:void 0:Math.min(.5*2**(t-1),r)*(.8+Math.random()*.4):void 0}function h(e,t){return new Promise((r,o)=>{if(t?.aborted)return o(t.reason);let n=()=>{clearTimeout(a),o(t?.reason)},a=setTimeout(()=>{t?.removeEventListener("abort",n),r()},e);t?.addEventListener("abort",n,{once:!0})})}function w(){if(typeof crypto.randomUUID=="function")return crypto.randomUUID();let e=crypto.getRandomValues(new Uint8Array(16));e[6]=e[6]&15|64,e[8]=e[8]&63|128;let t=[...e].map(r=>r.toString(16).padStart(2,"0")).join("");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}export{l as a,x as b,b as c,w as d};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
2
|
-
import{e as Re,g as Ae,h as Oe}from"./V2FEPVVD.js";import{h as Ce}from"./ZZG7ICDG.js";import{a as Ee}from"./3453XVQL.js";import{r as xe,t as Pe,u as Te}from"./3VY3ZZCI.js";import{b as V,c as K,e as Se,g as j,h as _e}from"./7WIMZTYB.js";import{a as Ie,b as F}from"./R3EIGCWV.js";import{b as I,d as U}from"./KNPQNBC2.js";function ht(n){let e=n,t=e?.body,s=t&&typeof t=="object"?t.reason:void 0;return s==="user_deleted"?"userDeleted":s==="user_banned"?"userBanned":e?.code==="session_expired"||e?.code==="token_expired"?"expired":"revoked"}var T=class extends Error{code="session_changed";constructor(e){super(e),this.name="SessionChangedError"}};function Me(){let n=null;return{load:()=>n,save:e=>{n=e},clear:()=>{n=null},shared:!1}}function Ne(n){let e=null,t=!0,s=()=>{try{return globalThis.localStorage}catch{return}};return{shared:!0,load(){try{let i=s()?.getItem(n);return i==null?t?null:e:JSON.parse(i)}catch{return e}},save(i){e=i;try{let r=s();if(!r)throw new Error("no storage");r.setItem(n,JSON.stringify(i)),t=!0}catch{t=!1}},clear(){e=null,t=!0;try{s()?.removeItem(n)}catch{}},watch(i){let r=globalThis;if(typeof r.addEventListener!="function")return()=>{};let a=o=>{(o.key===n||o.key===null)&&i()};return r.addEventListener("storage",a),()=>r.removeEventListener?.("storage",a)}}}function fe(n){try{let e=n.split(".")[1]??"",t=atob(e.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(e.length/4)*4,"=")),s=JSON.parse(t).sub;return typeof s=="string"?s:""}catch{return""}}var pt=6e4,ft=15e3;function gt(n,e,t){let s=n?globalThis.navigator?.locks:void 0;return s?s.request(e,t):t()}var W=class{current=null;loaded;inflight=null;endReason=null;listeners=new Set;store;refresher;isRejected;now;lockName;refreshTimeoutMs;mode;constructor(e,t,s,i={}){this.store=e,this.refresher=t,this.isRejected=s,this.now=i.now??Date.now,this.lockName=i.lockName??"palbase.session.refresh",this.refreshTimeoutMs=i.refreshTimeoutMs??ft,this.mode=i.refresh??"behind",this.loaded=Promise.resolve(e.load()).then(r=>{this.current=r}),e.watch?.(()=>{this.reconcile()})}async session(){return await this.loaded,this.current}snapshot(){return this.current}onChange(e){return this.listeners.add(e),()=>this.listeners.delete(e)}async set(e,t,s){await this.loaded;let i=t==="TOKEN_REFRESHED"?this.current:null,r={accessToken:e.access_token,refreshToken:e.refresh_token,expiresAt:this.now()+e.expires_in*1e3,userId:s?.id??i?.userId??fe(e.access_token),user:s??i?.user};return this.current=r,await this.store.save(r),this.emit(t,r),r}async setUser(e,t){await this.loaded,!(!this.current||!t||this.current.userId!==t.userId)&&(this.current={...this.current,user:e},await this.store.save(this.current),this.emit("USER_UPDATED",this.current))}async clear(e,t){await this.loaded;let s=this.current;this.current=null,this.inflight=null;let i=await this.store.load();(!i||!s||i.userId===s.userId)&&await this.store.clear(),s&&(e==="SESSION_EXPIRED"&&(this.endReason=t??"revoked"),this.emit(e,null))}async accessToken(){await this.loaded;let e=this.current;if(!e)return;let t=e.expiresAt-this.now();if(t>pt)return e.accessToken;if(this.mode==="never")return t>0?e.accessToken:void 0;if(t>0&&this.mode==="behind")return this.refresh().catch(()=>{}),e.accessToken;if(t>0)try{return(await this.refresh()).accessToken}catch(s){if(this.current===e)return e.accessToken;throw s}return(await this.refresh()).accessToken}refresh(){if(this.mode==="never")return Promise.reject(new Error("this client does not renew its session (refresh: 'never'): where the session cannot be written back, the request's middleware renews it"));if(this.inflight)return this.inflight;let e=gt(this.store.shared===!0,this.lockName,async()=>{await this.loaded;let t=this.current;if(!t)throw new T("no session to refresh");let s=await this.adoptStored(t);if(s)return s;try{let i=await this.withTimeout(this.refresher(t.refreshToken));if(this.current?.refreshToken!==t.refreshToken)throw new T("the session changed while it was refreshed");return await this.set(i,"TOKEN_REFRESHED")}catch(i){throw this.isRejected(i)&&this.current?.refreshToken===t.refreshToken&&await this.clear("SESSION_EXPIRED",ht(i)),i}});return this.inflight=e,e.finally(()=>{this.inflight===e&&(this.inflight=null)}).catch(()=>{}),e}async adoptStored(e){let t=await this.store.load();if(!t)throw this.current=null,this.emit("SIGNED_OUT",null),new T("signed out in another tab");if(t.userId!==e.userId)throw this.current=t,this.emit("SIGNED_OUT",null),this.emit("SIGNED_IN",t),new T("another user signed in in another tab");if(t.refreshToken!==e.refreshToken&&t.expiresAt>=e.expiresAt)return this.current=t,this.emit("TOKEN_REFRESHED",t),t}async reconcile(){await this.loaded;let e=this.current,t=await this.store.load();if(!e){t&&(this.current=t,this.emit("SIGNED_IN",t));return}await this.adoptStored(e).catch(()=>{})}withTimeout(e){let t,s=new Promise((i,r)=>{t=setTimeout(()=>r(new Error(`the refresh did not answer within ${this.refreshTimeoutMs/1e3} s`)),this.refreshTimeoutMs)});return Promise.race([e,s]).finally(()=>clearTimeout(t))}emit(e,t){(e==="SIGNED_IN"||e==="SIGNED_OUT")&&(this.endReason=null);for(let s of this.listeners)try{s(e,t)}catch{}}};var ge=class{state="closed";refusal;logSeq;joinRef=null;listeners=new Map;closers=new Set;joinWaiters=[];name;socket;constructor(e,t,s={}){this.name=e,this.socket=t,this.logSeq=s.after}get topic(){return`realtime:${this.name}`}join(){if(this.state==="joined")return Promise.resolve();let e=new Promise((t,s)=>this.joinWaiters.push({resolve:t,reject:s}));return this.state!=="joining"&&this.socket.join(this),e}leave(){this.socket.leave(this)}push(e,t){return this.socket.request(this,e,t)}on(e,t){let s=this.listeners.get(e);return s||this.listeners.set(e,s=new Set),s.add(t),()=>s.delete(t)}onClosed(e){return this.closers.add(e),()=>this.closers.delete(e)}deliver(e,t){e==="broadcast"&&typeof t.seq=="number"&&(this.logSeq=t.seq);for(let s of this.listeners.get(e)??[])try{s(t)}catch{}}settled(e,t){e&&typeof t.log_seq=="number"&&(this.logSeq=t.log_seq),this.state=e?"joined":"refused",this.refusal=e?void 0:t;let s=this.joinWaiters.splice(0);for(let i of s)e?i.resolve():i.reject(new Error(`join ${this.name} refused: ${JSON.stringify(t)}`))}closed(e){this.state="closed",this.joinRef=null;let t=this.joinWaiters.splice(0);for(let s of t)s.reject(new Error(`join ${this.name}: ${e}`));for(let s of[...this.closers])try{s()}catch{}}},B=class{ws=null;opening=null;ref=0;channels=new Map;replies=new Map;heartbeat=null;heartbeatRef=null;reconnectTimer=null;attempts=0;closedByUs=!1;reconnects=0;opts;constructor(e){this.opts=e}channel(e,t){let s=this.channels.get(e);return s||this.channels.set(e,s=new ge(e,this,t)),s}disconnect(){this.closedByUs=!0,this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=null,this.stopHeartbeat();let e=this.ws;this.ws=null,this.opening=null,e?.close(1e3);for(let[,t]of this.replies)t("error",{reason:"socket closed"});this.replies.clear();for(let t of this.channels.values())t.closed("the socket was closed")}async tokenChanged(){if(!this.ws||this.ws.readyState!==1)return;let e=await this.opts.accessToken();if(e)for(let t of this.channels.values())t.state==="joined"&&this.push(t.joinRef,t.topic,"access_token",{access_token:e})}join(e){e.state="joining",this.open().then(()=>this.sendJoin(e)).catch(t=>e.settled(!1,{reason:t instanceof Error?t.message:String(t)}))}leave(e){e.state==="joined"&&this.ws?.readyState===1&&this.push(e.joinRef,e.topic,"phx_leave",{}),e.state="closed",this.channels.delete(e.name)}async request(e,t,s){let i=this.ws;if(this.channels.get(e.name)!==e||e.state!=="joined"||i?.readyState!==1)return{status:"error",response:{reason:"not joined"}};let r=this.nextRef(),a=JSON.stringify([e.joinRef,r,e.topic,t,s]),o=this.awaitReply(r);return i.send(a),o}open(){if(this.ws?.readyState===1)return Promise.resolve();if(this.opening)return this.opening;this.closedByUs=!1;let e=this.opts.webSocket??globalThis.WebSocket,t=`${this.opts.baseUrl.replace(/^http/,"ws")}/realtime/v1/websocket?vsn=2.0.0&apikey=${encodeURIComponent(this.opts.publishableKey)}`,s=new Promise((i,r)=>{let a=new e(t);this.ws=a,a.onopen=()=>{this.attempts=0,this.startHeartbeat(),i()},a.onmessage=o=>this.receive(String(o.data)),a.onerror=()=>r(new Error("the realtime socket could not be opened")),a.onclose=()=>this.dropped(a)});return this.opening=s,s.finally(()=>{this.opening===s&&(this.opening=null)}).catch(()=>{}),s}dropped(e){if(this.ws!==e)return;this.ws=null,this.stopHeartbeat();for(let[,i]of this.replies)i("error",{reason:"socket closed"});this.replies.clear();for(let i of this.channels.values())i.state==="joined"&&(i.state="joining");if(this.closedByUs||![...this.channels.values()].some(i=>i.state==="joining"))return;let t=this.opts.backoff??[500,1e3,2e3,5e3,1e4,3e4],s=t[Math.min(this.attempts,t.length-1)]*(.8+Math.random()*.4);this.attempts++,this.reconnectTimer=J(setTimeout(()=>{this.reconnectTimer=null,this.reconnects++;let i=[...this.channels.values()].filter(r=>r.state==="joining");this.open().then(()=>Promise.all(i.map(r=>this.sendJoin(r)))).catch(()=>{})},s))}async sendJoin(e){let t=await this.opts.accessToken(),s=this.nextRef();e.joinRef=s;let i=this.awaitReply(s),r={broadcast:{self:!1}};e.logSeq!==void 0&&(r.log={after:e.logSeq}),this.push(s,e.topic,"phx_join",{access_token:t,config:r},s);let{status:a,response:o}=await i;if(this.channels.get(e.name)!==e||e.state!=="joining"){a==="ok"&&this.ws?.readyState===1&&this.push(s,e.topic,"phx_leave",{});return}e.settled(a==="ok",o)}awaitReply(e){return new Promise(t=>{let s=J(setTimeout(()=>{this.replies.delete(e),t({status:"timeout",response:{reason:"no reply"}})},this.opts.replyTimeoutMs??1e4));this.replies.set(e,(i,r)=>{clearTimeout(s),this.replies.delete(e),t({status:i,response:r})})})}receive(e){let t;try{t=JSON.parse(e)}catch{return}if(!Array.isArray(t)||t.length!==5||typeof t[2]!="string"||typeof t[3]!="string")return;let[,s,i,r,a]=t,o=typeof a=="object"&&a!==null?a:{};if(r==="phx_reply"&&typeof s=="string"){if(s===this.heartbeatRef){this.heartbeatRef=null;return}this.replies.get(s)?.(String(o.status),o.response??{});return}let c=[...this.channels.values()].find(l=>l.topic===i);if(c){if(r==="phx_close"){c.state="closed";return}if(r==="phx_error"){c.state="joining",J(setTimeout(()=>this.channels.get(c.name)===c&&c.state==="joining"&&this.ws?.readyState===1&&void this.sendJoin(c),1e3));return}c.deliver(r,o)}}push(e,t,s,i,r=this.nextRef()){this.ws?.send(JSON.stringify([e,r,t,s,i]))}nextRef(){return String(++this.ref)}startHeartbeat(){this.stopHeartbeat(),this.heartbeat=J(setInterval(()=>{if(this.heartbeatRef!==null){this.heartbeatRef=null,this.ws?.close(4e3);return}this.heartbeatRef=this.nextRef(),this.push(null,"phoenix","heartbeat",{},this.heartbeatRef)},this.opts.heartbeatMs??25e3))}stopHeartbeat(){this.heartbeat&&clearInterval(this.heartbeat),this.heartbeat=null,this.heartbeatRef=null}};function J(n){return n.unref?.(),n}var A="X-Palbase-Installation-Secret",z="X-Palbase-Installation",De=new WeakMap;function O(n){return De.get(n)}var Ue=new WeakSet;function Ke(n){return Ue.has(n)}var yt=/^[A-Za-z0-9_-]{43}$/,X=class{id;constructor(e){let t=`palbase.installation.secret.${e}`,s;try{let i=Le()?.getItem(t);i&&yt.test(i)&&(s=i)}catch{}if(!s){Ue.add(this),s=je(crypto.getRandomValues(new Uint8Array(32)));try{Le()?.setItem(t,s)}catch{}}De.set(this,s),this.id=mt(s)}};function mt(n){return je(wt(new TextEncoder().encode(n)).subarray(0,16))}function Le(){try{return globalThis.localStorage}catch{return}}function je(n){let e="";for(let t of n)e+=String.fromCharCode(t);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}var vt=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),E=(n,e)=>n>>>e|n<<32-e;function wt(n){let e=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),t=new Uint8Array(Math.ceil((n.length+9)/64)*64);t.set(n),t[n.length]=128;let s=new DataView(t.buffer);s.setUint32(t.length-8,Math.floor(n.length/536870912)),s.setUint32(t.length-4,n.length*8>>>0);let i=new Uint32Array(64);for(let o=0;o<t.length;o+=64){for(let g=0;g<16;g++)i[g]=s.getUint32(o+g*4);for(let g=16;g<64;g++){let m=E(i[g-15],7)^E(i[g-15],18)^i[g-15]>>>3,k=E(i[g-2],17)^E(i[g-2],19)^i[g-2]>>>10;i[g]=i[g-16]+m+i[g-7]+k|0}let[c,l,d,y,f,b,S,u]=e;for(let g=0;g<64;g++){let m=u+(E(f,6)^E(f,11)^E(f,25))+(f&b^~f&S)+vt[g]+i[g]|0,k=(E(c,2)^E(c,13)^E(c,22))+(c&l^c&d^l&d)|0;u=S,S=b,b=f,f=y+m|0,y=d,d=l,l=c,c=m+k|0}e[0]+=c,e[1]+=l,e[2]+=d,e[3]+=y,e[4]+=f,e[5]+=b,e[6]+=S,e[7]+=u}let r=new Uint8Array(32),a=new DataView(r.buffer);for(let o=0;o<8;o++)a.setUint32(o*4,e[o]);return r}var kt=30*6e4,$e=1e3,St=100,_t=60*1024,Y=()=>globalThis.crypto?.randomUUID?globalThis.crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;function D(){try{return globalThis.localStorage}catch{return}}var Q=class{api;closingApi;perfApi;closingPerfApi;flushMs;flushAt;now;anonKey;sessionKey;onceKey;events=[];samples=[];timer;memoryAnon;memorySession;memoryOnce;appVersion;stopAuto;session;consent;identifyPending=!1;listeners=new Set;people={set:e=>this.person({set:e}),setOnce:e=>this.person({set_once:e}),unset:e=>this.person({unset:[...e]}),add:e=>this.person({add:e})};constructor(e,t,s,i,r,a,o={}){this.session=s,this.consent=i;let c={send:d=>e.send(this.granted("analytics")?{...d,headers:{...d.headers,[z]:r.id}}:d)};this.api=V.client(c);let l={send:d=>(this.granted("analytics")?e:t).send(d)};this.perfApi=V.client(l),this.closingApi=V.client({send:d=>c.send({...d,keepalive:!0})}),this.closingPerfApi=V.client({send:d=>l.send({...d,keepalive:!0})}),this.flushMs=o.flushMs??5e3,this.flushAt=o.flushAt??20,this.now=o.now??Date.now,this.anonKey=`palbase.analytics.anonymous.${a}`,this.sessionKey=`palbase.analytics.session.${a}`,this.onceKey=`palbase.analytics.once.${a}`,s.onChange(d=>{d==="SIGNED_IN"?(this.identifyPending=!0,this.soon()):d==="SIGNED_OUT"&&(this.identifyPending=!1,this.reset())}),i.onChange((d,y)=>{y!=="granted"&&(d==="analytics"?(this.events=[],this.identifyPending=!1,this.samples=this.samples.map(ye),this.reset()):d==="performance"&&(this.samples=[]))})}capture(e,t){for(let i of this.listeners)i(e,t);if(!this.granted("analytics"))return;let s=this.now();this.hold({event:e,distinct_id:this.distinctId(),properties:t,timestamp:s,session_id:this.sessionId(s),...this.appVersion?{app_version:this.appVersion}:{}})}captureOnce(e,t,s){if(!this.granted("analytics"))return;let i=this.sessionId(this.now()),r=this.readOnce(),a=r?.session===i?r.keys:[];a.includes(e)||(this.writeOnce({session:i,keys:[...a,e].slice(-500)}),this.capture(t,s))}readOnce(){try{let e=D()?.getItem(this.onceKey);if(e)return JSON.parse(e)}catch{}return this.memoryOnce}writeOnce(e){this.memoryOnce=e;try{D()?.setItem(this.onceKey,JSON.stringify(e))}catch{}}onEvent(e){return this.listeners.add(e),()=>this.listeners.delete(e)}page(e={}){let t=globalThis.location,s=globalThis.document,i=e.url??(t?`${t.origin}${$(t.pathname)}`:"");if(!i)return;let r=e.referrer??Rt(s?.referrer);this.capture("$pageview",{...e.properties,url:i,...e.title??s?.title?{title:e.title??s?.title}:{},...r?{referrer:r}:{}})}async identify(e){this.identifyPending=!1;let t=this.session.snapshot()?.userId;!t||!this.granted("analytics")||(await this.flush(),await this.sendIdentify(this.api,t,e))}async sendIdentify(e,t,s){try{await e.identify({body:{distinct_id:t,anonymous_id:this.anonymousId(),traits:s,timestamp:this.now(),sent_at:this.now()}})}catch{}}reset(){this.memoryAnon=void 0,this.memorySession=void 0,this.memoryOnce=void 0;try{D()?.removeItem(this.anonKey),D()?.removeItem(this.sessionKey),D()?.removeItem(this.onceKey)}catch{}}async flush(e=!1){this.timer&&clearTimeout(this.timer),this.timer=void 0,this.granted("analytics")||(this.events=[]),this.granted("performance")?this.granted("analytics")||(this.samples=this.samples.map(ye)):this.samples=[];let t=e?this.closingApi:this.api,s=e?this.closingPerfApi:this.perfApi,i=this.now(),r=this.session.snapshot()?.userId;for(this.identifyPending&&r&&this.granted("analytics")&&(this.identifyPending=!1,await this.sendIdentify(t,r));this.events.length>0;){let a=this.take(this.events,e);try{await t.batch({body:{events:a.map(o=>({...o,sent_at:i}))}})}catch{}}for(;this.samples.length>0;){let a=this.take(this.samples,e);try{await s.sendPerf({body:{items:a}})}catch{}}}start(e={}){this.stopAuto?.(),this.appVersion=e.appVersion;let t=globalThis;if(typeof t.addEventListener!="function"||typeof globalThis.document>"u")return()=>{};let s=[];e.pageViews!==!1&&s.push(this.watchPages(t)),e.webVitals!==!1&&s.push(Pt((a,o)=>this.sample("web_vital",a,o))),e.network!==!1&&s.push(this.watchFetch(t));let i=()=>{document.visibilityState==="hidden"&&this.flush(!0)},r=()=>{this.flush(!0)};return document.addEventListener("visibilitychange",i),t.addEventListener("pagehide",r),s.push(()=>{document.removeEventListener("visibilitychange",i),t.removeEventListener("pagehide",r)}),this.stopAuto=()=>{for(let a of s.splice(0))a();this.stopAuto=void 0},this.stopAuto}granted(e){return this.consent.state(e)==="granted"}async person(e){if(!this.granted("analytics"))return;let t=this.session.snapshot()?.userId,s=this.now();try{await this.api.setPersonProperties({body:{...e,...t?{}:{distinct_id:this.anonymousId()},timestamp:s,sent_at:s}})}catch{}}hold(e){this.events.length>=$e&&this.events.shift(),this.events.push(e),this.soon()}sample(e,t,s,i={}){if(!this.granted("performance"))return;this.samples.length>=$e&&this.samples.shift();let r={row_id:Y(),trace_type:e,name:t,value:Math.max(0,s),timestamp:this.now(),...i};this.samples.push(this.granted("analytics")?{...r,distinct_id:this.distinctId()}:ye(r)),this.soon()}soon(){if(this.events.length+this.samples.length>=this.flushAt){this.flush();return}this.timer||(this.timer=setTimeout(()=>{this.flush()},this.flushMs),this.timer.unref?.())}take(e,t){let s=e.splice(0,St);if(!t)return s;for(;s.length>1&&JSON.stringify(s).length>_t;)e.unshift(s.pop());return s}distinctId(){return this.session.snapshot()?.userId??this.anonymousId()}anonymousId(){let e=D();try{let t=e?.getItem(this.anonKey);if(t)return t;let s=`anon_${Y()}`;if(e?.setItem(this.anonKey,s),e?.getItem(this.anonKey)===s)return s}catch{}return this.memoryAnon??=`anon_${Y()}`,this.memoryAnon}sessionId(e){let t=D(),s=this.memorySession;try{let r=t?.getItem(this.sessionKey);r&&(s=JSON.parse(r))}catch{}let i=s&&e-s.last<kt?{id:s.id,last:e}:{id:`ses_${Y()}`,last:e};this.memorySession=i;try{t?.setItem(this.sessionKey,JSON.stringify(i))}catch{}return i.id}watchPages(e){let t="",s=()=>{let o=`${e.location.origin}${e.location.pathname}`;if(o===t)return;t=o;let c=`${e.location.origin}${$(e.location.pathname)}`;setTimeout(()=>this.page({url:c}),0)},i=e.history,r=i.pushState.bind(i),a=i.replaceState.bind(i);return i.pushState=(...o)=>{r(...o),s()},i.replaceState=(...o)=>{a(...o),s()},e.addEventListener("popstate",s),s(),()=>{i.pushState=r,i.replaceState=a,e.removeEventListener("popstate",s)}}watchFetch(e){let t=e.fetch;if(typeof t!="function")return()=>{};let s=async(i,r)=>{let a=performance.now(),o=i instanceof Request?i:void 0,c=(r?.method??o?.method??"GET").toUpperCase(),l;try{l=new URL(o?.url??String(i),e.location.href)}catch{l=void 0}let d=!!l&&l.pathname.startsWith("/analytics/")||Tt(r?.headers??o?.headers);try{let y=await t(i,r);return l&&!d&&this.sample("network",`${c} ${l.origin}${$(l.pathname)}`,performance.now()-a,{attrs:{status:String(y.status)},...y.headers.get("x-request-id")?{request_id:y.headers.get("x-request-id")}:{}}),y}catch(y){throw l&&!d&&this.sample("network",`${c} ${l.origin}${$(l.pathname)}`,performance.now()-a,{attrs:{status:"0"}}),y}};return e.fetch=s,()=>{e.fetch===s&&(e.fetch=t)}}};function ye(n){let{distinct_id:e,request_id:t,...s}=n;return s}var It=n=>n.entryType==="layout-shift"&&"value"in n&&"hadRecentInput"in n,xt=n=>n.entryType==="event"||n.entryType==="first-input";function Z(n,e){if(!(typeof PerformanceObserver>"u"))try{let t=new PerformanceObserver(s=>e(s.getEntries()));return t.observe({type:n,buffered:!0}),t}catch{return}}function Pt(n){if(typeof document>"u"||typeof performance>"u"||typeof performance.getEntriesByType!="function")return()=>{};let e=0,t=0,s=0,i=[Z("largest-contentful-paint",l=>{for(let d of l)e=Math.max(e,d.startTime)}),Z("layout-shift",l=>{for(let d of l)It(d)&&!d.hadRecentInput&&(t+=d.value)}),Z("event",l=>{for(let d of l)xt(d)&&(s=Math.max(s,d.duration))}),Z("paint",l=>{for(let d of l)d.name==="first-contentful-paint"&&n("FCP",d.startTime)})],r=performance.getEntriesByType("navigation")[0];r&&r.responseStart>0&&n("TTFB",r.responseStart);let a=!1,o=()=>{a||(a=!0,e>0&&n("LCP",e),n("CLS",t),s>0&&n("INP",s))},c=()=>{document.visibilityState==="hidden"&&o()};return document.addEventListener("visibilitychange",c),()=>{o(),document.removeEventListener("visibilitychange",c);for(let l of i)l?.disconnect()}}function Tt(n){if(!n)return!1;try{return new Headers(n).has("next-router-prefetch")}catch{return!1}}var Et=/^[a-z][a-z0-9_-]{0,31}$/;function $(n){return n.split("/").map(e=>{if(e==="")return e;let t=e.split(";",1)[0],s=t.toLowerCase();return Et.test(s)&&(s.match(/\d/g)?.length??0)<=2&&t.slice(1)===s.slice(1)&&s.split(/[-_]/).every(r=>r.length<=16)?s:":id"}).join("/")}function Rt(n){if(!n)return"";try{let e=new URL(n);return`${e.origin}${$(e.pathname)}`}catch{return $(n.split(/[?#]/,1)[0]??"")}}var Ye=/^custom\.[a-z0-9_]{1,48}$/,At=/^[a-z][a-z0-9_]{0,63}$/,qe=n=>At.test(n)||Ye.test(n),Ot=50,Ve=[5e3,3e4,12e4,6e5],Ct=100,te=class{userApi;deviceApi;session;socket;ref;installation;start;textVersion;customKeys;storeKey;now;kept;listeners=new Set;engaged=!1;platformKeys;watch;sending;sendAgain=!1;retryTimer;retries=0;readFor;stale=!1;lastW=0;lastChosen=0;gpc=globalThis.navigator?.globalPrivacyControl===!0;constructor(e){let t=e.options??{};for(let[c,l]of Object.entries(t.start??{})){if(!qe(c))throw new TypeError(`consent.start: ${JSON.stringify(c)} is not a consent key (a platform key, or custom.<name>)`);if(l!=="granted"&&l!=="denied")throw new TypeError(`consent.start.${c} is granted or denied`)}for(let c of t.customKeys??[])if(!Ye.test(c))throw new TypeError(`consent.customKeys: ${JSON.stringify(c)} is not custom.<name> (a-z, 0-9 and _, 48 at most)`);if(t.textVersion!==void 0&&(t.textVersion===""||t.textVersion.length>64))throw new TypeError("consent.textVersion: 1 to 64 characters");this.userApi=e.userApi,this.deviceApi=e.deviceApi,this.session=e.session,this.socket=e.socket,this.ref=e.ref,this.installation=e.installation,this.start={...t.start},this.textVersion=t.textVersion,this.customKeys=[...t.customKeys??[]],this.storeKey=`palbase.consent.${e.origin}.${e.installation.id}`,this.now=e.now??Date.now;let s=this.load(),i=()=>Ke(this.installation)?{}:{unknown:{on:!0,w:this.stamp()}},r={whose:null,install:this.installation.id,choices:{},unsent:[]};typeof s!="object"?this.kept={...r,...s==="unreadable"?{unknown:{on:!0,w:this.stamp()}}:i()}:s.whose==null&&s.install!==void 0&&s.install!==this.installation.id?this.kept={...r,unsent:s.unsent.filter(c=>c.user!==null),...s.keys?{keys:s.keys}:{},...i()}:this.kept=s,e.session.onChange((c,l)=>{this.engaged&&(c==="SIGNED_IN"&&l?this.signedIn(l):(c==="SIGNED_OUT"||c==="SESSION_EXPIRED")&&this.signedOut())});let a=globalThis;typeof a.addEventListener=="function"&&(a.addEventListener("storage",c=>{(c.key===this.storeKey||c.key===null)&&this.reload()}),a.addEventListener("online",()=>{this.engaged&&this.send()}));let o=this.kept;(e.options!==void 0||s!=="empty"&&(o.unknown?.on||o.unsent.length>0||o.link!==void 0||Object.keys(o.choices).length>0))&&this.engage()}async keys(){return this.engage(),[...(await this.platform()).map(t=>({key:t.key,category:t.category,title:{...t.title},description:{...t.description},ads:t.ads})),...this.customKeys.map(t=>({key:t,category:"custom",title:{},description:{},ads:!1}))]}state(e){if(_(this.kept)!==this.holder()||this.gpcRefuses(e))return"denied";let t=Ge(this.kept,e);return t&&t.state!=="unset"?t.state:this.kept.unknown?.on?"denied":this.start[e]}owesRead(){return this.stale||this.kept.unknown?.on===!0||_(this.kept)!==this.holder()||Object.values(this.kept.choices).some(e=>e.provisional)}holder(){let e=this.session.snapshot()?.userId;return e?`user:${e}`:`device:${this.installation.id}`}lastDeniedAt(e){let t=this.kept.choices[e]?.last_denied_at;return t?new Date(t):void 0}set(e,t){this.setMany({[e]:t})}setMany(e){let t=Object.entries(e);for(let[a,o]of t){if(!qe(a))throw new TypeError(`${JSON.stringify(a)} is not a consent key (a platform key, or custom.<name>)`);if(o!=="granted"&&o!=="denied")throw new TypeError(`${a}: a choice is granted or denied`)}if(t.length===0)return;this.engage();let s=this.chosenAt(),i=this.session.snapshot()?.userId??null,r=this.states();for(let[a,o]of t)this.queue({key:a,state:o,source:"app",chosen_at:s,user:i,...this.textVersion!==void 0?{text_version:this.textVersion}:{}});this.commit(r),this.send()}onChange(e){return this.listeners.add(e),()=>this.listeners.delete(e)}async region(){this.engage();let e=await this.subject();if(this.readFor!==e)try{await this.read(e)}catch(t){if(!this.kept.region)throw t}return this.kept.region}async needsAsking(e){this.engage();let t=await this.subject();this.readFor!==t&&await this.read(t).catch(()=>{});let s=e??(await this.keys()).map(c=>c.key),i=await this.platform().catch(()=>this.kept.keys??[]),r=new Set(i.filter(c=>c.ads).map(c=>c.key)),a=this.kept.region?.jurisdiction==="us",o=new Date(this.now());return o.setUTCMonth(o.getUTCMonth()-12),s.filter(c=>{let l=this.kept.choices[c];return a&&r.has(c)&&l?.last_denied_at!==void 0&&Date.parse(l.last_denied_at)>o.getTime()?!1:!l||l.state==="unset"?!0:this.textVersion!==void 0&&l.source==="app"&&l.text_version!==this.textVersion})}engage(){this.engaged||(this.engaged=!0,this.session.session().then(e=>{e&&!this.watch&&this.follow(e),this.send(),this.refuseByGpc()}))}async subject(){return(await this.session.session())?.userId??null}secret(){return{[A]:O(this.installation)}}platform(){return this.platformKeys??=this.deviceApi.listConsentKeys().then(e=>(this.kept={...this.kept,keys:e.data.keys},this.commit(),e.data.keys),e=>{if(this.platformKeys=void 0,this.kept.keys)return this.kept.keys;throw e}),this.platformKeys}async read(e){let s=(await(e===null?this.deviceApi:this.userApi(e)).getConsents({query:{installation_id:this.installation.id},headers:this.secret()})).data;this.adopt(s,e)}adopt(e,t,s=[]){if(this.kept={...this.kept,region:e.region},(this.session.snapshot()?.userId??null)!==t){this.commit();return}let i=this.states(),r={};for(let u of e.choices)r[u.key]={state:u.state,source:u.source,chosen_at:u.chosen_at,...u.text_version!==void 0?{text_version:u.text_version}:{},...u.last_denied_at!==void 0?{last_denied_at:u.last_denied_at}:{}};let a=s.filter(u=>r[u.key]?.state!==u.state||Date.parse(r[u.key]?.chosen_at??"")!==Date.parse(u.chosen_at)).map(u=>C(u.key,u)),c=_(this.kept)===(t===null?`device:${this.installation.id}`:`user:${t}`)?Object.entries(this.kept.choices).filter(([,u])=>u.provisional).map(([u,g])=>C(u,g)):[];if(a.length+c.length>0&&(this.kept={...this.kept,void:M([...this.kept.void??[],...a,...c])}),t===null&&this.kept.resetAt!==void 0)for(let[u,g]of Object.entries(r))Date.parse(g.chosen_at)<this.kept.resetAt&&delete r[u];let l=new Set(Object.entries(r).map(([u,g])=>C(u,g))),d=(this.kept.void??[]).filter(u=>l.has(u));d.length>0&&(this.kept={...this.kept,unvoid:M([...this.kept.unvoid??[],...d])});let y=Ze(this.kept),f;if(_(this.kept)!==(t===null?`device:${this.installation.id}`:`user:${t}`))f=r;else{f={};for(let u of[...new Set([...Object.keys(this.kept.choices),...Object.keys(r)])].sort()){let g=this.kept.choices[u],m=g&&!g.provisional&&!y.has(C(u,g))?g:void 0,k=r[u],R=k&&(!m||Date.parse(k.chosen_at)>=Date.parse(m.chosen_at))?k:m;R&&(f[u]=R)}}for(let u of this.kept.unsent){if(u.user!==null&&u.user!==t||u.user===null&&u.device!==void 0&&u.device!==this.installation.id||u.user===null&&t!==null)continue;let g=f[u.key];g&&Date.parse(g.chosen_at)>Date.parse(u.chosen_at)||(f[u.key]=Fe(u,g))}let{install:b,...S}=this.kept;this.kept={...S,whose:t,...t===null?{install:this.installation.id}:{},choices:f,unknown:{on:!1,w:this.stamp()}},this.readFor=t,this.stale=!1,this.commit(i),this.refuseByGpc()}async refused(e,t,s){let i=t===e&&_(this.kept)===(t===null?`device:${this.installation.id}`:`user:${t}`),r=M([...this.kept.void??[],...s.map(c=>C(c.key,c))]);if(!i){this.kept={...this.kept,void:r},this.commit();return}let a=this.states(),o={...this.kept.choices};for(let c of s){if(this.kept.unsent.some(d=>d.key===c.key&&(d.user===null||d.user===e)&&Date.parse(d.chosen_at)>Date.parse(c.chosen_at)))continue;let l=o[c.key];o[c.key]={state:"denied",source:"app",chosen_at:c.chosen_at,...l?.last_denied_at!==void 0?{last_denied_at:l.last_denied_at}:{},provisional:!0}}this.kept={...this.kept,choices:o,void:r},this.commit(a);try{await this.read(e)}catch{this.stale=!0}}queue(e){let t=e.user===null?{...e,device:this.installation.id}:e,s=_(this.kept)===(t.user===null?`device:${this.installation.id}`:`user:${t.user}`);this.kept={...this.kept,unsent:Qe([...this.kept.unsent,t]),...s?{choices:{...this.kept.choices,[t.key]:Fe(t,this.kept.choices[t.key])}}:{}}}send(){if(this.sendAgain=!0,this.sending)return;let e=(async()=>{for(;this.sendAgain;)this.sendAgain=!1,await this.sendUnsent()||(this.sendAgain=!1)})();this.sending=e,e.finally(()=>{this.sending===e&&(this.sending=void 0)})}async sendUnsent(){this.retryTimer&&clearTimeout(this.retryTimer),this.retryTimer=void 0;let e=null;try{e=await this.subject();let t=await this.sendOf(null,e);if(e!==null&&(this.kept.link===e||t)){let s;try{s=(await this.userApi(e).linkConsents({headers:this.secret(),body:{installation_id:this.installation.id}})).data}catch(i){if(!Be(i))throw i}if(this.kept.link===e){let{link:i,...r}=this.kept;this.kept=r,this.commit()}if(s)this.adopt(s,e);else{let i=this.states();this.kept={...this.kept,unknown:{on:!0,w:this.stamp()}},this.commit(i)}}if(e!==null&&await this.sendOf(e,e),this.owesRead()&&(await this.read(e),this.owesRead()))throw new Error("the choices are not read yet");return this.retries=0,!0}catch(t){return t instanceof T&&(this.session.snapshot()?.userId??null)!==e?(this.sendAgain=!0,!0):(this.retryLater(),!1)}}async sendOf(e,t){let s=!1;for(;;){let i=this.nextGroup(e);if(i.length===0)return s;let r=i[0],a=e===null?this.deviceApi:this.userApi(e),o;try{o=(await a.chooseConsents({headers:this.secret(),body:{installation_id:this.installation.id,...r.source==="gpc"?{source:"gpc"}:{},...r.text_version!==void 0?{text_version:r.text_version}:{},choices:i.map(c=>({key:c.key,state:c.state,chosen_at:c.chosen_at}))}})).data}catch(c){if(!Be(c))throw c;if(i.length>1){this.kept={...this.kept,unsent:this.kept.unsent.map(l=>i.some(d=>Je(d,l))?{...l,alone:!0}:l)},this.commit();continue}}this.kept={...this.kept,unsent:this.kept.unsent.filter(c=>!i.some(l=>Je(l,c))),done:M([...this.kept.done??[],...i.map(se)])},this.commit(),o?(s=!0,e===t&&this.adopt(o,e,i)):await this.refused(t,e,i)}}nextGroup(e){let t=this.kept.unsent.filter(a=>a.user===e&&(e!==null||(a.device??this.installation.id)===this.installation.id)),s=t[0];if(!s)return[];let i=[],r=new Set;if(s.alone)return[s];for(let a of t)if(!r.has(a.key)&&(r.add(a.key),!(a.alone||a.source!==s.source||a.text_version!==s.text_version)&&(i.push(a),i.length===Ot)))break;return i}retryLater(){if(this.retryTimer)return;let e=Ve[Math.min(this.retries,Ve.length-1)];this.retries++,this.retryTimer=setTimeout(()=>{this.retryTimer=void 0,this.send()},e),this.retryTimer.unref?.()}signedIn(e){this.readFor=void 0,this.kept={...this.kept,link:e.userId},this.commit(),this.follow(e),this.send()}signedOut(){this.unfollow(),this.readFor=void 0;let e=this.states(),t=this.chosenAt(),s=new Set([...Object.entries(this.kept.choices).filter(([,o])=>o.state!=="unset").map(([o])=>o),...this.kept.unsent.filter(o=>o.user===null&&(o.device??this.installation.id)===this.installation.id).map(o=>o.key),...Object.keys(this.start),...this.customKeys,...(this.kept.keys??[]).map(o=>o.key)]),i={};for(let[o,c]of Object.entries(this.kept.choices))i[o]={state:"unset",source:"app",chosen_at:t,...c.last_denied_at!==void 0?{last_denied_at:c.last_denied_at}:{}};let r=o=>o.user===null&&(o.device??this.installation.id)===this.installation.id,a=this.kept.unsent.filter(r);this.kept={whose:null,install:this.installation.id,resetAt:Date.parse(t),choices:i,unsent:this.kept.unsent.filter(o=>!r(o)),...this.kept.void?{void:this.kept.void}:{},...this.kept.unvoid?{unvoid:this.kept.unvoid}:{},done:M([...this.kept.done??[],...a.map(se)]),...this.kept.region?{region:this.kept.region}:{},...this.kept.keys?{keys:this.kept.keys}:{},...this.kept.gpc?{gpc:this.kept.gpc}:{},...this.kept.unknown?{unknown:this.kept.unknown}:{}};for(let o of s)this.queue({key:o,state:"unset",source:"app",chosen_at:t,user:null});this.commit(e),this.send(),this.refuseByGpc()}follow(e){this.unfollow();let t=this.socket.channel(`consents:${this.ref}:${e.userId}`),s={userId:e.userId,channel:t,off:()=>{},version:-1},i=[t.on("broadcast",r=>{r.event==="changed"&&this.changed(s,me(r.payload))}),t.on("state_snapshot",r=>this.held(s,me(ze(r.entries)))),t.on("state_diff",r=>this.held(s,me(ze(r.set))))];s.off=()=>i.forEach(r=>r()),this.watch=s,t.join().catch(()=>{})}unfollow(){let e=this.watch;e&&(this.watch=void 0,e.off(),e.channel.leave())}held(e,t){t!==void 0&&this.changed(e,t)}changed(e,t){if(this.watch===e){if(t!==void 0){if(t<=e.version)return;e.version=t}this.read(e.userId).catch(()=>{this.watch===e&&(this.stale=!0,this.retryLater())})}}gpcRefuses(e){if(!this.gpc||!(this.kept.keys??[]).some(r=>r.key===e&&r.ads))return!1;let t=Ge(this.kept,e);if(t?.state==="denied")return!1;let s=this.kept.gpc?.[_(this.kept)],i=s!==void 0&&(this.kept.whose!=null||s>=(this.kept.resetAt??0));return!(t?.state==="granted"&&t.source==="app"&&i&&Date.parse(t.chosen_at)>s)}async refuseByGpc(){if(!this.gpc||_(this.kept)!==this.holder())return;let e;try{e=await this.platform()}catch{return}if(_(this.kept)!==this.holder())return;let t=this.session.snapshot()?.userId??null,s=e.filter(a=>a.ads&&this.gpcRefuses(a.key)&&!this.kept.unsent.some(o=>o.key===a.key&&o.source==="gpc"&&o.user===t));if(s.length===0)return;let i=this.chosenAt(),r=this.states();for(let a of s)this.queue({key:a.key,state:"denied",source:"gpc",chosen_at:i,user:t});this.kept={...this.kept,gpc:{...this.kept.gpc,[_(this.kept)]:Date.parse(i)}},this.commit(r),this.send()}states(){let e=new Map;for(let t of[...Object.keys(this.start),...Object.keys(this.kept.choices)])e.set(t,this.state(t));return e}tell(e){let t=this.states();for(let s of new Set([...e.keys(),...t.keys()])){let i=t.get(s);if(e.get(s)!==i)for(let r of[...this.listeners])try{r(s,i)}catch{}}}load(){let e;try{e=Xe()?.getItem(this.storeKey)}catch{return"unreadable"}if(e==null)return"empty";try{let t=JSON.parse(e);if(Dt(t))return t}catch{}return"unreadable"}reload(){let e=this.load();if(typeof e!="object"){this.write();return}let t=this.states();this.kept=He(e,this.kept,"theirs",this.holder()),_(e)===_(this.kept)&&We(this.kept)!==We(e)&&this.write(),this.tell(t);let s=this.session.snapshot()?.userId??null;this.engaged&&this.kept.unsent.some(i=>i.user!==null&&i.user===s||i.user===null&&(i.device??this.installation.id)===this.installation.id)&&this.retryLater(),this.engaged&&this.refuseByGpc()}commit(e=this.states()){let t=this.load();typeof t=="object"&&(this.kept=He(t,this.kept,"ours",this.holder())),this.write(),this.tell(e)}write(){try{Xe()?.setItem(this.storeKey,JSON.stringify(this.kept))}catch{}}chosenAt(){return this.lastChosen=Math.max(this.now(),this.lastChosen+1),new Date(this.lastChosen).toISOString()}stamp(){let e=this.kept,t=e?Math.max(0,e.unknown?.w??0):0;return this.lastW=Math.max(this.now(),this.lastW+1,t+1),this.lastW}};function Fe(n,e){let t=n.state==="denied"?n.chosen_at:e?.last_denied_at;return{state:n.state,source:n.source,chosen_at:n.chosen_at,...n.text_version!==void 0?{text_version:n.text_version}:{},...t!==void 0?{last_denied_at:t}:{}}}function C(n,e){return`${n}|${e.provisional?"provisional":e.state}|${Date.parse(e.chosen_at)}`}function Ze(n){let e=new Set(n.unvoid??[]);return new Set((n.void??[]).filter(t=>!e.has(t)))}var ee={denied:2,unset:1,granted:0};function Mt(n,e,t,s){let i=e&&!s.has(C(n,e))?e:void 0,r=t&&!s.has(C(n,t))?t:void 0;if(!i||!r)return i??r;let a=Date.parse(i.chosen_at),o=Date.parse(r.chosen_at);return a!==o?a>o?i:r:ee[i.state]!==ee[r.state]?ee[i.state]>ee[r.state]?i:r:i.provisional?r:i}function Nt(n,e){return!n||!e?n??e:e.w>n.w||e.w===n.w&&e.on?e:n}function He(n,e,t,s){let i=M([...n.void??[],...e.void??[]]),r=M([...n.unvoid??[],...e.unvoid??[]]),a=Ze({void:i,unvoid:r}),o={},c,l={...n.gpc};for(let[m,k]of Object.entries(e.gpc??{}))l[m]=Math.max(l[m]??0,k);let d;if(_(n)===_(e)){c=e;for(let m of[...new Set([...Object.keys(n.choices),...Object.keys(e.choices)])].sort()){let k=Mt(m,n.choices[m],e.choices[m],a);k&&(o[m]=k)}d=Nt(n.unknown,e.unknown)}else{c=_(e)===s?e:_(n)===s?n:t==="ours"?e:n;for(let[m,k]of Object.entries(c.choices))a.has(C(m,k))||(o[m]=k);d=c.unknown}let y=M([...n.done??[],...e.done??[]]),f=Qe([...n.unsent,...e.unsent]).filter(m=>!y.includes(se(m))),b=t==="ours"?e:n,S=t==="ours"?n:e,u=b.region??S.region,g=b.keys??S.keys;return{whose:c.whose??null,...c.whose==null&&c.install!==void 0?{install:c.install}:{},...c.whose==null&&(n.resetAt!==void 0||e.resetAt!==void 0)&&_(n)===_(e)?{resetAt:Math.max(n.resetAt??0,e.resetAt??0)}:c.whose==null&&c.resetAt!==void 0?{resetAt:c.resetAt}:{},choices:o,unsent:f,...y.length>0?{done:y}:{},...i.length>0?{void:i}:{},...r.length>0?{unvoid:r}:{},...b.link!==void 0?{link:b.link}:{},...u?{region:u}:{},...Object.keys(l).length>0?{gpc:l}:{},...g?{keys:g}:{},...d?{unknown:d}:{}}}function se(n){return`${n.user??`device:${n.device??""}`}|${n.key}|${n.state}|${n.source}|${n.chosen_at}`}function Ge(n,e){let t=n.choices[e];if(!t||n.whose!=null||n.resetAt===void 0||Date.parse(t.chosen_at)>=n.resetAt)return t}function _(n){return n.whose!=null?`user:${n.whose}`:`device:${n.install??""}`}function M(n){return[...new Set(n)].slice(-Ct)}function We(n){return JSON.stringify(n,(e,t)=>typeof t=="object"&&t!==null&&!Array.isArray(t)?Object.fromEntries(Object.entries(t).sort(([s],[i])=>s.localeCompare(i))):t)}function Qe(n){let e=new Map;for(let t of n){let s=se(t),i=e.get(s);e.set(s,i?i.alone||!t.alone?i:{...i,alone:!0}:t)}return[...e.values()].sort((t,s)=>Date.parse(t.chosen_at)-Date.parse(s.chosen_at))}var Lt=new Set(["granted","denied","unset"]);function Dt(n){if(typeof n!="object"||n===null)return!1;let e=n;if(typeof e.choices!="object"||e.choices===null||Array.isArray(e.choices)||!Array.isArray(e.unsent))return!1;let t=(o,c)=>{if(typeof o!="object"||o===null)return!1;let l=o;return Lt.has(l.state)&&typeof l.chosen_at=="string"&&(!c||typeof l.key=="string")},s=o=>o===void 0||typeof o=="object"&&o!==null&&typeof o.on=="boolean"&&typeof o.w=="number",i=n,r=o=>o===void 0||Array.isArray(o)&&o.every(c=>typeof c=="string"),a=i.whose===void 0||i.whose===null||typeof i.whose=="string";return Object.values(e.choices).every(o=>t(o,!1))&&e.unsent.every(o=>t(o,!0))&&(i.gpc===void 0||typeof i.gpc=="object"&&i.gpc!==null&&Object.values(i.gpc).every(o=>typeof o=="number"))&&s(i.unknown)&&r(i.done)&&r(i.void)&&r(i.unvoid)&&a}function Je(n,e){return n.key===e.key&&n.user===e.user&&n.state===e.state&&n.source===e.source&&n.chosen_at===e.chosen_at}function Be(n){return n instanceof I&&n.status>=400&&n.status<500&&n.status!==401&&n.status!==408&&n.status!==429}function Xe(){try{return globalThis.localStorage}catch{return}}function ze(n){let e=typeof n=="object"&&n!==null?n.version:void 0;return typeof e=="object"&&e!==null?e.v:void 0}function me(n){let e=typeof n=="object"&&n!==null?n.version:void 0;return typeof e=="number"&&Number.isFinite(e)?e:void 0}var Ut=`
|
|
1
|
+
/*! palbase 0.13.1 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{e as Re,g as Ae,h as Oe}from"./5U3YIYBP.js";import{h as Ce}from"./SGCYJGSM.js";import{a as Ee}from"./SGDOCWYB.js";import{r as xe,t as Pe,u as Te}from"./GXLUNOFZ.js";import{b as V,c as K,e as Se,g as j,h as _e}from"./MERWSLS2.js";import{a as Ie,b as F}from"./EQ4HNSWU.js";import{b as I,d as U}from"./2J3RT5GV.js";function ht(n){let e=n,t=e?.body,s=t&&typeof t=="object"?t.reason:void 0;return s==="user_deleted"?"userDeleted":s==="user_banned"?"userBanned":e?.code==="session_expired"||e?.code==="token_expired"?"expired":"revoked"}var T=class extends Error{code="session_changed";constructor(e){super(e),this.name="SessionChangedError"}};function Me(){let n=null;return{load:()=>n,save:e=>{n=e},clear:()=>{n=null},shared:!1}}function Ne(n){let e=null,t=!0,s=()=>{try{return globalThis.localStorage}catch{return}};return{shared:!0,load(){try{let i=s()?.getItem(n);return i==null?t?null:e:JSON.parse(i)}catch{return e}},save(i){e=i;try{let r=s();if(!r)throw new Error("no storage");r.setItem(n,JSON.stringify(i)),t=!0}catch{t=!1}},clear(){e=null,t=!0;try{s()?.removeItem(n)}catch{}},watch(i){let r=globalThis;if(typeof r.addEventListener!="function")return()=>{};let a=o=>{(o.key===n||o.key===null)&&i()};return r.addEventListener("storage",a),()=>r.removeEventListener?.("storage",a)}}}function fe(n){try{let e=n.split(".")[1]??"",t=atob(e.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(e.length/4)*4,"=")),s=JSON.parse(t).sub;return typeof s=="string"?s:""}catch{return""}}var pt=6e4,ft=15e3;function gt(n,e,t){let s=n?globalThis.navigator?.locks:void 0;return s?s.request(e,t):t()}var W=class{current=null;loaded;inflight=null;endReason=null;listeners=new Set;store;refresher;isRejected;now;lockName;refreshTimeoutMs;mode;constructor(e,t,s,i={}){this.store=e,this.refresher=t,this.isRejected=s,this.now=i.now??Date.now,this.lockName=i.lockName??"palbase.session.refresh",this.refreshTimeoutMs=i.refreshTimeoutMs??ft,this.mode=i.refresh??"behind",this.loaded=Promise.resolve(e.load()).then(r=>{this.current=r}),e.watch?.(()=>{this.reconcile()})}async session(){return await this.loaded,this.current}snapshot(){return this.current}onChange(e){return this.listeners.add(e),()=>this.listeners.delete(e)}async set(e,t,s){await this.loaded;let i=t==="TOKEN_REFRESHED"?this.current:null,r={accessToken:e.access_token,refreshToken:e.refresh_token,expiresAt:this.now()+e.expires_in*1e3,userId:s?.id??i?.userId??fe(e.access_token),user:s??i?.user};return this.current=r,await this.store.save(r),this.emit(t,r),r}async setUser(e,t){await this.loaded,!(!this.current||!t||this.current.userId!==t.userId)&&(this.current={...this.current,user:e},await this.store.save(this.current),this.emit("USER_UPDATED",this.current))}async clear(e,t){await this.loaded;let s=this.current;this.current=null,this.inflight=null;let i=await this.store.load();(!i||!s||i.userId===s.userId)&&await this.store.clear(),s&&(e==="SESSION_EXPIRED"&&(this.endReason=t??"revoked"),this.emit(e,null))}async accessToken(){await this.loaded;let e=this.current;if(!e)return;let t=e.expiresAt-this.now();if(t>pt)return e.accessToken;if(this.mode==="never")return t>0?e.accessToken:void 0;if(t>0&&this.mode==="behind")return this.refresh().catch(()=>{}),e.accessToken;if(t>0)try{return(await this.refresh()).accessToken}catch(s){if(this.current===e)return e.accessToken;throw s}return(await this.refresh()).accessToken}refresh(){if(this.mode==="never")return Promise.reject(new Error("this client does not renew its session (refresh: 'never'): where the session cannot be written back, the request's middleware renews it"));if(this.inflight)return this.inflight;let e=gt(this.store.shared===!0,this.lockName,async()=>{await this.loaded;let t=this.current;if(!t)throw new T("no session to refresh");let s=await this.adoptStored(t);if(s)return s;try{let i=await this.withTimeout(this.refresher(t.refreshToken));if(this.current?.refreshToken!==t.refreshToken)throw new T("the session changed while it was refreshed");return await this.set(i,"TOKEN_REFRESHED")}catch(i){throw this.isRejected(i)&&this.current?.refreshToken===t.refreshToken&&await this.clear("SESSION_EXPIRED",ht(i)),i}});return this.inflight=e,e.finally(()=>{this.inflight===e&&(this.inflight=null)}).catch(()=>{}),e}async adoptStored(e){let t=await this.store.load();if(!t)throw this.current=null,this.emit("SIGNED_OUT",null),new T("signed out in another tab");if(t.userId!==e.userId)throw this.current=t,this.emit("SIGNED_OUT",null),this.emit("SIGNED_IN",t),new T("another user signed in in another tab");if(t.refreshToken!==e.refreshToken&&t.expiresAt>=e.expiresAt)return this.current=t,this.emit("TOKEN_REFRESHED",t),t}async reconcile(){await this.loaded;let e=this.current,t=await this.store.load();if(!e){t&&(this.current=t,this.emit("SIGNED_IN",t));return}await this.adoptStored(e).catch(()=>{})}withTimeout(e){let t,s=new Promise((i,r)=>{t=setTimeout(()=>r(new Error(`the refresh did not answer within ${this.refreshTimeoutMs/1e3} s`)),this.refreshTimeoutMs)});return Promise.race([e,s]).finally(()=>clearTimeout(t))}emit(e,t){(e==="SIGNED_IN"||e==="SIGNED_OUT")&&(this.endReason=null);for(let s of this.listeners)try{s(e,t)}catch{}}};var ge=class{state="closed";refusal;logSeq;joinRef=null;listeners=new Map;closers=new Set;joinWaiters=[];name;socket;constructor(e,t,s={}){this.name=e,this.socket=t,this.logSeq=s.after}get topic(){return`realtime:${this.name}`}join(){if(this.state==="joined")return Promise.resolve();let e=new Promise((t,s)=>this.joinWaiters.push({resolve:t,reject:s}));return this.state!=="joining"&&this.socket.join(this),e}leave(){this.socket.leave(this)}push(e,t){return this.socket.request(this,e,t)}on(e,t){let s=this.listeners.get(e);return s||this.listeners.set(e,s=new Set),s.add(t),()=>s.delete(t)}onClosed(e){return this.closers.add(e),()=>this.closers.delete(e)}deliver(e,t){e==="broadcast"&&typeof t.seq=="number"&&(this.logSeq=t.seq);for(let s of this.listeners.get(e)??[])try{s(t)}catch{}}settled(e,t){e&&typeof t.log_seq=="number"&&(this.logSeq=t.log_seq),this.state=e?"joined":"refused",this.refusal=e?void 0:t;let s=this.joinWaiters.splice(0);for(let i of s)e?i.resolve():i.reject(new Error(`join ${this.name} refused: ${JSON.stringify(t)}`))}closed(e){this.state="closed",this.joinRef=null;let t=this.joinWaiters.splice(0);for(let s of t)s.reject(new Error(`join ${this.name}: ${e}`));for(let s of[...this.closers])try{s()}catch{}}},B=class{ws=null;opening=null;ref=0;channels=new Map;replies=new Map;heartbeat=null;heartbeatRef=null;reconnectTimer=null;attempts=0;closedByUs=!1;reconnects=0;opts;constructor(e){this.opts=e}channel(e,t){let s=this.channels.get(e);return s||this.channels.set(e,s=new ge(e,this,t)),s}disconnect(){this.closedByUs=!0,this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=null,this.stopHeartbeat();let e=this.ws;this.ws=null,this.opening=null,e?.close(1e3);for(let[,t]of this.replies)t("error",{reason:"socket closed"});this.replies.clear();for(let t of this.channels.values())t.closed("the socket was closed")}async tokenChanged(){if(!this.ws||this.ws.readyState!==1)return;let e=await this.opts.accessToken();if(e)for(let t of this.channels.values())t.state==="joined"&&this.push(t.joinRef,t.topic,"access_token",{access_token:e})}join(e){e.state="joining",this.open().then(()=>this.sendJoin(e)).catch(t=>e.settled(!1,{reason:t instanceof Error?t.message:String(t)}))}leave(e){e.state==="joined"&&this.ws?.readyState===1&&this.push(e.joinRef,e.topic,"phx_leave",{}),e.state="closed",this.channels.delete(e.name)}async request(e,t,s){let i=this.ws;if(this.channels.get(e.name)!==e||e.state!=="joined"||i?.readyState!==1)return{status:"error",response:{reason:"not joined"}};let r=this.nextRef(),a=JSON.stringify([e.joinRef,r,e.topic,t,s]),o=this.awaitReply(r);return i.send(a),o}open(){if(this.ws?.readyState===1)return Promise.resolve();if(this.opening)return this.opening;this.closedByUs=!1;let e=this.opts.webSocket??globalThis.WebSocket,t=`${this.opts.baseUrl.replace(/^http/,"ws")}/realtime/v1/websocket?vsn=2.0.0&apikey=${encodeURIComponent(this.opts.publishableKey)}`,s=new Promise((i,r)=>{let a=new e(t);this.ws=a,a.onopen=()=>{this.attempts=0,this.startHeartbeat(),i()},a.onmessage=o=>this.receive(String(o.data)),a.onerror=()=>r(new Error("the realtime socket could not be opened")),a.onclose=()=>this.dropped(a)});return this.opening=s,s.finally(()=>{this.opening===s&&(this.opening=null)}).catch(()=>{}),s}dropped(e){if(this.ws!==e)return;this.ws=null,this.stopHeartbeat();for(let[,i]of this.replies)i("error",{reason:"socket closed"});this.replies.clear();for(let i of this.channels.values())i.state==="joined"&&(i.state="joining");if(this.closedByUs||![...this.channels.values()].some(i=>i.state==="joining"))return;let t=this.opts.backoff??[500,1e3,2e3,5e3,1e4,3e4],s=t[Math.min(this.attempts,t.length-1)]*(.8+Math.random()*.4);this.attempts++,this.reconnectTimer=J(setTimeout(()=>{this.reconnectTimer=null,this.reconnects++;let i=[...this.channels.values()].filter(r=>r.state==="joining");this.open().then(()=>Promise.all(i.map(r=>this.sendJoin(r)))).catch(()=>{})},s))}async sendJoin(e){let t=await this.opts.accessToken(),s=this.nextRef();e.joinRef=s;let i=this.awaitReply(s),r={broadcast:{self:!1}};e.logSeq!==void 0&&(r.log={after:e.logSeq}),this.push(s,e.topic,"phx_join",{access_token:t,config:r},s);let{status:a,response:o}=await i;if(this.channels.get(e.name)!==e||e.state!=="joining"){a==="ok"&&this.ws?.readyState===1&&this.push(s,e.topic,"phx_leave",{});return}e.settled(a==="ok",o)}awaitReply(e){return new Promise(t=>{let s=J(setTimeout(()=>{this.replies.delete(e),t({status:"timeout",response:{reason:"no reply"}})},this.opts.replyTimeoutMs??1e4));this.replies.set(e,(i,r)=>{clearTimeout(s),this.replies.delete(e),t({status:i,response:r})})})}receive(e){let t;try{t=JSON.parse(e)}catch{return}if(!Array.isArray(t)||t.length!==5||typeof t[2]!="string"||typeof t[3]!="string")return;let[,s,i,r,a]=t,o=typeof a=="object"&&a!==null?a:{};if(r==="phx_reply"&&typeof s=="string"){if(s===this.heartbeatRef){this.heartbeatRef=null;return}this.replies.get(s)?.(String(o.status),o.response??{});return}let c=[...this.channels.values()].find(l=>l.topic===i);if(c){if(r==="phx_close"){c.state="closed";return}if(r==="phx_error"){c.state="joining",J(setTimeout(()=>this.channels.get(c.name)===c&&c.state==="joining"&&this.ws?.readyState===1&&void this.sendJoin(c),1e3));return}c.deliver(r,o)}}push(e,t,s,i,r=this.nextRef()){this.ws?.send(JSON.stringify([e,r,t,s,i]))}nextRef(){return String(++this.ref)}startHeartbeat(){this.stopHeartbeat(),this.heartbeat=J(setInterval(()=>{if(this.heartbeatRef!==null){this.heartbeatRef=null,this.ws?.close(4e3);return}this.heartbeatRef=this.nextRef(),this.push(null,"phoenix","heartbeat",{},this.heartbeatRef)},this.opts.heartbeatMs??25e3))}stopHeartbeat(){this.heartbeat&&clearInterval(this.heartbeat),this.heartbeat=null,this.heartbeatRef=null}};function J(n){return n.unref?.(),n}var A="X-Palbase-Installation-Secret",z="X-Palbase-Installation",De=new WeakMap;function O(n){return De.get(n)}var Ue=new WeakSet;function Ke(n){return Ue.has(n)}var yt=/^[A-Za-z0-9_-]{43}$/,X=class{id;constructor(e){let t=`palbase.installation.secret.${e}`,s;try{let i=Le()?.getItem(t);i&&yt.test(i)&&(s=i)}catch{}if(!s){Ue.add(this),s=je(crypto.getRandomValues(new Uint8Array(32)));try{Le()?.setItem(t,s)}catch{}}De.set(this,s),this.id=mt(s)}};function mt(n){return je(wt(new TextEncoder().encode(n)).subarray(0,16))}function Le(){try{return globalThis.localStorage}catch{return}}function je(n){let e="";for(let t of n)e+=String.fromCharCode(t);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}var vt=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),E=(n,e)=>n>>>e|n<<32-e;function wt(n){let e=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),t=new Uint8Array(Math.ceil((n.length+9)/64)*64);t.set(n),t[n.length]=128;let s=new DataView(t.buffer);s.setUint32(t.length-8,Math.floor(n.length/536870912)),s.setUint32(t.length-4,n.length*8>>>0);let i=new Uint32Array(64);for(let o=0;o<t.length;o+=64){for(let g=0;g<16;g++)i[g]=s.getUint32(o+g*4);for(let g=16;g<64;g++){let m=E(i[g-15],7)^E(i[g-15],18)^i[g-15]>>>3,k=E(i[g-2],17)^E(i[g-2],19)^i[g-2]>>>10;i[g]=i[g-16]+m+i[g-7]+k|0}let[c,l,d,y,f,b,S,u]=e;for(let g=0;g<64;g++){let m=u+(E(f,6)^E(f,11)^E(f,25))+(f&b^~f&S)+vt[g]+i[g]|0,k=(E(c,2)^E(c,13)^E(c,22))+(c&l^c&d^l&d)|0;u=S,S=b,b=f,f=y+m|0,y=d,d=l,l=c,c=m+k|0}e[0]+=c,e[1]+=l,e[2]+=d,e[3]+=y,e[4]+=f,e[5]+=b,e[6]+=S,e[7]+=u}let r=new Uint8Array(32),a=new DataView(r.buffer);for(let o=0;o<8;o++)a.setUint32(o*4,e[o]);return r}var kt=30*6e4,$e=1e3,St=100,_t=60*1024,Y=()=>globalThis.crypto?.randomUUID?globalThis.crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;function D(){try{return globalThis.localStorage}catch{return}}var Q=class{api;closingApi;perfApi;closingPerfApi;flushMs;flushAt;now;anonKey;sessionKey;onceKey;events=[];samples=[];timer;memoryAnon;memorySession;memoryOnce;appVersion;stopAuto;session;consent;identifyPending=!1;listeners=new Set;people={set:e=>this.person({set:e}),setOnce:e=>this.person({set_once:e}),unset:e=>this.person({unset:[...e]}),add:e=>this.person({add:e})};constructor(e,t,s,i,r,a,o={}){this.session=s,this.consent=i;let c={send:d=>e.send(this.granted("analytics")?{...d,headers:{...d.headers,[z]:r.id}}:d)};this.api=V.client(c);let l={send:d=>(this.granted("analytics")?e:t).send(d)};this.perfApi=V.client(l),this.closingApi=V.client({send:d=>c.send({...d,keepalive:!0})}),this.closingPerfApi=V.client({send:d=>l.send({...d,keepalive:!0})}),this.flushMs=o.flushMs??5e3,this.flushAt=o.flushAt??20,this.now=o.now??Date.now,this.anonKey=`palbase.analytics.anonymous.${a}`,this.sessionKey=`palbase.analytics.session.${a}`,this.onceKey=`palbase.analytics.once.${a}`,s.onChange(d=>{d==="SIGNED_IN"?(this.identifyPending=!0,this.soon()):d==="SIGNED_OUT"&&(this.identifyPending=!1,this.reset())}),i.onChange((d,y)=>{y!=="granted"&&(d==="analytics"?(this.events=[],this.identifyPending=!1,this.samples=this.samples.map(ye),this.reset()):d==="performance"&&(this.samples=[]))})}capture(e,t){for(let i of this.listeners)i(e,t);if(!this.granted("analytics"))return;let s=this.now();this.hold({event:e,distinct_id:this.distinctId(),properties:t,timestamp:s,session_id:this.sessionId(s),...this.appVersion?{app_version:this.appVersion}:{}})}captureOnce(e,t,s){if(!this.granted("analytics"))return;let i=this.sessionId(this.now()),r=this.readOnce(),a=r?.session===i?r.keys:[];a.includes(e)||(this.writeOnce({session:i,keys:[...a,e].slice(-500)}),this.capture(t,s))}readOnce(){try{let e=D()?.getItem(this.onceKey);if(e)return JSON.parse(e)}catch{}return this.memoryOnce}writeOnce(e){this.memoryOnce=e;try{D()?.setItem(this.onceKey,JSON.stringify(e))}catch{}}onEvent(e){return this.listeners.add(e),()=>this.listeners.delete(e)}page(e={}){let t=globalThis.location,s=globalThis.document,i=e.url??(t?`${t.origin}${$(t.pathname)}`:"");if(!i)return;let r=e.referrer??Rt(s?.referrer);this.capture("$pageview",{...e.properties,url:i,...e.title??s?.title?{title:e.title??s?.title}:{},...r?{referrer:r}:{}})}async identify(e){this.identifyPending=!1;let t=this.session.snapshot()?.userId;!t||!this.granted("analytics")||(await this.flush(),await this.sendIdentify(this.api,t,e))}async sendIdentify(e,t,s){try{await e.identify({body:{distinct_id:t,anonymous_id:this.anonymousId(),traits:s,timestamp:this.now(),sent_at:this.now()}})}catch{}}reset(){this.memoryAnon=void 0,this.memorySession=void 0,this.memoryOnce=void 0;try{D()?.removeItem(this.anonKey),D()?.removeItem(this.sessionKey),D()?.removeItem(this.onceKey)}catch{}}async flush(e=!1){this.timer&&clearTimeout(this.timer),this.timer=void 0,this.granted("analytics")||(this.events=[]),this.granted("performance")?this.granted("analytics")||(this.samples=this.samples.map(ye)):this.samples=[];let t=e?this.closingApi:this.api,s=e?this.closingPerfApi:this.perfApi,i=this.now(),r=this.session.snapshot()?.userId;for(this.identifyPending&&r&&this.granted("analytics")&&(this.identifyPending=!1,await this.sendIdentify(t,r));this.events.length>0;){let a=this.take(this.events,e);try{await t.batch({body:{events:a.map(o=>({...o,sent_at:i}))}})}catch{}}for(;this.samples.length>0;){let a=this.take(this.samples,e);try{await s.sendPerf({body:{items:a}})}catch{}}}start(e={}){this.stopAuto?.(),this.appVersion=e.appVersion;let t=globalThis;if(typeof t.addEventListener!="function"||typeof globalThis.document>"u")return()=>{};let s=[];e.pageViews!==!1&&s.push(this.watchPages(t)),e.webVitals!==!1&&s.push(Pt((a,o)=>this.sample("web_vital",a,o))),e.network!==!1&&s.push(this.watchFetch(t));let i=()=>{document.visibilityState==="hidden"&&this.flush(!0)},r=()=>{this.flush(!0)};return document.addEventListener("visibilitychange",i),t.addEventListener("pagehide",r),s.push(()=>{document.removeEventListener("visibilitychange",i),t.removeEventListener("pagehide",r)}),this.stopAuto=()=>{for(let a of s.splice(0))a();this.stopAuto=void 0},this.stopAuto}granted(e){return this.consent.state(e)==="granted"}async person(e){if(!this.granted("analytics"))return;let t=this.session.snapshot()?.userId,s=this.now();try{await this.api.setPersonProperties({body:{...e,...t?{}:{distinct_id:this.anonymousId()},timestamp:s,sent_at:s}})}catch{}}hold(e){this.events.length>=$e&&this.events.shift(),this.events.push(e),this.soon()}sample(e,t,s,i={}){if(!this.granted("performance"))return;this.samples.length>=$e&&this.samples.shift();let r={row_id:Y(),trace_type:e,name:t,value:Math.max(0,s),timestamp:this.now(),...i};this.samples.push(this.granted("analytics")?{...r,distinct_id:this.distinctId()}:ye(r)),this.soon()}soon(){if(this.events.length+this.samples.length>=this.flushAt){this.flush();return}this.timer||(this.timer=setTimeout(()=>{this.flush()},this.flushMs),this.timer.unref?.())}take(e,t){let s=e.splice(0,St);if(!t)return s;for(;s.length>1&&JSON.stringify(s).length>_t;)e.unshift(s.pop());return s}distinctId(){return this.session.snapshot()?.userId??this.anonymousId()}anonymousId(){let e=D();try{let t=e?.getItem(this.anonKey);if(t)return t;let s=`anon_${Y()}`;if(e?.setItem(this.anonKey,s),e?.getItem(this.anonKey)===s)return s}catch{}return this.memoryAnon??=`anon_${Y()}`,this.memoryAnon}sessionId(e){let t=D(),s=this.memorySession;try{let r=t?.getItem(this.sessionKey);r&&(s=JSON.parse(r))}catch{}let i=s&&e-s.last<kt?{id:s.id,last:e}:{id:`ses_${Y()}`,last:e};this.memorySession=i;try{t?.setItem(this.sessionKey,JSON.stringify(i))}catch{}return i.id}watchPages(e){let t="",s=()=>{let o=`${e.location.origin}${e.location.pathname}`;if(o===t)return;t=o;let c=`${e.location.origin}${$(e.location.pathname)}`;setTimeout(()=>this.page({url:c}),0)},i=e.history,r=i.pushState.bind(i),a=i.replaceState.bind(i);return i.pushState=(...o)=>{r(...o),s()},i.replaceState=(...o)=>{a(...o),s()},e.addEventListener("popstate",s),s(),()=>{i.pushState=r,i.replaceState=a,e.removeEventListener("popstate",s)}}watchFetch(e){let t=e.fetch;if(typeof t!="function")return()=>{};let s=async(i,r)=>{let a=performance.now(),o=i instanceof Request?i:void 0,c=(r?.method??o?.method??"GET").toUpperCase(),l;try{l=new URL(o?.url??String(i),e.location.href)}catch{l=void 0}let d=!!l&&l.pathname.startsWith("/analytics/")||Tt(r?.headers??o?.headers);try{let y=await t(i,r);return l&&!d&&this.sample("network",`${c} ${l.origin}${$(l.pathname)}`,performance.now()-a,{attrs:{status:String(y.status)},...y.headers.get("x-request-id")?{request_id:y.headers.get("x-request-id")}:{}}),y}catch(y){throw l&&!d&&this.sample("network",`${c} ${l.origin}${$(l.pathname)}`,performance.now()-a,{attrs:{status:"0"}}),y}};return e.fetch=s,()=>{e.fetch===s&&(e.fetch=t)}}};function ye(n){let{distinct_id:e,request_id:t,...s}=n;return s}var It=n=>n.entryType==="layout-shift"&&"value"in n&&"hadRecentInput"in n,xt=n=>n.entryType==="event"||n.entryType==="first-input";function Z(n,e){if(!(typeof PerformanceObserver>"u"))try{let t=new PerformanceObserver(s=>e(s.getEntries()));return t.observe({type:n,buffered:!0}),t}catch{return}}function Pt(n){if(typeof document>"u"||typeof performance>"u"||typeof performance.getEntriesByType!="function")return()=>{};let e=0,t=0,s=0,i=[Z("largest-contentful-paint",l=>{for(let d of l)e=Math.max(e,d.startTime)}),Z("layout-shift",l=>{for(let d of l)It(d)&&!d.hadRecentInput&&(t+=d.value)}),Z("event",l=>{for(let d of l)xt(d)&&(s=Math.max(s,d.duration))}),Z("paint",l=>{for(let d of l)d.name==="first-contentful-paint"&&n("FCP",d.startTime)})],r=performance.getEntriesByType("navigation")[0];r&&r.responseStart>0&&n("TTFB",r.responseStart);let a=!1,o=()=>{a||(a=!0,e>0&&n("LCP",e),n("CLS",t),s>0&&n("INP",s))},c=()=>{document.visibilityState==="hidden"&&o()};return document.addEventListener("visibilitychange",c),()=>{o(),document.removeEventListener("visibilitychange",c);for(let l of i)l?.disconnect()}}function Tt(n){if(!n)return!1;try{return new Headers(n).has("next-router-prefetch")}catch{return!1}}var Et=/^[a-z][a-z0-9_-]{0,31}$/;function $(n){return n.split("/").map(e=>{if(e==="")return e;let t=e.split(";",1)[0],s=t.toLowerCase();return Et.test(s)&&(s.match(/\d/g)?.length??0)<=2&&t.slice(1)===s.slice(1)&&s.split(/[-_]/).every(r=>r.length<=16)?s:":id"}).join("/")}function Rt(n){if(!n)return"";try{let e=new URL(n);return`${e.origin}${$(e.pathname)}`}catch{return $(n.split(/[?#]/,1)[0]??"")}}var Ye=/^custom\.[a-z0-9_]{1,48}$/,At=/^[a-z][a-z0-9_]{0,63}$/,qe=n=>At.test(n)||Ye.test(n),Ot=50,Ve=[5e3,3e4,12e4,6e5],Ct=100,te=class{userApi;deviceApi;session;socket;ref;installation;start;textVersion;customKeys;storeKey;now;kept;listeners=new Set;engaged=!1;platformKeys;watch;sending;sendAgain=!1;retryTimer;retries=0;readFor;stale=!1;lastW=0;lastChosen=0;gpc=globalThis.navigator?.globalPrivacyControl===!0;constructor(e){let t=e.options??{};for(let[c,l]of Object.entries(t.start??{})){if(!qe(c))throw new TypeError(`consent.start: ${JSON.stringify(c)} is not a consent key (a platform key, or custom.<name>)`);if(l!=="granted"&&l!=="denied")throw new TypeError(`consent.start.${c} is granted or denied`)}for(let c of t.customKeys??[])if(!Ye.test(c))throw new TypeError(`consent.customKeys: ${JSON.stringify(c)} is not custom.<name> (a-z, 0-9 and _, 48 at most)`);if(t.textVersion!==void 0&&(t.textVersion===""||t.textVersion.length>64))throw new TypeError("consent.textVersion: 1 to 64 characters");this.userApi=e.userApi,this.deviceApi=e.deviceApi,this.session=e.session,this.socket=e.socket,this.ref=e.ref,this.installation=e.installation,this.start={...t.start},this.textVersion=t.textVersion,this.customKeys=[...t.customKeys??[]],this.storeKey=`palbase.consent.${e.origin}.${e.installation.id}`,this.now=e.now??Date.now;let s=this.load(),i=()=>Ke(this.installation)?{}:{unknown:{on:!0,w:this.stamp()}},r={whose:null,install:this.installation.id,choices:{},unsent:[]};typeof s!="object"?this.kept={...r,...s==="unreadable"?{unknown:{on:!0,w:this.stamp()}}:i()}:s.whose==null&&s.install!==void 0&&s.install!==this.installation.id?this.kept={...r,unsent:s.unsent.filter(c=>c.user!==null),...s.keys?{keys:s.keys}:{},...i()}:this.kept=s,e.session.onChange((c,l)=>{this.engaged&&(c==="SIGNED_IN"&&l?this.signedIn(l):(c==="SIGNED_OUT"||c==="SESSION_EXPIRED")&&this.signedOut())});let a=globalThis;typeof a.addEventListener=="function"&&(a.addEventListener("storage",c=>{(c.key===this.storeKey||c.key===null)&&this.reload()}),a.addEventListener("online",()=>{this.engaged&&this.send()}));let o=this.kept;(e.options!==void 0||s!=="empty"&&(o.unknown?.on||o.unsent.length>0||o.link!==void 0||Object.keys(o.choices).length>0))&&this.engage()}async keys(){return this.engage(),[...(await this.platform()).map(t=>({key:t.key,category:t.category,title:{...t.title},description:{...t.description},ads:t.ads})),...this.customKeys.map(t=>({key:t,category:"custom",title:{},description:{},ads:!1}))]}state(e){if(_(this.kept)!==this.holder()||this.gpcRefuses(e))return"denied";let t=Ge(this.kept,e);return t&&t.state!=="unset"?t.state:this.kept.unknown?.on?"denied":this.start[e]}owesRead(){return this.stale||this.kept.unknown?.on===!0||_(this.kept)!==this.holder()||Object.values(this.kept.choices).some(e=>e.provisional)}holder(){let e=this.session.snapshot()?.userId;return e?`user:${e}`:`device:${this.installation.id}`}lastDeniedAt(e){let t=this.kept.choices[e]?.last_denied_at;return t?new Date(t):void 0}set(e,t){this.setMany({[e]:t})}setMany(e){let t=Object.entries(e);for(let[a,o]of t){if(!qe(a))throw new TypeError(`${JSON.stringify(a)} is not a consent key (a platform key, or custom.<name>)`);if(o!=="granted"&&o!=="denied")throw new TypeError(`${a}: a choice is granted or denied`)}if(t.length===0)return;this.engage();let s=this.chosenAt(),i=this.session.snapshot()?.userId??null,r=this.states();for(let[a,o]of t)this.queue({key:a,state:o,source:"app",chosen_at:s,user:i,...this.textVersion!==void 0?{text_version:this.textVersion}:{}});this.commit(r),this.send()}onChange(e){return this.listeners.add(e),()=>this.listeners.delete(e)}async region(){this.engage();let e=await this.subject();if(this.readFor!==e)try{await this.read(e)}catch(t){if(!this.kept.region)throw t}return this.kept.region}async needsAsking(e){this.engage();let t=await this.subject();this.readFor!==t&&await this.read(t).catch(()=>{});let s=e??(await this.keys()).map(c=>c.key),i=await this.platform().catch(()=>this.kept.keys??[]),r=new Set(i.filter(c=>c.ads).map(c=>c.key)),a=this.kept.region?.jurisdiction==="us",o=new Date(this.now());return o.setUTCMonth(o.getUTCMonth()-12),s.filter(c=>{let l=this.kept.choices[c];return a&&r.has(c)&&l?.last_denied_at!==void 0&&Date.parse(l.last_denied_at)>o.getTime()?!1:!l||l.state==="unset"?!0:this.textVersion!==void 0&&l.source==="app"&&l.text_version!==this.textVersion})}engage(){this.engaged||(this.engaged=!0,this.session.session().then(e=>{e&&!this.watch&&this.follow(e),this.send(),this.refuseByGpc()}))}async subject(){return(await this.session.session())?.userId??null}secret(){return{[A]:O(this.installation)}}platform(){return this.platformKeys??=this.deviceApi.listConsentKeys().then(e=>(this.kept={...this.kept,keys:e.data.keys},this.commit(),e.data.keys),e=>{if(this.platformKeys=void 0,this.kept.keys)return this.kept.keys;throw e}),this.platformKeys}async read(e){let s=(await(e===null?this.deviceApi:this.userApi(e)).getConsents({query:{installation_id:this.installation.id},headers:this.secret()})).data;this.adopt(s,e)}adopt(e,t,s=[]){if(this.kept={...this.kept,region:e.region},(this.session.snapshot()?.userId??null)!==t){this.commit();return}let i=this.states(),r={};for(let u of e.choices)r[u.key]={state:u.state,source:u.source,chosen_at:u.chosen_at,...u.text_version!==void 0?{text_version:u.text_version}:{},...u.last_denied_at!==void 0?{last_denied_at:u.last_denied_at}:{}};let a=s.filter(u=>r[u.key]?.state!==u.state||Date.parse(r[u.key]?.chosen_at??"")!==Date.parse(u.chosen_at)).map(u=>C(u.key,u)),c=_(this.kept)===(t===null?`device:${this.installation.id}`:`user:${t}`)?Object.entries(this.kept.choices).filter(([,u])=>u.provisional).map(([u,g])=>C(u,g)):[];if(a.length+c.length>0&&(this.kept={...this.kept,void:M([...this.kept.void??[],...a,...c])}),t===null&&this.kept.resetAt!==void 0)for(let[u,g]of Object.entries(r))Date.parse(g.chosen_at)<this.kept.resetAt&&delete r[u];let l=new Set(Object.entries(r).map(([u,g])=>C(u,g))),d=(this.kept.void??[]).filter(u=>l.has(u));d.length>0&&(this.kept={...this.kept,unvoid:M([...this.kept.unvoid??[],...d])});let y=Ze(this.kept),f;if(_(this.kept)!==(t===null?`device:${this.installation.id}`:`user:${t}`))f=r;else{f={};for(let u of[...new Set([...Object.keys(this.kept.choices),...Object.keys(r)])].sort()){let g=this.kept.choices[u],m=g&&!g.provisional&&!y.has(C(u,g))?g:void 0,k=r[u],R=k&&(!m||Date.parse(k.chosen_at)>=Date.parse(m.chosen_at))?k:m;R&&(f[u]=R)}}for(let u of this.kept.unsent){if(u.user!==null&&u.user!==t||u.user===null&&u.device!==void 0&&u.device!==this.installation.id||u.user===null&&t!==null)continue;let g=f[u.key];g&&Date.parse(g.chosen_at)>Date.parse(u.chosen_at)||(f[u.key]=Fe(u,g))}let{install:b,...S}=this.kept;this.kept={...S,whose:t,...t===null?{install:this.installation.id}:{},choices:f,unknown:{on:!1,w:this.stamp()}},this.readFor=t,this.stale=!1,this.commit(i),this.refuseByGpc()}async refused(e,t,s){let i=t===e&&_(this.kept)===(t===null?`device:${this.installation.id}`:`user:${t}`),r=M([...this.kept.void??[],...s.map(c=>C(c.key,c))]);if(!i){this.kept={...this.kept,void:r},this.commit();return}let a=this.states(),o={...this.kept.choices};for(let c of s){if(this.kept.unsent.some(d=>d.key===c.key&&(d.user===null||d.user===e)&&Date.parse(d.chosen_at)>Date.parse(c.chosen_at)))continue;let l=o[c.key];o[c.key]={state:"denied",source:"app",chosen_at:c.chosen_at,...l?.last_denied_at!==void 0?{last_denied_at:l.last_denied_at}:{},provisional:!0}}this.kept={...this.kept,choices:o,void:r},this.commit(a);try{await this.read(e)}catch{this.stale=!0}}queue(e){let t=e.user===null?{...e,device:this.installation.id}:e,s=_(this.kept)===(t.user===null?`device:${this.installation.id}`:`user:${t.user}`);this.kept={...this.kept,unsent:Qe([...this.kept.unsent,t]),...s?{choices:{...this.kept.choices,[t.key]:Fe(t,this.kept.choices[t.key])}}:{}}}send(){if(this.sendAgain=!0,this.sending)return;let e=(async()=>{for(;this.sendAgain;)this.sendAgain=!1,await this.sendUnsent()||(this.sendAgain=!1)})();this.sending=e,e.finally(()=>{this.sending===e&&(this.sending=void 0)})}async sendUnsent(){this.retryTimer&&clearTimeout(this.retryTimer),this.retryTimer=void 0;let e=null;try{e=await this.subject();let t=await this.sendOf(null,e);if(e!==null&&(this.kept.link===e||t)){let s;try{s=(await this.userApi(e).linkConsents({headers:this.secret(),body:{installation_id:this.installation.id}})).data}catch(i){if(!Be(i))throw i}if(this.kept.link===e){let{link:i,...r}=this.kept;this.kept=r,this.commit()}if(s)this.adopt(s,e);else{let i=this.states();this.kept={...this.kept,unknown:{on:!0,w:this.stamp()}},this.commit(i)}}if(e!==null&&await this.sendOf(e,e),this.owesRead()&&(await this.read(e),this.owesRead()))throw new Error("the choices are not read yet");return this.retries=0,!0}catch(t){return t instanceof T&&(this.session.snapshot()?.userId??null)!==e?(this.sendAgain=!0,!0):(this.retryLater(),!1)}}async sendOf(e,t){let s=!1;for(;;){let i=this.nextGroup(e);if(i.length===0)return s;let r=i[0],a=e===null?this.deviceApi:this.userApi(e),o;try{o=(await a.chooseConsents({headers:this.secret(),body:{installation_id:this.installation.id,...r.source==="gpc"?{source:"gpc"}:{},...r.text_version!==void 0?{text_version:r.text_version}:{},choices:i.map(c=>({key:c.key,state:c.state,chosen_at:c.chosen_at}))}})).data}catch(c){if(!Be(c))throw c;if(i.length>1){this.kept={...this.kept,unsent:this.kept.unsent.map(l=>i.some(d=>Je(d,l))?{...l,alone:!0}:l)},this.commit();continue}}this.kept={...this.kept,unsent:this.kept.unsent.filter(c=>!i.some(l=>Je(l,c))),done:M([...this.kept.done??[],...i.map(se)])},this.commit(),o?(s=!0,e===t&&this.adopt(o,e,i)):await this.refused(t,e,i)}}nextGroup(e){let t=this.kept.unsent.filter(a=>a.user===e&&(e!==null||(a.device??this.installation.id)===this.installation.id)),s=t[0];if(!s)return[];let i=[],r=new Set;if(s.alone)return[s];for(let a of t)if(!r.has(a.key)&&(r.add(a.key),!(a.alone||a.source!==s.source||a.text_version!==s.text_version)&&(i.push(a),i.length===Ot)))break;return i}retryLater(){if(this.retryTimer)return;let e=Ve[Math.min(this.retries,Ve.length-1)];this.retries++,this.retryTimer=setTimeout(()=>{this.retryTimer=void 0,this.send()},e),this.retryTimer.unref?.()}signedIn(e){this.readFor=void 0,this.kept={...this.kept,link:e.userId},this.commit(),this.follow(e),this.send()}signedOut(){this.unfollow(),this.readFor=void 0;let e=this.states(),t=this.chosenAt(),s=new Set([...Object.entries(this.kept.choices).filter(([,o])=>o.state!=="unset").map(([o])=>o),...this.kept.unsent.filter(o=>o.user===null&&(o.device??this.installation.id)===this.installation.id).map(o=>o.key),...Object.keys(this.start),...this.customKeys,...(this.kept.keys??[]).map(o=>o.key)]),i={};for(let[o,c]of Object.entries(this.kept.choices))i[o]={state:"unset",source:"app",chosen_at:t,...c.last_denied_at!==void 0?{last_denied_at:c.last_denied_at}:{}};let r=o=>o.user===null&&(o.device??this.installation.id)===this.installation.id,a=this.kept.unsent.filter(r);this.kept={whose:null,install:this.installation.id,resetAt:Date.parse(t),choices:i,unsent:this.kept.unsent.filter(o=>!r(o)),...this.kept.void?{void:this.kept.void}:{},...this.kept.unvoid?{unvoid:this.kept.unvoid}:{},done:M([...this.kept.done??[],...a.map(se)]),...this.kept.region?{region:this.kept.region}:{},...this.kept.keys?{keys:this.kept.keys}:{},...this.kept.gpc?{gpc:this.kept.gpc}:{},...this.kept.unknown?{unknown:this.kept.unknown}:{}};for(let o of s)this.queue({key:o,state:"unset",source:"app",chosen_at:t,user:null});this.commit(e),this.send(),this.refuseByGpc()}follow(e){this.unfollow();let t=this.socket.channel(`consents:${this.ref}:${e.userId}`),s={userId:e.userId,channel:t,off:()=>{},version:-1},i=[t.on("broadcast",r=>{r.event==="changed"&&this.changed(s,me(r.payload))}),t.on("state_snapshot",r=>this.held(s,me(ze(r.entries)))),t.on("state_diff",r=>this.held(s,me(ze(r.set))))];s.off=()=>i.forEach(r=>r()),this.watch=s,t.join().catch(()=>{})}unfollow(){let e=this.watch;e&&(this.watch=void 0,e.off(),e.channel.leave())}held(e,t){t!==void 0&&this.changed(e,t)}changed(e,t){if(this.watch===e){if(t!==void 0){if(t<=e.version)return;e.version=t}this.read(e.userId).catch(()=>{this.watch===e&&(this.stale=!0,this.retryLater())})}}gpcRefuses(e){if(!this.gpc||!(this.kept.keys??[]).some(r=>r.key===e&&r.ads))return!1;let t=Ge(this.kept,e);if(t?.state==="denied")return!1;let s=this.kept.gpc?.[_(this.kept)],i=s!==void 0&&(this.kept.whose!=null||s>=(this.kept.resetAt??0));return!(t?.state==="granted"&&t.source==="app"&&i&&Date.parse(t.chosen_at)>s)}async refuseByGpc(){if(!this.gpc||_(this.kept)!==this.holder())return;let e;try{e=await this.platform()}catch{return}if(_(this.kept)!==this.holder())return;let t=this.session.snapshot()?.userId??null,s=e.filter(a=>a.ads&&this.gpcRefuses(a.key)&&!this.kept.unsent.some(o=>o.key===a.key&&o.source==="gpc"&&o.user===t));if(s.length===0)return;let i=this.chosenAt(),r=this.states();for(let a of s)this.queue({key:a.key,state:"denied",source:"gpc",chosen_at:i,user:t});this.kept={...this.kept,gpc:{...this.kept.gpc,[_(this.kept)]:Date.parse(i)}},this.commit(r),this.send()}states(){let e=new Map;for(let t of[...Object.keys(this.start),...Object.keys(this.kept.choices)])e.set(t,this.state(t));return e}tell(e){let t=this.states();for(let s of new Set([...e.keys(),...t.keys()])){let i=t.get(s);if(e.get(s)!==i)for(let r of[...this.listeners])try{r(s,i)}catch{}}}load(){let e;try{e=Xe()?.getItem(this.storeKey)}catch{return"unreadable"}if(e==null)return"empty";try{let t=JSON.parse(e);if(Dt(t))return t}catch{}return"unreadable"}reload(){let e=this.load();if(typeof e!="object"){this.write();return}let t=this.states();this.kept=He(e,this.kept,"theirs",this.holder()),_(e)===_(this.kept)&&We(this.kept)!==We(e)&&this.write(),this.tell(t);let s=this.session.snapshot()?.userId??null;this.engaged&&this.kept.unsent.some(i=>i.user!==null&&i.user===s||i.user===null&&(i.device??this.installation.id)===this.installation.id)&&this.retryLater(),this.engaged&&this.refuseByGpc()}commit(e=this.states()){let t=this.load();typeof t=="object"&&(this.kept=He(t,this.kept,"ours",this.holder())),this.write(),this.tell(e)}write(){try{Xe()?.setItem(this.storeKey,JSON.stringify(this.kept))}catch{}}chosenAt(){return this.lastChosen=Math.max(this.now(),this.lastChosen+1),new Date(this.lastChosen).toISOString()}stamp(){let e=this.kept,t=e?Math.max(0,e.unknown?.w??0):0;return this.lastW=Math.max(this.now(),this.lastW+1,t+1),this.lastW}};function Fe(n,e){let t=n.state==="denied"?n.chosen_at:e?.last_denied_at;return{state:n.state,source:n.source,chosen_at:n.chosen_at,...n.text_version!==void 0?{text_version:n.text_version}:{},...t!==void 0?{last_denied_at:t}:{}}}function C(n,e){return`${n}|${e.provisional?"provisional":e.state}|${Date.parse(e.chosen_at)}`}function Ze(n){let e=new Set(n.unvoid??[]);return new Set((n.void??[]).filter(t=>!e.has(t)))}var ee={denied:2,unset:1,granted:0};function Mt(n,e,t,s){let i=e&&!s.has(C(n,e))?e:void 0,r=t&&!s.has(C(n,t))?t:void 0;if(!i||!r)return i??r;let a=Date.parse(i.chosen_at),o=Date.parse(r.chosen_at);return a!==o?a>o?i:r:ee[i.state]!==ee[r.state]?ee[i.state]>ee[r.state]?i:r:i.provisional?r:i}function Nt(n,e){return!n||!e?n??e:e.w>n.w||e.w===n.w&&e.on?e:n}function He(n,e,t,s){let i=M([...n.void??[],...e.void??[]]),r=M([...n.unvoid??[],...e.unvoid??[]]),a=Ze({void:i,unvoid:r}),o={},c,l={...n.gpc};for(let[m,k]of Object.entries(e.gpc??{}))l[m]=Math.max(l[m]??0,k);let d;if(_(n)===_(e)){c=e;for(let m of[...new Set([...Object.keys(n.choices),...Object.keys(e.choices)])].sort()){let k=Mt(m,n.choices[m],e.choices[m],a);k&&(o[m]=k)}d=Nt(n.unknown,e.unknown)}else{c=_(e)===s?e:_(n)===s?n:t==="ours"?e:n;for(let[m,k]of Object.entries(c.choices))a.has(C(m,k))||(o[m]=k);d=c.unknown}let y=M([...n.done??[],...e.done??[]]),f=Qe([...n.unsent,...e.unsent]).filter(m=>!y.includes(se(m))),b=t==="ours"?e:n,S=t==="ours"?n:e,u=b.region??S.region,g=b.keys??S.keys;return{whose:c.whose??null,...c.whose==null&&c.install!==void 0?{install:c.install}:{},...c.whose==null&&(n.resetAt!==void 0||e.resetAt!==void 0)&&_(n)===_(e)?{resetAt:Math.max(n.resetAt??0,e.resetAt??0)}:c.whose==null&&c.resetAt!==void 0?{resetAt:c.resetAt}:{},choices:o,unsent:f,...y.length>0?{done:y}:{},...i.length>0?{void:i}:{},...r.length>0?{unvoid:r}:{},...b.link!==void 0?{link:b.link}:{},...u?{region:u}:{},...Object.keys(l).length>0?{gpc:l}:{},...g?{keys:g}:{},...d?{unknown:d}:{}}}function se(n){return`${n.user??`device:${n.device??""}`}|${n.key}|${n.state}|${n.source}|${n.chosen_at}`}function Ge(n,e){let t=n.choices[e];if(!t||n.whose!=null||n.resetAt===void 0||Date.parse(t.chosen_at)>=n.resetAt)return t}function _(n){return n.whose!=null?`user:${n.whose}`:`device:${n.install??""}`}function M(n){return[...new Set(n)].slice(-Ct)}function We(n){return JSON.stringify(n,(e,t)=>typeof t=="object"&&t!==null&&!Array.isArray(t)?Object.fromEntries(Object.entries(t).sort(([s],[i])=>s.localeCompare(i))):t)}function Qe(n){let e=new Map;for(let t of n){let s=se(t),i=e.get(s);e.set(s,i?i.alone||!t.alone?i:{...i,alone:!0}:t)}return[...e.values()].sort((t,s)=>Date.parse(t.chosen_at)-Date.parse(s.chosen_at))}var Lt=new Set(["granted","denied","unset"]);function Dt(n){if(typeof n!="object"||n===null)return!1;let e=n;if(typeof e.choices!="object"||e.choices===null||Array.isArray(e.choices)||!Array.isArray(e.unsent))return!1;let t=(o,c)=>{if(typeof o!="object"||o===null)return!1;let l=o;return Lt.has(l.state)&&typeof l.chosen_at=="string"&&(!c||typeof l.key=="string")},s=o=>o===void 0||typeof o=="object"&&o!==null&&typeof o.on=="boolean"&&typeof o.w=="number",i=n,r=o=>o===void 0||Array.isArray(o)&&o.every(c=>typeof c=="string"),a=i.whose===void 0||i.whose===null||typeof i.whose=="string";return Object.values(e.choices).every(o=>t(o,!1))&&e.unsent.every(o=>t(o,!0))&&(i.gpc===void 0||typeof i.gpc=="object"&&i.gpc!==null&&Object.values(i.gpc).every(o=>typeof o=="number"))&&s(i.unknown)&&r(i.done)&&r(i.void)&&r(i.unvoid)&&a}function Je(n,e){return n.key===e.key&&n.user===e.user&&n.state===e.state&&n.source===e.source&&n.chosen_at===e.chosen_at}function Be(n){return n instanceof I&&n.status>=400&&n.status<500&&n.status!==401&&n.status!==408&&n.status!==429}function Xe(){try{return globalThis.localStorage}catch{return}}function ze(n){let e=typeof n=="object"&&n!==null?n.version:void 0;return typeof e=="object"&&e!==null?e.v:void 0}function me(n){let e=typeof n=="object"&&n!==null?n.version:void 0;return typeof e=="number"&&Number.isFinite(e)?e:void 0}var Ut=`
|
|
3
3
|
:host{display:block;color-scheme:light dark;font:15px/1.4 system-ui,-apple-system,"Segoe UI",Roboto,sans-serif}
|
|
4
4
|
.list{display:flex;flex-direction:column;gap:8px;margin:0;padding:0;list-style:none}
|
|
5
5
|
.item{position:relative;display:flex;gap:12px;align-items:flex-start;padding:12px 40px 12px 12px;border-radius:12px;background:var(--bg);color:var(--fg);cursor:pointer;outline:none}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
1
|
+
/*! palbase 0.13.1 — Palbase SDK License (see LICENSE) */
|
|
2
2
|
var Rt=d=>[...new Uint8Array(d)].map(t=>t.toString(16).padStart(2,"0")).join(""),At=d=>`pw-font-${d}`;function ne(d){return(typeof d=="string"?/^asset:([0-9a-f-]{36})$/.exec(d):null)?.[1]}async function an(d,t={}){let a={},l=t.fetch??((c,p)=>globalThis.fetch(c,p));return await Promise.all(d.map(async c=>{try{if(!/^https:\/\//.test(c.url))return;let p=await l(c.url,{signal:t.signal,credentials:"omit"});if(!p.ok)return;let g=await p.arrayBuffer();if(g.byteLength!==c.bytes&&c.bytes>0||Rt(await globalThis.crypto.subtle.digest("SHA-256",g))!==c.sha256.toLowerCase())return;let w=_t(c.kind,new Uint8Array(g));if(w===void 0)return;let y=await Et(c,g,w,t);y&&(a[c.id]=y)}catch{}})),a}var C=(d,t,a=0)=>d.length>=a+t.length&&t.every((l,c)=>d[a+c]===l),W=d=>[...d].map(t=>t.charCodeAt(0));function _t(d,t){switch(d){case"image":return C(t,[137,80,78,71,13,10,26,10])?"image/png":C(t,[255,216,255])?"image/jpeg":C(t,W("RIFF"))&&C(t,W("WEBP"),8)?"image/webp":void 0;case"video":return C(t,W("ftyp"),4)?C(t,W("qt "),8)?"video/quicktime":"video/mp4":C(t,[26,69,223,163])?"video/webm":void 0;case"font":return C(t,W("wOF2"))?"font/woff2":C(t,W("wOFF"))?"font/woff":C(t,W("OTTO"))?"font/otf":C(t,[0,1,0,0])||C(t,W("true"))?"font/ttf":void 0;case"html":return C(t,[80,75,3,4])||C(t,[80,75,5,6])?"application/zip":void 0;default:return}}async function Et(d,t,a,l){switch(d.kind){case"image":case"video":return{kind:d.kind,url:URL.createObjectURL(new Blob([t],{type:a}))};case"font":{let c=At(d.id),p=globalThis.FontFace,g=l.fonts??globalThis.document?.fonts;if(!p||!g)return;let h=new p(c,t,{display:"block"});return await h.load(),g.add(h),{kind:"font",url:"",family:c}}case"html":{let c=await Lt(new Uint8Array(t)),p=Ot(c);return p===void 0?void 0:{kind:"html",url:"",html:p}}}}async function Lt(d){let t=new DataView(d.buffer,d.byteOffset,d.byteLength),a=-1;for(let h=d.length-22;h>=Math.max(0,d.length-22-65535);h--)if(t.getUint32(h,!0)===101010256){a=h;break}if(a<0)throw new Error("not a zip");let l=t.getUint16(a+10,!0),c=t.getUint32(a+16,!0),p=new Map,g=0;for(let h=0;h<l;h++){if(t.getUint32(c,!0)!==33639248)throw new Error("a broken zip");let w=t.getUint16(c+10,!0),y=t.getUint32(c+20,!0),m=t.getUint32(c+24,!0),v=t.getUint16(c+28,!0),_=t.getUint16(c+30,!0),P=t.getUint16(c+32,!0),R=t.getUint32(c+42,!0),x=new TextDecoder().decode(d.subarray(c+46,c+46+v));if(c+=46+v+_+P,x.endsWith("/"))continue;if(x.startsWith("/")||x.split("/").includes(".."))throw new Error("a path leaving the zip");if(g+=m,p.size>=200||g>20971520)throw new Error("a zip too large");let T=R+30+t.getUint16(R+26,!0)+t.getUint16(R+28,!0),O=d.subarray(T,T+y);if(w===0)p.set(x,O);else if(w===8)p.set(x,await Pt(O));else throw new Error("a zip entry compressed another way")}return p}async function Pt(d){let t=new Response(new Uint8Array(d)).body.pipeThrough(new DecompressionStream("deflate-raw"));return new Uint8Array(await new Response(t).arrayBuffer())}var Tt={html:"text/html",css:"text/css",js:"text/javascript",mjs:"text/javascript",json:"application/json",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",webp:"image/webp",gif:"image/gif",svg:"image/svg+xml",mp4:"video/mp4",webm:"video/webm",woff2:"font/woff2",woff:"font/woff",ttf:"font/ttf",otf:"font/otf"};function qe(d,t){let a=Tt[d.split(".").pop()?.toLowerCase()??""]??"application/octet-stream",l="";for(let c=0;c<t.length;c+=32768)l+=String.fromCharCode(...t.subarray(c,c+32768));return`data:${a};base64,${btoa(l)}`}var $t="default-src 'none'; img-src data:; media-src data:; font-src data:; style-src 'unsafe-inline' data:; script-src 'unsafe-inline' data:";function Ot(d){let t=d.get("index.html");if(!t)return;let a=new TextDecoder().decode(t),l=y=>new TextDecoder().decode(d.get(y)),c=y=>{let m=y.replace(/^\.\//,"").split(/[?#]/)[0];return d.has(m)?m:void 0},p=y=>y.replace(/url\(\s*(['"]?)([^'")]+)\1\s*\)/g,(m,v,_)=>{let P=c(_);return P?`url("${qe(P,d.get(P))}")`:m}),g=globalThis.DOMParser;if(!g)return;let h=new g().parseFromString(a,"text/html");for(let y of[...h.querySelectorAll('link[rel~="stylesheet"][href]')]){let m=c(y.getAttribute("href")),v=h.createElement("style");v.textContent=m?p(l(m)):"",y.replaceWith(v)}for(let y of[...h.querySelectorAll("style")])y.textContent=p(y.textContent??"");for(let y of[...h.querySelectorAll("[src], [href], [poster]")])for(let m of["src","href","poster"]){let v=y.getAttribute(m);if(v===null)continue;let _=c(v);_?y.setAttribute(m,qe(_,d.get(_))):/^(https?:)?\/\//i.test(v)&&y.removeAttribute(m)}for(let y of[...h.querySelectorAll("[style]")])y.setAttribute("style",p(y.getAttribute("style")??""));let w=h.createElement("meta");return w.setAttribute("http-equiv","Content-Security-Policy"),w.setAttribute("content",$t),h.head.prepend(w),`<!doctype html>${h.documentElement.outerHTML}`}var K=(d,t,a)=>`M${d-a} ${t}a${a} ${a} 0 1 0 ${2*a} 0a${a} ${a} 0 1 0 ${-2*a} 0`,de={ad_free:["M3 7h18v10H3z","M4 4l16 16"],bell:["M6 16v-5a6 6 0 0 1 12 0v5l2 2H4z","M10 21a2 2 0 0 0 4 0"],bolt:["M13 2L4 14h7l-1 8 9-12h-7z"],book:["M5 4h11a3 3 0 0 1 3 3v13H8a3 3 0 0 1-3-3z","M5 17a3 3 0 0 1 3-3h11"],chart:["M3 20h18","M6 20v-8","M11 20V5","M16 20v-6","M21 20V9"],chat:["M4 5h16v11H9l-5 4z"],check:["M5 12l5 5 9-10"],check_circle:[K(12,12,9),"M8 12l3 3 5-6"],clock:[K(12,12,9),"M12 7v5l3 2"],cloud:["M7 18a4 4 0 0 1-.5-7.97A6 6 0 0 1 18 9a4.5 4.5 0 0 1-.5 9z"],crown:["M3 8l4 4 5-7 5 7 4-4-2 11H5z"],download:["M12 4v11","M7 10l5 5 5-5","M4 20h16"],gift:["M3 9h18v4H3z","M5 13v8h14v-8","M12 9v12","M12 9C10 5 6 5 6 7.5S12 9 12 9zm0 0c2-4 6-4 6-1.5S12 9 12 9z"],globe:[K(12,12,9),"M3 12h18","M12 3a14 14 0 0 1 0 18a14 14 0 0 1 0-18z"],heart:["M12 20s-7-4.5-9-9a4.5 4.5 0 0 1 9-3 4.5 4.5 0 0 1 9 3c-2 4.5-9 9-9 9z"],infinity:["M7 9a3 3 0 1 0 0 6c3 0 7-6 10-6a3 3 0 1 1 0 6c-3 0-7-6-10-6z"],lock_open:["M5 11h14v10H5z","M8 11V7a4 4 0 0 1 7.5-2"],music:["M9 18V5l11-2v13",K(6,18,3),K(17,16,3)],people:[K(9,8,3.5),"M2 20a7 7 0 0 1 14 0","M16 4.5a3.5 3.5 0 0 1 0 7","M18 14a6 6 0 0 1 4 6"],person:[K(12,8,4),"M4 21a8 8 0 0 1 16 0"],photo:["M3 5h18v14H3z",K(8.5,9.5,1.5),"M3 17l5-5 4 4 3-3 6 6"],shield:["M12 3l8 3v6c0 5-3.5 8-8 9-4.5-1-8-4-8-9V6z"],sparkles:["M12 3l1.8 5.2L19 10l-5.2 1.8L12 17l-1.8-5.2L5 10l5.2-1.8z","M19 15l.8 2.2L22 18l-2.2.8L19 21l-.8-2.2L16 18l2.2-.8z"],star:["M12 3l2.8 5.7 6.2.9-4.5 4.4 1 6.2L12 17.3l-5.5 2.9 1-6.2L3 9.6l6.2-.9z"],video:["M3 6h12v12H3z","M15 10l6-3v10l-6-3z"],arrow_right:["M4 12h15","M13 6l6 6-6 6"],calendar:["M4 6h16v15H4z","M4 10h16","M8 3v5","M16 3v5"],close:["M6 6l12 12","M18 6L6 18"],lock:["M5 11h14v10H5z","M8 11V7a4 4 0 0 1 8 0v4"],play:["M7 4l13 8-13 8z"],quote:["M5 17c3 0 4-2 4-5V7H4v5h3","M15 17c3 0 4-2 4-5V7h-5v5h3"],trophy:["M7 4h10v5a5 5 0 0 1-10 0z","M7 6H4v2a3 3 0 0 0 3 3","M17 6h3v2a3 3 0 0 1-3 3","M12 14v4","M8 21h8","M9 18h6v3H9z"]};var Be="http://www.w3.org/2000/svg";function pe(d,t,a){let l=d.createElementNS(Be,"svg");l.setAttribute("viewBox","0 0 24 24"),l.setAttribute("width",String(a)),l.setAttribute("height",String(a)),l.setAttribute("fill","none"),l.setAttribute("stroke","currentColor"),l.setAttribute("stroke-width","2"),l.setAttribute("stroke-linecap","round"),l.setAttribute("stroke-linejoin","round"),l.setAttribute("aria-hidden","true"),l.setAttribute("focusable","false");for(let c of t){let p=d.createElementNS(Be,"path");p.setAttribute("d",c),l.append(p)}return l}var dn=2,pn=2,f=(d,t=!1)=>({kind:"value",value:"plain",def:d,required:t}),j=d=>({kind:"value",value:"color",def:d}),We=d=>({kind:"value",value:"spacing",def:d}),zt=d=>({kind:"value",value:"radius",def:d}),X=(d=!1)=>({kind:"text",required:d}),Me=(d,t=!1)=>({kind:"list",item:d,required:t}),se=(d,t=!1)=>({kind:"object",item:d,required:t}),Ke=(d=!1)=>({kind:"component",required:d}),Re={kind:"components"},Ge={stack:{axis:f("vertical"),spacing:We(0),align:f("center"),distribution:f("start"),scroll:f(!1),children:Re},text:{text:X(),spans:Me("span"),font:f(),size:f(),weight:f(),line_height:f(),letter_spacing:f(),color:{kind:"value",value:"textColor",def:"text"},align:f("center"),max_lines:f(),uppercase:f(!1)},image:{src:f(void 0,!0),fit:f("fit"),aspect:f(),mask:se("mask"),overlay:{kind:"value",value:"textColor"},alt:X(),decorative:f(!1)},icon:{name:f(void 0,!0),color:j("accent"),size:f(24)},video:{src:f(void 0,!0),poster:f(),autoplay:f(!0),loop:f(!0),mute:f(!0),controls:f(!1),fit:f("fill"),aspect:f(),alt:X()},button:{action:se("action",!0),content:Ke(!0)},purchase_button:{content:Ke(!0),package:f()},package:{product:f(void 0,!0),plan:f(void 0,!0),selected:f(!1),offer:f(),children:Re},tabs:{},switch:{},carousel:{pages:Re,peek:f(0),spacing:f(8),loop:f(!1),auto_advance_ms:f(),indicator:se("indicator"),height:f("")},countdown:{},timeline:{items:Me("timeline_item",!0),line_color:j("accent"),line_width:f(2),icon_color:j("on_accent"),color:j("text"),spacing:f(16)},features:{items:Me("feature",!0),icon_color:j("accent"),color:j("text"),spacing:f(12)},spacer:{size:We()},divider:{color:j("muted"),thickness:f(1)},custom_html:{src:f(void 0,!0),height:f("",!0)}},Ht={style:{padding:{kind:"edges"},margin:{kind:"edges"},width:f(""),height:f(""),max_width:f(),background:{kind:"fill"},border:se("border"),corners:{kind:"corners"},shadow:se("shadow"),opacity:f(1)},border:{width:f(),color:j("")},shadow:{color:j(""),radius:f(0),x:f(0),y:f(0)},linear:{type:f(""),angle:f(180),stops:f()},radial:{type:f(""),center_x:f(.5),center_y:f(.5),radius:f(.5),stops:f()},image_fill:{type:f(""),src:f(),fit:f("fill")},video_fill:{type:f(""),src:f(),poster:f(),loop:f(!0)},animation:{type:f(""),duration_ms:f(300),delay_ms:f(0),easing:f("ease_out")},action:{type:f(""),url:f(),sheet:f(),package:f()},mask:{shape:f(""),radius:zt(0),depth:f(16)},span:{text:X(!0),bold:f(!1),italic:f(!1),underline:f(!1),strikethrough:f(!1),color:j(""),link:f()},timeline_item:{icon:f(void 0,!0),title:X(!0),text:X(),color:j("")},feature:{icon:f(void 0,!0),text:X(!0)},indicator:{style:f("dots"),color:j("muted"),active_color:j("accent"),size:f(8),spacing:f(6)},typography:{font:f("system"),size:f(),weight:f(400),line_height:f(),letter_spacing:f(0),text_style:f("body")}},Xe=new Set(["package","purchase_button"]),Ct={action:{type:f(""),url:f(),link:f(),sheet:f(),placement:f(),name:f(),value:f(),offer:f(),dismiss:f(!0)},presentation:{type:f(""),position:f("bottom"),auto_dismiss_seconds:f(),dismissible:f(!0),backdrop:j("#00000080")}},jt={modal:["type","dismissible","backdrop"],fullscreen:["type"],banner:["type","position","auto_dismiss_seconds","dismissible"],card:["type"]},Ft={linear:"linear",radial:"radial",image:"image_fill",video:"video_fill"},Nt=["top","bottom","leading","trailing"],Dt=["top_leading","top_trailing","bottom_leading","bottom_trailing"],Jt=Object.keys(Ge),un=Jt.filter(d=>!Xe.has(d)),Ye=/\{\{\s*([^{}]*?)\s*\}\}/g,Q=(d,t)=>typeof d=="object"&&d!==null&&Object.hasOwn(d,t),M=d=>typeof d=="object"&&d!==null&&!Array.isArray(d)?d:{},I=d=>Array.isArray(d)?d:[],G=(d,t)=>d??t;function It(d){let t="";for(let a of new TextEncoder().encode(d)){let l=String.fromCharCode(a);t+=/^[A-Za-z0-9._~-]$/.test(l)?l:`%${a.toString(16).toUpperCase().padStart(2,"0")}`}return t}function Vt(d){let t=Math.floor(d/86400),a=Math.floor(d%86400/3600),l=Math.floor(d%3600/60),c=d%60,p=h=>String(h).padStart(2,"0");return{countdown:t>0?`${t}d ${p(a)}:${p(l)}:${p(c)}`:a>0?`${a}:${p(l)}:${p(c)}`:`${p(l)}:${p(c)}`,days:String(t),hours:p(a),minutes:p(l),seconds:p(c)}}function fn(d){let t=[],a=c=>{if(Array.isArray(c))return c.forEach(a);if(typeof c!="object"||c===null)return;let p=c;if(p.type==="package"&&typeof p.product=="string"&&typeof p.plan=="string"){let g=`${p.product}.${p.plan}`;t.includes(g)||t.push(g)}for(let g of Object.keys(p).sort())a(p[g])},l=d;for(let c of["header","root","footer"])a(l[c]);for(let c of Object.keys(M(l.sheets)).sort())a(M(M(l.sheets)[c]).root);return t}function Ut(d){let t=new Map,a=c=>{if(Array.isArray(c))return c.forEach(a);if(typeof c!="object"||c===null)return;let p=c;if(p.type==="package"&&typeof p.offer=="string"){let g=`${p.product}.${p.plan}`;t.has(g)||t.set(g,p.offer)}for(let g of Object.keys(p).sort())a(p[g])},l=d;for(let c of["header","root","footer","sheets"])a(l[c]);return t}function gn(d,t){return _e(d,t).tree}function _e(d,t){return new ue("paywall",d,t).resolve()}function hn(d,t){return Ee(d,t).tree}function Ee(d,t){let{variables:a,...l}=t;return new ue("message",d,{...l,packages:{"":{...a}}}).resolve()}var ue=class{kind;d;opts;lang;texts={};palette;typography={};radii;spacing;packages;offers;selected="";tab="";paths=new WeakMap;tabsShown={};switchesOn={};countdowns={};constructor(t,a,l){this.kind=t,this.d=a,this.opts=l,this.offers=Ut(a);let c={};for(let[y,m]of Object.entries(l.packages??{})){let v={...m};this.open(y)||(m.price!==void 0?v.offer_price=m.price:delete v.offer_price),c[y]=v}this.packages=c;let p=M(this.d.locales),g=String(this.d.default_locale??""),h=l.locale;Q(p,h)||(h=h.split("-")[0]??"",Q(p,h)||(h=g)),this.lang=h;for(let y of[g,h])for(let[m,v]of Object.entries(M(p[y])))typeof v=="string"&&(this.texts[m]=v);let w=M(this.d.theme);this.palette=M(M(w.colors)[l.appearance]);for(let[y,m]of Object.entries(M(w.typography))){let v={};for(let[_,P]of Object.entries(this.objectFields("typography"))){let R=G(M(m)[_],P.def);R!=null&&(v[_]=R)}this.typography[y]=v}this.radii=M(w.radii),this.spacing=M(w.spacing)}open(t){let a=this.offers.get(t);return a!==void 0&&(this.opts.offers??[]).includes(a)}fields(t){if(!(this.kind==="message"&&Xe.has(t)))return Ge[t]}objectFields(t){return(this.kind==="message"?Ct[t]:void 0)??Ht[t]??{}}resolve(){let[t,a]=this.initialState();this.tab=t,this.selected=this.kind==="paywall"?a:"";let l={theme:{colors:this.palette,typography:this.typography,radii:this.radii,spacing:this.spacing}};this.kind==="paywall"&&(l.selected=a);let c=this.d.presentation;if(typeof c=="object"&&c!==null){let g=this.item("presentation",M(c),void 0)??{},h=jt[String(M(c).type)]??[];for(let w of Object.keys(g))h.includes(w)||delete g[w];l.presentation=g}for(let g of["header","root","footer"]){let h=this.d[g];if(typeof h=="object"&&h!==null){let w=this.component(M(h),g,"",!1);w&&(l[g]=w)}}let p={};if(typeof this.d.sheets=="object"&&this.d.sheets!==null){let g={};for(let[h,w]of Object.entries(M(this.d.sheets))){let y=this.component(M(M(w).root),`sheets.${h}.root`,"",!1);y&&(g[h]=y);let m=this.text(M(w).title,this.packages[this.selected]);m!==null&&(p[h]=m)}l.sheets=g}return{tree:l,pathOf:g=>this.paths.get(g),tabs:this.tabsShown,switches:this.switchesOn,sheetTitles:p,countdowns:this.countdowns,language:this.lang}}switchOn(t,a){return this.opts.switches&&Object.hasOwn(this.opts.switches,a)?this.opts.switches[a]:this.opts.switch?this.opts.switch==="on":t.default===!0}tabShown(t,a){let c=I(t.tabs).map(M).map(g=>String(g.id)),p=this.opts.tabs?.[a];return p!==void 0&&c.includes(p)?p:this.opts.tab?this.opts.tab:typeof t.default=="string"&&t.default!==""?t.default:c[0]??""}initialState(){let t="",a="",l="",c="",p=(h,w)=>{if(Array.isArray(h)){h.forEach((m,v)=>p(m,`${w}[${v}]`));return}if(typeof h!="object"||h===null)return;let y=h;switch(y.type){case"package":{let m=`${y.product}.${y.plan}`;l===""&&(l=m),y.selected===!0&&a===""&&(a=m);break}case"switch":{let m=this.switchOn(y,w),v=m?y.on_package:y.off_package;typeof v=="string"&&c===""&&(c=v),p(m?y.on:y.off,`${w}.${m?"on":"off"}`);return}case"tabs":{let m=this.tabShown(y,w);t===""&&(t=m),I(y.tabs).forEach((v,_)=>{let P=M(v);P.id===m&&(typeof P.package=="string"&&c===""&&(c=P.package),p(P.content,`${w}.tabs[${_}].content`))});return}}for(let m of Object.keys(y).sort())m!=="sheets"&&p(y[m],w===""?m:`${w}.${m}`)};for(let h of["header","root","footer"])p(this.d[h],h);let g=this.opts.selected||c||a||l;return[t,g]}holds(t,a){let l=a||this.selected;for(let[c,p]of Object.entries(t))switch(c){case"selected_package":if(!I(p).includes(this.selected))return!1;break;case"intro_eligible":if((this.opts.eligible??[]).includes(l)!==p)return!1;break;case"offer_open":if(this.open(l)!==p)return!1;break;case"platform":if(!I(p).includes(this.opts.platform))return!1;break;case"locale":if(!I(p).includes(this.opts.locale)&&!I(p).includes(this.lang))return!1;break;case"appearance":if(p!==this.opts.appearance)return!1;break;case"tab":if(p!==this.tab)return!1;break}return!0}component(t,a,l,c){if(typeof t.visible=="object"&&t.visible!==null&&!this.holds(M(t.visible),l))return null;let p=String(t.type),g=l,h=c;p==="package"&&(g=`${t.product}.${t.plan}`,h=g===this.selected);let w={type:p};this.paths.set(w,a),Q(t,"id")&&(w.id=t.id);let y={...M(t.style)};h&&Object.assign(y,M(M(t.states).selected)),Object.keys(y).length>0&&(w.style=this.style(y)),typeof t.animation=="object"&&t.animation!==null&&(w.animation=this.defaults(M(t.animation),this.objectFields("animation")));let m=this.packages[g||this.selected];switch(p){case"tabs":return this.tabs(t,w,a,g);case"switch":return this.switchOf(t,w,a,g,h);case"countdown":return this.countdown(t,w,a,g,h);case"purchase_button":{let v=typeof t.package=="string"?t.package:this.selected;w.package=v,this.open(v)&&(w.offer=this.offers.get(v));let _=this.component(M(t.content),`${a}.content`,v,h);return _?(w.content=_,w):null}case"package":w.product=t.product,w.plan=t.plan,w.selected=h,typeof t.offer=="string"&&(this.opts.offers??[]).includes(t.offer)&&(w.offer=t.offer)}for(let[v,_]of Object.entries(this.fields(p)??{})){if(p==="package"&&(v==="product"||v==="plan"||v==="selected"||v==="offer"))continue;let P=t[v],R=Q(t,v);switch(_.kind){case"component":{if(!R)continue;let x=this.component(M(P),`${a}.${v}`,g,h);if(!x&&_.required)return null;x&&(w[v]=x);break}case"components":{let x=[];I(P).forEach((T,O)=>{let V=this.component(M(T),`${a}.${v}[${O}]`,g,h);V&&x.push(V)}),w[v]=x;break}case"text":{let x=this.text(P,m);if(x!==null)w[v]=x;else if(_.required||p==="text"&&v==="text"&&R)return null;break}case"list":{let x=[];for(let T of I(P)){let O=this.item(_.item,M(T),m);O&&x.push(O)}if(p==="text"&&x.length===0&&R)return null;R&&(w[v]=x);break}case"object":{if(R){let x=this.object(M(P),_.item,m);if(x===null&&_.required)return null;w[v]=x}else v==="indicator"&&(w[v]=this.object({},_.item,m));break}case"value":{let x=this.value(G(P,_.def),_);x!=null&&x!==""&&(w[v]=x);break}}}return p==="text"&&this.typeStyle(w),w}typeStyle(t){if(typeof t.size!="string"){t.size!==void 0&&t.size!==null&&(t.text_style="body");return}let a=this.typography[t.size];for(let l of["font","weight","line_height","letter_spacing","text_style"])!Q(t,l)&&a?.[l]!==void 0&&a?.[l]!==null&&(t[l]=a[l]);t.size=a?.size??null}tabs(t,a,l,c){let p=this.tabShown(t,l);this.tabsShown[l]=p;let g=[];return I(t.tabs).forEach((h,w)=>{let y=M(h),m=y.id===p,v=this.component(M(y.label),`${l}.tabs[${w}].label`,c,m);if(g.push({id:y.id,selected:m,label:v}),m){let _=this.component(M(y.content),`${l}.tabs[${w}].content`,c,!1);_&&(a.content=_)}}),a.tabs=g,typeof t.bar=="object"&&t.bar!==null&&(a.bar=this.style(M(t.bar))),a}switchOf(t,a,l,c,p){let g=this.switchOn(t,l);this.switchesOn[l]=g,a.on=g;let h=this.text(t.label,this.packages[c||this.selected]);h!==null&&(a.label=h),a.tint=this.color(String(G(t.tint,"accent")));let w=g?"on":"off",y=this.component(M(t[w]),`${l}.${w}`,c,p);return y&&(a.content=y),a}countdown(t,a,l,c,p){let g=M(t.target),h=this.opts.now??Date.now(),w;if(typeof g.after_open_seconds=="number"?w=Math.trunc(g.after_open_seconds)-(this.opts.openedSecondsAgo??0):w=Math.trunc((Date.parse(String(g.at))-h)/1e3),w>0){a.state="counting",a.remaining_seconds=w,this.countdowns[l]=w;let y=this.packages,m={};for(let[_,P]of Object.entries(y))m[_]={...P,...Vt(w)};this.packages=m;let v=this.component(M(t.counting),`${l}.counting`,c,p);return v&&(a.content=v),this.packages=y,a}if(a.state="ended",a.remaining_seconds=0,typeof t.ended=="object"&&t.ended!==null){let y=this.component(M(t.ended),`${l}.ended`,c,p);y&&(a.content=y)}return a}item(t,a,l){let c={};for(let[p,g]of Object.entries(this.objectFields(t))){let h=a[p];if(g.kind==="text"){let w=this.text(h,l);if(w!==null)c[p]=w;else if(g.required)return null}else{let w=g.def,y=this.value(G(h,w),g);y!=null&&(Q(a,p)||w!=null&&w!=="")&&(c[p]=y)}}return c}object(t,a,l){if(a==="style")return this.style(t);let c=this.item(a,t,l)??{};if(a==="action")for(let p of["url","link"]){if(typeof c[p]!="string")continue;let g=qt(c[p],l);if(g===null)return null;c[p]=g}return c}defaults(t,a){let l={};for(let[c,p]of Object.entries(a)){let g=G(t[c],p.def);g!=null&&g!==""&&(l[c]=g)}return l}style(t){let a={};for(let[l,c]of Object.entries(t)){let p=this.objectFields("style")[l];if(!p){a[l]=c;continue}switch(p.kind){case"edges":a[l]=this.sides(c,Nt,this.spacing);break;case"corners":a[l]=this.sides(c,Dt,this.radii);break;case"fill":a[l]=this.fill(c);break;case"object":{let g=M(c),h={};for(let[w,y]of Object.entries(this.objectFields(p.item))){let m=G(g[w],y.def);m!=null&&m!==""&&(h[w]=this.value(m,y))}a[l]=h;break}default:a[l]=c}}return a}sides(t,a,l){let c={};for(let p of a){let g=typeof t=="object"&&t!==null?G(M(t)[p],0):t;c[p]=Ae(g,l)}return c}fill(t){if(typeof t=="string")return{type:"color",color:this.color(t)};let a=M(t),l=this.defaults(a,this.objectFields(Ft[String(a.type)]??""));return Array.isArray(a.stops)&&(l.stops=a.stops.map(c=>({color:this.color(String(M(c).color)),at:M(c).at}))),l}value(t,a){if(a.kind!=="value")return t;switch(a.value){case"color":return typeof t=="string"&&t!==""?this.color(t):t;case"textColor":return typeof t=="string"?this.color(t):t==null?t:this.fill(t);case"spacing":return Ae(t,this.spacing);case"radius":return Ae(t,this.radii);default:return t}}color(t){let a=Object.hasOwn(this.palette,t)?this.palette[t]:void 0;return typeof a=="string"?a:t}text(t,a){let l;if(typeof t=="string")l=t;else if(typeof t=="object"&&t!==null&&!Array.isArray(t)){let p=t.t;l=typeof p=="string"&&Object.hasOwn(this.texts,p)?this.texts[p]:""}else return null;let c=!1;return l=l.replace(Ye,(p,g)=>{let h=a&&Object.hasOwn(a,g)?a[g]:void 0;return typeof h!="string"||h===""?(c=!0,""):h}),c||l.trim()===""?null:l}};function qt(d,t){let a=!1,l=d.replace(Ye,(c,p)=>{let g=t&&Object.hasOwn(t,p)?t[p]:void 0;return typeof g!="string"||g===""?(a=!0,""):It(g)});return a?null:l}function Ae(d,t){return typeof d=="string"?Object.hasOwn(t,d)?t[d]:null:d}var Bt={packages:"Choose a plan",close:"Close",restore:"Restore purchases",page:(d,t)=>`${d} of ${t}`},ee={system:'-apple-system, BlinkMacSystemFont, "SF Pro Text", system-ui, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif',rounded:'ui-rounded, "SF Pro Rounded", Nunito, "Varela Round", system-ui, -apple-system, sans-serif',serif:'ui-serif, "New York", "Iowan Old Style", Georgia, "Times New Roman", serif',mono:'ui-monospace, "SF Mono", Menlo, Consolas, "Liberation Mono", monospace'},Wt=1.35,Ze=20,Kt=new Set(["button","purchase_button","package","text"]),Gt=new Set(["ar","he","fa","ur","ps","yi","dv","ug","ku","sd"]),Qe={ease_out:"cubic-bezier(0.16, 1, 0.3, 1)",ease_in_out:"cubic-bezier(0.65, 0, 0.35, 1)",spring:"cubic-bezier(0.34, 1.56, 0.64, 1)"},Xt={start:"flex-start",center:"center",end:"flex-end",stretch:"stretch"},Yt={start:"flex-start",center:"center",end:"flex-end",space_between:"space-between",space_around:"space-around",space_evenly:"space-evenly"},Zt={stack:["children"],package:["children"],button:["content"],purchase_button:["content"],tabs:["tabs","content"],switch:["content"],carousel:["pages"],countdown:["content"]},Qt={package:["selected"],purchase_button:["package"],switch:["on"],countdown:["state","remaining_seconds"]},en=`
|
|
3
3
|
:host{display:block;height:100%}
|
|
4
4
|
.pw2{position:relative;box-sizing:border-box;display:flex;flex-direction:column;height:100%;overflow:hidden;font-family:${ee.system};font-size:1rem;line-height:1.3;-webkit-font-smoothing:antialiased;-webkit-text-size-adjust:100%;text-rendering:optimizeLegibility}
|