palbase 0.68.0 → 0.69.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/dist/ai/index.js +2 -2
  2. package/dist/ai-sdk/index.js +2 -2
  3. package/dist/backend/engine.js +2 -2
  4. package/dist/backend/env.js +1 -1
  5. package/dist/backend/index.js +3 -3
  6. package/dist/backend/stack.js +1 -1
  7. package/dist/backend/test.js +2 -2
  8. package/dist/chunks/{2ZHSNWVZ.js → 37KUGTKN.js} +2 -2
  9. package/dist/chunks/{UJLFALKX.js → BCSBO6QR.js} +2 -2
  10. package/dist/chunks/BZYYDYLF.js +2 -0
  11. package/dist/chunks/{22GRHCVI.js → CD2TYINV.js} +1 -1
  12. package/dist/chunks/{J7WJF7F4.js → CE6XFRSZ.js} +2 -2
  13. package/dist/chunks/{XJLAH42O.js → CPTZEOT3.js} +1 -1
  14. package/dist/chunks/CRK2KWFW.js +18 -0
  15. package/dist/chunks/{D6EUPFUR.js → D6ZVNWQ2.js} +2 -2
  16. package/dist/chunks/{4YV35XDP.js → EZW67SHF.js} +2 -2
  17. package/dist/chunks/{QQUIM4VK.js → F7WQUODK.js} +2 -2
  18. package/dist/chunks/{OWLXCD3D.js → FQEGZTR3.js} +1 -1
  19. package/dist/chunks/{QFZ4GCJH.js → ICNSKNUT.js} +2 -2
  20. package/dist/chunks/{YCDAV3WO.js → JFVOERVR.js} +2 -2
  21. package/dist/chunks/{622BI7EV.js → KOX5W2ID.js} +1 -1
  22. package/dist/chunks/{LUUXXMXH.js → LQF6CVJR.js} +1 -1
  23. package/dist/chunks/{EJAGO6ZV.js → OA2EJLJ2.js} +2 -2
  24. package/dist/chunks/{IZWB7FGX.js → OE772CLE.js} +2 -2
  25. package/dist/chunks/{3OP3YJ63.js → OZM5TI3D.js} +4 -3
  26. package/dist/chunks/{EGWQ3EJE.js → P234HHKR.js} +2 -2
  27. package/dist/chunks/{PP7MW4OT.js → PM3BWYB5.js} +1 -1
  28. package/dist/chunks/TXOMPE5N.js +13 -0
  29. package/dist/chunks/{F4B6ELAN.js → XK7JQGKM.js} +2 -2
  30. package/dist/chunks/{7SGTDHXJ.js → Y4FKEIZV.js} +2 -2
  31. package/dist/chunks/{XU4G5W72.js → YGIYMCYC.js} +1 -1
  32. package/dist/cli.js +227 -227
  33. package/dist/cloud/index.js +2 -2
  34. package/dist/refuse/ai-sdk.js +1 -1
  35. package/dist/refuse/ai.js +1 -1
  36. package/dist/refuse/backend.js +1 -1
  37. package/dist/refuse/cloud.js +1 -1
  38. package/dist/refuse/server.js +1 -1
  39. package/dist/server/index.js +2 -2
  40. package/dist/server/testing.js +2 -2
  41. package/dist/web/index.js +2 -2
  42. package/dist/web/message.js +2 -2
  43. package/dist/web/palbe.js +2 -2
  44. package/dist/web/payments-ui.js +2 -2
  45. package/dist/web/paywall.js +2 -2
  46. package/dist/web/push-sw.js +1 -1
  47. package/dist/web/ssr.js +2 -2
  48. package/dist/web/vite.js +2 -2
  49. package/package.json +2 -2
  50. package/types/ai/src/ai.d.ts +22 -0
  51. package/types/ai/src/chats.d.ts +65 -15
  52. package/types/ai/src/index.d.ts +4 -1
  53. package/types/ai/src/templates.d.ts +76 -0
  54. package/types/ai/src/workflows.d.ts +201 -0
  55. package/types/cloud/src/generated/project.d.ts +2 -2
  56. package/types/internal/src/modules/ai.d.ts +2242 -674
  57. package/types/internal/src/modules/calls.d.ts +297 -0
  58. package/types/internal/src/modules/events.d.ts +2 -2
  59. package/types/web/src/client.d.ts +3 -0
  60. package/types/web/src/index.d.ts +1 -0
  61. package/types/web/src/templates.d.ts +75 -0
  62. package/types/web/src/voice.d.ts +4 -1
  63. package/dist/chunks/5ZXXBM6L.js +0 -18
  64. package/dist/chunks/65QZXK2S.js +0 -2
  65. package/dist/chunks/MVY4K43S.js +0 -13
@@ -1,13 +0,0 @@
1
- /*! palbase 0.68.0 — Palbase SDK License (see LICENSE) */
2
- import{b as N,d as I,e as R}from"./D6EUPFUR.js";import{a as Q,f as Y,g as Z,j as X,k as ee,l as te,o as G,p as ne,q as se}from"./LUUXXMXH.js";import{d as A}from"./J7WJF7F4.js";import{a as E,b as z,c as T,e as j}from"./QFZ4GCJH.js";var p=class extends Error{kind;code;status;requestId;fields;retryAfter;data;constructor(e,t){super(t.message,t.cause===void 0?void 0:{cause:t.cause}),this.name="BackendError",this.kind=e,this.code=t.code,this.status=t.status??0,this.requestId=t.requestId,this.fields=t.fields,this.retryAfter=t.retryAfter,this.data=t.data}};function ie(n){return n instanceof p||typeof n=="object"&&n!==null&&n.name==="BackendError"&&typeof n.kind=="string"}function D(n){let e=n.body,t={code:n.code,message:n.message,status:n.status,requestId:n.requestId??We(e,"request_id"),data:S(e,"data"),cause:n};if(n.code==="network_error")return new p("network",t);if(n.status===401&&n.code==="insufficient_user_authentication")return new p("stepUpRequired",t);if(n.status===401&&n.code==="app_attest_required")return new p("attestationRequired",t);if(n.status===401)return new p("unauthorized",t);if(n.status===429)return new p("rateLimited",{...t,retryAfter:He(e)??n.retryAfter});let s=Je(e);return n.status===400&&s?new p("validation",{...t,fields:s}):new p("server",t)}function P(n){return n instanceof z||n instanceof Error&&n.name==="PalbaseError"}function re(n){return Array.isArray(n)&&n.length>0&&n.every(e=>typeof e=="object"&&e!==null&&typeof e.field=="string"&&typeof e.message=="string")}function Je(n){let e=S(S(n,"data"),"fields");if(re(e))return e;let t=S(n,"fields");return re(t)?t:void 0}function He(n){return oe(n,"retry_after")??oe(S(n,"data"),"retryAfter")}function S(n,e){if(typeof n=="object"&&n!==null)return n[e]}function oe(n,e){let t=S(n,e);return typeof t=="number"?t:void 0}function We(n,e){let t=S(n,e);return typeof t=="string"?t:void 0}var Ve=/^[A-Za-z_$][A-Za-z0-9_$]*$/,Ue=Object.freeze(["adoptSession","analytics","anonymousTelemetry","appContext","appEvent","appVersion","auth","callOnSignOut","calls","cancelCallOnSignOut","captureOnce","chatToolCall","chatWorkspaceFile","configuration","consent","currentSession","defaults","flags","installation","keychainItem","module","moduleDirectory","notify","offerTaker","onAppEvent","onSessionChange","onSignOut","preferences","realtime","scope","send","setLanguage","setPreferredLanguages","signedInUserNow","socket","storage","storedUserId","telemetry","transport","transportFor","upload","version","watchSessions","palbe","data","stores","iap","payments","messaging","notifications","perf","debug","equals","hashCode","toString","self","Type","init","deinit","subscript","then","constructor","__proto__"]),ze=new Set(Ue),Qe=new Set(["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf","__proto__","__defineGetter__","__defineSetter__","__lookupGetter__","__lookupSetter__"]);function O(n){return n==="then"||n==="toJSON"||Qe.has(n)}function ae(n){return n==="call"||n==="join"||O(n)}function de(n){return typeof n=="string"&&Ve.test(n)&&!ze.has(n)&&!O(n)}function le(n){return typeof n=="string"&&/^[a-z][a-z0-9-]{0,62}$/.test(n)}function ce(n){j(n)}function ue(n){return j(n).origin}var $=class n{me;reader;messages=new Map;told=new Map;responses=new Map;order=[];turn=null;goal=null;goalWords=new Set;voiceWords=new Set;voice=null;execution={target:null,generation:0,workspaceSeq:0,machineId:null,machineStatus:null,failoverAt:null,lastHandoff:null,compactions:[],offloads:[]};handoffGens=new Set;compactionSeqs=new Set;offloadKeys=new Set;history=new Map;forkedFrom=null;calls=new Map;thoughts=new Set;at=0;next=0;lowest=0;folded=0;paged=new Set;pagedFrom;pagedTo;racing=!1;replays;held=[];racedPages=[];heldTimer;heldSince=0;oldestLive;olderCursor;olderLeft=!0;loading;chatId;listeners=new Set;enders=new Set;snapshot;changing=!1;ended=!1;constructor(e=()=>{},t,s,r=!0){this.me=e,this.reader=t,this.chatId=s,this.replays=r}get hasOlder(){return this.olderLeft}loadOlder(e={}){return e.limit!==void 0&&e.turns!==void 0?Promise.reject(new TypeError("loadOlder: limit (events) or turns (turns), not both")):e.turns!==void 0&&(!Number.isSafeInteger(e.turns)||e.turns<1||e.turns>20)?Promise.reject(new TypeError(`loadOlder: turns is how many more of the chat's turns to read back to, 1 to 20 (got ${String(e.turns)})`)):(this.loading??=this.readOlder(e).finally(()=>this.loading=void 0),this.loading)}async readOlder(e){let t=e.turns;do{if(!this.olderLeft)return!1;let s=this.olderCursor,r=this.next===0&&this.olderCursor===void 0,d={...this.olderCursor!==void 0?{cursor:this.olderCursor}:this.oldestLive!==void 0?{before:this.oldestLive}:{},...e.limit!==void 0?{limit:e.limit}:{},...t!==void 0?{turns:t}:{},...e.signal?{signal:e.signal}:{}},a;if(e.load)a=await e.load(d);else{let f=this.idFor("loadOlder",e.chatId);if(!this.reader)throw new TypeError("loadOlder: this chat reads its past through the app's way: give load");a=await this.reader.parts(f,d)}if(this.ended)return!1;let l=(a?.parts??[]).map(f=>N(f)).filter(f=>f!==void 0);if(this.olderCursor=a?.nextCursor,this.olderLeft=typeof a?.nextCursor=="string"&&a.nextCursor!=="",this.before(l),r&&this.replays&&this.next===0&&this.pagedFrom!==void 0?(this.racing=!0,this.racedPages=l):this.racing&&(this.racedPages=l.concat(this.racedPages)),t===void 0||typeof a?.turns!="number"||s!==void 0&&this.olderCursor===s)break;t-=a.turns}while(t>0);return this.olderLeft}idFor(e,t){let s=t??this.chatId;if(typeof s!="string"||s==="")throw new TypeError(`${e}: the chat's id is not known yet (no chatId in the join, no message heard): give { chatId }`);return s}before(e){for(let i of e){let u=w(i);u<=0||(this.paged.add(u),(this.pagedFrom===void 0||u<this.pagedFrom)&&(this.pagedFrom=u),(this.pagedTo===void 0||u>this.pagedTo)&&(this.pagedTo=u))}let t=new n(this.me);t.thoughts=this.thoughts,t.lowest=this.lowest-e.length;let s=t.lowest;for(let i of e)t.at=s++,t.fold(i);this.folded+=t.folded,this.lowest=t.lowest,this.chatId??=t.chatId;let r=new Map;for(let[i,u]of t.messages){let m=this.told.get(i)??[],k=u;if(m.length>0)for(let C of m)k=ye(k,C);else k=this.messages.get(i)??u;r.set(i,k);let _=[...t.told.get(i)??[],...m];_.length>0&&this.told.set(i,_)}for(let[i,u]of this.messages)r.has(i)||r.set(i,u);this.messages.clear();for(let[i,u]of r)this.messages.set(i,u);let o=new Map;for(let[i,u]of t.responses){let m=this.responses.get(i);o.set(i,m?Ze(u,m):u)}for(let[i,u]of this.responses)o.has(i)||o.set(i,u);this.responses.clear();for(let[i,u]of o)this.responses.set(i,u);let d=new Set;for(let i of t.order)(i.type==="message"||i.type==="response")&&d.add(`${i.type}\0${i.key}`);let a=[...t.order],l=new Set([...t.messages.values()].flatMap(i=>i.responseId?[i.responseId]:[]));for(let i of this.order)if(!((i.type==="message"||i.type==="response")&&d.has(`${i.type}\0${i.key}`))&&!(i.type==="goal"&&i.event.seq>0&&t.goalWords.has(i.event.seq))&&!(i.type==="voice"&&t.voiceWords.has(K(i.event)))&&!(i.type==="handoff"&&t.handoffGens.has(i.event.generation))&&!(i.type==="compaction"&&i.event.seq>0&&t.compactionSeqs.has(i.event.seq))){if(i.type==="message"&&i.began&&i.turn!==null){let u=this.responses.get(i.turn);l.has(i.turn)?a.push({...i,began:!1,at:i.arrived}):a.push({...i,at:u&&u.at<i.arrived?u.at-.5:i.arrived});continue}a.push(i)}a.sort((i,u)=>i.at-u.at),this.order=a;for(let i of t.goalWords)this.goalWords.add(i);this.goal=null;for(let i of a)i.type==="goal"&&this.goalSaid(i.event);for(let i of t.voiceWords)this.voiceWords.add(i);let f=new Set;this.voice=null;for(let i of a)i.type==="voice"&&(this.voice=me(this.voice,i.event,f));for(let i of t.handoffGens)this.handoffGens.add(i);for(let i of t.compactionSeqs)this.compactionSeqs.add(i);for(let i of t.offloadKeys)this.offloadKeys.add(i);t.execution.generation>this.execution.generation&&(this.execution={...this.execution,target:t.execution.target,generation:t.execution.generation,workspaceSeq:t.execution.workspaceSeq,lastHandoff:t.execution.lastHandoff}),this.execution.machineStatus===null&&t.execution.machineStatus!==null&&(this.execution={...this.execution,machineId:t.execution.machineId,machineStatus:t.execution.machineStatus,failoverAt:t.execution.failoverAt});let c=[];for(let i of a)i.type==="compaction"&&c.push(i.event);let h=[...t.execution.offloads,...this.execution.offloads.filter(i=>!t.offloadKeys.has(ge(i)))];this.execution={...this.execution,compactions:c,offloads:h},this.turn??=t.turn;let y=new Map([...t.calls,...this.calls]);this.calls.clear();for(let[i,u]of y)this.calls.set(i,u);for(let[i,u]of t.history)this.history.has(i)||this.history.set(i,u);this.forkedFrom??=t.forkedFrom,this.changed()}get state(){return this.snapshot??=this.build()}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}async*[Symbol.asyncIterator](){let e,t,s=this.subscribe(()=>e?.()),r=()=>e?.();this.enders.add(r);try{for(;;){let o=this.state;if(o!==t){t=o,yield o;continue}if(this.ended)return;await new Promise(d=>e=d)}}finally{s(),this.enders.delete(r)}}end(){if(!this.ended){this.ended=!0,clearTimeout(this.heldTimer);for(let e of[...this.enders])e()}}takePayload(e){let t=N(e);t&&this.take(t)}take(e){if(!this.ended){if(this.racing){this.held.length===0&&(this.heldSince=Date.now()),this.held.push(e);let t=w(e);t>0&&this.pagedTo!==void 0&&t>this.pagedTo?this.sortHeld():(clearTimeout(this.heldTimer),this.heldTimer=he(setTimeout(()=>this.quiet(),pe)));return}this.takeNow(e)}}quiet(){let e=this.held.map(w).filter(s=>s>0);e.length>0&&e.every(s=>!this.paged.has(s)&&this.pagedFrom!==void 0&&s<this.pagedFrom)&&Date.now()-this.heldSince<Ye?this.heldTimer=he(setTimeout(()=>this.quiet(),pe)):this.sortHeld()}takeNow(e){let t=w(e);t>0&&this.paged.has(t)||(t>0&&(this.oldestLive===void 0||t<this.oldestLive)&&(this.oldestLive=t),this.at=this.next++,this.fold(e)&&this.changed())}sortHeld(){clearTimeout(this.heldTimer),this.racing=!1;let e=this.held.splice(0),t=this.racedPages;this.racedPages=[];let s=[],r=[],o=e.findIndex(a=>this.paged.has(w(a))),d=o<0?-1:t.findIndex(a=>w(a)===w(e[o]));if(d>=0){let a=0;for(;a<o&&a<d&&fe(e[o-1-a],t[d-1-a]);)a++;let l=0;for(;o+l<e.length&&d+l<t.length&&fe(e[o+l],t[d+l]);)l++;s=e.slice(0,o-a),r=e.slice(o+l)}else{let a=e.find(f=>w(f)>0),l=a!==void 0&&this.pagedFrom!==void 0&&w(a)<this.pagedFrom;for(let f of e){let c=w(f);c>0&&!(this.pagedFrom!==void 0&&c<this.pagedFrom)&&(l=!1),(l?s:r).push(f)}}if(s.length>0){let a=Math.min(...s.map(w).filter(l=>l>0));this.before(s),Number.isFinite(a)&&(this.oldestLive=a,this.olderCursor=void 0)}for(let a of r)this.takeNow(a)}fold(e){switch(this.folded++,e.type){case"message":return this.chatId===void 0&&typeof e.message.chat_id=="string"&&e.message.chat_id!==""&&(this.chatId=e.message.chat_id),this.heard(e.message),!1;case"turn":{let t=this.response(e.response_id);t.status=e.status,t.waiting=e.waiting,t.error=e.error,t.end=typeof e.end=="string"?e.end:null,e.user_id!==void 0&&(t.startedBy=e.user_id),e.goal&&(t.goal={goalId:e.goal.goal_id,role:e.goal.role,seq:e.goal.seq}),this.turn=e;break}case"thinking":{let t=this.response(e.response_id);if(e.seq>0){if(this.thoughts.has(e.seq))return!1;this.thoughts.add(e.seq)}if(e.unavailable){t.marks.set("thinking:unavailable",{type:"thinking",text_offset:t.from+I(t.text),loose:t.text==="",cutAt:t.cut,thinking:{stepId:null,runId:e.run_id,text:"",unavailable:!0,model:e.model??null,reason:e.reason??null}});break}let s=`thinking:${e.step_id??`seq:${e.seq}`}`,r=t.marks.get(s);r?r.thinking={...r.thinking,text:r.thinking.text+e.text}:t.marks.set(s,{type:"thinking",text_offset:t.from+I(t.text),loose:t.text==="",cutAt:t.cut,thinking:{stepId:e.step_id??null,runId:e.run_id,text:e.text,unavailable:!1,model:null,reason:null}});break}case"goal":if(e.seq>0){if(this.goalWords.has(e.seq))return!1;this.goalWords.add(e.seq)}this.goalSaid(e),this.order.push({type:"goal",event:e,at:this.at});break;case"voice":{let t=K(e);if(this.voiceWords.has(t))return!1;this.voice=me(this.voice,e,this.voiceWords),this.order.push({type:"voice",event:e,at:this.at});break}case"transcript":return this.said(e),!1;case"history":e.forked_from&&(this.forkedFrom={chatId:e.forked_from.chat_id,beforeMessage:e.forked_from.before_message}),this.history.set(e.part,e.items);break;case"text":{let t=this.response(e.response_id);tt(t,e.offset,e.text),t.cut=t.cut===null?e.offset:Math.min(t.cut,e.offset);break}case"reset":{let t=this.response(e.response_id);e.offset<=t.from?(t.text="",t.from=Math.max(0,e.offset)):t.text=t.text.slice(0,R(t.text,e.offset-t.from)),t.cut=t.cut===null?e.offset:Math.min(t.cut,e.offset);break}case"tool":{this.response(typeof e.agent_response_id=="string"&&e.agent_response_id!==""?e.agent_response_id:e.response_id).marks.set(`tool:${e.call_id}`,e),this.calls.set(e.call_id,e);break}case"agent":{if(this.response(e.parent_response_id).marks.set(e.run_id?`agent:${e.run_id}`:`agent:seq:${e.seq}`,e),!e.response_id)break;let t=this.response(e.response_id);t.runId=e.run_id,t.agent=e.name,t.named=!0,t.parentId??=e.parent_response_id;break}case"session.handed_off":{if(this.handoffGens.has(e.generation))return!1;this.handoffGens.add(e.generation),e.generation>=this.execution.generation&&(this.execution={...this.execution,target:e.to_target,generation:e.generation,workspaceSeq:e.workspace_seq,machineId:e.to_target.compute.machine_id??null,failoverAt:null,lastHandoff:e}),this.order.push({type:"handoff",event:e,at:this.at});break}case"session.machine_status":{this.execution={...this.execution,machineId:e.machine_id||this.execution.machineId,machineStatus:e.status,failoverAt:e.failover_at??null};break}case"context.offloaded":{let t=ge(e);if(this.offloadKeys.has(t))return!1;this.offloadKeys.add(t),this.execution={...this.execution,offloads:[...this.execution.offloads,e]};break}case"context.compacted":{if(e.seq>0){if(this.compactionSeqs.has(e.seq))return!1;this.compactionSeqs.add(e.seq)}this.execution={...this.execution,compactions:[...this.execution.compactions,e]},this.order.push({type:"compaction",event:e,at:this.at});break}}return!0}goalSaid(e){if(e.kind==="set"&&e.goal){this.goal={id:e.goal_id,objective:e.goal.objective,rubric:e.goal.rubric,status:e.goal.status,stopCode:e.goal.stop_code,stopReason:e.goal.stop_reason,phase:e.goal.phase,maxTurns:e.goal.max_turns??null,maxCostUsd:e.goal.max_cost_usd??null,events:[e]};return}let t=this.goal;if(!t||t.id!==e.goal_id)return;let s={...t,events:[...t.events,e]};e.kind==="updated"&&e.goal?Object.assign(s,{objective:e.goal.objective,rubric:e.goal.rubric,status:e.goal.status,stopCode:e.goal.stop_code,stopReason:e.goal.stop_reason,phase:e.goal.phase,maxTurns:e.goal.max_turns??null,maxCostUsd:e.goal.max_cost_usd??null}):e.kind==="status_changed"&&typeof e.to=="string"?Object.assign(s,{status:e.to,stopCode:e.code??"",stopReason:e.reason??""}):e.kind==="cleared"&&Object.assign(s,{status:"cleared",stopReason:e.reason??""}),this.goal=s}heard(e){let t=et(e),s=this.messages.get(t);this.messages.set(t,ye(s,e));let r=this.told.get(t);r?r.push(e):this.told.set(t,[e]),s||this.place(e,t),this.changed()}said(e){let t=`voice\0${e.id}`,s=this.messages.get(t);this.messages.set(t,{clientId:"",id:e.id,text:e.text,author:e.user_id,authorName:e.author_name,delivery:"next",status:"delivered",error:null,responseId:null,createdAt:e.created_at,mine:!1,metadata:{},history:!1,truncated:!1,kind:"voice",voice:{id:e.voice_id,role:e.role},attachments:[]}),s||this.order.push({type:"message",key:t,at:this.at,arrived:this.at,turn:null,began:!1}),this.changed()}place(e,t){let s=e.response_id??null,r=s!==null&&![...this.messages.entries()].some(([l,f])=>l!==t&&f.responseId===s),o=r?this.responses.get(s):void 0,d={type:"message",key:t,at:o?o.at-.5:this.at,arrived:this.at,turn:s,began:r},a=o?this.order.findIndex(l=>l.type==="response"&&l.key===s):-1;a>=0?this.order.splice(a,0,d):this.order.push(d)}response(e){let t=this.responses.get(e);return t||(t={id:e,status:null,waiting:null,end:null,error:null,text:"",from:0,cut:null,marks:new Map,runId:null,agent:null,named:!1,parentId:null,startedBy:void 0,goal:null,at:this.at},this.responses.set(e,t),this.order.push({type:"response",key:e,at:this.at})),t}changed(){this.snapshot=void 0,!this.changing&&(this.changing=!0,queueMicrotask(()=>{if(this.changing=!1,this.listeners.size===0)return;let e=this.state;for(let t of[...this.listeners])try{t(e)}catch{}}))}build(){let e=this.me(),t=c=>e!==void 0&&c.startedBy===e,s=new Map;for(let c of this.responses.values()){let h=c.parentId!==null?this.responses.get(c.parentId)??c:c;s.set(c.id,nt(c,h.startedBy??null,t(h),c.goal??h.goal))}let r=new Map([...this.messages].map(([c,h])=>[c,e!==void 0&&h.author===e?{...h,mine:!0}:h])),o=[...this.history.entries()].sort(([c],[h])=>c-h).flatMap(([c,h])=>h.map((y,i)=>st(y,`${c}:${i}`,e))),d=[...o];for(let c of this.order)c.type==="goal"?d.push({type:"goal",goal:c.event}):c.type==="voice"?d.push({type:"voice",voice:c.event}):c.type==="handoff"?d.push({type:"handoff",handoff:c.event}):c.type==="compaction"?d.push({type:"compaction",compaction:c.event}):c.type==="message"?d.push({type:"message",message:r.get(c.key)}):this.responses.get(c.key).parentId===null&&d.push({type:"response",response:s.get(c.key)});let a=o.flatMap(c=>c.type==="message"?[c.message]:[]),l=o.flatMap(c=>c.type==="response"?[c.response]:[]),f=[...this.calls.values()].filter(c=>s.get(c.response_id)?.mine===!0);return{items:d,messages:[...a,...r.values()],responses:[...l,...s.values()],turn:this.turn,waiting:{approvals:f.filter(c=>c.status==="awaiting_approval"),outputs:f.filter(c=>c.status==="awaiting_output")},goal:this.goal,forkedFrom:this.forkedFrom,voice:this.voice?Xe(this.voice,e):null,execution:this.execution}}},pe=150,Ye=2e3;function fe(n,e){let t=w(n);return t>0||w(e)>0?t===w(e):JSON.stringify(n)===JSON.stringify(e)}function w(n){let e=n.seq;return typeof e=="number"&&e>0?e:0}function he(n){return n.unref?.(),n}function K(n){return`${n.voice_id}\0${n.status}`}function ge(n){return n.seq>0?`seq:${n.seq}`:`call:${n.call_id}:${n.ref??""}`}function me(n,e,t){return t.add(K(e)),(e.status==="closed"?n===null||n.voice_id===e.voice_id:!t.has(`${e.voice_id}\0closed`))?e:n}function ye(n,e){let t=e.status==="delivered"||e.status==="failed"?e.status:"pending";return{clientId:e.client_id,id:e.id??n?.id??null,text:e.text,author:e.author??null,authorName:e.author_name??"",delivery:e.delivery??"next",status:n?.status==="delivered"?"delivered":t,error:e.error??null,responseId:e.response_id??n?.responseId??null,createdAt:e.created_at??n?.createdAt??"",mine:!1,metadata:e.metadata??n?.metadata??{},history:!1,truncated:!1,kind:e.kind??n?.kind??"text",voice:e.voice?{id:e.voice.id,role:e.voice.role}:n?.voice??null,attachments:e.attachments?we(e.attachments):n?.attachments??[]}}function Ze(n,e){let t={...n,marks:new Map(n.marks)};e.status!==null&&(t.status=e.status,t.waiting=e.waiting,t.error=e.error,t.end=e.end),e.startedBy!==void 0&&(t.startedBy=e.startedBy),e.goal&&(t.goal=e.goal),e.named&&(t.runId=e.runId,t.agent=e.agent,t.named=!0),t.parentId=n.parentId??e.parentId,e.cut!==null&&(n.text===""||e.cut<=n.from?(t.text=e.text,t.from=e.text===""?Math.max(0,e.cut):e.from):t.text=n.text.slice(0,R(n.text,e.cut-n.from))+e.text,t.cut=n.cut===null?e.cut:Math.min(n.cut,e.cut));let s=r=>{if(n.text==="")return null;if(r!==null&&r<=n.from)return r;let o=I(n.text);return n.from+(r===null?o:Math.min(o,r-n.from))};for(let[r,o]of e.marks){let d=t.marks.get(r);if(d?.type==="thinking"&&o.type==="thinking"&&r!=="thinking:unavailable")t.marks.set(r,{...d,thinking:{...d.thinking,text:d.thinking.text+o.thinking.text}});else if(o.type==="thinking"&&o.loose){let a=s(o.cutAt);t.marks.set(r,a!==null?{...o,text_offset:a,loose:!1}:{...o,cutAt:o.cutAt===null?n.cut:n.cut===null?o.cutAt:Math.min(o.cutAt,n.cut)})}else t.marks.set(r,o)}return t}function Xe(n,e){return{id:n.voice_id,userId:n.user_id,mine:e!==void 0&&n.user_id===e,delegation:n.delegation,status:n.status,seconds:typeof n.seconds=="number"?n.seconds:null,closeReason:n.close_reason??""}}function we(n){return n.map((e,t)=>({kind:e.kind,name:e.name,contentType:e.content_type,size:e.size,sha256:e.sha256,position:t,bucket:e.bucket,path:e.path,workspacePath:e.workspace_path??null}))}function et(n){return`${n.author??""}\0${n.client_id}`}function tt(n,e,t){if(n.text===""||e<=n.from){n.from=Math.max(0,e),n.text=t;return}n.text=n.text.slice(0,R(n.text,e-n.from))+t}function nt(n,e,t,s){let r=[...n.marks.values()].map((l,f)=>({m:l,i:f,at:R(n.text,Math.max(0,(Number(l.text_offset)||0)-n.from))}));r.sort((l,f)=>l.at-f.at||l.i-f.i);let o=[],d=[],a=0;for(let{m:l,at:f}of r)f>a&&o.push({type:"text",text:n.text.slice(a,f)}),a=Math.max(a,f),l.type==="thinking"?(o.push({type:"thinking",thinking:l.thinking}),d.push(l.thinking)):o.push(l.type==="tool"?{type:"tool",tool:l}:{type:"agent",agent:l});return a<n.text.length&&o.push({type:"text",text:n.text.slice(a)}),{id:n.id,status:n.status,waiting:n.waiting,end:n.end,error:n.error,text:n.text,parts:o,runId:n.runId,agent:n.agent,parentId:n.parentId,startedBy:e,mine:t,thinking:d,goal:s,history:!1,truncated:!1}}function st(n,e,t){let s=n.text_truncated===!0;if(n.role==="user"){let r=n.author??null;return{type:"message",message:{clientId:n.client_id??"",id:n.message_id??null,text:n.text,author:r,authorName:n.author_name??"",delivery:"next",status:"delivered",error:null,responseId:null,createdAt:n.created_at??"",mine:t!==void 0&&r===t,metadata:n.metadata??{},history:!0,truncated:s,kind:"text",voice:null,attachments:we(n.attachments??[])}}}return{type:"response",response:{id:n.response_id??`history:${e}`,status:"completed",waiting:null,end:"completed",error:null,text:n.text,parts:n.text===""?[]:[{type:"text",text:n.text}],runId:null,agent:null,parentId:null,startedBy:null,mine:!1,thinking:[],goal:null,history:!0,truncated:s}}}var ve=[["ApiKeyAuth","userJWT"]];function be(n){return{async parts(e,t){let s={};t.limit!==void 0&&(s.limit=t.limit),t.turns!==void 0&&(s.turns=t.turns),t.cursor!==void 0?s.cursor=t.cursor:t.before!==void 0&&(s.before=t.before);let r=(await n.send({op:"ListChatParts",method:"GET",path:`/ai/chats/${T("ListChatParts","chat_id",e)}/parts`,auth:ve,answers:{200:"json"},query:s,signal:t.signal})).data;return{parts:r.parts,...r.next_cursor!==void 0?{nextCursor:r.next_cursor}:{},...r.turns!==void 0?{turns:r.turns}:{}}},async toolCall(e,t,s){if(typeof t!="string"||t==="")throw new TypeError("chatToolCall: callId is a tool part's call_id");let r=(await n.send({op:"GetChatToolCall",method:"GET",path:`/ai/chats/${T("GetChatToolCall","chat_id",e)}/tool-calls/${T("GetChatToolCall","call_id",t)}`,auth:ve,answers:{200:"json"},signal:s})).data;return{callId:r.call_id,name:r.name,status:r.status,runId:r.run_id,responseId:r.response_id,input:r.input,output:r.output,outputBytes:r.output_bytes,imageCount:r.image_count,isError:r.is_error}}}}var M=class extends Error{reason;constructor(e,t){super(e),this.name="GatewayError",this.reason=t}},ke=new WeakMap;async function Ee(n,e,t,s={},r=()=>{},o){let{pattern:d,events:a,messages:l,durable:f,chat:c}=rt(e),h=ot(d,t),y=ke.get(n);y||ke.set(n,y=new Map);let i=y,u=i.get(h)??{count:0};i.set(h,u),u.count++;let m=n.channel(h,f&&s.history!==!1?{after:0}:{});if(c&&!u.chat){let g=t.chatId,x=new $(r,o,typeof g=="string"&&g!==""?g:void 0,f&&s.history!==!1);u.chat=x,u.unchat=m.on("broadcast",v=>{v.event==="chat"&&x.takePayload(v.payload)})}let k=()=>{--u.count>0||(i.delete(h),u.unchat?.(),u.chat?.end(),m.leave())};try{await m.join()}catch{let g=m.state==="refused"?xe(m.refusal,"unavailable"):"socket closed";throw k(),new M(`gateway ${JSON.stringify(h)} was not joined: ${g}`,g)}let _=!1,C=new Set,W=()=>{if(!_){_=!0,Fe();for(let g of[...C])g();k()}},Fe=m.onClosed(W),V=g=>{if(_)return()=>{};let x=m.on("broadcast",b=>{typeof b.event=="string"&&a.has(b.event)&&g(b.event,E(b.payload))}),v=()=>{C.delete(v),x()};return C.add(v),v},U={topic:h,get seq(){return m.logSeq},on(g,x){if(typeof g=="function")return V((v,b)=>g({event:v,payload:b}));if(!a.has(g))throw new TypeError(`gateway ${JSON.stringify(d)} declares no event ${JSON.stringify(String(g))}`);if(typeof x!="function")throw new TypeError(`gateway ${JSON.stringify(d)}: on(${JSON.stringify(g)}, \u2026) takes the function the event is handed to`);return V((v,b)=>{v===g&&x(b)})},off(g){C.has(g)&&g()},async send(g,x){if(!l.has(g))throw new TypeError(`gateway ${JSON.stringify(d)} declares no message ${JSON.stringify(String(g))}`);let v=_?{status:"error",response:{reason:"not joined"}}:await m.push("broadcast",{type:"broadcast",event:g,payload:x});if(v.status==="ok")return E(v.response.reply);let b=xe(v.response,"unavailable");throw new M(`gateway ${JSON.stringify(h)} did not take ${JSON.stringify(g)}: ${b}`,b)},leave:W};return c&&Object.defineProperty(U,"chat",{value:u.chat,enumerable:!0}),U}function rt(n){let e=typeof n=="object"&&n!==null?n:{},t=s=>Array.isArray(s)&&s.every(r=>typeof r=="string");if(typeof e.pattern!="string"||e.pattern===""||!t(e.events)||!t(e.messages))throw new TypeError("join takes a gateway of the backend's generated module: its pattern, its events and its messages");return{pattern:e.pattern,events:new Set(e.events),messages:new Set(e.messages),durable:e.durable===!0,chat:e.chat===!0}}function ot(n,e){let t=typeof e=="object"&&e!==null?e:{};return n.split(":").map(s=>{if(!(s.startsWith("{")&&s.endsWith("}")&&s.length>2))return s;let r=s.slice(1,-1),o=Object.hasOwn(t,r)?t[r]:void 0;if(typeof o!="string"||o==="")throw new TypeError(`gateway ${JSON.stringify(n)} needs a value for ${JSON.stringify(r)}`);if(o.includes(":"))throw new TypeError(`gateway ${JSON.stringify(n)}: the value of ${JSON.stringify(r)} is one segment of the channel's name and cannot hold ":"`);return o}).join(":")}function xe(n,e){let t=n?.reason;return typeof t=="string"&&t!==""?t:e}var it=3600*1e3,q=new Map;function at(n,e,t=!1){let s=`${e.projectId}\0${e.signer}`,r=q.get(s);if(!t&&r&&Date.now()-r.at<it)return r.list;let o=(async()=>{let d=ne(),a;try{a=(await n.send({op:"GetTransitPublicKeys",method:"GET",path:"/secrets/transit/public",query:{nonce:d},auth:[["ApiKeyAuth"]],answers:{200:"json"}})).data}catch(l){throw new p("network",{code:"encryption_keys_unavailable",message:"the project's encryption keys could not be fetched: no encrypted field is sent without them",cause:l})}try{return await se(a,e.signer,e.projectId,d)}catch(l){throw new p("decode",{code:"encryption_keys_unverified",message:"the project's list of encryption keys does not verify with the key this app was built with: nothing is sealed to it",cause:l})}})();return q.set(s,{list:o,at:Date.now()}),o.catch(()=>{q.get(s)?.list===o&&q.delete(s)}),o}async function _e(n,e,t,s,r,o){let a=(await at(n,e,o)).keys[0];return Z(a.kid,a.key,Y(e.projectId,t,s,r))}function L(n,e,t,s){return e==null||!s||s.length===0?Promise.resolve(e):G(e,t,s,(r,o)=>X(n.key,r,o))}function Se(n,e,t,s){return e===void 0||!t||t.length===0?Promise.resolve(e):G(e,"/response",t,async(r,o)=>{if(!ee(o))throw new p("decode",{code:"field_not_encrypted",message:`${s}: ${r} came plain where the backend's contract says it is encrypted`});try{return await te(n.key,r,o)}catch(d){throw new p("decode",{code:"field_unopenable",message:`${s}: ${r} does not open with this call's key`,cause:d})}})}function Ce(n){return n instanceof p&&(n.code==="encryption_key_retired"||n.code==="encryption_key_unknown")}var B=class{pending="";dataLines=[];eventName;consume(e){this.pending+=e.replace(/\r\n/g,`
3
- `);let t=[],s=this.pending.indexOf(`
4
- `);for(;s!==-1;){let r=this.pending.slice(0,s);this.pending=this.pending.slice(s+1);let o=r.endsWith("\r")?r.slice(0,-1):r;if(o==="")this.dataLines.length>0&&t.push({event:this.eventName,payload:this.dataLines.join(`
5
- `)}),this.dataLines=[],this.eventName=void 0;else if(!o.startsWith(":")){if(o.startsWith("data:")){let d=o.slice(5);this.dataLines.push(d.startsWith(" ")?d.slice(1):d)}else if(o.startsWith("event:")){let d=o.slice(6);this.eventName=d.startsWith(" ")?d.slice(1):d}}s=this.pending.indexOf(`
6
- `)}return t}};async function*Te(n,e){let t=n.getReader(),s=new TextDecoder,r=new B;try{for(;;){let{done:o,value:d}=await t.read();if(o)break;for(let a of r.consume(s.decode(d,{stream:!0}))){if(a.event==="error")throw new p("network",{code:"stream_failed",message:`stream failed: ${a.payload}`});let l;try{l=JSON.parse(a.payload)}catch{throw new p("decode",{code:"invalid_frame",message:`stream frame is not valid JSON: ${a.payload.slice(0,120)}`})}yield E(l)}}}finally{e.abort();try{await t.cancel()}catch{}}}var dt={},Ie=new WeakMap;function zt(n,e,t,s,r,o=()=>{}){Ie.set(n,{project:e,machine:t,storage:s,socket:r,me:o})}var Pe=new Map,Re=new WeakMap;function Qt(n,e,t,s,r,o){if(!de(e))throw new p("validation",{code:"reserved_namespace",message:`Cannot register backend ${JSON.stringify(String(e))}: a backend's name is an identifier the client does not keep.`});let d=ue(n);if(!le(t))throw new TypeError(`${JSON.stringify(String(t))} is not a machine's name: a lowercase letter, then lowercase letters, digits and -`);ce(s),Me(r);for(let a of Object.keys(r))if(ae(a))throw Oe(a);if(o!==void 0)ft(o);else if($e(r))throw new p("validation",{code:"invalid_namespace_tree",message:`Backend ${e}: its routes carry encrypted fields, and its module holds no project id and signing key to seal them with \u2014 generate it again with palbase apps:sync`});(Pe.get(e)??lt(e)).set(d,{machine:t,url:s,tree:r,...o?{transit:{...o}}:{}})}function lt(n){let e=new Map;return Pe.set(n,e),Object.defineProperty(dt,n,{configurable:!0,get(){return ct(this,n,e)}}),e}function ct(n,e,t){let s=Ie.get(n);if(!s)return;let r=t.get(s.project);if(!r)throw new TypeError(`pb.${e} is the backend of ${[...t.keys()].join(" and ")}: this client is ${s.project}'s, and its user's session never goes to another project's machine`);let o=Re.get(n);o||Re.set(n,o=new Map);let d=o.get(e);if(d?.registration===r)return d.ns;let a={machine:()=>s.machine(r.url),storage:s.storage,name:r.machine,...r.transit?{transit:{project:s.storage,config:r.transit}}:{}},l=Object.assign({call:(f,c,h)=>wt(a.machine,f,c,h),join:(f,c,h)=>Ee(s.socket,f,c,h,s.me,be(s.storage))},qe(r.tree,a));return o.set(e,{registration:r,ns:l}),l}function Oe(n){return new p("validation",{code:"reserved_namespace",message:`Cannot register endpoint namespace ${JSON.stringify(n)}: the name is reserved.`})}function F(n){return typeof n.path=="string"&&typeof n.method=="string"}function ut(n,e){if(n.pathParams!==void 0){if(!Array.isArray(n.pathParams)||!n.pathParams.every(t=>typeof t=="string"))throw new p("validation",{code:"invalid_namespace_tree",message:`Descriptor '${e}': pathParams must be an array of strings.`});for(let t of n.pathParams)if(!n.path.includes(`{${t}}`))throw new p("validation",{code:"invalid_namespace_tree",message:`Descriptor '${e}': pathParams entry '${t}' has no '{${t}}' placeholder in the path.`})}if(n.sse!==void 0&&typeof n.sse!="boolean")throw new p("validation",{code:"invalid_namespace_tree",message:`Descriptor '${e}': sse must be a boolean.`});if(n.idempotent!==void 0&&typeof n.idempotent!="boolean")throw new p("validation",{code:"invalid_namespace_tree",message:`Descriptor '${e}': idempotent must be a boolean.`});if(n.upload!==void 0&&typeof n.upload!="boolean")throw new p("validation",{code:"invalid_namespace_tree",message:`Descriptor '${e}': upload must be a boolean.`});if(n.upload===!0&&(n.method!=="POST"||n.sse===!0))throw new p("validation",{code:"invalid_namespace_tree",message:`Descriptor '${e}': an upload endpoint is a POST, and no stream.`});if(n.sse===!0&&n.input==="query")throw new p("validation",{code:"invalid_namespace_tree",message:`Descriptor '${e}': an sse endpoint cannot take query input.`});if(n.input!==void 0&&n.input!=="body"&&n.input!=="query"&&n.input!=="none")throw new p("validation",{code:"invalid_namespace_tree",message:`Descriptor '${e}': input must be 'body', 'query' or 'none'.`});if(n.encryption!==void 0&&pt(n,e),n.errors!==void 0){for(let[t,s]of Object.entries(n.errors))if(typeof s!="function")throw new p("validation",{code:"invalid_namespace_tree",message:`Descriptor '${e}': errors['${t}'] must be a function.`})}}function pt(n,e){let t=n.encryption,s=r=>new p("validation",{code:"invalid_namespace_tree",message:`Descriptor '${e}': encryption ${r}.`});if(typeof t!="object"||t===null)throw s("is { request, response }");for(let[r,o]of[["request",["/body/","/query/"]],["response",["/response"]]]){let d=t[r];if(d!==void 0&&(!Array.isArray(d)||!d.every(a=>typeof a=="string"&&o.some(l=>a===l||a.startsWith(l.endsWith("/")?l:`${l}/`)))))throw s(`${r} is a list of places under ${o.join(" or ")}`)}if(n.upload===!0)throw s("is no upload\u2019s: storage seals nothing");if(n.sse===!0&&(t.response?.length??0)>0)throw s("of a streamed answer is none")}function $e(n){return F(n)?n.encryption!==void 0:Object.values(n).some(e=>$e(e))}function ft(n){if(typeof n!="object"||n===null||typeof n.projectId!="string"||!/^[0-9a-f-]{36}$/.test(n.projectId)||typeof n.signer!="string"||!/^[A-Za-z0-9_-]{43}$/.test(n.signer))throw new p("validation",{code:"invalid_namespace_tree",message:"The backend's encryption is { projectId, signer }: the project's id and its Ed25519 signing key, base64url"})}function Me(n){if(typeof n!="object"||n===null)throw new p("validation",{code:"invalid_namespace_tree",message:"Namespace tree nodes must be plain objects."});let e=Object.getPrototypeOf(n);if(e!==Object.prototype&&e!==null)throw new p("validation",{code:"invalid_namespace_tree",message:"Namespace tree nodes must be plain objects."});for(let[t,s]of Object.entries(n)){if(O(t))throw Oe(t);typeof s=="object"&&s!==null&&F(s)?(s.method=s.method.toUpperCase(),ut(s,s.path)):Me(s)}}function qe(n,e){if(F(n))return n.upload===!0?async(...s)=>yt(e,n,s):async(...s)=>Ge(e.machine(),n,s,e.transit);let t={};for(let[s,r]of Object.entries(n))t[s]=qe(r,e);return t}function J(n){if(n==null)return"";let e=Object.entries(n).filter(([,s])=>s!=null).sort(([s],[r])=>s<r?-1:s>r?1:0);return e.length===0?"":`?${e.map(([s,r])=>{if(typeof r!="string"&&typeof r!="number"&&typeof r!="boolean")throw new p("validation",{code:"invalid_query_value",message:`Query parameter '${s}' must be a string, number, or boolean.`});return`${encodeURIComponent(s)}=${encodeURIComponent(String(r))}`}).join("&")}`}function je(n,e,t){try{return T(n.path,e,t)}catch(s){if(!P(s)||s.code!=="invalid_path_parameter")throw s;let r=String(t);throw new p("validation",{code:"invalid_path_parameter",message:`${n.path}: ${e} cannot be ${r===""?"empty":JSON.stringify(r)}`})}}function Ae(n,e){let t=n.pathParams??[],s=n.path;for(let r=0;r<t.length;r++){let o=e[r];if(typeof o!="string"&&typeof o!="number")throw new p("validation",{code:"missing_path_param",message:`${n.path}: path parameter '${t[r]}' must be a string or number`});s=s.replace(`{${t[r]}}`,je(n,`path parameter '${t[r]}'`,o))}return s}var ht=new Set(["POST","PUT","PATCH","DELETE"]);async function Ge(n,e,t,s){let r=e.pathParams??[],o=Ae(e,t),d=o;if(e.input==="none"&&t.length>r.length+1)throw new p("validation",{code:"unexpected_argument",message:`${e.path}: endpoint takes no input \u2014 pass only path params and options`});let a=e.input==="none"?void 0:t[r.length],l=e.input==="none"?r.length:r.length+1,f=t[l],c;if(e.input==="query")d+=J(a);else if(e.input!=="none")if(e.method==="GET"){if(a!==void 0)throw new p("validation",{code:"unsupported_get_input",message:`${e.path}: GET endpoints take no body input`})}else c=a;let h={...f?.headers};if(ht.has(e.method)&&!Object.keys(h).some(y=>y.toLowerCase()==="idempotency-key")&&(h["Idempotency-Key"]=A()),e.encryption!==void 0){if(!s)throw new p("validation",{code:"encryption_unconfigured",message:`${e.method} ${e.path}: the route carries encrypted fields, and this backend's module holds no key to seal them with`});return gt(n,e,o,a,c,h,f?.signal,r.map((y,i)=>String(t[i])),s)}try{return e.sse===!0?await Be(n,e,d,c,h,f?.signal):await Ke(n,e,d,c,h,f?.signal)}catch(y){throw H(e,y)}}async function gt(n,e,t,s,r,o,d,a,l){let f=e.encryption;for(let c=0;;c++){let h=await _e(l.project,l.config,e.method,e.path,a,c>0);try{let y=e.input==="query"?t+J(await L(h,s,"/query",f.request)):t,i=await L(h,r,"/body",f.request),u={...o,[Q]:h.header};return e.sse===!0?await Be(n,e,y,i,u,d):E(await Se(h,await Ke(n,e,y,i,u,d),f.response,`${e.method} ${e.path}`))}catch(y){if(c===0&&Ce(y))continue;throw H(e,y)}}}function H(n,e){return n.errors&&ie(e)&&Object.hasOwn(n.errors,e.code)?n.errors[e.code](e):e}var mt=[["ApiKeyAuth","userJWT"],["ApiKeyAuth"]];async function yt(n,e,t){let s=e.pathParams??[],r=Ae(e,t),o=e.input==="none"?s.length:s.length+1;if(t.length>o+2)throw new p("validation",{code:"unexpected_argument",message:`${e.path}: an upload takes its path params, ${e.input==="none"?"":"its input, "}the file and options`});let d=e.input==="none"?void 0:t[s.length],a=t[o],l=t[o+1];if(!(a instanceof Blob))throw new p("validation",{code:"invalid_file",message:`${e.path}: the file is a Blob (a File is one)`});let f=`/storage/upload/${n.name}/${je(e,"the route",r.slice(1))}`;e.input==="query"&&(f+=J(d));let c=vt(e.input==="query"?void 0:d,a),h=c.body.size,y=0,i=u=>{y=u;try{l?.onProgress?.({loaded:u,total:h})}catch{}};l?.onProgress&&i(0);try{let u;try{let m={op:`Upload ${e.path}`,method:"POST",path:f,auth:mt,answers:Ne,body:{kind:"raw",contentType:c.type,value:c.body},signal:l?.signal,...l?.onProgress?{onUploadProgress:k=>i(k)}:{}};u=(await n.storage.send(m)).data}catch(m){throw P(m)?D(m):m}return l?.onProgress&&y<h&&i(h),await Le(e,u,l?.signal)}catch(u){throw H(e,u)}}function vt(n,e){let t=`Palbase-${A()}`,s=a=>a.replaceAll('"',"_").replace(/[\r\n]/g,""),r=typeof e.name=="string"?e.name:"blob",o=(a,l)=>`--${t}\r
7
- Content-Disposition: form-data; ${a}\r
8
- Content-Type: ${l}\r
9
- \r
10
- `,d=[];return n!==void 0&&d.push(o('name="body"',"application/json"),JSON.stringify(n),`\r
11
- `),d.push(o(`name="file"; filename="${s(r)}"`,s(e.type)||"application/octet-stream"),e,`\r
12
- --${t}--\r
13
- `),{body:new Blob(d),type:`multipart/form-data; boundary=${t}`}}async function wt(n,e,t,s){if(typeof e!="string"||e===""||e==="/")throw new p("validation",{code:"invalid_endpoint_name",message:'Endpoint name must be a non-empty path like "todos/create"'});let r=e.startsWith("/")?e:`/${e}`;return Ge(n(),{method:"POST",path:r},[t,s])}var Ne=Object.fromEntries(Array.from({length:100},(n,e)=>[200+e,"raw"])),bt=[["userJWT"],[]];async function De(n,e,t,s,r,o){let d={op:`${e.method} ${e.path}`,method:e.method,path:t,auth:bt,answers:Ne,headers:r,...s===void 0?{}:{body:{kind:"json",contentType:"application/json",value:s}},idempotent:e.idempotent===!0,signal:o};try{return(await n.send(d)).data}catch(a){throw P(a)?D(a):a}}async function Ke(n,e,t,s,r,o){return Le(e,await De(n,e,t,s,r,o),o)}async function Le(n,e,t){let s=e.headers.get("x-request-id")??void 0,r;try{r=await e.text()}catch(o){throw t?.aborted?o:new p("network",{code:"network_error",message:`${n.method} ${n.path}: the answer did not arrive whole`,status:e.status,requestId:s,cause:o})}if(r!=="")try{return E(JSON.parse(r))}catch(o){throw new p("decode",{code:"invalid_json",message:`${n.method} ${n.path}: the answer is not JSON`,status:e.status,requestId:s,cause:o})}}async function Be(n,e,t,s,r,o){let d=new AbortController;o&&(o.aborted?d.abort():o.addEventListener("abort",()=>d.abort(),{once:!0}));let a=await De(n,e,t,s,{accept:"text/event-stream",...r},d.signal);if(!a.body)throw new p("network",{code:"empty_stream",message:"the server answered a streaming route with no body",status:a.status});return Te(a.body,d)}export{p as a,ie as b,Ue as c,de as d,be as e,M as f,dt as g,zt as h,Qt as i};