swerasty_editor 0.1.0 → 0.1.2

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.
@@ -0,0 +1,377 @@
1
+ (function(ee,g){typeof exports=="object"&&typeof module<"u"?g(exports,require("react/jsx-runtime"),require("react")):typeof define=="function"&&define.amd?define(["exports","react/jsx-runtime","react"],g):(ee=typeof globalThis<"u"?globalThis:ee||self,g(ee.MyReactLibrary={},ee.jsxRuntime,ee.React))})(this,function(ee,g,w){"use strict";const Wo=({isOpen:t,onClose:e,onInsert:n})=>{const[o,s]=w.useState(3),[l,a]=w.useState(3);if(!t)return null;const u=()=>{o>0&&l>0&&n(o,l)};return g.jsx("div",{className:"fixed inset-0 z-[60] flex items-center justify-center bg-black bg-opacity-50 backdrop-blur-sm",onClick:e,children:g.jsxs("div",{className:"bg-white rounded-lg shadow-xl p-6 w-full max-w-sm",onClick:c=>c.stopPropagation(),children:[g.jsx("h3",{className:"text-lg font-semibold text-gray-800 mb-4",children:"Insert Table"}),g.jsxs("div",{className:"space-y-4",children:[g.jsxs("div",{children:[g.jsx("label",{htmlFor:"rows",className:"block text-sm font-medium text-gray-700 mb-1",children:"Rows"}),g.jsx("input",{type:"number",id:"rows",value:o,onChange:c=>s(Math.max(1,parseInt(c.target.value,10))),className:"w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:ring-blue-500 focus:border-blue-500 text-black"})]}),g.jsxs("div",{children:[g.jsx("label",{htmlFor:"cols",className:"block text-sm font-medium text-gray-700 mb-1",children:"Columns"}),g.jsx("input",{type:"number",id:"cols",value:l,onChange:c=>a(Math.max(1,parseInt(c.target.value,10))),className:"w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:ring-blue-500 focus:border-blue-500 text-black"})]})]}),g.jsxs("div",{className:"mt-6 flex justify-end space-x-3",children:[g.jsx("button",{onClick:e,className:"px-4 py-2 bg-gray-200 text-gray-800 rounded-md hover:bg-gray-300 transition",children:"Cancel"}),g.jsx("button",{onClick:u,className:"px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 transition",children:"Insert"})]})]})})};/**
2
+ * @license lucide-react v0.562.0 - ISC
3
+ *
4
+ * This source code is licensed under the ISC license.
5
+ * See the LICENSE file in the root directory of this source tree.
6
+ */const Yo=t=>t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),Ko=t=>t.replace(/^([A-Z])|[\s-_]+(\w)/g,(e,n,o)=>o?o.toUpperCase():n.toLowerCase()),ut=t=>{const e=Ko(t);return e.charAt(0).toUpperCase()+e.slice(1)},dt=(...t)=>t.filter((e,n,o)=>!!e&&e.trim()!==""&&o.indexOf(e)===n).join(" ").trim(),zo=t=>{for(const e in t)if(e.startsWith("aria-")||e==="role"||e==="title")return!0};/**
7
+ * @license lucide-react v0.562.0 - ISC
8
+ *
9
+ * This source code is licensed under the ISC license.
10
+ * See the LICENSE file in the root directory of this source tree.
11
+ */var Oo={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};/**
12
+ * @license lucide-react v0.562.0 - ISC
13
+ *
14
+ * This source code is licensed under the ISC license.
15
+ * See the LICENSE file in the root directory of this source tree.
16
+ */const Xo=w.forwardRef(({color:t="currentColor",size:e=24,strokeWidth:n=2,absoluteStrokeWidth:o,className:s="",children:l,iconNode:a,...u},c)=>w.createElement("svg",{ref:c,...Oo,width:e,height:e,stroke:t,strokeWidth:o?Number(n)*24/Number(e):n,className:dt("lucide",s),...!l&&!zo(u)&&{"aria-hidden":"true"},...u},[...a.map(([d,f])=>w.createElement(d,f)),...Array.isArray(l)?l:[l]]));/**
17
+ * @license lucide-react v0.562.0 - ISC
18
+ *
19
+ * This source code is licensed under the ISC license.
20
+ * See the LICENSE file in the root directory of this source tree.
21
+ */const F=(t,e)=>{const n=w.forwardRef(({className:o,...s},l)=>w.createElement(Xo,{ref:l,iconNode:e,className:dt(`lucide-${Yo(ut(t))}`,`lucide-${t}`,o),...s}));return n.displayName=ut(t),n};/**
22
+ * @license lucide-react v0.562.0 - ISC
23
+ *
24
+ * This source code is licensed under the ISC license.
25
+ * See the LICENSE file in the root directory of this source tree.
26
+ */const Qo=F("bold",[["path",{d:"M6 12h9a4 4 0 0 1 0 8H7a1 1 0 0 1-1-1V5a1 1 0 0 1 1-1h7a4 4 0 0 1 0 8",key:"mg9rjx"}]]);/**
27
+ * @license lucide-react v0.562.0 - ISC
28
+ *
29
+ * This source code is licensed under the ISC license.
30
+ * See the LICENSE file in the root directory of this source tree.
31
+ */const Zo=F("highlighter",[["path",{d:"m9 11-6 6v3h9l3-3",key:"1a3l36"}],["path",{d:"m22 12-4.6 4.6a2 2 0 0 1-2.8 0l-5.2-5.2a2 2 0 0 1 0-2.8L14 4",key:"14a9rk"}]]);/**
32
+ * @license lucide-react v0.562.0 - ISC
33
+ *
34
+ * This source code is licensed under the ISC license.
35
+ * See the LICENSE file in the root directory of this source tree.
36
+ */const jo=F("image",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["circle",{cx:"9",cy:"9",r:"2",key:"af1f0g"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21",key:"1xmnt7"}]]);/**
37
+ * @license lucide-react v0.562.0 - ISC
38
+ *
39
+ * This source code is licensed under the ISC license.
40
+ * See the LICENSE file in the root directory of this source tree.
41
+ */const ei=F("italic",[["line",{x1:"19",x2:"10",y1:"4",y2:"4",key:"15jd3p"}],["line",{x1:"14",x2:"5",y1:"20",y2:"20",key:"bu0au3"}],["line",{x1:"15",x2:"9",y1:"4",y2:"20",key:"uljnxc"}]]);/**
42
+ * @license lucide-react v0.562.0 - ISC
43
+ *
44
+ * This source code is licensed under the ISC license.
45
+ * See the LICENSE file in the root directory of this source tree.
46
+ */const ti=F("keyboard",[["path",{d:"M10 8h.01",key:"1r9ogq"}],["path",{d:"M12 12h.01",key:"1mp3jc"}],["path",{d:"M14 8h.01",key:"1primd"}],["path",{d:"M16 12h.01",key:"1l6xoz"}],["path",{d:"M18 8h.01",key:"emo2bl"}],["path",{d:"M6 8h.01",key:"x9i8wu"}],["path",{d:"M7 16h10",key:"wp8him"}],["path",{d:"M8 12h.01",key:"czm47f"}],["rect",{width:"20",height:"16",x:"2",y:"4",rx:"2",key:"18n3k1"}]]);/**
47
+ * @license lucide-react v0.562.0 - ISC
48
+ *
49
+ * This source code is licensed under the ISC license.
50
+ * See the LICENSE file in the root directory of this source tree.
51
+ */const ni=F("list-ordered",[["path",{d:"M11 5h10",key:"1cz7ny"}],["path",{d:"M11 12h10",key:"1438ji"}],["path",{d:"M11 19h10",key:"11t30w"}],["path",{d:"M4 4h1v5",key:"10yrso"}],["path",{d:"M4 9h2",key:"r1h2o0"}],["path",{d:"M6.5 20H3.4c0-1 2.6-1.925 2.6-3.5a1.5 1.5 0 0 0-2.6-1.02",key:"xtkcd5"}]]);/**
52
+ * @license lucide-react v0.562.0 - ISC
53
+ *
54
+ * This source code is licensed under the ISC license.
55
+ * See the LICENSE file in the root directory of this source tree.
56
+ */const oi=F("list",[["path",{d:"M3 5h.01",key:"18ugdj"}],["path",{d:"M3 12h.01",key:"nlz23k"}],["path",{d:"M3 19h.01",key:"noohij"}],["path",{d:"M8 5h13",key:"1pao27"}],["path",{d:"M8 12h13",key:"1za7za"}],["path",{d:"M8 19h13",key:"m83p4d"}]]);/**
57
+ * @license lucide-react v0.562.0 - ISC
58
+ *
59
+ * This source code is licensed under the ISC license.
60
+ * See the LICENSE file in the root directory of this source tree.
61
+ */const ii=F("loader-circle",[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]]);/**
62
+ * @license lucide-react v0.562.0 - ISC
63
+ *
64
+ * This source code is licensed under the ISC license.
65
+ * See the LICENSE file in the root directory of this source tree.
66
+ */const si=F("palette",[["path",{d:"M12 22a1 1 0 0 1 0-20 10 9 0 0 1 10 9 5 5 0 0 1-5 5h-2.25a1.75 1.75 0 0 0-1.4 2.8l.3.4a1.75 1.75 0 0 1-1.4 2.8z",key:"e79jfc"}],["circle",{cx:"13.5",cy:"6.5",r:".5",fill:"currentColor",key:"1okk4w"}],["circle",{cx:"17.5",cy:"10.5",r:".5",fill:"currentColor",key:"f64h9f"}],["circle",{cx:"6.5",cy:"12.5",r:".5",fill:"currentColor",key:"qy21gx"}],["circle",{cx:"8.5",cy:"7.5",r:".5",fill:"currentColor",key:"fotxhn"}]]);/**
67
+ * @license lucide-react v0.562.0 - ISC
68
+ *
69
+ * This source code is licensed under the ISC license.
70
+ * See the LICENSE file in the root directory of this source tree.
71
+ */const ri=F("pencil",[["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z",key:"1a8usu"}],["path",{d:"m15 5 4 4",key:"1mk7zo"}]]);/**
72
+ * @license lucide-react v0.562.0 - ISC
73
+ *
74
+ * This source code is licensed under the ISC license.
75
+ * See the LICENSE file in the root directory of this source tree.
76
+ */const li=F("redo-2",[["path",{d:"m15 14 5-5-5-5",key:"12vg1m"}],["path",{d:"M20 9H9.5A5.5 5.5 0 0 0 4 14.5A5.5 5.5 0 0 0 9.5 20H13",key:"6uklza"}]]);/**
77
+ * @license lucide-react v0.562.0 - ISC
78
+ *
79
+ * This source code is licensed under the ISC license.
80
+ * See the LICENSE file in the root directory of this source tree.
81
+ */const ai=F("rotate-ccw",[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}]]);/**
82
+ * @license lucide-react v0.562.0 - ISC
83
+ *
84
+ * This source code is licensed under the ISC license.
85
+ * See the LICENSE file in the root directory of this source tree.
86
+ */const ui=F("rotate-cw",[["path",{d:"M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8",key:"1p45f6"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}]]);/**
87
+ * @license lucide-react v0.562.0 - ISC
88
+ *
89
+ * This source code is licensed under the ISC license.
90
+ * See the LICENSE file in the root directory of this source tree.
91
+ */const di=F("sigma",[["path",{d:"M18 7V5a1 1 0 0 0-1-1H6.5a.5.5 0 0 0-.4.8l4.5 6a2 2 0 0 1 0 2.4l-4.5 6a.5.5 0 0 0 .4.8H17a1 1 0 0 0 1-1v-2",key:"wuwx1p"}]]);/**
92
+ * @license lucide-react v0.562.0 - ISC
93
+ *
94
+ * This source code is licensed under the ISC license.
95
+ * See the LICENSE file in the root directory of this source tree.
96
+ */const ci=F("strikethrough",[["path",{d:"M16 4H9a3 3 0 0 0-2.83 4",key:"43sutm"}],["path",{d:"M14 12a4 4 0 0 1 0 8H6",key:"nlfj13"}],["line",{x1:"4",x2:"20",y1:"12",y2:"12",key:"1e0a9i"}]]);/**
97
+ * @license lucide-react v0.562.0 - ISC
98
+ *
99
+ * This source code is licensed under the ISC license.
100
+ * See the LICENSE file in the root directory of this source tree.
101
+ */const fi=F("table",[["path",{d:"M12 3v18",key:"108xh3"}],["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M3 9h18",key:"1pudct"}],["path",{d:"M3 15h18",key:"5xshup"}]]);/**
102
+ * @license lucide-react v0.562.0 - ISC
103
+ *
104
+ * This source code is licensed under the ISC license.
105
+ * See the LICENSE file in the root directory of this source tree.
106
+ */const pi=F("trash-2",[["path",{d:"M10 11v6",key:"nco0om"}],["path",{d:"M14 11v6",key:"outv1u"}],["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6",key:"miytrc"}],["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2",key:"e791ji"}]]);/**
107
+ * @license lucide-react v0.562.0 - ISC
108
+ *
109
+ * This source code is licensed under the ISC license.
110
+ * See the LICENSE file in the root directory of this source tree.
111
+ */const hi=F("underline",[["path",{d:"M6 4v6a6 6 0 0 0 12 0V4",key:"9kb039"}],["line",{x1:"4",x2:"20",y1:"20",y2:"20",key:"nun2al"}]]);/**
112
+ * @license lucide-react v0.562.0 - ISC
113
+ *
114
+ * This source code is licensed under the ISC license.
115
+ * See the LICENSE file in the root directory of this source tree.
116
+ */const mi=F("undo-2",[["path",{d:"M9 14 4 9l5-5",key:"102s5s"}],["path",{d:"M4 9h10.5a5.5 5.5 0 0 1 5.5 5.5a5.5 5.5 0 0 1-5.5 5.5H11",key:"f3b9sd"}]]);/**
117
+ * @license lucide-react v0.562.0 - ISC
118
+ *
119
+ * This source code is licensed under the ISC license.
120
+ * See the LICENSE file in the root directory of this source tree.
121
+ */const gi=F("x",[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]]),ct={"12px":"1","14px":"2","16px":"3","18px":"4","24px":"5","32px":"6","48px":"7"},yi=({onOpenHandwritingModal:t,onApplyStyle:e,onUndo:n,onRedo:o,canUndo:s,canRedo:l})=>{const[a,u]=w.useState(!1),c=w.useRef(null),d=p=>{var y;const m=(y=p.target.files)==null?void 0:y[0];if(m){const _=new FileReader;_.onload=T=>{var C;const E=(C=T.target)==null?void 0:C.result;e("insertImage",E)},_.readAsDataURL(m)}p.target&&(p.target.value="")},f=(p,m)=>{let y='<table class="border-collapse w-full my-4 border border-slate-300">';for(let _=0;_<p;_++){y+="<tr>";for(let T=0;T<m;T++)y+='<td class="border border-slate-300 p-2 min-h-[40px]"><br></td>';y+="</tr>"}y+="</table><p><br></p>",e("insertHTML",y),u(!1)},h=({onClick:p,disabled:m,title:y,children:_,active:T})=>g.jsx("button",{onClick:p,disabled:m,onMouseDown:E=>E.preventDefault(),title:y,className:`p-2 rounded-md transition-colors flex items-center justify-center disabled:opacity-20 ${T?"bg-blue-100 text-blue-600":"hover:bg-slate-100 text-slate-600"}`,children:_});return g.jsxs(g.Fragment,{children:[g.jsxs("div",{className:"bg-white px-4 py-2 flex flex-wrap items-center gap-1 border-b border-slate-200 sticky top-0 z-20 shadow-sm",children:[g.jsxs("div",{className:"flex items-center gap-1 pr-2 border-r border-slate-200",children:[g.jsx(h,{onClick:n,disabled:!s,title:"Undo",children:g.jsx(mi,{size:18})}),g.jsx(h,{onClick:o,disabled:!l,title:"Redo",children:g.jsx(li,{size:18})})]}),g.jsxs("div",{className:"flex items-center gap-1 px-2 border-r border-slate-200",children:[g.jsxs("select",{onChange:p=>e("fontName",p.target.value),className:"bg-slate-50 border-none rounded-md px-2 py-1 text-xs font-medium text-slate-600 focus:ring-1 focus:ring-blue-500 outline-none",children:[g.jsx("option",{value:"Inter",children:"Inter"}),g.jsx("option",{value:"Arial",children:"Arial"}),g.jsx("option",{value:"Georgia",children:"Georgia"}),g.jsx("option",{value:"Courier New",children:"Monospace"})]}),g.jsx("select",{onChange:p=>e("fontSize",ct[p.target.value]),defaultValue:"16px",className:"bg-slate-50 border-none rounded-md px-2 py-1 text-xs font-medium text-slate-600 focus:ring-1 focus:ring-blue-500 outline-none w-20",children:Object.keys(ct).map(p=>g.jsx("option",{value:p,children:p},p))})]}),g.jsxs("div",{className:"flex items-center gap-0.5 px-2 border-r border-slate-200",children:[g.jsx(h,{onClick:()=>e("bold"),title:"Bold",children:g.jsx(Qo,{size:18})}),g.jsx(h,{onClick:()=>e("italic"),title:"Italic",children:g.jsx(ei,{size:18})}),g.jsx(h,{onClick:()=>e("underline"),title:"Underline",children:g.jsx(hi,{size:18})}),g.jsx(h,{onClick:()=>e("strikeThrough"),title:"Strikethrough",children:g.jsx(ci,{size:18})})]}),g.jsxs("div",{className:"flex items-center gap-1 px-2 border-r border-slate-200",children:[g.jsxs("label",{className:"p-2 hover:bg-slate-100 rounded-md cursor-pointer relative group",title:"Text Color",children:[g.jsx(si,{size:18,className:"text-slate-600"}),g.jsx("input",{type:"color",onChange:p=>e("foreColor",p.target.value),className:"opacity-0 absolute inset-0 cursor-pointer w-full h-full"})]}),g.jsxs("label",{className:"p-2 hover:bg-slate-100 rounded-md cursor-pointer relative group",title:"Highlight Color",children:[g.jsx(Zo,{size:18,className:"text-slate-600"}),g.jsx("input",{type:"color",defaultValue:"#FFFF00",onChange:p=>e("backColor",p.target.value),className:"opacity-0 absolute inset-0 cursor-pointer w-full h-full"})]})]}),g.jsxs("div",{className:"flex items-center gap-0.5 px-2 border-r border-slate-200",children:[g.jsx(h,{onClick:()=>e("insertOrderedList"),title:"Numbered List",children:g.jsx(ni,{size:18})}),g.jsx(h,{onClick:()=>e("insertUnorderedList"),title:"Bullet List",children:g.jsx(oi,{size:18})})]}),g.jsxs("div",{className:"flex items-center gap-0.5 px-2",children:[g.jsx(h,{onClick:()=>{var p;return(p=c.current)==null?void 0:p.click()},title:"Insert Image",children:g.jsx(jo,{size:18})}),g.jsx("input",{type:"file",ref:c,onChange:d,accept:"image/*",className:"hidden"}),g.jsx(h,{onClick:()=>u(!0),title:"Insert Table",children:g.jsx(fi,{size:18})})]}),g.jsx("div",{className:"ml-auto flex items-center",children:g.jsxs("button",{onClick:t,className:"flex items-center gap-2 px-3 py-1.5 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-all shadow-sm font-semibold text-sm",children:[g.jsx(di,{size:16}),g.jsx("span",{className:"hidden sm:inline",children:"AI Math Pad"})]})})]}),g.jsx(Wo,{isOpen:a,onClose:()=>u(!1),onInsert:f})]})},ft=w.forwardRef(({onHistoryChange:t},e)=>{const n=w.useRef(null),o=w.useRef(null),[s,l]=w.useState(!1),[a,u]=w.useState(!1),c=w.useRef(null),[d,f]=w.useState([]),[h,p]=w.useState(-1),m=w.useCallback(()=>{const C=n.current,v=c.current;if(!C||!v)return;const I=v.getImageData(0,0,C.width,C.height),A=d.slice(0,h+1);f([...A,I]),p(A.length)},[d,h]);w.useEffect(()=>{t==null||t({canUndo:h>0,canRedo:h<d.length-1})},[d,h,t]),w.useEffect(()=>{const C=n.current,v=o.current;if(!C||!v)return;c.current=C.getContext("2d");const I=new ResizeObserver(A=>{var R;const{width:P,height:N}=A[0].contentRect,U=(R=c.current)==null?void 0:R.getImageData(0,0,C.width,C.height);C.width=P,C.height=N;const x=c.current;if(x&&(x.lineCap="round",x.strokeStyle="#000",x.lineWidth=2,U&&x.putImageData(U,0,0)),d.length===0){const b=x==null?void 0:x.getImageData(0,0,P,N);b&&(f([b]),p(0))}});return I.observe(v),()=>{I.disconnect()}},[]);const y=C=>{const v=n.current;if(!v)return{offsetX:0,offsetY:0};const I=v.getBoundingClientRect(),A="touches"in C?C.touches[0].clientX:C.clientX,P="touches"in C?C.touches[0].clientY:C.clientY;return{offsetX:A-I.left,offsetY:P-I.top}},_=C=>{C.preventDefault();const v=c.current;if(!v)return;const{offsetX:I,offsetY:A}=y(C);v.beginPath(),v.moveTo(I,A),l(!0),u(!0)},T=()=>{const C=c.current;!C||!s||(C.closePath(),l(!1),m())},E=C=>{if(!s||!c.current)return;C.preventDefault();const{offsetX:v,offsetY:I}=y(C);c.current.lineTo(v,I),c.current.stroke()};return w.useImperativeHandle(e,()=>({clear(){const C=c.current,v=n.current;if(C&&v){C.clearRect(0,0,v.width,v.height),u(!1);const I=C.getImageData(0,0,v.width,v.height);f([I]),p(0)}},undo(){var C;if(h>0){const v=h-1;p(v);const I=d[v];(C=c.current)==null||C.putImageData(I,0,0),u(v>0)}},redo(){var C;if(h<d.length-1){const v=h+1;p(v);const I=d[v];(C=c.current)==null||C.putImageData(I,0,0),u(!0)}},getTrimmedImageData(){const C=n.current,v=c.current;if(!a||!C||!v)return null;const I=C.width,A=C.height,N=v.getImageData(0,0,I,A).data;let U=I,x=A,R=0,b=0;for(let X=0;X<A;X++)for(let ge=0;ge<I;ge++)N[(I*X+ge)*4+3]>0&&(U=Math.min(U,ge),x=Math.min(x,X),R=Math.max(R,ge),b=Math.max(b,X));if(U===I)return null;const k=15;U=Math.max(0,U-k),x=Math.max(0,x-k),R=Math.min(I,R+k),b=Math.min(A,b+k);const D=R-U,G=b-x,$=document.createElement("canvas");$.width=D,$.height=G;const H=$.getContext("2d");return H?(H.drawImage(C,U,x,D,G,0,0,D,G),$.toDataURL("image/png")):null}})),g.jsx("div",{ref:o,className:"absolute inset-0 w-full h-full",children:g.jsx("canvas",{ref:n,onMouseDown:_,onMouseUp:T,onMouseMove:E,onMouseLeave:T,onTouchStart:_,onTouchEnd:T,onTouchMove:E,className:"w-full h-full",style:{cursor:"crosshair",touchAction:"none"}})})});ft.displayName="Canvas";/**
122
+ * @license
123
+ * Copyright 2025 Google LLC
124
+ * SPDX-License-Identifier: Apache-2.0
125
+ */let Ti,_i;function Ei(){return{geminiUrl:Ti,vertexUrl:_i}}function Ci(t,e,n,o){var s,l;if(!(t!=null&&t.baseUrl)){const a=Ei();return e?(s=a.vertexUrl)!==null&&s!==void 0?s:n:(l=a.geminiUrl)!==null&&l!==void 0?l:o}return t.baseUrl}/**
126
+ * @license
127
+ * Copyright 2025 Google LLC
128
+ * SPDX-License-Identifier: Apache-2.0
129
+ */class Q{}function S(t,e){const n=/\{([^}]+)\}/g;return t.replace(n,(o,s)=>{if(Object.prototype.hasOwnProperty.call(e,s)){const l=e[s];return l!=null?String(l):""}else throw new Error(`Key '${s}' not found in valueMap.`)})}function r(t,e,n){for(let l=0;l<e.length-1;l++){const a=e[l];if(a.endsWith("[]")){const u=a.slice(0,-2);if(!(u in t))if(Array.isArray(n))t[u]=Array.from({length:n.length},()=>({}));else throw new Error(`Value must be a list given an array path ${a}`);if(Array.isArray(t[u])){const c=t[u];if(Array.isArray(n))for(let d=0;d<c.length;d++){const f=c[d];r(f,e.slice(l+1),n[d])}else for(const d of c)r(d,e.slice(l+1),n)}return}else if(a.endsWith("[0]")){const u=a.slice(0,-3);u in t||(t[u]=[{}]);const c=t[u];r(c[0],e.slice(l+1),n);return}(!t[a]||typeof t[a]!="object")&&(t[a]={}),t=t[a]}const o=e[e.length-1],s=t[o];if(s!==void 0){if(!n||typeof n=="object"&&Object.keys(n).length===0||n===s)return;if(typeof s=="object"&&typeof n=="object"&&s!==null&&n!==null)Object.assign(s,n);else throw new Error(`Cannot set value for an existing key. Key: ${o}`)}else o==="_self"&&typeof n=="object"&&n!==null&&!Array.isArray(n)?Object.assign(t,n):t[o]=n}function i(t,e,n=void 0){try{if(e.length===1&&e[0]==="_self")return t;for(let o=0;o<e.length;o++){if(typeof t!="object"||t===null)return n;const s=e[o];if(s.endsWith("[]")){const l=s.slice(0,-2);if(l in t){const a=t[l];return Array.isArray(a)?a.map(u=>i(u,e.slice(o+1),n)):n}else return n}else t=t[s]}return t}catch(o){if(o instanceof TypeError)return n;throw o}}function vi(t,e){for(const[n,o]of Object.entries(e)){const s=n.split("."),l=o.split("."),a=new Set;let u=-1;for(let c=0;c<s.length;c++)if(s[c]==="*"){u=c;break}if(u!==-1&&l.length>u)for(let c=u;c<l.length;c++){const d=l[c];d!=="*"&&!d.endsWith("[]")&&!d.endsWith("[0]")&&a.add(d)}Fe(t,s,l,0,a)}}function Fe(t,e,n,o,s){if(o>=e.length||typeof t!="object"||t===null)return;const l=e[o];if(l.endsWith("[]")){const a=l.slice(0,-2),u=t;if(a in u&&Array.isArray(u[a]))for(const c of u[a])Fe(c,e,n,o+1,s)}else if(l==="*"){if(typeof t=="object"&&t!==null&&!Array.isArray(t)){const a=t,u=Object.keys(a).filter(d=>!d.startsWith("_")&&!s.has(d)),c={};for(const d of u)c[d]=a[d];for(const[d,f]of Object.entries(c)){const h=[];for(const p of n.slice(o))p==="*"?h.push(d):h.push(p);r(a,h,f)}for(const d of u)delete a[d]}}else{const a=t;l in a&&Fe(a[l],e,n,o+1,s)}}/**
130
+ * @license
131
+ * Copyright 2025 Google LLC
132
+ * SPDX-License-Identifier: Apache-2.0
133
+ */function Ge(t){if(typeof t!="string")throw new Error("fromImageBytes must be a string");return t}/**
134
+ * @license
135
+ * Copyright 2025 Google LLC
136
+ * SPDX-License-Identifier: Apache-2.0
137
+ */function Ii(t){const e={},n=i(t,["operationName"]);n!=null&&r(e,["operationName"],n);const o=i(t,["resourceName"]);return o!=null&&r(e,["_url","resourceName"],o),e}function Si(t){const e={},n=i(t,["name"]);n!=null&&r(e,["name"],n);const o=i(t,["metadata"]);o!=null&&r(e,["metadata"],o);const s=i(t,["done"]);s!=null&&r(e,["done"],s);const l=i(t,["error"]);l!=null&&r(e,["error"],l);const a=i(t,["response","generateVideoResponse"]);return a!=null&&r(e,["response"],Ai(a)),e}function xi(t){const e={},n=i(t,["name"]);n!=null&&r(e,["name"],n);const o=i(t,["metadata"]);o!=null&&r(e,["metadata"],o);const s=i(t,["done"]);s!=null&&r(e,["done"],s);const l=i(t,["error"]);l!=null&&r(e,["error"],l);const a=i(t,["response"]);return a!=null&&r(e,["response"],wi(a)),e}function Ai(t){const e={},n=i(t,["generatedSamples"]);if(n!=null){let l=n;Array.isArray(l)&&(l=l.map(a=>Ni(a))),r(e,["generatedVideos"],l)}const o=i(t,["raiMediaFilteredCount"]);o!=null&&r(e,["raiMediaFilteredCount"],o);const s=i(t,["raiMediaFilteredReasons"]);return s!=null&&r(e,["raiMediaFilteredReasons"],s),e}function wi(t){const e={},n=i(t,["videos"]);if(n!=null){let l=n;Array.isArray(l)&&(l=l.map(a=>Mi(a))),r(e,["generatedVideos"],l)}const o=i(t,["raiMediaFilteredCount"]);o!=null&&r(e,["raiMediaFilteredCount"],o);const s=i(t,["raiMediaFilteredReasons"]);return s!=null&&r(e,["raiMediaFilteredReasons"],s),e}function Ni(t){const e={},n=i(t,["video"]);return n!=null&&r(e,["video"],Li(n)),e}function Mi(t){const e={},n=i(t,["_self"]);return n!=null&&r(e,["video"],bi(n)),e}function Pi(t){const e={},n=i(t,["operationName"]);return n!=null&&r(e,["_url","operationName"],n),e}function Ri(t){const e={},n=i(t,["operationName"]);return n!=null&&r(e,["_url","operationName"],n),e}function ki(t){const e={},n=i(t,["name"]);n!=null&&r(e,["name"],n);const o=i(t,["metadata"]);o!=null&&r(e,["metadata"],o);const s=i(t,["done"]);s!=null&&r(e,["done"],s);const l=i(t,["error"]);l!=null&&r(e,["error"],l);const a=i(t,["response"]);return a!=null&&r(e,["response"],Di(a)),e}function Di(t){const e={},n=i(t,["sdkHttpResponse"]);n!=null&&r(e,["sdkHttpResponse"],n);const o=i(t,["parent"]);o!=null&&r(e,["parent"],o);const s=i(t,["documentName"]);return s!=null&&r(e,["documentName"],s),e}function pt(t){const e={},n=i(t,["name"]);n!=null&&r(e,["name"],n);const o=i(t,["metadata"]);o!=null&&r(e,["metadata"],o);const s=i(t,["done"]);s!=null&&r(e,["done"],s);const l=i(t,["error"]);l!=null&&r(e,["error"],l);const a=i(t,["response"]);return a!=null&&r(e,["response"],Ui(a)),e}function Ui(t){const e={},n=i(t,["sdkHttpResponse"]);n!=null&&r(e,["sdkHttpResponse"],n);const o=i(t,["parent"]);o!=null&&r(e,["parent"],o);const s=i(t,["documentName"]);return s!=null&&r(e,["documentName"],s),e}function Li(t){const e={},n=i(t,["uri"]);n!=null&&r(e,["uri"],n);const o=i(t,["encodedVideo"]);o!=null&&r(e,["videoBytes"],Ge(o));const s=i(t,["encoding"]);return s!=null&&r(e,["mimeType"],s),e}function bi(t){const e={},n=i(t,["gcsUri"]);n!=null&&r(e,["uri"],n);const o=i(t,["bytesBase64Encoded"]);o!=null&&r(e,["videoBytes"],Ge(o));const s=i(t,["mimeType"]);return s!=null&&r(e,["mimeType"],s),e}/**
138
+ * @license
139
+ * Copyright 2025 Google LLC
140
+ * SPDX-License-Identifier: Apache-2.0
141
+ */var ht;(function(t){t.OUTCOME_UNSPECIFIED="OUTCOME_UNSPECIFIED",t.OUTCOME_OK="OUTCOME_OK",t.OUTCOME_FAILED="OUTCOME_FAILED",t.OUTCOME_DEADLINE_EXCEEDED="OUTCOME_DEADLINE_EXCEEDED"})(ht||(ht={}));var mt;(function(t){t.LANGUAGE_UNSPECIFIED="LANGUAGE_UNSPECIFIED",t.PYTHON="PYTHON"})(mt||(mt={}));var gt;(function(t){t.SCHEDULING_UNSPECIFIED="SCHEDULING_UNSPECIFIED",t.SILENT="SILENT",t.WHEN_IDLE="WHEN_IDLE",t.INTERRUPT="INTERRUPT"})(gt||(gt={}));var te;(function(t){t.TYPE_UNSPECIFIED="TYPE_UNSPECIFIED",t.STRING="STRING",t.NUMBER="NUMBER",t.INTEGER="INTEGER",t.BOOLEAN="BOOLEAN",t.ARRAY="ARRAY",t.OBJECT="OBJECT",t.NULL="NULL"})(te||(te={}));var yt;(function(t){t.MODE_UNSPECIFIED="MODE_UNSPECIFIED",t.MODE_DYNAMIC="MODE_DYNAMIC"})(yt||(yt={}));var Tt;(function(t){t.API_SPEC_UNSPECIFIED="API_SPEC_UNSPECIFIED",t.SIMPLE_SEARCH="SIMPLE_SEARCH",t.ELASTIC_SEARCH="ELASTIC_SEARCH"})(Tt||(Tt={}));var _t;(function(t){t.AUTH_TYPE_UNSPECIFIED="AUTH_TYPE_UNSPECIFIED",t.NO_AUTH="NO_AUTH",t.API_KEY_AUTH="API_KEY_AUTH",t.HTTP_BASIC_AUTH="HTTP_BASIC_AUTH",t.GOOGLE_SERVICE_ACCOUNT_AUTH="GOOGLE_SERVICE_ACCOUNT_AUTH",t.OAUTH="OAUTH",t.OIDC_AUTH="OIDC_AUTH"})(_t||(_t={}));var Et;(function(t){t.HTTP_IN_UNSPECIFIED="HTTP_IN_UNSPECIFIED",t.HTTP_IN_QUERY="HTTP_IN_QUERY",t.HTTP_IN_HEADER="HTTP_IN_HEADER",t.HTTP_IN_PATH="HTTP_IN_PATH",t.HTTP_IN_BODY="HTTP_IN_BODY",t.HTTP_IN_COOKIE="HTTP_IN_COOKIE"})(Et||(Et={}));var Ct;(function(t){t.PHISH_BLOCK_THRESHOLD_UNSPECIFIED="PHISH_BLOCK_THRESHOLD_UNSPECIFIED",t.BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",t.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",t.BLOCK_HIGH_AND_ABOVE="BLOCK_HIGH_AND_ABOVE",t.BLOCK_HIGHER_AND_ABOVE="BLOCK_HIGHER_AND_ABOVE",t.BLOCK_VERY_HIGH_AND_ABOVE="BLOCK_VERY_HIGH_AND_ABOVE",t.BLOCK_ONLY_EXTREMELY_HIGH="BLOCK_ONLY_EXTREMELY_HIGH"})(Ct||(Ct={}));var vt;(function(t){t.THINKING_LEVEL_UNSPECIFIED="THINKING_LEVEL_UNSPECIFIED",t.LOW="LOW",t.MEDIUM="MEDIUM",t.HIGH="HIGH",t.MINIMAL="MINIMAL"})(vt||(vt={}));var It;(function(t){t.HARM_CATEGORY_UNSPECIFIED="HARM_CATEGORY_UNSPECIFIED",t.HARM_CATEGORY_HARASSMENT="HARM_CATEGORY_HARASSMENT",t.HARM_CATEGORY_HATE_SPEECH="HARM_CATEGORY_HATE_SPEECH",t.HARM_CATEGORY_SEXUALLY_EXPLICIT="HARM_CATEGORY_SEXUALLY_EXPLICIT",t.HARM_CATEGORY_DANGEROUS_CONTENT="HARM_CATEGORY_DANGEROUS_CONTENT",t.HARM_CATEGORY_CIVIC_INTEGRITY="HARM_CATEGORY_CIVIC_INTEGRITY",t.HARM_CATEGORY_IMAGE_HATE="HARM_CATEGORY_IMAGE_HATE",t.HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT="HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT",t.HARM_CATEGORY_IMAGE_HARASSMENT="HARM_CATEGORY_IMAGE_HARASSMENT",t.HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT="HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT",t.HARM_CATEGORY_JAILBREAK="HARM_CATEGORY_JAILBREAK"})(It||(It={}));var St;(function(t){t.HARM_BLOCK_METHOD_UNSPECIFIED="HARM_BLOCK_METHOD_UNSPECIFIED",t.SEVERITY="SEVERITY",t.PROBABILITY="PROBABILITY"})(St||(St={}));var xt;(function(t){t.HARM_BLOCK_THRESHOLD_UNSPECIFIED="HARM_BLOCK_THRESHOLD_UNSPECIFIED",t.BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",t.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",t.BLOCK_ONLY_HIGH="BLOCK_ONLY_HIGH",t.BLOCK_NONE="BLOCK_NONE",t.OFF="OFF"})(xt||(xt={}));var At;(function(t){t.FINISH_REASON_UNSPECIFIED="FINISH_REASON_UNSPECIFIED",t.STOP="STOP",t.MAX_TOKENS="MAX_TOKENS",t.SAFETY="SAFETY",t.RECITATION="RECITATION",t.LANGUAGE="LANGUAGE",t.OTHER="OTHER",t.BLOCKLIST="BLOCKLIST",t.PROHIBITED_CONTENT="PROHIBITED_CONTENT",t.SPII="SPII",t.MALFORMED_FUNCTION_CALL="MALFORMED_FUNCTION_CALL",t.IMAGE_SAFETY="IMAGE_SAFETY",t.UNEXPECTED_TOOL_CALL="UNEXPECTED_TOOL_CALL",t.IMAGE_PROHIBITED_CONTENT="IMAGE_PROHIBITED_CONTENT",t.NO_IMAGE="NO_IMAGE",t.IMAGE_RECITATION="IMAGE_RECITATION",t.IMAGE_OTHER="IMAGE_OTHER"})(At||(At={}));var wt;(function(t){t.HARM_PROBABILITY_UNSPECIFIED="HARM_PROBABILITY_UNSPECIFIED",t.NEGLIGIBLE="NEGLIGIBLE",t.LOW="LOW",t.MEDIUM="MEDIUM",t.HIGH="HIGH"})(wt||(wt={}));var Nt;(function(t){t.HARM_SEVERITY_UNSPECIFIED="HARM_SEVERITY_UNSPECIFIED",t.HARM_SEVERITY_NEGLIGIBLE="HARM_SEVERITY_NEGLIGIBLE",t.HARM_SEVERITY_LOW="HARM_SEVERITY_LOW",t.HARM_SEVERITY_MEDIUM="HARM_SEVERITY_MEDIUM",t.HARM_SEVERITY_HIGH="HARM_SEVERITY_HIGH"})(Nt||(Nt={}));var Mt;(function(t){t.URL_RETRIEVAL_STATUS_UNSPECIFIED="URL_RETRIEVAL_STATUS_UNSPECIFIED",t.URL_RETRIEVAL_STATUS_SUCCESS="URL_RETRIEVAL_STATUS_SUCCESS",t.URL_RETRIEVAL_STATUS_ERROR="URL_RETRIEVAL_STATUS_ERROR",t.URL_RETRIEVAL_STATUS_PAYWALL="URL_RETRIEVAL_STATUS_PAYWALL",t.URL_RETRIEVAL_STATUS_UNSAFE="URL_RETRIEVAL_STATUS_UNSAFE"})(Mt||(Mt={}));var Pt;(function(t){t.BLOCKED_REASON_UNSPECIFIED="BLOCKED_REASON_UNSPECIFIED",t.SAFETY="SAFETY",t.OTHER="OTHER",t.BLOCKLIST="BLOCKLIST",t.PROHIBITED_CONTENT="PROHIBITED_CONTENT",t.IMAGE_SAFETY="IMAGE_SAFETY",t.MODEL_ARMOR="MODEL_ARMOR",t.JAILBREAK="JAILBREAK"})(Pt||(Pt={}));var Rt;(function(t){t.TRAFFIC_TYPE_UNSPECIFIED="TRAFFIC_TYPE_UNSPECIFIED",t.ON_DEMAND="ON_DEMAND",t.PROVISIONED_THROUGHPUT="PROVISIONED_THROUGHPUT"})(Rt||(Rt={}));var ye;(function(t){t.MODALITY_UNSPECIFIED="MODALITY_UNSPECIFIED",t.TEXT="TEXT",t.IMAGE="IMAGE",t.AUDIO="AUDIO"})(ye||(ye={}));var kt;(function(t){t.MEDIA_RESOLUTION_UNSPECIFIED="MEDIA_RESOLUTION_UNSPECIFIED",t.MEDIA_RESOLUTION_LOW="MEDIA_RESOLUTION_LOW",t.MEDIA_RESOLUTION_MEDIUM="MEDIA_RESOLUTION_MEDIUM",t.MEDIA_RESOLUTION_HIGH="MEDIA_RESOLUTION_HIGH"})(kt||(kt={}));var Dt;(function(t){t.TUNING_MODE_UNSPECIFIED="TUNING_MODE_UNSPECIFIED",t.TUNING_MODE_FULL="TUNING_MODE_FULL",t.TUNING_MODE_PEFT_ADAPTER="TUNING_MODE_PEFT_ADAPTER"})(Dt||(Dt={}));var Ut;(function(t){t.ADAPTER_SIZE_UNSPECIFIED="ADAPTER_SIZE_UNSPECIFIED",t.ADAPTER_SIZE_ONE="ADAPTER_SIZE_ONE",t.ADAPTER_SIZE_TWO="ADAPTER_SIZE_TWO",t.ADAPTER_SIZE_FOUR="ADAPTER_SIZE_FOUR",t.ADAPTER_SIZE_EIGHT="ADAPTER_SIZE_EIGHT",t.ADAPTER_SIZE_SIXTEEN="ADAPTER_SIZE_SIXTEEN",t.ADAPTER_SIZE_THIRTY_TWO="ADAPTER_SIZE_THIRTY_TWO"})(Ut||(Ut={}));var Ve;(function(t){t.JOB_STATE_UNSPECIFIED="JOB_STATE_UNSPECIFIED",t.JOB_STATE_QUEUED="JOB_STATE_QUEUED",t.JOB_STATE_PENDING="JOB_STATE_PENDING",t.JOB_STATE_RUNNING="JOB_STATE_RUNNING",t.JOB_STATE_SUCCEEDED="JOB_STATE_SUCCEEDED",t.JOB_STATE_FAILED="JOB_STATE_FAILED",t.JOB_STATE_CANCELLING="JOB_STATE_CANCELLING",t.JOB_STATE_CANCELLED="JOB_STATE_CANCELLED",t.JOB_STATE_PAUSED="JOB_STATE_PAUSED",t.JOB_STATE_EXPIRED="JOB_STATE_EXPIRED",t.JOB_STATE_UPDATING="JOB_STATE_UPDATING",t.JOB_STATE_PARTIALLY_SUCCEEDED="JOB_STATE_PARTIALLY_SUCCEEDED"})(Ve||(Ve={}));var Lt;(function(t){t.TUNING_TASK_UNSPECIFIED="TUNING_TASK_UNSPECIFIED",t.TUNING_TASK_I2V="TUNING_TASK_I2V",t.TUNING_TASK_T2V="TUNING_TASK_T2V",t.TUNING_TASK_R2V="TUNING_TASK_R2V"})(Lt||(Lt={}));var bt;(function(t){t.MEDIA_RESOLUTION_UNSPECIFIED="MEDIA_RESOLUTION_UNSPECIFIED",t.MEDIA_RESOLUTION_LOW="MEDIA_RESOLUTION_LOW",t.MEDIA_RESOLUTION_MEDIUM="MEDIA_RESOLUTION_MEDIUM",t.MEDIA_RESOLUTION_HIGH="MEDIA_RESOLUTION_HIGH",t.MEDIA_RESOLUTION_ULTRA_HIGH="MEDIA_RESOLUTION_ULTRA_HIGH"})(bt||(bt={}));var Ft;(function(t){t.FEATURE_SELECTION_PREFERENCE_UNSPECIFIED="FEATURE_SELECTION_PREFERENCE_UNSPECIFIED",t.PRIORITIZE_QUALITY="PRIORITIZE_QUALITY",t.BALANCED="BALANCED",t.PRIORITIZE_COST="PRIORITIZE_COST"})(Ft||(Ft={}));var Gt;(function(t){t.UNSPECIFIED="UNSPECIFIED",t.BLOCKING="BLOCKING",t.NON_BLOCKING="NON_BLOCKING"})(Gt||(Gt={}));var Vt;(function(t){t.MODE_UNSPECIFIED="MODE_UNSPECIFIED",t.MODE_DYNAMIC="MODE_DYNAMIC"})(Vt||(Vt={}));var qt;(function(t){t.ENVIRONMENT_UNSPECIFIED="ENVIRONMENT_UNSPECIFIED",t.ENVIRONMENT_BROWSER="ENVIRONMENT_BROWSER"})(qt||(qt={}));var Ht;(function(t){t.MODE_UNSPECIFIED="MODE_UNSPECIFIED",t.AUTO="AUTO",t.ANY="ANY",t.NONE="NONE",t.VALIDATED="VALIDATED"})(Ht||(Ht={}));var Bt;(function(t){t.BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",t.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",t.BLOCK_ONLY_HIGH="BLOCK_ONLY_HIGH",t.BLOCK_NONE="BLOCK_NONE"})(Bt||(Bt={}));var Jt;(function(t){t.DONT_ALLOW="DONT_ALLOW",t.ALLOW_ADULT="ALLOW_ADULT",t.ALLOW_ALL="ALLOW_ALL"})(Jt||(Jt={}));var $t;(function(t){t.auto="auto",t.en="en",t.ja="ja",t.ko="ko",t.hi="hi",t.zh="zh",t.pt="pt",t.es="es"})($t||($t={}));var Wt;(function(t){t.MASK_MODE_DEFAULT="MASK_MODE_DEFAULT",t.MASK_MODE_USER_PROVIDED="MASK_MODE_USER_PROVIDED",t.MASK_MODE_BACKGROUND="MASK_MODE_BACKGROUND",t.MASK_MODE_FOREGROUND="MASK_MODE_FOREGROUND",t.MASK_MODE_SEMANTIC="MASK_MODE_SEMANTIC"})(Wt||(Wt={}));var Yt;(function(t){t.CONTROL_TYPE_DEFAULT="CONTROL_TYPE_DEFAULT",t.CONTROL_TYPE_CANNY="CONTROL_TYPE_CANNY",t.CONTROL_TYPE_SCRIBBLE="CONTROL_TYPE_SCRIBBLE",t.CONTROL_TYPE_FACE_MESH="CONTROL_TYPE_FACE_MESH"})(Yt||(Yt={}));var Kt;(function(t){t.SUBJECT_TYPE_DEFAULT="SUBJECT_TYPE_DEFAULT",t.SUBJECT_TYPE_PERSON="SUBJECT_TYPE_PERSON",t.SUBJECT_TYPE_ANIMAL="SUBJECT_TYPE_ANIMAL",t.SUBJECT_TYPE_PRODUCT="SUBJECT_TYPE_PRODUCT"})(Kt||(Kt={}));var zt;(function(t){t.EDIT_MODE_DEFAULT="EDIT_MODE_DEFAULT",t.EDIT_MODE_INPAINT_REMOVAL="EDIT_MODE_INPAINT_REMOVAL",t.EDIT_MODE_INPAINT_INSERTION="EDIT_MODE_INPAINT_INSERTION",t.EDIT_MODE_OUTPAINT="EDIT_MODE_OUTPAINT",t.EDIT_MODE_CONTROLLED_EDITING="EDIT_MODE_CONTROLLED_EDITING",t.EDIT_MODE_STYLE="EDIT_MODE_STYLE",t.EDIT_MODE_BGSWAP="EDIT_MODE_BGSWAP",t.EDIT_MODE_PRODUCT_IMAGE="EDIT_MODE_PRODUCT_IMAGE"})(zt||(zt={}));var Ot;(function(t){t.FOREGROUND="FOREGROUND",t.BACKGROUND="BACKGROUND",t.PROMPT="PROMPT",t.SEMANTIC="SEMANTIC",t.INTERACTIVE="INTERACTIVE"})(Ot||(Ot={}));var Xt;(function(t){t.ASSET="ASSET",t.STYLE="STYLE"})(Xt||(Xt={}));var Qt;(function(t){t.INSERT="INSERT",t.REMOVE="REMOVE",t.REMOVE_STATIC="REMOVE_STATIC",t.OUTPAINT="OUTPAINT"})(Qt||(Qt={}));var Zt;(function(t){t.OPTIMIZED="OPTIMIZED",t.LOSSLESS="LOSSLESS"})(Zt||(Zt={}));var jt;(function(t){t.SUPERVISED_FINE_TUNING="SUPERVISED_FINE_TUNING",t.PREFERENCE_TUNING="PREFERENCE_TUNING"})(jt||(jt={}));var en;(function(t){t.STATE_UNSPECIFIED="STATE_UNSPECIFIED",t.STATE_PENDING="STATE_PENDING",t.STATE_ACTIVE="STATE_ACTIVE",t.STATE_FAILED="STATE_FAILED"})(en||(en={}));var tn;(function(t){t.STATE_UNSPECIFIED="STATE_UNSPECIFIED",t.PROCESSING="PROCESSING",t.ACTIVE="ACTIVE",t.FAILED="FAILED"})(tn||(tn={}));var nn;(function(t){t.SOURCE_UNSPECIFIED="SOURCE_UNSPECIFIED",t.UPLOADED="UPLOADED",t.GENERATED="GENERATED"})(nn||(nn={}));var on;(function(t){t.TURN_COMPLETE_REASON_UNSPECIFIED="TURN_COMPLETE_REASON_UNSPECIFIED",t.MALFORMED_FUNCTION_CALL="MALFORMED_FUNCTION_CALL",t.RESPONSE_REJECTED="RESPONSE_REJECTED",t.NEED_MORE_INPUT="NEED_MORE_INPUT"})(on||(on={}));var sn;(function(t){t.MODALITY_UNSPECIFIED="MODALITY_UNSPECIFIED",t.TEXT="TEXT",t.IMAGE="IMAGE",t.VIDEO="VIDEO",t.AUDIO="AUDIO",t.DOCUMENT="DOCUMENT"})(sn||(sn={}));var rn;(function(t){t.VAD_SIGNAL_TYPE_UNSPECIFIED="VAD_SIGNAL_TYPE_UNSPECIFIED",t.VAD_SIGNAL_TYPE_SOS="VAD_SIGNAL_TYPE_SOS",t.VAD_SIGNAL_TYPE_EOS="VAD_SIGNAL_TYPE_EOS"})(rn||(rn={}));var ln;(function(t){t.START_SENSITIVITY_UNSPECIFIED="START_SENSITIVITY_UNSPECIFIED",t.START_SENSITIVITY_HIGH="START_SENSITIVITY_HIGH",t.START_SENSITIVITY_LOW="START_SENSITIVITY_LOW"})(ln||(ln={}));var an;(function(t){t.END_SENSITIVITY_UNSPECIFIED="END_SENSITIVITY_UNSPECIFIED",t.END_SENSITIVITY_HIGH="END_SENSITIVITY_HIGH",t.END_SENSITIVITY_LOW="END_SENSITIVITY_LOW"})(an||(an={}));var un;(function(t){t.ACTIVITY_HANDLING_UNSPECIFIED="ACTIVITY_HANDLING_UNSPECIFIED",t.START_OF_ACTIVITY_INTERRUPTS="START_OF_ACTIVITY_INTERRUPTS",t.NO_INTERRUPTION="NO_INTERRUPTION"})(un||(un={}));var dn;(function(t){t.TURN_COVERAGE_UNSPECIFIED="TURN_COVERAGE_UNSPECIFIED",t.TURN_INCLUDES_ONLY_ACTIVITY="TURN_INCLUDES_ONLY_ACTIVITY",t.TURN_INCLUDES_ALL_INPUT="TURN_INCLUDES_ALL_INPUT"})(dn||(dn={}));var cn;(function(t){t.SCALE_UNSPECIFIED="SCALE_UNSPECIFIED",t.C_MAJOR_A_MINOR="C_MAJOR_A_MINOR",t.D_FLAT_MAJOR_B_FLAT_MINOR="D_FLAT_MAJOR_B_FLAT_MINOR",t.D_MAJOR_B_MINOR="D_MAJOR_B_MINOR",t.E_FLAT_MAJOR_C_MINOR="E_FLAT_MAJOR_C_MINOR",t.E_MAJOR_D_FLAT_MINOR="E_MAJOR_D_FLAT_MINOR",t.F_MAJOR_D_MINOR="F_MAJOR_D_MINOR",t.G_FLAT_MAJOR_E_FLAT_MINOR="G_FLAT_MAJOR_E_FLAT_MINOR",t.G_MAJOR_E_MINOR="G_MAJOR_E_MINOR",t.A_FLAT_MAJOR_F_MINOR="A_FLAT_MAJOR_F_MINOR",t.A_MAJOR_G_FLAT_MINOR="A_MAJOR_G_FLAT_MINOR",t.B_FLAT_MAJOR_G_MINOR="B_FLAT_MAJOR_G_MINOR",t.B_MAJOR_A_FLAT_MINOR="B_MAJOR_A_FLAT_MINOR"})(cn||(cn={}));var fn;(function(t){t.MUSIC_GENERATION_MODE_UNSPECIFIED="MUSIC_GENERATION_MODE_UNSPECIFIED",t.QUALITY="QUALITY",t.DIVERSITY="DIVERSITY",t.VOCALIZATION="VOCALIZATION"})(fn||(fn={}));var se;(function(t){t.PLAYBACK_CONTROL_UNSPECIFIED="PLAYBACK_CONTROL_UNSPECIFIED",t.PLAY="PLAY",t.PAUSE="PAUSE",t.STOP="STOP",t.RESET_CONTEXT="RESET_CONTEXT"})(se||(se={}));class qe{constructor(e){const n={};for(const o of e.headers.entries())n[o[0]]=o[1];this.headers=n,this.responseInternal=e}json(){return this.responseInternal.json()}}class pe{get text(){var e,n,o,s,l,a,u,c;if(((s=(o=(n=(e=this.candidates)===null||e===void 0?void 0:e[0])===null||n===void 0?void 0:n.content)===null||o===void 0?void 0:o.parts)===null||s===void 0?void 0:s.length)===0)return;this.candidates&&this.candidates.length>1&&console.warn("there are multiple candidates in the response, returning text from the first one.");let d="",f=!1;const h=[];for(const p of(c=(u=(a=(l=this.candidates)===null||l===void 0?void 0:l[0])===null||a===void 0?void 0:a.content)===null||u===void 0?void 0:u.parts)!==null&&c!==void 0?c:[]){for(const[m,y]of Object.entries(p))m!=="text"&&m!=="thought"&&m!=="thoughtSignature"&&(y!==null||y!==void 0)&&h.push(m);if(typeof p.text=="string"){if(typeof p.thought=="boolean"&&p.thought)continue;f=!0,d+=p.text}}return h.length>0&&console.warn(`there are non-text parts ${h} in the response, returning concatenation of all text parts. Please refer to the non text parts for a full response from model.`),f?d:void 0}get data(){var e,n,o,s,l,a,u,c;if(((s=(o=(n=(e=this.candidates)===null||e===void 0?void 0:e[0])===null||n===void 0?void 0:n.content)===null||o===void 0?void 0:o.parts)===null||s===void 0?void 0:s.length)===0)return;this.candidates&&this.candidates.length>1&&console.warn("there are multiple candidates in the response, returning data from the first one.");let d="";const f=[];for(const h of(c=(u=(a=(l=this.candidates)===null||l===void 0?void 0:l[0])===null||a===void 0?void 0:a.content)===null||u===void 0?void 0:u.parts)!==null&&c!==void 0?c:[]){for(const[p,m]of Object.entries(h))p!=="inlineData"&&(m!==null||m!==void 0)&&f.push(p);h.inlineData&&typeof h.inlineData.data=="string"&&(d+=atob(h.inlineData.data))}return f.length>0&&console.warn(`there are non-data parts ${f} in the response, returning concatenation of all data parts. Please refer to the non data parts for a full response from model.`),d.length>0?btoa(d):void 0}get functionCalls(){var e,n,o,s,l,a,u,c;if(((s=(o=(n=(e=this.candidates)===null||e===void 0?void 0:e[0])===null||n===void 0?void 0:n.content)===null||o===void 0?void 0:o.parts)===null||s===void 0?void 0:s.length)===0)return;this.candidates&&this.candidates.length>1&&console.warn("there are multiple candidates in the response, returning function calls from the first one.");const d=(c=(u=(a=(l=this.candidates)===null||l===void 0?void 0:l[0])===null||a===void 0?void 0:a.content)===null||u===void 0?void 0:u.parts)===null||c===void 0?void 0:c.filter(f=>f.functionCall).map(f=>f.functionCall).filter(f=>f!==void 0);if((d==null?void 0:d.length)!==0)return d}get executableCode(){var e,n,o,s,l,a,u,c,d;if(((s=(o=(n=(e=this.candidates)===null||e===void 0?void 0:e[0])===null||n===void 0?void 0:n.content)===null||o===void 0?void 0:o.parts)===null||s===void 0?void 0:s.length)===0)return;this.candidates&&this.candidates.length>1&&console.warn("there are multiple candidates in the response, returning executable code from the first one.");const f=(c=(u=(a=(l=this.candidates)===null||l===void 0?void 0:l[0])===null||a===void 0?void 0:a.content)===null||u===void 0?void 0:u.parts)===null||c===void 0?void 0:c.filter(h=>h.executableCode).map(h=>h.executableCode).filter(h=>h!==void 0);if((f==null?void 0:f.length)!==0)return(d=f==null?void 0:f[0])===null||d===void 0?void 0:d.code}get codeExecutionResult(){var e,n,o,s,l,a,u,c,d;if(((s=(o=(n=(e=this.candidates)===null||e===void 0?void 0:e[0])===null||n===void 0?void 0:n.content)===null||o===void 0?void 0:o.parts)===null||s===void 0?void 0:s.length)===0)return;this.candidates&&this.candidates.length>1&&console.warn("there are multiple candidates in the response, returning code execution result from the first one.");const f=(c=(u=(a=(l=this.candidates)===null||l===void 0?void 0:l[0])===null||a===void 0?void 0:a.content)===null||u===void 0?void 0:u.parts)===null||c===void 0?void 0:c.filter(h=>h.codeExecutionResult).map(h=>h.codeExecutionResult).filter(h=>h!==void 0);if((f==null?void 0:f.length)!==0)return(d=f==null?void 0:f[0])===null||d===void 0?void 0:d.output}}class pn{}class hn{}class Fi{}class Gi{}class Vi{}class qi{}class mn{}class gn{}class yn{}class Hi{}class Te{_fromAPIResponse({apiResponse:e,_isVertexAI:n}){const o=new Te;let s;const l=e;return n?s=xi(l):s=Si(l),Object.assign(o,s),o}}class Tn{}class _n{}class En{}class Cn{}class Bi{}class Ji{}class $i{}class He{_fromAPIResponse({apiResponse:e,_isVertexAI:n}){const o=new He,l=ki(e);return Object.assign(o,l),o}}class Wi{}class Yi{}class Ki{}class vn{}class zi{get text(){var e,n,o;let s="",l=!1;const a=[];for(const u of(o=(n=(e=this.serverContent)===null||e===void 0?void 0:e.modelTurn)===null||n===void 0?void 0:n.parts)!==null&&o!==void 0?o:[]){for(const[c,d]of Object.entries(u))c!=="text"&&c!=="thought"&&d!==null&&a.push(c);if(typeof u.text=="string"){if(typeof u.thought=="boolean"&&u.thought)continue;l=!0,s+=u.text}}return a.length>0&&console.warn(`there are non-text parts ${a} in the response, returning concatenation of all text parts. Please refer to the non text parts for a full response from model.`),l?s:void 0}get data(){var e,n,o;let s="";const l=[];for(const a of(o=(n=(e=this.serverContent)===null||e===void 0?void 0:e.modelTurn)===null||n===void 0?void 0:n.parts)!==null&&o!==void 0?o:[]){for(const[u,c]of Object.entries(a))u!=="inlineData"&&c!==null&&l.push(u);a.inlineData&&typeof a.inlineData.data=="string"&&(s+=atob(a.inlineData.data))}return l.length>0&&console.warn(`there are non-data parts ${l} in the response, returning concatenation of all data parts. Please refer to the non data parts for a full response from model.`),s.length>0?btoa(s):void 0}}class Oi{get audioChunk(){if(this.serverContent&&this.serverContent.audioChunks&&this.serverContent.audioChunks.length>0)return this.serverContent.audioChunks[0]}}class Be{_fromAPIResponse({apiResponse:e,_isVertexAI:n}){const o=new Be,l=pt(e);return Object.assign(o,l),o}}/**
142
+ * @license
143
+ * Copyright 2025 Google LLC
144
+ * SPDX-License-Identifier: Apache-2.0
145
+ */function L(t,e){if(!e||typeof e!="string")throw new Error("model is required and must be a string");if(e.includes("..")||e.includes("?")||e.includes("&"))throw new Error("invalid model parameter");if(t.isVertexAI()){if(e.startsWith("publishers/")||e.startsWith("projects/")||e.startsWith("models/"))return e;if(e.indexOf("/")>=0){const n=e.split("/",2);return`publishers/${n[0]}/models/${n[1]}`}else return`publishers/google/models/${e}`}else return e.startsWith("models/")||e.startsWith("tunedModels/")?e:`models/${e}`}function In(t,e){const n=L(t,e);return n?n.startsWith("publishers/")&&t.isVertexAI()?`projects/${t.getProject()}/locations/${t.getLocation()}/${n}`:n.startsWith("models/")&&t.isVertexAI()?`projects/${t.getProject()}/locations/${t.getLocation()}/publishers/google/${n}`:n:""}function Sn(t){return Array.isArray(t)?t.map(e=>_e(e)):[_e(t)]}function _e(t){if(typeof t=="object"&&t!==null)return t;throw new Error(`Could not parse input as Blob. Unsupported blob type: ${typeof t}`)}function xn(t){const e=_e(t);if(e.mimeType&&e.mimeType.startsWith("image/"))return e;throw new Error(`Unsupported mime type: ${e.mimeType}`)}function An(t){const e=_e(t);if(e.mimeType&&e.mimeType.startsWith("audio/"))return e;throw new Error(`Unsupported mime type: ${e.mimeType}`)}function wn(t){if(t==null)throw new Error("PartUnion is required");if(typeof t=="object")return t;if(typeof t=="string")return{text:t};throw new Error(`Unsupported part type: ${typeof t}`)}function Nn(t){if(t==null||Array.isArray(t)&&t.length===0)throw new Error("PartListUnion is required");return Array.isArray(t)?t.map(e=>wn(e)):[wn(t)]}function Je(t){return t!=null&&typeof t=="object"&&"parts"in t&&Array.isArray(t.parts)}function Mn(t){return t!=null&&typeof t=="object"&&"functionCall"in t}function Pn(t){return t!=null&&typeof t=="object"&&"functionResponse"in t}function q(t){if(t==null)throw new Error("ContentUnion is required");return Je(t)?t:{role:"user",parts:Nn(t)}}function $e(t,e){if(!e)return[];if(t.isVertexAI()&&Array.isArray(e))return e.flatMap(n=>{const o=q(n);return o.parts&&o.parts.length>0&&o.parts[0].text!==void 0?[o.parts[0].text]:[]});if(t.isVertexAI()){const n=q(e);return n.parts&&n.parts.length>0&&n.parts[0].text!==void 0?[n.parts[0].text]:[]}return Array.isArray(e)?e.map(n=>q(n)):[q(e)]}function W(t){if(t==null||Array.isArray(t)&&t.length===0)throw new Error("contents are required");if(!Array.isArray(t)){if(Mn(t)||Pn(t))throw new Error("To specify functionCall or functionResponse parts, please wrap them in a Content object, specifying the role for them");return[q(t)]}const e=[],n=[],o=Je(t[0]);for(const s of t){const l=Je(s);if(l!=o)throw new Error("Mixing Content and Parts is not supported, please group the parts into a the appropriate Content objects and specify the roles for them");if(l)e.push(s);else{if(Mn(s)||Pn(s))throw new Error("To specify functionCall or functionResponse parts, please wrap them, and any other parts, in Content objects as appropriate, specifying the role for them");n.push(s)}}return o||e.push({role:"user",parts:Nn(n)}),e}function Xi(t,e){t.includes("null")&&(e.nullable=!0);const n=t.filter(o=>o!=="null");if(n.length===1)e.type=Object.values(te).includes(n[0].toUpperCase())?n[0].toUpperCase():te.TYPE_UNSPECIFIED;else{e.anyOf=[];for(const o of n)e.anyOf.push({type:Object.values(te).includes(o.toUpperCase())?o.toUpperCase():te.TYPE_UNSPECIFIED})}}function re(t){const e={},n=["items"],o=["anyOf"],s=["properties"];if(t.type&&t.anyOf)throw new Error("type and anyOf cannot be both populated.");const l=t.anyOf;l!=null&&l.length==2&&(l[0].type==="null"?(e.nullable=!0,t=l[1]):l[1].type==="null"&&(e.nullable=!0,t=l[0])),t.type instanceof Array&&Xi(t.type,e);for(const[a,u]of Object.entries(t))if(u!=null)if(a=="type"){if(u==="null")throw new Error("type: null can not be the only possible type for the field.");if(u instanceof Array)continue;e.type=Object.values(te).includes(u.toUpperCase())?u.toUpperCase():te.TYPE_UNSPECIFIED}else if(n.includes(a))e[a]=re(u);else if(o.includes(a)){const c=[];for(const d of u){if(d.type=="null"){e.nullable=!0;continue}c.push(re(d))}e[a]=c}else if(s.includes(a)){const c={};for(const[d,f]of Object.entries(u))c[d]=re(f);e[a]=c}else{if(a==="additionalProperties")continue;e[a]=u}return e}function We(t){return re(t)}function Ye(t){if(typeof t=="object")return t;if(typeof t=="string")return{voiceConfig:{prebuiltVoiceConfig:{voiceName:t}}};throw new Error(`Unsupported speechConfig type: ${typeof t}`)}function Ke(t){if("multiSpeakerVoiceConfig"in t)throw new Error("multiSpeakerVoiceConfig is not supported in the live API.");return t}function le(t){if(t.functionDeclarations)for(const e of t.functionDeclarations)e.parameters&&(Object.keys(e.parameters).includes("$schema")?e.parametersJsonSchema||(e.parametersJsonSchema=e.parameters,delete e.parameters):e.parameters=re(e.parameters)),e.response&&(Object.keys(e.response).includes("$schema")?e.responseJsonSchema||(e.responseJsonSchema=e.response,delete e.response):e.response=re(e.response));return t}function ae(t){if(t==null)throw new Error("tools is required");if(!Array.isArray(t))throw new Error("tools is required and must be an array of Tools");const e=[];for(const n of t)e.push(n);return e}function Qi(t,e,n,o=1){const s=!e.startsWith(`${n}/`)&&e.split("/").length===o;return t.isVertexAI()?e.startsWith("projects/")?e:e.startsWith("locations/")?`projects/${t.getProject()}/${e}`:e.startsWith(`${n}/`)?`projects/${t.getProject()}/locations/${t.getLocation()}/${e}`:s?`projects/${t.getProject()}/locations/${t.getLocation()}/${n}/${e}`:e:s?`${n}/${e}`:e}function Z(t,e){if(typeof e!="string")throw new Error("name must be a string");return Qi(t,e,"cachedContents")}function Rn(t){switch(t){case"STATE_UNSPECIFIED":return"JOB_STATE_UNSPECIFIED";case"CREATING":return"JOB_STATE_RUNNING";case"ACTIVE":return"JOB_STATE_SUCCEEDED";case"FAILED":return"JOB_STATE_FAILED";default:return t}}function ne(t){return Ge(t)}function Zi(t){return t!=null&&typeof t=="object"&&"name"in t}function ji(t){return t!=null&&typeof t=="object"&&"video"in t}function es(t){return t!=null&&typeof t=="object"&&"uri"in t}function kn(t){var e;let n;if(Zi(t)&&(n=t.name),!(es(t)&&(n=t.uri,n===void 0))&&!(ji(t)&&(n=(e=t.video)===null||e===void 0?void 0:e.uri,n===void 0))){if(typeof t=="string"&&(n=t),n===void 0)throw new Error("Could not extract file name from the provided input.");if(n.startsWith("https://")){const s=n.split("files/")[1].match(/[a-z0-9]+/);if(s===null)throw new Error(`Could not extract file name from URI ${n}`);n=s[0]}else n.startsWith("files/")&&(n=n.split("files/")[1]);return n}}function Dn(t,e){let n;return t.isVertexAI()?n=e?"publishers/google/models":"models":n=e?"models":"tunedModels",n}function Un(t){for(const e of["models","tunedModels","publisherModels"])if(ts(t,e))return t[e];return[]}function ts(t,e){return t!==null&&typeof t=="object"&&e in t}function ns(t,e={}){const n=t,o={name:n.name,description:n.description,parametersJsonSchema:n.inputSchema};return n.outputSchema&&(o.responseJsonSchema=n.outputSchema),e.behavior&&(o.behavior=e.behavior),{functionDeclarations:[o]}}function os(t,e={}){const n=[],o=new Set;for(const s of t){const l=s.name;if(o.has(l))throw new Error(`Duplicate function name ${l} found in MCP tools. Please ensure function names are unique.`);o.add(l);const a=ns(s,e);a.functionDeclarations&&n.push(...a.functionDeclarations)}return{functionDeclarations:n}}function Ln(t,e){let n;if(typeof e=="string")if(t.isVertexAI())if(e.startsWith("gs://"))n={format:"jsonl",gcsUri:[e]};else if(e.startsWith("bq://"))n={format:"bigquery",bigqueryUri:e};else throw new Error(`Unsupported string source for Vertex AI: ${e}`);else if(e.startsWith("files/"))n={fileName:e};else throw new Error(`Unsupported string source for Gemini API: ${e}`);else if(Array.isArray(e)){if(t.isVertexAI())throw new Error("InlinedRequest[] is not supported in Vertex AI.");n={inlinedRequests:e}}else n=e;const o=[n.gcsUri,n.bigqueryUri].filter(Boolean).length,s=[n.inlinedRequests,n.fileName].filter(Boolean).length;if(t.isVertexAI()){if(s>0||o!==1)throw new Error("Exactly one of `gcsUri` or `bigqueryUri` must be set for Vertex AI.")}else if(o>0||s!==1)throw new Error("Exactly one of `inlinedRequests`, `fileName`, must be set for Gemini API.");return n}function is(t){if(typeof t!="string")return t;const e=t;if(e.startsWith("gs://"))return{format:"jsonl",gcsUri:e};if(e.startsWith("bq://"))return{format:"bigquery",bigqueryUri:e};throw new Error(`Unsupported destination: ${e}`)}function bn(t){if(typeof t!="object"||t===null)return{};const e=t,n=e.inlinedResponses;if(typeof n!="object"||n===null)return t;const s=n.inlinedResponses;if(!Array.isArray(s)||s.length===0)return t;let l=!1;for(const a of s){if(typeof a!="object"||a===null)continue;const c=a.response;if(typeof c!="object"||c===null)continue;if(c.embedding!==void 0){l=!0;break}}return l&&(e.inlinedEmbedContentResponses=e.inlinedResponses,delete e.inlinedResponses),t}function ue(t,e){const n=e;if(!t.isVertexAI()){if(/batches\/[^/]+$/.test(n))return n.split("/").pop();throw new Error(`Invalid batch job name: ${n}.`)}if(/^projects\/[^/]+\/locations\/[^/]+\/batchPredictionJobs\/[^/]+$/.test(n))return n.split("/").pop();if(/^\d+$/.test(n))return n;throw new Error(`Invalid batch job name: ${n}.`)}function Fn(t){const e=t;return e==="BATCH_STATE_UNSPECIFIED"?"JOB_STATE_UNSPECIFIED":e==="BATCH_STATE_PENDING"?"JOB_STATE_PENDING":e==="BATCH_STATE_RUNNING"?"JOB_STATE_RUNNING":e==="BATCH_STATE_SUCCEEDED"?"JOB_STATE_SUCCEEDED":e==="BATCH_STATE_FAILED"?"JOB_STATE_FAILED":e==="BATCH_STATE_CANCELLED"?"JOB_STATE_CANCELLED":e==="BATCH_STATE_EXPIRED"?"JOB_STATE_EXPIRED":e}/**
146
+ * @license
147
+ * Copyright 2025 Google LLC
148
+ * SPDX-License-Identifier: Apache-2.0
149
+ */function ss(t){const e={},n=i(t,["responsesFile"]);n!=null&&r(e,["fileName"],n);const o=i(t,["inlinedResponses","inlinedResponses"]);if(o!=null){let l=o;Array.isArray(l)&&(l=l.map(a=>Vs(a))),r(e,["inlinedResponses"],l)}const s=i(t,["inlinedEmbedContentResponses","inlinedResponses"]);if(s!=null){let l=s;Array.isArray(l)&&(l=l.map(a=>a)),r(e,["inlinedEmbedContentResponses"],l)}return e}function rs(t){const e={},n=i(t,["predictionsFormat"]);n!=null&&r(e,["format"],n);const o=i(t,["gcsDestination","outputUriPrefix"]);o!=null&&r(e,["gcsUri"],o);const s=i(t,["bigqueryDestination","outputUri"]);return s!=null&&r(e,["bigqueryUri"],s),e}function ls(t){const e={},n=i(t,["format"]);n!=null&&r(e,["predictionsFormat"],n);const o=i(t,["gcsUri"]);o!=null&&r(e,["gcsDestination","outputUriPrefix"],o);const s=i(t,["bigqueryUri"]);if(s!=null&&r(e,["bigqueryDestination","outputUri"],s),i(t,["fileName"])!==void 0)throw new Error("fileName parameter is not supported in Vertex AI.");if(i(t,["inlinedResponses"])!==void 0)throw new Error("inlinedResponses parameter is not supported in Vertex AI.");if(i(t,["inlinedEmbedContentResponses"])!==void 0)throw new Error("inlinedEmbedContentResponses parameter is not supported in Vertex AI.");return e}function Ee(t){const e={},n=i(t,["name"]);n!=null&&r(e,["name"],n);const o=i(t,["metadata","displayName"]);o!=null&&r(e,["displayName"],o);const s=i(t,["metadata","state"]);s!=null&&r(e,["state"],Fn(s));const l=i(t,["metadata","createTime"]);l!=null&&r(e,["createTime"],l);const a=i(t,["metadata","endTime"]);a!=null&&r(e,["endTime"],a);const u=i(t,["metadata","updateTime"]);u!=null&&r(e,["updateTime"],u);const c=i(t,["metadata","model"]);c!=null&&r(e,["model"],c);const d=i(t,["metadata","output"]);return d!=null&&r(e,["dest"],ss(bn(d))),e}function ze(t){const e={},n=i(t,["name"]);n!=null&&r(e,["name"],n);const o=i(t,["displayName"]);o!=null&&r(e,["displayName"],o);const s=i(t,["state"]);s!=null&&r(e,["state"],Fn(s));const l=i(t,["error"]);l!=null&&r(e,["error"],l);const a=i(t,["createTime"]);a!=null&&r(e,["createTime"],a);const u=i(t,["startTime"]);u!=null&&r(e,["startTime"],u);const c=i(t,["endTime"]);c!=null&&r(e,["endTime"],c);const d=i(t,["updateTime"]);d!=null&&r(e,["updateTime"],d);const f=i(t,["model"]);f!=null&&r(e,["model"],f);const h=i(t,["inputConfig"]);h!=null&&r(e,["src"],as(h));const p=i(t,["outputConfig"]);p!=null&&r(e,["dest"],rs(bn(p)));const m=i(t,["completionStats"]);return m!=null&&r(e,["completionStats"],m),e}function as(t){const e={},n=i(t,["instancesFormat"]);n!=null&&r(e,["format"],n);const o=i(t,["gcsSource","uris"]);o!=null&&r(e,["gcsUri"],o);const s=i(t,["bigquerySource","inputUri"]);return s!=null&&r(e,["bigqueryUri"],s),e}function us(t,e){const n={};if(i(e,["format"])!==void 0)throw new Error("format parameter is not supported in Gemini API.");if(i(e,["gcsUri"])!==void 0)throw new Error("gcsUri parameter is not supported in Gemini API.");if(i(e,["bigqueryUri"])!==void 0)throw new Error("bigqueryUri parameter is not supported in Gemini API.");const o=i(e,["fileName"]);o!=null&&r(n,["fileName"],o);const s=i(e,["inlinedRequests"]);if(s!=null){let l=s;Array.isArray(l)&&(l=l.map(a=>Gs(t,a))),r(n,["requests","requests"],l)}return n}function ds(t){const e={},n=i(t,["format"]);n!=null&&r(e,["instancesFormat"],n);const o=i(t,["gcsUri"]);o!=null&&r(e,["gcsSource","uris"],o);const s=i(t,["bigqueryUri"]);if(s!=null&&r(e,["bigquerySource","inputUri"],s),i(t,["fileName"])!==void 0)throw new Error("fileName parameter is not supported in Vertex AI.");if(i(t,["inlinedRequests"])!==void 0)throw new Error("inlinedRequests parameter is not supported in Vertex AI.");return e}function cs(t){const e={},n=i(t,["data"]);if(n!=null&&r(e,["data"],n),i(t,["displayName"])!==void 0)throw new Error("displayName parameter is not supported in Gemini API.");const o=i(t,["mimeType"]);return o!=null&&r(e,["mimeType"],o),e}function fs(t,e){const n={},o=i(e,["name"]);return o!=null&&r(n,["_url","name"],ue(t,o)),n}function ps(t,e){const n={},o=i(e,["name"]);return o!=null&&r(n,["_url","name"],ue(t,o)),n}function hs(t){const e={},n=i(t,["content"]);n!=null&&r(e,["content"],n);const o=i(t,["citationMetadata"]);o!=null&&r(e,["citationMetadata"],ms(o));const s=i(t,["tokenCount"]);s!=null&&r(e,["tokenCount"],s);const l=i(t,["finishReason"]);l!=null&&r(e,["finishReason"],l);const a=i(t,["avgLogprobs"]);a!=null&&r(e,["avgLogprobs"],a);const u=i(t,["groundingMetadata"]);u!=null&&r(e,["groundingMetadata"],u);const c=i(t,["index"]);c!=null&&r(e,["index"],c);const d=i(t,["logprobsResult"]);d!=null&&r(e,["logprobsResult"],d);const f=i(t,["safetyRatings"]);if(f!=null){let p=f;Array.isArray(p)&&(p=p.map(m=>m)),r(e,["safetyRatings"],p)}const h=i(t,["urlContextMetadata"]);return h!=null&&r(e,["urlContextMetadata"],h),e}function ms(t){const e={},n=i(t,["citationSources"]);if(n!=null){let o=n;Array.isArray(o)&&(o=o.map(s=>s)),r(e,["citations"],o)}return e}function Gn(t){const e={},n=i(t,["parts"]);if(n!=null){let s=n;Array.isArray(s)&&(s=s.map(l=>Ys(l))),r(e,["parts"],s)}const o=i(t,["role"]);return o!=null&&r(e,["role"],o),e}function gs(t,e){const n={},o=i(t,["displayName"]);if(e!==void 0&&o!=null&&r(e,["batch","displayName"],o),i(t,["dest"])!==void 0)throw new Error("dest parameter is not supported in Gemini API.");return n}function ys(t,e){const n={},o=i(t,["displayName"]);e!==void 0&&o!=null&&r(e,["displayName"],o);const s=i(t,["dest"]);return e!==void 0&&s!=null&&r(e,["outputConfig"],ls(is(s))),n}function Vn(t,e){const n={},o=i(e,["model"]);o!=null&&r(n,["_url","model"],L(t,o));const s=i(e,["src"]);s!=null&&r(n,["batch","inputConfig"],us(t,Ln(t,s)));const l=i(e,["config"]);return l!=null&&gs(l,n),n}function Ts(t,e){const n={},o=i(e,["model"]);o!=null&&r(n,["model"],L(t,o));const s=i(e,["src"]);s!=null&&r(n,["inputConfig"],ds(Ln(t,s)));const l=i(e,["config"]);return l!=null&&ys(l,n),n}function _s(t,e){const n={},o=i(t,["displayName"]);return e!==void 0&&o!=null&&r(e,["batch","displayName"],o),n}function Es(t,e){const n={},o=i(e,["model"]);o!=null&&r(n,["_url","model"],L(t,o));const s=i(e,["src"]);s!=null&&r(n,["batch","inputConfig"],ws(t,s));const l=i(e,["config"]);return l!=null&&_s(l,n),n}function Cs(t,e){const n={},o=i(e,["name"]);return o!=null&&r(n,["_url","name"],ue(t,o)),n}function vs(t,e){const n={},o=i(e,["name"]);return o!=null&&r(n,["_url","name"],ue(t,o)),n}function Is(t){const e={},n=i(t,["sdkHttpResponse"]);n!=null&&r(e,["sdkHttpResponse"],n);const o=i(t,["name"]);o!=null&&r(e,["name"],o);const s=i(t,["done"]);s!=null&&r(e,["done"],s);const l=i(t,["error"]);return l!=null&&r(e,["error"],l),e}function Ss(t){const e={},n=i(t,["sdkHttpResponse"]);n!=null&&r(e,["sdkHttpResponse"],n);const o=i(t,["name"]);o!=null&&r(e,["name"],o);const s=i(t,["done"]);s!=null&&r(e,["done"],s);const l=i(t,["error"]);return l!=null&&r(e,["error"],l),e}function xs(t,e){const n={},o=i(e,["contents"]);if(o!=null){let l=$e(t,o);Array.isArray(l)&&(l=l.map(a=>a)),r(n,["requests[]","request","content"],l)}const s=i(e,["config"]);return s!=null&&(r(n,["_self"],As(s,n)),vi(n,{"requests[].*":"requests[].request.*"})),n}function As(t,e){const n={},o=i(t,["taskType"]);e!==void 0&&o!=null&&r(e,["requests[]","taskType"],o);const s=i(t,["title"]);e!==void 0&&s!=null&&r(e,["requests[]","title"],s);const l=i(t,["outputDimensionality"]);if(e!==void 0&&l!=null&&r(e,["requests[]","outputDimensionality"],l),i(t,["mimeType"])!==void 0)throw new Error("mimeType parameter is not supported in Gemini API.");if(i(t,["autoTruncate"])!==void 0)throw new Error("autoTruncate parameter is not supported in Gemini API.");return n}function ws(t,e){const n={},o=i(e,["fileName"]);o!=null&&r(n,["file_name"],o);const s=i(e,["inlinedRequests"]);return s!=null&&r(n,["requests"],xs(t,s)),n}function Ns(t){const e={};if(i(t,["displayName"])!==void 0)throw new Error("displayName parameter is not supported in Gemini API.");const n=i(t,["fileUri"]);n!=null&&r(e,["fileUri"],n);const o=i(t,["mimeType"]);return o!=null&&r(e,["mimeType"],o),e}function Ms(t){const e={},n=i(t,["id"]);n!=null&&r(e,["id"],n);const o=i(t,["args"]);o!=null&&r(e,["args"],o);const s=i(t,["name"]);if(s!=null&&r(e,["name"],s),i(t,["partialArgs"])!==void 0)throw new Error("partialArgs parameter is not supported in Gemini API.");if(i(t,["willContinue"])!==void 0)throw new Error("willContinue parameter is not supported in Gemini API.");return e}function Ps(t){const e={},n=i(t,["mode"]);n!=null&&r(e,["mode"],n);const o=i(t,["allowedFunctionNames"]);if(o!=null&&r(e,["allowedFunctionNames"],o),i(t,["streamFunctionCallArguments"])!==void 0)throw new Error("streamFunctionCallArguments parameter is not supported in Gemini API.");return e}function Rs(t,e,n){const o={},s=i(e,["systemInstruction"]);n!==void 0&&s!=null&&r(n,["systemInstruction"],Gn(q(s)));const l=i(e,["temperature"]);l!=null&&r(o,["temperature"],l);const a=i(e,["topP"]);a!=null&&r(o,["topP"],a);const u=i(e,["topK"]);u!=null&&r(o,["topK"],u);const c=i(e,["candidateCount"]);c!=null&&r(o,["candidateCount"],c);const d=i(e,["maxOutputTokens"]);d!=null&&r(o,["maxOutputTokens"],d);const f=i(e,["stopSequences"]);f!=null&&r(o,["stopSequences"],f);const h=i(e,["responseLogprobs"]);h!=null&&r(o,["responseLogprobs"],h);const p=i(e,["logprobs"]);p!=null&&r(o,["logprobs"],p);const m=i(e,["presencePenalty"]);m!=null&&r(o,["presencePenalty"],m);const y=i(e,["frequencyPenalty"]);y!=null&&r(o,["frequencyPenalty"],y);const _=i(e,["seed"]);_!=null&&r(o,["seed"],_);const T=i(e,["responseMimeType"]);T!=null&&r(o,["responseMimeType"],T);const E=i(e,["responseSchema"]);E!=null&&r(o,["responseSchema"],We(E));const C=i(e,["responseJsonSchema"]);if(C!=null&&r(o,["responseJsonSchema"],C),i(e,["routingConfig"])!==void 0)throw new Error("routingConfig parameter is not supported in Gemini API.");if(i(e,["modelSelectionConfig"])!==void 0)throw new Error("modelSelectionConfig parameter is not supported in Gemini API.");const v=i(e,["safetySettings"]);if(n!==void 0&&v!=null){let D=v;Array.isArray(D)&&(D=D.map(G=>Ks(G))),r(n,["safetySettings"],D)}const I=i(e,["tools"]);if(n!==void 0&&I!=null){let D=ae(I);Array.isArray(D)&&(D=D.map(G=>Os(le(G)))),r(n,["tools"],D)}const A=i(e,["toolConfig"]);if(n!==void 0&&A!=null&&r(n,["toolConfig"],zs(A)),i(e,["labels"])!==void 0)throw new Error("labels parameter is not supported in Gemini API.");const P=i(e,["cachedContent"]);n!==void 0&&P!=null&&r(n,["cachedContent"],Z(t,P));const N=i(e,["responseModalities"]);N!=null&&r(o,["responseModalities"],N);const U=i(e,["mediaResolution"]);U!=null&&r(o,["mediaResolution"],U);const x=i(e,["speechConfig"]);if(x!=null&&r(o,["speechConfig"],Ye(x)),i(e,["audioTimestamp"])!==void 0)throw new Error("audioTimestamp parameter is not supported in Gemini API.");const R=i(e,["thinkingConfig"]);R!=null&&r(o,["thinkingConfig"],R);const b=i(e,["imageConfig"]);b!=null&&r(o,["imageConfig"],Fs(b));const k=i(e,["enableEnhancedCivicAnswers"]);return k!=null&&r(o,["enableEnhancedCivicAnswers"],k),o}function ks(t){const e={},n=i(t,["sdkHttpResponse"]);n!=null&&r(e,["sdkHttpResponse"],n);const o=i(t,["candidates"]);if(o!=null){let c=o;Array.isArray(c)&&(c=c.map(d=>hs(d))),r(e,["candidates"],c)}const s=i(t,["modelVersion"]);s!=null&&r(e,["modelVersion"],s);const l=i(t,["promptFeedback"]);l!=null&&r(e,["promptFeedback"],l);const a=i(t,["responseId"]);a!=null&&r(e,["responseId"],a);const u=i(t,["usageMetadata"]);return u!=null&&r(e,["usageMetadata"],u),e}function Ds(t,e){const n={},o=i(e,["name"]);return o!=null&&r(n,["_url","name"],ue(t,o)),n}function Us(t,e){const n={},o=i(e,["name"]);return o!=null&&r(n,["_url","name"],ue(t,o)),n}function Ls(t){const e={};if(i(t,["authConfig"])!==void 0)throw new Error("authConfig parameter is not supported in Gemini API.");const n=i(t,["enableWidget"]);return n!=null&&r(e,["enableWidget"],n),e}function bs(t){const e={};if(i(t,["excludeDomains"])!==void 0)throw new Error("excludeDomains parameter is not supported in Gemini API.");if(i(t,["blockingConfidence"])!==void 0)throw new Error("blockingConfidence parameter is not supported in Gemini API.");const n=i(t,["timeRangeFilter"]);return n!=null&&r(e,["timeRangeFilter"],n),e}function Fs(t){const e={},n=i(t,["aspectRatio"]);n!=null&&r(e,["aspectRatio"],n);const o=i(t,["imageSize"]);if(o!=null&&r(e,["imageSize"],o),i(t,["outputMimeType"])!==void 0)throw new Error("outputMimeType parameter is not supported in Gemini API.");if(i(t,["outputCompressionQuality"])!==void 0)throw new Error("outputCompressionQuality parameter is not supported in Gemini API.");return e}function Gs(t,e){const n={},o=i(e,["model"]);o!=null&&r(n,["request","model"],L(t,o));const s=i(e,["contents"]);if(s!=null){let u=W(s);Array.isArray(u)&&(u=u.map(c=>Gn(c))),r(n,["request","contents"],u)}const l=i(e,["metadata"]);l!=null&&r(n,["metadata"],l);const a=i(e,["config"]);return a!=null&&r(n,["request","generationConfig"],Rs(t,a,i(n,["request"],{}))),n}function Vs(t){const e={},n=i(t,["response"]);n!=null&&r(e,["response"],ks(n));const o=i(t,["error"]);return o!=null&&r(e,["error"],o),e}function qs(t,e){const n={},o=i(t,["pageSize"]);e!==void 0&&o!=null&&r(e,["_query","pageSize"],o);const s=i(t,["pageToken"]);if(e!==void 0&&s!=null&&r(e,["_query","pageToken"],s),i(t,["filter"])!==void 0)throw new Error("filter parameter is not supported in Gemini API.");return n}function Hs(t,e){const n={},o=i(t,["pageSize"]);e!==void 0&&o!=null&&r(e,["_query","pageSize"],o);const s=i(t,["pageToken"]);e!==void 0&&s!=null&&r(e,["_query","pageToken"],s);const l=i(t,["filter"]);return e!==void 0&&l!=null&&r(e,["_query","filter"],l),n}function Bs(t){const e={},n=i(t,["config"]);return n!=null&&qs(n,e),e}function Js(t){const e={},n=i(t,["config"]);return n!=null&&Hs(n,e),e}function $s(t){const e={},n=i(t,["sdkHttpResponse"]);n!=null&&r(e,["sdkHttpResponse"],n);const o=i(t,["nextPageToken"]);o!=null&&r(e,["nextPageToken"],o);const s=i(t,["operations"]);if(s!=null){let l=s;Array.isArray(l)&&(l=l.map(a=>Ee(a))),r(e,["batchJobs"],l)}return e}function Ws(t){const e={},n=i(t,["sdkHttpResponse"]);n!=null&&r(e,["sdkHttpResponse"],n);const o=i(t,["nextPageToken"]);o!=null&&r(e,["nextPageToken"],o);const s=i(t,["batchPredictionJobs"]);if(s!=null){let l=s;Array.isArray(l)&&(l=l.map(a=>ze(a))),r(e,["batchJobs"],l)}return e}function Ys(t){const e={},n=i(t,["mediaResolution"]);n!=null&&r(e,["mediaResolution"],n);const o=i(t,["codeExecutionResult"]);o!=null&&r(e,["codeExecutionResult"],o);const s=i(t,["executableCode"]);s!=null&&r(e,["executableCode"],s);const l=i(t,["fileData"]);l!=null&&r(e,["fileData"],Ns(l));const a=i(t,["functionCall"]);a!=null&&r(e,["functionCall"],Ms(a));const u=i(t,["functionResponse"]);u!=null&&r(e,["functionResponse"],u);const c=i(t,["inlineData"]);c!=null&&r(e,["inlineData"],cs(c));const d=i(t,["text"]);d!=null&&r(e,["text"],d);const f=i(t,["thought"]);f!=null&&r(e,["thought"],f);const h=i(t,["thoughtSignature"]);h!=null&&r(e,["thoughtSignature"],h);const p=i(t,["videoMetadata"]);return p!=null&&r(e,["videoMetadata"],p),e}function Ks(t){const e={},n=i(t,["category"]);if(n!=null&&r(e,["category"],n),i(t,["method"])!==void 0)throw new Error("method parameter is not supported in Gemini API.");const o=i(t,["threshold"]);return o!=null&&r(e,["threshold"],o),e}function zs(t){const e={},n=i(t,["functionCallingConfig"]);n!=null&&r(e,["functionCallingConfig"],Ps(n));const o=i(t,["retrievalConfig"]);return o!=null&&r(e,["retrievalConfig"],o),e}function Os(t){const e={},n=i(t,["functionDeclarations"]);if(n!=null){let f=n;Array.isArray(f)&&(f=f.map(h=>h)),r(e,["functionDeclarations"],f)}if(i(t,["retrieval"])!==void 0)throw new Error("retrieval parameter is not supported in Gemini API.");const o=i(t,["googleSearchRetrieval"]);o!=null&&r(e,["googleSearchRetrieval"],o);const s=i(t,["computerUse"]);s!=null&&r(e,["computerUse"],s);const l=i(t,["fileSearch"]);l!=null&&r(e,["fileSearch"],l);const a=i(t,["codeExecution"]);if(a!=null&&r(e,["codeExecution"],a),i(t,["enterpriseWebSearch"])!==void 0)throw new Error("enterpriseWebSearch parameter is not supported in Gemini API.");const u=i(t,["googleMaps"]);u!=null&&r(e,["googleMaps"],Ls(u));const c=i(t,["googleSearch"]);c!=null&&r(e,["googleSearch"],bs(c));const d=i(t,["urlContext"]);return d!=null&&r(e,["urlContext"],d),e}/**
150
+ * @license
151
+ * Copyright 2025 Google LLC
152
+ * SPDX-License-Identifier: Apache-2.0
153
+ */var j;(function(t){t.PAGED_ITEM_BATCH_JOBS="batchJobs",t.PAGED_ITEM_MODELS="models",t.PAGED_ITEM_TUNING_JOBS="tuningJobs",t.PAGED_ITEM_FILES="files",t.PAGED_ITEM_CACHED_CONTENTS="cachedContents",t.PAGED_ITEM_FILE_SEARCH_STORES="fileSearchStores",t.PAGED_ITEM_DOCUMENTS="documents"})(j||(j={}));class oe{constructor(e,n,o,s){this.pageInternal=[],this.paramsInternal={},this.requestInternal=n,this.init(e,o,s)}init(e,n,o){var s,l;this.nameInternal=e,this.pageInternal=n[this.nameInternal]||[],this.sdkHttpResponseInternal=n==null?void 0:n.sdkHttpResponse,this.idxInternal=0;let a={config:{}};!o||Object.keys(o).length===0?a={config:{}}:typeof o=="object"?a=Object.assign({},o):a=o,a.config&&(a.config.pageToken=n.nextPageToken),this.paramsInternal=a,this.pageInternalSize=(l=(s=a.config)===null||s===void 0?void 0:s.pageSize)!==null&&l!==void 0?l:this.pageInternal.length}initNextPage(e){this.init(this.nameInternal,e,this.paramsInternal)}get page(){return this.pageInternal}get name(){return this.nameInternal}get pageSize(){return this.pageInternalSize}get sdkHttpResponse(){return this.sdkHttpResponseInternal}get params(){return this.paramsInternal}get pageLength(){return this.pageInternal.length}getItem(e){return this.pageInternal[e]}[Symbol.asyncIterator](){return{next:async()=>{if(this.idxInternal>=this.pageLength)if(this.hasNextPage())await this.nextPage();else return{value:void 0,done:!0};const e=this.getItem(this.idxInternal);return this.idxInternal+=1,{value:e,done:!1}},return:async()=>({value:void 0,done:!0})}}async nextPage(){if(!this.hasNextPage())throw new Error("No more pages to fetch.");const e=await this.requestInternal(this.params);return this.initNextPage(e),this.page}hasNextPage(){var e;return((e=this.params.config)===null||e===void 0?void 0:e.pageToken)!==void 0}}/**
154
+ * @license
155
+ * Copyright 2025 Google LLC
156
+ * SPDX-License-Identifier: Apache-2.0
157
+ */class Xs extends Q{constructor(e){super(),this.apiClient=e,this.list=async(n={})=>new oe(j.PAGED_ITEM_BATCH_JOBS,o=>this.listInternal(o),await this.listInternal(n),n),this.create=async n=>(this.apiClient.isVertexAI()&&(n.config=this.formatDestination(n.src,n.config)),this.createInternal(n)),this.createEmbeddings=async n=>{if(console.warn("batches.createEmbeddings() is experimental and may change without notice."),this.apiClient.isVertexAI())throw new Error("Vertex AI does not support batches.createEmbeddings.");return this.createEmbeddingsInternal(n)}}createInlinedGenerateContentRequest(e){const n=Vn(this.apiClient,e),o=n._url,s=S("{model}:batchGenerateContent",o),u=n.batch.inputConfig.requests,c=u.requests,d=[];for(const f of c){const h=Object.assign({},f);if(h.systemInstruction){const p=h.systemInstruction;delete h.systemInstruction;const m=h.request;m.systemInstruction=p,h.request=m}d.push(h)}return u.requests=d,delete n.config,delete n._url,delete n._query,{path:s,body:n}}getGcsUri(e){if(typeof e=="string")return e.startsWith("gs://")?e:void 0;if(!Array.isArray(e)&&e.gcsUri&&e.gcsUri.length>0)return e.gcsUri[0]}getBigqueryUri(e){if(typeof e=="string")return e.startsWith("bq://")?e:void 0;if(!Array.isArray(e))return e.bigqueryUri}formatDestination(e,n){const o=n?Object.assign({},n):{},s=Date.now().toString();if(o.displayName||(o.displayName=`genaiBatchJob_${s}`),o.dest===void 0){const l=this.getGcsUri(e),a=this.getBigqueryUri(e);if(l)l.endsWith(".jsonl")?o.dest=`${l.slice(0,-6)}/dest`:o.dest=`${l}_dest_${s}`;else if(a)o.dest=`${a}_dest_${s}`;else throw new Error("Unsupported source for Vertex AI: No GCS or BigQuery URI found.")}return o}async createInternal(e){var n,o,s,l;let a,u="",c={};if(this.apiClient.isVertexAI()){const d=Ts(this.apiClient,e);return u=S("batchPredictionJobs",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(f=>f.json()),a.then(f=>ze(f))}else{const d=Vn(this.apiClient,e);return u=S("{model}:batchGenerateContent",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(s=e.config)===null||s===void 0?void 0:s.httpOptions,abortSignal:(l=e.config)===null||l===void 0?void 0:l.abortSignal}).then(f=>f.json()),a.then(f=>Ee(f))}}async createEmbeddingsInternal(e){var n,o;let s,l="",a={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const u=Es(this.apiClient,e);return l=S("{model}:asyncBatchEmbedContent",u._url),a=u._query,delete u._url,delete u._query,s=this.apiClient.request({path:l,queryParams:a,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(c=>c.json()),s.then(c=>Ee(c))}}async get(e){var n,o,s,l;let a,u="",c={};if(this.apiClient.isVertexAI()){const d=Us(this.apiClient,e);return u=S("batchPredictionJobs/{name}",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(f=>f.json()),a.then(f=>ze(f))}else{const d=Ds(this.apiClient,e);return u=S("batches/{name}",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"GET",httpOptions:(s=e.config)===null||s===void 0?void 0:s.httpOptions,abortSignal:(l=e.config)===null||l===void 0?void 0:l.abortSignal}).then(f=>f.json()),a.then(f=>Ee(f))}}async cancel(e){var n,o,s,l;let a="",u={};if(this.apiClient.isVertexAI()){const c=ps(this.apiClient,e);a=S("batchPredictionJobs/{name}:cancel",c._url),u=c._query,delete c._url,delete c._query,await this.apiClient.request({path:a,queryParams:u,body:JSON.stringify(c),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal})}else{const c=fs(this.apiClient,e);a=S("batches/{name}:cancel",c._url),u=c._query,delete c._url,delete c._query,await this.apiClient.request({path:a,queryParams:u,body:JSON.stringify(c),httpMethod:"POST",httpOptions:(s=e.config)===null||s===void 0?void 0:s.httpOptions,abortSignal:(l=e.config)===null||l===void 0?void 0:l.abortSignal})}}async listInternal(e){var n,o,s,l;let a,u="",c={};if(this.apiClient.isVertexAI()){const d=Js(e);return u=S("batchPredictionJobs",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(f=>f.json().then(h=>{const p=h;return p.sdkHttpResponse={headers:f.headers},p})),a.then(f=>{const h=Ws(f),p=new vn;return Object.assign(p,h),p})}else{const d=Bs(e);return u=S("batches",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"GET",httpOptions:(s=e.config)===null||s===void 0?void 0:s.httpOptions,abortSignal:(l=e.config)===null||l===void 0?void 0:l.abortSignal}).then(f=>f.json().then(h=>{const p=h;return p.sdkHttpResponse={headers:f.headers},p})),a.then(f=>{const h=$s(f),p=new vn;return Object.assign(p,h),p})}}async delete(e){var n,o,s,l;let a,u="",c={};if(this.apiClient.isVertexAI()){const d=vs(this.apiClient,e);return u=S("batchPredictionJobs/{name}",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"DELETE",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(f=>f.json().then(h=>{const p=h;return p.sdkHttpResponse={headers:f.headers},p})),a.then(f=>Ss(f))}else{const d=Cs(this.apiClient,e);return u=S("batches/{name}",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"DELETE",httpOptions:(s=e.config)===null||s===void 0?void 0:s.httpOptions,abortSignal:(l=e.config)===null||l===void 0?void 0:l.abortSignal}).then(f=>f.json().then(h=>{const p=h;return p.sdkHttpResponse={headers:f.headers},p})),a.then(f=>Is(f))}}}/**
158
+ * @license
159
+ * Copyright 2025 Google LLC
160
+ * SPDX-License-Identifier: Apache-2.0
161
+ */function Qs(t){const e={},n=i(t,["data"]);if(n!=null&&r(e,["data"],n),i(t,["displayName"])!==void 0)throw new Error("displayName parameter is not supported in Gemini API.");const o=i(t,["mimeType"]);return o!=null&&r(e,["mimeType"],o),e}function qn(t){const e={},n=i(t,["parts"]);if(n!=null){let s=n;Array.isArray(s)&&(s=s.map(l=>Er(l))),r(e,["parts"],s)}const o=i(t,["role"]);return o!=null&&r(e,["role"],o),e}function Zs(t,e){const n={},o=i(t,["ttl"]);e!==void 0&&o!=null&&r(e,["ttl"],o);const s=i(t,["expireTime"]);e!==void 0&&s!=null&&r(e,["expireTime"],s);const l=i(t,["displayName"]);e!==void 0&&l!=null&&r(e,["displayName"],l);const a=i(t,["contents"]);if(e!==void 0&&a!=null){let f=W(a);Array.isArray(f)&&(f=f.map(h=>qn(h))),r(e,["contents"],f)}const u=i(t,["systemInstruction"]);e!==void 0&&u!=null&&r(e,["systemInstruction"],qn(q(u)));const c=i(t,["tools"]);if(e!==void 0&&c!=null){let f=c;Array.isArray(f)&&(f=f.map(h=>vr(h))),r(e,["tools"],f)}const d=i(t,["toolConfig"]);if(e!==void 0&&d!=null&&r(e,["toolConfig"],Cr(d)),i(t,["kmsKeyName"])!==void 0)throw new Error("kmsKeyName parameter is not supported in Gemini API.");return n}function js(t,e){const n={},o=i(t,["ttl"]);e!==void 0&&o!=null&&r(e,["ttl"],o);const s=i(t,["expireTime"]);e!==void 0&&s!=null&&r(e,["expireTime"],s);const l=i(t,["displayName"]);e!==void 0&&l!=null&&r(e,["displayName"],l);const a=i(t,["contents"]);if(e!==void 0&&a!=null){let h=W(a);Array.isArray(h)&&(h=h.map(p=>p)),r(e,["contents"],h)}const u=i(t,["systemInstruction"]);e!==void 0&&u!=null&&r(e,["systemInstruction"],q(u));const c=i(t,["tools"]);if(e!==void 0&&c!=null){let h=c;Array.isArray(h)&&(h=h.map(p=>Ir(p))),r(e,["tools"],h)}const d=i(t,["toolConfig"]);e!==void 0&&d!=null&&r(e,["toolConfig"],d);const f=i(t,["kmsKeyName"]);return e!==void 0&&f!=null&&r(e,["encryption_spec","kmsKeyName"],f),n}function er(t,e){const n={},o=i(e,["model"]);o!=null&&r(n,["model"],In(t,o));const s=i(e,["config"]);return s!=null&&Zs(s,n),n}function tr(t,e){const n={},o=i(e,["model"]);o!=null&&r(n,["model"],In(t,o));const s=i(e,["config"]);return s!=null&&js(s,n),n}function nr(t,e){const n={},o=i(e,["name"]);return o!=null&&r(n,["_url","name"],Z(t,o)),n}function or(t,e){const n={},o=i(e,["name"]);return o!=null&&r(n,["_url","name"],Z(t,o)),n}function ir(t){const e={},n=i(t,["sdkHttpResponse"]);return n!=null&&r(e,["sdkHttpResponse"],n),e}function sr(t){const e={},n=i(t,["sdkHttpResponse"]);return n!=null&&r(e,["sdkHttpResponse"],n),e}function rr(t){const e={};if(i(t,["displayName"])!==void 0)throw new Error("displayName parameter is not supported in Gemini API.");const n=i(t,["fileUri"]);n!=null&&r(e,["fileUri"],n);const o=i(t,["mimeType"]);return o!=null&&r(e,["mimeType"],o),e}function lr(t){const e={},n=i(t,["id"]);n!=null&&r(e,["id"],n);const o=i(t,["args"]);o!=null&&r(e,["args"],o);const s=i(t,["name"]);if(s!=null&&r(e,["name"],s),i(t,["partialArgs"])!==void 0)throw new Error("partialArgs parameter is not supported in Gemini API.");if(i(t,["willContinue"])!==void 0)throw new Error("willContinue parameter is not supported in Gemini API.");return e}function ar(t){const e={},n=i(t,["mode"]);n!=null&&r(e,["mode"],n);const o=i(t,["allowedFunctionNames"]);if(o!=null&&r(e,["allowedFunctionNames"],o),i(t,["streamFunctionCallArguments"])!==void 0)throw new Error("streamFunctionCallArguments parameter is not supported in Gemini API.");return e}function ur(t){const e={};if(i(t,["behavior"])!==void 0)throw new Error("behavior parameter is not supported in Vertex AI.");const n=i(t,["description"]);n!=null&&r(e,["description"],n);const o=i(t,["name"]);o!=null&&r(e,["name"],o);const s=i(t,["parameters"]);s!=null&&r(e,["parameters"],s);const l=i(t,["parametersJsonSchema"]);l!=null&&r(e,["parametersJsonSchema"],l);const a=i(t,["response"]);a!=null&&r(e,["response"],a);const u=i(t,["responseJsonSchema"]);return u!=null&&r(e,["responseJsonSchema"],u),e}function dr(t,e){const n={},o=i(e,["name"]);return o!=null&&r(n,["_url","name"],Z(t,o)),n}function cr(t,e){const n={},o=i(e,["name"]);return o!=null&&r(n,["_url","name"],Z(t,o)),n}function fr(t){const e={};if(i(t,["authConfig"])!==void 0)throw new Error("authConfig parameter is not supported in Gemini API.");const n=i(t,["enableWidget"]);return n!=null&&r(e,["enableWidget"],n),e}function pr(t){const e={};if(i(t,["excludeDomains"])!==void 0)throw new Error("excludeDomains parameter is not supported in Gemini API.");if(i(t,["blockingConfidence"])!==void 0)throw new Error("blockingConfidence parameter is not supported in Gemini API.");const n=i(t,["timeRangeFilter"]);return n!=null&&r(e,["timeRangeFilter"],n),e}function hr(t,e){const n={},o=i(t,["pageSize"]);e!==void 0&&o!=null&&r(e,["_query","pageSize"],o);const s=i(t,["pageToken"]);return e!==void 0&&s!=null&&r(e,["_query","pageToken"],s),n}function mr(t,e){const n={},o=i(t,["pageSize"]);e!==void 0&&o!=null&&r(e,["_query","pageSize"],o);const s=i(t,["pageToken"]);return e!==void 0&&s!=null&&r(e,["_query","pageToken"],s),n}function gr(t){const e={},n=i(t,["config"]);return n!=null&&hr(n,e),e}function yr(t){const e={},n=i(t,["config"]);return n!=null&&mr(n,e),e}function Tr(t){const e={},n=i(t,["sdkHttpResponse"]);n!=null&&r(e,["sdkHttpResponse"],n);const o=i(t,["nextPageToken"]);o!=null&&r(e,["nextPageToken"],o);const s=i(t,["cachedContents"]);if(s!=null){let l=s;Array.isArray(l)&&(l=l.map(a=>a)),r(e,["cachedContents"],l)}return e}function _r(t){const e={},n=i(t,["sdkHttpResponse"]);n!=null&&r(e,["sdkHttpResponse"],n);const o=i(t,["nextPageToken"]);o!=null&&r(e,["nextPageToken"],o);const s=i(t,["cachedContents"]);if(s!=null){let l=s;Array.isArray(l)&&(l=l.map(a=>a)),r(e,["cachedContents"],l)}return e}function Er(t){const e={},n=i(t,["mediaResolution"]);n!=null&&r(e,["mediaResolution"],n);const o=i(t,["codeExecutionResult"]);o!=null&&r(e,["codeExecutionResult"],o);const s=i(t,["executableCode"]);s!=null&&r(e,["executableCode"],s);const l=i(t,["fileData"]);l!=null&&r(e,["fileData"],rr(l));const a=i(t,["functionCall"]);a!=null&&r(e,["functionCall"],lr(a));const u=i(t,["functionResponse"]);u!=null&&r(e,["functionResponse"],u);const c=i(t,["inlineData"]);c!=null&&r(e,["inlineData"],Qs(c));const d=i(t,["text"]);d!=null&&r(e,["text"],d);const f=i(t,["thought"]);f!=null&&r(e,["thought"],f);const h=i(t,["thoughtSignature"]);h!=null&&r(e,["thoughtSignature"],h);const p=i(t,["videoMetadata"]);return p!=null&&r(e,["videoMetadata"],p),e}function Cr(t){const e={},n=i(t,["functionCallingConfig"]);n!=null&&r(e,["functionCallingConfig"],ar(n));const o=i(t,["retrievalConfig"]);return o!=null&&r(e,["retrievalConfig"],o),e}function vr(t){const e={},n=i(t,["functionDeclarations"]);if(n!=null){let f=n;Array.isArray(f)&&(f=f.map(h=>h)),r(e,["functionDeclarations"],f)}if(i(t,["retrieval"])!==void 0)throw new Error("retrieval parameter is not supported in Gemini API.");const o=i(t,["googleSearchRetrieval"]);o!=null&&r(e,["googleSearchRetrieval"],o);const s=i(t,["computerUse"]);s!=null&&r(e,["computerUse"],s);const l=i(t,["fileSearch"]);l!=null&&r(e,["fileSearch"],l);const a=i(t,["codeExecution"]);if(a!=null&&r(e,["codeExecution"],a),i(t,["enterpriseWebSearch"])!==void 0)throw new Error("enterpriseWebSearch parameter is not supported in Gemini API.");const u=i(t,["googleMaps"]);u!=null&&r(e,["googleMaps"],fr(u));const c=i(t,["googleSearch"]);c!=null&&r(e,["googleSearch"],pr(c));const d=i(t,["urlContext"]);return d!=null&&r(e,["urlContext"],d),e}function Ir(t){const e={},n=i(t,["functionDeclarations"]);if(n!=null){let h=n;Array.isArray(h)&&(h=h.map(p=>ur(p))),r(e,["functionDeclarations"],h)}const o=i(t,["retrieval"]);o!=null&&r(e,["retrieval"],o);const s=i(t,["googleSearchRetrieval"]);s!=null&&r(e,["googleSearchRetrieval"],s);const l=i(t,["computerUse"]);if(l!=null&&r(e,["computerUse"],l),i(t,["fileSearch"])!==void 0)throw new Error("fileSearch parameter is not supported in Vertex AI.");const a=i(t,["codeExecution"]);a!=null&&r(e,["codeExecution"],a);const u=i(t,["enterpriseWebSearch"]);u!=null&&r(e,["enterpriseWebSearch"],u);const c=i(t,["googleMaps"]);c!=null&&r(e,["googleMaps"],c);const d=i(t,["googleSearch"]);d!=null&&r(e,["googleSearch"],d);const f=i(t,["urlContext"]);return f!=null&&r(e,["urlContext"],f),e}function Sr(t,e){const n={},o=i(t,["ttl"]);e!==void 0&&o!=null&&r(e,["ttl"],o);const s=i(t,["expireTime"]);return e!==void 0&&s!=null&&r(e,["expireTime"],s),n}function xr(t,e){const n={},o=i(t,["ttl"]);e!==void 0&&o!=null&&r(e,["ttl"],o);const s=i(t,["expireTime"]);return e!==void 0&&s!=null&&r(e,["expireTime"],s),n}function Ar(t,e){const n={},o=i(e,["name"]);o!=null&&r(n,["_url","name"],Z(t,o));const s=i(e,["config"]);return s!=null&&Sr(s,n),n}function wr(t,e){const n={},o=i(e,["name"]);o!=null&&r(n,["_url","name"],Z(t,o));const s=i(e,["config"]);return s!=null&&xr(s,n),n}/**
162
+ * @license
163
+ * Copyright 2025 Google LLC
164
+ * SPDX-License-Identifier: Apache-2.0
165
+ */class Nr extends Q{constructor(e){super(),this.apiClient=e,this.list=async(n={})=>new oe(j.PAGED_ITEM_CACHED_CONTENTS,o=>this.listInternal(o),await this.listInternal(n),n)}async create(e){var n,o,s,l;let a,u="",c={};if(this.apiClient.isVertexAI()){const d=tr(this.apiClient,e);return u=S("cachedContents",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(f=>f.json()),a.then(f=>f)}else{const d=er(this.apiClient,e);return u=S("cachedContents",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(s=e.config)===null||s===void 0?void 0:s.httpOptions,abortSignal:(l=e.config)===null||l===void 0?void 0:l.abortSignal}).then(f=>f.json()),a.then(f=>f)}}async get(e){var n,o,s,l;let a,u="",c={};if(this.apiClient.isVertexAI()){const d=cr(this.apiClient,e);return u=S("{name}",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(f=>f.json()),a.then(f=>f)}else{const d=dr(this.apiClient,e);return u=S("{name}",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"GET",httpOptions:(s=e.config)===null||s===void 0?void 0:s.httpOptions,abortSignal:(l=e.config)===null||l===void 0?void 0:l.abortSignal}).then(f=>f.json()),a.then(f=>f)}}async delete(e){var n,o,s,l;let a,u="",c={};if(this.apiClient.isVertexAI()){const d=or(this.apiClient,e);return u=S("{name}",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"DELETE",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(f=>f.json().then(h=>{const p=h;return p.sdkHttpResponse={headers:f.headers},p})),a.then(f=>{const h=sr(f),p=new En;return Object.assign(p,h),p})}else{const d=nr(this.apiClient,e);return u=S("{name}",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"DELETE",httpOptions:(s=e.config)===null||s===void 0?void 0:s.httpOptions,abortSignal:(l=e.config)===null||l===void 0?void 0:l.abortSignal}).then(f=>f.json().then(h=>{const p=h;return p.sdkHttpResponse={headers:f.headers},p})),a.then(f=>{const h=ir(f),p=new En;return Object.assign(p,h),p})}}async update(e){var n,o,s,l;let a,u="",c={};if(this.apiClient.isVertexAI()){const d=wr(this.apiClient,e);return u=S("{name}",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"PATCH",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(f=>f.json()),a.then(f=>f)}else{const d=Ar(this.apiClient,e);return u=S("{name}",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"PATCH",httpOptions:(s=e.config)===null||s===void 0?void 0:s.httpOptions,abortSignal:(l=e.config)===null||l===void 0?void 0:l.abortSignal}).then(f=>f.json()),a.then(f=>f)}}async listInternal(e){var n,o,s,l;let a,u="",c={};if(this.apiClient.isVertexAI()){const d=yr(e);return u=S("cachedContents",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(f=>f.json().then(h=>{const p=h;return p.sdkHttpResponse={headers:f.headers},p})),a.then(f=>{const h=_r(f),p=new Cn;return Object.assign(p,h),p})}else{const d=gr(e);return u=S("cachedContents",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"GET",httpOptions:(s=e.config)===null||s===void 0?void 0:s.httpOptions,abortSignal:(l=e.config)===null||l===void 0?void 0:l.abortSignal}).then(f=>f.json().then(h=>{const p=h;return p.sdkHttpResponse={headers:f.headers},p})),a.then(f=>{const h=Tr(f),p=new Cn;return Object.assign(p,h),p})}}}function Ce(t,e){var n={};for(var o in t)Object.prototype.hasOwnProperty.call(t,o)&&e.indexOf(o)<0&&(n[o]=t[o]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,o=Object.getOwnPropertySymbols(t);s<o.length;s++)e.indexOf(o[s])<0&&Object.prototype.propertyIsEnumerable.call(t,o[s])&&(n[o[s]]=t[o[s]]);return n}function Hn(t){var e=typeof Symbol=="function"&&Symbol.iterator,n=e&&t[e],o=0;if(n)return n.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&o>=t.length&&(t=void 0),{value:t&&t[o++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function M(t){return this instanceof M?(this.v=t,this):new M(t)}function K(t,e,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var o=n.apply(t,e||[]),s,l=[];return s=Object.create((typeof AsyncIterator=="function"?AsyncIterator:Object).prototype),u("next"),u("throw"),u("return",a),s[Symbol.asyncIterator]=function(){return this},s;function a(m){return function(y){return Promise.resolve(y).then(m,h)}}function u(m,y){o[m]&&(s[m]=function(_){return new Promise(function(T,E){l.push([m,_,T,E])>1||c(m,_)})},y&&(s[m]=y(s[m])))}function c(m,y){try{d(o[m](y))}catch(_){p(l[0][3],_)}}function d(m){m.value instanceof M?Promise.resolve(m.value.v).then(f,h):p(l[0][2],m)}function f(m){c("next",m)}function h(m){c("throw",m)}function p(m,y){m(y),l.shift(),l.length&&c(l[0][0],l[0][1])}}function z(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],n;return e?e.call(t):(t=typeof Hn=="function"?Hn(t):t[Symbol.iterator](),n={},o("next"),o("throw"),o("return"),n[Symbol.asyncIterator]=function(){return this},n);function o(l){n[l]=t[l]&&function(a){return new Promise(function(u,c){a=t[l](a),s(u,c,a.done,a.value)})}}function s(l,a,u,c){Promise.resolve(c).then(function(d){l({value:d,done:u})},a)}}typeof SuppressedError=="function"&&SuppressedError;/**
166
+ * @license
167
+ * Copyright 2025 Google LLC
168
+ * SPDX-License-Identifier: Apache-2.0
169
+ */function Mr(t){var e;if(t.candidates==null||t.candidates.length===0)return!1;const n=(e=t.candidates[0])===null||e===void 0?void 0:e.content;return n===void 0?!1:Bn(n)}function Bn(t){if(t.parts===void 0||t.parts.length===0)return!1;for(const e of t.parts)if(e===void 0||Object.keys(e).length===0)return!1;return!0}function Pr(t){if(t.length!==0){for(const e of t)if(e.role!=="user"&&e.role!=="model")throw new Error(`Role must be user or model, but got ${e.role}.`)}}function Jn(t){if(t===void 0||t.length===0)return[];const e=[],n=t.length;let o=0;for(;o<n;)if(t[o].role==="user")e.push(t[o]),o++;else{const s=[];let l=!0;for(;o<n&&t[o].role==="model";)s.push(t[o]),l&&!Bn(t[o])&&(l=!1),o++;l?e.push(...s):e.pop()}return e}class Rr{constructor(e,n){this.modelsModule=e,this.apiClient=n}create(e){return new kr(this.apiClient,this.modelsModule,e.model,e.config,structuredClone(e.history))}}class kr{constructor(e,n,o,s={},l=[]){this.apiClient=e,this.modelsModule=n,this.model=o,this.config=s,this.history=l,this.sendPromise=Promise.resolve(),Pr(l)}async sendMessage(e){var n;await this.sendPromise;const o=q(e.message),s=this.modelsModule.generateContent({model:this.model,contents:this.getHistory(!0).concat(o),config:(n=e.config)!==null&&n!==void 0?n:this.config});return this.sendPromise=(async()=>{var l,a,u;const c=await s,d=(a=(l=c.candidates)===null||l===void 0?void 0:l[0])===null||a===void 0?void 0:a.content,f=c.automaticFunctionCallingHistory,h=this.getHistory(!0).length;let p=[];f!=null&&(p=(u=f.slice(h))!==null&&u!==void 0?u:[]);const m=d?[d]:[];this.recordHistory(o,m,p)})(),await this.sendPromise.catch(()=>{this.sendPromise=Promise.resolve()}),s}async sendMessageStream(e){var n;await this.sendPromise;const o=q(e.message),s=this.modelsModule.generateContentStream({model:this.model,contents:this.getHistory(!0).concat(o),config:(n=e.config)!==null&&n!==void 0?n:this.config});this.sendPromise=s.then(()=>{}).catch(()=>{});const l=await s;return this.processStreamResponse(l,o)}getHistory(e=!1){const n=e?Jn(this.history):this.history;return structuredClone(n)}processStreamResponse(e,n){return K(this,arguments,function*(){var s,l,a,u,c,d;const f=[];try{for(var h=!0,p=z(e),m;m=yield M(p.next()),s=m.done,!s;h=!0){u=m.value,h=!1;const y=u;if(Mr(y)){const _=(d=(c=y.candidates)===null||c===void 0?void 0:c[0])===null||d===void 0?void 0:d.content;_!==void 0&&f.push(_)}yield yield M(y)}}catch(y){l={error:y}}finally{try{!h&&!s&&(a=p.return)&&(yield M(a.call(p)))}finally{if(l)throw l.error}}this.recordHistory(n,f)})}recordHistory(e,n,o){let s=[];n.length>0&&n.every(l=>l.role!==void 0)?s=n:s.push({role:"model",parts:[]}),o&&o.length>0?this.history.push(...Jn(o)):this.history.push(e),this.history.push(...s)}}/**
170
+ * @license
171
+ * Copyright 2025 Google LLC
172
+ * SPDX-License-Identifier: Apache-2.0
173
+ */class ve extends Error{constructor(e){super(e.message),this.name="ApiError",this.status=e.status,Object.setPrototypeOf(this,ve.prototype)}}/**
174
+ * @license
175
+ * Copyright 2025 Google LLC
176
+ * SPDX-License-Identifier: Apache-2.0
177
+ */function Dr(t){const e={},n=i(t,["file"]);return n!=null&&r(e,["file"],n),e}function Ur(t){const e={},n=i(t,["sdkHttpResponse"]);return n!=null&&r(e,["sdkHttpResponse"],n),e}function Lr(t){const e={},n=i(t,["name"]);return n!=null&&r(e,["_url","file"],kn(n)),e}function br(t){const e={},n=i(t,["sdkHttpResponse"]);return n!=null&&r(e,["sdkHttpResponse"],n),e}function Fr(t){const e={},n=i(t,["name"]);return n!=null&&r(e,["_url","file"],kn(n)),e}function Gr(t,e){const n={},o=i(t,["pageSize"]);e!==void 0&&o!=null&&r(e,["_query","pageSize"],o);const s=i(t,["pageToken"]);return e!==void 0&&s!=null&&r(e,["_query","pageToken"],s),n}function Vr(t){const e={},n=i(t,["config"]);return n!=null&&Gr(n,e),e}function qr(t){const e={},n=i(t,["sdkHttpResponse"]);n!=null&&r(e,["sdkHttpResponse"],n);const o=i(t,["nextPageToken"]);o!=null&&r(e,["nextPageToken"],o);const s=i(t,["files"]);if(s!=null){let l=s;Array.isArray(l)&&(l=l.map(a=>a)),r(e,["files"],l)}return e}/**
178
+ * @license
179
+ * Copyright 2025 Google LLC
180
+ * SPDX-License-Identifier: Apache-2.0
181
+ */class Hr extends Q{constructor(e){super(),this.apiClient=e,this.list=async(n={})=>new oe(j.PAGED_ITEM_FILES,o=>this.listInternal(o),await this.listInternal(n),n)}async upload(e){if(this.apiClient.isVertexAI())throw new Error("Vertex AI does not support uploading files. You can share files through a GCS bucket.");return this.apiClient.uploadFile(e.file,e.config).then(n=>n)}async download(e){await this.apiClient.downloadFile(e)}async listInternal(e){var n,o;let s,l="",a={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const u=Vr(e);return l=S("files",u._url),a=u._query,delete u._url,delete u._query,s=this.apiClient.request({path:l,queryParams:a,body:JSON.stringify(u),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(c=>c.json().then(d=>{const f=d;return f.sdkHttpResponse={headers:c.headers},f})),s.then(c=>{const d=qr(c),f=new Wi;return Object.assign(f,d),f})}}async createInternal(e){var n,o;let s,l="",a={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const u=Dr(e);return l=S("upload/v1beta/files",u._url),a=u._query,delete u._url,delete u._query,s=this.apiClient.request({path:l,queryParams:a,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(c=>c.json()),s.then(c=>{const d=Ur(c),f=new Yi;return Object.assign(f,d),f})}}async get(e){var n,o;let s,l="",a={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const u=Fr(e);return l=S("files/{file}",u._url),a=u._query,delete u._url,delete u._query,s=this.apiClient.request({path:l,queryParams:a,body:JSON.stringify(u),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(c=>c.json()),s.then(c=>c)}}async delete(e){var n,o;let s,l="",a={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const u=Lr(e);return l=S("files/{file}",u._url),a=u._query,delete u._url,delete u._query,s=this.apiClient.request({path:l,queryParams:a,body:JSON.stringify(u),httpMethod:"DELETE",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(c=>c.json().then(d=>{const f=d;return f.sdkHttpResponse={headers:c.headers},f})),s.then(c=>{const d=br(c),f=new Ki;return Object.assign(f,d),f})}}}/**
182
+ * @license
183
+ * Copyright 2025 Google LLC
184
+ * SPDX-License-Identifier: Apache-2.0
185
+ */function Ie(t){const e={},n=i(t,["data"]);if(n!=null&&r(e,["data"],n),i(t,["displayName"])!==void 0)throw new Error("displayName parameter is not supported in Gemini API.");const o=i(t,["mimeType"]);return o!=null&&r(e,["mimeType"],o),e}function Br(t){const e={},n=i(t,["parts"]);if(n!=null){let s=n;Array.isArray(s)&&(s=s.map(l=>il(l))),r(e,["parts"],s)}const o=i(t,["role"]);return o!=null&&r(e,["role"],o),e}function Jr(t){const e={};if(i(t,["displayName"])!==void 0)throw new Error("displayName parameter is not supported in Gemini API.");const n=i(t,["fileUri"]);n!=null&&r(e,["fileUri"],n);const o=i(t,["mimeType"]);return o!=null&&r(e,["mimeType"],o),e}function $r(t){const e={},n=i(t,["id"]);n!=null&&r(e,["id"],n);const o=i(t,["args"]);o!=null&&r(e,["args"],o);const s=i(t,["name"]);if(s!=null&&r(e,["name"],s),i(t,["partialArgs"])!==void 0)throw new Error("partialArgs parameter is not supported in Gemini API.");if(i(t,["willContinue"])!==void 0)throw new Error("willContinue parameter is not supported in Gemini API.");return e}function Wr(t){const e={};if(i(t,["behavior"])!==void 0)throw new Error("behavior parameter is not supported in Vertex AI.");const n=i(t,["description"]);n!=null&&r(e,["description"],n);const o=i(t,["name"]);o!=null&&r(e,["name"],o);const s=i(t,["parameters"]);s!=null&&r(e,["parameters"],s);const l=i(t,["parametersJsonSchema"]);l!=null&&r(e,["parametersJsonSchema"],l);const a=i(t,["response"]);a!=null&&r(e,["response"],a);const u=i(t,["responseJsonSchema"]);return u!=null&&r(e,["responseJsonSchema"],u),e}function Yr(t){const e={},n=i(t,["modelSelectionConfig"]);n!=null&&r(e,["modelConfig"],n);const o=i(t,["responseJsonSchema"]);o!=null&&r(e,["responseJsonSchema"],o);const s=i(t,["audioTimestamp"]);s!=null&&r(e,["audioTimestamp"],s);const l=i(t,["candidateCount"]);l!=null&&r(e,["candidateCount"],l);const a=i(t,["enableAffectiveDialog"]);a!=null&&r(e,["enableAffectiveDialog"],a);const u=i(t,["frequencyPenalty"]);u!=null&&r(e,["frequencyPenalty"],u);const c=i(t,["logprobs"]);c!=null&&r(e,["logprobs"],c);const d=i(t,["maxOutputTokens"]);d!=null&&r(e,["maxOutputTokens"],d);const f=i(t,["mediaResolution"]);f!=null&&r(e,["mediaResolution"],f);const h=i(t,["presencePenalty"]);h!=null&&r(e,["presencePenalty"],h);const p=i(t,["responseLogprobs"]);p!=null&&r(e,["responseLogprobs"],p);const m=i(t,["responseMimeType"]);m!=null&&r(e,["responseMimeType"],m);const y=i(t,["responseModalities"]);y!=null&&r(e,["responseModalities"],y);const _=i(t,["responseSchema"]);_!=null&&r(e,["responseSchema"],_);const T=i(t,["routingConfig"]);T!=null&&r(e,["routingConfig"],T);const E=i(t,["seed"]);E!=null&&r(e,["seed"],E);const C=i(t,["speechConfig"]);C!=null&&r(e,["speechConfig"],C);const v=i(t,["stopSequences"]);v!=null&&r(e,["stopSequences"],v);const I=i(t,["temperature"]);I!=null&&r(e,["temperature"],I);const A=i(t,["thinkingConfig"]);A!=null&&r(e,["thinkingConfig"],A);const P=i(t,["topK"]);P!=null&&r(e,["topK"],P);const N=i(t,["topP"]);if(N!=null&&r(e,["topP"],N),i(t,["enableEnhancedCivicAnswers"])!==void 0)throw new Error("enableEnhancedCivicAnswers parameter is not supported in Vertex AI.");return e}function Kr(t){const e={};if(i(t,["authConfig"])!==void 0)throw new Error("authConfig parameter is not supported in Gemini API.");const n=i(t,["enableWidget"]);return n!=null&&r(e,["enableWidget"],n),e}function zr(t){const e={};if(i(t,["excludeDomains"])!==void 0)throw new Error("excludeDomains parameter is not supported in Gemini API.");if(i(t,["blockingConfidence"])!==void 0)throw new Error("blockingConfidence parameter is not supported in Gemini API.");const n=i(t,["timeRangeFilter"]);return n!=null&&r(e,["timeRangeFilter"],n),e}function Or(t,e){const n={},o=i(t,["generationConfig"]);e!==void 0&&o!=null&&r(e,["setup","generationConfig"],o);const s=i(t,["responseModalities"]);e!==void 0&&s!=null&&r(e,["setup","generationConfig","responseModalities"],s);const l=i(t,["temperature"]);e!==void 0&&l!=null&&r(e,["setup","generationConfig","temperature"],l);const a=i(t,["topP"]);e!==void 0&&a!=null&&r(e,["setup","generationConfig","topP"],a);const u=i(t,["topK"]);e!==void 0&&u!=null&&r(e,["setup","generationConfig","topK"],u);const c=i(t,["maxOutputTokens"]);e!==void 0&&c!=null&&r(e,["setup","generationConfig","maxOutputTokens"],c);const d=i(t,["mediaResolution"]);e!==void 0&&d!=null&&r(e,["setup","generationConfig","mediaResolution"],d);const f=i(t,["seed"]);e!==void 0&&f!=null&&r(e,["setup","generationConfig","seed"],f);const h=i(t,["speechConfig"]);e!==void 0&&h!=null&&r(e,["setup","generationConfig","speechConfig"],Ke(h));const p=i(t,["thinkingConfig"]);e!==void 0&&p!=null&&r(e,["setup","generationConfig","thinkingConfig"],p);const m=i(t,["enableAffectiveDialog"]);e!==void 0&&m!=null&&r(e,["setup","generationConfig","enableAffectiveDialog"],m);const y=i(t,["systemInstruction"]);e!==void 0&&y!=null&&r(e,["setup","systemInstruction"],Br(q(y)));const _=i(t,["tools"]);if(e!==void 0&&_!=null){let P=ae(_);Array.isArray(P)&&(P=P.map(N=>rl(le(N)))),r(e,["setup","tools"],P)}const T=i(t,["sessionResumption"]);e!==void 0&&T!=null&&r(e,["setup","sessionResumption"],sl(T));const E=i(t,["inputAudioTranscription"]);e!==void 0&&E!=null&&r(e,["setup","inputAudioTranscription"],E);const C=i(t,["outputAudioTranscription"]);e!==void 0&&C!=null&&r(e,["setup","outputAudioTranscription"],C);const v=i(t,["realtimeInputConfig"]);e!==void 0&&v!=null&&r(e,["setup","realtimeInputConfig"],v);const I=i(t,["contextWindowCompression"]);e!==void 0&&I!=null&&r(e,["setup","contextWindowCompression"],I);const A=i(t,["proactivity"]);if(e!==void 0&&A!=null&&r(e,["setup","proactivity"],A),i(t,["explicitVadSignal"])!==void 0)throw new Error("explicitVadSignal parameter is not supported in Gemini API.");return n}function Xr(t,e){const n={},o=i(t,["generationConfig"]);e!==void 0&&o!=null&&r(e,["setup","generationConfig"],Yr(o));const s=i(t,["responseModalities"]);e!==void 0&&s!=null&&r(e,["setup","generationConfig","responseModalities"],s);const l=i(t,["temperature"]);e!==void 0&&l!=null&&r(e,["setup","generationConfig","temperature"],l);const a=i(t,["topP"]);e!==void 0&&a!=null&&r(e,["setup","generationConfig","topP"],a);const u=i(t,["topK"]);e!==void 0&&u!=null&&r(e,["setup","generationConfig","topK"],u);const c=i(t,["maxOutputTokens"]);e!==void 0&&c!=null&&r(e,["setup","generationConfig","maxOutputTokens"],c);const d=i(t,["mediaResolution"]);e!==void 0&&d!=null&&r(e,["setup","generationConfig","mediaResolution"],d);const f=i(t,["seed"]);e!==void 0&&f!=null&&r(e,["setup","generationConfig","seed"],f);const h=i(t,["speechConfig"]);e!==void 0&&h!=null&&r(e,["setup","generationConfig","speechConfig"],Ke(h));const p=i(t,["thinkingConfig"]);e!==void 0&&p!=null&&r(e,["setup","generationConfig","thinkingConfig"],p);const m=i(t,["enableAffectiveDialog"]);e!==void 0&&m!=null&&r(e,["setup","generationConfig","enableAffectiveDialog"],m);const y=i(t,["systemInstruction"]);e!==void 0&&y!=null&&r(e,["setup","systemInstruction"],q(y));const _=i(t,["tools"]);if(e!==void 0&&_!=null){let N=ae(_);Array.isArray(N)&&(N=N.map(U=>ll(le(U)))),r(e,["setup","tools"],N)}const T=i(t,["sessionResumption"]);e!==void 0&&T!=null&&r(e,["setup","sessionResumption"],T);const E=i(t,["inputAudioTranscription"]);e!==void 0&&E!=null&&r(e,["setup","inputAudioTranscription"],E);const C=i(t,["outputAudioTranscription"]);e!==void 0&&C!=null&&r(e,["setup","outputAudioTranscription"],C);const v=i(t,["realtimeInputConfig"]);e!==void 0&&v!=null&&r(e,["setup","realtimeInputConfig"],v);const I=i(t,["contextWindowCompression"]);e!==void 0&&I!=null&&r(e,["setup","contextWindowCompression"],I);const A=i(t,["proactivity"]);e!==void 0&&A!=null&&r(e,["setup","proactivity"],A);const P=i(t,["explicitVadSignal"]);return e!==void 0&&P!=null&&r(e,["setup","explicitVadSignal"],P),n}function Qr(t,e){const n={},o=i(e,["model"]);o!=null&&r(n,["setup","model"],L(t,o));const s=i(e,["config"]);return s!=null&&r(n,["config"],Or(s,n)),n}function Zr(t,e){const n={},o=i(e,["model"]);o!=null&&r(n,["setup","model"],L(t,o));const s=i(e,["config"]);return s!=null&&r(n,["config"],Xr(s,n)),n}function jr(t){const e={},n=i(t,["musicGenerationConfig"]);return n!=null&&r(e,["musicGenerationConfig"],n),e}function el(t){const e={},n=i(t,["weightedPrompts"]);if(n!=null){let o=n;Array.isArray(o)&&(o=o.map(s=>s)),r(e,["weightedPrompts"],o)}return e}function tl(t){const e={},n=i(t,["media"]);if(n!=null){let d=Sn(n);Array.isArray(d)&&(d=d.map(f=>Ie(f))),r(e,["mediaChunks"],d)}const o=i(t,["audio"]);o!=null&&r(e,["audio"],Ie(An(o)));const s=i(t,["audioStreamEnd"]);s!=null&&r(e,["audioStreamEnd"],s);const l=i(t,["video"]);l!=null&&r(e,["video"],Ie(xn(l)));const a=i(t,["text"]);a!=null&&r(e,["text"],a);const u=i(t,["activityStart"]);u!=null&&r(e,["activityStart"],u);const c=i(t,["activityEnd"]);return c!=null&&r(e,["activityEnd"],c),e}function nl(t){const e={},n=i(t,["media"]);if(n!=null){let d=Sn(n);Array.isArray(d)&&(d=d.map(f=>f)),r(e,["mediaChunks"],d)}const o=i(t,["audio"]);o!=null&&r(e,["audio"],An(o));const s=i(t,["audioStreamEnd"]);s!=null&&r(e,["audioStreamEnd"],s);const l=i(t,["video"]);l!=null&&r(e,["video"],xn(l));const a=i(t,["text"]);a!=null&&r(e,["text"],a);const u=i(t,["activityStart"]);u!=null&&r(e,["activityStart"],u);const c=i(t,["activityEnd"]);return c!=null&&r(e,["activityEnd"],c),e}function ol(t){const e={},n=i(t,["setupComplete"]);n!=null&&r(e,["setupComplete"],n);const o=i(t,["serverContent"]);o!=null&&r(e,["serverContent"],o);const s=i(t,["toolCall"]);s!=null&&r(e,["toolCall"],s);const l=i(t,["toolCallCancellation"]);l!=null&&r(e,["toolCallCancellation"],l);const a=i(t,["usageMetadata"]);a!=null&&r(e,["usageMetadata"],al(a));const u=i(t,["goAway"]);u!=null&&r(e,["goAway"],u);const c=i(t,["sessionResumptionUpdate"]);c!=null&&r(e,["sessionResumptionUpdate"],c);const d=i(t,["voiceActivityDetectionSignal"]);return d!=null&&r(e,["voiceActivityDetectionSignal"],d),e}function il(t){const e={},n=i(t,["mediaResolution"]);n!=null&&r(e,["mediaResolution"],n);const o=i(t,["codeExecutionResult"]);o!=null&&r(e,["codeExecutionResult"],o);const s=i(t,["executableCode"]);s!=null&&r(e,["executableCode"],s);const l=i(t,["fileData"]);l!=null&&r(e,["fileData"],Jr(l));const a=i(t,["functionCall"]);a!=null&&r(e,["functionCall"],$r(a));const u=i(t,["functionResponse"]);u!=null&&r(e,["functionResponse"],u);const c=i(t,["inlineData"]);c!=null&&r(e,["inlineData"],Ie(c));const d=i(t,["text"]);d!=null&&r(e,["text"],d);const f=i(t,["thought"]);f!=null&&r(e,["thought"],f);const h=i(t,["thoughtSignature"]);h!=null&&r(e,["thoughtSignature"],h);const p=i(t,["videoMetadata"]);return p!=null&&r(e,["videoMetadata"],p),e}function sl(t){const e={},n=i(t,["handle"]);if(n!=null&&r(e,["handle"],n),i(t,["transparent"])!==void 0)throw new Error("transparent parameter is not supported in Gemini API.");return e}function rl(t){const e={},n=i(t,["functionDeclarations"]);if(n!=null){let f=n;Array.isArray(f)&&(f=f.map(h=>h)),r(e,["functionDeclarations"],f)}if(i(t,["retrieval"])!==void 0)throw new Error("retrieval parameter is not supported in Gemini API.");const o=i(t,["googleSearchRetrieval"]);o!=null&&r(e,["googleSearchRetrieval"],o);const s=i(t,["computerUse"]);s!=null&&r(e,["computerUse"],s);const l=i(t,["fileSearch"]);l!=null&&r(e,["fileSearch"],l);const a=i(t,["codeExecution"]);if(a!=null&&r(e,["codeExecution"],a),i(t,["enterpriseWebSearch"])!==void 0)throw new Error("enterpriseWebSearch parameter is not supported in Gemini API.");const u=i(t,["googleMaps"]);u!=null&&r(e,["googleMaps"],Kr(u));const c=i(t,["googleSearch"]);c!=null&&r(e,["googleSearch"],zr(c));const d=i(t,["urlContext"]);return d!=null&&r(e,["urlContext"],d),e}function ll(t){const e={},n=i(t,["functionDeclarations"]);if(n!=null){let h=n;Array.isArray(h)&&(h=h.map(p=>Wr(p))),r(e,["functionDeclarations"],h)}const o=i(t,["retrieval"]);o!=null&&r(e,["retrieval"],o);const s=i(t,["googleSearchRetrieval"]);s!=null&&r(e,["googleSearchRetrieval"],s);const l=i(t,["computerUse"]);if(l!=null&&r(e,["computerUse"],l),i(t,["fileSearch"])!==void 0)throw new Error("fileSearch parameter is not supported in Vertex AI.");const a=i(t,["codeExecution"]);a!=null&&r(e,["codeExecution"],a);const u=i(t,["enterpriseWebSearch"]);u!=null&&r(e,["enterpriseWebSearch"],u);const c=i(t,["googleMaps"]);c!=null&&r(e,["googleMaps"],c);const d=i(t,["googleSearch"]);d!=null&&r(e,["googleSearch"],d);const f=i(t,["urlContext"]);return f!=null&&r(e,["urlContext"],f),e}function al(t){const e={},n=i(t,["promptTokenCount"]);n!=null&&r(e,["promptTokenCount"],n);const o=i(t,["cachedContentTokenCount"]);o!=null&&r(e,["cachedContentTokenCount"],o);const s=i(t,["candidatesTokenCount"]);s!=null&&r(e,["responseTokenCount"],s);const l=i(t,["toolUsePromptTokenCount"]);l!=null&&r(e,["toolUsePromptTokenCount"],l);const a=i(t,["thoughtsTokenCount"]);a!=null&&r(e,["thoughtsTokenCount"],a);const u=i(t,["totalTokenCount"]);u!=null&&r(e,["totalTokenCount"],u);const c=i(t,["promptTokensDetails"]);if(c!=null){let m=c;Array.isArray(m)&&(m=m.map(y=>y)),r(e,["promptTokensDetails"],m)}const d=i(t,["cacheTokensDetails"]);if(d!=null){let m=d;Array.isArray(m)&&(m=m.map(y=>y)),r(e,["cacheTokensDetails"],m)}const f=i(t,["candidatesTokensDetails"]);if(f!=null){let m=f;Array.isArray(m)&&(m=m.map(y=>y)),r(e,["responseTokensDetails"],m)}const h=i(t,["toolUsePromptTokensDetails"]);if(h!=null){let m=h;Array.isArray(m)&&(m=m.map(y=>y)),r(e,["toolUsePromptTokensDetails"],m)}const p=i(t,["trafficType"]);return p!=null&&r(e,["trafficType"],p),e}/**
186
+ * @license
187
+ * Copyright 2025 Google LLC
188
+ * SPDX-License-Identifier: Apache-2.0
189
+ */function ul(t){const e={},n=i(t,["data"]);if(n!=null&&r(e,["data"],n),i(t,["displayName"])!==void 0)throw new Error("displayName parameter is not supported in Gemini API.");const o=i(t,["mimeType"]);return o!=null&&r(e,["mimeType"],o),e}function dl(t){const e={},n=i(t,["content"]);n!=null&&r(e,["content"],n);const o=i(t,["citationMetadata"]);o!=null&&r(e,["citationMetadata"],cl(o));const s=i(t,["tokenCount"]);s!=null&&r(e,["tokenCount"],s);const l=i(t,["finishReason"]);l!=null&&r(e,["finishReason"],l);const a=i(t,["avgLogprobs"]);a!=null&&r(e,["avgLogprobs"],a);const u=i(t,["groundingMetadata"]);u!=null&&r(e,["groundingMetadata"],u);const c=i(t,["index"]);c!=null&&r(e,["index"],c);const d=i(t,["logprobsResult"]);d!=null&&r(e,["logprobsResult"],d);const f=i(t,["safetyRatings"]);if(f!=null){let p=f;Array.isArray(p)&&(p=p.map(m=>m)),r(e,["safetyRatings"],p)}const h=i(t,["urlContextMetadata"]);return h!=null&&r(e,["urlContextMetadata"],h),e}function cl(t){const e={},n=i(t,["citationSources"]);if(n!=null){let o=n;Array.isArray(o)&&(o=o.map(s=>s)),r(e,["citations"],o)}return e}function fl(t,e){const n={},o=i(e,["model"]);o!=null&&r(n,["_url","model"],L(t,o));const s=i(e,["contents"]);if(s!=null){let l=W(s);Array.isArray(l)&&(l=l.map(a=>a)),r(n,["contents"],l)}return n}function pl(t){const e={},n=i(t,["sdkHttpResponse"]);n!=null&&r(e,["sdkHttpResponse"],n);const o=i(t,["tokensInfo"]);if(o!=null){let s=o;Array.isArray(s)&&(s=s.map(l=>l)),r(e,["tokensInfo"],s)}return e}function hl(t){const e={},n=i(t,["values"]);n!=null&&r(e,["values"],n);const o=i(t,["statistics"]);return o!=null&&r(e,["statistics"],ml(o)),e}function ml(t){const e={},n=i(t,["truncated"]);n!=null&&r(e,["truncated"],n);const o=i(t,["token_count"]);return o!=null&&r(e,["tokenCount"],o),e}function Se(t){const e={},n=i(t,["parts"]);if(n!=null){let s=n;Array.isArray(s)&&(s=s.map(l=>Sa(l))),r(e,["parts"],s)}const o=i(t,["role"]);return o!=null&&r(e,["role"],o),e}function gl(t){const e={},n=i(t,["controlType"]);n!=null&&r(e,["controlType"],n);const o=i(t,["enableControlImageComputation"]);return o!=null&&r(e,["computeControl"],o),e}function yl(t){const e={};if(i(t,["systemInstruction"])!==void 0)throw new Error("systemInstruction parameter is not supported in Gemini API.");if(i(t,["tools"])!==void 0)throw new Error("tools parameter is not supported in Gemini API.");if(i(t,["generationConfig"])!==void 0)throw new Error("generationConfig parameter is not supported in Gemini API.");return e}function Tl(t,e){const n={},o=i(t,["systemInstruction"]);e!==void 0&&o!=null&&r(e,["systemInstruction"],q(o));const s=i(t,["tools"]);if(e!==void 0&&s!=null){let a=s;Array.isArray(a)&&(a=a.map(u=>Qn(u))),r(e,["tools"],a)}const l=i(t,["generationConfig"]);return e!==void 0&&l!=null&&r(e,["generationConfig"],ua(l)),n}function _l(t,e){const n={},o=i(e,["model"]);o!=null&&r(n,["_url","model"],L(t,o));const s=i(e,["contents"]);if(s!=null){let a=W(s);Array.isArray(a)&&(a=a.map(u=>Se(u))),r(n,["contents"],a)}const l=i(e,["config"]);return l!=null&&yl(l),n}function El(t,e){const n={},o=i(e,["model"]);o!=null&&r(n,["_url","model"],L(t,o));const s=i(e,["contents"]);if(s!=null){let a=W(s);Array.isArray(a)&&(a=a.map(u=>u)),r(n,["contents"],a)}const l=i(e,["config"]);return l!=null&&Tl(l,n),n}function Cl(t){const e={},n=i(t,["sdkHttpResponse"]);n!=null&&r(e,["sdkHttpResponse"],n);const o=i(t,["totalTokens"]);o!=null&&r(e,["totalTokens"],o);const s=i(t,["cachedContentTokenCount"]);return s!=null&&r(e,["cachedContentTokenCount"],s),e}function vl(t){const e={},n=i(t,["sdkHttpResponse"]);n!=null&&r(e,["sdkHttpResponse"],n);const o=i(t,["totalTokens"]);return o!=null&&r(e,["totalTokens"],o),e}function Il(t,e){const n={},o=i(e,["model"]);return o!=null&&r(n,["_url","name"],L(t,o)),n}function Sl(t,e){const n={},o=i(e,["model"]);return o!=null&&r(n,["_url","name"],L(t,o)),n}function xl(t){const e={},n=i(t,["sdkHttpResponse"]);return n!=null&&r(e,["sdkHttpResponse"],n),e}function Al(t){const e={},n=i(t,["sdkHttpResponse"]);return n!=null&&r(e,["sdkHttpResponse"],n),e}function wl(t,e){const n={},o=i(t,["outputGcsUri"]);e!==void 0&&o!=null&&r(e,["parameters","storageUri"],o);const s=i(t,["negativePrompt"]);e!==void 0&&s!=null&&r(e,["parameters","negativePrompt"],s);const l=i(t,["numberOfImages"]);e!==void 0&&l!=null&&r(e,["parameters","sampleCount"],l);const a=i(t,["aspectRatio"]);e!==void 0&&a!=null&&r(e,["parameters","aspectRatio"],a);const u=i(t,["guidanceScale"]);e!==void 0&&u!=null&&r(e,["parameters","guidanceScale"],u);const c=i(t,["seed"]);e!==void 0&&c!=null&&r(e,["parameters","seed"],c);const d=i(t,["safetyFilterLevel"]);e!==void 0&&d!=null&&r(e,["parameters","safetySetting"],d);const f=i(t,["personGeneration"]);e!==void 0&&f!=null&&r(e,["parameters","personGeneration"],f);const h=i(t,["includeSafetyAttributes"]);e!==void 0&&h!=null&&r(e,["parameters","includeSafetyAttributes"],h);const p=i(t,["includeRaiReason"]);e!==void 0&&p!=null&&r(e,["parameters","includeRaiReason"],p);const m=i(t,["language"]);e!==void 0&&m!=null&&r(e,["parameters","language"],m);const y=i(t,["outputMimeType"]);e!==void 0&&y!=null&&r(e,["parameters","outputOptions","mimeType"],y);const _=i(t,["outputCompressionQuality"]);e!==void 0&&_!=null&&r(e,["parameters","outputOptions","compressionQuality"],_);const T=i(t,["addWatermark"]);e!==void 0&&T!=null&&r(e,["parameters","addWatermark"],T);const E=i(t,["labels"]);e!==void 0&&E!=null&&r(e,["labels"],E);const C=i(t,["editMode"]);e!==void 0&&C!=null&&r(e,["parameters","editMode"],C);const v=i(t,["baseSteps"]);return e!==void 0&&v!=null&&r(e,["parameters","editConfig","baseSteps"],v),n}function Nl(t,e){const n={},o=i(e,["model"]);o!=null&&r(n,["_url","model"],L(t,o));const s=i(e,["prompt"]);s!=null&&r(n,["instances[0]","prompt"],s);const l=i(e,["referenceImages"]);if(l!=null){let u=l;Array.isArray(u)&&(u=u.map(c=>Pa(c))),r(n,["instances[0]","referenceImages"],u)}const a=i(e,["config"]);return a!=null&&wl(a,n),n}function Ml(t){const e={},n=i(t,["sdkHttpResponse"]);n!=null&&r(e,["sdkHttpResponse"],n);const o=i(t,["predictions"]);if(o!=null){let s=o;Array.isArray(s)&&(s=s.map(l=>xe(l))),r(e,["generatedImages"],s)}return e}function Pl(t,e){const n={},o=i(t,["taskType"]);e!==void 0&&o!=null&&r(e,["requests[]","taskType"],o);const s=i(t,["title"]);e!==void 0&&s!=null&&r(e,["requests[]","title"],s);const l=i(t,["outputDimensionality"]);if(e!==void 0&&l!=null&&r(e,["requests[]","outputDimensionality"],l),i(t,["mimeType"])!==void 0)throw new Error("mimeType parameter is not supported in Gemini API.");if(i(t,["autoTruncate"])!==void 0)throw new Error("autoTruncate parameter is not supported in Gemini API.");return n}function Rl(t,e){const n={},o=i(t,["taskType"]);e!==void 0&&o!=null&&r(e,["instances[]","task_type"],o);const s=i(t,["title"]);e!==void 0&&s!=null&&r(e,["instances[]","title"],s);const l=i(t,["outputDimensionality"]);e!==void 0&&l!=null&&r(e,["parameters","outputDimensionality"],l);const a=i(t,["mimeType"]);e!==void 0&&a!=null&&r(e,["instances[]","mimeType"],a);const u=i(t,["autoTruncate"]);return e!==void 0&&u!=null&&r(e,["parameters","autoTruncate"],u),n}function kl(t,e){const n={},o=i(e,["model"]);o!=null&&r(n,["_url","model"],L(t,o));const s=i(e,["contents"]);if(s!=null){let u=$e(t,s);Array.isArray(u)&&(u=u.map(c=>c)),r(n,["requests[]","content"],u)}const l=i(e,["config"]);l!=null&&Pl(l,n);const a=i(e,["model"]);return a!==void 0&&r(n,["requests[]","model"],L(t,a)),n}function Dl(t,e){const n={},o=i(e,["model"]);o!=null&&r(n,["_url","model"],L(t,o));const s=i(e,["contents"]);if(s!=null){let a=$e(t,s);Array.isArray(a)&&(a=a.map(u=>u)),r(n,["instances[]","content"],a)}const l=i(e,["config"]);return l!=null&&Rl(l,n),n}function Ul(t){const e={},n=i(t,["sdkHttpResponse"]);n!=null&&r(e,["sdkHttpResponse"],n);const o=i(t,["embeddings"]);if(o!=null){let l=o;Array.isArray(l)&&(l=l.map(a=>a)),r(e,["embeddings"],l)}const s=i(t,["metadata"]);return s!=null&&r(e,["metadata"],s),e}function Ll(t){const e={},n=i(t,["sdkHttpResponse"]);n!=null&&r(e,["sdkHttpResponse"],n);const o=i(t,["predictions[]","embeddings"]);if(o!=null){let l=o;Array.isArray(l)&&(l=l.map(a=>hl(a))),r(e,["embeddings"],l)}const s=i(t,["metadata"]);return s!=null&&r(e,["metadata"],s),e}function bl(t){const e={},n=i(t,["endpoint"]);n!=null&&r(e,["name"],n);const o=i(t,["deployedModelId"]);return o!=null&&r(e,["deployedModelId"],o),e}function Fl(t){const e={};if(i(t,["displayName"])!==void 0)throw new Error("displayName parameter is not supported in Gemini API.");const n=i(t,["fileUri"]);n!=null&&r(e,["fileUri"],n);const o=i(t,["mimeType"]);return o!=null&&r(e,["mimeType"],o),e}function Gl(t){const e={},n=i(t,["id"]);n!=null&&r(e,["id"],n);const o=i(t,["args"]);o!=null&&r(e,["args"],o);const s=i(t,["name"]);if(s!=null&&r(e,["name"],s),i(t,["partialArgs"])!==void 0)throw new Error("partialArgs parameter is not supported in Gemini API.");if(i(t,["willContinue"])!==void 0)throw new Error("willContinue parameter is not supported in Gemini API.");return e}function Vl(t){const e={},n=i(t,["mode"]);n!=null&&r(e,["mode"],n);const o=i(t,["allowedFunctionNames"]);if(o!=null&&r(e,["allowedFunctionNames"],o),i(t,["streamFunctionCallArguments"])!==void 0)throw new Error("streamFunctionCallArguments parameter is not supported in Gemini API.");return e}function ql(t){const e={};if(i(t,["behavior"])!==void 0)throw new Error("behavior parameter is not supported in Vertex AI.");const n=i(t,["description"]);n!=null&&r(e,["description"],n);const o=i(t,["name"]);o!=null&&r(e,["name"],o);const s=i(t,["parameters"]);s!=null&&r(e,["parameters"],s);const l=i(t,["parametersJsonSchema"]);l!=null&&r(e,["parametersJsonSchema"],l);const a=i(t,["response"]);a!=null&&r(e,["response"],a);const u=i(t,["responseJsonSchema"]);return u!=null&&r(e,["responseJsonSchema"],u),e}function Hl(t,e,n){const o={},s=i(e,["systemInstruction"]);n!==void 0&&s!=null&&r(n,["systemInstruction"],Se(q(s)));const l=i(e,["temperature"]);l!=null&&r(o,["temperature"],l);const a=i(e,["topP"]);a!=null&&r(o,["topP"],a);const u=i(e,["topK"]);u!=null&&r(o,["topK"],u);const c=i(e,["candidateCount"]);c!=null&&r(o,["candidateCount"],c);const d=i(e,["maxOutputTokens"]);d!=null&&r(o,["maxOutputTokens"],d);const f=i(e,["stopSequences"]);f!=null&&r(o,["stopSequences"],f);const h=i(e,["responseLogprobs"]);h!=null&&r(o,["responseLogprobs"],h);const p=i(e,["logprobs"]);p!=null&&r(o,["logprobs"],p);const m=i(e,["presencePenalty"]);m!=null&&r(o,["presencePenalty"],m);const y=i(e,["frequencyPenalty"]);y!=null&&r(o,["frequencyPenalty"],y);const _=i(e,["seed"]);_!=null&&r(o,["seed"],_);const T=i(e,["responseMimeType"]);T!=null&&r(o,["responseMimeType"],T);const E=i(e,["responseSchema"]);E!=null&&r(o,["responseSchema"],We(E));const C=i(e,["responseJsonSchema"]);if(C!=null&&r(o,["responseJsonSchema"],C),i(e,["routingConfig"])!==void 0)throw new Error("routingConfig parameter is not supported in Gemini API.");if(i(e,["modelSelectionConfig"])!==void 0)throw new Error("modelSelectionConfig parameter is not supported in Gemini API.");const v=i(e,["safetySettings"]);if(n!==void 0&&v!=null){let D=v;Array.isArray(D)&&(D=D.map(G=>Ra(G))),r(n,["safetySettings"],D)}const I=i(e,["tools"]);if(n!==void 0&&I!=null){let D=ae(I);Array.isArray(D)&&(D=D.map(G=>Ga(le(G)))),r(n,["tools"],D)}const A=i(e,["toolConfig"]);if(n!==void 0&&A!=null&&r(n,["toolConfig"],Fa(A)),i(e,["labels"])!==void 0)throw new Error("labels parameter is not supported in Gemini API.");const P=i(e,["cachedContent"]);n!==void 0&&P!=null&&r(n,["cachedContent"],Z(t,P));const N=i(e,["responseModalities"]);N!=null&&r(o,["responseModalities"],N);const U=i(e,["mediaResolution"]);U!=null&&r(o,["mediaResolution"],U);const x=i(e,["speechConfig"]);if(x!=null&&r(o,["speechConfig"],Ye(x)),i(e,["audioTimestamp"])!==void 0)throw new Error("audioTimestamp parameter is not supported in Gemini API.");const R=i(e,["thinkingConfig"]);R!=null&&r(o,["thinkingConfig"],R);const b=i(e,["imageConfig"]);b!=null&&r(o,["imageConfig"],ha(b));const k=i(e,["enableEnhancedCivicAnswers"]);return k!=null&&r(o,["enableEnhancedCivicAnswers"],k),o}function Bl(t,e,n){const o={},s=i(e,["systemInstruction"]);n!==void 0&&s!=null&&r(n,["systemInstruction"],q(s));const l=i(e,["temperature"]);l!=null&&r(o,["temperature"],l);const a=i(e,["topP"]);a!=null&&r(o,["topP"],a);const u=i(e,["topK"]);u!=null&&r(o,["topK"],u);const c=i(e,["candidateCount"]);c!=null&&r(o,["candidateCount"],c);const d=i(e,["maxOutputTokens"]);d!=null&&r(o,["maxOutputTokens"],d);const f=i(e,["stopSequences"]);f!=null&&r(o,["stopSequences"],f);const h=i(e,["responseLogprobs"]);h!=null&&r(o,["responseLogprobs"],h);const p=i(e,["logprobs"]);p!=null&&r(o,["logprobs"],p);const m=i(e,["presencePenalty"]);m!=null&&r(o,["presencePenalty"],m);const y=i(e,["frequencyPenalty"]);y!=null&&r(o,["frequencyPenalty"],y);const _=i(e,["seed"]);_!=null&&r(o,["seed"],_);const T=i(e,["responseMimeType"]);T!=null&&r(o,["responseMimeType"],T);const E=i(e,["responseSchema"]);E!=null&&r(o,["responseSchema"],We(E));const C=i(e,["responseJsonSchema"]);C!=null&&r(o,["responseJsonSchema"],C);const v=i(e,["routingConfig"]);v!=null&&r(o,["routingConfig"],v);const I=i(e,["modelSelectionConfig"]);I!=null&&r(o,["modelConfig"],I);const A=i(e,["safetySettings"]);if(n!==void 0&&A!=null){let H=A;Array.isArray(H)&&(H=H.map(X=>X)),r(n,["safetySettings"],H)}const P=i(e,["tools"]);if(n!==void 0&&P!=null){let H=ae(P);Array.isArray(H)&&(H=H.map(X=>Qn(le(X)))),r(n,["tools"],H)}const N=i(e,["toolConfig"]);n!==void 0&&N!=null&&r(n,["toolConfig"],N);const U=i(e,["labels"]);n!==void 0&&U!=null&&r(n,["labels"],U);const x=i(e,["cachedContent"]);n!==void 0&&x!=null&&r(n,["cachedContent"],Z(t,x));const R=i(e,["responseModalities"]);R!=null&&r(o,["responseModalities"],R);const b=i(e,["mediaResolution"]);b!=null&&r(o,["mediaResolution"],b);const k=i(e,["speechConfig"]);k!=null&&r(o,["speechConfig"],Ye(k));const D=i(e,["audioTimestamp"]);D!=null&&r(o,["audioTimestamp"],D);const G=i(e,["thinkingConfig"]);G!=null&&r(o,["thinkingConfig"],G);const $=i(e,["imageConfig"]);if($!=null&&r(o,["imageConfig"],ma($)),i(e,["enableEnhancedCivicAnswers"])!==void 0)throw new Error("enableEnhancedCivicAnswers parameter is not supported in Vertex AI.");return o}function $n(t,e){const n={},o=i(e,["model"]);o!=null&&r(n,["_url","model"],L(t,o));const s=i(e,["contents"]);if(s!=null){let a=W(s);Array.isArray(a)&&(a=a.map(u=>Se(u))),r(n,["contents"],a)}const l=i(e,["config"]);return l!=null&&r(n,["generationConfig"],Hl(t,l,n)),n}function Wn(t,e){const n={},o=i(e,["model"]);o!=null&&r(n,["_url","model"],L(t,o));const s=i(e,["contents"]);if(s!=null){let a=W(s);Array.isArray(a)&&(a=a.map(u=>u)),r(n,["contents"],a)}const l=i(e,["config"]);return l!=null&&r(n,["generationConfig"],Bl(t,l,n)),n}function Yn(t){const e={},n=i(t,["sdkHttpResponse"]);n!=null&&r(e,["sdkHttpResponse"],n);const o=i(t,["candidates"]);if(o!=null){let c=o;Array.isArray(c)&&(c=c.map(d=>dl(d))),r(e,["candidates"],c)}const s=i(t,["modelVersion"]);s!=null&&r(e,["modelVersion"],s);const l=i(t,["promptFeedback"]);l!=null&&r(e,["promptFeedback"],l);const a=i(t,["responseId"]);a!=null&&r(e,["responseId"],a);const u=i(t,["usageMetadata"]);return u!=null&&r(e,["usageMetadata"],u),e}function Kn(t){const e={},n=i(t,["sdkHttpResponse"]);n!=null&&r(e,["sdkHttpResponse"],n);const o=i(t,["candidates"]);if(o!=null){let d=o;Array.isArray(d)&&(d=d.map(f=>f)),r(e,["candidates"],d)}const s=i(t,["createTime"]);s!=null&&r(e,["createTime"],s);const l=i(t,["modelVersion"]);l!=null&&r(e,["modelVersion"],l);const a=i(t,["promptFeedback"]);a!=null&&r(e,["promptFeedback"],a);const u=i(t,["responseId"]);u!=null&&r(e,["responseId"],u);const c=i(t,["usageMetadata"]);return c!=null&&r(e,["usageMetadata"],c),e}function Jl(t,e){const n={};if(i(t,["outputGcsUri"])!==void 0)throw new Error("outputGcsUri parameter is not supported in Gemini API.");if(i(t,["negativePrompt"])!==void 0)throw new Error("negativePrompt parameter is not supported in Gemini API.");const o=i(t,["numberOfImages"]);e!==void 0&&o!=null&&r(e,["parameters","sampleCount"],o);const s=i(t,["aspectRatio"]);e!==void 0&&s!=null&&r(e,["parameters","aspectRatio"],s);const l=i(t,["guidanceScale"]);if(e!==void 0&&l!=null&&r(e,["parameters","guidanceScale"],l),i(t,["seed"])!==void 0)throw new Error("seed parameter is not supported in Gemini API.");const a=i(t,["safetyFilterLevel"]);e!==void 0&&a!=null&&r(e,["parameters","safetySetting"],a);const u=i(t,["personGeneration"]);e!==void 0&&u!=null&&r(e,["parameters","personGeneration"],u);const c=i(t,["includeSafetyAttributes"]);e!==void 0&&c!=null&&r(e,["parameters","includeSafetyAttributes"],c);const d=i(t,["includeRaiReason"]);e!==void 0&&d!=null&&r(e,["parameters","includeRaiReason"],d);const f=i(t,["language"]);e!==void 0&&f!=null&&r(e,["parameters","language"],f);const h=i(t,["outputMimeType"]);e!==void 0&&h!=null&&r(e,["parameters","outputOptions","mimeType"],h);const p=i(t,["outputCompressionQuality"]);if(e!==void 0&&p!=null&&r(e,["parameters","outputOptions","compressionQuality"],p),i(t,["addWatermark"])!==void 0)throw new Error("addWatermark parameter is not supported in Gemini API.");if(i(t,["labels"])!==void 0)throw new Error("labels parameter is not supported in Gemini API.");const m=i(t,["imageSize"]);if(e!==void 0&&m!=null&&r(e,["parameters","sampleImageSize"],m),i(t,["enhancePrompt"])!==void 0)throw new Error("enhancePrompt parameter is not supported in Gemini API.");return n}function $l(t,e){const n={},o=i(t,["outputGcsUri"]);e!==void 0&&o!=null&&r(e,["parameters","storageUri"],o);const s=i(t,["negativePrompt"]);e!==void 0&&s!=null&&r(e,["parameters","negativePrompt"],s);const l=i(t,["numberOfImages"]);e!==void 0&&l!=null&&r(e,["parameters","sampleCount"],l);const a=i(t,["aspectRatio"]);e!==void 0&&a!=null&&r(e,["parameters","aspectRatio"],a);const u=i(t,["guidanceScale"]);e!==void 0&&u!=null&&r(e,["parameters","guidanceScale"],u);const c=i(t,["seed"]);e!==void 0&&c!=null&&r(e,["parameters","seed"],c);const d=i(t,["safetyFilterLevel"]);e!==void 0&&d!=null&&r(e,["parameters","safetySetting"],d);const f=i(t,["personGeneration"]);e!==void 0&&f!=null&&r(e,["parameters","personGeneration"],f);const h=i(t,["includeSafetyAttributes"]);e!==void 0&&h!=null&&r(e,["parameters","includeSafetyAttributes"],h);const p=i(t,["includeRaiReason"]);e!==void 0&&p!=null&&r(e,["parameters","includeRaiReason"],p);const m=i(t,["language"]);e!==void 0&&m!=null&&r(e,["parameters","language"],m);const y=i(t,["outputMimeType"]);e!==void 0&&y!=null&&r(e,["parameters","outputOptions","mimeType"],y);const _=i(t,["outputCompressionQuality"]);e!==void 0&&_!=null&&r(e,["parameters","outputOptions","compressionQuality"],_);const T=i(t,["addWatermark"]);e!==void 0&&T!=null&&r(e,["parameters","addWatermark"],T);const E=i(t,["labels"]);e!==void 0&&E!=null&&r(e,["labels"],E);const C=i(t,["imageSize"]);e!==void 0&&C!=null&&r(e,["parameters","sampleImageSize"],C);const v=i(t,["enhancePrompt"]);return e!==void 0&&v!=null&&r(e,["parameters","enhancePrompt"],v),n}function Wl(t,e){const n={},o=i(e,["model"]);o!=null&&r(n,["_url","model"],L(t,o));const s=i(e,["prompt"]);s!=null&&r(n,["instances[0]","prompt"],s);const l=i(e,["config"]);return l!=null&&Jl(l,n),n}function Yl(t,e){const n={},o=i(e,["model"]);o!=null&&r(n,["_url","model"],L(t,o));const s=i(e,["prompt"]);s!=null&&r(n,["instances[0]","prompt"],s);const l=i(e,["config"]);return l!=null&&$l(l,n),n}function Kl(t){const e={},n=i(t,["sdkHttpResponse"]);n!=null&&r(e,["sdkHttpResponse"],n);const o=i(t,["predictions"]);if(o!=null){let l=o;Array.isArray(l)&&(l=l.map(a=>sa(a))),r(e,["generatedImages"],l)}const s=i(t,["positivePromptSafetyAttributes"]);return s!=null&&r(e,["positivePromptSafetyAttributes"],On(s)),e}function zl(t){const e={},n=i(t,["sdkHttpResponse"]);n!=null&&r(e,["sdkHttpResponse"],n);const o=i(t,["predictions"]);if(o!=null){let l=o;Array.isArray(l)&&(l=l.map(a=>xe(a))),r(e,["generatedImages"],l)}const s=i(t,["positivePromptSafetyAttributes"]);return s!=null&&r(e,["positivePromptSafetyAttributes"],Xn(s)),e}function Ol(t,e){const n={},o=i(t,["numberOfVideos"]);if(e!==void 0&&o!=null&&r(e,["parameters","sampleCount"],o),i(t,["outputGcsUri"])!==void 0)throw new Error("outputGcsUri parameter is not supported in Gemini API.");if(i(t,["fps"])!==void 0)throw new Error("fps parameter is not supported in Gemini API.");const s=i(t,["durationSeconds"]);if(e!==void 0&&s!=null&&r(e,["parameters","durationSeconds"],s),i(t,["seed"])!==void 0)throw new Error("seed parameter is not supported in Gemini API.");const l=i(t,["aspectRatio"]);e!==void 0&&l!=null&&r(e,["parameters","aspectRatio"],l);const a=i(t,["resolution"]);e!==void 0&&a!=null&&r(e,["parameters","resolution"],a);const u=i(t,["personGeneration"]);if(e!==void 0&&u!=null&&r(e,["parameters","personGeneration"],u),i(t,["pubsubTopic"])!==void 0)throw new Error("pubsubTopic parameter is not supported in Gemini API.");const c=i(t,["negativePrompt"]);e!==void 0&&c!=null&&r(e,["parameters","negativePrompt"],c);const d=i(t,["enhancePrompt"]);if(e!==void 0&&d!=null&&r(e,["parameters","enhancePrompt"],d),i(t,["generateAudio"])!==void 0)throw new Error("generateAudio parameter is not supported in Gemini API.");const f=i(t,["lastFrame"]);e!==void 0&&f!=null&&r(e,["instances[0]","lastFrame"],Ae(f));const h=i(t,["referenceImages"]);if(e!==void 0&&h!=null){let p=h;Array.isArray(p)&&(p=p.map(m=>Qa(m))),r(e,["instances[0]","referenceImages"],p)}if(i(t,["mask"])!==void 0)throw new Error("mask parameter is not supported in Gemini API.");if(i(t,["compressionQuality"])!==void 0)throw new Error("compressionQuality parameter is not supported in Gemini API.");return n}function Xl(t,e){const n={},o=i(t,["numberOfVideos"]);e!==void 0&&o!=null&&r(e,["parameters","sampleCount"],o);const s=i(t,["outputGcsUri"]);e!==void 0&&s!=null&&r(e,["parameters","storageUri"],s);const l=i(t,["fps"]);e!==void 0&&l!=null&&r(e,["parameters","fps"],l);const a=i(t,["durationSeconds"]);e!==void 0&&a!=null&&r(e,["parameters","durationSeconds"],a);const u=i(t,["seed"]);e!==void 0&&u!=null&&r(e,["parameters","seed"],u);const c=i(t,["aspectRatio"]);e!==void 0&&c!=null&&r(e,["parameters","aspectRatio"],c);const d=i(t,["resolution"]);e!==void 0&&d!=null&&r(e,["parameters","resolution"],d);const f=i(t,["personGeneration"]);e!==void 0&&f!=null&&r(e,["parameters","personGeneration"],f);const h=i(t,["pubsubTopic"]);e!==void 0&&h!=null&&r(e,["parameters","pubsubTopic"],h);const p=i(t,["negativePrompt"]);e!==void 0&&p!=null&&r(e,["parameters","negativePrompt"],p);const m=i(t,["enhancePrompt"]);e!==void 0&&m!=null&&r(e,["parameters","enhancePrompt"],m);const y=i(t,["generateAudio"]);e!==void 0&&y!=null&&r(e,["parameters","generateAudio"],y);const _=i(t,["lastFrame"]);e!==void 0&&_!=null&&r(e,["instances[0]","lastFrame"],O(_));const T=i(t,["referenceImages"]);if(e!==void 0&&T!=null){let v=T;Array.isArray(v)&&(v=v.map(I=>Za(I))),r(e,["instances[0]","referenceImages"],v)}const E=i(t,["mask"]);e!==void 0&&E!=null&&r(e,["instances[0]","mask"],Xa(E));const C=i(t,["compressionQuality"]);return e!==void 0&&C!=null&&r(e,["parameters","compressionQuality"],C),n}function Ql(t){const e={},n=i(t,["name"]);n!=null&&r(e,["name"],n);const o=i(t,["metadata"]);o!=null&&r(e,["metadata"],o);const s=i(t,["done"]);s!=null&&r(e,["done"],s);const l=i(t,["error"]);l!=null&&r(e,["error"],l);const a=i(t,["response","generateVideoResponse"]);return a!=null&&r(e,["response"],ta(a)),e}function Zl(t){const e={},n=i(t,["name"]);n!=null&&r(e,["name"],n);const o=i(t,["metadata"]);o!=null&&r(e,["metadata"],o);const s=i(t,["done"]);s!=null&&r(e,["done"],s);const l=i(t,["error"]);l!=null&&r(e,["error"],l);const a=i(t,["response"]);return a!=null&&r(e,["response"],na(a)),e}function jl(t,e){const n={},o=i(e,["model"]);o!=null&&r(n,["_url","model"],L(t,o));const s=i(e,["prompt"]);s!=null&&r(n,["instances[0]","prompt"],s);const l=i(e,["image"]);l!=null&&r(n,["instances[0]","image"],Ae(l));const a=i(e,["video"]);a!=null&&r(n,["instances[0]","video"],Zn(a));const u=i(e,["source"]);u!=null&&oa(u,n);const c=i(e,["config"]);return c!=null&&Ol(c,n),n}function ea(t,e){const n={},o=i(e,["model"]);o!=null&&r(n,["_url","model"],L(t,o));const s=i(e,["prompt"]);s!=null&&r(n,["instances[0]","prompt"],s);const l=i(e,["image"]);l!=null&&r(n,["instances[0]","image"],O(l));const a=i(e,["video"]);a!=null&&r(n,["instances[0]","video"],jn(a));const u=i(e,["source"]);u!=null&&ia(u,n);const c=i(e,["config"]);return c!=null&&Xl(c,n),n}function ta(t){const e={},n=i(t,["generatedSamples"]);if(n!=null){let l=n;Array.isArray(l)&&(l=l.map(a=>la(a))),r(e,["generatedVideos"],l)}const o=i(t,["raiMediaFilteredCount"]);o!=null&&r(e,["raiMediaFilteredCount"],o);const s=i(t,["raiMediaFilteredReasons"]);return s!=null&&r(e,["raiMediaFilteredReasons"],s),e}function na(t){const e={},n=i(t,["videos"]);if(n!=null){let l=n;Array.isArray(l)&&(l=l.map(a=>aa(a))),r(e,["generatedVideos"],l)}const o=i(t,["raiMediaFilteredCount"]);o!=null&&r(e,["raiMediaFilteredCount"],o);const s=i(t,["raiMediaFilteredReasons"]);return s!=null&&r(e,["raiMediaFilteredReasons"],s),e}function oa(t,e){const n={},o=i(t,["prompt"]);e!==void 0&&o!=null&&r(e,["instances[0]","prompt"],o);const s=i(t,["image"]);e!==void 0&&s!=null&&r(e,["instances[0]","image"],Ae(s));const l=i(t,["video"]);return e!==void 0&&l!=null&&r(e,["instances[0]","video"],Zn(l)),n}function ia(t,e){const n={},o=i(t,["prompt"]);e!==void 0&&o!=null&&r(e,["instances[0]","prompt"],o);const s=i(t,["image"]);e!==void 0&&s!=null&&r(e,["instances[0]","image"],O(s));const l=i(t,["video"]);return e!==void 0&&l!=null&&r(e,["instances[0]","video"],jn(l)),n}function sa(t){const e={},n=i(t,["_self"]);n!=null&&r(e,["image"],ga(n));const o=i(t,["raiFilteredReason"]);o!=null&&r(e,["raiFilteredReason"],o);const s=i(t,["_self"]);return s!=null&&r(e,["safetyAttributes"],On(s)),e}function xe(t){const e={},n=i(t,["_self"]);n!=null&&r(e,["image"],zn(n));const o=i(t,["raiFilteredReason"]);o!=null&&r(e,["raiFilteredReason"],o);const s=i(t,["_self"]);s!=null&&r(e,["safetyAttributes"],Xn(s));const l=i(t,["prompt"]);return l!=null&&r(e,["enhancedPrompt"],l),e}function ra(t){const e={},n=i(t,["_self"]);n!=null&&r(e,["mask"],zn(n));const o=i(t,["labels"]);if(o!=null){let s=o;Array.isArray(s)&&(s=s.map(l=>l)),r(e,["labels"],s)}return e}function la(t){const e={},n=i(t,["video"]);return n!=null&&r(e,["video"],za(n)),e}function aa(t){const e={},n=i(t,["_self"]);return n!=null&&r(e,["video"],Oa(n)),e}function ua(t){const e={},n=i(t,["modelSelectionConfig"]);n!=null&&r(e,["modelConfig"],n);const o=i(t,["responseJsonSchema"]);o!=null&&r(e,["responseJsonSchema"],o);const s=i(t,["audioTimestamp"]);s!=null&&r(e,["audioTimestamp"],s);const l=i(t,["candidateCount"]);l!=null&&r(e,["candidateCount"],l);const a=i(t,["enableAffectiveDialog"]);a!=null&&r(e,["enableAffectiveDialog"],a);const u=i(t,["frequencyPenalty"]);u!=null&&r(e,["frequencyPenalty"],u);const c=i(t,["logprobs"]);c!=null&&r(e,["logprobs"],c);const d=i(t,["maxOutputTokens"]);d!=null&&r(e,["maxOutputTokens"],d);const f=i(t,["mediaResolution"]);f!=null&&r(e,["mediaResolution"],f);const h=i(t,["presencePenalty"]);h!=null&&r(e,["presencePenalty"],h);const p=i(t,["responseLogprobs"]);p!=null&&r(e,["responseLogprobs"],p);const m=i(t,["responseMimeType"]);m!=null&&r(e,["responseMimeType"],m);const y=i(t,["responseModalities"]);y!=null&&r(e,["responseModalities"],y);const _=i(t,["responseSchema"]);_!=null&&r(e,["responseSchema"],_);const T=i(t,["routingConfig"]);T!=null&&r(e,["routingConfig"],T);const E=i(t,["seed"]);E!=null&&r(e,["seed"],E);const C=i(t,["speechConfig"]);C!=null&&r(e,["speechConfig"],C);const v=i(t,["stopSequences"]);v!=null&&r(e,["stopSequences"],v);const I=i(t,["temperature"]);I!=null&&r(e,["temperature"],I);const A=i(t,["thinkingConfig"]);A!=null&&r(e,["thinkingConfig"],A);const P=i(t,["topK"]);P!=null&&r(e,["topK"],P);const N=i(t,["topP"]);if(N!=null&&r(e,["topP"],N),i(t,["enableEnhancedCivicAnswers"])!==void 0)throw new Error("enableEnhancedCivicAnswers parameter is not supported in Vertex AI.");return e}function da(t,e){const n={},o=i(e,["model"]);return o!=null&&r(n,["_url","name"],L(t,o)),n}function ca(t,e){const n={},o=i(e,["model"]);return o!=null&&r(n,["_url","name"],L(t,o)),n}function fa(t){const e={};if(i(t,["authConfig"])!==void 0)throw new Error("authConfig parameter is not supported in Gemini API.");const n=i(t,["enableWidget"]);return n!=null&&r(e,["enableWidget"],n),e}function pa(t){const e={};if(i(t,["excludeDomains"])!==void 0)throw new Error("excludeDomains parameter is not supported in Gemini API.");if(i(t,["blockingConfidence"])!==void 0)throw new Error("blockingConfidence parameter is not supported in Gemini API.");const n=i(t,["timeRangeFilter"]);return n!=null&&r(e,["timeRangeFilter"],n),e}function ha(t){const e={},n=i(t,["aspectRatio"]);n!=null&&r(e,["aspectRatio"],n);const o=i(t,["imageSize"]);if(o!=null&&r(e,["imageSize"],o),i(t,["outputMimeType"])!==void 0)throw new Error("outputMimeType parameter is not supported in Gemini API.");if(i(t,["outputCompressionQuality"])!==void 0)throw new Error("outputCompressionQuality parameter is not supported in Gemini API.");return e}function ma(t){const e={},n=i(t,["aspectRatio"]);n!=null&&r(e,["aspectRatio"],n);const o=i(t,["imageSize"]);o!=null&&r(e,["imageSize"],o);const s=i(t,["outputMimeType"]);s!=null&&r(e,["imageOutputOptions","mimeType"],s);const l=i(t,["outputCompressionQuality"]);return l!=null&&r(e,["imageOutputOptions","compressionQuality"],l),e}function ga(t){const e={},n=i(t,["bytesBase64Encoded"]);n!=null&&r(e,["imageBytes"],ne(n));const o=i(t,["mimeType"]);return o!=null&&r(e,["mimeType"],o),e}function zn(t){const e={},n=i(t,["gcsUri"]);n!=null&&r(e,["gcsUri"],n);const o=i(t,["bytesBase64Encoded"]);o!=null&&r(e,["imageBytes"],ne(o));const s=i(t,["mimeType"]);return s!=null&&r(e,["mimeType"],s),e}function Ae(t){const e={};if(i(t,["gcsUri"])!==void 0)throw new Error("gcsUri parameter is not supported in Gemini API.");const n=i(t,["imageBytes"]);n!=null&&r(e,["bytesBase64Encoded"],ne(n));const o=i(t,["mimeType"]);return o!=null&&r(e,["mimeType"],o),e}function O(t){const e={},n=i(t,["gcsUri"]);n!=null&&r(e,["gcsUri"],n);const o=i(t,["imageBytes"]);o!=null&&r(e,["bytesBase64Encoded"],ne(o));const s=i(t,["mimeType"]);return s!=null&&r(e,["mimeType"],s),e}function ya(t,e,n){const o={},s=i(e,["pageSize"]);n!==void 0&&s!=null&&r(n,["_query","pageSize"],s);const l=i(e,["pageToken"]);n!==void 0&&l!=null&&r(n,["_query","pageToken"],l);const a=i(e,["filter"]);n!==void 0&&a!=null&&r(n,["_query","filter"],a);const u=i(e,["queryBase"]);return n!==void 0&&u!=null&&r(n,["_url","models_url"],Dn(t,u)),o}function Ta(t,e,n){const o={},s=i(e,["pageSize"]);n!==void 0&&s!=null&&r(n,["_query","pageSize"],s);const l=i(e,["pageToken"]);n!==void 0&&l!=null&&r(n,["_query","pageToken"],l);const a=i(e,["filter"]);n!==void 0&&a!=null&&r(n,["_query","filter"],a);const u=i(e,["queryBase"]);return n!==void 0&&u!=null&&r(n,["_url","models_url"],Dn(t,u)),o}function _a(t,e){const n={},o=i(e,["config"]);return o!=null&&ya(t,o,n),n}function Ea(t,e){const n={},o=i(e,["config"]);return o!=null&&Ta(t,o,n),n}function Ca(t){const e={},n=i(t,["sdkHttpResponse"]);n!=null&&r(e,["sdkHttpResponse"],n);const o=i(t,["nextPageToken"]);o!=null&&r(e,["nextPageToken"],o);const s=i(t,["_self"]);if(s!=null){let l=Un(s);Array.isArray(l)&&(l=l.map(a=>Oe(a))),r(e,["models"],l)}return e}function va(t){const e={},n=i(t,["sdkHttpResponse"]);n!=null&&r(e,["sdkHttpResponse"],n);const o=i(t,["nextPageToken"]);o!=null&&r(e,["nextPageToken"],o);const s=i(t,["_self"]);if(s!=null){let l=Un(s);Array.isArray(l)&&(l=l.map(a=>Xe(a))),r(e,["models"],l)}return e}function Ia(t){const e={},n=i(t,["maskMode"]);n!=null&&r(e,["maskMode"],n);const o=i(t,["segmentationClasses"]);o!=null&&r(e,["maskClasses"],o);const s=i(t,["maskDilation"]);return s!=null&&r(e,["dilation"],s),e}function Oe(t){const e={},n=i(t,["name"]);n!=null&&r(e,["name"],n);const o=i(t,["displayName"]);o!=null&&r(e,["displayName"],o);const s=i(t,["description"]);s!=null&&r(e,["description"],s);const l=i(t,["version"]);l!=null&&r(e,["version"],l);const a=i(t,["_self"]);a!=null&&r(e,["tunedModelInfo"],Va(a));const u=i(t,["inputTokenLimit"]);u!=null&&r(e,["inputTokenLimit"],u);const c=i(t,["outputTokenLimit"]);c!=null&&r(e,["outputTokenLimit"],c);const d=i(t,["supportedGenerationMethods"]);d!=null&&r(e,["supportedActions"],d);const f=i(t,["temperature"]);f!=null&&r(e,["temperature"],f);const h=i(t,["maxTemperature"]);h!=null&&r(e,["maxTemperature"],h);const p=i(t,["topP"]);p!=null&&r(e,["topP"],p);const m=i(t,["topK"]);m!=null&&r(e,["topK"],m);const y=i(t,["thinking"]);return y!=null&&r(e,["thinking"],y),e}function Xe(t){const e={},n=i(t,["name"]);n!=null&&r(e,["name"],n);const o=i(t,["displayName"]);o!=null&&r(e,["displayName"],o);const s=i(t,["description"]);s!=null&&r(e,["description"],s);const l=i(t,["versionId"]);l!=null&&r(e,["version"],l);const a=i(t,["deployedModels"]);if(a!=null){let h=a;Array.isArray(h)&&(h=h.map(p=>bl(p))),r(e,["endpoints"],h)}const u=i(t,["labels"]);u!=null&&r(e,["labels"],u);const c=i(t,["_self"]);c!=null&&r(e,["tunedModelInfo"],qa(c));const d=i(t,["defaultCheckpointId"]);d!=null&&r(e,["defaultCheckpointId"],d);const f=i(t,["checkpoints"]);if(f!=null){let h=f;Array.isArray(h)&&(h=h.map(p=>p)),r(e,["checkpoints"],h)}return e}function Sa(t){const e={},n=i(t,["mediaResolution"]);n!=null&&r(e,["mediaResolution"],n);const o=i(t,["codeExecutionResult"]);o!=null&&r(e,["codeExecutionResult"],o);const s=i(t,["executableCode"]);s!=null&&r(e,["executableCode"],s);const l=i(t,["fileData"]);l!=null&&r(e,["fileData"],Fl(l));const a=i(t,["functionCall"]);a!=null&&r(e,["functionCall"],Gl(a));const u=i(t,["functionResponse"]);u!=null&&r(e,["functionResponse"],u);const c=i(t,["inlineData"]);c!=null&&r(e,["inlineData"],ul(c));const d=i(t,["text"]);d!=null&&r(e,["text"],d);const f=i(t,["thought"]);f!=null&&r(e,["thought"],f);const h=i(t,["thoughtSignature"]);h!=null&&r(e,["thoughtSignature"],h);const p=i(t,["videoMetadata"]);return p!=null&&r(e,["videoMetadata"],p),e}function xa(t){const e={},n=i(t,["productImage"]);return n!=null&&r(e,["image"],O(n)),e}function Aa(t,e){const n={},o=i(t,["numberOfImages"]);e!==void 0&&o!=null&&r(e,["parameters","sampleCount"],o);const s=i(t,["baseSteps"]);e!==void 0&&s!=null&&r(e,["parameters","baseSteps"],s);const l=i(t,["outputGcsUri"]);e!==void 0&&l!=null&&r(e,["parameters","storageUri"],l);const a=i(t,["seed"]);e!==void 0&&a!=null&&r(e,["parameters","seed"],a);const u=i(t,["safetyFilterLevel"]);e!==void 0&&u!=null&&r(e,["parameters","safetySetting"],u);const c=i(t,["personGeneration"]);e!==void 0&&c!=null&&r(e,["parameters","personGeneration"],c);const d=i(t,["addWatermark"]);e!==void 0&&d!=null&&r(e,["parameters","addWatermark"],d);const f=i(t,["outputMimeType"]);e!==void 0&&f!=null&&r(e,["parameters","outputOptions","mimeType"],f);const h=i(t,["outputCompressionQuality"]);e!==void 0&&h!=null&&r(e,["parameters","outputOptions","compressionQuality"],h);const p=i(t,["enhancePrompt"]);e!==void 0&&p!=null&&r(e,["parameters","enhancePrompt"],p);const m=i(t,["labels"]);return e!==void 0&&m!=null&&r(e,["labels"],m),n}function wa(t,e){const n={},o=i(e,["model"]);o!=null&&r(n,["_url","model"],L(t,o));const s=i(e,["source"]);s!=null&&Ma(s,n);const l=i(e,["config"]);return l!=null&&Aa(l,n),n}function Na(t){const e={},n=i(t,["predictions"]);if(n!=null){let o=n;Array.isArray(o)&&(o=o.map(s=>xe(s))),r(e,["generatedImages"],o)}return e}function Ma(t,e){const n={},o=i(t,["prompt"]);e!==void 0&&o!=null&&r(e,["instances[0]","prompt"],o);const s=i(t,["personImage"]);e!==void 0&&s!=null&&r(e,["instances[0]","personImage","image"],O(s));const l=i(t,["productImages"]);if(e!==void 0&&l!=null){let a=l;Array.isArray(a)&&(a=a.map(u=>xa(u))),r(e,["instances[0]","productImages"],a)}return n}function Pa(t){const e={},n=i(t,["referenceImage"]);n!=null&&r(e,["referenceImage"],O(n));const o=i(t,["referenceId"]);o!=null&&r(e,["referenceId"],o);const s=i(t,["referenceType"]);s!=null&&r(e,["referenceType"],s);const l=i(t,["maskImageConfig"]);l!=null&&r(e,["maskImageConfig"],Ia(l));const a=i(t,["controlImageConfig"]);a!=null&&r(e,["controlImageConfig"],gl(a));const u=i(t,["styleImageConfig"]);u!=null&&r(e,["styleImageConfig"],u);const c=i(t,["subjectImageConfig"]);return c!=null&&r(e,["subjectImageConfig"],c),e}function On(t){const e={},n=i(t,["safetyAttributes","categories"]);n!=null&&r(e,["categories"],n);const o=i(t,["safetyAttributes","scores"]);o!=null&&r(e,["scores"],o);const s=i(t,["contentType"]);return s!=null&&r(e,["contentType"],s),e}function Xn(t){const e={},n=i(t,["safetyAttributes","categories"]);n!=null&&r(e,["categories"],n);const o=i(t,["safetyAttributes","scores"]);o!=null&&r(e,["scores"],o);const s=i(t,["contentType"]);return s!=null&&r(e,["contentType"],s),e}function Ra(t){const e={},n=i(t,["category"]);if(n!=null&&r(e,["category"],n),i(t,["method"])!==void 0)throw new Error("method parameter is not supported in Gemini API.");const o=i(t,["threshold"]);return o!=null&&r(e,["threshold"],o),e}function ka(t){const e={},n=i(t,["image"]);return n!=null&&r(e,["image"],O(n)),e}function Da(t,e){const n={},o=i(t,["mode"]);e!==void 0&&o!=null&&r(e,["parameters","mode"],o);const s=i(t,["maxPredictions"]);e!==void 0&&s!=null&&r(e,["parameters","maxPredictions"],s);const l=i(t,["confidenceThreshold"]);e!==void 0&&l!=null&&r(e,["parameters","confidenceThreshold"],l);const a=i(t,["maskDilation"]);e!==void 0&&a!=null&&r(e,["parameters","maskDilation"],a);const u=i(t,["binaryColorThreshold"]);e!==void 0&&u!=null&&r(e,["parameters","binaryColorThreshold"],u);const c=i(t,["labels"]);return e!==void 0&&c!=null&&r(e,["labels"],c),n}function Ua(t,e){const n={},o=i(e,["model"]);o!=null&&r(n,["_url","model"],L(t,o));const s=i(e,["source"]);s!=null&&ba(s,n);const l=i(e,["config"]);return l!=null&&Da(l,n),n}function La(t){const e={},n=i(t,["predictions"]);if(n!=null){let o=n;Array.isArray(o)&&(o=o.map(s=>ra(s))),r(e,["generatedMasks"],o)}return e}function ba(t,e){const n={},o=i(t,["prompt"]);e!==void 0&&o!=null&&r(e,["instances[0]","prompt"],o);const s=i(t,["image"]);e!==void 0&&s!=null&&r(e,["instances[0]","image"],O(s));const l=i(t,["scribbleImage"]);return e!==void 0&&l!=null&&r(e,["instances[0]","scribble"],ka(l)),n}function Fa(t){const e={},n=i(t,["functionCallingConfig"]);n!=null&&r(e,["functionCallingConfig"],Vl(n));const o=i(t,["retrievalConfig"]);return o!=null&&r(e,["retrievalConfig"],o),e}function Ga(t){const e={},n=i(t,["functionDeclarations"]);if(n!=null){let f=n;Array.isArray(f)&&(f=f.map(h=>h)),r(e,["functionDeclarations"],f)}if(i(t,["retrieval"])!==void 0)throw new Error("retrieval parameter is not supported in Gemini API.");const o=i(t,["googleSearchRetrieval"]);o!=null&&r(e,["googleSearchRetrieval"],o);const s=i(t,["computerUse"]);s!=null&&r(e,["computerUse"],s);const l=i(t,["fileSearch"]);l!=null&&r(e,["fileSearch"],l);const a=i(t,["codeExecution"]);if(a!=null&&r(e,["codeExecution"],a),i(t,["enterpriseWebSearch"])!==void 0)throw new Error("enterpriseWebSearch parameter is not supported in Gemini API.");const u=i(t,["googleMaps"]);u!=null&&r(e,["googleMaps"],fa(u));const c=i(t,["googleSearch"]);c!=null&&r(e,["googleSearch"],pa(c));const d=i(t,["urlContext"]);return d!=null&&r(e,["urlContext"],d),e}function Qn(t){const e={},n=i(t,["functionDeclarations"]);if(n!=null){let h=n;Array.isArray(h)&&(h=h.map(p=>ql(p))),r(e,["functionDeclarations"],h)}const o=i(t,["retrieval"]);o!=null&&r(e,["retrieval"],o);const s=i(t,["googleSearchRetrieval"]);s!=null&&r(e,["googleSearchRetrieval"],s);const l=i(t,["computerUse"]);if(l!=null&&r(e,["computerUse"],l),i(t,["fileSearch"])!==void 0)throw new Error("fileSearch parameter is not supported in Vertex AI.");const a=i(t,["codeExecution"]);a!=null&&r(e,["codeExecution"],a);const u=i(t,["enterpriseWebSearch"]);u!=null&&r(e,["enterpriseWebSearch"],u);const c=i(t,["googleMaps"]);c!=null&&r(e,["googleMaps"],c);const d=i(t,["googleSearch"]);d!=null&&r(e,["googleSearch"],d);const f=i(t,["urlContext"]);return f!=null&&r(e,["urlContext"],f),e}function Va(t){const e={},n=i(t,["baseModel"]);n!=null&&r(e,["baseModel"],n);const o=i(t,["createTime"]);o!=null&&r(e,["createTime"],o);const s=i(t,["updateTime"]);return s!=null&&r(e,["updateTime"],s),e}function qa(t){const e={},n=i(t,["labels","google-vertex-llm-tuning-base-model-id"]);n!=null&&r(e,["baseModel"],n);const o=i(t,["createTime"]);o!=null&&r(e,["createTime"],o);const s=i(t,["updateTime"]);return s!=null&&r(e,["updateTime"],s),e}function Ha(t,e){const n={},o=i(t,["displayName"]);e!==void 0&&o!=null&&r(e,["displayName"],o);const s=i(t,["description"]);e!==void 0&&s!=null&&r(e,["description"],s);const l=i(t,["defaultCheckpointId"]);return e!==void 0&&l!=null&&r(e,["defaultCheckpointId"],l),n}function Ba(t,e){const n={},o=i(t,["displayName"]);e!==void 0&&o!=null&&r(e,["displayName"],o);const s=i(t,["description"]);e!==void 0&&s!=null&&r(e,["description"],s);const l=i(t,["defaultCheckpointId"]);return e!==void 0&&l!=null&&r(e,["defaultCheckpointId"],l),n}function Ja(t,e){const n={},o=i(e,["model"]);o!=null&&r(n,["_url","name"],L(t,o));const s=i(e,["config"]);return s!=null&&Ha(s,n),n}function $a(t,e){const n={},o=i(e,["model"]);o!=null&&r(n,["_url","model"],L(t,o));const s=i(e,["config"]);return s!=null&&Ba(s,n),n}function Wa(t,e){const n={},o=i(t,["outputGcsUri"]);e!==void 0&&o!=null&&r(e,["parameters","storageUri"],o);const s=i(t,["safetyFilterLevel"]);e!==void 0&&s!=null&&r(e,["parameters","safetySetting"],s);const l=i(t,["personGeneration"]);e!==void 0&&l!=null&&r(e,["parameters","personGeneration"],l);const a=i(t,["includeRaiReason"]);e!==void 0&&a!=null&&r(e,["parameters","includeRaiReason"],a);const u=i(t,["outputMimeType"]);e!==void 0&&u!=null&&r(e,["parameters","outputOptions","mimeType"],u);const c=i(t,["outputCompressionQuality"]);e!==void 0&&c!=null&&r(e,["parameters","outputOptions","compressionQuality"],c);const d=i(t,["enhanceInputImage"]);e!==void 0&&d!=null&&r(e,["parameters","upscaleConfig","enhanceInputImage"],d);const f=i(t,["imagePreservationFactor"]);e!==void 0&&f!=null&&r(e,["parameters","upscaleConfig","imagePreservationFactor"],f);const h=i(t,["labels"]);e!==void 0&&h!=null&&r(e,["labels"],h);const p=i(t,["numberOfImages"]);e!==void 0&&p!=null&&r(e,["parameters","sampleCount"],p);const m=i(t,["mode"]);return e!==void 0&&m!=null&&r(e,["parameters","mode"],m),n}function Ya(t,e){const n={},o=i(e,["model"]);o!=null&&r(n,["_url","model"],L(t,o));const s=i(e,["image"]);s!=null&&r(n,["instances[0]","image"],O(s));const l=i(e,["upscaleFactor"]);l!=null&&r(n,["parameters","upscaleConfig","upscaleFactor"],l);const a=i(e,["config"]);return a!=null&&Wa(a,n),n}function Ka(t){const e={},n=i(t,["sdkHttpResponse"]);n!=null&&r(e,["sdkHttpResponse"],n);const o=i(t,["predictions"]);if(o!=null){let s=o;Array.isArray(s)&&(s=s.map(l=>xe(l))),r(e,["generatedImages"],s)}return e}function za(t){const e={},n=i(t,["uri"]);n!=null&&r(e,["uri"],n);const o=i(t,["encodedVideo"]);o!=null&&r(e,["videoBytes"],ne(o));const s=i(t,["encoding"]);return s!=null&&r(e,["mimeType"],s),e}function Oa(t){const e={},n=i(t,["gcsUri"]);n!=null&&r(e,["uri"],n);const o=i(t,["bytesBase64Encoded"]);o!=null&&r(e,["videoBytes"],ne(o));const s=i(t,["mimeType"]);return s!=null&&r(e,["mimeType"],s),e}function Xa(t){const e={},n=i(t,["image"]);n!=null&&r(e,["_self"],O(n));const o=i(t,["maskMode"]);return o!=null&&r(e,["maskMode"],o),e}function Qa(t){const e={},n=i(t,["image"]);n!=null&&r(e,["image"],Ae(n));const o=i(t,["referenceType"]);return o!=null&&r(e,["referenceType"],o),e}function Za(t){const e={},n=i(t,["image"]);n!=null&&r(e,["image"],O(n));const o=i(t,["referenceType"]);return o!=null&&r(e,["referenceType"],o),e}function Zn(t){const e={},n=i(t,["uri"]);n!=null&&r(e,["uri"],n);const o=i(t,["videoBytes"]);o!=null&&r(e,["encodedVideo"],ne(o));const s=i(t,["mimeType"]);return s!=null&&r(e,["encoding"],s),e}function jn(t){const e={},n=i(t,["uri"]);n!=null&&r(e,["gcsUri"],n);const o=i(t,["videoBytes"]);o!=null&&r(e,["bytesBase64Encoded"],ne(o));const s=i(t,["mimeType"]);return s!=null&&r(e,["mimeType"],s),e}/**
190
+ * @license
191
+ * Copyright 2025 Google LLC
192
+ * SPDX-License-Identifier: Apache-2.0
193
+ */function ja(t,e){const n={},o=i(t,["displayName"]);return e!==void 0&&o!=null&&r(e,["displayName"],o),n}function eu(t){const e={},n=i(t,["config"]);return n!=null&&ja(n,e),e}function tu(t,e){const n={},o=i(t,["force"]);return e!==void 0&&o!=null&&r(e,["_query","force"],o),n}function nu(t){const e={},n=i(t,["name"]);n!=null&&r(e,["_url","name"],n);const o=i(t,["config"]);return o!=null&&tu(o,e),e}function ou(t){const e={},n=i(t,["name"]);return n!=null&&r(e,["_url","name"],n),e}function iu(t,e){const n={},o=i(t,["customMetadata"]);if(e!==void 0&&o!=null){let l=o;Array.isArray(l)&&(l=l.map(a=>a)),r(e,["customMetadata"],l)}const s=i(t,["chunkingConfig"]);return e!==void 0&&s!=null&&r(e,["chunkingConfig"],s),n}function su(t){const e={},n=i(t,["name"]);n!=null&&r(e,["name"],n);const o=i(t,["metadata"]);o!=null&&r(e,["metadata"],o);const s=i(t,["done"]);s!=null&&r(e,["done"],s);const l=i(t,["error"]);l!=null&&r(e,["error"],l);const a=i(t,["response"]);return a!=null&&r(e,["response"],lu(a)),e}function ru(t){const e={},n=i(t,["fileSearchStoreName"]);n!=null&&r(e,["_url","file_search_store_name"],n);const o=i(t,["fileName"]);o!=null&&r(e,["fileName"],o);const s=i(t,["config"]);return s!=null&&iu(s,e),e}function lu(t){const e={},n=i(t,["sdkHttpResponse"]);n!=null&&r(e,["sdkHttpResponse"],n);const o=i(t,["parent"]);o!=null&&r(e,["parent"],o);const s=i(t,["documentName"]);return s!=null&&r(e,["documentName"],s),e}function au(t,e){const n={},o=i(t,["pageSize"]);e!==void 0&&o!=null&&r(e,["_query","pageSize"],o);const s=i(t,["pageToken"]);return e!==void 0&&s!=null&&r(e,["_query","pageToken"],s),n}function uu(t){const e={},n=i(t,["config"]);return n!=null&&au(n,e),e}function du(t){const e={},n=i(t,["sdkHttpResponse"]);n!=null&&r(e,["sdkHttpResponse"],n);const o=i(t,["nextPageToken"]);o!=null&&r(e,["nextPageToken"],o);const s=i(t,["fileSearchStores"]);if(s!=null){let l=s;Array.isArray(l)&&(l=l.map(a=>a)),r(e,["fileSearchStores"],l)}return e}function eo(t,e){const n={},o=i(t,["mimeType"]);e!==void 0&&o!=null&&r(e,["mimeType"],o);const s=i(t,["displayName"]);e!==void 0&&s!=null&&r(e,["displayName"],s);const l=i(t,["customMetadata"]);if(e!==void 0&&l!=null){let u=l;Array.isArray(u)&&(u=u.map(c=>c)),r(e,["customMetadata"],u)}const a=i(t,["chunkingConfig"]);return e!==void 0&&a!=null&&r(e,["chunkingConfig"],a),n}function cu(t){const e={},n=i(t,["fileSearchStoreName"]);n!=null&&r(e,["_url","file_search_store_name"],n);const o=i(t,["config"]);return o!=null&&eo(o,e),e}function fu(t){const e={},n=i(t,["sdkHttpResponse"]);return n!=null&&r(e,["sdkHttpResponse"],n),e}/**
194
+ * @license
195
+ * Copyright 2025 Google LLC
196
+ * SPDX-License-Identifier: Apache-2.0
197
+ */const pu="Content-Type",hu="X-Server-Timeout",mu="User-Agent",Qe="x-goog-api-client",gu="google-genai-sdk/1.34.0",yu="v1beta1",Tu="v1beta";class _u{constructor(e){var n,o;this.clientOptions=Object.assign(Object.assign({},e),{project:e.project,location:e.location,apiKey:e.apiKey,vertexai:e.vertexai});const s={};this.clientOptions.vertexai?(s.apiVersion=(n=this.clientOptions.apiVersion)!==null&&n!==void 0?n:yu,s.baseUrl=this.baseUrlFromProjectLocation(),this.normalizeAuthParameters()):(s.apiVersion=(o=this.clientOptions.apiVersion)!==null&&o!==void 0?o:Tu,s.baseUrl="https://generativelanguage.googleapis.com/"),s.headers=this.getDefaultHeaders(),this.clientOptions.httpOptions=s,e.httpOptions&&(this.clientOptions.httpOptions=this.patchHttpOptions(s,e.httpOptions))}baseUrlFromProjectLocation(){return this.clientOptions.project&&this.clientOptions.location&&this.clientOptions.location!=="global"?`https://${this.clientOptions.location}-aiplatform.googleapis.com/`:"https://aiplatform.googleapis.com/"}normalizeAuthParameters(){if(this.clientOptions.project&&this.clientOptions.location){this.clientOptions.apiKey=void 0;return}this.clientOptions.project=void 0,this.clientOptions.location=void 0}isVertexAI(){var e;return(e=this.clientOptions.vertexai)!==null&&e!==void 0?e:!1}getProject(){return this.clientOptions.project}getLocation(){return this.clientOptions.location}async getAuthHeaders(){const e=new Headers;return await this.clientOptions.auth.addAuthHeaders(e),e}getApiVersion(){if(this.clientOptions.httpOptions&&this.clientOptions.httpOptions.apiVersion!==void 0)return this.clientOptions.httpOptions.apiVersion;throw new Error("API version is not set.")}getBaseUrl(){if(this.clientOptions.httpOptions&&this.clientOptions.httpOptions.baseUrl!==void 0)return this.clientOptions.httpOptions.baseUrl;throw new Error("Base URL is not set.")}getRequestUrl(){return this.getRequestUrlInternal(this.clientOptions.httpOptions)}getHeaders(){if(this.clientOptions.httpOptions&&this.clientOptions.httpOptions.headers!==void 0)return this.clientOptions.httpOptions.headers;throw new Error("Headers are not set.")}getRequestUrlInternal(e){if(!e||e.baseUrl===void 0||e.apiVersion===void 0)throw new Error("HTTP options are not correctly set.");const o=[e.baseUrl.endsWith("/")?e.baseUrl.slice(0,-1):e.baseUrl];return e.apiVersion&&e.apiVersion!==""&&o.push(e.apiVersion),o.join("/")}getBaseResourcePath(){return`projects/${this.clientOptions.project}/locations/${this.clientOptions.location}`}getApiKey(){return this.clientOptions.apiKey}getWebsocketBaseUrl(){const e=this.getBaseUrl(),n=new URL(e);return n.protocol=n.protocol=="http:"?"ws":"wss",n.toString()}setBaseUrl(e){if(this.clientOptions.httpOptions)this.clientOptions.httpOptions.baseUrl=e;else throw new Error("HTTP options are not correctly set.")}constructUrl(e,n,o){const s=[this.getRequestUrlInternal(n)];return o&&s.push(this.getBaseResourcePath()),e!==""&&s.push(e),new URL(`${s.join("/")}`)}shouldPrependVertexProjectPath(e){return!(this.clientOptions.apiKey||!this.clientOptions.vertexai||e.path.startsWith("projects/")||e.httpMethod==="GET"&&e.path.startsWith("publishers/google/models"))}async request(e){let n=this.clientOptions.httpOptions;e.httpOptions&&(n=this.patchHttpOptions(this.clientOptions.httpOptions,e.httpOptions));const o=this.shouldPrependVertexProjectPath(e),s=this.constructUrl(e.path,n,o);if(e.queryParams)for(const[a,u]of Object.entries(e.queryParams))s.searchParams.append(a,String(u));let l={};if(e.httpMethod==="GET"){if(e.body&&e.body!=="{}")throw new Error("Request body should be empty for GET request, but got non empty request body")}else l.body=e.body;return l=await this.includeExtraHttpOptionsToRequestInit(l,n,s.toString(),e.abortSignal),this.unaryApiCall(s,l,e.httpMethod)}patchHttpOptions(e,n){const o=JSON.parse(JSON.stringify(e));for(const[s,l]of Object.entries(n))typeof l=="object"?o[s]=Object.assign(Object.assign({},o[s]),l):l!==void 0&&(o[s]=l);return o}async requestStream(e){let n=this.clientOptions.httpOptions;e.httpOptions&&(n=this.patchHttpOptions(this.clientOptions.httpOptions,e.httpOptions));const o=this.shouldPrependVertexProjectPath(e),s=this.constructUrl(e.path,n,o);(!s.searchParams.has("alt")||s.searchParams.get("alt")!=="sse")&&s.searchParams.set("alt","sse");let l={};return l.body=e.body,l=await this.includeExtraHttpOptionsToRequestInit(l,n,s.toString(),e.abortSignal),this.streamApiCall(s,l,e.httpMethod)}async includeExtraHttpOptionsToRequestInit(e,n,o,s){if(n&&n.timeout||s){const l=new AbortController,a=l.signal;if(n.timeout&&(n==null?void 0:n.timeout)>0){const u=setTimeout(()=>l.abort(),n.timeout);u&&typeof u.unref=="function"&&u.unref()}s&&s.addEventListener("abort",()=>{l.abort()}),e.signal=a}return n&&n.extraBody!==null&&Eu(e,n.extraBody),e.headers=await this.getHeadersInternal(n,o),e}async unaryApiCall(e,n,o){return this.apiCall(e.toString(),Object.assign(Object.assign({},n),{method:o})).then(async s=>(await to(s),new qe(s))).catch(s=>{throw s instanceof Error?s:new Error(JSON.stringify(s))})}async streamApiCall(e,n,o){return this.apiCall(e.toString(),Object.assign(Object.assign({},n),{method:o})).then(async s=>(await to(s),this.processStreamResponse(s))).catch(s=>{throw s instanceof Error?s:new Error(JSON.stringify(s))})}processStreamResponse(e){return K(this,arguments,function*(){var o;const s=(o=e==null?void 0:e.body)===null||o===void 0?void 0:o.getReader(),l=new TextDecoder("utf-8");if(!s)throw new Error("Response body is empty");try{let a="";const u="data:",c=[`
198
+
199
+ `,"\r\r",`\r
200
+ \r
201
+ `];for(;;){const{done:d,value:f}=yield M(s.read());if(d){if(a.trim().length>0)throw new Error("Incomplete JSON segment at the end");break}const h=l.decode(f,{stream:!0});try{const y=JSON.parse(h);if("error"in y){const _=JSON.parse(JSON.stringify(y.error)),T=_.status,E=_.code,C=`got status: ${T}. ${JSON.stringify(y)}`;if(E>=400&&E<600)throw new ve({message:C,status:E})}}catch(y){if(y.name==="ApiError")throw y}a+=h;let p=-1,m=0;for(;;){p=-1,m=0;for(const T of c){const E=a.indexOf(T);E!==-1&&(p===-1||E<p)&&(p=E,m=T.length)}if(p===-1)break;const y=a.substring(0,p);a=a.substring(p+m);const _=y.trim();if(_.startsWith(u)){const T=_.substring(u.length).trim();try{const E=new Response(T,{headers:e==null?void 0:e.headers,status:e==null?void 0:e.status,statusText:e==null?void 0:e.statusText});yield yield M(new qe(E))}catch(E){throw new Error(`exception parsing stream chunk ${T}. ${E}`)}}}}}finally{s.releaseLock()}})}async apiCall(e,n){return fetch(e,n).catch(o=>{throw new Error(`exception ${o} sending request`)})}getDefaultHeaders(){const e={},n=gu+" "+this.clientOptions.userAgentExtra;return e[mu]=n,e[Qe]=n,e[pu]="application/json",e}async getHeadersInternal(e,n){const o=new Headers;if(e&&e.headers){for(const[s,l]of Object.entries(e.headers))o.append(s,l);e.timeout&&e.timeout>0&&o.append(hu,String(Math.ceil(e.timeout/1e3)))}return await this.clientOptions.auth.addAuthHeaders(o,n),o}getFileName(e){var n;let o="";return typeof e=="string"&&(o=e.replace(/[/\\]+$/,""),o=(n=o.split(/[/\\]/).pop())!==null&&n!==void 0?n:""),o}async uploadFile(e,n){var o;const s={};n!=null&&(s.mimeType=n.mimeType,s.name=n.name,s.displayName=n.displayName),s.name&&!s.name.startsWith("files/")&&(s.name=`files/${s.name}`);const l=this.clientOptions.uploader,a=await l.stat(e);s.sizeBytes=String(a.size);const u=(o=n==null?void 0:n.mimeType)!==null&&o!==void 0?o:a.type;if(u===void 0||u==="")throw new Error("Can not determine mimeType. Please provide mimeType in the config.");s.mimeType=u;const c={file:s},d=this.getFileName(e),f=S("upload/v1beta/files",c._url),h=await this.fetchUploadUrl(f,s.sizeBytes,s.mimeType,d,c,n==null?void 0:n.httpOptions);return l.upload(e,h,this)}async uploadFileToFileSearchStore(e,n,o){var s;const l=this.clientOptions.uploader,a=await l.stat(n),u=String(a.size),c=(s=o==null?void 0:o.mimeType)!==null&&s!==void 0?s:a.type;if(c===void 0||c==="")throw new Error("Can not determine mimeType. Please provide mimeType in the config.");const d=`upload/v1beta/${e}:uploadToFileSearchStore`,f=this.getFileName(n),h={};o!=null&&eo(o,h);const p=await this.fetchUploadUrl(d,u,c,f,h,o==null?void 0:o.httpOptions);return l.uploadToFileSearchStore(n,p,this)}async downloadFile(e){await this.clientOptions.downloader.download(e,this)}async fetchUploadUrl(e,n,o,s,l,a){var u;let c={};a?c=a:c={apiVersion:"",headers:Object.assign({"Content-Type":"application/json","X-Goog-Upload-Protocol":"resumable","X-Goog-Upload-Command":"start","X-Goog-Upload-Header-Content-Length":`${n}`,"X-Goog-Upload-Header-Content-Type":`${o}`},s?{"X-Goog-Upload-File-Name":s}:{})};const d=await this.request({path:e,body:JSON.stringify(l),httpMethod:"POST",httpOptions:c});if(!d||!(d!=null&&d.headers))throw new Error("Server did not return an HttpResponse or the returned HttpResponse did not have headers.");const f=(u=d==null?void 0:d.headers)===null||u===void 0?void 0:u["x-goog-upload-url"];if(f===void 0)throw new Error("Failed to get upload url. Server did not return the x-google-upload-url in the headers");return f}}async function to(t){var e;if(t===void 0)throw new Error("response is undefined");if(!t.ok){const n=t.status;let o;!((e=t.headers.get("content-type"))===null||e===void 0)&&e.includes("application/json")?o=await t.json():o={error:{message:await t.text(),code:t.status,status:t.statusText}};const s=JSON.stringify(o);throw n>=400&&n<600?new ve({message:s,status:n}):new Error(s)}}function Eu(t,e){if(!e||Object.keys(e).length===0)return;if(t.body instanceof Blob){console.warn("includeExtraBodyToRequestInit: extraBody provided but current request body is a Blob. extraBody will be ignored as merging is not supported for Blob bodies.");return}let n={};if(typeof t.body=="string"&&t.body.length>0)try{const l=JSON.parse(t.body);if(typeof l=="object"&&l!==null&&!Array.isArray(l))n=l;else{console.warn("includeExtraBodyToRequestInit: Original request body is valid JSON but not a non-array object. Skip applying extraBody to the request body.");return}}catch{console.warn("includeExtraBodyToRequestInit: Original request body is not valid JSON. Skip applying extraBody to the request body.");return}function o(l,a){const u=Object.assign({},l);for(const c in a)if(Object.prototype.hasOwnProperty.call(a,c)){const d=a[c],f=u[c];d&&typeof d=="object"&&!Array.isArray(d)&&f&&typeof f=="object"&&!Array.isArray(f)?u[c]=o(f,d):(f&&d&&typeof f!=typeof d&&console.warn(`includeExtraBodyToRequestInit:deepMerge: Type mismatch for key "${c}". Original type: ${typeof f}, New type: ${typeof d}. Overwriting.`),u[c]=d)}return u}const s=o(n,e);t.body=JSON.stringify(s)}/**
202
+ * @license
203
+ * Copyright 2025 Google LLC
204
+ * SPDX-License-Identifier: Apache-2.0
205
+ */const Cu="mcp_used/unknown";let vu=!1;function no(t){for(const e of t)if(Iu(e)||typeof e=="object"&&"inputSchema"in e)return!0;return vu}function oo(t){var e;const n=(e=t[Qe])!==null&&e!==void 0?e:"";t[Qe]=(n+` ${Cu}`).trimStart()}function Iu(t){return t!==null&&typeof t=="object"&&t instanceof Ze}function Su(t){return K(this,arguments,function*(n,o=100){let s,l=0;for(;l<o;){const a=yield M(n.listTools({cursor:s}));for(const u of a.tools)yield yield M(u),l++;if(!a.nextCursor)break;s=a.nextCursor}})}class Ze{constructor(e=[],n){this.mcpTools=[],this.functionNameToMcpClient={},this.mcpClients=e,this.config=n}static create(e,n){return new Ze(e,n)}async initialize(){var e,n,o,s;if(this.mcpTools.length>0)return;const l={},a=[];for(const f of this.mcpClients)try{for(var u=!0,c=(n=void 0,z(Su(f))),d;d=await c.next(),e=d.done,!e;u=!0){s=d.value,u=!1;const h=s;a.push(h);const p=h.name;if(l[p])throw new Error(`Duplicate function name ${p} found in MCP tools. Please ensure function names are unique.`);l[p]=f}}catch(h){n={error:h}}finally{try{!u&&!e&&(o=c.return)&&await o.call(c)}finally{if(n)throw n.error}}this.mcpTools=a,this.functionNameToMcpClient=l}async tool(){return await this.initialize(),os(this.mcpTools,this.config)}async callTool(e){await this.initialize();const n=[];for(const o of e)if(o.name in this.functionNameToMcpClient){const s=this.functionNameToMcpClient[o.name];let l;this.config.timeout&&(l={timeout:this.config.timeout});const a=await s.callTool({name:o.name,arguments:o.args},void 0,l);n.push({functionResponse:{name:o.name,response:a.isError?{error:a}:a}})}return n}}/**
206
+ * @license
207
+ * Copyright 2025 Google LLC
208
+ * SPDX-License-Identifier: Apache-2.0
209
+ */async function xu(t,e,n){const o=new Oi;let s;n.data instanceof Blob?s=JSON.parse(await n.data.text()):s=JSON.parse(n.data),Object.assign(o,s),e(o)}class Au{constructor(e,n,o){this.apiClient=e,this.auth=n,this.webSocketFactory=o}async connect(e){var n,o;if(this.apiClient.isVertexAI())throw new Error("Live music is not supported for Vertex AI.");console.warn("Live music generation is experimental and may change in future versions.");const s=this.apiClient.getWebsocketBaseUrl(),l=this.apiClient.getApiVersion(),a=Mu(this.apiClient.getDefaultHeaders()),u=this.apiClient.getApiKey(),c=`${s}/ws/google.ai.generativelanguage.${l}.GenerativeService.BidiGenerateMusic?key=${u}`;let d=()=>{};const f=new Promise(v=>{d=v}),h=e.callbacks,p=function(){d({})},m=this.apiClient,y={onopen:p,onmessage:v=>{xu(m,h.onmessage,v)},onerror:(n=h==null?void 0:h.onerror)!==null&&n!==void 0?n:function(v){},onclose:(o=h==null?void 0:h.onclose)!==null&&o!==void 0?o:function(v){}},_=this.webSocketFactory.create(c,Nu(a),y);_.connect(),await f;const C={setup:{model:L(this.apiClient,e.model)}};return _.send(JSON.stringify(C)),new wu(_,this.apiClient)}}class wu{constructor(e,n){this.conn=e,this.apiClient=n}async setWeightedPrompts(e){if(!e.weightedPrompts||Object.keys(e.weightedPrompts).length===0)throw new Error("Weighted prompts must be set and contain at least one entry.");const n=el(e);this.conn.send(JSON.stringify({clientContent:n}))}async setMusicGenerationConfig(e){e.musicGenerationConfig||(e.musicGenerationConfig={});const n=jr(e);this.conn.send(JSON.stringify(n))}sendPlaybackControl(e){const n={playbackControl:e};this.conn.send(JSON.stringify(n))}play(){this.sendPlaybackControl(se.PLAY)}pause(){this.sendPlaybackControl(se.PAUSE)}stop(){this.sendPlaybackControl(se.STOP)}resetContext(){this.sendPlaybackControl(se.RESET_CONTEXT)}close(){this.conn.close()}}function Nu(t){const e={};return t.forEach((n,o)=>{e[o]=n}),e}function Mu(t){const e=new Headers;for(const[n,o]of Object.entries(t))e.append(n,o);return e}/**
210
+ * @license
211
+ * Copyright 2025 Google LLC
212
+ * SPDX-License-Identifier: Apache-2.0
213
+ */const Pu="FunctionResponse request must have an `id` field from the response of a ToolCall.FunctionalCalls in Google AI.";async function Ru(t,e,n){const o=new zi;let s;n.data instanceof Blob?s=await n.data.text():n.data instanceof ArrayBuffer?s=new TextDecoder().decode(n.data):s=n.data;const l=JSON.parse(s);if(t.isVertexAI()){const a=ol(l);Object.assign(o,a)}else Object.assign(o,l);e(o)}class ku{constructor(e,n,o){this.apiClient=e,this.auth=n,this.webSocketFactory=o,this.music=new Au(this.apiClient,this.auth,this.webSocketFactory)}async connect(e){var n,o,s,l,a,u;if(e.config&&e.config.httpOptions)throw new Error("The Live module does not support httpOptions at request-level in LiveConnectConfig yet. Please use the client-level httpOptions configuration instead.");const c=this.apiClient.getWebsocketBaseUrl(),d=this.apiClient.getApiVersion();let f;const h=this.apiClient.getHeaders();e.config&&e.config.tools&&no(e.config.tools)&&oo(h);const p=bu(h);if(this.apiClient.isVertexAI())f=`${c}/ws/google.cloud.aiplatform.${d}.LlmBidiService/BidiGenerateContent`,await this.auth.addAuthHeaders(p,f);else{const x=this.apiClient.getApiKey();let R="BidiGenerateContent",b="key";x!=null&&x.startsWith("auth_tokens/")&&(console.warn("Warning: Ephemeral token support is experimental and may change in future versions."),d!=="v1alpha"&&console.warn("Warning: The SDK's ephemeral token support is in v1alpha only. Please use const ai = new GoogleGenAI({apiKey: token.name, httpOptions: { apiVersion: 'v1alpha' }}); before session connection."),R="BidiGenerateContentConstrained",b="access_token"),f=`${c}/ws/google.ai.generativelanguage.${d}.GenerativeService.${R}?${b}=${x}`}let m=()=>{};const y=new Promise(x=>{m=x}),_=e.callbacks,T=function(){var x;(x=_==null?void 0:_.onopen)===null||x===void 0||x.call(_),m({})},E=this.apiClient,C={onopen:T,onmessage:x=>{Ru(E,_.onmessage,x)},onerror:(n=_==null?void 0:_.onerror)!==null&&n!==void 0?n:function(x){},onclose:(o=_==null?void 0:_.onclose)!==null&&o!==void 0?o:function(x){}},v=this.webSocketFactory.create(f,Lu(p),C);v.connect(),await y;let I=L(this.apiClient,e.model);if(this.apiClient.isVertexAI()&&I.startsWith("publishers/")){const x=this.apiClient.getProject(),R=this.apiClient.getLocation();I=`projects/${x}/locations/${R}/`+I}let A={};this.apiClient.isVertexAI()&&((s=e.config)===null||s===void 0?void 0:s.responseModalities)===void 0&&(e.config===void 0?e.config={responseModalities:[ye.AUDIO]}:e.config.responseModalities=[ye.AUDIO]),!((l=e.config)===null||l===void 0)&&l.generationConfig&&console.warn("Setting `LiveConnectConfig.generation_config` is deprecated, please set the fields on `LiveConnectConfig` directly. This will become an error in a future version (not before Q3 2025).");const P=(u=(a=e.config)===null||a===void 0?void 0:a.tools)!==null&&u!==void 0?u:[],N=[];for(const x of P)if(this.isCallableTool(x)){const R=x;N.push(await R.tool())}else N.push(x);N.length>0&&(e.config.tools=N);const U={model:I,config:e.config,callbacks:e.callbacks};return this.apiClient.isVertexAI()?A=Zr(this.apiClient,U):A=Qr(this.apiClient,U),delete A.config,v.send(JSON.stringify(A)),new Uu(v,this.apiClient)}isCallableTool(e){return"callTool"in e&&typeof e.callTool=="function"}}const Du={turnComplete:!0};class Uu{constructor(e,n){this.conn=e,this.apiClient=n}tLiveClientContent(e,n){if(n.turns!==null&&n.turns!==void 0){let o=[];try{o=W(n.turns),e.isVertexAI()||(o=o.map(s=>Se(s)))}catch{throw new Error(`Failed to parse client content "turns", type: '${typeof n.turns}'`)}return{clientContent:{turns:o,turnComplete:n.turnComplete}}}return{clientContent:{turnComplete:n.turnComplete}}}tLiveClienttToolResponse(e,n){let o=[];if(n.functionResponses==null)throw new Error("functionResponses is required.");if(Array.isArray(n.functionResponses)?o=n.functionResponses:o=[n.functionResponses],o.length===0)throw new Error("functionResponses is required.");for(const l of o){if(typeof l!="object"||l===null||!("name"in l)||!("response"in l))throw new Error(`Could not parse function response, type '${typeof l}'.`);if(!e.isVertexAI()&&!("id"in l))throw new Error(Pu)}return{toolResponse:{functionResponses:o}}}sendClientContent(e){e=Object.assign(Object.assign({},Du),e);const n=this.tLiveClientContent(this.apiClient,e);this.conn.send(JSON.stringify(n))}sendRealtimeInput(e){let n={};this.apiClient.isVertexAI()?n={realtimeInput:nl(e)}:n={realtimeInput:tl(e)},this.conn.send(JSON.stringify(n))}sendToolResponse(e){if(e.functionResponses==null)throw new Error("Tool response parameters are required.");const n=this.tLiveClienttToolResponse(this.apiClient,e);this.conn.send(JSON.stringify(n))}close(){this.conn.close()}}function Lu(t){const e={};return t.forEach((n,o)=>{e[o]=n}),e}function bu(t){const e=new Headers;for(const[n,o]of Object.entries(t))e.append(n,o);return e}/**
214
+ * @license
215
+ * Copyright 2025 Google LLC
216
+ * SPDX-License-Identifier: Apache-2.0
217
+ */const io=10;function so(t){var e,n,o;if(!((e=t==null?void 0:t.automaticFunctionCalling)===null||e===void 0)&&e.disable)return!0;let s=!1;for(const a of(n=t==null?void 0:t.tools)!==null&&n!==void 0?n:[])if(de(a)){s=!0;break}if(!s)return!0;const l=(o=t==null?void 0:t.automaticFunctionCalling)===null||o===void 0?void 0:o.maximumRemoteCalls;return l&&(l<0||!Number.isInteger(l))||l==0?(console.warn("Invalid maximumRemoteCalls value provided for automatic function calling. Disabled automatic function calling. Please provide a valid integer value greater than 0. maximumRemoteCalls provided:",l),!0):!1}function de(t){return"callTool"in t&&typeof t.callTool=="function"}function Fu(t){var e,n,o;return(o=(n=(e=t.config)===null||e===void 0?void 0:e.tools)===null||n===void 0?void 0:n.some(s=>de(s)))!==null&&o!==void 0?o:!1}function ro(t){var e;const n=[];return!((e=t==null?void 0:t.config)===null||e===void 0)&&e.tools&&t.config.tools.forEach((o,s)=>{if(de(o))return;const l=o;l.functionDeclarations&&l.functionDeclarations.length>0&&n.push(s)}),n}function lo(t){var e;return!(!((e=t==null?void 0:t.automaticFunctionCalling)===null||e===void 0)&&e.ignoreCallHistory)}/**
218
+ * @license
219
+ * Copyright 2025 Google LLC
220
+ * SPDX-License-Identifier: Apache-2.0
221
+ */class Gu extends Q{constructor(e){super(),this.apiClient=e,this.generateContent=async n=>{var o,s,l,a,u;const c=await this.processParamsMaybeAddMcpUsage(n);if(this.maybeMoveToResponseJsonSchem(n),!Fu(n)||so(n.config))return await this.generateContentInternal(c);const d=ro(n);if(d.length>0){const _=d.map(T=>`tools[${T}]`).join(", ");throw new Error(`Automatic function calling with CallableTools (or MCP objects) and basic FunctionDeclarations is not yet supported. Incompatible tools found at ${_}.`)}let f,h;const p=W(c.contents),m=(l=(s=(o=c.config)===null||o===void 0?void 0:o.automaticFunctionCalling)===null||s===void 0?void 0:s.maximumRemoteCalls)!==null&&l!==void 0?l:io;let y=0;for(;y<m&&(f=await this.generateContentInternal(c),!(!f.functionCalls||f.functionCalls.length===0));){const _=f.candidates[0].content,T=[];for(const E of(u=(a=n.config)===null||a===void 0?void 0:a.tools)!==null&&u!==void 0?u:[])if(de(E)){const v=await E.callTool(f.functionCalls);T.push(...v)}y++,h={role:"user",parts:T},c.contents=W(c.contents),c.contents.push(_),c.contents.push(h),lo(c.config)&&(p.push(_),p.push(h))}return lo(c.config)&&(f.automaticFunctionCallingHistory=p),f},this.generateContentStream=async n=>{var o,s,l,a,u;if(this.maybeMoveToResponseJsonSchem(n),so(n.config)){const h=await this.processParamsMaybeAddMcpUsage(n);return await this.generateContentStreamInternal(h)}const c=ro(n);if(c.length>0){const h=c.map(p=>`tools[${p}]`).join(", ");throw new Error(`Incompatible tools found at ${h}. Automatic function calling with CallableTools (or MCP objects) and basic FunctionDeclarations" is not yet supported.`)}const d=(l=(s=(o=n==null?void 0:n.config)===null||o===void 0?void 0:o.toolConfig)===null||s===void 0?void 0:s.functionCallingConfig)===null||l===void 0?void 0:l.streamFunctionCallArguments,f=(u=(a=n==null?void 0:n.config)===null||a===void 0?void 0:a.automaticFunctionCalling)===null||u===void 0?void 0:u.disable;if(d&&!f)throw new Error("Running in streaming mode with 'streamFunctionCallArguments' enabled, this feature is not compatible with automatic function calling (AFC). Please set 'config.automaticFunctionCalling.disable' to true to disable AFC or leave 'config.toolConfig.functionCallingConfig.streamFunctionCallArguments' to be undefined or set to false to disable streaming function call arguments feature.");return await this.processAfcStream(n)},this.generateImages=async n=>await this.generateImagesInternal(n).then(o=>{var s;let l;const a=[];if(o!=null&&o.generatedImages)for(const c of o.generatedImages)c&&(c!=null&&c.safetyAttributes)&&((s=c==null?void 0:c.safetyAttributes)===null||s===void 0?void 0:s.contentType)==="Positive Prompt"?l=c==null?void 0:c.safetyAttributes:a.push(c);let u;return l?u={generatedImages:a,positivePromptSafetyAttributes:l,sdkHttpResponse:o.sdkHttpResponse}:u={generatedImages:a,sdkHttpResponse:o.sdkHttpResponse},u}),this.list=async n=>{var o;const a={config:Object.assign(Object.assign({},{queryBase:!0}),n==null?void 0:n.config)};if(this.apiClient.isVertexAI()&&!a.config.queryBase){if(!((o=a.config)===null||o===void 0)&&o.filter)throw new Error("Filtering tuned models list for Vertex AI is not currently supported");a.config.filter="labels.tune-type:*"}return new oe(j.PAGED_ITEM_MODELS,u=>this.listInternal(u),await this.listInternal(a),a)},this.editImage=async n=>{const o={model:n.model,prompt:n.prompt,referenceImages:[],config:n.config};return n.referenceImages&&n.referenceImages&&(o.referenceImages=n.referenceImages.map(s=>s.toReferenceImageAPI())),await this.editImageInternal(o)},this.upscaleImage=async n=>{let o={numberOfImages:1,mode:"upscale"};n.config&&(o=Object.assign(Object.assign({},o),n.config));const s={model:n.model,image:n.image,upscaleFactor:n.upscaleFactor,config:o};return await this.upscaleImageInternal(s)},this.generateVideos=async n=>{var o,s,l,a,u,c;if((n.prompt||n.image||n.video)&&n.source)throw new Error("Source and prompt/image/video are mutually exclusive. Please only use source.");return this.apiClient.isVertexAI()||(!((o=n.video)===null||o===void 0)&&o.uri&&(!((s=n.video)===null||s===void 0)&&s.videoBytes)?n.video={uri:n.video.uri,mimeType:n.video.mimeType}:!((a=(l=n.source)===null||l===void 0?void 0:l.video)===null||a===void 0)&&a.uri&&(!((c=(u=n.source)===null||u===void 0?void 0:u.video)===null||c===void 0)&&c.videoBytes)&&(n.source.video={uri:n.source.video.uri,mimeType:n.source.video.mimeType})),await this.generateVideosInternal(n)}}maybeMoveToResponseJsonSchem(e){e.config&&e.config.responseSchema&&(e.config.responseJsonSchema||Object.keys(e.config.responseSchema).includes("$schema")&&(e.config.responseJsonSchema=e.config.responseSchema,delete e.config.responseSchema))}async processParamsMaybeAddMcpUsage(e){var n,o,s;const l=(n=e.config)===null||n===void 0?void 0:n.tools;if(!l)return e;const a=await Promise.all(l.map(async c=>de(c)?await c.tool():c)),u={model:e.model,contents:e.contents,config:Object.assign(Object.assign({},e.config),{tools:a})};if(u.config.tools=a,e.config&&e.config.tools&&no(e.config.tools)){const c=(s=(o=e.config.httpOptions)===null||o===void 0?void 0:o.headers)!==null&&s!==void 0?s:{};let d=Object.assign({},c);Object.keys(d).length===0&&(d=this.apiClient.getDefaultHeaders()),oo(d),u.config.httpOptions=Object.assign(Object.assign({},e.config.httpOptions),{headers:d})}return u}async initAfcToolsMap(e){var n,o,s;const l=new Map;for(const a of(o=(n=e.config)===null||n===void 0?void 0:n.tools)!==null&&o!==void 0?o:[])if(de(a)){const u=a,c=await u.tool();for(const d of(s=c.functionDeclarations)!==null&&s!==void 0?s:[]){if(!d.name)throw new Error("Function declaration name is required.");if(l.has(d.name))throw new Error(`Duplicate tool declaration name: ${d.name}`);l.set(d.name,u)}}return l}async processAfcStream(e){var n,o,s;const l=(s=(o=(n=e.config)===null||n===void 0?void 0:n.automaticFunctionCalling)===null||o===void 0?void 0:o.maximumRemoteCalls)!==null&&s!==void 0?s:io;let a=!1,u=0;const c=await this.initAfcToolsMap(e);return function(d,f,h){return K(this,arguments,function*(){for(var p,m,y,_,T,E;u<l;){a&&(u++,a=!1);const A=yield M(d.processParamsMaybeAddMcpUsage(h)),P=yield M(d.generateContentStreamInternal(A)),N=[],U=[];try{for(var C=!0,v=(m=void 0,z(P)),I;I=yield M(v.next()),p=I.done,!p;C=!0){_=I.value,C=!1;const x=_;if(yield yield M(x),x.candidates&&(!((T=x.candidates[0])===null||T===void 0)&&T.content)){U.push(x.candidates[0].content);for(const R of(E=x.candidates[0].content.parts)!==null&&E!==void 0?E:[])if(u<l&&R.functionCall){if(!R.functionCall.name)throw new Error("Function call name was not returned by the model.");if(f.has(R.functionCall.name)){const b=yield M(f.get(R.functionCall.name).callTool([R.functionCall]));N.push(...b)}else throw new Error(`Automatic function calling was requested, but not all the tools the model used implement the CallableTool interface. Available tools: ${f.keys()}, mising tool: ${R.functionCall.name}`)}}}}catch(x){m={error:x}}finally{try{!C&&!p&&(y=v.return)&&(yield M(y.call(v)))}finally{if(m)throw m.error}}if(N.length>0){a=!0;const x=new pe;x.candidates=[{content:{role:"user",parts:N}}],yield yield M(x);const R=[];R.push(...U),R.push({role:"user",parts:N});const b=W(h.contents).concat(R);h.contents=b}else break}})}(this,c,e)}async generateContentInternal(e){var n,o,s,l;let a,u="",c={};if(this.apiClient.isVertexAI()){const d=Wn(this.apiClient,e);return u=S("{model}:generateContent",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(f=>f.json().then(h=>{const p=h;return p.sdkHttpResponse={headers:f.headers},p})),a.then(f=>{const h=Kn(f),p=new pe;return Object.assign(p,h),p})}else{const d=$n(this.apiClient,e);return u=S("{model}:generateContent",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(s=e.config)===null||s===void 0?void 0:s.httpOptions,abortSignal:(l=e.config)===null||l===void 0?void 0:l.abortSignal}).then(f=>f.json().then(h=>{const p=h;return p.sdkHttpResponse={headers:f.headers},p})),a.then(f=>{const h=Yn(f),p=new pe;return Object.assign(p,h),p})}}async generateContentStreamInternal(e){var n,o,s,l;let a,u="",c={};if(this.apiClient.isVertexAI()){const d=Wn(this.apiClient,e);return u=S("{model}:streamGenerateContent?alt=sse",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.requestStream({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}),a.then(function(h){return K(this,arguments,function*(){var p,m,y,_;try{for(var T=!0,E=z(h),C;C=yield M(E.next()),p=C.done,!p;T=!0){_=C.value,T=!1;const v=_,I=Kn(yield M(v.json()));I.sdkHttpResponse={headers:v.headers};const A=new pe;Object.assign(A,I),yield yield M(A)}}catch(v){m={error:v}}finally{try{!T&&!p&&(y=E.return)&&(yield M(y.call(E)))}finally{if(m)throw m.error}}})})}else{const d=$n(this.apiClient,e);return u=S("{model}:streamGenerateContent?alt=sse",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.requestStream({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(s=e.config)===null||s===void 0?void 0:s.httpOptions,abortSignal:(l=e.config)===null||l===void 0?void 0:l.abortSignal}),a.then(function(h){return K(this,arguments,function*(){var p,m,y,_;try{for(var T=!0,E=z(h),C;C=yield M(E.next()),p=C.done,!p;T=!0){_=C.value,T=!1;const v=_,I=Yn(yield M(v.json()));I.sdkHttpResponse={headers:v.headers};const A=new pe;Object.assign(A,I),yield yield M(A)}}catch(v){m={error:v}}finally{try{!T&&!p&&(y=E.return)&&(yield M(y.call(E)))}finally{if(m)throw m.error}}})})}}async embedContent(e){var n,o,s,l;let a,u="",c={};if(this.apiClient.isVertexAI()){const d=Dl(this.apiClient,e);return u=S("{model}:predict",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(f=>f.json().then(h=>{const p=h;return p.sdkHttpResponse={headers:f.headers},p})),a.then(f=>{const h=Ll(f),p=new pn;return Object.assign(p,h),p})}else{const d=kl(this.apiClient,e);return u=S("{model}:batchEmbedContents",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(s=e.config)===null||s===void 0?void 0:s.httpOptions,abortSignal:(l=e.config)===null||l===void 0?void 0:l.abortSignal}).then(f=>f.json().then(h=>{const p=h;return p.sdkHttpResponse={headers:f.headers},p})),a.then(f=>{const h=Ul(f),p=new pn;return Object.assign(p,h),p})}}async generateImagesInternal(e){var n,o,s,l;let a,u="",c={};if(this.apiClient.isVertexAI()){const d=Yl(this.apiClient,e);return u=S("{model}:predict",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(f=>f.json().then(h=>{const p=h;return p.sdkHttpResponse={headers:f.headers},p})),a.then(f=>{const h=zl(f),p=new hn;return Object.assign(p,h),p})}else{const d=Wl(this.apiClient,e);return u=S("{model}:predict",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(s=e.config)===null||s===void 0?void 0:s.httpOptions,abortSignal:(l=e.config)===null||l===void 0?void 0:l.abortSignal}).then(f=>f.json().then(h=>{const p=h;return p.sdkHttpResponse={headers:f.headers},p})),a.then(f=>{const h=Kl(f),p=new hn;return Object.assign(p,h),p})}}async editImageInternal(e){var n,o;let s,l="",a={};if(this.apiClient.isVertexAI()){const u=Nl(this.apiClient,e);return l=S("{model}:predict",u._url),a=u._query,delete u._url,delete u._query,s=this.apiClient.request({path:l,queryParams:a,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(c=>c.json().then(d=>{const f=d;return f.sdkHttpResponse={headers:c.headers},f})),s.then(c=>{const d=Ml(c),f=new Fi;return Object.assign(f,d),f})}else throw new Error("This method is only supported by the Vertex AI.")}async upscaleImageInternal(e){var n,o;let s,l="",a={};if(this.apiClient.isVertexAI()){const u=Ya(this.apiClient,e);return l=S("{model}:predict",u._url),a=u._query,delete u._url,delete u._query,s=this.apiClient.request({path:l,queryParams:a,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(c=>c.json().then(d=>{const f=d;return f.sdkHttpResponse={headers:c.headers},f})),s.then(c=>{const d=Ka(c),f=new Gi;return Object.assign(f,d),f})}else throw new Error("This method is only supported by the Vertex AI.")}async recontextImage(e){var n,o;let s,l="",a={};if(this.apiClient.isVertexAI()){const u=wa(this.apiClient,e);return l=S("{model}:predict",u._url),a=u._query,delete u._url,delete u._query,s=this.apiClient.request({path:l,queryParams:a,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(c=>c.json()),s.then(c=>{const d=Na(c),f=new Vi;return Object.assign(f,d),f})}else throw new Error("This method is only supported by the Vertex AI.")}async segmentImage(e){var n,o;let s,l="",a={};if(this.apiClient.isVertexAI()){const u=Ua(this.apiClient,e);return l=S("{model}:predict",u._url),a=u._query,delete u._url,delete u._query,s=this.apiClient.request({path:l,queryParams:a,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(c=>c.json()),s.then(c=>{const d=La(c),f=new qi;return Object.assign(f,d),f})}else throw new Error("This method is only supported by the Vertex AI.")}async get(e){var n,o,s,l;let a,u="",c={};if(this.apiClient.isVertexAI()){const d=ca(this.apiClient,e);return u=S("{name}",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(f=>f.json()),a.then(f=>Xe(f))}else{const d=da(this.apiClient,e);return u=S("{name}",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"GET",httpOptions:(s=e.config)===null||s===void 0?void 0:s.httpOptions,abortSignal:(l=e.config)===null||l===void 0?void 0:l.abortSignal}).then(f=>f.json()),a.then(f=>Oe(f))}}async listInternal(e){var n,o,s,l;let a,u="",c={};if(this.apiClient.isVertexAI()){const d=Ea(this.apiClient,e);return u=S("{models_url}",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(f=>f.json().then(h=>{const p=h;return p.sdkHttpResponse={headers:f.headers},p})),a.then(f=>{const h=va(f),p=new mn;return Object.assign(p,h),p})}else{const d=_a(this.apiClient,e);return u=S("{models_url}",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"GET",httpOptions:(s=e.config)===null||s===void 0?void 0:s.httpOptions,abortSignal:(l=e.config)===null||l===void 0?void 0:l.abortSignal}).then(f=>f.json().then(h=>{const p=h;return p.sdkHttpResponse={headers:f.headers},p})),a.then(f=>{const h=Ca(f),p=new mn;return Object.assign(p,h),p})}}async update(e){var n,o,s,l;let a,u="",c={};if(this.apiClient.isVertexAI()){const d=$a(this.apiClient,e);return u=S("{model}",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"PATCH",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(f=>f.json()),a.then(f=>Xe(f))}else{const d=Ja(this.apiClient,e);return u=S("{name}",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"PATCH",httpOptions:(s=e.config)===null||s===void 0?void 0:s.httpOptions,abortSignal:(l=e.config)===null||l===void 0?void 0:l.abortSignal}).then(f=>f.json()),a.then(f=>Oe(f))}}async delete(e){var n,o,s,l;let a,u="",c={};if(this.apiClient.isVertexAI()){const d=Sl(this.apiClient,e);return u=S("{name}",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"DELETE",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(f=>f.json().then(h=>{const p=h;return p.sdkHttpResponse={headers:f.headers},p})),a.then(f=>{const h=Al(f),p=new gn;return Object.assign(p,h),p})}else{const d=Il(this.apiClient,e);return u=S("{name}",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"DELETE",httpOptions:(s=e.config)===null||s===void 0?void 0:s.httpOptions,abortSignal:(l=e.config)===null||l===void 0?void 0:l.abortSignal}).then(f=>f.json().then(h=>{const p=h;return p.sdkHttpResponse={headers:f.headers},p})),a.then(f=>{const h=xl(f),p=new gn;return Object.assign(p,h),p})}}async countTokens(e){var n,o,s,l;let a,u="",c={};if(this.apiClient.isVertexAI()){const d=El(this.apiClient,e);return u=S("{model}:countTokens",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(f=>f.json().then(h=>{const p=h;return p.sdkHttpResponse={headers:f.headers},p})),a.then(f=>{const h=vl(f),p=new yn;return Object.assign(p,h),p})}else{const d=_l(this.apiClient,e);return u=S("{model}:countTokens",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(s=e.config)===null||s===void 0?void 0:s.httpOptions,abortSignal:(l=e.config)===null||l===void 0?void 0:l.abortSignal}).then(f=>f.json().then(h=>{const p=h;return p.sdkHttpResponse={headers:f.headers},p})),a.then(f=>{const h=Cl(f),p=new yn;return Object.assign(p,h),p})}}async computeTokens(e){var n,o;let s,l="",a={};if(this.apiClient.isVertexAI()){const u=fl(this.apiClient,e);return l=S("{model}:computeTokens",u._url),a=u._query,delete u._url,delete u._query,s=this.apiClient.request({path:l,queryParams:a,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(c=>c.json().then(d=>{const f=d;return f.sdkHttpResponse={headers:c.headers},f})),s.then(c=>{const d=pl(c),f=new Hi;return Object.assign(f,d),f})}else throw new Error("This method is only supported by the Vertex AI.")}async generateVideosInternal(e){var n,o,s,l;let a,u="",c={};if(this.apiClient.isVertexAI()){const d=ea(this.apiClient,e);return u=S("{model}:predictLongRunning",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(f=>f.json()),a.then(f=>{const h=Zl(f),p=new Te;return Object.assign(p,h),p})}else{const d=jl(this.apiClient,e);return u=S("{model}:predictLongRunning",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(s=e.config)===null||s===void 0?void 0:s.httpOptions,abortSignal:(l=e.config)===null||l===void 0?void 0:l.abortSignal}).then(f=>f.json()),a.then(f=>{const h=Ql(f),p=new Te;return Object.assign(p,h),p})}}}/**
222
+ * @license
223
+ * Copyright 2025 Google LLC
224
+ * SPDX-License-Identifier: Apache-2.0
225
+ */class Vu extends Q{constructor(e){super(),this.apiClient=e}async getVideosOperation(e){const n=e.operation,o=e.config;if(n.name===void 0||n.name==="")throw new Error("Operation name is required.");if(this.apiClient.isVertexAI()){const s=n.name.split("/operations/")[0];let l;o&&"httpOptions"in o&&(l=o.httpOptions);const a=await this.fetchPredictVideosOperationInternal({operationName:n.name,resourceName:s,config:{httpOptions:l}});return n._fromAPIResponse({apiResponse:a,_isVertexAI:!0})}else{const s=await this.getVideosOperationInternal({operationName:n.name,config:o});return n._fromAPIResponse({apiResponse:s,_isVertexAI:!1})}}async get(e){const n=e.operation,o=e.config;if(n.name===void 0||n.name==="")throw new Error("Operation name is required.");if(this.apiClient.isVertexAI()){const s=n.name.split("/operations/")[0];let l;o&&"httpOptions"in o&&(l=o.httpOptions);const a=await this.fetchPredictVideosOperationInternal({operationName:n.name,resourceName:s,config:{httpOptions:l}});return n._fromAPIResponse({apiResponse:a,_isVertexAI:!0})}else{const s=await this.getVideosOperationInternal({operationName:n.name,config:o});return n._fromAPIResponse({apiResponse:s,_isVertexAI:!1})}}async getVideosOperationInternal(e){var n,o,s,l;let a,u="",c={};if(this.apiClient.isVertexAI()){const d=Ri(e);return u=S("{operationName}",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(f=>f.json()),a}else{const d=Pi(e);return u=S("{operationName}",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"GET",httpOptions:(s=e.config)===null||s===void 0?void 0:s.httpOptions,abortSignal:(l=e.config)===null||l===void 0?void 0:l.abortSignal}).then(f=>f.json()),a}}async fetchPredictVideosOperationInternal(e){var n,o;let s,l="",a={};if(this.apiClient.isVertexAI()){const u=Ii(e);return l=S("{resourceName}:fetchPredictOperation",u._url),a=u._query,delete u._url,delete u._query,s=this.apiClient.request({path:l,queryParams:a,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(c=>c.json()),s}else throw new Error("This method is only supported by the Vertex AI.")}}/**
226
+ * @license
227
+ * Copyright 2025 Google LLC
228
+ * SPDX-License-Identifier: Apache-2.0
229
+ */function qu(t){const e={},n=i(t,["data"]);if(n!=null&&r(e,["data"],n),i(t,["displayName"])!==void 0)throw new Error("displayName parameter is not supported in Gemini API.");const o=i(t,["mimeType"]);return o!=null&&r(e,["mimeType"],o),e}function Hu(t){const e={},n=i(t,["parts"]);if(n!=null){let s=n;Array.isArray(s)&&(s=s.map(l=>Xu(l))),r(e,["parts"],s)}const o=i(t,["role"]);return o!=null&&r(e,["role"],o),e}function Bu(t,e,n){const o={},s=i(e,["expireTime"]);n!==void 0&&s!=null&&r(n,["expireTime"],s);const l=i(e,["newSessionExpireTime"]);n!==void 0&&l!=null&&r(n,["newSessionExpireTime"],l);const a=i(e,["uses"]);n!==void 0&&a!=null&&r(n,["uses"],a);const u=i(e,["liveConnectConstraints"]);n!==void 0&&u!=null&&r(n,["bidiGenerateContentSetup"],Ou(t,u));const c=i(e,["lockAdditionalFields"]);return n!==void 0&&c!=null&&r(n,["fieldMask"],c),o}function Ju(t,e){const n={},o=i(e,["config"]);return o!=null&&r(n,["config"],Bu(t,o,n)),n}function $u(t){const e={};if(i(t,["displayName"])!==void 0)throw new Error("displayName parameter is not supported in Gemini API.");const n=i(t,["fileUri"]);n!=null&&r(e,["fileUri"],n);const o=i(t,["mimeType"]);return o!=null&&r(e,["mimeType"],o),e}function Wu(t){const e={},n=i(t,["id"]);n!=null&&r(e,["id"],n);const o=i(t,["args"]);o!=null&&r(e,["args"],o);const s=i(t,["name"]);if(s!=null&&r(e,["name"],s),i(t,["partialArgs"])!==void 0)throw new Error("partialArgs parameter is not supported in Gemini API.");if(i(t,["willContinue"])!==void 0)throw new Error("willContinue parameter is not supported in Gemini API.");return e}function Yu(t){const e={};if(i(t,["authConfig"])!==void 0)throw new Error("authConfig parameter is not supported in Gemini API.");const n=i(t,["enableWidget"]);return n!=null&&r(e,["enableWidget"],n),e}function Ku(t){const e={};if(i(t,["excludeDomains"])!==void 0)throw new Error("excludeDomains parameter is not supported in Gemini API.");if(i(t,["blockingConfidence"])!==void 0)throw new Error("blockingConfidence parameter is not supported in Gemini API.");const n=i(t,["timeRangeFilter"]);return n!=null&&r(e,["timeRangeFilter"],n),e}function zu(t,e){const n={},o=i(t,["generationConfig"]);e!==void 0&&o!=null&&r(e,["setup","generationConfig"],o);const s=i(t,["responseModalities"]);e!==void 0&&s!=null&&r(e,["setup","generationConfig","responseModalities"],s);const l=i(t,["temperature"]);e!==void 0&&l!=null&&r(e,["setup","generationConfig","temperature"],l);const a=i(t,["topP"]);e!==void 0&&a!=null&&r(e,["setup","generationConfig","topP"],a);const u=i(t,["topK"]);e!==void 0&&u!=null&&r(e,["setup","generationConfig","topK"],u);const c=i(t,["maxOutputTokens"]);e!==void 0&&c!=null&&r(e,["setup","generationConfig","maxOutputTokens"],c);const d=i(t,["mediaResolution"]);e!==void 0&&d!=null&&r(e,["setup","generationConfig","mediaResolution"],d);const f=i(t,["seed"]);e!==void 0&&f!=null&&r(e,["setup","generationConfig","seed"],f);const h=i(t,["speechConfig"]);e!==void 0&&h!=null&&r(e,["setup","generationConfig","speechConfig"],Ke(h));const p=i(t,["thinkingConfig"]);e!==void 0&&p!=null&&r(e,["setup","generationConfig","thinkingConfig"],p);const m=i(t,["enableAffectiveDialog"]);e!==void 0&&m!=null&&r(e,["setup","generationConfig","enableAffectiveDialog"],m);const y=i(t,["systemInstruction"]);e!==void 0&&y!=null&&r(e,["setup","systemInstruction"],Hu(q(y)));const _=i(t,["tools"]);if(e!==void 0&&_!=null){let P=ae(_);Array.isArray(P)&&(P=P.map(N=>Zu(le(N)))),r(e,["setup","tools"],P)}const T=i(t,["sessionResumption"]);e!==void 0&&T!=null&&r(e,["setup","sessionResumption"],Qu(T));const E=i(t,["inputAudioTranscription"]);e!==void 0&&E!=null&&r(e,["setup","inputAudioTranscription"],E);const C=i(t,["outputAudioTranscription"]);e!==void 0&&C!=null&&r(e,["setup","outputAudioTranscription"],C);const v=i(t,["realtimeInputConfig"]);e!==void 0&&v!=null&&r(e,["setup","realtimeInputConfig"],v);const I=i(t,["contextWindowCompression"]);e!==void 0&&I!=null&&r(e,["setup","contextWindowCompression"],I);const A=i(t,["proactivity"]);if(e!==void 0&&A!=null&&r(e,["setup","proactivity"],A),i(t,["explicitVadSignal"])!==void 0)throw new Error("explicitVadSignal parameter is not supported in Gemini API.");return n}function Ou(t,e){const n={},o=i(e,["model"]);o!=null&&r(n,["setup","model"],L(t,o));const s=i(e,["config"]);return s!=null&&r(n,["config"],zu(s,n)),n}function Xu(t){const e={},n=i(t,["mediaResolution"]);n!=null&&r(e,["mediaResolution"],n);const o=i(t,["codeExecutionResult"]);o!=null&&r(e,["codeExecutionResult"],o);const s=i(t,["executableCode"]);s!=null&&r(e,["executableCode"],s);const l=i(t,["fileData"]);l!=null&&r(e,["fileData"],$u(l));const a=i(t,["functionCall"]);a!=null&&r(e,["functionCall"],Wu(a));const u=i(t,["functionResponse"]);u!=null&&r(e,["functionResponse"],u);const c=i(t,["inlineData"]);c!=null&&r(e,["inlineData"],qu(c));const d=i(t,["text"]);d!=null&&r(e,["text"],d);const f=i(t,["thought"]);f!=null&&r(e,["thought"],f);const h=i(t,["thoughtSignature"]);h!=null&&r(e,["thoughtSignature"],h);const p=i(t,["videoMetadata"]);return p!=null&&r(e,["videoMetadata"],p),e}function Qu(t){const e={},n=i(t,["handle"]);if(n!=null&&r(e,["handle"],n),i(t,["transparent"])!==void 0)throw new Error("transparent parameter is not supported in Gemini API.");return e}function Zu(t){const e={},n=i(t,["functionDeclarations"]);if(n!=null){let f=n;Array.isArray(f)&&(f=f.map(h=>h)),r(e,["functionDeclarations"],f)}if(i(t,["retrieval"])!==void 0)throw new Error("retrieval parameter is not supported in Gemini API.");const o=i(t,["googleSearchRetrieval"]);o!=null&&r(e,["googleSearchRetrieval"],o);const s=i(t,["computerUse"]);s!=null&&r(e,["computerUse"],s);const l=i(t,["fileSearch"]);l!=null&&r(e,["fileSearch"],l);const a=i(t,["codeExecution"]);if(a!=null&&r(e,["codeExecution"],a),i(t,["enterpriseWebSearch"])!==void 0)throw new Error("enterpriseWebSearch parameter is not supported in Gemini API.");const u=i(t,["googleMaps"]);u!=null&&r(e,["googleMaps"],Yu(u));const c=i(t,["googleSearch"]);c!=null&&r(e,["googleSearch"],Ku(c));const d=i(t,["urlContext"]);return d!=null&&r(e,["urlContext"],d),e}/**
230
+ * @license
231
+ * Copyright 2025 Google LLC
232
+ * SPDX-License-Identifier: Apache-2.0
233
+ */function ju(t){const e=[];for(const n in t)if(Object.prototype.hasOwnProperty.call(t,n)){const o=t[n];if(typeof o=="object"&&o!=null&&Object.keys(o).length>0){const s=Object.keys(o).map(l=>`${n}.${l}`);e.push(...s)}else e.push(n)}return e.join(",")}function ed(t,e){let n=null;const o=t.bidiGenerateContentSetup;if(typeof o=="object"&&o!==null&&"setup"in o){const l=o.setup;typeof l=="object"&&l!==null?(t.bidiGenerateContentSetup=l,n=l):delete t.bidiGenerateContentSetup}else o!==void 0&&delete t.bidiGenerateContentSetup;const s=t.fieldMask;if(n){const l=ju(n);if(Array.isArray(e==null?void 0:e.lockAdditionalFields)&&(e==null?void 0:e.lockAdditionalFields.length)===0)l?t.fieldMask=l:delete t.fieldMask;else if(e!=null&&e.lockAdditionalFields&&e.lockAdditionalFields.length>0&&s!==null&&Array.isArray(s)&&s.length>0){const a=["temperature","topK","topP","maxOutputTokens","responseModalities","seed","speechConfig"];let u=[];s.length>0&&(u=s.map(d=>a.includes(d)?`generationConfig.${d}`:d));const c=[];l&&c.push(l),u.length>0&&c.push(...u),c.length>0?t.fieldMask=c.join(","):delete t.fieldMask}else delete t.fieldMask}else s!==null&&Array.isArray(s)&&s.length>0?t.fieldMask=s.join(","):delete t.fieldMask;return t}class td extends Q{constructor(e){super(),this.apiClient=e}async create(e){var n,o;let s,l="",a={};if(this.apiClient.isVertexAI())throw new Error("The client.tokens.create method is only supported by the Gemini Developer API.");{const u=Ju(this.apiClient,e);l=S("auth_tokens",u._url),a=u._query,delete u.config,delete u._url,delete u._query;const c=ed(u,e.config);return s=this.apiClient.request({path:l,queryParams:a,body:JSON.stringify(c),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(d=>d.json()),s.then(d=>d)}}}/**
234
+ * @license
235
+ * Copyright 2025 Google LLC
236
+ * SPDX-License-Identifier: Apache-2.0
237
+ */function nd(t,e){const n={},o=i(t,["force"]);return e!==void 0&&o!=null&&r(e,["_query","force"],o),n}function od(t){const e={},n=i(t,["name"]);n!=null&&r(e,["_url","name"],n);const o=i(t,["config"]);return o!=null&&nd(o,e),e}function id(t){const e={},n=i(t,["name"]);return n!=null&&r(e,["_url","name"],n),e}function sd(t,e){const n={},o=i(t,["pageSize"]);e!==void 0&&o!=null&&r(e,["_query","pageSize"],o);const s=i(t,["pageToken"]);return e!==void 0&&s!=null&&r(e,["_query","pageToken"],s),n}function rd(t){const e={},n=i(t,["parent"]);n!=null&&r(e,["_url","parent"],n);const o=i(t,["config"]);return o!=null&&sd(o,e),e}function ld(t){const e={},n=i(t,["sdkHttpResponse"]);n!=null&&r(e,["sdkHttpResponse"],n);const o=i(t,["nextPageToken"]);o!=null&&r(e,["nextPageToken"],o);const s=i(t,["documents"]);if(s!=null){let l=s;Array.isArray(l)&&(l=l.map(a=>a)),r(e,["documents"],l)}return e}/**
238
+ * @license
239
+ * Copyright 2025 Google LLC
240
+ * SPDX-License-Identifier: Apache-2.0
241
+ */class ad extends Q{constructor(e){super(),this.apiClient=e,this.list=async n=>new oe(j.PAGED_ITEM_DOCUMENTS,o=>this.listInternal({parent:n.parent,config:o.config}),await this.listInternal(n),n)}async get(e){var n,o;let s,l="",a={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const u=id(e);return l=S("{name}",u._url),a=u._query,delete u._url,delete u._query,s=this.apiClient.request({path:l,queryParams:a,body:JSON.stringify(u),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(c=>c.json()),s.then(c=>c)}}async delete(e){var n,o;let s="",l={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const a=od(e);s=S("{name}",a._url),l=a._query,delete a._url,delete a._query,await this.apiClient.request({path:s,queryParams:l,body:JSON.stringify(a),httpMethod:"DELETE",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal})}}async listInternal(e){var n,o;let s,l="",a={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const u=rd(e);return l=S("{parent}/documents",u._url),a=u._query,delete u._url,delete u._query,s=this.apiClient.request({path:l,queryParams:a,body:JSON.stringify(u),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(c=>c.json()),s.then(c=>{const d=ld(c),f=new Bi;return Object.assign(f,d),f})}}}/**
242
+ * @license
243
+ * Copyright 2025 Google LLC
244
+ * SPDX-License-Identifier: Apache-2.0
245
+ */class ud extends Q{constructor(e,n=new ad(e)){super(),this.apiClient=e,this.documents=n,this.list=async(o={})=>new oe(j.PAGED_ITEM_FILE_SEARCH_STORES,s=>this.listInternal(s),await this.listInternal(o),o)}async uploadToFileSearchStore(e){if(this.apiClient.isVertexAI())throw new Error("Vertex AI does not support uploading files to a file search store.");return this.apiClient.uploadFileToFileSearchStore(e.fileSearchStoreName,e.file,e.config)}async create(e){var n,o;let s,l="",a={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const u=eu(e);return l=S("fileSearchStores",u._url),a=u._query,delete u._url,delete u._query,s=this.apiClient.request({path:l,queryParams:a,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(c=>c.json()),s.then(c=>c)}}async get(e){var n,o;let s,l="",a={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const u=ou(e);return l=S("{name}",u._url),a=u._query,delete u._url,delete u._query,s=this.apiClient.request({path:l,queryParams:a,body:JSON.stringify(u),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(c=>c.json()),s.then(c=>c)}}async delete(e){var n,o;let s="",l={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const a=nu(e);s=S("{name}",a._url),l=a._query,delete a._url,delete a._query,await this.apiClient.request({path:s,queryParams:l,body:JSON.stringify(a),httpMethod:"DELETE",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal})}}async listInternal(e){var n,o;let s,l="",a={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const u=uu(e);return l=S("fileSearchStores",u._url),a=u._query,delete u._url,delete u._query,s=this.apiClient.request({path:l,queryParams:a,body:JSON.stringify(u),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(c=>c.json()),s.then(c=>{const d=du(c),f=new Ji;return Object.assign(f,d),f})}}async uploadToFileSearchStoreInternal(e){var n,o;let s,l="",a={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const u=cu(e);return l=S("upload/v1beta/{file_search_store_name}:uploadToFileSearchStore",u._url),a=u._query,delete u._url,delete u._query,s=this.apiClient.request({path:l,queryParams:a,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(c=>c.json()),s.then(c=>{const d=fu(c),f=new $i;return Object.assign(f,d),f})}}async importFile(e){var n,o;let s,l="",a={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const u=ru(e);return l=S("{file_search_store_name}:importFile",u._url),a=u._query,delete u._url,delete u._query,s=this.apiClient.request({path:l,queryParams:a,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(c=>c.json()),s.then(c=>{const d=su(c),f=new He;return Object.assign(f,d),f})}}}/**
246
+ * @license
247
+ * Copyright 2025 Google LLC
248
+ * SPDX-License-Identifier: Apache-2.0
249
+ */let ao=function(){const{crypto:t}=globalThis;if(t!=null&&t.randomUUID)return ao=t.randomUUID.bind(t),t.randomUUID();const e=new Uint8Array(1),n=t?()=>t.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,o=>(+o^n()&15>>+o/4).toString(16))};const dd=()=>ao();/**
250
+ * @license
251
+ * Copyright 2025 Google LLC
252
+ * SPDX-License-Identifier: Apache-2.0
253
+ */function je(t){return typeof t=="object"&&t!==null&&("name"in t&&t.name==="AbortError"||"message"in t&&String(t.message).includes("FetchRequestCanceledException"))}const et=t=>{if(t instanceof Error)return t;if(typeof t=="object"&&t!==null){try{if(Object.prototype.toString.call(t)==="[object Error]"){const e=new Error(t.message,t.cause?{cause:t.cause}:{});return t.stack&&(e.stack=t.stack),t.cause&&!e.cause&&(e.cause=t.cause),t.name&&(e.name=t.name),e}}catch{}try{return new Error(JSON.stringify(t))}catch{}}return new Error(t)};/**
254
+ * @license
255
+ * Copyright 2025 Google LLC
256
+ * SPDX-License-Identifier: Apache-2.0
257
+ */class Y extends Error{}class B extends Y{constructor(e,n,o,s){super(`${B.makeMessage(e,n,o)}`),this.status=e,this.headers=s,this.error=n}static makeMessage(e,n,o){const s=n!=null&&n.message?typeof n.message=="string"?n.message:JSON.stringify(n.message):n?JSON.stringify(n):o;return e&&s?`${e} ${s}`:e?`${e} status code (no body)`:s||"(no status code or body)"}static generate(e,n,o,s){if(!e||!s)return new we({message:o,cause:et(n)});const l=n;return e===400?new co(e,l,o,s):e===401?new fo(e,l,o,s):e===403?new po(e,l,o,s):e===404?new ho(e,l,o,s):e===409?new mo(e,l,o,s):e===422?new go(e,l,o,s):e===429?new yo(e,l,o,s):e>=500?new To(e,l,o,s):new B(e,l,o,s)}}class tt extends B{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}}class we extends B{constructor({message:e,cause:n}){super(void 0,void 0,e||"Connection error.",void 0),n&&(this.cause=n)}}class uo extends we{constructor({message:e}={}){super({message:e??"Request timed out."})}}class co extends B{}class fo extends B{}class po extends B{}class ho extends B{}class mo extends B{}class go extends B{}class yo extends B{}class To extends B{}/**
258
+ * @license
259
+ * Copyright 2025 Google LLC
260
+ * SPDX-License-Identifier: Apache-2.0
261
+ */const cd=/^[a-z][a-z0-9+.-]*:/i,fd=t=>cd.test(t);let nt=t=>(nt=Array.isArray,nt(t));const _o=nt;function pd(t){if(!t)return!0;for(const e in t)return!1;return!0}function hd(t,e){return Object.prototype.hasOwnProperty.call(t,e)}const md=(t,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new Y(`${t} must be an integer`);if(e<0)throw new Y(`${t} must be a positive integer`);return e},gd=t=>{try{return JSON.parse(t)}catch{return}};/**
262
+ * @license
263
+ * Copyright 2025 Google LLC
264
+ * SPDX-License-Identifier: Apache-2.0
265
+ */const yd=t=>new Promise(e=>setTimeout(e,t));/**
266
+ * @license
267
+ * Copyright 2025 Google LLC
268
+ * SPDX-License-Identifier: Apache-2.0
269
+ */const ce="0.0.1";/**
270
+ * @license
271
+ * Copyright 2025 Google LLC
272
+ * SPDX-License-Identifier: Apache-2.0
273
+ */function Td(){return typeof Deno<"u"&&Deno.build!=null?"deno":typeof EdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}const _d=()=>{var t,e,n,o,s;const l=Td();if(l==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ce,"X-Stainless-OS":Co(Deno.build.os),"X-Stainless-Arch":Eo(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:(e=(t=Deno.version)===null||t===void 0?void 0:t.deno)!==null&&e!==void 0?e:"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ce,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(l==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ce,"X-Stainless-OS":Co((n=globalThis.process.platform)!==null&&n!==void 0?n:"unknown"),"X-Stainless-Arch":Eo((o=globalThis.process.arch)!==null&&o!==void 0?o:"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":(s=globalThis.process.version)!==null&&s!==void 0?s:"unknown"};const a=Ed();return a?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ce,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${a.browser}`,"X-Stainless-Runtime-Version":a.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ce,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function Ed(){if(typeof navigator>"u"||!navigator)return null;const t=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(const{key:e,pattern:n}of t){const o=n.exec(navigator.userAgent);if(o){const s=o[1]||0,l=o[2]||0,a=o[3]||0;return{browser:e,version:`${s}.${l}.${a}`}}}return null}const Eo=t=>t==="x32"?"x32":t==="x86_64"||t==="x64"?"x64":t==="arm"?"arm":t==="aarch64"||t==="arm64"?"arm64":t?`other:${t}`:"unknown",Co=t=>(t=t.toLowerCase(),t.includes("ios")?"iOS":t==="android"?"Android":t==="darwin"?"MacOS":t==="win32"?"Windows":t==="freebsd"?"FreeBSD":t==="openbsd"?"OpenBSD":t==="linux"?"Linux":t?`Other:${t}`:"Unknown");let Ne;const Cd=()=>Ne??(Ne=_d());/**
274
+ * @license
275
+ * Copyright 2025 Google LLC
276
+ * SPDX-License-Identifier: Apache-2.0
277
+ */function vd(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new GeminiNextGenAPIClient({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function vo(...t){const e=globalThis.ReadableStream;if(typeof e>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new e(...t)}function Id(t){let e=Symbol.asyncIterator in t?t[Symbol.asyncIterator]():t[Symbol.iterator]();return vo({start(){},async pull(n){const{done:o,value:s}=await e.next();o?n.close():n.enqueue(s)},async cancel(){var n;await((n=e.return)===null||n===void 0?void 0:n.call(e))}})}function Io(t){if(t[Symbol.asyncIterator])return t;const e=t.getReader();return{async next(){try{const n=await e.read();return n!=null&&n.done&&e.releaseLock(),n}catch(n){throw e.releaseLock(),n}},async return(){const n=e.cancel();return e.releaseLock(),await n,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function Sd(t){var e,n;if(t===null||typeof t!="object")return;if(t[Symbol.asyncIterator]){await((n=(e=t[Symbol.asyncIterator]()).return)===null||n===void 0?void 0:n.call(e));return}const o=t.getReader(),s=o.cancel();o.releaseLock(),await s}/**
278
+ * @license
279
+ * Copyright 2025 Google LLC
280
+ * SPDX-License-Identifier: Apache-2.0
281
+ */const xd=({headers:t,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)});/**
282
+ * @license
283
+ * Copyright 2025 Google LLC
284
+ * SPDX-License-Identifier: Apache-2.0
285
+ */const So=()=>{var t;if(typeof File>"u"){const{process:e}=globalThis,n=typeof((t=e==null?void 0:e.versions)===null||t===void 0?void 0:t.node)=="string"&&parseInt(e.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(n?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function ot(t,e,n){return So(),new File(t,e??"unknown_file",n)}function Ad(t){return(typeof t=="object"&&t!==null&&("name"in t&&t.name&&String(t.name)||"url"in t&&t.url&&String(t.url)||"filename"in t&&t.filename&&String(t.filename)||"path"in t&&t.path&&String(t.path))||"").split(/[\\/]/).pop()||void 0}const wd=t=>t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function";/**
286
+ * @license
287
+ * Copyright 2025 Google LLC
288
+ * SPDX-License-Identifier: Apache-2.0
289
+ */const xo=t=>t!=null&&typeof t=="object"&&typeof t.size=="number"&&typeof t.type=="string"&&typeof t.text=="function"&&typeof t.slice=="function"&&typeof t.arrayBuffer=="function",Nd=t=>t!=null&&typeof t=="object"&&typeof t.name=="string"&&typeof t.lastModified=="number"&&xo(t),Md=t=>t!=null&&typeof t=="object"&&typeof t.url=="string"&&typeof t.blob=="function";async function Pd(t,e,n){if(So(),t=await t,Nd(t))return t instanceof File?t:ot([await t.arrayBuffer()],t.name);if(Md(t)){const s=await t.blob();return e||(e=new URL(t.url).pathname.split(/[\\/]/).pop()),ot(await it(s),e,n)}const o=await it(t);if(e||(e=Ad(t)),!(n!=null&&n.type)){const s=o.find(l=>typeof l=="object"&&"type"in l&&l.type);typeof s=="string"&&(n=Object.assign(Object.assign({},n),{type:s}))}return ot(o,e,n)}async function it(t){var e,n,o,s,l;let a=[];if(typeof t=="string"||ArrayBuffer.isView(t)||t instanceof ArrayBuffer)a.push(t);else if(xo(t))a.push(t instanceof Blob?t:await t.arrayBuffer());else if(wd(t))try{for(var u=!0,c=z(t),d;d=await c.next(),e=d.done,!e;u=!0){s=d.value,u=!1;const f=s;a.push(...await it(f))}}catch(f){n={error:f}}finally{try{!u&&!e&&(o=c.return)&&await o.call(c)}finally{if(n)throw n.error}}else{const f=(l=t==null?void 0:t.constructor)===null||l===void 0?void 0:l.name;throw new Error(`Unexpected data type: ${typeof t}${f?`; constructor: ${f}`:""}${Rd(t)}`)}return a}function Rd(t){return typeof t!="object"||t===null?"":`; props: [${Object.getOwnPropertyNames(t).map(n=>`"${n}"`).join(", ")}]`}/**
290
+ * @license
291
+ * Copyright 2025 Google LLC
292
+ * SPDX-License-Identifier: Apache-2.0
293
+ */class Ao{constructor(e){this._client=e}}Ao._key=[];/**
294
+ * @license
295
+ * Copyright 2025 Google LLC
296
+ * SPDX-License-Identifier: Apache-2.0
297
+ */function wo(t){return t.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}const No=Object.freeze(Object.create(null)),Me=((t=wo)=>function(n,...o){if(n.length===1)return n[0];let s=!1;const l=[],a=n.reduce((f,h,p)=>{var m,y,_;/[?#]/.test(h)&&(s=!0);const T=o[p];let E=(s?encodeURIComponent:t)(""+T);return p!==o.length&&(T==null||typeof T=="object"&&T.toString===((_=Object.getPrototypeOf((y=Object.getPrototypeOf((m=T.hasOwnProperty)!==null&&m!==void 0?m:No))!==null&&y!==void 0?y:No))===null||_===void 0?void 0:_.toString))&&(E=T+"",l.push({start:f.length+h.length,length:E.length,error:`Value of type ${Object.prototype.toString.call(T).slice(8,-1)} is not a valid path parameter`})),f+h+(p===o.length?"":E)},""),u=a.split(/[?#]/,1)[0],c=new RegExp("(?<=^|\\/)(?:\\.|%2e){1,2}(?=\\/|$)","gi");let d;for(;(d=c.exec(u))!==null;)l.push({start:d.index,length:d[0].length,error:`Value "${d[0]}" can't be safely passed as a path parameter`});if(l.sort((f,h)=>f.start-h.start),l.length>0){let f=0;const h=l.reduce((p,m)=>{const y=" ".repeat(m.start-f),_="^".repeat(m.length);return f=m.start+m.length,p+y+_},"");throw new Y(`Path parameters result in path with invalid segments:
298
+ ${l.map(p=>p.error).join(`
299
+ `)}
300
+ ${a}
301
+ ${h}`)}return a})(wo);/**
302
+ * @license
303
+ * Copyright 2025 Google LLC
304
+ * SPDX-License-Identifier: Apache-2.0
305
+ */class Mo extends Ao{create(e,n){var o;const{api_version:s=this._client.apiVersion}=e,l=Ce(e,["api_version"]);if("model"in l&&"agent_config"in l)throw new Y("Invalid request: specified `model` and `agent_config`. If specifying `model`, use `generation_config`.");if("agent"in l&&"generation_config"in l)throw new Y("Invalid request: specified `agent` and `generation_config`. If specifying `agent`, use `agent_config`.");return this._client.post(Me`/${s}/interactions`,Object.assign(Object.assign({body:l},n),{stream:(o=e.stream)!==null&&o!==void 0?o:!1}))}delete(e,n={},o){const{api_version:s=this._client.apiVersion}=n??{};return this._client.delete(Me`/${s}/interactions/${e}`,o)}cancel(e,n={},o){const{api_version:s=this._client.apiVersion}=n??{};return this._client.post(Me`/${s}/interactions/${e}/cancel`,o)}get(e,n={},o){var s;const l=n??{},{api_version:a=this._client.apiVersion}=l,u=Ce(l,["api_version"]);return this._client.get(Me`/${a}/interactions/${e}`,Object.assign(Object.assign({query:u},o),{stream:(s=n==null?void 0:n.stream)!==null&&s!==void 0?s:!1}))}}Mo._key=Object.freeze(["interactions"]);class Po extends Mo{}/**
306
+ * @license
307
+ * Copyright 2025 Google LLC
308
+ * SPDX-License-Identifier: Apache-2.0
309
+ */function kd(t){let e=0;for(const s of t)e+=s.length;const n=new Uint8Array(e);let o=0;for(const s of t)n.set(s,o),o+=s.length;return n}let Pe;function st(t){let e;return(Pe??(e=new globalThis.TextEncoder,Pe=e.encode.bind(e)))(t)}let Re;function Ro(t){let e;return(Re??(e=new globalThis.TextDecoder,Re=e.decode.bind(e)))(t)}/**
310
+ * @license
311
+ * Copyright 2025 Google LLC
312
+ * SPDX-License-Identifier: Apache-2.0
313
+ */class ke{constructor(){this.buffer=new Uint8Array,this.carriageReturnIndex=null}decode(e){if(e==null)return[];const n=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?st(e):e;this.buffer=kd([this.buffer,n]);const o=[];let s;for(;(s=Dd(this.buffer,this.carriageReturnIndex))!=null;){if(s.carriage&&this.carriageReturnIndex==null){this.carriageReturnIndex=s.index;continue}if(this.carriageReturnIndex!=null&&(s.index!==this.carriageReturnIndex+1||s.carriage)){o.push(Ro(this.buffer.subarray(0,this.carriageReturnIndex-1))),this.buffer=this.buffer.subarray(this.carriageReturnIndex),this.carriageReturnIndex=null;continue}const l=this.carriageReturnIndex!==null?s.preceding-1:s.preceding,a=Ro(this.buffer.subarray(0,l));o.push(a),this.buffer=this.buffer.subarray(s.index),this.carriageReturnIndex=null}return o}flush(){return this.buffer.length?this.decode(`
314
+ `):[]}}ke.NEWLINE_CHARS=new Set([`
315
+ `,"\r"]),ke.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function Dd(t,e){for(let s=e??0;s<t.length;s++){if(t[s]===10)return{preceding:s,index:s+1,carriage:!1};if(t[s]===13)return{preceding:s,index:s+1,carriage:!0}}return null}function Ud(t){for(let o=0;o<t.length-1;o++){if(t[o]===10&&t[o+1]===10||t[o]===13&&t[o+1]===13)return o+2;if(t[o]===13&&t[o+1]===10&&o+3<t.length&&t[o+2]===13&&t[o+3]===10)return o+4}return-1}/**
316
+ * @license
317
+ * Copyright 2025 Google LLC
318
+ * SPDX-License-Identifier: Apache-2.0
319
+ */const De={off:0,error:200,warn:300,info:400,debug:500},ko=(t,e,n)=>{if(t){if(hd(De,t))return t;J(n).warn(`${e} was set to ${JSON.stringify(t)}, expected one of ${JSON.stringify(Object.keys(De))}`)}};function he(){}function Ue(t,e,n){return!e||De[t]>De[n]?he:e[t].bind(e)}const Ld={error:he,warn:he,info:he,debug:he};let Do=new WeakMap;function J(t){var e;const n=t.logger,o=(e=t.logLevel)!==null&&e!==void 0?e:"off";if(!n)return Ld;const s=Do.get(n);if(s&&s[0]===o)return s[1];const l={error:Ue("error",n,o),warn:Ue("warn",n,o),info:Ue("info",n,o),debug:Ue("debug",n,o)};return Do.set(n,[o,l]),l}const ie=t=>(t.options&&(t.options=Object.assign({},t.options),delete t.options.headers),t.headers&&(t.headers=Object.fromEntries((t.headers instanceof Headers?[...t.headers]:Object.entries(t.headers)).map(([e,n])=>[e,e.toLowerCase()==="x-goog-api-key"||e.toLowerCase()==="authorization"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":n]))),"retryOfRequestLogID"in t&&(t.retryOfRequestLogID&&(t.retryOf=t.retryOfRequestLogID),delete t.retryOfRequestLogID),t);/**
320
+ * @license
321
+ * Copyright 2025 Google LLC
322
+ * SPDX-License-Identifier: Apache-2.0
323
+ */class fe{constructor(e,n,o){this.iterator=e,this.controller=n,this.client=o}static fromSSEResponse(e,n,o){let s=!1;const l=o?J(o):console;function a(){return K(this,arguments,function*(){var c,d,f,h;if(s)throw new Y("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");s=!0;let p=!1;try{try{for(var m=!0,y=z(bd(e,n)),_;_=yield M(y.next()),c=_.done,!c;m=!0){h=_.value,m=!1;const T=h;if(!p)if(T.data.startsWith("[DONE]")){p=!0;continue}else try{yield yield M(JSON.parse(T.data))}catch(E){throw l.error("Could not parse message into JSON:",T.data),l.error("From chunk:",T.raw),E}}}catch(T){d={error:T}}finally{try{!m&&!c&&(f=y.return)&&(yield M(f.call(y)))}finally{if(d)throw d.error}}p=!0}catch(T){if(je(T))return yield M(void 0);throw T}finally{p||n.abort()}})}return new fe(a,n,o)}static fromReadableStream(e,n,o){let s=!1;function l(){return K(this,arguments,function*(){var c,d,f,h;const p=new ke,m=Io(e);try{for(var y=!0,_=z(m),T;T=yield M(_.next()),c=T.done,!c;y=!0){h=T.value,y=!1;const E=h;for(const C of p.decode(E))yield yield M(C)}}catch(E){d={error:E}}finally{try{!y&&!c&&(f=_.return)&&(yield M(f.call(_)))}finally{if(d)throw d.error}}for(const E of p.flush())yield yield M(E)})}function a(){return K(this,arguments,function*(){var c,d,f,h;if(s)throw new Y("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");s=!0;let p=!1;try{try{for(var m=!0,y=z(l()),_;_=yield M(y.next()),c=_.done,!c;m=!0){h=_.value,m=!1;const T=h;p||T&&(yield yield M(JSON.parse(T)))}}catch(T){d={error:T}}finally{try{!m&&!c&&(f=y.return)&&(yield M(f.call(y)))}finally{if(d)throw d.error}}p=!0}catch(T){if(je(T))return yield M(void 0);throw T}finally{p||n.abort()}})}return new fe(a,n,o)}[Symbol.asyncIterator](){return this.iterator()}tee(){const e=[],n=[],o=this.iterator(),s=l=>({next:()=>{if(l.length===0){const a=o.next();e.push(a),n.push(a)}return l.shift()}});return[new fe(()=>s(e),this.controller,this.client),new fe(()=>s(n),this.controller,this.client)]}toReadableStream(){const e=this;let n;return vo({async start(){n=e[Symbol.asyncIterator]()},async pull(o){try{const{value:s,done:l}=await n.next();if(l)return o.close();const a=st(JSON.stringify(s)+`
324
+ `);o.enqueue(a)}catch(s){o.error(s)}},async cancel(){var o;await((o=n.return)===null||o===void 0?void 0:o.call(n))}})}}function bd(t,e){return K(this,arguments,function*(){var o,s,l,a;if(!t.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new Y("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new Y("Attempted to iterate over a response with no body");const u=new Gd,c=new ke,d=Io(t.body);try{for(var f=!0,h=z(Fd(d)),p;p=yield M(h.next()),o=p.done,!o;f=!0){a=p.value,f=!1;const m=a;for(const y of c.decode(m)){const _=u.decode(y);_&&(yield yield M(_))}}}catch(m){s={error:m}}finally{try{!f&&!o&&(l=h.return)&&(yield M(l.call(h)))}finally{if(s)throw s.error}}for(const m of c.flush()){const y=u.decode(m);y&&(yield yield M(y))}})}function Fd(t){return K(this,arguments,function*(){var n,o,s,l;let a=new Uint8Array;try{for(var u=!0,c=z(t),d;d=yield M(c.next()),n=d.done,!n;u=!0){l=d.value,u=!1;const f=l;if(f==null)continue;const h=f instanceof ArrayBuffer?new Uint8Array(f):typeof f=="string"?st(f):f;let p=new Uint8Array(a.length+h.length);p.set(a),p.set(h,a.length),a=p;let m;for(;(m=Ud(a))!==-1;)yield yield M(a.slice(0,m)),a=a.slice(m)}}catch(f){o={error:f}}finally{try{!u&&!n&&(s=c.return)&&(yield M(s.call(c)))}finally{if(o)throw o.error}}a.length>0&&(yield yield M(a))})}class Gd{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;const l={event:this.event,data:this.data.join(`
325
+ `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],l}if(this.chunks.push(e),e.startsWith(":"))return null;let[n,o,s]=Vd(e,":");return s.startsWith(" ")&&(s=s.substring(1)),n==="event"?this.event=s:n==="data"&&this.data.push(s),null}}function Vd(t,e){const n=t.indexOf(e);return n!==-1?[t.substring(0,n),e,t.substring(n+e.length)]:[t,"",""]}/**
326
+ * @license
327
+ * Copyright 2025 Google LLC
328
+ * SPDX-License-Identifier: Apache-2.0
329
+ */async function qd(t,e){const{response:n,requestLogID:o,retryOfRequestLogID:s,startTime:l}=e,a=await(async()=>{var u;if(e.options.stream)return J(t).debug("response",n.status,n.url,n.headers,n.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(n,e.controller,t):fe.fromSSEResponse(n,e.controller,t);if(n.status===204)return null;if(e.options.__binaryResponse)return n;const c=n.headers.get("content-type"),d=(u=c==null?void 0:c.split(";")[0])===null||u===void 0?void 0:u.trim();return(d==null?void 0:d.includes("application/json"))||(d==null?void 0:d.endsWith("+json"))?await n.json():await n.text()})();return J(t).debug(`[${o}] response parsed`,ie({retryOfRequestLogID:s,url:n.url,status:n.status,body:a,durationMs:Date.now()-l})),a}/**
330
+ * @license
331
+ * Copyright 2025 Google LLC
332
+ * SPDX-License-Identifier: Apache-2.0
333
+ */class rt extends Promise{constructor(e,n,o=qd){super(s=>{s(null)}),this.responsePromise=n,this.parseResponse=o,this.client=e}_thenUnwrap(e){return new rt(this.client,this.responsePromise,async(n,o)=>e(await this.parseResponse(n,o),o))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){const[e,n]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:n}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(this.client,e))),this.parsedPromise}then(e,n){return this.parse().then(e,n)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}}/**
334
+ * @license
335
+ * Copyright 2025 Google LLC
336
+ * SPDX-License-Identifier: Apache-2.0
337
+ */const Uo=Symbol("brand.privateNullableHeaders");function*Hd(t){if(!t)return;if(Uo in t){const{values:o,nulls:s}=t;yield*o.entries();for(const l of s)yield[l,null];return}let e=!1,n;t instanceof Headers?n=t.entries():_o(t)?n=t:(e=!0,n=Object.entries(t??{}));for(let o of n){const s=o[0];if(typeof s!="string")throw new TypeError("expected header name to be a string");const l=_o(o[1])?o[1]:[o[1]];let a=!1;for(const u of l)u!==void 0&&(e&&!a&&(a=!0,yield[s,null]),yield[s,u])}}const me=t=>{const e=new Headers,n=new Set;for(const o of t){const s=new Set;for(const[l,a]of Hd(o)){const u=l.toLowerCase();s.has(u)||(e.delete(l),s.add(u)),a===null?(e.delete(l),n.add(u)):(e.append(l,a),n.delete(u))}}return{[Uo]:!0,values:e,nulls:n}};/**
338
+ * @license
339
+ * Copyright 2025 Google LLC
340
+ * SPDX-License-Identifier: Apache-2.0
341
+ */const lt=t=>{var e,n,o,s,l,a;if(typeof globalThis.process<"u")return(o=(n=(e=globalThis.process.env)===null||e===void 0?void 0:e[t])===null||n===void 0?void 0:n.trim())!==null&&o!==void 0?o:void 0;if(typeof globalThis.Deno<"u")return(a=(l=(s=globalThis.Deno.env)===null||s===void 0?void 0:s.get)===null||l===void 0?void 0:l.call(s,t))===null||a===void 0?void 0:a.trim()};/**
342
+ * @license
343
+ * Copyright 2025 Google LLC
344
+ * SPDX-License-Identifier: Apache-2.0
345
+ */var Lo;class Le{constructor(e){var n,o,s,l,a,u,c,{baseURL:d=lt("GEMINI_NEXT_GEN_API_BASE_URL"),apiKey:f=(n=lt("GEMINI_API_KEY"))!==null&&n!==void 0?n:null,apiVersion:h="v1beta"}=e,p=Ce(e,["baseURL","apiKey","apiVersion"]);const m=Object.assign(Object.assign({apiKey:f,apiVersion:h},p),{baseURL:d||"https://generativelanguage.googleapis.com"});this.baseURL=m.baseURL,this.timeout=(o=m.timeout)!==null&&o!==void 0?o:Le.DEFAULT_TIMEOUT,this.logger=(s=m.logger)!==null&&s!==void 0?s:console;const y="warn";this.logLevel=y,this.logLevel=(a=(l=ko(m.logLevel,"ClientOptions.logLevel",this))!==null&&l!==void 0?l:ko(lt("GEMINI_NEXT_GEN_API_LOG"),"process.env['GEMINI_NEXT_GEN_API_LOG']",this))!==null&&a!==void 0?a:y,this.fetchOptions=m.fetchOptions,this.maxRetries=(u=m.maxRetries)!==null&&u!==void 0?u:2,this.fetch=(c=m.fetch)!==null&&c!==void 0?c:vd(),this.encoder=xd,this._options=m,this.apiKey=f,this.apiVersion=h,this.clientAdapter=m.clientAdapter}withOptions(e){return new this.constructor(Object.assign(Object.assign(Object.assign({},this._options),{baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,apiVersion:this.apiVersion}),e))}baseURLOverridden(){return this.baseURL!=="https://generativelanguage.googleapis.com"}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:n}){if(!(e.has("authorization")||e.has("x-goog-api-key"))&&!(this.apiKey&&e.get("x-goog-api-key"))&&!n.has("x-goog-api-key"))throw new Error('Could not resolve authentication method. Expected the apiKey to be set. Or for the "x-goog-api-key" headers to be explicitly omitted')}async authHeaders(e){const n=me([e.headers]);if(!(n.values.has("authorization")||n.values.has("x-goog-api-key"))){if(this.apiKey)return me([{"x-goog-api-key":this.apiKey}]);if(this.clientAdapter.isVertexAI())return me([await this.clientAdapter.getAuthHeaders()])}}stringifyQuery(e){return Object.entries(e).filter(([n,o])=>typeof o<"u").map(([n,o])=>{if(typeof o=="string"||typeof o=="number"||typeof o=="boolean")return`${encodeURIComponent(n)}=${encodeURIComponent(o)}`;if(o===null)return`${encodeURIComponent(n)}=`;throw new Y(`Cannot stringify type ${typeof o}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join("&")}getUserAgent(){return`${this.constructor.name}/JS ${ce}`}defaultIdempotencyKey(){return`stainless-node-retry-${dd()}`}makeStatusError(e,n,o,s){return B.generate(e,n,o,s)}buildURL(e,n,o){const s=!this.baseURLOverridden()&&o||this.baseURL,l=fd(e)?new URL(e):new URL(s+(s.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),a=this.defaultQuery();return pd(a)||(n=Object.assign(Object.assign({},a),n)),typeof n=="object"&&n&&!Array.isArray(n)&&(l.search=this.stringifyQuery(n)),l.toString()}async prepareOptions(e){if(this.clientAdapter&&this.clientAdapter.isVertexAI()&&!e.path.startsWith(`/${this.apiVersion}/projects/`)){const n=e.path.slice(this.apiVersion.length+1);e.path=`/${this.apiVersion}/projects/${this.clientAdapter.getProject()}/locations/${this.clientAdapter.getLocation()}${n}`}}async prepareRequest(e,{url:n,options:o}){}get(e,n){return this.methodRequest("get",e,n)}post(e,n){return this.methodRequest("post",e,n)}patch(e,n){return this.methodRequest("patch",e,n)}put(e,n){return this.methodRequest("put",e,n)}delete(e,n){return this.methodRequest("delete",e,n)}methodRequest(e,n,o){return this.request(Promise.resolve(o).then(s=>Object.assign({method:e,path:n},s)))}request(e,n=null){return new rt(this,this.makeRequest(e,n,void 0))}async makeRequest(e,n,o){var s,l,a;const u=await e,c=(s=u.maxRetries)!==null&&s!==void 0?s:this.maxRetries;n==null&&(n=c),await this.prepareOptions(u);const{req:d,url:f,timeout:h}=await this.buildRequest(u,{retryCount:c-n});await this.prepareRequest(d,{url:f,options:u});const p="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),m=o===void 0?"":`, retryOf: ${o}`,y=Date.now();if(J(this).debug(`[${p}] sending request`,ie({retryOfRequestLogID:o,method:u.method,url:f,options:u,headers:d.headers})),!((l=u.signal)===null||l===void 0)&&l.aborted)throw new tt;const _=new AbortController,T=await this.fetchWithTimeout(f,d,h,_).catch(et),E=Date.now();if(T instanceof globalThis.Error){const v=`retrying, ${n} attempts remaining`;if(!((a=u.signal)===null||a===void 0)&&a.aborted)throw new tt;const I=je(T)||/timed? ?out/i.test(String(T)+("cause"in T?String(T.cause):""));if(n)return J(this).info(`[${p}] connection ${I?"timed out":"failed"} - ${v}`),J(this).debug(`[${p}] connection ${I?"timed out":"failed"} (${v})`,ie({retryOfRequestLogID:o,url:f,durationMs:E-y,message:T.message})),this.retryRequest(u,n,o??p);throw J(this).info(`[${p}] connection ${I?"timed out":"failed"} - error; no more retries left`),J(this).debug(`[${p}] connection ${I?"timed out":"failed"} (error; no more retries left)`,ie({retryOfRequestLogID:o,url:f,durationMs:E-y,message:T.message})),I?new uo:new we({cause:T})}const C=`[${p}${m}] ${d.method} ${f} ${T.ok?"succeeded":"failed"} with status ${T.status} in ${E-y}ms`;if(!T.ok){const v=await this.shouldRetry(T);if(n&&v){const x=`retrying, ${n} attempts remaining`;return await Sd(T.body),J(this).info(`${C} - ${x}`),J(this).debug(`[${p}] response error (${x})`,ie({retryOfRequestLogID:o,url:T.url,status:T.status,headers:T.headers,durationMs:E-y})),this.retryRequest(u,n,o??p,T.headers)}const I=v?"error; no more retries left":"error; not retryable";J(this).info(`${C} - ${I}`);const A=await T.text().catch(x=>et(x).message),P=gd(A),N=P?void 0:A;throw J(this).debug(`[${p}] response error (${I})`,ie({retryOfRequestLogID:o,url:T.url,status:T.status,headers:T.headers,message:N,durationMs:Date.now()-y})),this.makeStatusError(T.status,P,N,T.headers)}return J(this).info(C),J(this).debug(`[${p}] response start`,ie({retryOfRequestLogID:o,url:T.url,status:T.status,headers:T.headers,durationMs:E-y})),{response:T,options:u,controller:_,requestLogID:p,retryOfRequestLogID:o,startTime:y}}async fetchWithTimeout(e,n,o,s){const l=n||{},{signal:a,method:u}=l,c=Ce(l,["signal","method"]);a&&a.addEventListener("abort",()=>s.abort());const d=setTimeout(()=>s.abort(),o),f=globalThis.ReadableStream&&c.body instanceof globalThis.ReadableStream||typeof c.body=="object"&&c.body!==null&&Symbol.asyncIterator in c.body,h=Object.assign(Object.assign(Object.assign({signal:s.signal},f?{duplex:"half"}:{}),{method:"GET"}),c);u&&(h.method=u.toUpperCase());try{return await this.fetch.call(void 0,e,h)}finally{clearTimeout(d)}}async shouldRetry(e){const n=e.headers.get("x-should-retry");return n==="true"?!0:n==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,n,o,s){var l;let a;const u=s==null?void 0:s.get("retry-after-ms");if(u){const d=parseFloat(u);Number.isNaN(d)||(a=d)}const c=s==null?void 0:s.get("retry-after");if(c&&!a){const d=parseFloat(c);Number.isNaN(d)?a=Date.parse(c)-Date.now():a=d*1e3}if(!(a&&0<=a&&a<60*1e3)){const d=(l=e.maxRetries)!==null&&l!==void 0?l:this.maxRetries;a=this.calculateDefaultRetryTimeoutMillis(n,d)}return await yd(a),this.makeRequest(e,n-1,o)}calculateDefaultRetryTimeoutMillis(e,n){const l=n-e,a=Math.min(.5*Math.pow(2,l),8),u=1-Math.random()*.25;return a*u*1e3}async buildRequest(e,{retryCount:n=0}={}){var o,s,l;const a=Object.assign({},e),{method:u,path:c,query:d,defaultBaseURL:f}=a,h=this.buildURL(c,d,f);"timeout"in a&&md("timeout",a.timeout),a.timeout=(o=a.timeout)!==null&&o!==void 0?o:this.timeout;const{bodyHeaders:p,body:m}=this.buildBody({options:a}),y=await this.buildHeaders({options:e,method:u,bodyHeaders:p,retryCount:n});return{req:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({method:u,headers:y},a.signal&&{signal:a.signal}),globalThis.ReadableStream&&m instanceof globalThis.ReadableStream&&{duplex:"half"}),m&&{body:m}),(s=this.fetchOptions)!==null&&s!==void 0?s:{}),(l=a.fetchOptions)!==null&&l!==void 0?l:{}),url:h,timeout:a.timeout}}async buildHeaders({options:e,method:n,bodyHeaders:o,retryCount:s}){let l={};this.idempotencyHeader&&n!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),l[this.idempotencyHeader]=e.idempotencyKey);const a=await this.authHeaders(e);let u=me([l,Object.assign(Object.assign({Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(s)},e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{}),Cd()),this._options.defaultHeaders,o,e.headers,a]);return this.validateHeaders(u),u.values}buildBody({options:{body:e,headers:n}}){if(!e)return{bodyHeaders:void 0,body:void 0};const o=me([n]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e=="string"&&o.values.has("content-type")||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:e}:typeof e=="object"&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&typeof e.next=="function")?{bodyHeaders:void 0,body:Id(e)}:this.encoder({body:e,headers:o})}}Le.DEFAULT_TIMEOUT=6e4;class V extends Le{constructor(){super(...arguments),this.interactions=new Po(this)}}Lo=V,V.GeminiNextGenAPIClient=Lo,V.GeminiNextGenAPIClientError=Y,V.APIError=B,V.APIConnectionError=we,V.APIConnectionTimeoutError=uo,V.APIUserAbortError=tt,V.NotFoundError=ho,V.ConflictError=mo,V.RateLimitError=yo,V.BadRequestError=co,V.AuthenticationError=fo,V.InternalServerError=To,V.PermissionDeniedError=po,V.UnprocessableEntityError=go,V.toFile=Pd,V.Interactions=Po;/**
346
+ * @license
347
+ * Copyright 2025 Google LLC
348
+ * SPDX-License-Identifier: Apache-2.0
349
+ */function Bd(t,e){const n={},o=i(t,["name"]);return o!=null&&r(n,["_url","name"],o),n}function Jd(t,e){const n={},o=i(t,["name"]);return o!=null&&r(n,["_url","name"],o),n}function $d(t,e){const n={},o=i(t,["sdkHttpResponse"]);return o!=null&&r(n,["sdkHttpResponse"],o),n}function Wd(t,e){const n={},o=i(t,["sdkHttpResponse"]);return o!=null&&r(n,["sdkHttpResponse"],o),n}function Yd(t,e,n){const o={};if(i(t,["validationDataset"])!==void 0)throw new Error("validationDataset parameter is not supported in Gemini API.");const s=i(t,["tunedModelDisplayName"]);if(e!==void 0&&s!=null&&r(e,["displayName"],s),i(t,["description"])!==void 0)throw new Error("description parameter is not supported in Gemini API.");const l=i(t,["epochCount"]);e!==void 0&&l!=null&&r(e,["tuningTask","hyperparameters","epochCount"],l);const a=i(t,["learningRateMultiplier"]);if(a!=null&&r(o,["tuningTask","hyperparameters","learningRateMultiplier"],a),i(t,["exportLastCheckpointOnly"])!==void 0)throw new Error("exportLastCheckpointOnly parameter is not supported in Gemini API.");if(i(t,["preTunedModelCheckpointId"])!==void 0)throw new Error("preTunedModelCheckpointId parameter is not supported in Gemini API.");if(i(t,["adapterSize"])!==void 0)throw new Error("adapterSize parameter is not supported in Gemini API.");const u=i(t,["batchSize"]);e!==void 0&&u!=null&&r(e,["tuningTask","hyperparameters","batchSize"],u);const c=i(t,["learningRate"]);if(e!==void 0&&c!=null&&r(e,["tuningTask","hyperparameters","learningRate"],c),i(t,["labels"])!==void 0)throw new Error("labels parameter is not supported in Gemini API.");if(i(t,["beta"])!==void 0)throw new Error("beta parameter is not supported in Gemini API.");return o}function Kd(t,e,n){const o={};let s=i(n,["config","method"]);if(s===void 0&&(s="SUPERVISED_FINE_TUNING"),s==="SUPERVISED_FINE_TUNING"){const m=i(t,["validationDataset"]);e!==void 0&&m!=null&&r(e,["supervisedTuningSpec"],Fo(m))}else if(s==="PREFERENCE_TUNING"){const m=i(t,["validationDataset"]);e!==void 0&&m!=null&&r(e,["preferenceOptimizationSpec"],Fo(m))}const l=i(t,["tunedModelDisplayName"]);e!==void 0&&l!=null&&r(e,["tunedModelDisplayName"],l);const a=i(t,["description"]);e!==void 0&&a!=null&&r(e,["description"],a);let u=i(n,["config","method"]);if(u===void 0&&(u="SUPERVISED_FINE_TUNING"),u==="SUPERVISED_FINE_TUNING"){const m=i(t,["epochCount"]);e!==void 0&&m!=null&&r(e,["supervisedTuningSpec","hyperParameters","epochCount"],m)}else if(u==="PREFERENCE_TUNING"){const m=i(t,["epochCount"]);e!==void 0&&m!=null&&r(e,["preferenceOptimizationSpec","hyperParameters","epochCount"],m)}let c=i(n,["config","method"]);if(c===void 0&&(c="SUPERVISED_FINE_TUNING"),c==="SUPERVISED_FINE_TUNING"){const m=i(t,["learningRateMultiplier"]);e!==void 0&&m!=null&&r(e,["supervisedTuningSpec","hyperParameters","learningRateMultiplier"],m)}else if(c==="PREFERENCE_TUNING"){const m=i(t,["learningRateMultiplier"]);e!==void 0&&m!=null&&r(e,["preferenceOptimizationSpec","hyperParameters","learningRateMultiplier"],m)}let d=i(n,["config","method"]);if(d===void 0&&(d="SUPERVISED_FINE_TUNING"),d==="SUPERVISED_FINE_TUNING"){const m=i(t,["exportLastCheckpointOnly"]);e!==void 0&&m!=null&&r(e,["supervisedTuningSpec","exportLastCheckpointOnly"],m)}else if(d==="PREFERENCE_TUNING"){const m=i(t,["exportLastCheckpointOnly"]);e!==void 0&&m!=null&&r(e,["preferenceOptimizationSpec","exportLastCheckpointOnly"],m)}let f=i(n,["config","method"]);if(f===void 0&&(f="SUPERVISED_FINE_TUNING"),f==="SUPERVISED_FINE_TUNING"){const m=i(t,["adapterSize"]);e!==void 0&&m!=null&&r(e,["supervisedTuningSpec","hyperParameters","adapterSize"],m)}else if(f==="PREFERENCE_TUNING"){const m=i(t,["adapterSize"]);e!==void 0&&m!=null&&r(e,["preferenceOptimizationSpec","hyperParameters","adapterSize"],m)}if(i(t,["batchSize"])!==void 0)throw new Error("batchSize parameter is not supported in Vertex AI.");if(i(t,["learningRate"])!==void 0)throw new Error("learningRate parameter is not supported in Vertex AI.");const h=i(t,["labels"]);e!==void 0&&h!=null&&r(e,["labels"],h);const p=i(t,["beta"]);return e!==void 0&&p!=null&&r(e,["preferenceOptimizationSpec","hyperParameters","beta"],p),o}function zd(t,e){const n={},o=i(t,["baseModel"]);o!=null&&r(n,["baseModel"],o);const s=i(t,["preTunedModel"]);s!=null&&r(n,["preTunedModel"],s);const l=i(t,["trainingDataset"]);l!=null&&sc(l);const a=i(t,["config"]);return a!=null&&Yd(a,n),n}function Od(t,e){const n={},o=i(t,["baseModel"]);o!=null&&r(n,["baseModel"],o);const s=i(t,["preTunedModel"]);s!=null&&r(n,["preTunedModel"],s);const l=i(t,["trainingDataset"]);l!=null&&rc(l,n,e);const a=i(t,["config"]);return a!=null&&Kd(a,n,e),n}function Xd(t,e){const n={},o=i(t,["name"]);return o!=null&&r(n,["_url","name"],o),n}function Qd(t,e){const n={},o=i(t,["name"]);return o!=null&&r(n,["_url","name"],o),n}function Zd(t,e,n){const o={},s=i(t,["pageSize"]);e!==void 0&&s!=null&&r(e,["_query","pageSize"],s);const l=i(t,["pageToken"]);e!==void 0&&l!=null&&r(e,["_query","pageToken"],l);const a=i(t,["filter"]);return e!==void 0&&a!=null&&r(e,["_query","filter"],a),o}function jd(t,e,n){const o={},s=i(t,["pageSize"]);e!==void 0&&s!=null&&r(e,["_query","pageSize"],s);const l=i(t,["pageToken"]);e!==void 0&&l!=null&&r(e,["_query","pageToken"],l);const a=i(t,["filter"]);return e!==void 0&&a!=null&&r(e,["_query","filter"],a),o}function ec(t,e){const n={},o=i(t,["config"]);return o!=null&&Zd(o,n),n}function tc(t,e){const n={},o=i(t,["config"]);return o!=null&&jd(o,n),n}function nc(t,e){const n={},o=i(t,["sdkHttpResponse"]);o!=null&&r(n,["sdkHttpResponse"],o);const s=i(t,["nextPageToken"]);s!=null&&r(n,["nextPageToken"],s);const l=i(t,["tunedModels"]);if(l!=null){let a=l;Array.isArray(a)&&(a=a.map(u=>bo(u))),r(n,["tuningJobs"],a)}return n}function oc(t,e){const n={},o=i(t,["sdkHttpResponse"]);o!=null&&r(n,["sdkHttpResponse"],o);const s=i(t,["nextPageToken"]);s!=null&&r(n,["nextPageToken"],s);const l=i(t,["tuningJobs"]);if(l!=null){let a=l;Array.isArray(a)&&(a=a.map(u=>at(u))),r(n,["tuningJobs"],a)}return n}function ic(t,e){const n={},o=i(t,["name"]);o!=null&&r(n,["model"],o);const s=i(t,["name"]);return s!=null&&r(n,["endpoint"],s),n}function sc(t,e){const n={};if(i(t,["gcsUri"])!==void 0)throw new Error("gcsUri parameter is not supported in Gemini API.");if(i(t,["vertexDatasetResource"])!==void 0)throw new Error("vertexDatasetResource parameter is not supported in Gemini API.");const o=i(t,["examples"]);if(o!=null){let s=o;Array.isArray(s)&&(s=s.map(l=>l)),r(n,["examples","examples"],s)}return n}function rc(t,e,n){const o={};let s=i(n,["config","method"]);if(s===void 0&&(s="SUPERVISED_FINE_TUNING"),s==="SUPERVISED_FINE_TUNING"){const a=i(t,["gcsUri"]);e!==void 0&&a!=null&&r(e,["supervisedTuningSpec","trainingDatasetUri"],a)}else if(s==="PREFERENCE_TUNING"){const a=i(t,["gcsUri"]);e!==void 0&&a!=null&&r(e,["preferenceOptimizationSpec","trainingDatasetUri"],a)}let l=i(n,["config","method"]);if(l===void 0&&(l="SUPERVISED_FINE_TUNING"),l==="SUPERVISED_FINE_TUNING"){const a=i(t,["vertexDatasetResource"]);e!==void 0&&a!=null&&r(e,["supervisedTuningSpec","trainingDatasetUri"],a)}else if(l==="PREFERENCE_TUNING"){const a=i(t,["vertexDatasetResource"]);e!==void 0&&a!=null&&r(e,["preferenceOptimizationSpec","trainingDatasetUri"],a)}if(i(t,["examples"])!==void 0)throw new Error("examples parameter is not supported in Vertex AI.");return o}function bo(t,e){const n={},o=i(t,["sdkHttpResponse"]);o!=null&&r(n,["sdkHttpResponse"],o);const s=i(t,["name"]);s!=null&&r(n,["name"],s);const l=i(t,["state"]);l!=null&&r(n,["state"],Rn(l));const a=i(t,["createTime"]);a!=null&&r(n,["createTime"],a);const u=i(t,["tuningTask","startTime"]);u!=null&&r(n,["startTime"],u);const c=i(t,["tuningTask","completeTime"]);c!=null&&r(n,["endTime"],c);const d=i(t,["updateTime"]);d!=null&&r(n,["updateTime"],d);const f=i(t,["description"]);f!=null&&r(n,["description"],f);const h=i(t,["baseModel"]);h!=null&&r(n,["baseModel"],h);const p=i(t,["_self"]);return p!=null&&r(n,["tunedModel"],ic(p)),n}function at(t,e){const n={},o=i(t,["sdkHttpResponse"]);o!=null&&r(n,["sdkHttpResponse"],o);const s=i(t,["name"]);s!=null&&r(n,["name"],s);const l=i(t,["state"]);l!=null&&r(n,["state"],Rn(l));const a=i(t,["createTime"]);a!=null&&r(n,["createTime"],a);const u=i(t,["startTime"]);u!=null&&r(n,["startTime"],u);const c=i(t,["endTime"]);c!=null&&r(n,["endTime"],c);const d=i(t,["updateTime"]);d!=null&&r(n,["updateTime"],d);const f=i(t,["error"]);f!=null&&r(n,["error"],f);const h=i(t,["description"]);h!=null&&r(n,["description"],h);const p=i(t,["baseModel"]);p!=null&&r(n,["baseModel"],p);const m=i(t,["tunedModel"]);m!=null&&r(n,["tunedModel"],m);const y=i(t,["preTunedModel"]);y!=null&&r(n,["preTunedModel"],y);const _=i(t,["supervisedTuningSpec"]);_!=null&&r(n,["supervisedTuningSpec"],_);const T=i(t,["preferenceOptimizationSpec"]);T!=null&&r(n,["preferenceOptimizationSpec"],T);const E=i(t,["tuningDataStats"]);E!=null&&r(n,["tuningDataStats"],E);const C=i(t,["encryptionSpec"]);C!=null&&r(n,["encryptionSpec"],C);const v=i(t,["partnerModelTuningSpec"]);v!=null&&r(n,["partnerModelTuningSpec"],v);const I=i(t,["customBaseModel"]);I!=null&&r(n,["customBaseModel"],I);const A=i(t,["experiment"]);A!=null&&r(n,["experiment"],A);const P=i(t,["labels"]);P!=null&&r(n,["labels"],P);const N=i(t,["outputUri"]);N!=null&&r(n,["outputUri"],N);const U=i(t,["pipelineJob"]);U!=null&&r(n,["pipelineJob"],U);const x=i(t,["serviceAccount"]);x!=null&&r(n,["serviceAccount"],x);const R=i(t,["tunedModelDisplayName"]);R!=null&&r(n,["tunedModelDisplayName"],R);const b=i(t,["veoTuningSpec"]);return b!=null&&r(n,["veoTuningSpec"],b),n}function lc(t,e){const n={},o=i(t,["sdkHttpResponse"]);o!=null&&r(n,["sdkHttpResponse"],o);const s=i(t,["name"]);s!=null&&r(n,["name"],s);const l=i(t,["metadata"]);l!=null&&r(n,["metadata"],l);const a=i(t,["done"]);a!=null&&r(n,["done"],a);const u=i(t,["error"]);return u!=null&&r(n,["error"],u),n}function Fo(t,e){const n={},o=i(t,["gcsUri"]);o!=null&&r(n,["validationDatasetUri"],o);const s=i(t,["vertexDatasetResource"]);return s!=null&&r(n,["validationDatasetUri"],s),n}/**
350
+ * @license
351
+ * Copyright 2025 Google LLC
352
+ * SPDX-License-Identifier: Apache-2.0
353
+ */class ac extends Q{constructor(e){super(),this.apiClient=e,this.list=async(n={})=>new oe(j.PAGED_ITEM_TUNING_JOBS,o=>this.listInternal(o),await this.listInternal(n),n),this.get=async n=>await this.getInternal(n),this.tune=async n=>{var o;if(this.apiClient.isVertexAI())if(n.baseModel.startsWith("projects/")){const s={tunedModelName:n.baseModel};!((o=n.config)===null||o===void 0)&&o.preTunedModelCheckpointId&&(s.checkpointId=n.config.preTunedModelCheckpointId);const l=Object.assign(Object.assign({},n),{preTunedModel:s});return l.baseModel=void 0,await this.tuneInternal(l)}else{const s=Object.assign({},n);return await this.tuneInternal(s)}else{const s=Object.assign({},n),l=await this.tuneMldevInternal(s);let a="";return l.metadata!==void 0&&l.metadata.tunedModel!==void 0?a=l.metadata.tunedModel:l.name!==void 0&&l.name.includes("/operations/")&&(a=l.name.split("/operations/")[0]),{name:a,state:Ve.JOB_STATE_QUEUED}}}}async getInternal(e){var n,o,s,l;let a,u="",c={};if(this.apiClient.isVertexAI()){const d=Qd(e);return u=S("{name}",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(f=>f.json().then(h=>{const p=h;return p.sdkHttpResponse={headers:f.headers},p})),a.then(f=>at(f))}else{const d=Xd(e);return u=S("{name}",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"GET",httpOptions:(s=e.config)===null||s===void 0?void 0:s.httpOptions,abortSignal:(l=e.config)===null||l===void 0?void 0:l.abortSignal}).then(f=>f.json().then(h=>{const p=h;return p.sdkHttpResponse={headers:f.headers},p})),a.then(f=>bo(f))}}async listInternal(e){var n,o,s,l;let a,u="",c={};if(this.apiClient.isVertexAI()){const d=tc(e);return u=S("tuningJobs",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(f=>f.json().then(h=>{const p=h;return p.sdkHttpResponse={headers:f.headers},p})),a.then(f=>{const h=oc(f),p=new Tn;return Object.assign(p,h),p})}else{const d=ec(e);return u=S("tunedModels",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"GET",httpOptions:(s=e.config)===null||s===void 0?void 0:s.httpOptions,abortSignal:(l=e.config)===null||l===void 0?void 0:l.abortSignal}).then(f=>f.json().then(h=>{const p=h;return p.sdkHttpResponse={headers:f.headers},p})),a.then(f=>{const h=nc(f),p=new Tn;return Object.assign(p,h),p})}}async cancel(e){var n,o,s,l;let a,u="",c={};if(this.apiClient.isVertexAI()){const d=Jd(e);return u=S("{name}:cancel",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(f=>f.json().then(h=>{const p=h;return p.sdkHttpResponse={headers:f.headers},p})),a.then(f=>{const h=Wd(f),p=new _n;return Object.assign(p,h),p})}else{const d=Bd(e);return u=S("{name}:cancel",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(s=e.config)===null||s===void 0?void 0:s.httpOptions,abortSignal:(l=e.config)===null||l===void 0?void 0:l.abortSignal}).then(f=>f.json().then(h=>{const p=h;return p.sdkHttpResponse={headers:f.headers},p})),a.then(f=>{const h=$d(f),p=new _n;return Object.assign(p,h),p})}}async tuneInternal(e){var n,o;let s,l="",a={};if(this.apiClient.isVertexAI()){const u=Od(e,e);return l=S("tuningJobs",u._url),a=u._query,delete u._url,delete u._query,s=this.apiClient.request({path:l,queryParams:a,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(c=>c.json().then(d=>{const f=d;return f.sdkHttpResponse={headers:c.headers},f})),s.then(c=>at(c))}else throw new Error("This method is only supported by the Vertex AI.")}async tuneMldevInternal(e){var n,o;let s,l="",a={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const u=zd(e);return l=S("tunedModels",u._url),a=u._query,delete u._url,delete u._query,s=this.apiClient.request({path:l,queryParams:a,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(c=>c.json().then(d=>{const f=d;return f.sdkHttpResponse={headers:c.headers},f})),s.then(c=>lc(c))}}}/**
354
+ * @license
355
+ * Copyright 2025 Google LLC
356
+ * SPDX-License-Identifier: Apache-2.0
357
+ */class uc{async download(e,n){throw new Error("Download to file is not supported in the browser, please use a browser compliant download like an <a> tag.")}}const dc=1024*1024*8,cc=3,fc=1e3,pc=2,be="x-goog-upload-status";async function hc(t,e,n){var o;const s=await Go(t,e,n),l=await(s==null?void 0:s.json());if(((o=s==null?void 0:s.headers)===null||o===void 0?void 0:o[be])!=="final")throw new Error("Failed to upload file: Upload status is not finalized.");return l.file}async function mc(t,e,n){var o;const s=await Go(t,e,n),l=await(s==null?void 0:s.json());if(((o=s==null?void 0:s.headers)===null||o===void 0?void 0:o[be])!=="final")throw new Error("Failed to upload file: Upload status is not finalized.");const a=pt(l),u=new Be;return Object.assign(u,a),u}async function Go(t,e,n){var o,s;let l=0,a=0,u=new qe(new Response),c="upload";for(l=t.size;a<l;){const d=Math.min(dc,l-a),f=t.slice(a,a+d);a+d>=l&&(c+=", finalize");let h=0,p=fc;for(;h<cc&&(u=await n.request({path:"",body:f,httpMethod:"POST",httpOptions:{apiVersion:"",baseUrl:e,headers:{"X-Goog-Upload-Command":c,"X-Goog-Upload-Offset":String(a),"Content-Length":String(d)}}}),!(!((o=u==null?void 0:u.headers)===null||o===void 0)&&o[be]));)h++,await yc(p),p=p*pc;if(a+=d,((s=u==null?void 0:u.headers)===null||s===void 0?void 0:s[be])!=="active")break;if(l<=a)throw new Error("All content has been uploaded, but the upload status is not finalized.")}return u}async function gc(t){return{size:t.size,type:t.type}}function yc(t){return new Promise(e=>setTimeout(e,t))}class Tc{async upload(e,n,o){if(typeof e=="string")throw new Error("File path is not supported in browser uploader.");return await hc(e,n,o)}async uploadToFileSearchStore(e,n,o){if(typeof e=="string")throw new Error("File path is not supported in browser uploader.");return await mc(e,n,o)}async stat(e){if(typeof e=="string")throw new Error("File path is not supported in browser uploader.");return await gc(e)}}/**
358
+ * @license
359
+ * Copyright 2025 Google LLC
360
+ * SPDX-License-Identifier: Apache-2.0
361
+ */class _c{create(e,n,o){return new Ec(e,n,o)}}class Ec{constructor(e,n,o){this.url=e,this.headers=n,this.callbacks=o}connect(){this.ws=new WebSocket(this.url),this.ws.onopen=this.callbacks.onopen,this.ws.onerror=this.callbacks.onerror,this.ws.onclose=this.callbacks.onclose,this.ws.onmessage=this.callbacks.onmessage}send(e){if(this.ws===void 0)throw new Error("WebSocket is not connected");this.ws.send(e)}close(){if(this.ws===void 0)throw new Error("WebSocket is not connected");this.ws.close()}}/**
362
+ * @license
363
+ * Copyright 2025 Google LLC
364
+ * SPDX-License-Identifier: Apache-2.0
365
+ */const Vo="x-goog-api-key";class Cc{constructor(e){this.apiKey=e}async addAuthHeaders(e,n){if(e.get(Vo)===null){if(this.apiKey.startsWith("auth_tokens/"))throw new Error("Ephemeral tokens are only supported by the live API.");if(!this.apiKey)throw new Error("API key is missing. Please provide a valid API key.");e.append(Vo,this.apiKey)}}}/**
366
+ * @license
367
+ * Copyright 2025 Google LLC
368
+ * SPDX-License-Identifier: Apache-2.0
369
+ */const vc="gl-node/";class Ic{get interactions(){if(this._interactions!==void 0)return this._interactions;console.warn("GoogleGenAI.interactions: Interactions usage is experimental and may change in future versions.");const e=this.httpOptions;e!=null&&e.extraBody&&console.warn("GoogleGenAI.interactions: Client level httpOptions.extraBody is not supported by the interactions client and will be ignored.");const n=new V({baseURL:this.apiClient.getBaseUrl(),apiKey:this.apiKey,apiVersion:this.apiClient.getApiVersion(),clientAdapter:this.apiClient,defaultHeaders:this.apiClient.getDefaultHeaders(),timeout:e==null?void 0:e.timeout});return this._interactions=n.interactions,this._interactions}constructor(e){var n;if(e.apiKey==null)throw new Error("An API Key must be set when running in a browser");if(e.project||e.location)throw new Error("Vertex AI project based authentication is not supported on browser runtimes. Please do not provide a project or location.");this.vertexai=(n=e.vertexai)!==null&&n!==void 0?n:!1,this.apiKey=e.apiKey;const o=Ci(e.httpOptions,e.vertexai,void 0,void 0);o&&(e.httpOptions?e.httpOptions.baseUrl=o:e.httpOptions={baseUrl:o}),this.apiVersion=e.apiVersion,this.httpOptions=e.httpOptions;const s=new Cc(this.apiKey);this.apiClient=new _u({auth:s,apiVersion:this.apiVersion,apiKey:this.apiKey,vertexai:this.vertexai,httpOptions:this.httpOptions,userAgentExtra:vc+"web",uploader:new Tc,downloader:new uc}),this.models=new Gu(this.apiClient),this.live=new ku(this.apiClient,s,new _c),this.batches=new Xs(this.apiClient),this.chats=new Rr(this.models,this.apiClient),this.caches=new Nr(this.apiClient),this.files=new Hr(this.apiClient),this.operations=new Vu(this.apiClient),this.authTokens=new td(this.apiClient),this.tunings=new ac(this.apiClient),this.fileSearchStores=new ud(this.apiClient)}}const Sc=async(t,e)=>{if(!e)throw new Error("API key is not provided. Please provide an API key to use the AI features.");const n=new Ic({apiKey:e});try{const o="gemini-3-pro-preview",l={text:`Analyze the handwritten formula in the image. Your ONLY task is to return a single, valid line of LaTeX code that represents the formula.
370
+
371
+ IMPORTANT RULES:
372
+ 1. **SINGLE OUTPUT ONLY:** Provide only one LaTeX transcription. Do NOT give alternatives or variations. For example, if you see a fraction, output '\\frac{a}{b}', not '\\frac{a}{b} or a/b'.
373
+ 2. **CODE ONLY:** Your entire response must be ONLY the LaTeX code. No explanations, no introductory text like "Here is the LaTeX:", no markdown, no dollar signs.
374
+ 3. **ACCURACY:** Transcribe the symbols and structure as precisely as possible.
375
+
376
+ Example: For an image showing 'x squared', your literal output must be: x^2`},a={inlineData:{mimeType:"image/png",data:t}};let c=(await n.models.generateContent({model:o,contents:{parts:[l,a]}})).text;if(!c)throw new Error("API returned no text. The drawing might be unclear or empty.");return c=c.trim().split(`
377
+ `)[0],c.startsWith("```latex")?(c=c.substring(7).trim(),c.endsWith("```")&&(c=c.slice(0,-3).trim())):c.startsWith("```")&&(c=c.substring(3).trim(),c.endsWith("```")&&(c=c.slice(0,-3).trim())),c.startsWith("$$")&&c.endsWith("$$")?c=c.substring(2,c.length-2).trim():c.startsWith("$")&&c.endsWith("$")&&(c=c.substring(1,c.length-1).trim()),c}catch(o){throw console.error("Error calling Gemini API:",o),o instanceof Error&&(o.message.includes("API key not valid")||o.message.includes("400"))?new Error("The API key is not valid. Please check your configuration."):new Error("Failed to recognize handwriting. The model may be unavailable or the drawing is unclear.")}},qo=()=>g.jsxs("span",{className:"text-sm leading-tight flex flex-col items-center text-black -mt-0.5",children:[g.jsx("span",{children:"□"}),g.jsx("span",{className:"w-2 h-px bg-black my-[1px]"}),g.jsx("span",{children:"□"})]}),Ho=()=>g.jsxs("span",{className:"text-black text-lg",children:["√",g.jsx("span",{className:"border-t border-black -ml-1",children:"□"})]}),xc=()=>g.jsxs("span",{className:"text-black text-lg",children:[g.jsx("sup",{className:"-mr-1",children:"□"}),"√",g.jsx("span",{className:"border-t border-black -ml-1",children:"□"})]}),Ac=({symbol:t,onInsert:e})=>g.jsx("button",{onClick:()=>e(t.latex),title:t.title||(typeof t.display=="string"?t.display:t.latex),className:`w-8 h-7 bg-white hover:bg-gray-100 border border-transparent hover:border-blue-400 flex items-center justify-center text-black transition-colors text-base rounded ${t.className||""}`,children:t.display}),wc=({onClick:t,isActive:e,children:n,title:o})=>g.jsx("button",{onClick:t,title:o,className:`px-2 h-7 flex items-center justify-center rounded transition-all select-none border ${e?"bg-white text-black border-gray-300 shadow-inner":"bg-transparent text-black border-transparent hover:bg-white/60"}`,children:n}),Nc=[{key:"layout",display:g.jsxs("div",{className:"flex items-center gap-1",children:[g.jsx(Ho,{})," ",g.jsx(qo,{})]}),title:"Layout Templates"},{key:"symbols",display:g.jsx("span",{className:"text-lg",children:"∈∞"}),title:"Symbols"},{key:"arrows",display:g.jsx("span",{className:"text-lg font-mono",children:"→…"}),title:"Arrows"},{key:"greek",display:g.jsx("span",{className:"text-lg",children:"αΩ"}),title:"Greek Symbols"},{key:"matrices",display:g.jsx("span",{className:"text-lg",children:"[□]"}),title:"Matrix Templates"},{key:"fences",display:g.jsx("span",{className:"text-lg",children:"(□)"}),title:"Fences & Accents"},{key:"sums",display:g.jsx("span",{className:"text-lg",children:"Σ∪"}),title:"Sums & Set Theory"},{key:"integrals",display:g.jsx("span",{className:"text-lg",children:"∫ lim"}),title:"Integrals & Functions"}],Bo={layout:[[[{display:g.jsx(qo,{}),latex:"\\frac{}{}"}],[{display:"%",latex:"\\%"}]],[[{display:g.jsx(Ho,{}),latex:"\\sqrt{}"}],[{display:g.jsx(xc,{}),latex:"\\sqrt[]{}"}]],[[{display:"□²",latex:"^{}"}],[{display:"□₂",latex:"_{}"}],[{display:"□₂²",latex:"_{}^{}"}]],[[{display:"(□)",latex:"({})"}],[{display:"[□]",latex:"[]"}],[{display:"{□}",latex:"\\{\\}"}]],[[{display:"|□|",latex:"|{}|"}],[{display:"||□||",latex:"\\|{}|\\|"}]]],symbols:[[[{display:"∅",latex:"\\emptyset"},{display:"+",latex:"+"},{display:"×",latex:"\\times"},{display:"·",latex:"\\cdot"},{display:"π",latex:"\\pi"},{display:"∂",latex:"\\partial"},{display:"°",latex:"^\\circ"}],[{display:"−",latex:"-"},{display:"÷",latex:"\\div"},{display:"/",latex:"/"},{display:"∞",latex:"\\infty"},{display:"Δ",latex:"\\Delta"},{display:"′",latex:"\\prime"}],[{display:"±",latex:"\\pm"},{display:"∓",latex:"\\mp"},{display:"∘",latex:"\\circ"},{display:"ø",latex:"\\o"},{display:"∇",latex:"\\nabla"},{display:"″",latex:"\\prime\\prime"}]],[[{display:"=",latex:"="},{display:"≡",latex:"\\equiv"},{display:">",latex:">"},{display:"<",latex:"<"}],[{display:"≠",latex:"\\neq"},{display:"≈",latex:"\\approx"},{display:"≥",latex:"\\geq"},{display:"≤",latex:"\\leq"}],[{display:"∼",latex:"\\sim"},{display:"≃",latex:"\\simeq"},{display:"≫",latex:"\\gg"},{display:"≪",latex:"\\ll"}]],[[{display:"∈",latex:"\\in"},{display:"∃",latex:"\\exists"},{display:"∧",latex:"\\land"},{display:"∨",latex:"\\lor"}],[{display:"∪",latex:"\\cup"},{display:"∩",latex:"\\cap"},{display:"∀",latex:"\\forall"},{display:"¬",latex:"\\neg"}],[{display:"⊂",latex:"\\subset"},{display:"⊃",latex:"\\supset"},{display:"∃!",latex:"\\exists!"},{display:"⊥",latex:"\\perp"}]],[[{display:"∠",latex:"\\angle"},{display:"□",latex:"\\square"},{display:"⊕",latex:"\\oplus"}],[{display:"∥",latex:"\\parallel"},{display:"△",latex:"\\triangle"},{display:"⊗",latex:"\\otimes"}],[{display:"○",latex:"\\circ"},{display:"⊙",latex:"\\odot"}]]],arrows:[[[{display:"←",latex:"\\leftarrow"},{display:"⇐",latex:"\\Leftarrow"},{display:"↖",latex:"\\nwarrow"}],[{display:"→",latex:"\\rightarrow"},{display:"⇒",latex:"\\Rightarrow"},{display:"↗",latex:"\\nearrow"}],[{display:"↔",latex:"\\leftrightarrow"},{display:"⇔",latex:"\\Leftrightarrow"},{display:"↘",latex:"\\searrow"}],[{display:"↦",latex:"\\mapsto"},{display:"↼",latex:"\\leftharpoonup"},{display:"↙",latex:"\\swarrow"}]],[[{display:"…",latex:"\\dots"},{display:"⋮",latex:"\\vdots"},{display:"⋯",latex:"\\cdots"},{display:"⋱",latex:"\\ddots"}]]],greek:[[[{display:"α",latex:"\\alpha"},{display:"κ",latex:"\\kappa"},{display:"σ",latex:"\\sigma"}],[{display:"β",latex:"\\beta"},{display:"λ",latex:"\\lambda"},{display:"τ",latex:"\\tau"}],[{display:"γ",latex:"\\gamma"},{display:"μ",latex:"\\mu"},{display:"υ",latex:"\\upsilon"}],[{display:"δ",latex:"\\delta"},{display:"ν",latex:"\\nu"},{display:"φ",latex:"\\phi"}],[{display:"ε",latex:"\\epsilon"},{display:"ξ",latex:"\\xi"},{display:"χ",latex:"\\chi"}],[{display:"ζ",latex:"\\zeta"},{display:"ο",latex:"\\omicron"},{display:"ψ",latex:"\\psi"}],[{display:"η",latex:"\\eta"},{display:"π",latex:"\\pi"},{display:"ω",latex:"\\omega"}],[{display:"θ",latex:"\\theta"},{display:"ρ",latex:"\\rho"}],[{display:"ι",latex:"\\iota"},{display:"ς",latex:"\\varsigma"}]],[[{display:"Α",latex:"A"},{display:"Κ",latex:"K"},{display:"Σ",latex:"\\Sigma"}],[{display:"Β",latex:"B"},{display:"Λ",latex:"\\Lambda"},{display:"Τ",latex:"T"}],[{display:"Γ",latex:"\\Gamma"},{display:"Μ",latex:"M"},{display:"Υ",latex:"\\Upsilon"}],[{display:"Δ",latex:"\\Delta"},{display:"Ν",latex:"N"},{display:"Φ",latex:"\\Phi"}],[{display:"Ε",latex:"E"},{display:"Ξ",latex:"\\Xi"},{display:"Χ",latex:"X"}],[{display:"Ζ",latex:"Z"},{display:"Ο",latex:"O"},{display:"Ψ",latex:"\\Psi"}],[{display:"Η",latex:"H"},{display:"Π",latex:"\\Pi"},{display:"Ω",latex:"\\Omega"}],[{display:"Θ",latex:"\\Theta"},{display:"Ρ",latex:"P"}],[{display:"Ι",latex:"I"},{display:"Σ",latex:"\\Sigma"}]]],matrices:[[[{display:"[□]",latex:"\\begin{bmatrix} {} \\end{bmatrix}"},{display:"(□)",latex:"\\begin{pmatrix} {} \\end{pmatrix}"},{display:"|□|",latex:"\\begin{vmatrix} {} \\end{vmatrix}"},{display:"||□||",latex:"\\begin{Vmatrix} {} \\end{Vmatrix}"}],[{display:"[□,□]",latex:"\\begin{bmatrix} {} & {} \\end{bmatrix}"},{display:"(□,□)",latex:"\\begin{pmatrix} {} & {} \\end{pmatrix}"}],[{display:"[□;□]",latex:"\\begin{bmatrix} {} \\\\ {} \\end{bmatrix}"},{display:"(□;□)",latex:"\\begin{pmatrix} {} \\\\ {} \\end{pmatrix}"}]],[[{display:"[::]",latex:"\\begin{bmatrix} {} & {} \\\\ {} & {} \\end{bmatrix}"}],[{display:"⋮",latex:"\\vdots"},{display:"⋯",latex:"\\cdots"},{display:"⋱",latex:"\\ddots"}]]],fences:[[[{display:"(□)",latex:"({})"},{display:"|□|",latex:"|{}|"},{display:"⟨□⟩",latex:"\\langle {} \\rangle"}],[{display:"[□]",latex:"[{}]"},{display:"||□||",latex:"\\|{}|\\|"},{display:"{□}",latex:"\\{{}\\}"}]],[[{display:"◯",latex:"\\enclose{circle}{}"},{display:"□",latex:"\\enclose{box}{}"},{display:"╱",latex:"\\enclose{updiagonalstrike}{}"},{display:"⃫",latex:"\\enclose{updiagonalstrike,downdiagonalstrike}{}"}],[{display:"()",latex:"\\enclose{actuarial}{}"},{display:"╳",latex:"\\enclose{downdiagonalstrike}{}"},{display:"│",latex:"\\enclose{verticalstrike}{}"},{display:"─",latex:"\\enclose{horizontalstrike}{}"}]],[[{display:g.jsx("span",{className:"text-xl",children:"ô"}),latex:"\\hat{}"},{display:g.jsx("span",{className:"text-xl",children:"ō"}),latex:"\\bar{}"},{display:g.jsx("span",{className:"text-xl",children:"ò"}),latex:"\\vec{}"}],[{display:g.jsx("span",{className:"text-xl",children:"õ"}),latex:"\\tilde{}"},{display:g.jsx("span",{className:"text-xl",children:"ó"}),latex:"\\acute{}"},{display:g.jsx("span",{className:"text-xl",children:"ö"}),latex:"\\ddot{}"}]]],sums:[[[{display:"∑",latex:"\\sum"},{display:"∑ límites",latex:"\\sum_{}^{}"}],[{display:"∏",latex:"\\prod"},{display:"∏ límites",latex:"\\prod_{}^{}"}],[{display:"∐",latex:"\\coprod"},{display:"∐ límites",latex:"\\coprod_{}^{}"}]],[[{display:"∪",latex:"\\cup"},{display:"∩",latex:"\\cap"}],[{display:"⋃",latex:"\\bigcup"},{display:"⋂",latex:"\\bigcap"}]]],integrals:[[[{display:"∫",latex:"\\int"},{display:"∫ límites",latex:"\\int_{}^{}"}],[{display:"∬",latex:"\\iint"},{display:"∬ límites",latex:"\\iint_{}^{}"}],[{display:"∮",latex:"\\oint"},{display:"∮ límites",latex:"\\oint_{}^{}"}],[{display:"∯",latex:"\\oiint"},{display:"∯ límites",latex:"\\oiint_{}^{}"}]],[[{display:"d",latex:"d"},{display:"∂",latex:"\\partial"},{display:"∇",latex:"\\nabla"},{display:"Δ",latex:"\\Delta"}]],[[{display:"lim",latex:"\\lim"},{display:"lim →",latex:"\\lim_{x \\to {} }"}]],[[{display:"sin",latex:"\\sin"},{display:"cos",latex:"\\cos"},{display:"tan",latex:"\\tan"}],[{display:"log",latex:"\\log"},{display:"log base",latex:"\\log_{}"},{display:"ln",latex:"\\ln"}]]],products:[]},Mc=({onInsert:t})=>{const[e,n]=w.useState("layout");return g.jsxs("div",{className:"bg-[#e9eff1] px-2 py-1 flex flex-col space-y-1 shrink-0 border-b border-gray-300",children:[g.jsxs("div",{className:"flex flex-wrap gap-1 items-center",children:[Nc.map(o=>g.jsx(wc,{onClick:()=>n(o.key),isActive:e===o.key,title:o.title,children:o.display},o.key)),g.jsx("div",{className:"flex-grow"}),g.jsx("button",{title:"Help",className:"w-8 h-8 rounded-full bg-gray-400 hover:bg-gray-500 text-white flex items-center justify-center shadow-sm transition-all",children:g.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:g.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})})})]}),g.jsxs("div",{className:"flex items-start bg-white rounded border border-gray-300 min-h-[5rem] shadow-inner p-1 overflow-x-auto",children:[g.jsx("div",{className:"flex items-start",children:Bo[e].map((o,s)=>g.jsxs(w.Fragment,{children:[g.jsx("div",{className:"flex flex-col",children:o.map((l,a)=>g.jsx("div",{className:"flex",children:l.map((u,c)=>g.jsx(Ac,{symbol:u,onInsert:t},c))},a))}),s<Bo[e].length-1&&g.jsx("div",{className:"w-px bg-gray-300 mx-1 self-stretch"})]},s))}),g.jsx("div",{className:"flex-grow"}),g.jsx("div",{className:"flex items-center space-x-2 shrink-0 self-center pr-2",children:g.jsxs("div",{className:"flex flex-col space-y-1",children:[g.jsx("select",{disabled:!0,className:"text-sm border border-gray-300 rounded h-6 w-32 px-1 text-black opacity-50",children:g.jsx("option",{children:"Font..."})}),g.jsx("select",{disabled:!0,className:"text-sm border border-gray-300 rounded h-6 w-32 px-1 text-black opacity-50",children:g.jsx("option",{children:"Size..."})})]})})]})]})},Pc=({symbol:t,onInsert:e})=>g.jsx("button",{onClick:()=>e(t.latex),title:t.title||(typeof t.display=="string"?t.display:t.latex),className:`w-8 h-7 bg-white hover:bg-gray-100 border border-transparent hover:border-blue-400 flex items-center justify-center text-black transition-colors text-base rounded ${t.className||""}`,children:t.display}),Rc=({onClick:t,isActive:e,children:n,title:o})=>g.jsx("button",{onClick:t,title:o,className:`px-2 h-7 flex items-center justify-center rounded transition-all select-none border ${e?"bg-white text-black border-gray-300 shadow-inner":"bg-transparent text-black border-transparent hover:bg-white/60"}`,children:n}),kc=[{key:"chem",display:g.jsx("span",{className:"text-base",children:"H₂O"}),title:"Chemistry"},{key:"symbols",display:g.jsx("span",{className:"text-lg",children:"∈∞"}),title:"Symbols"},{key:"arrows",display:g.jsx("span",{className:"text-lg font-mono",children:"→…"}),title:"Arrows"},{key:"greek",display:g.jsx("span",{className:"text-lg",children:"αΩ"}),title:"Greek Symbols"},{key:"matrices",display:g.jsx("span",{className:"text-lg",children:"[□]"}),title:"Matrix Templates"},{key:"fences",display:g.jsx("span",{className:"text-lg",children:"(□)"}),title:"Fences & Accents"}],Jo={chem:[[[{display:"H",latex:"H"},{display:"C",latex:"C"}],[{display:"N",latex:"N"},{display:"O",latex:"O"}],[{display:"F",latex:"F"},{display:"S",latex:"S"}]],[[{display:"°",latex:"^{\\circ}"}],[{display:"Δ",latex:"\\Delta "}],[{display:"mol",latex:"\\text{mol}"}]],[[{display:"→",latex:"\\rightarrow "}],[{display:"⇌",latex:"\\rightleftharpoons"}],[{display:"↔",latex:"\\leftrightarrow "}]],[[{display:g.jsxs("span",{className:"text-lg",children:["→",g.jsx("sup",{className:"-top-1.5 text-[8px]",children:"□"})]}),latex:"\\xrightarrow{}"}],[{display:g.jsxs("span",{className:"text-lg",children:["⇌",g.jsx("sup",{className:"-top-1.5 text-[8px]",children:"□"})]}),latex:"\\xrightleftharpoons{}"}]],[[{display:"□²",latex:"^{}"}],[{display:"□₂",latex:"_{}"}],[{display:"□₂²",latex:"_{}^{}"}]],[[{display:"(□)",latex:"({})"}],[{display:"[□]",latex:"[]"}],[{display:"{□}",latex:"\\{\\}"}]]],symbols:[[[{display:"∅",latex:"\\emptyset"},{display:"+",latex:"+"},{display:"×",latex:"\\times"},{display:"·",latex:"\\cdot"},{display:"π",latex:"\\pi"},{display:"∂",latex:"\\partial"},{display:"°",latex:"^\\circ"}],[{display:"−",latex:"-"},{display:"÷",latex:"\\div"},{display:"/",latex:"/"},{display:"∞",latex:"\\infty"},{display:"Δ",latex:"\\Delta"},{display:"′",latex:"\\prime"}],[{display:"±",latex:"\\pm"},{display:"∓",latex:"\\mp"},{display:"∘",latex:"\\circ"},{display:"ø",latex:"\\o"},{display:"∇",latex:"\\nabla"},{display:"″",latex:"\\prime\\prime"}]],[[{display:"=",latex:"="},{display:"≡",latex:"\\equiv"},{display:">",latex:">"},{display:"<",latex:"<"}],[{display:"≠",latex:"\\neq"},{display:"≈",latex:"\\approx"},{display:"≥",latex:"\\geq"},{display:"≤",latex:"\\leq"}],[{display:"∼",latex:"\\sim"},{display:"≃",latex:"\\simeq"},{display:"≫",latex:"\\gg"},{display:"≪",latex:"\\ll"}]],[[{display:"∈",latex:"\\in"},{display:"∃",latex:"\\exists"},{display:"∧",latex:"\\land"},{display:"∨",latex:"\\lor"}],[{display:"∪",latex:"\\cup"},{display:"∩",latex:"\\cap"},{display:"∀",latex:"\\forall"},{display:"¬",latex:"\\neg"}],[{display:"⊂",latex:"\\subset"},{display:"⊃",latex:"\\supset"},{display:"∃!",latex:"\\exists!"},{display:"⊥",latex:"\\perp"}]]],arrows:[[[{display:"←",latex:"\\leftarrow"},{display:"⇐",latex:"\\Leftarrow"},{display:"↖",latex:"\\nwarrow"}],[{display:"→",latex:"\\rightarrow"},{display:"⇒",latex:"\\Rightarrow"},{display:"↗",latex:"\\nearrow"}],[{display:"↔",latex:"\\leftrightarrow"},{display:"⇔",latex:"\\Leftrightarrow"},{display:"↘",latex:"\\searrow"}],[{display:"↦",latex:"\\mapsto"},{display:"↼",latex:"\\leftharpoonup"},{display:"↙",latex:"\\swarrow"}]],[[{display:"…",latex:"\\dots"},{display:"⋮",latex:"\\vdots"},{display:"⋯",latex:"\\cdots"},{display:"⋱",latex:"\\ddots"}]]],greek:[[[{display:"α",latex:"\\alpha"},{display:"κ",latex:"\\kappa"},{display:"σ",latex:"\\sigma"}],[{display:"β",latex:"\\beta"},{display:"λ",latex:"\\lambda"},{display:"τ",latex:"\\tau"}],[{display:"γ",latex:"\\gamma"},{display:"μ",latex:"\\mu"},{display:"υ",latex:"\\upsilon"}],[{display:"δ",latex:"\\delta"},{display:"ν",latex:"\\nu"},{display:"φ",latex:"\\phi"}],[{display:"ε",latex:"\\epsilon"},{display:"ξ",latex:"\\xi"},{display:"χ",latex:"\\chi"}],[{display:"ζ",latex:"\\zeta"},{display:"ο",latex:"\\omicron"},{display:"ψ",latex:"\\psi"}],[{display:"η",latex:"\\eta"},{display:"π",latex:"\\pi"},{display:"ω",latex:"\\omega"}],[{display:"θ",latex:"\\theta"},{display:"ρ",latex:"\\rho"}]],[[{display:"Α",latex:"A"},{display:"Κ",latex:"K"},{display:"Σ",latex:"\\Sigma"}],[{display:"Β",latex:"B"},{display:"Λ",latex:"\\Lambda"},{display:"Τ",latex:"T"}],[{display:"Γ",latex:"\\Gamma"},{display:"Μ",latex:"M"},{display:"Υ",latex:"\\Upsilon"}],[{display:"Δ",latex:"\\Delta"},{display:"Ν",latex:"N"},{display:"Φ",latex:"\\Phi"}]]],matrices:[[[{display:"[::]",latex:"\\begin{bmatrix} {} & {} \\\\ {} & {} \\end{bmatrix}"}],[{display:"⋮",latex:"\\vdots"},{display:"⋯",latex:"\\cdots"},{display:"⋱",latex:"\\ddots"}]]],fences:[[[{display:"(□)",latex:"({})"},{display:"|□|",latex:"|{}|"},{display:"⟨□⟩",latex:"\\langle {} \\rangle"}],[{display:"[□]",latex:"[{}]"},{display:"||□||",latex:"\\|{}|\\|"},{display:"{□}",latex:"\\{{}\\}"}]],[[{display:g.jsx("span",{className:"text-xl",children:"ô"}),latex:"\\hat{}"},{display:g.jsx("span",{className:"text-xl",children:"ō"}),latex:"\\bar{}"},{display:g.jsx("span",{className:"text-xl",children:"ò"}),latex:"\\vec{}"}]]]},Dc=({onInsert:t})=>{const[e,n]=w.useState("chem");return g.jsxs("div",{className:"bg-[#e9eff1] px-2 py-1 flex flex-col space-y-1 shrink-0 border-b border-gray-300",children:[g.jsxs("div",{className:"flex flex-wrap gap-1 items-center",children:[kc.map(o=>g.jsx(Rc,{onClick:()=>n(o.key),isActive:e===o.key,title:o.title,children:o.display},o.key)),g.jsx("div",{className:"flex-grow"}),g.jsx("button",{title:"Help",className:"w-8 h-8 rounded-full bg-gray-400 hover:bg-gray-500 text-white flex items-center justify-center shadow-sm transition-all",children:g.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:g.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})})})]}),g.jsxs("div",{className:"flex items-start bg-white rounded border border-gray-300 min-h-[5rem] shadow-inner p-1 overflow-x-auto",children:[g.jsx("div",{className:"flex items-start",children:Jo[e].map((o,s)=>g.jsxs(w.Fragment,{children:[g.jsx("div",{className:"flex flex-col",children:o.map((l,a)=>g.jsx("div",{className:"flex",children:l.map((u,c)=>g.jsx(Pc,{symbol:u,onInsert:t},c))},a))}),s<Jo[e].length-1&&g.jsx("div",{className:"w-px bg-gray-300 mx-1 self-stretch"})]},s))}),g.jsx("div",{className:"flex-grow"}),g.jsx("div",{className:"flex items-center space-x-2 shrink-0 self-center pr-2",children:g.jsxs("div",{className:"flex flex-col space-y-1",children:[g.jsx("select",{disabled:!0,className:"text-sm border border-gray-300 rounded h-6 w-32 px-1 text-black opacity-50",children:g.jsx("option",{children:"Font..."})}),g.jsx("select",{disabled:!0,className:"text-sm border border-gray-300 rounded h-6 w-32 px-1 text-black opacity-50",children:g.jsx("option",{children:"Size..."})})]})})]})]})},Uc=({isOpen:t,onClose:e,onInsert:n,apiKey:o=""})=>{const s=w.useRef(null),l=w.useRef(null),[a,u]=w.useState(!1),[c,d]=w.useState(null),[f,h]=w.useState(""),[p,m]=w.useState("keyboard"),[y,_]=w.useState("math"),[T,E]=w.useState(!1),[C,v]=w.useState(!1),[I,A]=w.useState(""),[P,N]=w.useState(!1);w.useEffect(()=>{if(p==="keyboard"&&f.trim()&&window.katex)try{const k=window.katex.renderToString(f,{throwOnError:!0,displayMode:!1,output:"mathml"});A(k),N(!0)}catch{A('<span class="text-red-500 text-xs">Invalid formula syntax</span>'),N(!1)}else A(""),N(!1)},[f,p]);const U=k=>{_(k),k==="chem"&&m("keyboard")},x=w.useCallback(()=>{var k;(k=s.current)==null||k.clear(),h(""),d(null),u(!1)},[]),R=w.useCallback(k=>{const D=l.current;if(!D){h(X=>X+k);return}const G=D.selectionStart,$=D.selectionEnd,H=f.substring(0,G)+k+f.substring($);h(H),setTimeout(()=>{D.focus(),D.selectionStart=D.selectionEnd=G+k.length},0)},[f]),b=w.useCallback(async()=>{var D,G;if(!o){d("Please configure your Gemini API key in the main editor.");return}const k=(D=s.current)==null?void 0:D.getTrimmedImageData();if(!k){d("Draw a formula on the pad first.");return}u(!0),d(null);try{const $=k.split(",")[1],H=await Sc($,o);R(H),m("keyboard"),(G=s.current)==null||G.clear()}catch($){d($.message||"AI recognition failed.")}finally{u(!1)}},[o,R]);return t?g.jsx("div",{className:"fixed inset-0 z-[100] flex items-center justify-center bg-slate-900/40 backdrop-blur-md p-4 animate-in fade-in duration-200",children:g.jsxs("div",{className:"bg-white rounded-2xl shadow-2xl flex flex-col w-full max-w-4xl h-[600px] border border-slate-200 overflow-hidden",onClick:k=>k.stopPropagation(),children:[g.jsxs("header",{className:"px-6 py-4 border-b border-slate-100 flex items-center justify-between bg-slate-50/50",children:[g.jsxs("div",{className:"flex items-center gap-6",children:[g.jsx("h2",{className:"text-lg font-bold text-slate-900",children:"AI Formula Pad"}),g.jsxs("div",{className:"flex bg-slate-200 p-1 rounded-lg",children:[g.jsx("button",{onClick:()=>U("math"),className:`px-4 py-1 text-xs font-semibold rounded-md transition-all ${y==="math"?"bg-white shadow text-blue-600":"text-slate-500"}`,children:"Math"}),g.jsx("button",{onClick:()=>U("chem"),className:`px-4 py-1 text-xs font-semibold rounded-md transition-all ${y==="chem"?"bg-white shadow text-blue-600":"text-slate-500"}`,children:"Chemistry"})]})]}),g.jsx("button",{onClick:e,className:"p-2 hover:bg-slate-200 rounded-full text-slate-400 hover:text-slate-600 transition-colors",children:g.jsx(gi,{size:20})})]}),g.jsxs("div",{className:"flex-1 flex overflow-hidden",children:[g.jsxs("div",{className:"w-16 border-r border-slate-100 flex flex-col items-center py-6 gap-4 bg-slate-50/30",children:[g.jsx("button",{onClick:()=>m("keyboard"),className:`p-3 rounded-xl transition-all ${p==="keyboard"?"bg-blue-600 text-white shadow-lg":"text-slate-400 hover:text-slate-600"}`,children:g.jsx(ti,{size:24})}),y==="math"&&g.jsx("button",{onClick:()=>m("handwriting"),className:`p-3 rounded-xl transition-all ${p==="handwriting"?"bg-blue-600 text-white shadow-lg":"text-slate-400 hover:text-slate-600"}`,children:g.jsx(ri,{size:24})})]}),g.jsxs("div",{className:"flex-1 flex flex-col overflow-hidden",children:[g.jsx("div",{className:"shrink-0",children:p==="keyboard"&&(y==="math"?g.jsx(Mc,{onInsert:R}):g.jsx(Dc,{onInsert:R}))}),g.jsx("div",{className:"flex-1 p-6 relative bg-slate-50/20",children:p==="keyboard"?g.jsxs("div",{className:"h-full flex flex-col gap-4",children:[g.jsx("textarea",{ref:l,value:f,onChange:k=>h(k.target.value),className:"flex-1 w-full p-6 border border-slate-200 rounded-xl shadow-inner focus:outline-none focus:ring-2 focus:ring-blue-500/10 font-mono text-xl text-slate-800",placeholder:`Enter LaTeX for ${y}...`}),g.jsx("div",{className:"h-20 bg-white border border-slate-100 rounded-xl flex items-center justify-center p-4 shadow-sm overflow-auto",children:I?g.jsx("div",{dangerouslySetInnerHTML:{__html:I}}):g.jsx("span",{className:"text-slate-300 italic",children:"Preview will appear here"})})]}):g.jsxs("div",{className:"h-full border border-slate-200 bg-white rounded-2xl shadow-inner overflow-hidden relative",children:[g.jsx(ft,{ref:s,onHistoryChange:k=>{E(k.canUndo),v(k.canRedo)}}),g.jsxs("div",{className:"absolute top-4 right-4 flex flex-col gap-2",children:[g.jsx("button",{onClick:()=>{var k;return(k=s.current)==null?void 0:k.undo()},disabled:!T,className:"p-2 bg-white border border-slate-200 rounded-lg shadow-sm disabled:opacity-30 hover:bg-slate-50",children:g.jsx(ai,{size:18})}),g.jsx("button",{onClick:()=>{var k;return(k=s.current)==null?void 0:k.redo()},disabled:!C,className:"p-2 bg-white border border-slate-200 rounded-lg shadow-sm disabled:opacity-30 hover:bg-slate-50",children:g.jsx(ui,{size:18})}),g.jsx("button",{onClick:x,className:"p-2 bg-white border border-slate-200 rounded-lg shadow-sm text-red-500 hover:bg-red-50",children:g.jsx(pi,{size:18})})]}),g.jsx("div",{className:"absolute bottom-6 left-1/2 -translate-x-1/2 flex gap-4",children:g.jsxs("button",{onClick:b,disabled:a,className:"px-8 py-2.5 bg-blue-600 text-white rounded-full font-bold shadow-xl hover:bg-blue-700 transition flex items-center gap-2 disabled:bg-slate-400",children:[a?g.jsx(ii,{className:"animate-spin",size:18}):null,a?"Processing...":"Recognize Drawing"]})})]})})]})]}),g.jsxs("footer",{className:"px-6 py-4 border-t border-slate-100 flex justify-between items-center bg-slate-50/50",children:[c&&g.jsx("span",{className:"text-sm font-medium text-red-500 animate-pulse",children:c}),g.jsxs("div",{className:"ml-auto flex gap-3",children:[g.jsx("button",{onClick:e,className:"px-6 py-2 text-slate-600 font-semibold hover:bg-slate-200 rounded-xl transition",children:"Cancel"}),g.jsx("button",{onClick:()=>{n(I),e()},disabled:!P,className:"px-8 py-2 bg-slate-900 text-white font-bold rounded-xl shadow-lg disabled:opacity-40 hover:bg-slate-800 transition",children:"Insert Into Editor"})]})]})]})}):null},$o=w.forwardRef(({initialContent:t="",onChange:e,apiKey:n},o)=>{const s=w.useRef(null),[l,a]=w.useState(!1),[u,c]=w.useState([t]),[d,f]=w.useState(0),h=d>0,p=d<u.length-1,m=w.useCallback(E=>{if(E===u[d])return;const C=u.slice(0,d+1);C.push(E),C.length>50&&C.shift(),c(C),f(C.length-1),e==null||e(E)},[u,d,e]);w.useImperativeHandle(o,()=>({getContent:()=>{var E;return((E=s.current)==null?void 0:E.innerHTML)||""},setContent:E=>{s.current&&(s.current.innerHTML=E,m(E))}})),w.useEffect(()=>{s.current&&t&&!s.current.innerHTML&&(s.current.innerHTML=t)},[t]);const y=(E,C)=>{var v,I;(v=s.current)==null||v.focus(),document.execCommand(E,!1,C),m(((I=s.current)==null?void 0:I.innerHTML)||"")},_=()=>{if(h){const E=d-1;f(E),s.current&&(s.current.innerHTML=u[E],e==null||e(u[E]))}},T=()=>{if(p){const E=d+1;f(E),s.current&&(s.current.innerHTML=u[E],e==null||e(u[E]))}};return g.jsxs("div",{className:"w-full max-w-5xl bg-white rounded-2xl shadow-xl border border-slate-200 overflow-hidden flex flex-col min-h-[700px] transition-all duration-300",children:[g.jsx(yi,{onApplyStyle:y,onOpenHandwritingModal:()=>a(!0),onUndo:_,onRedo:T,canUndo:h,canRedo:p}),g.jsx("div",{ref:s,contentEditable:!0,onInput:()=>{var E;return m(((E=s.current)==null?void 0:E.innerHTML)||"")},className:"flex-1 p-10 outline-none prose prose-slate prose-lg max-w-none prose-headings:font-bold prose-a:text-blue-600 prose-img:rounded-xl prose-table:border border-slate-100 bg-white",style:{minHeight:"600px",fontVariantLigatures:"common-ligatures"}}),l&&g.jsx(Uc,{isOpen:l,onClose:()=>a(!1),onInsert:E=>{var C,v;(C=s.current)==null||C.focus(),document.execCommand("insertHTML",!1,`<span contenteditable="false" class="math-container inline-block mx-1 align-middle">${E}</span>&nbsp;`),m(((v=s.current)==null?void 0:v.innerHTML)||"")},apiKey:n})]})});$o.displayName="Editor",ee.Editor=$o,Object.defineProperty(ee,Symbol.toStringTag,{value:"Module"})});