@cortex-agent/server 2026.10.28 → 2026.12.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (401) hide show
  1. package/LICENSE +255 -21
  2. package/README.md +36 -7
  3. package/THIRD_PARTY_NOTICES.txt +1990 -593
  4. package/defaults/hooks/cortex-hook-api.mjs +2 -1
  5. package/defaults/hooks/quota-stop.mjs +37 -0
  6. package/defaults/plugins/cortex-system/skills/client-manage/SKILL.md +23 -15
  7. package/defaults/prompts/clean-workspace.md +5 -0
  8. package/dist/agent-adapter/claude/remote-mcp-proxy.js +1 -1
  9. package/dist/chunks/agent-runner-LVZVKBZX.js +4 -0
  10. package/dist/chunks/anthropic-messages-TT6454AA.js +8 -0
  11. package/dist/chunks/azure-openai-responses-52LR2XZD.js +4 -0
  12. package/dist/chunks/bedrock-converse-stream-EOZGYUNY.js +60 -0
  13. package/dist/chunks/bowser-MLGGLXTZ.js +20 -0
  14. package/dist/chunks/child-runner-SMG2VOU5.js +4 -0
  15. package/dist/chunks/chunk-24DH4IR5.js +4 -0
  16. package/dist/chunks/chunk-25XKBRDT.js +70 -0
  17. package/dist/chunks/chunk-2ABET62E.js +23 -0
  18. package/dist/chunks/chunk-2BVUA256.js +4 -0
  19. package/dist/chunks/{chunk-LEUENXI2.js → chunk-2WFL62UO.js} +1 -1
  20. package/dist/chunks/{chunk-OZGBWAT2.js → chunk-2YTYYG4K.js} +1 -1
  21. package/dist/chunks/chunk-335SSANX.js +4 -0
  22. package/dist/chunks/chunk-377OPTXX.js +17 -0
  23. package/dist/chunks/chunk-3EZNVLBF.js +129 -0
  24. package/dist/chunks/chunk-3O6ZG5HA.js +7 -0
  25. package/dist/chunks/{chunk-6AKUD3CF.js → chunk-3XLHL5YT.js} +1 -1
  26. package/dist/chunks/chunk-4HRI75GU.js +4 -0
  27. package/dist/chunks/chunk-4JBYLRPM.js +57 -0
  28. package/dist/chunks/chunk-4KKV7VKE.js +4 -0
  29. package/dist/chunks/chunk-4KQHDDC5.js +4 -0
  30. package/dist/chunks/chunk-4SWD4JMP.js +33 -0
  31. package/dist/chunks/chunk-52VCLZS5.js +4 -0
  32. package/dist/chunks/chunk-54P7TSY3.js +10 -0
  33. package/dist/chunks/chunk-5DVSAXOI.js +7 -0
  34. package/dist/chunks/chunk-5F3A62YS.js +4 -0
  35. package/dist/chunks/{chunk-XNSSUVT6.js → chunk-5FHETFZM.js} +1 -1
  36. package/dist/chunks/{chunk-A34TDMIC.js → chunk-5LBLRAHS.js} +1 -1
  37. package/dist/chunks/chunk-5UYVNA3W.js +4 -0
  38. package/dist/chunks/chunk-6G3OYMCV.js +21 -0
  39. package/dist/chunks/chunk-7GGPYU5E.js +30 -0
  40. package/dist/chunks/chunk-7TYSMLUV.js +4 -0
  41. package/dist/chunks/chunk-7W7VYUTK.js +5 -0
  42. package/dist/chunks/chunk-AXYAZTTN.js +6 -0
  43. package/dist/chunks/{chunk-BGVHA2D4.js → chunk-B3NB243Z.js} +1 -1
  44. package/dist/chunks/chunk-BKYP6AGM.js +8 -0
  45. package/dist/chunks/chunk-BVEDNESB.js +4 -0
  46. package/dist/chunks/chunk-BWDJS6A4.js +12 -0
  47. package/dist/chunks/chunk-C6YVF7EI.js +4 -0
  48. package/dist/chunks/chunk-CEJIYYVE.js +15 -0
  49. package/dist/chunks/chunk-CI2RHH74.js +50 -0
  50. package/dist/chunks/chunk-CMSOOLJB.js +4 -0
  51. package/dist/chunks/chunk-CSVTYYLP.js +4 -0
  52. package/dist/chunks/chunk-DE5EGVKG.js +6 -0
  53. package/dist/chunks/{chunk-E6BYRULL.js → chunk-DK3RPZOQ.js} +1 -1
  54. package/dist/chunks/{chunk-YPK2CAIZ.js → chunk-DK4UCK7L.js} +1 -1
  55. package/dist/chunks/chunk-DYLBVUAU.js +4 -0
  56. package/dist/chunks/chunk-FDC2GRBK.js +27 -0
  57. package/dist/chunks/chunk-FE7HH5JS.js +18 -0
  58. package/dist/chunks/chunk-FYD57YRO.js +436 -0
  59. package/dist/chunks/chunk-G264APQN.js +5 -0
  60. package/dist/chunks/chunk-G4JYZFEO.js +11 -0
  61. package/dist/chunks/chunk-GFFM56U2.js +4 -0
  62. package/dist/chunks/chunk-GOS3P7KS.js +132 -0
  63. package/dist/chunks/chunk-HVN37UXD.js +4 -0
  64. package/dist/chunks/chunk-IA6IODY3.js +4 -0
  65. package/dist/chunks/{chunk-HU6UIDEJ.js → chunk-IGZWZP7Z.js} +1 -1
  66. package/dist/chunks/{chunk-NR6U3WIZ.js → chunk-IJ7XFQMI.js} +1 -1
  67. package/dist/chunks/chunk-IMMGYDAB.js +6 -0
  68. package/dist/chunks/chunk-IOWBF7UK.js +10 -0
  69. package/dist/chunks/{chunk-HALUQ7ZF.js → chunk-ITGCWQFK.js} +1 -1
  70. package/dist/chunks/chunk-IVZ7QUEG.js +4 -0
  71. package/dist/chunks/{chunk-YAEVYJAR.js → chunk-IWY2HIFK.js} +1 -1
  72. package/dist/chunks/{chunk-KGJZAYQD.js → chunk-J7OBATRN.js} +1 -1
  73. package/dist/chunks/{chunk-QWAQHHRS.js → chunk-JGUEIW2W.js} +1 -1
  74. package/dist/chunks/chunk-JKL3AK5D.js +106 -0
  75. package/dist/chunks/chunk-JZ7U7RUK.js +351 -0
  76. package/dist/chunks/chunk-KJUQCCB5.js +4 -0
  77. package/dist/chunks/chunk-KST6OY76.js +10 -0
  78. package/dist/chunks/chunk-KZSAFVSY.js +129 -0
  79. package/dist/chunks/chunk-LD2ZSH3M.js +903 -0
  80. package/dist/chunks/chunk-LE6QPXN6.js +7 -0
  81. package/dist/chunks/chunk-LEAV3FFG.js +4 -0
  82. package/dist/chunks/chunk-LIIZI3HY.js +5 -0
  83. package/dist/chunks/chunk-LP72AF56.js +45 -0
  84. package/dist/chunks/{chunk-FXDIR3SQ.js → chunk-MJQ2D2OP.js} +1 -1
  85. package/dist/chunks/{chunk-6LZK4DDH.js → chunk-NHHR4DCF.js} +1 -1
  86. package/dist/chunks/chunk-NW4GW47L.js +4 -0
  87. package/dist/chunks/chunk-OALEJ6FG.js +60 -0
  88. package/dist/chunks/chunk-OIV4DIMB.js +4 -0
  89. package/dist/chunks/chunk-OJ37ZWBG.js +4 -0
  90. package/dist/chunks/chunk-OZXMPBUX.js +4 -0
  91. package/dist/chunks/{chunk-3THJYAEF.js → chunk-PG7452XE.js} +1 -1
  92. package/dist/chunks/chunk-PJCUB7YJ.js +4 -0
  93. package/dist/chunks/chunk-PTS3J4DQ.js +6 -0
  94. package/dist/chunks/{chunk-PXS5SHOV.js → chunk-PVVEEBUU.js} +1 -1
  95. package/dist/chunks/chunk-Q7BZLPBU.js +8 -0
  96. package/dist/chunks/{chunk-FOJQXLL2.js → chunk-QC66ZXPP.js} +1 -1
  97. package/dist/chunks/chunk-QXFWIL4C.js +4 -0
  98. package/dist/chunks/{chunk-PFMEUFJ7.js → chunk-R2CCD4OF.js} +1 -1
  99. package/dist/chunks/chunk-R6CGBSTC.js +22 -0
  100. package/dist/chunks/chunk-RG5GP4RB.js +5 -0
  101. package/dist/chunks/{chunk-D3NXKK2L.js → chunk-RW2F2QNP.js} +1 -1
  102. package/dist/chunks/{models-L5VF4I5O-XXNJYQMQ.js → chunk-RWPO3NZ3.js} +1 -1
  103. package/dist/chunks/chunk-SAJD4EKE.js +10 -0
  104. package/dist/chunks/chunk-SDUS2H3E.js +4 -0
  105. package/dist/chunks/chunk-SIHGKM4E.js +4 -0
  106. package/dist/chunks/chunk-SKHFU5DI.js +4 -0
  107. package/dist/chunks/{chunk-STUHNKQS.js → chunk-SM45TH22.js} +1 -1
  108. package/dist/chunks/chunk-T54CZKNJ.js +6 -0
  109. package/dist/chunks/chunk-TKFFQNAP.js +19 -0
  110. package/dist/chunks/chunk-TMV2ZDOI.js +18 -0
  111. package/dist/chunks/chunk-TRXLIL7V.js +4 -0
  112. package/dist/chunks/{chunk-SUFW24P4.js → chunk-UEEW2R4E.js} +1 -1
  113. package/dist/chunks/chunk-UHXPRU6G.js +10 -0
  114. package/dist/chunks/chunk-UPQVWHZ3.js +4 -0
  115. package/dist/chunks/{chunk-JERCOLY3.js → chunk-V35MFAUQ.js} +4 -6
  116. package/dist/chunks/chunk-V7K3KNDM.js +4 -0
  117. package/dist/chunks/chunk-VHX2GHBF.js +4 -0
  118. package/dist/chunks/chunk-VOAKRJ4R.js +4 -0
  119. package/dist/chunks/{chunk-X2GYYRVM.js → chunk-VW7TLY3P.js} +1 -1
  120. package/dist/chunks/chunk-W34AK4SK.js +65 -0
  121. package/dist/chunks/{chunk-REBNWCKI.js → chunk-WU7RNAZD.js} +1 -1
  122. package/dist/chunks/chunk-WZC4TDDM.js +6 -0
  123. package/dist/chunks/chunk-WZYS2HAK.js +4 -0
  124. package/dist/chunks/chunk-X2TKJ7KR.js +11 -0
  125. package/dist/chunks/{chunk-H2FP6DG4.js → chunk-X5ND4H4P.js} +1 -1
  126. package/dist/chunks/{chunk-4U7XXM4W.js → chunk-Y3AOGNDT.js} +1 -1
  127. package/dist/chunks/chunk-Y6DGVTKM.js +6 -0
  128. package/dist/chunks/{chunk-KENCMLRE.js → chunk-YAEHSSR4.js} +1 -1
  129. package/dist/chunks/chunk-YWPBE5LP.js +4 -0
  130. package/dist/chunks/chunk-ZAVX7G2M.js +15 -0
  131. package/dist/chunks/chunk-ZD2M73XA.js +19 -0
  132. package/dist/chunks/chunk-ZD4O6NPV.js +4 -0
  133. package/dist/chunks/chunk-ZNAMETPQ.js +4 -0
  134. package/dist/chunks/chunk-ZY6N5LVQ.js +4 -0
  135. package/dist/chunks/chunk-ZYQ4TDTT.js +81 -0
  136. package/dist/chunks/cli-VB2N7HEK.js +55 -0
  137. package/dist/chunks/cloudflare-workers-ai-system-one-YKU742EC.js +4 -0
  138. package/dist/chunks/context-CI2FKEQE.js +4 -0
  139. package/dist/chunks/cost-CZRRSIUF.js +5 -0
  140. package/dist/chunks/dist-QCNQN6DY.js +4 -0
  141. package/dist/chunks/easter-egg-3d-XR5S2O3T.js +4 -0
  142. package/dist/chunks/{event-streams-3JSFPOTZ.js → event-streams-AVE4MSS6.js} +1 -1
  143. package/dist/chunks/{execution-repo-ZLJTBWFC.js → execution-repo-5TLV2NM4.js} +1 -1
  144. package/dist/chunks/{executions-6ARGR3IO.js → executions-I3UUIGSL.js} +1 -1
  145. package/dist/chunks/file-Y5G56IUT.js +4 -0
  146. package/dist/chunks/github-copilot-BRU2SRRZ.js +4 -0
  147. package/dist/chunks/google-generative-ai-ZF5QEUZV.js +4 -0
  148. package/dist/chunks/google-vertex-4PJZZI3Y.js +4 -0
  149. package/dist/chunks/init-A6GY656J.js +4 -0
  150. package/dist/chunks/{install-cli-4IZCSDFZ.js → install-cli-FALWKQYO.js} +1 -1
  151. package/dist/chunks/{interaction-ask-G5T3H3CG.js → interaction-ask-O5HGF6CH.js} +1 -1
  152. package/dist/chunks/{interaction-plan-E5V42MUP.js → interaction-plan-JTVDN3BC.js} +1 -1
  153. package/dist/chunks/kimi-coding-ZCIBMDZ6.js +4 -0
  154. package/dist/chunks/{llama-cpp-classify-OTXZWCMW.js → llama-cpp-classify-NRUXAIGQ.js} +3 -3
  155. package/dist/chunks/local-client-stop-RS4AHNF4.js +4 -0
  156. package/dist/chunks/{memory-cli-PYOILNN5.js → memory-cli-DIT4DQF3.js} +1 -1
  157. package/dist/chunks/meta-JQH66YU7.js +4 -0
  158. package/dist/chunks/mistral-conversations-CXHOECUV.js +7 -0
  159. package/dist/chunks/model-resolver-GIBPYRKP.js +4 -0
  160. package/dist/chunks/monitor-Z2HKNY5E.js +4 -0
  161. package/dist/chunks/{node-PTK2HCDV.js → node-DAO3SX7O.js} +1 -1
  162. package/dist/chunks/{openai-codex-2REL6UQU.js → openai-codex-JULCKICT.js} +1 -1
  163. package/dist/chunks/openai-codex-responses-U6DGMGDK.js +12 -0
  164. package/dist/chunks/openai-completions-PP4XLLOM.js +9 -0
  165. package/dist/chunks/{openai-decisions-2N6ZRPZC.js → openai-decisions-JU6QQKEM.js} +1 -1
  166. package/dist/chunks/openai-responses-2SG757TL.js +6 -0
  167. package/dist/chunks/openrouter-images-32M7YZWC.js +4 -0
  168. package/dist/chunks/pi-messages-VSINMXN4.js +10 -0
  169. package/dist/chunks/radius-THYKWV4E.js +4 -0
  170. package/dist/chunks/remote-ops-2WBEFQ3E.js +14 -0
  171. package/dist/chunks/runner-5MKMRTIN.js +4 -0
  172. package/dist/chunks/runtime-DST3H5JP.js +4 -0
  173. package/dist/chunks/schedule-cli-V7Y2BBVY.js +4 -0
  174. package/dist/chunks/slack-R7SEJYMY.js +4 -0
  175. package/dist/chunks/start-ui-http-7K5JOLPU.js +43 -0
  176. package/dist/chunks/subagent-Z5IQ4L54.js +4 -0
  177. package/dist/chunks/{time-KEHDQT6K.js → time-P6PE52WL.js} +1 -1
  178. package/dist/chunks/tool-shims-YCXZWTST.js +4 -0
  179. package/dist/chunks/typesafe-system-one-M2DABJSZ.js +4 -0
  180. package/dist/chunks/ui-board-HQIE4RZG.js +5 -0
  181. package/dist/chunks/ui-decision-YBZDS4YW.js +4 -0
  182. package/dist/chunks/{ui-file-GVH53O3X.js → ui-file-SRD4ILBS.js} +1 -1
  183. package/dist/chunks/ui-view-Z25MTZT7.js +4 -0
  184. package/dist/chunks/virtual-modules-H4DXPJZB.js +4 -0
  185. package/dist/chunks/waitpoint-M6JZBSLT.js +5 -0
  186. package/dist/chunks/workers-SQ2R32TK.js +4 -0
  187. package/dist/client-bundle/client.mjs +273 -93
  188. package/dist/client-bundle/manifest.json +2 -2
  189. package/dist/core/pi-sdk.js +1 -1
  190. package/dist/domain/auth/cc-auth-cli.js +1 -1
  191. package/dist/domain/mcp/bundled-server.js +1 -1
  192. package/dist/domain/mcp/feishu/client.js +4 -0
  193. package/dist/entry/app.js +151 -559
  194. package/dist/entry/browser-cli.js +10 -10
  195. package/dist/entry/cli.js +1 -1
  196. package/dist/entry/cortex-cli.js +1 -1
  197. package/dist/entry/daemon.js +4 -4
  198. package/dist/entry/hook-cli.js +2 -2
  199. package/dist/entry/production-app-bootstrap.js +1 -1
  200. package/dist/entry/production-evidence-export-cli.js +1 -1
  201. package/dist/entry/signal-cli.js +2 -2
  202. package/dist/tui/index.js +41 -41
  203. package/package.json +3 -3
  204. package/vendor/pi/CHANGELOG.md +330 -0
  205. package/vendor/pi/dist/codemode-worker.js +2 -0
  206. package/vendor/pi/dist/core/export-html/ansi-to-html.js +57 -20
  207. package/vendor/pi/dist/core/export-html/template.css +9 -0
  208. package/vendor/pi/dist/core/export-html/template.js +166 -46
  209. package/vendor/pi/dist/core/export-html/tool-renderer.js +5 -3
  210. package/vendor/pi/dist/core/extensions/loader.js +1 -1
  211. package/vendor/pi/dist/extensions/codemode/execute.js +15 -13
  212. package/vendor/pi/dist/modes/interactive/theme/theme.js +36 -23
  213. package/vendor/pi/dist/utils/image-resize-worker.js +1 -1
  214. package/vendor/pi/dist/utils/image-resize.js +1 -1
  215. package/vendor/pi/docs/cli.md +35 -12
  216. package/vendor/pi/docs/custom-provider.md +2 -0
  217. package/vendor/pi/docs/environment-variables.md +2 -0
  218. package/vendor/pi/docs/extensions.md +3192 -225
  219. package/vendor/pi/docs/keybindings.md +2 -2
  220. package/vendor/pi/docs/llama-cpp.md +27 -19
  221. package/vendor/pi/docs/mcp.md +6 -4
  222. package/vendor/pi/docs/message-types.md +1 -1
  223. package/vendor/pi/docs/models-configuration.md +9 -3
  224. package/vendor/pi/docs/models.md +2 -1
  225. package/vendor/pi/docs/nvidia-rtx-llama-cpp.md +5 -5
  226. package/vendor/pi/docs/packages.md +24 -0
  227. package/vendor/pi/docs/prompt-templates.md +1 -1
  228. package/vendor/pi/docs/providers.md +4 -2
  229. package/vendor/pi/docs/quickstart.md +7 -3
  230. package/vendor/pi/docs/rpc-commands.md +1 -1
  231. package/vendor/pi/docs/rpc.md +4 -2
  232. package/vendor/pi/docs/sessions.md +17 -3
  233. package/vendor/pi/docs/settings.md +6 -5
  234. package/vendor/pi/docs/slash-commands.md +3 -2
  235. package/vendor/pi/docs/terminal-setup.md +3 -1
  236. package/vendor/pi/docs/tmux.md +6 -0
  237. package/vendor/pi/docs/tui.md +4 -0
  238. package/vendor/pi/docs/windows.md +27 -0
  239. package/vendor/pi/examples/extensions/README.md +2 -1
  240. package/vendor/pi/examples/extensions/custom-provider-anthropic/index.ts +27 -31
  241. package/vendor/pi/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  242. package/vendor/pi/examples/extensions/custom-provider-anthropic/package.json +1 -1
  243. package/vendor/pi/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  244. package/vendor/pi/examples/extensions/debug-provider.ts +2 -2
  245. package/vendor/pi/examples/extensions/gondolin/index.ts +4 -7
  246. package/vendor/pi/examples/extensions/gondolin/package-lock.json +19 -29
  247. package/vendor/pi/examples/extensions/gondolin/package.json +2 -2
  248. package/vendor/pi/examples/extensions/plan-mode/index.ts +23 -13
  249. package/vendor/pi/examples/extensions/plan-mode/utils.ts +42 -16
  250. package/vendor/pi/examples/extensions/preset.ts +2 -0
  251. package/vendor/pi/examples/extensions/reload-runtime.ts +17 -5
  252. package/vendor/pi/examples/extensions/subagent/README.md +14 -11
  253. package/vendor/pi/examples/extensions/subagent/index.ts +392 -171
  254. package/vendor/pi/examples/extensions/todo.ts +7 -0
  255. package/vendor/pi/examples/extensions/tools.ts +2 -0
  256. package/vendor/pi/examples/extensions/with-deps/package-lock.json +2 -2
  257. package/vendor/pi/examples/extensions/with-deps/package.json +1 -1
  258. package/vendor/pi/examples/tsconfig.json +208 -0
  259. package/vendor/pi/package.json +15 -16
  260. package/vendor/pi/schemas/models.schema.json +66 -37
  261. package/vendor/pi/schemas/settings.schema.json +18 -1
  262. package/vendor/pi-ai/bedrock.js +1 -1
  263. package/vendor/pi-ai/oauth-load.js +1 -1
  264. package/web/dist/assets/{board-math-css-BPXakv_3.js → board-math-css-DKX6FcUS.js} +1 -1
  265. package/web/dist/assets/index-D11wi0uG.js +540 -0
  266. package/web/dist/assets/index-JedYumhY.css +1 -0
  267. package/web/dist/assets/{index-WCm6wwmM.js → index-jl30Gy8P.js} +1 -1
  268. package/web/dist/assets/pdf-worker-DdZgk2mV.js +57 -0
  269. package/web/dist/assets/pdf.worker.min-Bz_KHX45.js +55 -0
  270. package/web/dist/index.html +2 -2
  271. package/web/dist/theme.css +22 -0
  272. package/dist/chunks/anthropic-messages-M3SMXACA.js +0 -8
  273. package/dist/chunks/api-GM53PHIL-GFHEXXE6.js +0 -4
  274. package/dist/chunks/azure-openai-responses-76YWXHSB.js +0 -4
  275. package/dist/chunks/bedrock-converse-stream-5UPX4NTQ.js +0 -58
  276. package/dist/chunks/child-runner-3GHOWGZP.js +0 -4
  277. package/dist/chunks/chunk-2ZNLUY2U.js +0 -128
  278. package/dist/chunks/chunk-3F6WW7HR.js +0 -13
  279. package/dist/chunks/chunk-3OKHUVEM.js +0 -7
  280. package/dist/chunks/chunk-3YHOCPQU.js +0 -10
  281. package/dist/chunks/chunk-4EX2JJWB.js +0 -4
  282. package/dist/chunks/chunk-4LLH5OWM.js +0 -10
  283. package/dist/chunks/chunk-52T37Y47.js +0 -8
  284. package/dist/chunks/chunk-7MU2AKNM.js +0 -4
  285. package/dist/chunks/chunk-AAA3UBIS.js +0 -4
  286. package/dist/chunks/chunk-ASYQHJVQ.js +0 -9
  287. package/dist/chunks/chunk-BKHDWCRT.js +0 -79
  288. package/dist/chunks/chunk-CQLH4UVX.js +0 -4
  289. package/dist/chunks/chunk-CVC66CFV.js +0 -33
  290. package/dist/chunks/chunk-D6UA4BZC.js +0 -19
  291. package/dist/chunks/chunk-DGMNI4AO.js +0 -4
  292. package/dist/chunks/chunk-DHSA5ACV.js +0 -125
  293. package/dist/chunks/chunk-DPQPXBTP.js +0 -68
  294. package/dist/chunks/chunk-DXBSQXJL.js +0 -18
  295. package/dist/chunks/chunk-E7ZMYIY6.js +0 -30
  296. package/dist/chunks/chunk-EQITBTJC.js +0 -10
  297. package/dist/chunks/chunk-EXJA5RIX.js +0 -357
  298. package/dist/chunks/chunk-FF7UELTU.js +0 -4
  299. package/dist/chunks/chunk-FH74NME3.js +0 -115
  300. package/dist/chunks/chunk-FOQ7VLIL.js +0 -17
  301. package/dist/chunks/chunk-FX6MOGLR.js +0 -11
  302. package/dist/chunks/chunk-G2V65UBA.js +0 -4
  303. package/dist/chunks/chunk-HGPBHTVD.js +0 -6
  304. package/dist/chunks/chunk-J5DVLUKY.js +0 -6
  305. package/dist/chunks/chunk-JW2HFMTF.js +0 -4
  306. package/dist/chunks/chunk-KDYEGGMW.js +0 -4
  307. package/dist/chunks/chunk-KIGMAATV.js +0 -23
  308. package/dist/chunks/chunk-KIU5FAPY.js +0 -5
  309. package/dist/chunks/chunk-KIWMQPH7.js +0 -739
  310. package/dist/chunks/chunk-L6VCIGWS.js +0 -11
  311. package/dist/chunks/chunk-LACGULCN.js +0 -10
  312. package/dist/chunks/chunk-LMSQZ6TQ.js +0 -4
  313. package/dist/chunks/chunk-MEPASGPP.js +0 -6
  314. package/dist/chunks/chunk-MFAEUHMV.js +0 -28
  315. package/dist/chunks/chunk-NAA7GF6Q.js +0 -5
  316. package/dist/chunks/chunk-NKDMKRSB.js +0 -68
  317. package/dist/chunks/chunk-NKXV32S6.js +0 -4
  318. package/dist/chunks/chunk-NVX5IPRN.js +0 -4
  319. package/dist/chunks/chunk-O3JW2F7D.js +0 -8
  320. package/dist/chunks/chunk-OE4KH3NJ.js +0 -4
  321. package/dist/chunks/chunk-OISO5JXB.js +0 -4
  322. package/dist/chunks/chunk-OPYXNSMY.js +0 -4
  323. package/dist/chunks/chunk-OSEIQ7SS.js +0 -4
  324. package/dist/chunks/chunk-P52RMIYX.js +0 -6
  325. package/dist/chunks/chunk-PBJ5MPPX.js +0 -60
  326. package/dist/chunks/chunk-PZMGBKUR.js +0 -13
  327. package/dist/chunks/chunk-PZMXHA6X.js +0 -9
  328. package/dist/chunks/chunk-Q7CE3UIE.js +0 -133
  329. package/dist/chunks/chunk-QBKCAIJG.js +0 -4
  330. package/dist/chunks/chunk-QEOFEETJ.js +0 -4
  331. package/dist/chunks/chunk-QUUEQRIT.js +0 -4
  332. package/dist/chunks/chunk-RA6HKFBV.js +0 -4
  333. package/dist/chunks/chunk-REPYBMQS.js +0 -4
  334. package/dist/chunks/chunk-SKHLZ6XY.js +0 -9
  335. package/dist/chunks/chunk-TAWLERZA.js +0 -4
  336. package/dist/chunks/chunk-TWAEABGG.js +0 -52
  337. package/dist/chunks/chunk-TZFLHVOQ.js +0 -7
  338. package/dist/chunks/chunk-UD3NMUHR.js +0 -12
  339. package/dist/chunks/chunk-UNVEZI57.js +0 -4
  340. package/dist/chunks/chunk-VQUPKMDR.js +0 -4
  341. package/dist/chunks/chunk-W25TB3PU.js +0 -4
  342. package/dist/chunks/chunk-W5LGYSPZ.js +0 -4
  343. package/dist/chunks/chunk-WEZWKMYU.js +0 -4
  344. package/dist/chunks/chunk-XAJLZR7C.js +0 -28
  345. package/dist/chunks/chunk-XH6FMP3N.js +0 -71
  346. package/dist/chunks/chunk-XSRZHN63.js +0 -4
  347. package/dist/chunks/chunk-Y3GFB5XM.js +0 -8
  348. package/dist/chunks/chunk-YG7OEPR2.js +0 -6
  349. package/dist/chunks/chunk-YHIWOGVL.js +0 -4
  350. package/dist/chunks/chunk-YKKEI5GI.js +0 -4
  351. package/dist/chunks/chunk-YZSHTWNM.js +0 -92
  352. package/dist/chunks/chunk-Z4H3VDHI.js +0 -4
  353. package/dist/chunks/cli-5DBTRMHU.js +0 -53
  354. package/dist/chunks/client-XOGYH5UR.js +0 -4
  355. package/dist/chunks/cloudflare-workers-ai-system-one-32JCFHI3.js +0 -4
  356. package/dist/chunks/config-DJSQI77S-335IXHSM.js +0 -4
  357. package/dist/chunks/context-VCQH5OB6.js +0 -4
  358. package/dist/chunks/cost-PGGFI7QJ.js +0 -5
  359. package/dist/chunks/dist-PUKMZ7GW.js +0 -4
  360. package/dist/chunks/easter-egg-3d-MO4MOEVF.js +0 -4
  361. package/dist/chunks/es5-VNTQPCKX.js +0 -4
  362. package/dist/chunks/file-7BN7RCAY.js +0 -4
  363. package/dist/chunks/gateway-UCRPMR75.js +0 -36
  364. package/dist/chunks/github-copilot-HAI2DA62.js +0 -4
  365. package/dist/chunks/google-generative-ai-2VXWLHWI.js +0 -4
  366. package/dist/chunks/google-vertex-UA36QP2U.js +0 -4
  367. package/dist/chunks/init-HA7FAQ73.js +0 -4
  368. package/dist/chunks/kimi-coding-HMJRKCPA.js +0 -4
  369. package/dist/chunks/local-client-stop-SQRU7ZZM.js +0 -4
  370. package/dist/chunks/meta-KY3LNFV2.js +0 -4
  371. package/dist/chunks/mistral-conversations-34F66L3O.js +0 -7
  372. package/dist/chunks/model-resolver-N3DTAQ2S.js +0 -4
  373. package/dist/chunks/openai-codex-responses-ZBVHREB3.js +0 -12
  374. package/dist/chunks/openai-completions-VVIB26SH.js +0 -9
  375. package/dist/chunks/openai-responses-735XA2ZX.js +0 -6
  376. package/dist/chunks/openrouter-images-3IKETHAC.js +0 -4
  377. package/dist/chunks/pi-messages-I3E4ZFHA.js +0 -10
  378. package/dist/chunks/radius-HXRZVBDB.js +0 -4
  379. package/dist/chunks/remote-ops-BALZYKH6.js +0 -14
  380. package/dist/chunks/runner-PLVZDGHB.js +0 -4
  381. package/dist/chunks/runtime-6YLTA2ZD.js +0 -4
  382. package/dist/chunks/schedule-cli-OLASBBYJ.js +0 -4
  383. package/dist/chunks/slack-WAGSPZUX.js +0 -4
  384. package/dist/chunks/start-ui-http-QALT7C3P.js +0 -43
  385. package/dist/chunks/subagent-E3UC7ZHC.js +0 -4
  386. package/dist/chunks/tool-shims-Q6P6UXVC.js +0 -4
  387. package/dist/chunks/typesafe-system-one-6ULACYD4.js +0 -4
  388. package/dist/chunks/ui-board-4GYW6KKW.js +0 -5
  389. package/dist/chunks/ui-decision-U2FXSEC2.js +0 -4
  390. package/dist/chunks/ui-view-O7PLANT7.js +0 -4
  391. package/dist/chunks/virtual-modules-IDC5YKZJ.js +0 -4
  392. package/dist/chunks/waitpoint-2FGQBIAC.js +0 -5
  393. package/dist/chunks/workers-XN4PSTH6.js +0 -4
  394. package/vendor/aistatus/gateway-cli.js +0 -21
  395. package/vendor/pi/examples/extensions/sandbox/index.ts +0 -321
  396. package/vendor/pi/examples/extensions/sandbox/package-lock.json +0 -92
  397. package/vendor/pi/examples/extensions/sandbox/package.json +0 -19
  398. package/web/dist/assets/index-BHZpFXhc.js +0 -525
  399. package/web/dist/assets/index-DqWMdMkh.css +0 -1
  400. package/web/dist/assets/pdf-worker-Hp15W1QJ.js +0 -57
  401. package/web/dist/assets/pdf.worker.min-DnhTvCwe.js +0 -55
@@ -0,0 +1,70 @@
1
+ import { createRequire as __cortexCreateRequire } from 'node:module';
2
+ const require = __cortexCreateRequire(import.meta.url);
3
+ const __cortexPackageRoot = new URL("../../", import.meta.url);
4
+ import{a as xl}from"./chunk-23PRJECN.js";import{b as Dl,f as Mi,q as Ml}from"./chunk-7TYSMLUV.js";import{I as Nl,q as Pl,u as kl}from"./chunk-DE5EGVKG.js";import{a as Yt}from"./chunk-USBJFDJ6.js";import{a as Hh,b as wl}from"./chunk-QN44UXQR.js";import{a as Fh}from"./chunk-I6OPDRVF.js";import{a as Rl}from"./chunk-2YTYYG4K.js";import{a as me,c as W,e as Sl}from"./chunk-WHC7AYZD.js";var Ui=W((Bw,Hl)=>{"use strict";var Zn=Object.prototype.hasOwnProperty,Fl=Object.prototype.toString,Ul=Object.defineProperty,Gl=Object.getOwnPropertyDescriptor,bl=function(e){return typeof Array.isArray=="function"?Array.isArray(e):Fl.call(e)==="[object Array]"},Ll=function(e){if(!e||Fl.call(e)!=="[object Object]")return!1;var n=Zn.call(e,"constructor"),o=e.constructor&&e.constructor.prototype&&Zn.call(e.constructor.prototype,"isPrototypeOf");if(e.constructor&&!n&&!o)return!1;var i;for(i in e);return typeof i>"u"||Zn.call(e,i)},ql=function(e,n){Ul&&n.name==="__proto__"?Ul(e,n.name,{enumerable:!0,configurable:!0,value:n.newValue,writable:!0}):e[n.name]=n.newValue},Ol=function(e,n){if(n==="__proto__")if(Zn.call(e,n)){if(Gl)return Gl(e,n).value}else return;return e[n]};Hl.exports=function t(){var e,n,o,i,r,a,u=arguments[0],c=1,d=arguments.length,f=!1;for(typeof u=="boolean"&&(f=u,u=arguments[1]||{},c=2),(u==null||typeof u!="object"&&typeof u!="function")&&(u={});c<d;++c)if(e=arguments[c],e!=null)for(n in e)o=Ol(u,n),i=Ol(e,n),u!==i&&(f&&i&&(Ll(i)||(r=bl(i)))?(r?(r=!1,a=o&&bl(o)?o:[]):a=o&&Ll(o)?o:{},ql(u,{name:n,newValue:t(f,a,i)})):typeof i<"u"&&ql(u,{name:n,newValue:i}));return u}});var Vl=W(($w,Vh)=>{Vh.exports={name:"gaxios",version:"7.3.1",description:"A simple common HTTP client specifically for Google APIs and services.",main:"build/cjs/src/index.js",types:"build/cjs/src/index.d.ts",files:["build/"],exports:{".":{import:{types:"./build/esm/src/index.d.ts",default:"./build/esm/src/index.js"},require:{types:"./build/cjs/src/index.d.ts",default:"./build/cjs/src/index.js"}}},scripts:{lint:"gts check --no-inline-config",test:"c8 mocha build/esm/test","presystem-test":"npm run compile","system-test":"mocha build/esm/system-test --timeout 80000",compile:"tsc -b ./tsconfig.json ./tsconfig.cjs.json && node utils/enable-esm.mjs",fix:"gts fix",prepare:"npm run compile",pretest:"npm run compile",webpack:"webpack","prebrowser-test":"npm run compile","browser-test":"node build/browser-test/browser-test-runner.js",docs:"jsdoc -c .jsdoc.js","samples-test":"cd samples/ && npm link ../ && npm test && cd ../",prelint:"cd samples; npm link ../; npm install",clean:"gts clean"},repository:{type:"git",directory:"core/packages/gaxios",url:"https://github.com/googleapis/google-cloud-node.git"},keywords:["google"],engines:{node:">=18"},author:"Google, LLC",license:"Apache-2.0",devDependencies:{"@babel/plugin-proposal-private-methods":"^7.18.6","@types/cors":"^2.8.6","@types/express":"^5.0.0","@types/extend":"^3.0.1","@types/mocha":"^10.0.10","@types/multiparty":"4.2.1","@types/mv":"^2.1.0","@types/ncp":"^2.0.8","@types/node":"^24.0.0","@types/sinon":"^21.0.0","@types/tmp":"^0.2.6",assert:"^2.0.0",browserify:"^17.0.0",c8:"^10.1.3",cors:"^2.8.5",express:"^5.0.0",gts:"^6.0.2","is-docker":"^3.0.0",jsdoc:"^4.0.4","jsdoc-fresh":"^5.0.0","jsdoc-region-tag":"^4.0.0",karma:"^6.0.0","karma-chrome-launcher":"^3.0.0","karma-coverage":"^2.0.0","karma-firefox-launcher":"^2.0.0","karma-mocha":"^2.0.0","karma-remap-coverage":"^0.1.5","karma-sourcemap-loader":"^0.4.0","karma-webpack":"^5.0.0",mocha:"^11.1.0",multiparty:"^4.2.1",mv:"^2.1.1",ncp:"^2.0.0",nock:"14.0.5","null-loader":"^4.0.1","pack-n-play":"^4.0.0",puppeteer:"^24.0.0",sinon:"21.0.3","stream-browserify":"^3.0.0",tmp:"0.2.7","ts-loader":"^9.5.2",typescript:"5.8.3","undici-types":"^7.24.1",webpack:"^5.97.1","webpack-cli":"^6.0.1"},dependencies:{extend:"^3.0.2","https-proxy-agent":"^7.0.1","node-fetch":"^3.3.2"},homepage:"https://github.com/googleapis/google-cloud-node/tree/main/core/packages/gaxios"}});var $l=W((Xw,Bl)=>{"use strict";var Bh=Vl();Bl.exports={pkg:Bh}});var Li=W(We=>{"use strict";var Jl=We&&We.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(We,"__esModule",{value:!0});We.GaxiosError=We.GAXIOS_ERROR_SYMBOL=void 0;We.defaultErrorRedactor=Kl;var Xl=Jl(Ui()),$h=Jl($l()),Gi=$h.default.pkg;We.GAXIOS_ERROR_SYMBOL=Symbol.for(`${Gi.name}-gaxios-error`);var bi=class t extends Error{config;response;code;status;error;[We.GAXIOS_ERROR_SYMBOL]=Gi.version;static[Symbol.hasInstance](e){return e&&typeof e=="object"&&We.GAXIOS_ERROR_SYMBOL in e&&e[We.GAXIOS_ERROR_SYMBOL]===Gi.version?!0:Function.prototype[Symbol.hasInstance].call(t,e)}constructor(e,n,o,i){if(super(e,{cause:i}),this.config=n,this.response=o,this.error=i instanceof Error?i:void 0,this.config=(0,Xl.default)(!0,{},n),this.response&&(this.response.config=(0,Xl.default)(!0,{},this.response.config)),this.response){try{this.response.data=Xh(this.config.responseType,this.response?.bodyUsed?this.response?.data:void 0)}catch{}this.status=this.response.status}i instanceof DOMException?this.code=i.name:i&&typeof i=="object"&&"code"in i&&(typeof i.code=="string"||typeof i.code=="number")&&(this.code=i.code)}static extractAPIErrorFromResponse(e,n="The request failed"){let o=n;if(typeof e.data=="string"&&(o=e.data),e.data&&typeof e.data=="object"&&"error"in e.data&&e.data.error&&!e.ok){if(typeof e.data.error=="string")return{message:e.data.error,code:e.status,status:e.statusText};if(typeof e.data.error=="object"){o="message"in e.data.error&&typeof e.data.error.message=="string"?e.data.error.message:o;let i="status"in e.data.error&&typeof e.data.error.status=="string"?e.data.error.status:e.statusText,r="code"in e.data.error&&typeof e.data.error.code=="number"?e.data.error.code:e.status;if("errors"in e.data.error&&Array.isArray(e.data.error.errors)){let a=[];for(let u of e.data.error.errors)typeof u=="object"&&"message"in u&&typeof u.message=="string"&&a.push(u.message);return Object.assign({message:a.join(`
5
+ `)||o,code:r,status:i},e.data.error)}return Object.assign({message:o,code:r,status:i},e.data.error)}}return{message:o,code:e.status,status:e.statusText}}};We.GaxiosError=bi;function Xh(t,e){switch(t){case"stream":return e;case"json":return JSON.parse(JSON.stringify(e));case"arraybuffer":return JSON.parse(Buffer.from(e).toString("utf8"));case"blob":return JSON.parse(e.text());default:return e}}function Kl(t){let e="<<REDACTED> - See `errorRedactor` option in `gaxios` for configuration>.";function n(r){r&&r.forEach((a,u)=>{(/^authentication$/i.test(u)||/^authorization$/i.test(u)||/secret/i.test(u))&&r.set(u,e)})}function o(r,a){if(typeof r=="object"&&r!==null&&typeof r[a]=="string"){let u=r[a];(/grant_type=/i.test(u)||/assertion=/i.test(u)||/secret/i.test(u))&&(r[a]=e)}}function i(r){!r||typeof r!="object"||(r instanceof FormData||r instanceof URLSearchParams||"forEach"in r&&"set"in r?r.forEach((a,u)=>{(["grant_type","assertion"].includes(u)||/secret/.test(u))&&r.set(u,e)}):("grant_type"in r&&(r.grant_type=e),"assertion"in r&&(r.assertion=e),"client_secret"in r&&(r.client_secret=e)))}return t.config&&(n(t.config.headers),o(t.config,"data"),i(t.config.data),o(t.config,"body"),i(t.config.body),t.config.url.searchParams.has("token")&&t.config.url.searchParams.set("token",e),t.config.url.searchParams.has("client_secret")&&t.config.url.searchParams.set("client_secret",e)),t.response&&(Kl({config:t.response.config}),n(t.response.headers),t.response.bodyUsed&&(o(t.response,"data"),i(t.response.data))),t}});var Wl=W(qi=>{"use strict";Object.defineProperty(qi,"__esModule",{value:!0});qi.getRetryConfig=Jh;async function Jh(t){let e=Yl(t);if(!t||!t.config||!e&&!t.config.retry)return{shouldRetry:!1};e=e||{},e.currentRetryAttempt=e.currentRetryAttempt||0,e.retry=e.retry===void 0||e.retry===null?3:e.retry,e.httpMethodsToRetry=e.httpMethodsToRetry||["GET","HEAD","PUT","OPTIONS","DELETE"],e.noResponseRetries=e.noResponseRetries===void 0||e.noResponseRetries===null?2:e.noResponseRetries,e.retryDelayMultiplier=e.retryDelayMultiplier?e.retryDelayMultiplier:2,e.timeOfFirstRequest=e.timeOfFirstRequest?e.timeOfFirstRequest:Date.now(),e.totalTimeout=e.totalTimeout?e.totalTimeout:Number.MAX_SAFE_INTEGER,e.maxRetryDelay=e.maxRetryDelay?e.maxRetryDelay:Number.MAX_SAFE_INTEGER;let n=[[100,199],[408,408],[429,429],[500,599]];if(e.statusCodesToRetry=e.statusCodesToRetry||n,t.config.retryConfig=e,!await(e.shouldRetry||Kh)(t))return{shouldRetry:!1,config:t.config};let i=Yh(e);t.config.retryConfig.currentRetryAttempt+=1;let r=e.retryBackoff?e.retryBackoff(t,i):new Promise(a=>{setTimeout(a,i)});return e.onRetryAttempt&&await e.onRetryAttempt(t),await r,{shouldRetry:!0,config:t.config}}function Kh(t){let e=Yl(t);if(t.config.signal?.aborted&&t.code!=="TimeoutError"||t.code==="AbortError"||!e||e.retry===0||!t.response&&(e.currentRetryAttempt||0)>=e.noResponseRetries||!e.httpMethodsToRetry||!e.httpMethodsToRetry.includes(t.config.method?.toUpperCase()||"GET"))return!1;if(t.response&&t.response.status){let n=!1;for(let[o,i]of e.statusCodesToRetry){let r=t.response.status;if(r>=o&&r<=i){n=!0;break}}if(!n)return!1}return e.currentRetryAttempt=e.currentRetryAttempt||0,!(e.currentRetryAttempt>=e.retry)}function Yl(t){if(t&&t.config&&t.config.retryConfig)return t.config.retryConfig}function Yh(t){let n=(t.currentRetryAttempt?0:t.retryDelay??100)+(Math.pow(t.retryDelayMultiplier,t.currentRetryAttempt)-1)/2*1e3,o=t.totalTimeout-(Date.now()-t.timeOfFirstRequest);return Math.min(n,o,t.maxRetryDelay)}});var Fi=W(jn=>{"use strict";Object.defineProperty(jn,"__esModule",{value:!0});jn.GaxiosInterceptorManager=void 0;var Oi=class extends Set{};jn.GaxiosInterceptorManager=Oi});var Zl=W(nn=>{"use strict";var Wh=nn&&nn.__importDefault||function(t){return t&&t.__esModule?t:{default:t}},tn;Object.defineProperty(nn,"__esModule",{value:!0});nn.Gaxios=void 0;var zh=Wh(Ui()),Qh=me("https"),Wt=Li(),Zh=Wl(),zl=me("stream"),Ql=Fi(),jh=async()=>globalThis.crypto?.randomUUID()||(await import("crypto")).randomUUID(),em=204,eo=class{agentCache=new Map;defaults;interceptors;constructor(e){this.defaults=e||{},this.interceptors={request:new Ql.GaxiosInterceptorManager,response:new Ql.GaxiosInterceptorManager}}fetch(...e){let n=e[0],o=e[1],i,r=new Headers;return typeof n=="string"?i=new URL(n):n instanceof URL?i=n:n&&n.url&&(i=new URL(n.url)),n&&typeof n=="object"&&"headers"in n&&tn.mergeHeaders(r,n.headers),o&&tn.mergeHeaders(r,new Headers(o.headers)),typeof n=="object"&&!(n instanceof URL)?this.request({...o,...n,headers:r,url:i}):this.request({...o,headers:r,url:i})}async request(e={}){let n=await this.#o(e);return n=await this.#t(n),this.#n(this._request(n))}async _defaultAdapter(e){let n=e.fetchImplementation||this.defaults.fetchImplementation||await tn.#l(),o={...e};delete o.data;let i=await n(e.url,o),r=await this.getResponseData(e,i);return Object.getOwnPropertyDescriptor(i,"data")?.configurable||Object.defineProperties(i,{data:{configurable:!0,writable:!0,enumerable:!0,value:r}}),Object.assign(i,{config:e,data:r})}async _request(e){try{let n;if(e.adapter?n=await e.adapter(e,this._defaultAdapter.bind(this)):n=await this._defaultAdapter(e),!e.validateStatus(n.status)){if(e.responseType==="stream"){let i=[];for await(let r of n.data)i.push(r);n.data=Buffer.concat(i.map(r=>typeof r=="string"?Buffer.from(r):r)).toString("utf8")}let o=Wt.GaxiosError.extractAPIErrorFromResponse(n,`Request failed with status code ${n.status}`);throw new Wt.GaxiosError(o?.message,e,n,o)}return n}catch(n){let o;n instanceof Wt.GaxiosError?o=n:n instanceof Error?o=new Wt.GaxiosError(n.message,e,void 0,n):o=new Wt.GaxiosError("Unexpected Gaxios Error",e,void 0,n);let{shouldRetry:i,config:r}=await(0,Zh.getRetryConfig)(o);if(i&&r)return o.config.retryConfig.currentRetryAttempt=r.retryConfig.currentRetryAttempt,e.retryConfig=o.config?.retryConfig,this.#i(e),this._request(e);throw e.errorRedactor&&e.errorRedactor(o),o}}async getResponseData(e,n){if(n.status===em)return"";if(e.maxContentLength&&n.headers.has("content-length")&&e.maxContentLength<Number.parseInt(n.headers?.get("content-length")||""))throw new Wt.GaxiosError("Response's `Content-Length` is over the limit.",e,Object.assign(n,{config:e}));switch(e.responseType){case"stream":return n.body;case"json":{let o=await n.text();try{return JSON.parse(o)}catch{return o}}case"arraybuffer":return n.arrayBuffer();case"blob":return n.blob();case"text":return n.text();default:return this.getResponseDataFromContentType(n)}}#e(e,n=[]){let o=new URL(e),i=[...n],r=(process.env.NO_PROXY??process.env.no_proxy)?.split(",")||[];for(let a of r)i.push(a.trim());for(let a of i)if(a instanceof RegExp){if(a.test(o.toString()))return!1}else if(a instanceof URL){if(a.origin===o.origin)return!1}else if(a.startsWith("*.")||a.startsWith(".")){let u=a.replace(/^\*\./,".");if(o.hostname.endsWith(u))return!1}else if(a===o.origin||a===o.hostname||a===o.href)return!1;return!0}async#t(e){let n=Promise.resolve(e);for(let o of this.interceptors.request.values())o&&(n=n.then(o.resolved,o.rejected));return n}async#n(e){let n=Promise.resolve(e);for(let o of this.interceptors.response.values())o&&(n=n.then(o.resolved,o.rejected));return n}async#o(e){let n=new Headers(this.defaults.headers);tn.mergeHeaders(n,e.headers);let o=(0,zh.default)(!0,{},this.defaults,e);if(!o.url)throw new Error("URL is required.");if(o.baseURL&&(o.url=new URL(o.url,o.baseURL)),o.url=new URL(o.url),o.params)if(o.paramsSerializer){let a=o.paramsSerializer(o.params);a.startsWith("?")&&(a=a.slice(1));let u=o.url.toString().includes("?")?"&":"?";o.url=o.url+u+a}else{let a=o.url instanceof URL?o.url:new URL(o.url);for(let[u,c]of new URLSearchParams(o.params))a.searchParams.append(u,c);o.url=a}typeof e.maxContentLength=="number"&&(o.size=e.maxContentLength),typeof e.maxRedirects=="number"&&(o.follow=e.maxRedirects);let i=typeof o.data=="string"||o.data instanceof ArrayBuffer||o.data instanceof Blob||globalThis.File&&o.data instanceof File||o.data instanceof FormData||o.data instanceof zl.Readable||o.data instanceof ReadableStream||o.data instanceof String||o.data instanceof URLSearchParams||ArrayBuffer.isView(o.data)||["Blob","File","FormData"].includes(o.data?.constructor?.name||"");if(o.multipart?.length){let a=await jh();n.set("content-type",`multipart/related; boundary=${a}`),o.body=zl.Readable.from(this.getMultipartRequest(o.multipart,a))}else i?o.body=o.data:typeof o.data=="object"?n.get("Content-Type")==="application/x-www-form-urlencoded"?o.body=o.paramsSerializer?o.paramsSerializer(o.data):new URLSearchParams(o.data):(n.has("content-type")||n.set("content-type","application/json"),o.body=JSON.stringify(o.data)):o.data&&(o.body=o.data);o.validateStatus=o.validateStatus||this.validateStatus,o.responseType=o.responseType||"unknown",!n.has("accept")&&o.responseType==="json"&&n.set("accept","application/json");let r=o.proxy||process?.env?.HTTPS_PROXY||process?.env?.https_proxy||process?.env?.HTTP_PROXY||process?.env?.http_proxy;if(!o.agent)if(r&&this.#e(o.url,o.noProxy)){let a=await tn.#a();this.agentCache.has(r)?o.agent=this.agentCache.get(r):(o.agent=new a(r,{cert:o.cert,key:o.key}),this.agentCache.set(r,o.agent))}else o.cert&&o.key&&(this.agentCache.has(o.key)?o.agent=this.agentCache.get(o.key):(o.agent=new Qh.Agent({cert:o.cert,key:o.key}),this.agentCache.set(o.key,o.agent)));return typeof o.errorRedactor!="function"&&o.errorRedactor!==!1&&(o.errorRedactor=Wt.defaultErrorRedactor),o.body&&!("duplex"in o)&&(o.duplex="half"),this.#i(o),Object.assign(o,{headers:n,url:o.url instanceof URL?o.url:new URL(o.url)})}#i(e){if(e.timeout){let n=AbortSignal.timeout(e.timeout);e.signal&&!e.signal.aborted?e.signal=AbortSignal.any([e.signal,n]):e.signal=n}}validateStatus(e){return e>=200&&e<300}async getResponseDataFromContentType(e){let n=e.headers.get("Content-Type");if(n===null)return e.text();if(n=n.toLowerCase(),n.includes("application/json")){let o=await e.text();try{o=JSON.parse(o)}catch{}return o}else return n.match(/^text\//)?e.text():e.blob()}async*getMultipartRequest(e,n){let o=`--${n}--`;for(let i of e){let r=i.headers.get("Content-Type")||"application/octet-stream";yield`--${n}\r
6
+ Content-Type: ${r}\r
7
+ \r
8
+ `,typeof i.content=="string"?yield i.content:yield*i.content,yield`\r
9
+ `}yield o}static#r;static#s;static async#a(){return this.#r||=(await import("./dist-7RWW7YH4.js")).HttpsProxyAgent,this.#r}static async#l(){let e=typeof window<"u"&&!!window;return this.#s||=e?window.fetch:(await import("./src-CCI7P7AI.js")).default,this.#s}static mergeHeaders(e,...n){e=e instanceof Headers?e:new Headers(e);for(let o of n)(o instanceof Headers?o:new Headers(o)).forEach((r,a)=>{a==="set-cookie"?e.append(a,r):e.set(a,r)});return e}};nn.Gaxios=eo;tn=eo});var xe=W(Le=>{"use strict";var tm=Le&&Le.__createBinding||(Object.create?(function(t,e,n,o){o===void 0&&(o=n);var i=Object.getOwnPropertyDescriptor(e,n);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,o,i)}):(function(t,e,n,o){o===void 0&&(o=n),t[o]=e[n]})),nm=Le&&Le.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&tm(e,t,n)};Object.defineProperty(Le,"__esModule",{value:!0});Le.instance=Le.Gaxios=Le.GaxiosError=void 0;Le.request=im;var jl=Zl();Object.defineProperty(Le,"Gaxios",{enumerable:!0,get:function(){return jl.Gaxios}});var om=Li();Object.defineProperty(Le,"GaxiosError",{enumerable:!0,get:function(){return om.GaxiosError}});nm(Fi(),Le);Le.instance=new jl.Gaxios;async function im(t){return Le.instance.request(t)}});var Hi=W((eu,to)=>{(function(t){"use strict";var e,n=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,o=Math.ceil,i=Math.floor,r="[BigNumber Error] ",a=r+"Number primitive has more than 15 significant digits: ",u=1e14,c=14,d=9007199254740991,f=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],p=1e7,h=1e9;function g(w){var N,q,V,M=B.prototype={constructor:B,toString:null,valueOf:null},O=new B(1),H=20,$=4,j=-7,D=21,Q=-1e7,te=1e7,Ae=!1,ve=1,fe=0,He={prefix:"",groupSize:3,secondaryGroupSize:0,groupSeparator:",",decimalSeparator:".",fractionGroupSize:0,fractionGroupSeparator:"\xA0",suffix:""},Ue="0123456789abcdefghijklmnopqrstuvwxyz",Ge=!0;function B(T,I){var S,G,P,x,L,R,k,b,U=this;if(!(U instanceof B))return new B(T,I);if(I==null){if(T&&T._isBigNumber===!0){U.s=T.s,!T.c||T.e>te?U.c=U.e=null:T.e<Q?U.c=[U.e=0]:(U.e=T.e,U.c=T.c.slice());return}if((R=typeof T=="number")&&T*0==0){if(U.s=1/T<0?(T=-T,-1):1,T===~~T){for(x=0,L=T;L>=10;L/=10,x++);x>te?U.c=U.e=null:(U.e=x,U.c=[T]);return}b=String(T)}else{if(!n.test(b=String(T)))return V(U,b,R);U.s=b.charCodeAt(0)==45?(b=b.slice(1),-1):1}(x=b.indexOf("."))>-1&&(b=b.replace(".","")),(L=b.search(/e/i))>0?(x<0&&(x=L),x+=+b.slice(L+1),b=b.substring(0,L)):x<0&&(x=b.length)}else{if(y(I,2,Ue.length,"Base"),I==10&&Ge)return U=new B(T),Ke(U,H+U.e+1,$);if(b=String(T),R=typeof T=="number"){if(T*0!=0)return V(U,b,R,I);if(U.s=1/T<0?(b=b.slice(1),-1):1,B.DEBUG&&b.replace(/^0\.0*|\./,"").length>15)throw Error(a+T)}else U.s=b.charCodeAt(0)===45?(b=b.slice(1),-1):1;for(S=Ue.slice(0,I),x=L=0,k=b.length;L<k;L++)if(S.indexOf(G=b.charAt(L))<0){if(G=="."){if(L>x){x=k;continue}}else if(!P&&(b==b.toUpperCase()&&(b=b.toLowerCase())||b==b.toLowerCase()&&(b=b.toUpperCase()))){P=!0,L=-1,x=0;continue}return V(U,String(T),R,I)}R=!1,b=q(b,I,10,U.s),(x=b.indexOf("."))>-1?b=b.replace(".",""):x=b.length}for(L=0;b.charCodeAt(L)===48;L++);for(k=b.length;b.charCodeAt(--k)===48;);if(b=b.slice(L,++k)){if(k-=L,R&&B.DEBUG&&k>15&&(T>d||T!==i(T)))throw Error(a+U.s*T);if((x=x-L-1)>te)U.c=U.e=null;else if(x<Q)U.c=[U.e=0];else{if(U.e=x,U.c=[],L=(x+1)%c,x<0&&(L+=c),L<k){for(L&&U.c.push(+b.slice(0,L)),k-=c;L<k;)U.c.push(+b.slice(L,L+=c));L=c-(b=b.slice(L)).length}else L-=k;for(;L--;b+="0");U.c.push(+b)}}else U.c=[U.e=0]}B.clone=g,B.ROUND_UP=0,B.ROUND_DOWN=1,B.ROUND_CEIL=2,B.ROUND_FLOOR=3,B.ROUND_HALF_UP=4,B.ROUND_HALF_DOWN=5,B.ROUND_HALF_EVEN=6,B.ROUND_HALF_CEIL=7,B.ROUND_HALF_FLOOR=8,B.EUCLID=9,B.config=B.set=function(T){var I,S;if(T!=null)if(typeof T=="object"){if(T.hasOwnProperty(I="DECIMAL_PLACES")&&(S=T[I],y(S,0,h,I),H=S),T.hasOwnProperty(I="ROUNDING_MODE")&&(S=T[I],y(S,0,8,I),$=S),T.hasOwnProperty(I="EXPONENTIAL_AT")&&(S=T[I],S&&S.pop?(y(S[0],-h,0,I),y(S[1],0,h,I),j=S[0],D=S[1]):(y(S,-h,h,I),j=-(D=S<0?-S:S))),T.hasOwnProperty(I="RANGE"))if(S=T[I],S&&S.pop)y(S[0],-h,-1,I),y(S[1],1,h,I),Q=S[0],te=S[1];else if(y(S,-h,h,I),S)Q=-(te=S<0?-S:S);else throw Error(r+I+" cannot be zero: "+S);if(T.hasOwnProperty(I="CRYPTO"))if(S=T[I],S===!!S)if(S)if(typeof crypto<"u"&&crypto&&(crypto.getRandomValues||crypto.randomBytes))Ae=S;else throw Ae=!S,Error(r+"crypto unavailable");else Ae=S;else throw Error(r+I+" not true or false: "+S);if(T.hasOwnProperty(I="MODULO_MODE")&&(S=T[I],y(S,0,9,I),ve=S),T.hasOwnProperty(I="POW_PRECISION")&&(S=T[I],y(S,0,h,I),fe=S),T.hasOwnProperty(I="FORMAT"))if(S=T[I],typeof S=="object")He=S;else throw Error(r+I+" not an object: "+S);if(T.hasOwnProperty(I="ALPHABET"))if(S=T[I],typeof S=="string"&&!/^.?$|[+\-.\s]|(.).*\1/.test(S))Ge=S.slice(0,10)=="0123456789",Ue=S;else throw Error(r+I+" invalid: "+S)}else throw Error(r+"Object expected: "+T);return{DECIMAL_PLACES:H,ROUNDING_MODE:$,EXPONENTIAL_AT:[j,D],RANGE:[Q,te],CRYPTO:Ae,MODULO_MODE:ve,POW_PRECISION:fe,FORMAT:He,ALPHABET:Ue}},B.isBigNumber=function(T){if(!T||T._isBigNumber!==!0)return!1;if(!B.DEBUG)return!0;var I,S,G=T.c,P=T.e,x=T.s;e:if({}.toString.call(G)=="[object Array]"){if((x===1||x===-1)&&P>=-h&&P<=h&&P===i(P)){if(G[0]===0){if(P===0&&G.length===1)return!0;break e}if(I=(P+1)%c,I<1&&(I+=c),String(G[0]).length==I){for(I=0;I<G.length;I++)if(S=G[I],S<0||S>=u||S!==i(S))break e;if(S!==0)return!0}}}else if(G===null&&P===null&&(x===null||x===1||x===-1))return!0;throw Error(r+"Invalid BigNumber: "+T)},B.maximum=B.max=function(){return Il(arguments,-1)},B.minimum=B.min=function(){return Il(arguments,1)},B.random=(function(){var T=9007199254740992,I=Math.random()*T&2097151?function(){return i(Math.random()*T)}:function(){return(Math.random()*1073741824|0)*8388608+(Math.random()*8388608|0)};return function(S){var G,P,x,L,R,k=0,b=[],U=new B(O);if(S==null?S=H:y(S,0,h),L=o(S/c),Ae)if(crypto.getRandomValues){for(G=crypto.getRandomValues(new Uint32Array(L*=2));k<L;)R=G[k]*131072+(G[k+1]>>>11),R>=9e15?(P=crypto.getRandomValues(new Uint32Array(2)),G[k]=P[0],G[k+1]=P[1]):(b.push(R%1e14),k+=2);k=L/2}else if(crypto.randomBytes){for(G=crypto.randomBytes(L*=7);k<L;)R=(G[k]&31)*281474976710656+G[k+1]*1099511627776+G[k+2]*4294967296+G[k+3]*16777216+(G[k+4]<<16)+(G[k+5]<<8)+G[k+6],R>=9e15?crypto.randomBytes(7).copy(G,k):(b.push(R%1e14),k+=7);k=L/7}else throw Ae=!1,Error(r+"crypto unavailable");if(!Ae)for(;k<L;)R=I(),R<9e15&&(b[k++]=R%1e14);for(L=b[--k],S%=c,L&&S&&(R=f[c-S],b[k]=i(L/R)*R);b[k]===0;b.pop(),k--);if(k<0)b=[x=0];else{for(x=-1;b[0]===0;b.splice(0,1),x-=c);for(k=1,R=b[0];R>=10;R/=10,k++);k<c&&(x-=c-k)}return U.e=x,U.c=b,U}})(),B.sum=function(){for(var T=1,I=arguments,S=new B(I[0]);T<I.length;)S=S.plus(I[T++]);return S},q=(function(){var T="0123456789";function I(S,G,P,x){for(var L,R=[0],k,b=0,U=S.length;b<U;){for(k=R.length;k--;R[k]*=G);for(R[0]+=x.indexOf(S.charAt(b++)),L=0;L<R.length;L++)R[L]>P-1&&(R[L+1]==null&&(R[L+1]=0),R[L+1]+=R[L]/P|0,R[L]%=P)}return R.reverse()}return function(S,G,P,x,L){var R,k,b,U,F,z,Z,_e,we=S.indexOf("."),Ne=H,ge=$;for(we>=0&&(U=fe,fe=0,S=S.replace(".",""),_e=new B(G),z=_e.pow(S.length-we),fe=U,_e.c=I(C(m(z.c),z.e,"0"),10,P,T),_e.e=_e.c.length),Z=I(S,G,P,L?(R=Ue,T):(R=T,Ue)),b=U=Z.length;Z[--U]==0;Z.pop());if(!Z[0])return R.charAt(0);if(we<0?--b:(z.c=Z,z.e=b,z.s=x,z=N(z,_e,Ne,ge,P),Z=z.c,F=z.r,b=z.e),k=b+Ne+1,we=Z[k],U=P/2,F=F||k<0||Z[k+1]!=null,F=ge<4?(we!=null||F)&&(ge==0||ge==(z.s<0?3:2)):we>U||we==U&&(ge==4||F||ge==6&&Z[k-1]&1||ge==(z.s<0?8:7)),k<1||!Z[0])S=F?C(R.charAt(1),-Ne,R.charAt(0)):R.charAt(0);else{if(Z.length=k,F)for(--P;++Z[--k]>P;)Z[k]=0,k||(++b,Z=[1].concat(Z));for(U=Z.length;!Z[--U];);for(we=0,S="";we<=U;S+=R.charAt(Z[we++]));S=C(S,b,R.charAt(0))}return S}})(),N=(function(){function T(G,P,x){var L,R,k,b,U=0,F=G.length,z=P%p,Z=P/p|0;for(G=G.slice();F--;)k=G[F]%p,b=G[F]/p|0,L=Z*k+b*z,R=z*k+L%p*p+U,U=(R/x|0)+(L/p|0)+Z*b,G[F]=R%x;return U&&(G=[U].concat(G)),G}function I(G,P,x,L){var R,k;if(x!=L)k=x>L?1:-1;else for(R=k=0;R<x;R++)if(G[R]!=P[R]){k=G[R]>P[R]?1:-1;break}return k}function S(G,P,x,L){for(var R=0;x--;)G[x]-=R,R=G[x]<P[x]?1:0,G[x]=R*L+G[x]-P[x];for(;!G[0]&&G.length>1;G.splice(0,1));}return function(G,P,x,L,R){var k,b,U,F,z,Z,_e,we,Ne,ge,Ee,De,Qn,xi,Di,pt,Rn,Ye=G.s==P.s?1:-1,be=G.c,Re=P.c;if(!be||!be[0]||!Re||!Re[0])return new B(!G.s||!P.s||(be?Re&&be[0]==Re[0]:!Re)?NaN:be&&be[0]==0||!Re?Ye*0:Ye/0);for(we=new B(Ye),Ne=we.c=[],b=G.e-P.e,Ye=x+b+1,R||(R=u,b=_(G.e/c)-_(P.e/c),Ye=Ye/c|0),U=0;Re[U]==(be[U]||0);U++);if(Re[U]>(be[U]||0)&&b--,Ye<0)Ne.push(1),F=!0;else{for(xi=be.length,pt=Re.length,U=0,Ye+=2,z=i(R/(Re[0]+1)),z>1&&(Re=T(Re,z,R),be=T(be,z,R),pt=Re.length,xi=be.length),Qn=pt,ge=be.slice(0,pt),Ee=ge.length;Ee<pt;ge[Ee++]=0);Rn=Re.slice(),Rn=[0].concat(Rn),Di=Re[0],Re[1]>=R/2&&Di++;do{if(z=0,k=I(Re,ge,pt,Ee),k<0){if(De=ge[0],pt!=Ee&&(De=De*R+(ge[1]||0)),z=i(De/Di),z>1)for(z>=R&&(z=R-1),Z=T(Re,z,R),_e=Z.length,Ee=ge.length;I(Z,ge,_e,Ee)==1;)z--,S(Z,pt<_e?Rn:Re,_e,R),_e=Z.length,k=1;else z==0&&(k=z=1),Z=Re.slice(),_e=Z.length;if(_e<Ee&&(Z=[0].concat(Z)),S(ge,Z,Ee,R),Ee=ge.length,k==-1)for(;I(Re,ge,pt,Ee)<1;)z++,S(ge,pt<Ee?Rn:Re,Ee,R),Ee=ge.length}else k===0&&(z++,ge=[0]);Ne[U++]=z,ge[0]?ge[Ee++]=be[Qn]||0:(ge=[be[Qn]],Ee=1)}while((Qn++<xi||ge[0]!=null)&&Ye--);F=ge[0]!=null,Ne[0]||Ne.splice(0,1)}if(R==u){for(U=1,Ye=Ne[0];Ye>=10;Ye/=10,U++);Ke(we,x+(we.e=U+b*c-1)+1,L,F)}else we.e=b,we.r=+F;return we}})();function ki(T,I,S,G){var P,x,L,R,k;if(S==null?S=$:y(S,0,8),!T.c)return T.toString();if(P=T.c[0],L=T.e,I==null)k=m(T.c),k=G==1||G==2&&(L<=j||L>=D)?A(k,L):C(k,L,"0");else if(T=Ke(new B(T),I,S),x=T.e,k=m(T.c),R=k.length,G==1||G==2&&(I<=x||x<=j)){for(;R<I;k+="0",R++);k=A(k,x)}else if(I-=L+(G===2&&x>L),k=C(k,x,"0"),x+1>R){if(--I>0)for(k+=".";I--;k+="0");}else if(I+=x-R,I>0)for(x+1==R&&(k+=".");I--;k+="0");return T.s<0&&P?"-"+k:k}function Il(T,I){for(var S,G,P=1,x=new B(T[0]);P<T.length;P++)G=new B(T[P]),(!G.s||(S=v(x,G))===I||S===0&&x.s===I)&&(x=G);return x}function Ni(T,I,S){for(var G=1,P=I.length;!I[--P];I.pop());for(P=I[0];P>=10;P/=10,G++);return(S=G+S*c-1)>te?T.c=T.e=null:S<Q?T.c=[T.e=0]:(T.e=S,T.c=I),T}V=(function(){var T=/^(-?)0([xbo])(?=\w[\w.]*$)/i,I=/^([^.]+)\.$/,S=/^\.([^.]+)$/,G=/^-?(Infinity|NaN)$/,P=/^\s*\+(?=[\w.])|^\s+|\s+$/g;return function(x,L,R,k){var b,U=R?L:L.replace(P,"");if(G.test(U))x.s=isNaN(U)?null:U<0?-1:1;else{if(!R&&(U=U.replace(T,function(F,z,Z){return b=(Z=Z.toLowerCase())=="x"?16:Z=="b"?2:8,!k||k==b?z:F}),k&&(b=k,U=U.replace(I,"$1").replace(S,"0.$1")),L!=U))return new B(U,b);if(B.DEBUG)throw Error(r+"Not a"+(k?" base "+k:"")+" number: "+L);x.s=null}x.c=x.e=null}})();function Ke(T,I,S,G){var P,x,L,R,k,b,U,F=T.c,z=f;if(F){e:{for(P=1,R=F[0];R>=10;R/=10,P++);if(x=I-P,x<0)x+=c,L=I,k=F[b=0],U=i(k/z[P-L-1]%10);else if(b=o((x+1)/c),b>=F.length)if(G){for(;F.length<=b;F.push(0));k=U=0,P=1,x%=c,L=x-c+1}else break e;else{for(k=R=F[b],P=1;R>=10;R/=10,P++);x%=c,L=x-c+P,U=L<0?0:i(k/z[P-L-1]%10)}if(G=G||I<0||F[b+1]!=null||(L<0?k:k%z[P-L-1]),G=S<4?(U||G)&&(S==0||S==(T.s<0?3:2)):U>5||U==5&&(S==4||G||S==6&&(x>0?L>0?k/z[P-L]:0:F[b-1])%10&1||S==(T.s<0?8:7)),I<1||!F[0])return F.length=0,G?(I-=T.e+1,F[0]=z[(c-I%c)%c],T.e=-I||0):F[0]=T.e=0,T;if(x==0?(F.length=b,R=1,b--):(F.length=b+1,R=z[c-x],F[b]=L>0?i(k/z[P-L]%z[L])*R:0),G)for(;;)if(b==0){for(x=1,L=F[0];L>=10;L/=10,x++);for(L=F[0]+=R,R=1;L>=10;L/=10,R++);x!=R&&(T.e++,F[0]==u&&(F[0]=1));break}else{if(F[b]+=R,F[b]!=u)break;F[b--]=0,R=1}for(x=F.length;F[--x]===0;F.pop());}T.e>te?T.c=T.e=null:T.e<Q&&(T.c=[T.e=0])}return T}function Et(T){var I,S=T.e;return S===null?T.toString():(I=m(T.c),I=S<=j||S>=D?A(I,S):C(I,S,"0"),T.s<0?"-"+I:I)}return M.absoluteValue=M.abs=function(){var T=new B(this);return T.s<0&&(T.s=1),T},M.comparedTo=function(T,I){return v(this,new B(T,I))},M.decimalPlaces=M.dp=function(T,I){var S,G,P,x=this;if(T!=null)return y(T,0,h),I==null?I=$:y(I,0,8),Ke(new B(x),T+x.e+1,I);if(!(S=x.c))return null;if(G=((P=S.length-1)-_(this.e/c))*c,P=S[P])for(;P%10==0;P/=10,G--);return G<0&&(G=0),G},M.dividedBy=M.div=function(T,I){return N(this,new B(T,I),H,$)},M.dividedToIntegerBy=M.idiv=function(T,I){return N(this,new B(T,I),0,1)},M.exponentiatedBy=M.pow=function(T,I){var S,G,P,x,L,R,k,b,U,F=this;if(T=new B(T),T.c&&!T.isInteger())throw Error(r+"Exponent not an integer: "+Et(T));if(I!=null&&(I=new B(I)),R=T.e>14,!F.c||!F.c[0]||F.c[0]==1&&!F.e&&F.c.length==1||!T.c||!T.c[0])return U=new B(Math.pow(+Et(F),R?T.s*(2-E(T)):+Et(T))),I?U.mod(I):U;if(k=T.s<0,I){if(I.c?!I.c[0]:!I.s)return new B(NaN);G=!k&&F.isInteger()&&I.isInteger(),G&&(F=F.mod(I))}else{if(T.e>9&&(F.e>0||F.e<-1||(F.e==0?F.c[0]>1||R&&F.c[1]>=24e7:F.c[0]<8e13||R&&F.c[0]<=9999975e7)))return x=F.s<0&&E(T)?-0:0,F.e>-1&&(x=1/x),new B(k?1/x:x);fe&&(x=o(fe/c+2))}for(R?(S=new B(.5),k&&(T.s=1),b=E(T)):(P=Math.abs(+Et(T)),b=P%2),U=new B(O);;){if(b){if(U=U.times(F),!U.c)break;x?U.c.length>x&&(U.c.length=x):G&&(U=U.mod(I))}if(P){if(P=i(P/2),P===0)break;b=P%2}else if(T=T.times(S),Ke(T,T.e+1,1),T.e>14)b=E(T);else{if(P=+Et(T),P===0)break;b=P%2}F=F.times(F),x?F.c&&F.c.length>x&&(F.c.length=x):G&&(F=F.mod(I))}return G?U:(k&&(U=O.div(U)),I?U.mod(I):x?Ke(U,fe,$,L):U)},M.integerValue=function(T){var I=new B(this);return T==null?T=$:y(T,0,8),Ke(I,I.e+1,T)},M.isEqualTo=M.eq=function(T,I){return v(this,new B(T,I))===0},M.isFinite=function(){return!!this.c},M.isGreaterThan=M.gt=function(T,I){return v(this,new B(T,I))>0},M.isGreaterThanOrEqualTo=M.gte=function(T,I){return(I=v(this,new B(T,I)))===1||I===0},M.isInteger=function(){return!!this.c&&_(this.e/c)>this.c.length-2},M.isLessThan=M.lt=function(T,I){return v(this,new B(T,I))<0},M.isLessThanOrEqualTo=M.lte=function(T,I){return(I=v(this,new B(T,I)))===-1||I===0},M.isNaN=function(){return!this.s},M.isNegative=function(){return this.s<0},M.isPositive=function(){return this.s>0},M.isZero=function(){return!!this.c&&this.c[0]==0},M.minus=function(T,I){var S,G,P,x,L=this,R=L.s;if(T=new B(T,I),I=T.s,!R||!I)return new B(NaN);if(R!=I)return T.s=-I,L.plus(T);var k=L.e/c,b=T.e/c,U=L.c,F=T.c;if(!k||!b){if(!U||!F)return U?(T.s=-I,T):new B(F?L:NaN);if(!U[0]||!F[0])return F[0]?(T.s=-I,T):new B(U[0]?L:$==3?-0:0)}if(k=_(k),b=_(b),U=U.slice(),R=k-b){for((x=R<0)?(R=-R,P=U):(b=k,P=F),P.reverse(),I=R;I--;P.push(0));P.reverse()}else for(G=(x=(R=U.length)<(I=F.length))?R:I,R=I=0;I<G;I++)if(U[I]!=F[I]){x=U[I]<F[I];break}if(x&&(P=U,U=F,F=P,T.s=-T.s),I=(G=F.length)-(S=U.length),I>0)for(;I--;U[S++]=0);for(I=u-1;G>R;){if(U[--G]<F[G]){for(S=G;S&&!U[--S];U[S]=I);--U[S],U[G]+=u}U[G]-=F[G]}for(;U[0]==0;U.splice(0,1),--b);return U[0]?Ni(T,U,b):(T.s=$==3?-1:1,T.c=[T.e=0],T)},M.modulo=M.mod=function(T,I){var S,G,P=this;return T=new B(T,I),!P.c||!T.s||T.c&&!T.c[0]?new B(NaN):!T.c||P.c&&!P.c[0]?new B(P):(ve==9?(G=T.s,T.s=1,S=N(P,T,0,3),T.s=G,S.s*=G):S=N(P,T,0,ve),T=P.minus(S.times(T)),!T.c[0]&&ve==1&&(T.s=P.s),T)},M.multipliedBy=M.times=function(T,I){var S,G,P,x,L,R,k,b,U,F,z,Z,_e,we,Ne,ge=this,Ee=ge.c,De=(T=new B(T,I)).c;if(!Ee||!De||!Ee[0]||!De[0])return!ge.s||!T.s||Ee&&!Ee[0]&&!De||De&&!De[0]&&!Ee?T.c=T.e=T.s=null:(T.s*=ge.s,!Ee||!De?T.c=T.e=null:(T.c=[0],T.e=0)),T;for(G=_(ge.e/c)+_(T.e/c),T.s*=ge.s,k=Ee.length,F=De.length,k<F&&(_e=Ee,Ee=De,De=_e,P=k,k=F,F=P),P=k+F,_e=[];P--;_e.push(0));for(we=u,Ne=p,P=F;--P>=0;){for(S=0,z=De[P]%Ne,Z=De[P]/Ne|0,L=k,x=P+L;x>P;)b=Ee[--L]%Ne,U=Ee[L]/Ne|0,R=Z*b+U*z,b=z*b+R%Ne*Ne+_e[x]+S,S=(b/we|0)+(R/Ne|0)+Z*U,_e[x--]=b%we;_e[x]=S}return S?++G:_e.splice(0,1),Ni(T,_e,G)},M.negated=function(){var T=new B(this);return T.s=-T.s||null,T},M.plus=function(T,I){var S,G=this,P=G.s;if(T=new B(T,I),I=T.s,!P||!I)return new B(NaN);if(P!=I)return T.s=-I,G.minus(T);var x=G.e/c,L=T.e/c,R=G.c,k=T.c;if(!x||!L){if(!R||!k)return new B(P/0);if(!R[0]||!k[0])return k[0]?T:new B(R[0]?G:P*0)}if(x=_(x),L=_(L),R=R.slice(),P=x-L){for(P>0?(L=x,S=k):(P=-P,S=R),S.reverse();P--;S.push(0));S.reverse()}for(P=R.length,I=k.length,P-I<0&&(S=k,k=R,R=S,I=P),P=0;I;)P=(R[--I]=R[I]+k[I]+P)/u|0,R[I]=u===R[I]?0:R[I]%u;return P&&(R=[P].concat(R),++L),Ni(T,R,L)},M.precision=M.sd=function(T,I){var S,G,P,x=this;if(T!=null&&T!==!!T)return y(T,1,h),I==null?I=$:y(I,0,8),Ke(new B(x),T,I);if(!(S=x.c))return null;if(P=S.length-1,G=P*c+1,P=S[P]){for(;P%10==0;P/=10,G--);for(P=S[0];P>=10;P/=10,G++);}return T&&x.e+1>G&&(G=x.e+1),G},M.shiftedBy=function(T){return y(T,-d,d),this.times("1e"+T)},M.squareRoot=M.sqrt=function(){var T,I,S,G,P,x=this,L=x.c,R=x.s,k=x.e,b=H+4,U=new B("0.5");if(R!==1||!L||!L[0])return new B(!R||R<0&&(!L||L[0])?NaN:L?x:1/0);if(R=Math.sqrt(+Et(x)),R==0||R==1/0?(I=m(L),(I.length+k)%2==0&&(I+="0"),R=Math.sqrt(+I),k=_((k+1)/2)-(k<0||k%2),R==1/0?I="5e"+k:(I=R.toExponential(),I=I.slice(0,I.indexOf("e")+1)+k),S=new B(I)):S=new B(R+""),S.c[0]){for(k=S.e,R=k+b,R<3&&(R=0);;)if(P=S,S=U.times(P.plus(N(x,P,b,1))),m(P.c).slice(0,R)===(I=m(S.c)).slice(0,R))if(S.e<k&&--R,I=I.slice(R-3,R+1),I=="9999"||!G&&I=="4999"){if(!G&&(Ke(P,P.e+H+2,0),P.times(P).eq(x))){S=P;break}b+=4,R+=4,G=1}else{(!+I||!+I.slice(1)&&I.charAt(0)=="5")&&(Ke(S,S.e+H+2,1),T=!S.times(S).eq(x));break}}return Ke(S,S.e+H+1,$,T)},M.toExponential=function(T,I){return T!=null&&(y(T,0,h),T++),ki(this,T,I,1)},M.toFixed=function(T,I){return T!=null&&(y(T,0,h),T=T+this.e+1),ki(this,T,I)},M.toFormat=function(T,I,S){var G,P=this;if(S==null)T!=null&&I&&typeof I=="object"?(S=I,I=null):T&&typeof T=="object"?(S=T,T=I=null):S=He;else if(typeof S!="object")throw Error(r+"Argument not an object: "+S);if(G=P.toFixed(T,I),P.c){var x,L=G.split("."),R=+S.groupSize,k=+S.secondaryGroupSize,b=S.groupSeparator||"",U=L[0],F=L[1],z=P.s<0,Z=z?U.slice(1):U,_e=Z.length;if(k&&(x=R,R=k,k=x,_e-=x),R>0&&_e>0){for(x=_e%R||R,U=Z.substr(0,x);x<_e;x+=R)U+=b+Z.substr(x,R);k>0&&(U+=b+Z.slice(x)),z&&(U="-"+U)}G=F?U+(S.decimalSeparator||"")+((k=+S.fractionGroupSize)?F.replace(new RegExp("\\d{"+k+"}\\B","g"),"$&"+(S.fractionGroupSeparator||"")):F):U}return(S.prefix||"")+G+(S.suffix||"")},M.toFraction=function(T){var I,S,G,P,x,L,R,k,b,U,F,z,Z=this,_e=Z.c;if(T!=null&&(R=new B(T),!R.isInteger()&&(R.c||R.s!==1)||R.lt(O)))throw Error(r+"Argument "+(R.isInteger()?"out of range: ":"not an integer: ")+Et(R));if(!_e)return new B(Z);for(I=new B(O),b=S=new B(O),G=k=new B(O),z=m(_e),x=I.e=z.length-Z.e-1,I.c[0]=f[(L=x%c)<0?c+L:L],T=!T||R.comparedTo(I)>0?x>0?I:b:R,L=te,te=1/0,R=new B(z),k.c[0]=0;U=N(R,I,0,1),P=S.plus(U.times(G)),P.comparedTo(T)!=1;)S=G,G=P,b=k.plus(U.times(P=b)),k=P,I=R.minus(U.times(P=I)),R=P;return P=N(T.minus(S),G,0,1),k=k.plus(P.times(b)),S=S.plus(P.times(G)),k.s=b.s=Z.s,x=x*2,F=N(b,G,x,$).minus(Z).abs().comparedTo(N(k,S,x,$).minus(Z).abs())<1?[b,G]:[k,S],te=L,F},M.toNumber=function(){return+Et(this)},M.toPrecision=function(T,I){return T!=null&&y(T,1,h),ki(this,T,I,2)},M.toString=function(T){var I,S=this,G=S.s,P=S.e;return P===null?G?(I="Infinity",G<0&&(I="-"+I)):I="NaN":(T==null?I=P<=j||P>=D?A(m(S.c),P):C(m(S.c),P,"0"):T===10&&Ge?(S=Ke(new B(S),H+P+1,$),I=C(m(S.c),S.e,"0")):(y(T,2,Ue.length,"Base"),I=q(C(m(S.c),P,"0"),10,T,G,!0)),G<0&&S.c[0]&&(I="-"+I)),I},M.valueOf=M.toJSON=function(){return Et(this)},M._isBigNumber=!0,w!=null&&B.set(w),B}function _(w){var N=w|0;return w>0||w===N?N:N-1}function m(w){for(var N,q,V=1,M=w.length,O=w[0]+"";V<M;){for(N=w[V++]+"",q=c-N.length;q--;N="0"+N);O+=N}for(M=O.length;O.charCodeAt(--M)===48;);return O.slice(0,M+1||1)}function v(w,N){var q,V,M=w.c,O=N.c,H=w.s,$=N.s,j=w.e,D=N.e;if(!H||!$)return null;if(q=M&&!M[0],V=O&&!O[0],q||V)return q?V?0:-$:H;if(H!=$)return H;if(q=H<0,V=j==D,!M||!O)return V?0:!M^q?1:-1;if(!V)return j>D^q?1:-1;for($=(j=M.length)<(D=O.length)?j:D,H=0;H<$;H++)if(M[H]!=O[H])return M[H]>O[H]^q?1:-1;return j==D?0:j>D^q?1:-1}function y(w,N,q,V){if(w<N||w>q||w!==i(w))throw Error(r+(V||"Argument")+(typeof w=="number"?w<N||w>q?" out of range: ":" not an integer: ":" not a primitive number: ")+String(w))}function E(w){var N=w.c.length-1;return _(w.e/c)==N&&w.c[N]%2!=0}function A(w,N){return(w.length>1?w.charAt(0)+"."+w.slice(1):w)+(N<0?"e":"e+")+N}function C(w,N,q){var V,M;if(N<0){for(M=q+".";++N;M+=q);w=M+w}else if(V=w.length,++N>V){for(M=q,N-=V;--N;M+=q);w+=M}else N<V&&(w=w.slice(0,N)+"."+w.slice(N));return w}e=g(),e.default=e.BigNumber=e,typeof define=="function"&&define.amd?define(function(){return e}):typeof to<"u"&&to.exports?to.exports=e:(t||(t=typeof self<"u"&&self?self:window),t.BigNumber=e)})(eu)});var iu=W((Qw,ou)=>{var tu=Hi(),nu=ou.exports;(function(){"use strict";function t(d){return d<10?"0"+d:d}var e=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,n=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,o,i,r={"\b":"\\b"," ":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"},a;function u(d){return n.lastIndex=0,n.test(d)?'"'+d.replace(n,function(f){var p=r[f];return typeof p=="string"?p:"\\u"+("0000"+f.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+d+'"'}function c(d,f){var p,h,g,_,m=o,v,y=f[d],E=y!=null&&(y instanceof tu||tu.isBigNumber(y));switch(y&&typeof y=="object"&&typeof y.toJSON=="function"&&(y=y.toJSON(d)),typeof a=="function"&&(y=a.call(f,d,y)),typeof y){case"string":return E?y:u(y);case"number":return isFinite(y)?String(y):"null";case"boolean":case"null":case"bigint":return String(y);case"object":if(!y)return"null";if(o+=i,v=[],Object.prototype.toString.apply(y)==="[object Array]"){for(_=y.length,p=0;p<_;p+=1)v[p]=c(p,y)||"null";return g=v.length===0?"[]":o?`[
10
+ `+o+v.join(`,
11
+ `+o)+`
12
+ `+m+"]":"["+v.join(",")+"]",o=m,g}if(a&&typeof a=="object")for(_=a.length,p=0;p<_;p+=1)typeof a[p]=="string"&&(h=a[p],g=c(h,y),g&&v.push(u(h)+(o?": ":":")+g));else Object.keys(y).forEach(function(A){var C=c(A,y);C&&v.push(u(A)+(o?": ":":")+C)});return g=v.length===0?"{}":o?`{
13
+ `+o+v.join(`,
14
+ `+o)+`
15
+ `+m+"}":"{"+v.join(",")+"}",o=m,g}}typeof nu.stringify!="function"&&(nu.stringify=function(d,f,p){var h;if(o="",i="",typeof p=="number")for(h=0;h<p;h+=1)i+=" ";else typeof p=="string"&&(i=p);if(a=f,f&&typeof f!="function"&&(typeof f!="object"||typeof f.length!="number"))throw new Error("JSON.stringify");return c("",{"":d})})})()});var su=W((Zw,ru)=>{var no=null,rm=/(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])/,sm=/(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)/,am=function(t){"use strict";var e={strict:!1,storeAsString:!1,alwaysParseAsBig:!1,useNativeBigInt:!1,protoAction:"error",constructorAction:"error"};if(t!=null){if(t.strict===!0&&(e.strict=!0),t.storeAsString===!0&&(e.storeAsString=!0),e.alwaysParseAsBig=t.alwaysParseAsBig===!0?t.alwaysParseAsBig:!1,e.useNativeBigInt=t.useNativeBigInt===!0?t.useNativeBigInt:!1,typeof t.constructorAction<"u")if(t.constructorAction==="error"||t.constructorAction==="ignore"||t.constructorAction==="preserve")e.constructorAction=t.constructorAction;else throw new Error(`Incorrect value for constructorAction option, must be "error", "ignore" or undefined but passed ${t.constructorAction}`);if(typeof t.protoAction<"u")if(t.protoAction==="error"||t.protoAction==="ignore"||t.protoAction==="preserve")e.protoAction=t.protoAction;else throw new Error(`Incorrect value for protoAction option, must be "error", "ignore" or undefined but passed ${t.protoAction}`)}var n,o,i={'"':'"',"\\":"\\","/":"/",b:"\b",f:"\f",n:`
16
+ `,r:"\r",t:" "},r,a=function(m){throw{name:"SyntaxError",message:m,at:n,text:r}},u=function(m){return m&&m!==o&&a("Expected '"+m+"' instead of '"+o+"'"),o=r.charAt(n),n+=1,o},c=function(){var m,v="";for(o==="-"&&(v="-",u("-"));o>="0"&&o<="9";)v+=o,u();if(o===".")for(v+=".";u()&&o>="0"&&o<="9";)v+=o;if(o==="e"||o==="E")for(v+=o,u(),(o==="-"||o==="+")&&(v+=o,u());o>="0"&&o<="9";)v+=o,u();if(m=+v,!isFinite(m))a("Bad number");else return no==null&&(no=Hi()),v.length>15?e.storeAsString?v:e.useNativeBigInt?BigInt(v):new no(v):e.alwaysParseAsBig?e.useNativeBigInt?BigInt(m):new no(m):m},d=function(){var m,v,y="",E;if(o==='"')for(var A=n;u();){if(o==='"')return n-1>A&&(y+=r.substring(A,n-1)),u(),y;if(o==="\\"){if(n-1>A&&(y+=r.substring(A,n-1)),u(),o==="u"){for(E=0,v=0;v<4&&(m=parseInt(u(),16),!!isFinite(m));v+=1)E=E*16+m;y+=String.fromCharCode(E)}else if(typeof i[o]=="string")y+=i[o];else break;A=n}}a("Bad string")},f=function(){for(;o&&o<=" ";)u()},p=function(){switch(o){case"t":return u("t"),u("r"),u("u"),u("e"),!0;case"f":return u("f"),u("a"),u("l"),u("s"),u("e"),!1;case"n":return u("n"),u("u"),u("l"),u("l"),null}a("Unexpected '"+o+"'")},h,g=function(){var m=[];if(o==="["){if(u("["),f(),o==="]")return u("]"),m;for(;o;){if(m.push(h()),f(),o==="]")return u("]"),m;u(","),f()}}a("Bad array")},_=function(){var m,v=Object.create(null);if(o==="{"){if(u("{"),f(),o==="}")return u("}"),v;for(;o;){if(m=d(),f(),u(":"),e.strict===!0&&Object.hasOwnProperty.call(v,m)&&a('Duplicate key "'+m+'"'),rm.test(m)===!0?e.protoAction==="error"?a("Object contains forbidden prototype property"):e.protoAction==="ignore"?h():v[m]=h():sm.test(m)===!0?e.constructorAction==="error"?a("Object contains forbidden constructor property"):e.constructorAction==="ignore"?h():v[m]=h():v[m]=h(),f(),o==="}")return u("}"),v;u(","),f()}}a("Bad object")};return h=function(){switch(f(),o){case"{":return _();case"[":return g();case'"':return d();case"-":return c();default:return o>="0"&&o<="9"?c():p()}},function(m,v){var y;return r=m+"",n=0,o=" ",y=h(),f(),o&&a("Syntax error"),typeof v=="function"?(function E(A,C){var w,N,q=A[C];return q&&typeof q=="object"&&Object.keys(q).forEach(function(V){N=E(q,V),N!==void 0?q[V]=N:delete q[V]}),v.call(A,C,q)})({"":y},""):y}};ru.exports=am});var uu=W((jw,oo)=>{var au=iu().stringify,lu=su();oo.exports=function(t){return{parse:lu(t),stringify:au}};oo.exports.parse=lu();oo.exports.stringify=au});var Vi=W(rt=>{"use strict";Object.defineProperty(rt,"__esModule",{value:!0});rt.GCE_LINUX_BIOS_PATHS=void 0;rt.isGoogleCloudServerless=fu;rt.isGoogleComputeEngineLinux=pu;rt.isGoogleComputeEngineMACAddress=hu;rt.isGoogleComputeEngine=mu;rt.detectGCPResidency=um;var cu=me("fs"),du=me("os");rt.GCE_LINUX_BIOS_PATHS={BIOS_DATE:"/sys/class/dmi/id/bios_date",BIOS_VENDOR:"/sys/class/dmi/id/bios_vendor"};var lm=/^42:01/;function fu(){return!!(process.env.CLOUD_RUN_JOB||process.env.FUNCTION_NAME||process.env.K_SERVICE)}function pu(){if((0,du.platform)()!=="linux")return!1;try{(0,cu.statSync)(rt.GCE_LINUX_BIOS_PATHS.BIOS_DATE);let t=(0,cu.readFileSync)(rt.GCE_LINUX_BIOS_PATHS.BIOS_VENDOR,"utf8");return/Google/.test(t)}catch{return!1}}function hu(){let t=(0,du.networkInterfaces)();for(let e of Object.values(t))if(e){for(let{mac:n}of e)if(lm.test(n))return!0}return!1}function mu(){return pu()||hu()}function um(){return fu()||mu()}});var gu=W(io=>{"use strict";Object.defineProperty(io,"__esModule",{value:!0});io.Colours=void 0;var Me=class t{static isEnabled(e){return e&&e.isTTY&&(typeof e.getColorDepth=="function"?e.getColorDepth()>2:!0)}static refresh(){t.enabled=t.isEnabled(process==null?void 0:process.stderr),this.enabled?(t.reset="\x1B[0m",t.bright="\x1B[1m",t.dim="\x1B[2m",t.red="\x1B[31m",t.green="\x1B[32m",t.yellow="\x1B[33m",t.blue="\x1B[34m",t.magenta="\x1B[35m",t.cyan="\x1B[36m",t.white="\x1B[37m",t.grey="\x1B[90m"):(t.reset="",t.bright="",t.dim="",t.red="",t.green="",t.yellow="",t.blue="",t.magenta="",t.cyan="",t.white="",t.grey="")}};io.Colours=Me;Me.enabled=!1;Me.reset="";Me.bright="";Me.dim="";Me.red="";Me.green="";Me.yellow="";Me.blue="";Me.magenta="";Me.cyan="";Me.white="";Me.grey="";Me.refresh()});var Eu=W(Te=>{"use strict";var cm=Te&&Te.__createBinding||(Object.create?(function(t,e,n,o){o===void 0&&(o=n);var i=Object.getOwnPropertyDescriptor(e,n);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,o,i)}):(function(t,e,n,o){o===void 0&&(o=n),t[o]=e[n]})),dm=Te&&Te.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),_u=Te&&Te.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var o=[];for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(o[o.length]=i);return o},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var o=t(e),i=0;i<o.length;i++)o[i]!=="default"&&cm(n,e,o[i]);return dm(n,e),n}})();Object.defineProperty(Te,"__esModule",{value:!0});Te.env=Te.DebugLogBackendBase=Te.placeholder=Te.AdhocDebugLogger=Te.LogSeverity=void 0;Te.getNodeBackend=$i;Te.getDebugBackend=pm;Te.getStructuredBackend=hm;Te.setBackend=mm;Te.log=vu;var fm=me("events"),Pn=_u(me("process")),yu=_u(me("util")),Ve=gu(),st;(function(t){t.DEFAULT="DEFAULT",t.DEBUG="DEBUG",t.INFO="INFO",t.WARNING="WARNING",t.ERROR="ERROR"})(st||(Te.LogSeverity=st={}));var kn=class extends fm.EventEmitter{constructor(e,n){super(),this.namespace=e,this.upstream=n,this.func=Object.assign(this.invoke.bind(this),{instance:this,on:(o,i)=>this.on(o,i)}),this.func.debug=(...o)=>this.invokeSeverity(st.DEBUG,...o),this.func.info=(...o)=>this.invokeSeverity(st.INFO,...o),this.func.warn=(...o)=>this.invokeSeverity(st.WARNING,...o),this.func.error=(...o)=>this.invokeSeverity(st.ERROR,...o),this.func.sublog=o=>vu(o,this.func)}invoke(e,...n){if(this.upstream)try{this.upstream(e,...n)}catch{}try{this.emit("log",e,n)}catch{}}invokeSeverity(e,...n){this.invoke({severity:e},...n)}};Te.AdhocDebugLogger=kn;Te.placeholder=new kn("",()=>{}).func;var on=class{constructor(){var e;this.cached=new Map,this.filters=[],this.filtersSet=!1;let n=(e=Pn.env[Te.env.nodeEnables])!==null&&e!==void 0?e:"*";n==="all"&&(n="*"),this.filters=n.split(",")}log(e,n,...o){try{this.filtersSet||(this.setFilters(),this.filtersSet=!0);let i=this.cached.get(e);i||(i=this.makeLogger(e),this.cached.set(e,i)),i(n,...o)}catch(i){console.error(i)}}};Te.DebugLogBackendBase=on;var Bi=class extends on{constructor(){super(...arguments),this.enabledRegexp=/.*/g}isEnabled(e){return this.enabledRegexp.test(e)}makeLogger(e){return this.enabledRegexp.test(e)?(n,...o)=>{var i;let r=`${Ve.Colours.green}${e}${Ve.Colours.reset}`,a=`${Ve.Colours.yellow}${Pn.pid}${Ve.Colours.reset}`,u;switch(n.severity){case st.ERROR:u=`${Ve.Colours.red}${n.severity}${Ve.Colours.reset}`;break;case st.INFO:u=`${Ve.Colours.magenta}${n.severity}${Ve.Colours.reset}`;break;case st.WARNING:u=`${Ve.Colours.yellow}${n.severity}${Ve.Colours.reset}`;break;default:u=(i=n.severity)!==null&&i!==void 0?i:st.DEFAULT;break}let c=yu.formatWithOptions({colors:Ve.Colours.enabled},...o),d=Object.assign({},n);delete d.severity;let f=Object.getOwnPropertyNames(d).length?JSON.stringify(d):"",p=f?`${Ve.Colours.grey}${f}${Ve.Colours.reset}`:"";console.error("%s [%s|%s] %s%s",a,r,u,c,f?` ${p}`:"")}:()=>{}}setFilters(){let n=this.filters.join(",").replace(/[|\\{}()[\]^$+?.]/g,"\\$&").replace(/\*/g,".*").replace(/,/g,"$|^");this.enabledRegexp=new RegExp(`^${n}$`,"i")}};function $i(){return new Bi}var Xi=class extends on{constructor(e){super(),this.debugPkg=e}makeLogger(e){let n=this.debugPkg(e);return(o,...i)=>{n(i[0],...i.slice(1))}}setFilters(){var e;let n=(e=Pn.env.NODE_DEBUG)!==null&&e!==void 0?e:"";Pn.env.NODE_DEBUG=`${n}${n?",":""}${this.filters.join(",")}`}};function pm(t){return new Xi(t)}var Ji=class extends on{constructor(e){var n;super(),this.upstream=(n=e)!==null&&n!==void 0?n:void 0}makeLogger(e){var n;let o=(n=this.upstream)===null||n===void 0?void 0:n.makeLogger(e);return(i,...r)=>{var a;let u=(a=i.severity)!==null&&a!==void 0?a:st.INFO,c=Object.assign({severity:u,message:yu.format(...r)},i),d=JSON.stringify(c);o?o(i,d):console.log("%s",d)}}setFilters(){var e;(e=this.upstream)===null||e===void 0||e.setFilters()}};function hm(t){return new Ji(t)}Te.env={nodeEnables:"GOOGLE_SDK_NODE_LOGGING"};var Ki=new Map,Be;function mm(t){Be=t,Ki.clear()}function vu(t,e){if(!Be&&!Pn.env[Te.env.nodeEnables]||!t)return Te.placeholder;e&&(t=`${e.instance.namespace}:${t}`);let n=Ki.get(t);if(n)return n.func;if(Be===null)return Te.placeholder;Be===void 0&&(Be=$i());let o=(()=>{let i;return new kn(t,(a,...u)=>{if(i!==Be){if(Be===null)return;Be===void 0&&(Be=$i()),i=Be}Be?.log(t,a,...u)})})();return Ki.set(t,o),o.func}});var Yi=W(zt=>{"use strict";var gm=zt&&zt.__createBinding||(Object.create?(function(t,e,n,o){o===void 0&&(o=n);var i=Object.getOwnPropertyDescriptor(e,n);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,o,i)}):(function(t,e,n,o){o===void 0&&(o=n),t[o]=e[n]})),_m=zt&&zt.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&gm(e,t,n)};Object.defineProperty(zt,"__esModule",{value:!0});_m(Eu(),zt)});var xn=W(ee=>{"use strict";var Au=ee&&ee.__createBinding||(Object.create?(function(t,e,n,o){o===void 0&&(o=n);var i=Object.getOwnPropertyDescriptor(e,n);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,o,i)}):(function(t,e,n,o){o===void 0&&(o=n),t[o]=e[n]})),ym=ee&&ee.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),vm=ee&&ee.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var o=[];for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(o[o.length]=i);return o},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var o=t(e),i=0;i<o.length;i++)o[i]!=="default"&&Au(n,e,o[i]);return ym(n,e),n}})(),Em=ee&&ee.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&Au(e,t,n)};Object.defineProperty(ee,"__esModule",{value:!0});ee.gcpResidencyCache=ee.METADATA_SERVER_DETECTION=ee.HEADERS=ee.HEADER_VALUE=ee.HEADER_NAME=ee.SECONDARY_HOST_ADDRESS=ee.HOST_ADDRESS=ee.BASE_PATH=void 0;ee.instance=wm;ee.project=Rm;ee.universe=Pm;ee.bulk=km;ee.isAvailable=xm;ee.resetIsAvailableCache=Dm;ee.getGCPResidency=Qi;ee.setGCPResidency=Cu;ee.requestTimeout=Iu;var Wi=xe(),Tm=uu(),Am=Vi(),Cm=vm(Yi());ee.BASE_PATH="/computeMetadata/v1";ee.HOST_ADDRESS="http://169.254.169.254";ee.SECONDARY_HOST_ADDRESS="http://metadata.google.internal.";ee.HEADER_NAME="Metadata-Flavor";ee.HEADER_VALUE="Google";ee.HEADERS=Object.freeze({[ee.HEADER_NAME]:ee.HEADER_VALUE});var Tu=Cm.log("gcp-metadata");ee.METADATA_SERVER_DETECTION=Object.freeze({"assume-present":"don't try to ping the metadata server, but assume it's present",none:"don't try to ping the metadata server, but don't try to use it either","bios-only":"treat the result of a BIOS probe as canonical (don't fall back to pinging)","ping-only":"skip the BIOS probe, and go straight to pinging"});function zi(t){return t||(t=process.env.GCE_METADATA_IP||process.env.GCE_METADATA_HOST||ee.HOST_ADDRESS),/^https?:\/\//.test(t)||(t=`http://${t}`),new URL(ee.BASE_PATH,t).href}function Im(t){Object.keys(t).forEach(e=>{switch(e){case"params":case"property":case"headers":break;case"qs":throw new Error("'qs' is not a valid configuration option. Please use 'params' instead.");default:throw new Error(`'${e}' is not a valid configuration option.`)}})}async function Nn(t,e={},n=3,o=!1){let i=new Headers(ee.HEADERS),r="",a={};if(typeof t=="object"){let p=t;new Headers(p.headers).forEach((h,g)=>i.set(g,h)),r=p.metadataKey,a=p.params||a,n=p.noResponseRetries||n,o=p.fastFail||o}else r=t;typeof e=="string"?r+=`/${e}`:(Im(e),e.property&&(r+=`/${e.property}`),new Headers(e.headers).forEach((p,h)=>i.set(h,p)),a=e.params||a);let u=o?Sm:Wi.request,c={url:`${zi()}/${r}`,headers:i,retryConfig:{noResponseRetries:n},params:a,responseType:"text",timeout:Iu()};Tu.info("instance request %j",c);let d=await u(c);Tu.info("instance metadata is %s",d.data);let f=d.headers.get(ee.HEADER_NAME);if(f!==ee.HEADER_VALUE)throw new RangeError(`Invalid response from metadata service: incorrect ${ee.HEADER_NAME} header. Expected '${ee.HEADER_VALUE}', got ${f?`'${f}'`:"no header"}`);if(typeof d.data=="string")try{return Tm.parse(d.data)}catch{}return d.data}async function Sm(t){let e={...t,url:t.url?.toString().replace(zi(),zi(ee.SECONDARY_HOST_ADDRESS))},n=(0,Wi.request)(t),o=(0,Wi.request)(e);return Promise.any([n,o])}function wm(t){return Nn("instance",t)}function Rm(t){return Nn("project",t)}function Pm(t){return Nn("universe",t)}async function km(t){let e={};return await Promise.all(t.map(n=>(async()=>{let o=await Nn(n),i=n.metadataKey;e[i]=o})())),e}function Nm(){return process.env.DETECT_GCP_RETRIES?Number(process.env.DETECT_GCP_RETRIES):0}var ro;async function xm(){if(process.env.METADATA_SERVER_DETECTION){let t=process.env.METADATA_SERVER_DETECTION.trim().toLocaleLowerCase();if(!(t in ee.METADATA_SERVER_DETECTION))throw new RangeError(`Unknown \`METADATA_SERVER_DETECTION\` env variable. Got \`${t}\`, but it should be \`${Object.keys(ee.METADATA_SERVER_DETECTION).join("`, `")}\`, or unset`);switch(t){case"assume-present":return!0;case"none":return!1;case"bios-only":return Qi();case"ping-only":}}try{return ro===void 0&&(ro=Nn("instance",void 0,Nm(),!(process.env.GCE_METADATA_IP||process.env.GCE_METADATA_HOST))),await ro,!0}catch(t){let e=t;if(process.env.DEBUG_AUTH&&console.info(e),e.type==="request-timeout"||e.response&&e.response.status===404)return!1;if(!(e.response&&e.response.status===404)&&(!e.code||!["EHOSTDOWN","EHOSTUNREACH","ENETUNREACH","ENOENT","ENOTFOUND","ECONNREFUSED"].includes(e.code.toString()))){let n="UNKNOWN";e.code&&(n=e.code.toString()),process.emitWarning(`received unexpected error = ${e.message} code = ${n}`,"MetadataLookupWarning")}return!1}}function Dm(){ro=void 0}ee.gcpResidencyCache=null;function Qi(){return ee.gcpResidencyCache===null&&Cu(),ee.gcpResidencyCache}function Cu(t=null){ee.gcpResidencyCache=t!==null?t:(0,Am.detectGCPResidency)()}function Iu(){return Qi()?0:3e3}Em(Vi(),ee)});var Ru=W(so=>{"use strict";so.byteLength=Um;so.toByteArray=bm;so.fromByteArray=Om;var ht=[],ze=[],Mm=typeof Uint8Array<"u"?Uint8Array:Array,Zi="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(Qt=0,Su=Zi.length;Qt<Su;++Qt)ht[Qt]=Zi[Qt],ze[Zi.charCodeAt(Qt)]=Qt;var Qt,Su;ze[45]=62;ze[95]=63;function wu(t){var e=t.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var n=t.indexOf("=");n===-1&&(n=e);var o=n===e?0:4-n%4;return[n,o]}function Um(t){var e=wu(t),n=e[0],o=e[1];return(n+o)*3/4-o}function Gm(t,e,n){return(e+n)*3/4-n}function bm(t){var e,n=wu(t),o=n[0],i=n[1],r=new Mm(Gm(t,o,i)),a=0,u=i>0?o-4:o,c;for(c=0;c<u;c+=4)e=ze[t.charCodeAt(c)]<<18|ze[t.charCodeAt(c+1)]<<12|ze[t.charCodeAt(c+2)]<<6|ze[t.charCodeAt(c+3)],r[a++]=e>>16&255,r[a++]=e>>8&255,r[a++]=e&255;return i===2&&(e=ze[t.charCodeAt(c)]<<2|ze[t.charCodeAt(c+1)]>>4,r[a++]=e&255),i===1&&(e=ze[t.charCodeAt(c)]<<10|ze[t.charCodeAt(c+1)]<<4|ze[t.charCodeAt(c+2)]>>2,r[a++]=e>>8&255,r[a++]=e&255),r}function Lm(t){return ht[t>>18&63]+ht[t>>12&63]+ht[t>>6&63]+ht[t&63]}function qm(t,e,n){for(var o,i=[],r=e;r<n;r+=3)o=(t[r]<<16&16711680)+(t[r+1]<<8&65280)+(t[r+2]&255),i.push(Lm(o));return i.join("")}function Om(t){for(var e,n=t.length,o=n%3,i=[],r=16383,a=0,u=n-o;a<u;a+=r)i.push(qm(t,a,a+r>u?u:a+r));return o===1?(e=t[n-1],i.push(ht[e>>2]+ht[e<<4&63]+"==")):o===2&&(e=(t[n-2]<<8)+t[n-1],i.push(ht[e>>10]+ht[e>>4&63]+ht[e<<2&63]+"=")),i.join("")}});var er=W(ji=>{"use strict";Object.defineProperty(ji,"__esModule",{value:!0});ji.fromArrayBufferToHex=Fm;function Fm(t){return Array.from(new Uint8Array(t)).map(n=>n.toString(16).padStart(2,"0")).join("")}});var Pu=W(ao=>{"use strict";Object.defineProperty(ao,"__esModule",{value:!0});ao.BrowserCrypto=void 0;var rn=Ru(),Hm=er(),tr=class t{constructor(){if(typeof window>"u"||window.crypto===void 0||window.crypto.subtle===void 0)throw new Error("SubtleCrypto not found. Make sure it's an https:// website.")}async sha256DigestBase64(e){let n=new TextEncoder().encode(e),o=await window.crypto.subtle.digest("SHA-256",n);return rn.fromByteArray(new Uint8Array(o))}randomBytesBase64(e){let n=new Uint8Array(e);return window.crypto.getRandomValues(n),rn.fromByteArray(n)}static padBase64(e){for(;e.length%4!==0;)e+="=";return e}async verify(e,n,o){let i={name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},r=new TextEncoder().encode(n),a=rn.toByteArray(t.padBase64(o)),u=await window.crypto.subtle.importKey("jwk",e,i,!0,["verify"]);return await window.crypto.subtle.verify(i,u,Buffer.from(a),r)}async sign(e,n){let o={name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},i=new TextEncoder().encode(n),r=await window.crypto.subtle.importKey("jwk",e,o,!0,["sign"]),a=await window.crypto.subtle.sign(o,r,i);return rn.fromByteArray(new Uint8Array(a))}decodeBase64StringUtf8(e){let n=rn.toByteArray(t.padBase64(e));return new TextDecoder().decode(n)}encodeBase64StringUtf8(e){let n=new TextEncoder().encode(e);return rn.fromByteArray(n)}async sha256DigestHex(e){let n=new TextEncoder().encode(e),o=await window.crypto.subtle.digest("SHA-256",n);return(0,Hm.fromArrayBufferToHex)(o)}async signWithHmacSha256(e,n){let o=typeof e=="string"?e:String.fromCharCode(...new Uint16Array(e)),i=new TextEncoder,r=await window.crypto.subtle.importKey("raw",i.encode(o),{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return window.crypto.subtle.sign("HMAC",r,i.encode(n))}};ao.BrowserCrypto=tr});var ku=W(lo=>{"use strict";Object.defineProperty(lo,"__esModule",{value:!0});lo.NodeCrypto=void 0;var sn=me("crypto"),nr=class{async sha256DigestBase64(e){return sn.createHash("sha256").update(e).digest("base64")}randomBytesBase64(e){return sn.randomBytes(e).toString("base64")}async verify(e,n,o){let i=sn.createVerify("RSA-SHA256");return i.update(n),i.end(),i.verify(e,o,"base64")}async sign(e,n){let o=sn.createSign("RSA-SHA256");return o.update(n),o.end(),o.sign(e,"base64")}decodeBase64StringUtf8(e){return Buffer.from(e,"base64").toString("utf-8")}encodeBase64StringUtf8(e){return Buffer.from(e,"utf-8").toString("base64")}async sha256DigestHex(e){return sn.createHash("sha256").update(e).digest("hex")}async signWithHmacSha256(e,n){let o=typeof e=="string"?e:Bm(e);return Vm(sn.createHmac("sha256",o).update(n).digest())}};lo.NodeCrypto=nr;function Vm(t){let e=new ArrayBuffer(t.length),n=new Uint8Array(e);for(let o=0;o<t.length;++o)n[o]=t[o];return e}function Bm(t){return Buffer.from(t)}});var Dn=W(Tt=>{"use strict";var $m=Tt&&Tt.__createBinding||(Object.create?(function(t,e,n,o){o===void 0&&(o=n);var i=Object.getOwnPropertyDescriptor(e,n);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,o,i)}):(function(t,e,n,o){o===void 0&&(o=n),t[o]=e[n]})),Xm=Tt&&Tt.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&$m(e,t,n)};Object.defineProperty(Tt,"__esModule",{value:!0});Tt.createCrypto=Ym;Tt.hasBrowserCrypto=Nu;var Jm=Pu(),Km=ku();Xm(er(),Tt);function Ym(){return Nu()?new Jm.BrowserCrypto:new Km.NodeCrypto}function Nu(){return typeof window<"u"&&typeof window.crypto<"u"&&typeof window.crypto.subtle<"u"}});var at=W(At=>{"use strict";Object.defineProperty(At,"__esModule",{value:!0});At.LRUCache=void 0;At.snakeToCamel=Du;At.originalOrCamelOptions=Zm;At.removeUndefinedValuesInObject=jm;At.isValidFile=eg;At.getWellKnownCertificateConfigFileLocation=tg;var Wm=me("fs"),zm=me("os"),or=me("path"),Qm="certificate_config.json",xu="gcloud";function Du(t){return t.replace(/([_][^_])/g,e=>e.slice(1).toUpperCase())}function Zm(t){function e(n){let o=t||{};return o[n]??o[Du(n)]}return{get:e}}var ir=class{capacity;#e=new Map;maxAge;constructor(e){this.capacity=e.capacity,this.maxAge=e.maxAge}#t(e,n){this.#e.delete(e),this.#e.set(e,{value:n,lastAccessed:Date.now()})}set(e,n){this.#t(e,n),this.#n()}get(e){let n=this.#e.get(e);if(n)return this.#t(e,n.value),this.#n(),n.value}#n(){let e=this.maxAge?Date.now()-this.maxAge:0,n=this.#e.entries().next();for(;!n.done&&(this.#e.size>this.capacity||n.value[1].lastAccessed<e);)this.#e.delete(n.value[0]),n=this.#e.entries().next()}};At.LRUCache=ir;function jm(t){return Object.entries(t).forEach(([e,n])=>{(n===void 0||n==="undefined")&&delete t[e]}),t}async function eg(t){try{return(await Wm.promises.lstat(t)).isFile()}catch{return!1}}function tg(){let t=process.env.CLOUDSDK_CONFIG||(ng()?or.join(process.env.APPDATA||"",xu):or.join(process.env.HOME||"",".config",xu));return or.join(t,Qm)}function ng(){return zm.platform().startsWith("win")}});var Mu=W((dR,og)=>{og.exports={name:"google-auth-library",version:"10.9.1",author:"Google Inc.",description:"Google APIs Authentication Client Library for Node.js",engines:{node:">=18"},main:"./build/src/index.js",types:"./build/src/index.d.ts",repository:{type:"git",directory:"core/packages/google-auth-library-nodejs",url:"https://github.com/googleapis/google-cloud-node.git"},keywords:["google","api","google apis","client","client library"],dependencies:{"base64-js":"^1.3.0","ecdsa-sig-formatter":"^1.0.11",gaxios:"^7.1.4","gcp-metadata":"8.1.2","google-logging-utils":"1.1.3",jws:"^4.0.0"},devDependencies:{"@types/base64-js":"^1.2.5","@types/jws":"^3.1.0","@types/mocha":"^10.0.10","@types/mv":"^2.1.0","@types/ncp":"^2.0.8","@types/node":"^24.0.0","@types/sinon":"^21.0.0","assert-rejects":"^1.0.0",c8:"^10.1.3",codecov:"^3.8.3",gts:"^6.0.2","is-docker":"^3.0.0",jsdoc:"^4.0.4","jsdoc-fresh":"^5.0.0","jsdoc-region-tag":"^4.0.0",karma:"^6.0.0","karma-chrome-launcher":"^3.0.0","karma-coverage":"^2.0.0","karma-firefox-launcher":"^2.0.0","karma-mocha":"^2.0.0","karma-sourcemap-loader":"^0.4.0","karma-webpack":"^5.0.1",keypair:"^1.0.4",mocha:"^11.1.0",mv:"^2.1.1",ncp:"^2.0.0",nock:"^14.0.5","null-loader":"^4.0.1",puppeteer:"^24.0.0",sinon:"21.0.3","ts-loader":"^9.5.2",typescript:"5.8.3",webpack:"^5.97.1","webpack-cli":"^6.0.1"},files:["build/src","!build/src/**/*.map"],scripts:{test:"c8 mocha build/test",clean:"gts clean",prepare:"npm run compile",lint:"gts check --no-inline-config",compile:"tsc -p .",fix:"gts fix",pretest:"npm run compile -- --sourceMap",docs:"jsdoc -c .jsdoc.js","samples-setup":"cd samples/ && npm link ../ && npm run setup && cd ../","samples-test":"cd samples/ && npm link ../ && npm test && cd ../","system-test":"mocha build/system-test --timeout 60000","presystem-test":"npm run compile -- --sourceMap",webpack:"webpack","browser-test":"karma start",prelint:"cd samples; npm link ../; npm install"},license:"Apache-2.0",homepage:"https://github.com/googleapis/google-cloud-node/tree/main/core/packages/google-auth-library-nodejs"}});var rr=W(Nt=>{"use strict";Object.defineProperty(Nt,"__esModule",{value:!0});Nt.USER_AGENT=Nt.PRODUCT_NAME=Nt.pkg=void 0;var Uu=Mu();Nt.pkg=Uu;var Gu="google-api-nodejs-client";Nt.PRODUCT_NAME=Gu;var ig=`${Gu}/${Uu.version}`;Nt.USER_AGENT=ig});var $e=W(lt=>{"use strict";Object.defineProperty(lt,"__esModule",{value:!0});lt.AuthClient=lt.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS=lt.DEFAULT_UNIVERSE=void 0;var rg=me("events"),sr=xe(),sg=at(),ag=Yi(),ar=rr();lt.DEFAULT_UNIVERSE="googleapis.com";lt.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS=300*1e3;var lr=class t extends rg.EventEmitter{apiKey;projectId;quotaProjectId;transporter;credentials={};eagerRefreshThresholdMillis=lt.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS;forceRefreshOnFailure=!1;universeDomain=lt.DEFAULT_UNIVERSE;static RequestMethodNameSymbol=Symbol("request method name");static RequestLogIdSymbol=Symbol("request log id");constructor(e={}){super();let n=(0,sg.originalOrCamelOptions)(e);this.apiKey=e.apiKey,this.projectId=n.get("project_id")??null,this.quotaProjectId=n.get("quota_project_id"),this.credentials=n.get("credentials")??{},this.universeDomain=n.get("universe_domain")??lt.DEFAULT_UNIVERSE,this.transporter=e.transporter??new sr.Gaxios(e.transporterOptions),n.get("useAuthRequestParameters")!==!1&&(this.transporter.interceptors.request.add(t.DEFAULT_REQUEST_INTERCEPTOR),this.transporter.interceptors.response.add(t.DEFAULT_RESPONSE_INTERCEPTOR)),e.eagerRefreshThresholdMillis&&(this.eagerRefreshThresholdMillis=e.eagerRefreshThresholdMillis),this.forceRefreshOnFailure=e.forceRefreshOnFailure??!1}fetch(...e){let n=e[0],o=e[1],i,r=new Headers;return typeof n=="string"?i=new URL(n):n instanceof URL?i=n:n&&n.url&&(i=new URL(n.url)),n&&typeof n=="object"&&"headers"in n&&sr.Gaxios.mergeHeaders(r,n.headers),o&&sr.Gaxios.mergeHeaders(r,new Headers(o.headers)),typeof n=="object"&&!(n instanceof URL)?this.request({...o,...n,headers:r,url:i}):this.request({...o,headers:r,url:i})}setCredentials(e){this.credentials=e}addSharedMetadataHeaders(e){return!e.has("x-goog-user-project")&&this.quotaProjectId&&e.set("x-goog-user-project",this.quotaProjectId),e}addUserProjectAndAuthHeaders(e,n){let o=n.get("x-goog-user-project"),i=n.get("authorization");return o&&e.set("x-goog-user-project",o),i&&e.set("authorization",i),e}static log=(0,ag.log)("auth");static DEFAULT_REQUEST_INTERCEPTOR={resolved:async e=>{if(!e.headers.has("x-goog-api-client")){let o=process.version.replace(/^v/,"");e.headers.set("x-goog-api-client",`gl-node/${o}`)}let n=e.headers.get("User-Agent");n?n.includes(`${ar.PRODUCT_NAME}/`)||e.headers.set("User-Agent",`${n} ${ar.USER_AGENT}`):e.headers.set("User-Agent",ar.USER_AGENT);try{let o=e,i=o[t.RequestMethodNameSymbol],r=`${Math.floor(Math.random()*1e3)}`;o[t.RequestLogIdSymbol]=r;let a={url:e.url,headers:e.headers};i?t.log.info("%s [%s] request %j",i,r,a):t.log.info("[%s] request %j",r,a)}catch{}return e}};static DEFAULT_RESPONSE_INTERCEPTOR={resolved:async e=>{try{let n=e.config,o=n[t.RequestMethodNameSymbol],i=n[t.RequestLogIdSymbol];o?t.log.info("%s [%s] response %j",o,i,e.data):t.log.info("[%s] response %j",i,e.data)}catch{}return e},rejected:async e=>{try{let n=e.config,o=n[t.RequestMethodNameSymbol],i=n[t.RequestLogIdSymbol];o?t.log.info("%s [%s] error %j",o,i,e.response?.data):t.log.error("[%s] error %j",i,e.response?.data)}catch{}throw e}};static setMethodName(e,n){try{let o=e;o[t.RequestMethodNameSymbol]=n}catch{}}static get RETRY_CONFIG(){return{retry:!0,retryConfig:{httpMethodsToRetry:["GET","PUT","POST","HEAD","OPTIONS","DELETE"]}}}};lt.AuthClient=lr});var cr=W(uo=>{"use strict";Object.defineProperty(uo,"__esModule",{value:!0});uo.LoginTicket=void 0;var ur=class{envelope;payload;constructor(e,n){this.envelope=e,this.payload=n}getEnvelope(){return this.envelope}getPayload(){return this.payload}getUserId(){let e=this.getPayload();return e&&e.sub?e.sub:null}getAttributes(){return{envelope:this.getEnvelope(),payload:this.getPayload()}}};uo.LoginTicket=ur});var xt=W(mt=>{"use strict";Object.defineProperty(mt,"__esModule",{value:!0});mt.OAuth2Client=mt.ClientAuthentication=mt.CertificateFormat=mt.CodeChallengeMethod=void 0;var bu=xe(),lg=me("querystring"),ug=me("stream"),cg=Hh(),Lu=at(),dr=Dn(),an=$e(),dg=cr(),qu;(function(t){t.Plain="plain",t.S256="S256"})(qu||(mt.CodeChallengeMethod=qu={}));var Ct;(function(t){t.PEM="PEM",t.JWK="JWK"})(Ct||(mt.CertificateFormat=Ct={}));var Mn;(function(t){t.ClientSecretPost="ClientSecretPost",t.ClientSecretBasic="ClientSecretBasic",t.None="None"})(Mn||(mt.ClientAuthentication=Mn={}));var fr=class t extends an.AuthClient{redirectUri;certificateCache={};certificateExpiry=null;certificateCacheFormat=Ct.PEM;refreshTokenPromises=new Map;endpoints;issuers;clientAuthentication;_clientId;_clientSecret;refreshHandler;constructor(e={},n,o){super(typeof e=="object"?e:{}),typeof e!="object"&&(e={clientId:e,clientSecret:n,redirectUri:o}),this._clientId=e.clientId||e.client_id,this._clientSecret=e.clientSecret||e.client_secret,this.redirectUri=e.redirectUri||e.redirect_uris?.[0],this.endpoints={tokenInfoUrl:"https://oauth2.googleapis.com/tokeninfo",oauth2AuthBaseUrl:"https://accounts.google.com/o/oauth2/v2/auth",oauth2TokenUrl:"https://oauth2.googleapis.com/token",oauth2RevokeUrl:"https://oauth2.googleapis.com/revoke",oauth2FederatedSignonPemCertsUrl:"https://www.googleapis.com/oauth2/v1/certs",oauth2FederatedSignonJwkCertsUrl:"https://www.googleapis.com/oauth2/v3/certs",oauth2IapPublicKeyUrl:"https://www.gstatic.com/iap/verify/public_key",...e.endpoints},this.clientAuthentication=e.clientAuthentication||Mn.ClientSecretPost,this.issuers=e.issuers||["accounts.google.com","https://accounts.google.com",this.universeDomain]}static GOOGLE_TOKEN_INFO_URL="https://oauth2.googleapis.com/tokeninfo";static CLOCK_SKEW_SECS_=300;static DEFAULT_MAX_TOKEN_LIFETIME_SECS_=86400;generateAuthUrl(e={}){if(e.code_challenge_method&&!e.code_challenge)throw new Error("If a code_challenge_method is provided, code_challenge must be included.");return e.response_type=e.response_type||"code",e.client_id=e.client_id||this._clientId,e.redirect_uri=e.redirect_uri||this.redirectUri,Array.isArray(e.scope)&&(e.scope=e.scope.join(" ")),this.endpoints.oauth2AuthBaseUrl.toString()+"?"+lg.stringify(e)}generateCodeVerifier(){throw new Error("generateCodeVerifier is removed, please use generateCodeVerifierAsync instead.")}async generateCodeVerifierAsync(){let e=(0,dr.createCrypto)(),o=e.randomBytesBase64(96).replace(/\+/g,"~").replace(/=/g,"_").replace(/\//g,"-"),r=(await e.sha256DigestBase64(o)).split("=")[0].replace(/\+/g,"-").replace(/\//g,"_");return{codeVerifier:o,codeChallenge:r}}getToken(e,n){let o=typeof e=="string"?{code:e}:e;if(n)this.getTokenAsync(o).then(i=>n(null,i.tokens,i.res),i=>n(i,null,i.response));else return this.getTokenAsync(o)}async getTokenAsync(e){let n=this.endpoints.oauth2TokenUrl.toString(),o=new Headers,i={client_id:e.client_id||this._clientId,code_verifier:e.codeVerifier,code:e.code,grant_type:"authorization_code",redirect_uri:e.redirect_uri||this.redirectUri};if(this.clientAuthentication===Mn.ClientSecretBasic){let c=Buffer.from(`${this._clientId}:${this._clientSecret}`);o.set("authorization",`Basic ${c.toString("base64")}`)}this.clientAuthentication===Mn.ClientSecretPost&&(i.client_secret=this._clientSecret);let r={...t.RETRY_CONFIG,method:"POST",url:n,data:new URLSearchParams((0,Lu.removeUndefinedValuesInObject)(i)),headers:o};an.AuthClient.setMethodName(r,"getTokenAsync");let a=await this.transporter.request(r),u=a.data;return a.data&&a.data.expires_in&&(u.expiry_date=new Date().getTime()+a.data.expires_in*1e3,delete u.expires_in),this.emit("tokens",u),{tokens:u,res:a}}async refreshToken(e){if(!e)return this.refreshTokenNoCache(e);if(this.refreshTokenPromises.has(e))return this.refreshTokenPromises.get(e);let n=this.refreshTokenNoCache(e).then(o=>(this.refreshTokenPromises.delete(e),o),o=>{throw this.refreshTokenPromises.delete(e),o});return this.refreshTokenPromises.set(e,n),n}async refreshTokenNoCache(e){if(!e)throw new Error("No refresh token is set.");let n=this.endpoints.oauth2TokenUrl.toString(),o={refresh_token:e,client_id:this._clientId,client_secret:this._clientSecret,grant_type:"refresh_token"},i;try{let a={...t.RETRY_CONFIG,method:"POST",url:n,data:new URLSearchParams((0,Lu.removeUndefinedValuesInObject)(o))};an.AuthClient.setMethodName(a,"refreshTokenNoCache"),i=await this.transporter.request(a)}catch(a){throw a instanceof bu.GaxiosError&&a.message==="invalid_grant"&&a.response?.data&&/ReAuth/i.test(a.response.data.error_description)&&(a.message=JSON.stringify(a.response.data)),a}let r=i.data;return i.data&&i.data.expires_in&&(r.expiry_date=new Date().getTime()+i.data.expires_in*1e3,delete r.expires_in),this.emit("tokens",r),{tokens:r,res:i}}refreshAccessToken(e){if(e)this.refreshAccessTokenAsync().then(n=>e(null,n.credentials,n.res),e);else return this.refreshAccessTokenAsync()}async refreshAccessTokenAsync(){let e=await this.refreshToken(this.credentials.refresh_token),n=e.tokens;return n.refresh_token=this.credentials.refresh_token,this.credentials=n,{credentials:this.credentials,res:e.res}}getAccessToken(e){if(e)this.getAccessTokenAsync().then(n=>e(null,n.token,n.res),e);else return this.getAccessTokenAsync()}async getAccessTokenAsync(){if(!this.credentials.access_token||this.isTokenExpiring()){if(!this.credentials.refresh_token)if(this.refreshHandler){let o=await this.processAndValidateRefreshHandler();if(o?.access_token)return this.setCredentials(o),{token:this.credentials.access_token}}else throw new Error("No refresh token or refresh handler callback is set.");let n=await this.refreshAccessTokenAsync();if(!n.credentials||n.credentials&&!n.credentials.access_token)throw new Error("Could not refresh access token.");return{token:n.credentials.access_token,res:n.res}}else return{token:this.credentials.access_token}}async getRequestHeaders(e){return(await this.getRequestMetadataAsync(e)).headers}async getRequestMetadataAsync(e){let n=this.credentials;if(!n.access_token&&!n.refresh_token&&!this.apiKey&&!this.refreshHandler)throw new Error("No access, refresh token, API key or refresh handler callback is set.");if(n.access_token&&!this.isTokenExpiring()){n.token_type=n.token_type||"Bearer";let u=new Headers({authorization:n.token_type+" "+n.access_token});return{headers:this.addSharedMetadataHeaders(u)}}if(this.refreshHandler){let u=await this.processAndValidateRefreshHandler();if(u?.access_token){this.setCredentials(u);let c=new Headers({authorization:"Bearer "+this.credentials.access_token});return{headers:this.addSharedMetadataHeaders(c)}}}if(this.apiKey)return{headers:new Headers({"X-Goog-Api-Key":this.apiKey})};let o=null,i=null;try{o=await this.refreshToken(n.refresh_token),i=o.tokens}catch(u){let c=u;throw c.response&&(c.response.status===403||c.response.status===404)&&(c.message=`Could not refresh access token: ${c.message}`),c}let r=this.credentials;r.token_type=r.token_type||"Bearer",i.refresh_token=r.refresh_token,this.credentials=i;let a=new Headers({authorization:r.token_type+" "+i.access_token});return{headers:this.addSharedMetadataHeaders(a),res:o.res}}static getRevokeTokenUrl(e){return new t().getRevokeTokenURL(e).toString()}getRevokeTokenURL(e){let n=new URL(this.endpoints.oauth2RevokeUrl);return n.searchParams.append("token",e),n}revokeToken(e,n){let o={...t.RETRY_CONFIG,url:this.getRevokeTokenURL(e).toString(),method:"POST"};if(an.AuthClient.setMethodName(o,"revokeToken"),n)this.transporter.request(o).then(i=>n(null,i),n);else return this.transporter.request(o)}revokeCredentials(e){if(e)this.revokeCredentialsAsync().then(n=>e(null,n),e);else return this.revokeCredentialsAsync()}async revokeCredentialsAsync(){let e=this.credentials.access_token;if(this.credentials={},e)return this.revokeToken(e);throw new Error("No access token to revoke.")}request(e,n){if(n)this.requestAsync(e).then(o=>n(null,o),o=>n(o,o.response));else return this.requestAsync(e)}async requestAsync(e,n=!1){try{let o=await this.getRequestMetadataAsync();return e.headers=bu.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,o.headers),this.apiKey&&e.headers.set("X-Goog-Api-Key",this.apiKey),await this.transporter.request(e)}catch(o){let i=o.response;if(i){let r=i.status,a=this.credentials&&this.credentials.access_token&&this.credentials.refresh_token&&(!this.credentials.expiry_date||this.forceRefreshOnFailure),u=this.credentials&&this.credentials.access_token&&!this.credentials.refresh_token&&(!this.credentials.expiry_date||this.forceRefreshOnFailure)&&this.refreshHandler,c=i.config.data instanceof ug.Readable,d=r===401||r===403;if(!n&&d&&!c&&a)return await this.refreshAccessTokenAsync(),this.requestAsync(e,!0);if(!n&&d&&!c&&u){let f=await this.processAndValidateRefreshHandler();return f?.access_token&&this.setCredentials(f),this.requestAsync(e,!0)}}throw o}}verifyIdToken(e,n){if(n&&typeof n!="function")throw new Error("This method accepts an options object as the first parameter, which includes the idToken, audience, and maxExpiry.");if(n)this.verifyIdTokenAsync(e).then(o=>n(null,o),n);else return this.verifyIdTokenAsync(e)}async verifyIdTokenAsync(e){if(!e.idToken)throw new Error("The verifyIdToken method requires an ID Token");let n=await this.getFederatedSignonCertsAsync();return await this.verifySignedJwtWithCertsAsync(e.idToken,n.certs,e.audience,this.issuers,e.maxExpiry)}async getTokenInfo(e){let{data:n}=await this.transporter.request({...t.RETRY_CONFIG,method:"POST",headers:{"content-type":"application/x-www-form-urlencoded;charset=UTF-8",authorization:`Bearer ${e}`},url:this.endpoints.tokenInfoUrl.toString()}),o=Object.assign({expiry_date:new Date().getTime()+n.expires_in*1e3,scopes:n.scope.split(" ")},n);return delete o.expires_in,delete o.scope,o}getFederatedSignonCerts(e){if(e)this.getFederatedSignonCertsAsync().then(n=>e(null,n.certs,n.res),e);else return this.getFederatedSignonCertsAsync()}async getFederatedSignonCertsAsync(){let e=new Date().getTime(),n=(0,dr.hasBrowserCrypto)()?Ct.JWK:Ct.PEM;if(this.certificateExpiry&&e<this.certificateExpiry.getTime()&&this.certificateCacheFormat===n)return{certs:this.certificateCache,format:n};let o,i;switch(n){case Ct.PEM:i=this.endpoints.oauth2FederatedSignonPemCertsUrl.toString();break;case Ct.JWK:i=this.endpoints.oauth2FederatedSignonJwkCertsUrl.toString();break;default:throw new Error(`Unsupported certificate format ${n}`)}try{let d={...t.RETRY_CONFIG,url:i};an.AuthClient.setMethodName(d,"getFederatedSignonCertsAsync"),o=await this.transporter.request(d)}catch(d){throw d instanceof Error&&(d.message=`Failed to retrieve verification certificates: ${d.message}`),d}let r=o?.headers.get("cache-control"),a=-1;if(r){let d=/max-age=(?<maxAge>[0-9]+)/.exec(r)?.groups?.maxAge;d&&(a=Number(d)*1e3)}let u={};switch(n){case Ct.PEM:u=o.data;break;case Ct.JWK:for(let d of o.data.keys)u[d.kid]=d;break;default:throw new Error(`Unsupported certificate format ${n}`)}let c=new Date;return this.certificateExpiry=a===-1?null:new Date(c.getTime()+a),this.certificateCache=u,this.certificateCacheFormat=n,{certs:u,format:n,res:o}}getIapPublicKeys(e){if(e)this.getIapPublicKeysAsync().then(n=>e(null,n.pubkeys,n.res),e);else return this.getIapPublicKeysAsync()}async getIapPublicKeysAsync(){let e,n=this.endpoints.oauth2IapPublicKeyUrl.toString();try{let o={...t.RETRY_CONFIG,url:n};an.AuthClient.setMethodName(o,"getIapPublicKeysAsync"),e=await this.transporter.request(o)}catch(o){throw o instanceof Error&&(o.message=`Failed to retrieve verification certificates: ${o.message}`),o}return{pubkeys:e.data,res:e}}verifySignedJwtWithCerts(){throw new Error("verifySignedJwtWithCerts is removed, please use verifySignedJwtWithCertsAsync instead.")}async verifySignedJwtWithCertsAsync(e,n,o,i,r){let a=(0,dr.createCrypto)();r||(r=t.DEFAULT_MAX_TOKEN_LIFETIME_SECS_);let u=e.split(".");if(u.length!==3)throw new Error("Wrong number of segments in token: "+e);let c=u[0]+"."+u[1],d=u[2],f,p;try{f=JSON.parse(a.decodeBase64StringUtf8(u[0]))}catch(A){throw A instanceof Error&&(A.message=`Can't parse token envelope: ${u[0]}': ${A.message}`),A}if(!f)throw new Error("Can't parse token envelope: "+u[0]);try{p=JSON.parse(a.decodeBase64StringUtf8(u[1]))}catch(A){throw A instanceof Error&&(A.message=`Can't parse token payload '${u[0]}`),A}if(!p)throw new Error("Can't parse token payload: "+u[1]);if(!Object.prototype.hasOwnProperty.call(n,f.kid))throw new Error("No pem found for envelope: "+JSON.stringify(f));let h=n[f.kid];if(f.alg==="ES256"&&(d=cg.joseToDer(d,"ES256").toString("base64")),!await a.verify(h,c,d))throw new Error("Invalid token signature: "+e);if(!p.iat)throw new Error("No issue time in token: "+JSON.stringify(p));if(!p.exp)throw new Error("No expiration time in token: "+JSON.stringify(p));let _=Number(p.iat);if(isNaN(_))throw new Error("iat field using invalid format");let m=Number(p.exp);if(isNaN(m))throw new Error("exp field using invalid format");let v=new Date().getTime()/1e3;if(m>=v+r)throw new Error("Expiration time too far in future: "+JSON.stringify(p));let y=_-t.CLOCK_SKEW_SECS_,E=m+t.CLOCK_SKEW_SECS_;if(v<y)throw new Error("Token used too early, "+v+" < "+y+": "+JSON.stringify(p));if(v>E)throw new Error("Token used too late, "+v+" > "+E+": "+JSON.stringify(p));if(i&&i.indexOf(p.iss)<0)throw new Error("Invalid issuer, expected one of ["+i+"], but got "+p.iss);if(typeof o<"u"&&o!==null){let A=p.aud,C=!1;if(o.constructor===Array?C=o.indexOf(A)>-1:C=A===o,!C)throw new Error("Wrong recipient, payload audience != requiredAudience")}return new dg.LoginTicket(f,p)}async processAndValidateRefreshHandler(){if(this.refreshHandler){let e=await this.refreshHandler();if(!e.access_token)throw new Error("No access token is returned by the refreshHandler callback.");return e}}isTokenExpiring(){let e=this.credentials.expiry_date;return e?e<=new Date().getTime()+this.eagerRefreshThresholdMillis:!1}};mt.OAuth2Client=fr});var hr=W(co=>{"use strict";Object.defineProperty(co,"__esModule",{value:!0});co.Compute=void 0;var fg=xe(),Ou=xn(),pg=xt(),pr=class extends pg.OAuth2Client{serviceAccountEmail;scopes;constructor(e={}){super(e),this.credentials={expiry_date:1,refresh_token:"compute-placeholder"},this.serviceAccountEmail=e.serviceAccountEmail||"default",this.scopes=Array.isArray(e.scopes)?e.scopes:e.scopes?[e.scopes]:[]}async refreshTokenNoCache(){let e=`service-accounts/${this.serviceAccountEmail}/token`,n;try{let i={property:e};this.scopes.length>0&&(i.params={scopes:this.scopes.join(",")}),n=await Ou.instance(i)}catch(i){throw i instanceof fg.GaxiosError&&(i.message=`Could not refresh access token: ${i.message}`,this.wrapError(i)),i}let o=n;return n&&n.expires_in&&(o.expiry_date=new Date().getTime()+n.expires_in*1e3,delete o.expires_in),this.emit("tokens",o),{tokens:o,res:null}}async fetchIdToken(e){let n=`service-accounts/${this.serviceAccountEmail}/identity?format=full&audience=${e}`,o;try{let i={property:n};o=await Ou.instance(i)}catch(i){throw i instanceof Error&&(i.message=`Could not fetch ID token: ${i.message}`),i}return o}wrapError(e){let n=e.response;n&&n.status&&(e.status=n.status,n.status===403?e.message="A Forbidden error was returned while attempting to retrieve an access token for the Compute Engine built-in service account. This may be because the Compute Engine instance does not have the correct permission scopes specified: "+e.message:n.status===404&&(e.message="A Not Found error was returned while attempting to retrieve an accesstoken for the Compute Engine built-in service account. This may be because the Compute Engine instance does not have any permission scopes specified: "+e.message))}};co.Compute=pr});var gr=W(fo=>{"use strict";Object.defineProperty(fo,"__esModule",{value:!0});fo.IdTokenClient=void 0;var hg=xt(),mr=class extends hg.OAuth2Client{targetAudience;idTokenProvider;constructor(e){super(e),this.targetAudience=e.targetAudience,this.idTokenProvider=e.idTokenProvider}async getRequestMetadataAsync(){if(!this.credentials.id_token||!this.credentials.expiry_date||this.isTokenExpiring()){let n=await this.idTokenProvider.fetchIdToken(this.targetAudience);this.credentials={id_token:n,expiry_date:this.getIdTokenExpiryDate(n)}}return{headers:new Headers({authorization:"Bearer "+this.credentials.id_token})}}getIdTokenExpiryDate(e){let n=e.split(".")[1];if(n)return JSON.parse(Buffer.from(n,"base64").toString("ascii")).exp*1e3}};fo.IdTokenClient=mr});var _r=W(ln=>{"use strict";Object.defineProperty(ln,"__esModule",{value:!0});ln.GCPEnv=void 0;ln.clear=mg;ln.getEnv=gg;var Fu=xn(),gt;(function(t){t.APP_ENGINE="APP_ENGINE",t.KUBERNETES_ENGINE="KUBERNETES_ENGINE",t.CLOUD_FUNCTIONS="CLOUD_FUNCTIONS",t.COMPUTE_ENGINE="COMPUTE_ENGINE",t.CLOUD_RUN="CLOUD_RUN",t.CLOUD_RUN_JOBS="CLOUD_RUN_JOBS",t.NONE="NONE"})(gt||(ln.GCPEnv=gt={}));var Un;function mg(){Un=void 0}async function gg(){return Un||(Un=_g(),Un)}async function _g(){let t=gt.NONE;return yg()?t=gt.APP_ENGINE:vg()?t=gt.CLOUD_FUNCTIONS:await Cg()?await Ag()?t=gt.KUBERNETES_ENGINE:Eg()?t=gt.CLOUD_RUN:Tg()?t=gt.CLOUD_RUN_JOBS:t=gt.COMPUTE_ENGINE:t=gt.NONE,t}function yg(){return!!(process.env.GAE_SERVICE||process.env.GAE_MODULE_NAME)}function vg(){return!!(process.env.FUNCTION_NAME||process.env.FUNCTION_TARGET)}function Eg(){return!!process.env.K_CONFIGURATION}function Tg(){return!!process.env.CLOUD_RUN_JOB}async function Ag(){try{return await Fu.instance("attributes/cluster-name"),!0}catch{return!1}}async function Cg(){return Fu.isAvailable()}});var Vu=W(po=>{"use strict";Object.defineProperty(po,"__esModule",{value:!0});po.buildPayloadForJwsSign=Hu;po.getJwsSign=Rg;var Ig=wl(),Sg="RS256",wg="https://oauth2.googleapis.com/token";function Hu(t){let e=Math.floor(new Date().getTime()/1e3);return{iss:t.iss,scope:t.scope,aud:wg,exp:e+3600,iat:e,sub:t.sub,...t.additionalClaims}}function Rg(t){let e=Hu(t);return(0,Ig.sign)({header:{alg:Sg},payload:e,secret:t.key})}});var Bu=W(yr=>{"use strict";Object.defineProperty(yr,"__esModule",{value:!0});yr.getToken=Dg;var Pg=Vu(),kg="https://oauth2.googleapis.com/token",Ng="urn:ietf:params:oauth:grant-type:jwt-bearer",xg=t=>({method:"POST",url:kg,data:new URLSearchParams({grant_type:Ng,assertion:(0,Pg.getJwsSign)(t)}),responseType:"json",retryConfig:{httpMethodsToRetry:["POST"]}});async function Dg(t){if(!t.transporter)throw new Error("No transporter set.");try{let e=xg(t);return(await t.transporter.request(e)).data}catch(e){let n=e,o=n.response?.data;throw o?.error&&(n.message=`${o.error}: ${o.error_description}`),n}}});var $u=W(ho=>{"use strict";Object.defineProperty(ho,"__esModule",{value:!0});ho.ErrorWithCode=void 0;var vr=class extends Error{code;constructor(e,n){super(e),this.code=n}};ho.ErrorWithCode=vr});var Sr=W(Ir=>{"use strict";Object.defineProperty(Ir,"__esModule",{value:!0});Ir.getCredentials=Gg;var Mg=me("path"),Xu=me("fs"),Ug=me("util"),mo=$u(),Ju=Xu.readFile?(0,Ug.promisify)(Xu.readFile):async()=>{throw new mo.ErrorWithCode("use key rather than keyFile.","MISSING_CREDENTIALS")},Dt;(function(t){t.JSON=".json",t.DER=".der",t.CRT=".crt",t.PEM=".pem",t.P12=".p12",t.PFX=".pfx"})(Dt||(Dt={}));var Er=class{keyFilePath;constructor(e){this.keyFilePath=e}async getCredentials(){let e=await Ju(this.keyFilePath,"utf8"),n;try{n=JSON.parse(e)}catch(r){let a=r;throw new Error(`Invalid JSON key file: ${a.message}`)}let o=n.private_key,i=n.client_email;if(!o||!i)throw new mo.ErrorWithCode("private_key and client_email are required.","MISSING_CREDENTIALS");return{privateKey:o,clientEmail:i}}},Tr=class{keyFilePath;constructor(e){this.keyFilePath=e}async getCredentials(){return{privateKey:await Ju(this.keyFilePath,"utf8")}}},Ar=class{async getCredentials(){throw new mo.ErrorWithCode("*.p12 certificates are not supported after v6.1.2. Consider utilizing *.json format or converting *.p12 to *.pem using the OpenSSL CLI.","UNKNOWN_CERTIFICATE_TYPE")}},Cr=class{static create(e){switch(Mg.extname(e)){case Dt.JSON:return new Er(e);case Dt.DER:case Dt.CRT:case Dt.PEM:return new Tr(e);case Dt.P12:case Dt.PFX:return new Ar;default:throw new mo.ErrorWithCode("Unknown certificate type. Type is determined based on file extension. Current supported extensions are *.json, and *.pem.","UNKNOWN_CERTIFICATE_TYPE")}}};async function Gg(t){return Cr.create(t).getCredentials()}});var Ku=W(go=>{"use strict";Object.defineProperty(go,"__esModule",{value:!0});go.TokenHandler=void 0;var bg=Bu(),Lg=Sr(),wr=class{token;tokenExpiresAt;inFlightRequest;tokenOptions;constructor(e){this.tokenOptions=e}async processCredentials(){if(!this.tokenOptions.key&&!this.tokenOptions.keyFile)throw new Error("No key or keyFile set.");if(!this.tokenOptions.key&&this.tokenOptions.keyFile){let e=await(0,Lg.getCredentials)(this.tokenOptions.keyFile);this.tokenOptions.key=e.privateKey,this.tokenOptions.email=e.clientEmail}}isTokenExpiring(){if(!this.token||!this.tokenExpiresAt)return!0;let e=new Date().getTime(),n=this.tokenOptions.eagerRefreshThresholdMillis??0;return this.tokenExpiresAt<=e+n}hasExpired(){let e=new Date().getTime();return this.token&&this.tokenExpiresAt?new Date().getTime()>=this.tokenExpiresAt:!0}async getToken(e){if(await this.processCredentials(),this.inFlightRequest&&!e)return this.inFlightRequest;if(this.token&&!this.isTokenExpiring()&&!e)return this.token;try{this.inFlightRequest=(0,bg.getToken)(this.tokenOptions);let n=await this.inFlightRequest;return this.token=n,this.tokenExpiresAt=new Date().getTime()+(n.expires_in??0)*1e3,n}finally{this.inFlightRequest=void 0}}};go.TokenHandler=wr});var Yu=W(Rr=>{"use strict";Object.defineProperty(Rr,"__esModule",{value:!0});Rr.revokeToken=Fg;var qg="https://oauth2.googleapis.com/revoke?token=",Og=!0;async function Fg(t,e){let n=qg+t;return await e.request({url:n,retry:Og})}});var kr=W(_o=>{"use strict";Object.defineProperty(_o,"__esModule",{value:!0});_o.GoogleToken=void 0;var Hg=xe(),Wu=Ku(),Vg=Yu(),Pr=class{tokenOptions;tokenHandler;constructor(e){this.tokenOptions=e||{},this.tokenOptions.transporter=this.tokenOptions.transporter||{request:n=>(0,Hg.request)(n)},this.tokenOptions.iss||(this.tokenOptions.iss=this.tokenOptions.email),typeof this.tokenOptions.scope=="object"&&(this.tokenOptions.scope=this.tokenOptions.scope.join(" ")),this.tokenHandler=new Wu.TokenHandler(this.tokenOptions)}get expiresAt(){return this.tokenHandler.tokenExpiresAt}get accessToken(){return this.tokenHandler.token?.access_token}get idToken(){return this.tokenHandler.token?.id_token}get tokenType(){return this.tokenHandler.token?.token_type}get refreshToken(){return this.tokenHandler.token?.refresh_token}hasExpired(){return this.tokenHandler.hasExpired()}isTokenExpiring(){return this.tokenHandler.isTokenExpiring()}getToken(e,n={forceRefresh:!1}){let o;typeof e=="function"?o=e:typeof e=="object"&&(n=e);let i=this.tokenHandler.getToken(n.forceRefresh??!1);return o&&i.then(r=>o(null,r),o),i}revokeToken(e){if(!this.accessToken)return Promise.reject(new Error("No token to revoke."));let n=(0,Vg.revokeToken)(this.accessToken,this.tokenOptions.transporter);e&&n.then(()=>e(),e),this.tokenHandler=new Wu.TokenHandler(this.tokenOptions)}get googleTokenOptions(){return this.tokenOptions}};_o.GoogleToken=Pr});var xr=W(yo=>{"use strict";Object.defineProperty(yo,"__esModule",{value:!0});yo.JWTAccess=void 0;var Bg=wl(),$g=at(),zu={alg:"RS256",typ:"JWT"},Nr=class t{email;key;keyId;projectId;eagerRefreshThresholdMillis;cache=new $g.LRUCache({capacity:500,maxAge:3600*1e3});constructor(e,n,o,i){this.email=e,this.key=n,this.keyId=o,this.eagerRefreshThresholdMillis=i??300*1e3}getCachedKey(e,n){let o=e;if(n&&Array.isArray(n)&&n.length?o=e?`${e}_${n.join("_")}`:`${n.join("_")}`:typeof n=="string"&&(o=e?`${e}_${n}`:n),!o)throw Error("Scopes or url must be provided");return o}getRequestHeaders(e,n,o){let i=this.getCachedKey(e,o),r=this.cache.get(i),a=Date.now();if(r&&r.expiration-a>this.eagerRefreshThresholdMillis)return new Headers(r.headers);let u=Math.floor(Date.now()/1e3),c=t.getExpirationTime(u),d;if(Array.isArray(o)&&(o=o.join(" ")),o?d={iss:this.email,sub:this.email,scope:o,exp:c,iat:u}:d={iss:this.email,sub:this.email,aud:e,exp:c,iat:u},n){for(let _ in d)if(n[_])throw new Error(`The '${_}' property is not allowed when passing additionalClaims. This claim is included in the JWT by default.`)}let f=this.keyId?{...zu,kid:this.keyId}:zu,p=Object.assign(d,n),h=Bg.sign({header:f,payload:p,secret:this.key}),g=new Headers({authorization:`Bearer ${h}`});return this.cache.set(i,{expiration:c*1e3,headers:g}),g}static getExpirationTime(e){return e+3600}fromJSON(e){if(!e)throw new Error("Must pass in a JSON object containing the service account auth settings.");if(!e.client_email)throw new Error("The incoming JSON object does not contain a client_email field");if(!e.private_key)throw new Error("The incoming JSON object does not contain a private_key field");this.email=e.client_email,this.key=e.private_key,this.keyId=e.private_key_id,this.projectId=e.project_id}fromStream(e,n){if(n)this.fromStreamAsync(e).then(()=>n(),n);else return this.fromStreamAsync(e)}fromStreamAsync(e){return new Promise((n,o)=>{e||o(new Error("Must pass in a stream containing the service account auth settings."));let i="";e.setEncoding("utf8").on("data",r=>i+=r).on("error",o).on("end",()=>{try{let r=JSON.parse(i);this.fromJSON(r),n()}catch(r){o(r)}})})}};yo.JWTAccess=Nr});var Mr=W(Eo=>{"use strict";Object.defineProperty(Eo,"__esModule",{value:!0});Eo.JWT=void 0;var Qu=kr(),Xg=Sr(),Jg=xr(),Kg=xt(),vo=$e(),Dr=class t extends Kg.OAuth2Client{email;keyFile;key;keyId;defaultScopes;scopes;scope;subject;gtoken;additionalClaims;useJWTAccessWithScope;defaultServicePath;access;constructor(e={}){super(e),this.email=e.email,this.keyFile=e.keyFile,this.key=e.key,this.keyId=e.keyId,this.scopes=e.scopes,this.subject=e.subject,this.additionalClaims=e.additionalClaims,this.credentials={refresh_token:"jwt-placeholder",expiry_date:1}}createScoped(e){let n=new t(this);return n.scopes=e,n}async getRequestMetadataAsync(e){e=this.defaultServicePath?`https://${this.defaultServicePath}/`:e;let n=!this.hasUserScopes()&&e||this.useJWTAccessWithScope&&this.hasAnyScopes()||this.universeDomain!==vo.DEFAULT_UNIVERSE;if(this.subject&&this.universeDomain!==vo.DEFAULT_UNIVERSE)throw new RangeError(`Service Account user is configured for the credential. Domain-wide delegation is not supported in universes other than ${vo.DEFAULT_UNIVERSE}`);if(!this.apiKey&&n)if(this.additionalClaims&&this.additionalClaims.target_audience){let{tokens:o}=await this.refreshToken();return{headers:this.addSharedMetadataHeaders(new Headers({authorization:`Bearer ${o.id_token}`}))}}else{this.access||(this.access=new Jg.JWTAccess(this.email,this.key,this.keyId,this.eagerRefreshThresholdMillis));let o;this.hasUserScopes()?o=this.scopes:e||(o=this.defaultScopes);let i=this.useJWTAccessWithScope||this.universeDomain!==vo.DEFAULT_UNIVERSE,r=await this.access.getRequestHeaders(e??void 0,this.additionalClaims,i?o:void 0);return{headers:this.addSharedMetadataHeaders(r)}}else return this.hasAnyScopes()||this.apiKey?super.getRequestMetadataAsync(e):{headers:new Headers}}async fetchIdToken(e){let n=new Qu.GoogleToken({iss:this.email,sub:this.subject,scope:this.scopes||this.defaultScopes,keyFile:this.keyFile,key:this.key,additionalClaims:{target_audience:e},transporter:this.transporter});if(await n.getToken({forceRefresh:!0}),!n.idToken)throw new Error("Unknown error: Failed to fetch ID token");return n.idToken}hasUserScopes(){return this.scopes?this.scopes.length>0:!1}hasAnyScopes(){return!!(this.scopes&&this.scopes.length>0||this.defaultScopes&&this.defaultScopes.length>0)}authorize(e){if(e)this.authorizeAsync().then(n=>e(null,n),e);else return this.authorizeAsync()}async authorizeAsync(){let e=await this.refreshToken();if(!e)throw new Error("No result returned");return this.credentials=e.tokens,this.credentials.refresh_token="jwt-placeholder",this.key=this.gtoken.googleTokenOptions?.key,this.email=this.gtoken.googleTokenOptions?.iss,e.tokens}async refreshTokenNoCache(){let e=this.createGToken(),o={access_token:(await e.getToken({forceRefresh:this.isTokenExpiring()})).access_token,token_type:"Bearer",expiry_date:e.expiresAt,id_token:e.idToken};return this.emit("tokens",o),{res:null,tokens:o}}createGToken(){return this.gtoken||(this.gtoken=new Qu.GoogleToken({iss:this.email,sub:this.subject,scope:this.scopes||this.defaultScopes,keyFile:this.keyFile,key:this.key,additionalClaims:this.additionalClaims,transporter:this.transporter})),this.gtoken}fromJSON(e){if(!e)throw new Error("Must pass in a JSON object containing the service account auth settings.");if(!e.client_email)throw new Error("The incoming JSON object does not contain a client_email field");if(!e.private_key)throw new Error("The incoming JSON object does not contain a private_key field");this.email=e.client_email,this.key=e.private_key,this.keyId=e.private_key_id,this.projectId=e.project_id,this.quotaProjectId=e.quota_project_id,this.universeDomain=e.universe_domain||this.universeDomain}fromStream(e,n){if(n)this.fromStreamAsync(e).then(()=>n(),n);else return this.fromStreamAsync(e)}fromStreamAsync(e){return new Promise((n,o)=>{if(!e)throw new Error("Must pass in a stream containing the service account auth settings.");let i="";e.setEncoding("utf8").on("error",o).on("data",r=>i+=r).on("end",()=>{try{let r=JSON.parse(i);this.fromJSON(r),n()}catch(r){o(r)}})})}fromAPIKey(e){if(typeof e!="string")throw new Error("Must provide an API Key string.");this.apiKey=e}async getCredentials(){if(this.key)return{private_key:this.key,client_email:this.email};if(this.keyFile){let e=this.createGToken(),n=await(0,Xg.getCredentials)(this.keyFile);return{private_key:n.privateKey,client_email:n.clientEmail}}throw new Error("A key or a keyFile must be provided to getCredentials.")}};Eo.JWT=Dr});var Gr=W(un=>{"use strict";Object.defineProperty(un,"__esModule",{value:!0});un.UserRefreshClient=un.USER_REFRESH_ACCOUNT_TYPE=void 0;var Yg=xt(),Wg=$e();un.USER_REFRESH_ACCOUNT_TYPE="authorized_user";var Ur=class t extends Yg.OAuth2Client{_refreshToken;constructor(e,n,o,i,r){let a=e&&typeof e=="object"?e:{clientId:e,clientSecret:n,refreshToken:o,eagerRefreshThresholdMillis:i,forceRefreshOnFailure:r};super(a),this._refreshToken=a.refreshToken,this.credentials.refresh_token=a.refreshToken}async refreshTokenNoCache(){return super.refreshTokenNoCache(this._refreshToken)}async fetchIdToken(e){let n={...t.RETRY_CONFIG,url:this.endpoints.oauth2TokenUrl,method:"POST",data:new URLSearchParams({client_id:this._clientId,client_secret:this._clientSecret,grant_type:"refresh_token",refresh_token:this._refreshToken,target_audience:e}),responseType:"json"};return Wg.AuthClient.setMethodName(n,"fetchIdToken"),(await this.transporter.request(n)).data.id_token}fromJSON(e){if(!e)throw new Error("Must pass in a JSON object containing the user refresh token");if(e.type!=="authorized_user")throw new Error('The incoming JSON object does not have the "authorized_user" type');if(!e.client_id)throw new Error("The incoming JSON object does not contain a client_id field");if(!e.client_secret)throw new Error("The incoming JSON object does not contain a client_secret field");if(!e.refresh_token)throw new Error("The incoming JSON object does not contain a refresh_token field");this._clientId=e.client_id,this._clientSecret=e.client_secret,this._refreshToken=e.refresh_token,this.credentials.refresh_token=e.refresh_token,this.quotaProjectId=e.quota_project_id,this.universeDomain=e.universe_domain||this.universeDomain}fromStream(e,n){if(n)this.fromStreamAsync(e).then(()=>n(),n);else return this.fromStreamAsync(e)}async fromStreamAsync(e){return new Promise((n,o)=>{if(!e)return o(new Error("Must pass in a stream containing the user refresh token."));let i="";e.setEncoding("utf8").on("error",o).on("data",r=>i+=r).on("end",()=>{try{let r=JSON.parse(i);return this.fromJSON(r),n()}catch(r){return o(r)}})})}static fromJSON(e){let n=new t;return n.fromJSON(e),n}};un.UserRefreshClient=Ur});var Lr=W(cn=>{"use strict";Object.defineProperty(cn,"__esModule",{value:!0});cn.Impersonated=cn.IMPERSONATED_ACCOUNT_TYPE=void 0;var Zu=xt(),zg=xe(),Qg=at();cn.IMPERSONATED_ACCOUNT_TYPE="impersonated_service_account";var br=class t extends Zu.OAuth2Client{sourceClient;targetPrincipal;targetScopes;delegates;lifetime;endpoint;constructor(e={}){if(super(e),this.credentials={expiry_date:1,refresh_token:"impersonated-placeholder"},this.sourceClient=e.sourceClient??new Zu.OAuth2Client,this.targetPrincipal=e.targetPrincipal??"",this.delegates=e.delegates??[],this.targetScopes=e.targetScopes??[],this.lifetime=e.lifetime??3600,!!!(0,Qg.originalOrCamelOptions)(e).get("universe_domain"))this.universeDomain=this.sourceClient.universeDomain;else if(this.sourceClient.universeDomain!==this.universeDomain)throw new RangeError(`Universe domain ${this.sourceClient.universeDomain} in source credentials does not match ${this.universeDomain} universe domain set for impersonated credentials.`);this.endpoint=e.endpoint??`https://iamcredentials.${this.universeDomain}`}async sign(e){await this.sourceClient.getAccessToken();let n=`projects/-/serviceAccounts/${this.targetPrincipal}`,o=`${this.endpoint}/v1/${n}:signBlob`,i={delegates:this.delegates,payload:Buffer.from(e).toString("base64")};return(await this.sourceClient.request({...t.RETRY_CONFIG,url:o,data:i,method:"POST"})).data}getTargetPrincipal(){return this.targetPrincipal}async refreshToken(){try{await this.sourceClient.getAccessToken();let e="projects/-/serviceAccounts/"+this.targetPrincipal,n=`${this.endpoint}/v1/${e}:generateAccessToken`,o={delegates:this.delegates,scope:this.targetScopes,lifetime:this.lifetime+"s"},i=await this.sourceClient.request({...t.RETRY_CONFIG,url:n,data:o,method:"POST"}),r=i.data;return this.credentials.access_token=r.accessToken,this.credentials.expiry_date=Date.parse(r.expireTime),{tokens:this.credentials,res:i}}catch(e){if(!(e instanceof Error))throw e;let n=0,o="";throw e instanceof zg.GaxiosError&&(n=e?.response?.data?.error?.status,o=e?.response?.data?.error?.message),n&&o?(e.message=`${n}: unable to impersonate: ${o}`,e):(e.message=`unable to impersonate: ${e}`,e)}}async fetchIdToken(e,n){await this.sourceClient.getAccessToken();let o=`projects/-/serviceAccounts/${this.targetPrincipal}`,i=`${this.endpoint}/v1/${o}:generateIdToken`,r={delegates:this.delegates,audience:e,includeEmail:n?.includeEmail??!0,useEmailAzp:n?.includeEmail??!0};return(await this.sourceClient.request({...t.RETRY_CONFIG,url:i,data:r,method:"POST"})).data.token}};cn.Impersonated=br});var Or=W(Gn=>{"use strict";Object.defineProperty(Gn,"__esModule",{value:!0});Gn.OAuthClientAuthHandler=void 0;Gn.getErrorFromOAuthErrorResponse=e_;var dn=xe(),Zg=Dn(),jg=["PUT","POST","PATCH"],qr=class{#e=(0,Zg.createCrypto)();#t;transporter;constructor(e){e&&"clientId"in e?(this.#t=e,this.transporter=new dn.Gaxios):(this.#t=e?.clientAuthentication,this.transporter=e?.transporter||new dn.Gaxios)}applyClientAuthenticationOptions(e,n){e.headers=dn.Gaxios.mergeHeaders(e.headers),this.injectAuthenticatedHeaders(e,n),n||this.injectAuthenticatedRequestBody(e)}injectAuthenticatedHeaders(e,n){if(n)e.headers=dn.Gaxios.mergeHeaders(e.headers,{authorization:`Bearer ${n}`});else if(this.#t?.confidentialClientType==="basic"){e.headers=dn.Gaxios.mergeHeaders(e.headers);let o=this.#t.clientId,i=this.#t.clientSecret||"",r=this.#e.encodeBase64StringUtf8(`${o}:${i}`);dn.Gaxios.mergeHeaders(e.headers,{authorization:`Basic ${r}`})}}injectAuthenticatedRequestBody(e){if(this.#t?.confidentialClientType==="request-body"){let n=(e.method||"GET").toUpperCase();if(!jg.includes(n))throw new Error(`${n} HTTP method does not support ${this.#t.confidentialClientType} client authentication`);let i=new Headers(e.headers).get("content-type");if(i?.startsWith("application/x-www-form-urlencoded")||e.data instanceof URLSearchParams){let r=new URLSearchParams(e.data??"");r.append("client_id",this.#t.clientId),r.append("client_secret",this.#t.clientSecret||""),e.data=r}else if(i?.startsWith("application/json"))e.data=e.data||{},Object.assign(e.data,{client_id:this.#t.clientId,client_secret:this.#t.clientSecret||""});else throw new Error(`${i} content-types are not supported with ${this.#t.confidentialClientType} client authentication`)}}static get RETRY_CONFIG(){return{retry:!0,retryConfig:{httpMethodsToRetry:["GET","PUT","POST","HEAD","OPTIONS","DELETE"]}}}};Gn.OAuthClientAuthHandler=qr;function e_(t,e){let n=t.error,o=t.error_description,i=t.error_uri,r=`Error code ${n}`;typeof o<"u"&&(r+=`: ${o}`),typeof i<"u"&&(r+=` - ${i}`);let a=new Error(r);if(e){let u=Object.keys(e);e.stack&&u.push("stack"),u.forEach(c=>{c!=="message"&&Object.defineProperty(a,c,{value:e[c],writable:!1,enumerable:!0})})}return a}});var Ao=W(To=>{"use strict";Object.defineProperty(To,"__esModule",{value:!0});To.StsCredentials=void 0;var t_=xe(),n_=$e(),ju=Or(),o_=at(),Fr=class t extends ju.OAuthClientAuthHandler{#e;constructor(e={tokenExchangeEndpoint:""},n){(typeof e!="object"||e instanceof URL)&&(e={tokenExchangeEndpoint:e,clientAuthentication:n}),super(e),this.#e=e.tokenExchangeEndpoint}async exchangeToken(e,n,o){let i={grant_type:e.grantType,resource:e.resource,audience:e.audience,scope:e.scope?.join(" "),requested_token_type:e.requestedTokenType,subject_token:e.subjectToken,subject_token_type:e.subjectTokenType,actor_token:e.actingParty?.actorToken,actor_token_type:e.actingParty?.actorTokenType,options:o&&JSON.stringify(o)},r={...t.RETRY_CONFIG,url:this.#e.toString(),method:"POST",headers:n,data:new URLSearchParams((0,o_.removeUndefinedValuesInObject)(i)),responseType:"json"};n_.AuthClient.setMethodName(r,"exchangeToken"),this.applyClientAuthenticationOptions(r);try{let a=await this.transporter.request(r),u=a.data;return u.res=a,u}catch(a){throw a instanceof t_.GaxiosError&&a.response?(0,ju.getErrorFromOAuthErrorResponse)(a.response.data,a):a}}};To.StsCredentials=Fr});var Mt=W(Qe=>{"use strict";Object.defineProperty(Qe,"__esModule",{value:!0});Qe.BaseExternalAccountClient=Qe.CLOUD_RESOURCE_MANAGER=Qe.EXTERNAL_ACCOUNT_TYPE=Qe.EXPIRATION_TIME_OFFSET=void 0;var i_=xe(),r_=me("stream"),Hr=$e(),s_=Ao(),ec=at(),a_=rr(),l_="urn:ietf:params:oauth:grant-type:token-exchange",u_="urn:ietf:params:oauth:token-type:access_token",Vr="https://www.googleapis.com/auth/cloud-platform",c_=3600;Qe.EXPIRATION_TIME_OFFSET=300*1e3;Qe.EXTERNAL_ACCOUNT_TYPE="external_account";Qe.CLOUD_RESOURCE_MANAGER="https://cloudresourcemanager.googleapis.com/v1/projects/";var d_="//iam\\.googleapis\\.com/locations/[^/]+/workforcePools/[^/]+/providers/.+",f_="https://sts.{universeDomain}/v1/token",Br=class t extends Hr.AuthClient{scopes;projectNumber;audience;subjectTokenType;stsCredential;clientAuth;credentialSourceType;cachedAccessToken;serviceAccountImpersonationUrl;serviceAccountImpersonationLifetime;workforcePoolUserProject;configLifetimeRequested;tokenUrl;cloudResourceManagerURL;supplierContext;#e=null;constructor(e){super(e);let n=(0,ec.originalOrCamelOptions)(e),o=n.get("type");if(o&&o!==Qe.EXTERNAL_ACCOUNT_TYPE)throw new Error(`Expected "${Qe.EXTERNAL_ACCOUNT_TYPE}" type but received "${e.type}"`);let i=n.get("client_id"),r=n.get("client_secret");this.tokenUrl=n.get("token_url")??f_.replace("{universeDomain}",this.universeDomain);let a=n.get("subject_token_type"),u=n.get("workforce_pool_user_project"),c=n.get("service_account_impersonation_url"),d=n.get("service_account_impersonation"),f=(0,ec.originalOrCamelOptions)(d).get("token_lifetime_seconds");this.cloudResourceManagerURL=new URL(n.get("cloud_resource_manager_url")||`https://cloudresourcemanager.${this.universeDomain}/v1/projects/`),i&&(this.clientAuth={confidentialClientType:"basic",clientId:i,clientSecret:r}),this.stsCredential=new s_.StsCredentials({tokenExchangeEndpoint:this.tokenUrl,clientAuthentication:this.clientAuth}),this.scopes=n.get("scopes")||[Vr],this.cachedAccessToken=null,this.audience=n.get("audience"),this.subjectTokenType=a,this.workforcePoolUserProject=u;let p=new RegExp(d_);if(this.workforcePoolUserProject&&!this.audience.match(p))throw new Error("workforcePoolUserProject should not be set for non-workforce pool credentials.");this.serviceAccountImpersonationUrl=c,this.serviceAccountImpersonationLifetime=f,this.serviceAccountImpersonationLifetime?this.configLifetimeRequested=!0:(this.configLifetimeRequested=!1,this.serviceAccountImpersonationLifetime=c_),this.projectNumber=this.getProjectNumber(this.audience),this.supplierContext={audience:this.audience,subjectTokenType:this.subjectTokenType,transporter:this.transporter}}getServiceAccountEmail(){if(this.serviceAccountImpersonationUrl){if(this.serviceAccountImpersonationUrl.length>256)throw new RangeError(`URL is too long: ${this.serviceAccountImpersonationUrl}`);return/serviceAccounts\/(?<email>[^:]+):generateAccessToken$/.exec(this.serviceAccountImpersonationUrl)?.groups?.email||null}return null}setCredentials(e){super.setCredentials(e),this.cachedAccessToken=e}async getAccessToken(){return(!this.cachedAccessToken||this.isExpired(this.cachedAccessToken))&&await this.refreshAccessTokenAsync(),{token:this.cachedAccessToken.access_token,res:this.cachedAccessToken.res}}async getRequestHeaders(){let e=await this.getAccessToken(),n=new Headers({authorization:`Bearer ${e.token}`});return this.addSharedMetadataHeaders(n)}request(e,n){if(n)this.requestAsync(e).then(o=>n(null,o),o=>n(o,o.response));else return this.requestAsync(e)}async getProjectId(){let e=this.projectNumber||this.workforcePoolUserProject;if(this.projectId)return this.projectId;if(e){let n=await this.getRequestHeaders(),o={...t.RETRY_CONFIG,headers:n,url:`${this.cloudResourceManagerURL.toString()}${e}`,responseType:"json"};Hr.AuthClient.setMethodName(o,"getProjectId");let i=await this.transporter.request(o);return this.projectId=i.data.projectId,this.projectId}return null}async requestAsync(e,n=!1){let o;try{let i=await this.getRequestHeaders();e.headers=i_.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,i),o=await this.transporter.request(e)}catch(i){let r=i.response;if(r){let a=r.status,u=r.config.data instanceof r_.Readable;if(!n&&(a===401||a===403)&&!u&&this.forceRefreshOnFailure)return await this.refreshAccessTokenAsync(),await this.requestAsync(e,!0)}throw i}return o}async refreshAccessTokenAsync(){this.#e=this.#e||this.#t();try{return await this.#e}finally{this.#e=null}}async#t(){let e=await this.retrieveSubjectToken(),n={grantType:l_,audience:this.audience,requestedTokenType:u_,subjectToken:e,subjectTokenType:this.subjectTokenType,scope:this.serviceAccountImpersonationUrl?[Vr]:this.getScopesArray()},o=!this.clientAuth&&this.workforcePoolUserProject?{userProject:this.workforcePoolUserProject}:void 0,i=new Headers({"x-goog-api-client":this.getMetricsHeaderValue()}),r=await this.stsCredential.exchangeToken(n,i,o);return this.serviceAccountImpersonationUrl?this.cachedAccessToken=await this.getImpersonatedAccessToken(r.access_token):r.expires_in?this.cachedAccessToken={access_token:r.access_token,expiry_date:new Date().getTime()+r.expires_in*1e3,res:r.res}:this.cachedAccessToken={access_token:r.access_token,res:r.res},this.credentials={},Object.assign(this.credentials,this.cachedAccessToken),delete this.credentials.res,this.emit("tokens",{refresh_token:null,expiry_date:this.cachedAccessToken.expiry_date,access_token:this.cachedAccessToken.access_token,token_type:"Bearer",id_token:null}),this.cachedAccessToken}getProjectNumber(e){let n=e.match(/\/projects\/([^/]+)/);return n?n[1]:null}async getImpersonatedAccessToken(e){let n={...t.RETRY_CONFIG,url:this.serviceAccountImpersonationUrl,method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e}`},data:{scope:this.getScopesArray(),lifetime:this.serviceAccountImpersonationLifetime+"s"},responseType:"json"};Hr.AuthClient.setMethodName(n,"getImpersonatedAccessToken");let o=await this.transporter.request(n),i=o.data;return{access_token:i.accessToken,expiry_date:new Date(i.expireTime).getTime(),res:o}}isExpired(e){let n=new Date().getTime();return e.expiry_date?n>=e.expiry_date-this.eagerRefreshThresholdMillis:!1}getScopesArray(){return typeof this.scopes=="string"?[this.scopes]:this.scopes||[Vr]}getMetricsHeaderValue(){let e=process.version.replace(/^v/,""),n=this.serviceAccountImpersonationUrl!==void 0,o=this.credentialSourceType?this.credentialSourceType:"unknown";return`gl-node/${e} auth/${a_.pkg.version} google-byoid-sdk source/${o} sa-impersonation/${n} config-lifetime/${this.configLifetimeRequested}`}getTokenUrl(){return this.tokenUrl}};Qe.BaseExternalAccountClient=Br});var tc=W(Co=>{"use strict";Object.defineProperty(Co,"__esModule",{value:!0});Co.FileSubjectTokenSupplier=void 0;var Xr=me("util"),Jr=me("fs"),p_=(0,Xr.promisify)(Jr.readFile??(()=>{})),h_=(0,Xr.promisify)(Jr.realpath??(()=>{})),m_=(0,Xr.promisify)(Jr.lstat??(()=>{})),$r=class{filePath;formatType;subjectTokenFieldName;constructor(e){this.filePath=e.filePath,this.formatType=e.formatType,this.subjectTokenFieldName=e.subjectTokenFieldName}async getSubjectToken(){let e=this.filePath;try{if(e=await h_(e),!(await m_(e)).isFile())throw new Error}catch(i){throw i instanceof Error&&(i.message=`The file at ${e} does not exist, or it is not a file. ${i.message}`),i}let n,o=await p_(e,{encoding:"utf8"});if(this.formatType==="text"?n=o:this.formatType==="json"&&this.subjectTokenFieldName&&(n=JSON.parse(o)[this.subjectTokenFieldName]),!n)throw new Error("Unable to parse the subject_token from the credential_source file");return n}};Co.FileSubjectTokenSupplier=$r});var nc=W(Io=>{"use strict";Object.defineProperty(Io,"__esModule",{value:!0});Io.UrlSubjectTokenSupplier=void 0;var g_=$e(),Kr=class{url;headers;formatType;subjectTokenFieldName;additionalGaxiosOptions;constructor(e){this.url=e.url,this.formatType=e.formatType,this.subjectTokenFieldName=e.subjectTokenFieldName,this.headers=e.headers,this.additionalGaxiosOptions=e.additionalGaxiosOptions}async getSubjectToken(e){let n={...this.additionalGaxiosOptions,url:this.url,method:"GET",headers:this.headers,responseType:this.formatType};g_.AuthClient.setMethodName(n,"getSubjectToken");let o;if(this.formatType==="text"?o=(await e.transporter.request(n)).data:this.formatType==="json"&&this.subjectTokenFieldName&&(o=(await e.transporter.request(n)).data[this.subjectTokenFieldName]),!o)throw new Error("Unable to parse the subject_token from the credential_source URL");return o}};Io.UrlSubjectTokenSupplier=Kr});var oc=W(Xe=>{"use strict";Object.defineProperty(Xe,"__esModule",{value:!0});Xe.CertificateSubjectTokenSupplier=Xe.InvalidConfigurationError=Xe.CertificateSourceUnavailableError=Xe.CERTIFICATE_CONFIGURATION_ENV_VARIABLE=void 0;var So=at(),wo=me("fs"),Ro=me("crypto"),__=me("https");Xe.CERTIFICATE_CONFIGURATION_ENV_VARIABLE="GOOGLE_API_CERTIFICATE_CONFIG";var _t=class extends Error{constructor(e){super(e),this.name="CertificateSourceUnavailableError"}};Xe.CertificateSourceUnavailableError=_t;var Ze=class extends Error{constructor(e){super(e),this.name="InvalidConfigurationError"}};Xe.InvalidConfigurationError=Ze;var Yr=class{certificateConfigPath;trustChainPath;cert;key;constructor(e){if(!e.useDefaultCertificateConfig&&!e.certificateConfigLocation)throw new Ze("Either `useDefaultCertificateConfig` must be true or a `certificateConfigLocation` must be provided.");if(e.useDefaultCertificateConfig&&e.certificateConfigLocation)throw new Ze("Both `useDefaultCertificateConfig` and `certificateConfigLocation` cannot be provided.");this.trustChainPath=e.trustChainPath,this.certificateConfigPath=e.certificateConfigLocation??""}async createMtlsHttpsAgent(){if(!this.key||!this.cert)throw new Ze("Cannot create mTLS Agent with missing certificate or key");return new __.Agent({key:this.key,cert:this.cert})}async getSubjectToken(){this.certificateConfigPath=await this.#e();let{certPath:e,keyPath:n}=await this.#t();return{cert:this.cert,key:this.key}=await this.#n(e,n),await this.#o(this.cert)}async#e(){let e=this.certificateConfigPath;if(e){if(await(0,So.isValidFile)(e))return e;throw new _t(`Provided certificate config path is invalid: ${e}`)}let n=process.env[Xe.CERTIFICATE_CONFIGURATION_ENV_VARIABLE];if(n){if(await(0,So.isValidFile)(n))return n;throw new _t(`Path from environment variable "${Xe.CERTIFICATE_CONFIGURATION_ENV_VARIABLE}" is invalid: ${n}`)}let o=(0,So.getWellKnownCertificateConfigFileLocation)();if(await(0,So.isValidFile)(o))return o;throw new _t(`Could not find certificate configuration file. Searched override path, the "${Xe.CERTIFICATE_CONFIGURATION_ENV_VARIABLE}" env var, and the gcloud path (${o}).`)}async#t(){let e=this.certificateConfigPath,n;try{n=await wo.promises.readFile(e,"utf8")}catch{throw new _t(`Failed to read certificate config file at: ${e}`)}try{let o=JSON.parse(n),i=o?.cert_configs?.workload?.cert_path,r=o?.cert_configs?.workload?.key_path;if(!i||!r)throw new Ze(`Certificate config file (${e}) is missing required "cert_path" or "key_path" in the workload config.`);return{certPath:i,keyPath:r}}catch(o){throw o instanceof Ze?o:new Ze(`Failed to parse certificate config from ${e}: ${o.message}`)}}async#n(e,n){let o,i;try{o=await wo.promises.readFile(e),new Ro.X509Certificate(o)}catch(r){let a=r instanceof Error?r.message:String(r);throw new _t(`Failed to read certificate file at ${e}: ${a}`)}try{i=await wo.promises.readFile(n),(0,Ro.createPrivateKey)(i)}catch(r){let a=r instanceof Error?r.message:String(r);throw new _t(`Failed to read private key file at ${n}: ${a}`)}return{cert:o,key:i}}async#o(e){let n=new Ro.X509Certificate(e);if(!this.trustChainPath)return JSON.stringify([n.raw.toString("base64")]);try{let r=((await wo.promises.readFile(this.trustChainPath,"utf8")).match(/-----BEGIN CERTIFICATE-----[^-]+-----END CERTIFICATE-----/g)??[]).map((c,d)=>{try{return new Ro.X509Certificate(c)}catch(f){let p=f instanceof Error?f.message:String(f);throw new Ze(`Failed to parse certificate at index ${d} in trust chain file ${this.trustChainPath}: ${p}`)}}),a=r.findIndex(c=>n.raw.equals(c.raw)),u;if(a===-1)u=[n,...r];else if(a===0)u=r;else throw new Ze(`Leaf certificate exists in the trust chain but is not the first entry (found at index ${a}).`);return JSON.stringify(u.map(c=>c.raw.toString("base64")))}catch(o){if(o instanceof Ze)throw o;let i=o instanceof Error?o.message:String(o);throw new _t(`Failed to process certificate chain from ${this.trustChainPath}: ${i}`)}}};Xe.CertificateSubjectTokenSupplier=Yr});var Qr=W(Po=>{"use strict";Object.defineProperty(Po,"__esModule",{value:!0});Po.IdentityPoolClient=void 0;var y_=Mt(),Wr=at(),v_=tc(),E_=nc(),ic=oc(),T_=Ao(),rc=xe(),zr=class t extends y_.BaseExternalAccountClient{subjectTokenSupplier;constructor(e){super(e);let n=(0,Wr.originalOrCamelOptions)(e),o=n.get("credential_source"),i=n.get("subject_token_supplier");if(!o&&!i)throw new Error("A credential source or subject token supplier must be specified.");if(o&&i)throw new Error("Only one of credential source or subject token supplier can be specified.");if(i)this.subjectTokenSupplier=i,this.credentialSourceType="programmatic";else{let r=(0,Wr.originalOrCamelOptions)(o),a=(0,Wr.originalOrCamelOptions)(r.get("format")),u=a.get("type")||"text",c=a.get("subject_token_field_name");if(u!=="json"&&u!=="text")throw new Error(`Invalid credential_source format "${u}"`);if(u==="json"&&!c)throw new Error("Missing subject_token_field_name for JSON credential_source format");let d=r.get("file"),f=r.get("url"),p=r.get("certificate"),h=r.get("headers");if(d&&f||f&&p||d&&p)throw new Error('No valid Identity Pool "credential_source" provided, must be either file, url, or certificate.');if(d)this.credentialSourceType="file",this.subjectTokenSupplier=new v_.FileSubjectTokenSupplier({filePath:d,formatType:u,subjectTokenFieldName:c});else if(f)this.credentialSourceType="url",this.subjectTokenSupplier=new E_.UrlSubjectTokenSupplier({url:f,formatType:u,subjectTokenFieldName:c,headers:h,additionalGaxiosOptions:t.RETRY_CONFIG});else if(p){this.credentialSourceType="certificate";let g=new ic.CertificateSubjectTokenSupplier({useDefaultCertificateConfig:p.use_default_certificate_config,certificateConfigLocation:p.certificate_config_location,trustChainPath:p.trust_chain_path});this.subjectTokenSupplier=g}else throw new Error('No valid Identity Pool "credential_source" provided, must be either file, url, or certificate.')}}async retrieveSubjectToken(){let e=await this.subjectTokenSupplier.getSubjectToken(this.supplierContext);if(this.subjectTokenSupplier instanceof ic.CertificateSubjectTokenSupplier){let n=await this.subjectTokenSupplier.createMtlsHttpsAgent();this.stsCredential=new T_.StsCredentials({tokenExchangeEndpoint:this.getTokenUrl(),clientAuthentication:this.clientAuth,transporter:new rc.Gaxios({agent:n})}),this.transporter=new rc.Gaxios({...this.transporter.defaults||{},agent:n})}return e}};Po.IdentityPoolClient=zr});var jr=W(No=>{"use strict";Object.defineProperty(No,"__esModule",{value:!0});No.AwsRequestSigner=void 0;var ko=xe(),ac=Dn(),sc="AWS4-HMAC-SHA256",A_="aws4_request",Zr=class{getCredentials;region;crypto;constructor(e,n){this.getCredentials=e,this.region=n,this.crypto=(0,ac.createCrypto)()}async getRequestOptions(e){if(!e.url)throw new RangeError('"url" is required in "amzOptions"');let n=typeof e.data=="object"?JSON.stringify(e.data):e.data,o=e.url,i=e.method||"GET",r=e.body||n,a=e.headers,u=await this.getCredentials(),c=new URL(o);if(typeof r!="string"&&r!==void 0)throw new TypeError(`'requestPayload' is expected to be a string if provided. Got: ${r}`);let d=await I_({crypto:this.crypto,host:c.host,canonicalUri:c.pathname,canonicalQuerystring:c.search.slice(1),method:i,region:this.region,securityCredentials:u,requestPayload:r,additionalAmzHeaders:a}),f=ko.Gaxios.mergeHeaders(d.amzDate?{"x-amz-date":d.amzDate}:{},{authorization:d.authorizationHeader,host:c.host},a||{});u.token&&ko.Gaxios.mergeHeaders(f,{"x-amz-security-token":u.token});let p={url:o,method:i,headers:f};return r!==void 0&&(p.body=r),p}};No.AwsRequestSigner=Zr;async function bn(t,e,n){return await t.signWithHmacSha256(e,n)}async function C_(t,e,n,o,i){let r=await bn(t,`AWS4${e}`,n),a=await bn(t,r,o),u=await bn(t,a,i);return await bn(t,u,"aws4_request")}async function I_(t){let e=ko.Gaxios.mergeHeaders(t.additionalAmzHeaders),n=t.requestPayload||"",o=t.host.split(".")[0],i=new Date,r=i.toISOString().replace(/[-:]/g,"").replace(/\.[0-9]+/,""),a=i.toISOString().replace(/[-]/g,"").replace(/T.*/,"");t.securityCredentials.token&&e.set("x-amz-security-token",t.securityCredentials.token);let u=ko.Gaxios.mergeHeaders({host:t.host},e.has("date")?{}:{"x-amz-date":r},e),c="",d=[...u.keys()].sort();d.forEach(E=>{c+=`${E}:${u.get(E)}
17
+ `});let f=d.join(";"),p=await t.crypto.sha256DigestHex(n),h=`${t.method.toUpperCase()}
18
+ ${t.canonicalUri}
19
+ ${t.canonicalQuerystring}
20
+ ${c}
21
+ ${f}
22
+ ${p}`,g=`${a}/${t.region}/${o}/${A_}`,_=`${sc}
23
+ ${r}
24
+ ${g}
25
+ `+await t.crypto.sha256DigestHex(h),m=await C_(t.crypto,t.securityCredentials.secretAccessKey,a,t.region,o),v=await bn(t.crypto,m,_),y=`${sc} Credential=${t.securityCredentials.accessKeyId}/${g}, SignedHeaders=${f}, Signature=${(0,ac.fromArrayBufferToHex)(v)}`;return{amzDate:e.has("date")?void 0:r,authorizationHeader:y,canonicalQuerystring:t.canonicalQuerystring}}});var lc=W(Do=>{"use strict";Object.defineProperty(Do,"__esModule",{value:!0});Do.DefaultAwsSecurityCredentialsSupplier=void 0;var xo=$e(),es=class{regionUrl;securityCredentialsUrl;imdsV2SessionTokenUrl;additionalGaxiosOptions;constructor(e){this.regionUrl=e.regionUrl,this.securityCredentialsUrl=e.securityCredentialsUrl,this.imdsV2SessionTokenUrl=e.imdsV2SessionTokenUrl,this.additionalGaxiosOptions=e.additionalGaxiosOptions}async getAwsRegion(e){if(this.#o)return this.#o;let n=new Headers;if(!this.#o&&this.imdsV2SessionTokenUrl&&n.set("x-aws-ec2-metadata-token",await this.#e(e.transporter)),!this.regionUrl)throw new RangeError('Unable to determine AWS region due to missing "options.credential_source.region_url"');let o={...this.additionalGaxiosOptions,url:this.regionUrl,method:"GET",responseType:"text",headers:n};xo.AuthClient.setMethodName(o,"getAwsRegion");let i=await e.transporter.request(o);return i.data.substr(0,i.data.length-1)}async getAwsSecurityCredentials(e){if(this.#i)return this.#i;let n=new Headers;this.imdsV2SessionTokenUrl&&n.set("x-aws-ec2-metadata-token",await this.#e(e.transporter));let o=await this.#t(n,e.transporter),i=await this.#n(o,n,e.transporter);return{accessKeyId:i.AccessKeyId,secretAccessKey:i.SecretAccessKey,token:i.Token}}async#e(e){let n={...this.additionalGaxiosOptions,url:this.imdsV2SessionTokenUrl,method:"PUT",responseType:"text",headers:{"x-aws-ec2-metadata-token-ttl-seconds":"300"}};return xo.AuthClient.setMethodName(n,"#getImdsV2SessionToken"),(await e.request(n)).data}async#t(e,n){if(!this.securityCredentialsUrl)throw new Error('Unable to determine AWS role name due to missing "options.credential_source.url"');let o={...this.additionalGaxiosOptions,url:this.securityCredentialsUrl,method:"GET",responseType:"text",headers:e};return xo.AuthClient.setMethodName(o,"#getAwsRoleName"),(await n.request(o)).data}async#n(e,n,o){let i={...this.additionalGaxiosOptions,url:`${this.securityCredentialsUrl}/${e}`,headers:n,responseType:"json"};return xo.AuthClient.setMethodName(i,"#retrieveAwsSecurityCredentials"),(await o.request(i)).data}get#o(){return process.env.AWS_REGION||process.env.AWS_DEFAULT_REGION||null}get#i(){return process.env.AWS_ACCESS_KEY_ID&&process.env.AWS_SECRET_ACCESS_KEY?{accessKeyId:process.env.AWS_ACCESS_KEY_ID,secretAccessKey:process.env.AWS_SECRET_ACCESS_KEY,token:process.env.AWS_SESSION_TOKEN}:null}};Do.DefaultAwsSecurityCredentialsSupplier=es});var ns=W(Mo=>{"use strict";Object.defineProperty(Mo,"__esModule",{value:!0});Mo.AwsClient=void 0;var S_=jr(),w_=Mt(),R_=lc(),uc=at(),P_=xe(),ts=class t extends w_.BaseExternalAccountClient{environmentId;awsSecurityCredentialsSupplier;regionalCredVerificationUrl;awsRequestSigner;region;static#e="https://sts.{region}.amazonaws.com?Action=GetCallerIdentity&Version=2011-06-15";static AWS_EC2_METADATA_IPV4_ADDRESS="169.254.169.254";static AWS_EC2_METADATA_IPV6_ADDRESS="fd00:ec2::254";constructor(e){super(e);let n=(0,uc.originalOrCamelOptions)(e),o=n.get("credential_source"),i=n.get("aws_security_credentials_supplier");if(!o&&!i)throw new Error("A credential source or AWS security credentials supplier must be specified.");if(o&&i)throw new Error("Only one of credential source or AWS security credentials supplier can be specified.");if(i)this.awsSecurityCredentialsSupplier=i,this.regionalCredVerificationUrl=t.#e,this.credentialSourceType="programmatic";else{let r=(0,uc.originalOrCamelOptions)(o);this.environmentId=r.get("environment_id");let a=r.get("region_url"),u=r.get("url"),c=r.get("imdsv2_session_token_url");this.awsSecurityCredentialsSupplier=new R_.DefaultAwsSecurityCredentialsSupplier({regionUrl:a,securityCredentialsUrl:u,imdsV2SessionTokenUrl:c}),this.regionalCredVerificationUrl=r.get("regional_cred_verification_url"),this.credentialSourceType="aws",this.validateEnvironmentId()}this.awsRequestSigner=null,this.region=""}validateEnvironmentId(){let e=this.environmentId?.match(/^(aws)(\d+)$/);if(!e||!this.regionalCredVerificationUrl)throw new Error('No valid AWS "credential_source" provided');if(parseInt(e[2],10)!==1)throw new Error(`aws version "${e[2]}" is not supported in the current build.`)}async retrieveSubjectToken(){this.awsRequestSigner||(this.region=await this.awsSecurityCredentialsSupplier.getAwsRegion(this.supplierContext),this.awsRequestSigner=new S_.AwsRequestSigner(async()=>this.awsSecurityCredentialsSupplier.getAwsSecurityCredentials(this.supplierContext),this.region));let e=await this.awsRequestSigner.getRequestOptions({...t.RETRY_CONFIG,url:this.regionalCredVerificationUrl.replace("{region}",this.region),method:"POST"}),n=[];return P_.Gaxios.mergeHeaders({"x-goog-cloud-target-resource":this.audience},e.headers).forEach((i,r)=>n.push({key:r,value:i})),encodeURIComponent(JSON.stringify({url:e.url,method:e.method,headers:n}))}};Mo.AwsClient=ts});var as=W(Pe=>{"use strict";Object.defineProperty(Pe,"__esModule",{value:!0});Pe.InvalidSubjectTokenError=Pe.InvalidMessageFieldError=Pe.InvalidCodeFieldError=Pe.InvalidTokenTypeFieldError=Pe.InvalidExpirationTimeFieldError=Pe.InvalidSuccessFieldError=Pe.InvalidVersionFieldError=Pe.ExecutableResponseError=Pe.ExecutableResponse=void 0;var Uo="urn:ietf:params:oauth:token-type:saml2",os="urn:ietf:params:oauth:token-type:id_token",is="urn:ietf:params:oauth:token-type:jwt",rs=class{version;success;expirationTime;tokenType;errorCode;errorMessage;subjectToken;constructor(e){if(!e.version)throw new Go("Executable response must contain a 'version' field.");if(e.success===void 0)throw new bo("Executable response must contain a 'success' field.");if(this.version=e.version,this.success=e.success,this.success){if(this.expirationTime=e.expiration_time,this.tokenType=e.token_type,this.tokenType!==Uo&&this.tokenType!==os&&this.tokenType!==is)throw new Lo(`Executable response must contain a 'token_type' field when successful and it must be one of ${os}, ${is}, or ${Uo}.`);if(this.tokenType===Uo){if(!e.saml_response)throw new Ln(`Executable response must contain a 'saml_response' field when token_type=${Uo}.`);this.subjectToken=e.saml_response}else{if(!e.id_token)throw new Ln(`Executable response must contain a 'id_token' field when token_type=${os} or ${is}.`);this.subjectToken=e.id_token}}else{if(!e.code)throw new qo("Executable response must contain a 'code' field when unsuccessful.");if(!e.message)throw new Oo("Executable response must contain a 'message' field when unsuccessful.");this.errorCode=e.code,this.errorMessage=e.message}}isValid(){return!this.isExpired()&&this.success}isExpired(){return this.expirationTime!==void 0&&this.expirationTime<Math.round(Date.now()/1e3)}};Pe.ExecutableResponse=rs;var yt=class extends Error{constructor(e){super(e),Object.setPrototypeOf(this,new.target.prototype)}};Pe.ExecutableResponseError=yt;var Go=class extends yt{};Pe.InvalidVersionFieldError=Go;var bo=class extends yt{};Pe.InvalidSuccessFieldError=bo;var ss=class extends yt{};Pe.InvalidExpirationTimeFieldError=ss;var Lo=class extends yt{};Pe.InvalidTokenTypeFieldError=Lo;var qo=class extends yt{};Pe.InvalidCodeFieldError=qo;var Oo=class extends yt{};Pe.InvalidMessageFieldError=Oo;var Ln=class extends yt{};Pe.InvalidSubjectTokenError=Ln});var cs=W(fn=>{"use strict";Object.defineProperty(fn,"__esModule",{value:!0});fn.PluggableAuthHandler=fn.ExecutableError=void 0;var Zt=as(),k_=me("child_process"),ls=me("fs"),Fo=class extends Error{code;constructor(e,n){super(`The executable failed with exit code: ${n} and error message: ${e}.`),this.code=n,Object.setPrototypeOf(this,new.target.prototype)}};fn.ExecutableError=Fo;var us=class t{commandComponents;timeoutMillis;outputFile;constructor(e){if(!e.command)throw new Error("No command provided.");if(this.commandComponents=t.parseCommand(e.command),this.timeoutMillis=e.timeoutMillis,!this.timeoutMillis)throw new Error("No timeoutMillis provided.");this.outputFile=e.outputFile}retrieveResponseFromExecutable(e){return new Promise((n,o)=>{let i=k_.spawn(this.commandComponents[0],this.commandComponents.slice(1),{env:{...process.env,...Object.fromEntries(e)}}),r="";i.stdout.on("data",u=>{r+=u}),i.stderr.on("data",u=>{r+=u});let a=setTimeout(()=>(i.removeAllListeners(),i.kill(),o(new Error("The executable failed to finish within the timeout specified."))),this.timeoutMillis);i.on("close",u=>{if(clearTimeout(a),u===0)try{let c=JSON.parse(r),d=new Zt.ExecutableResponse(c);return n(d)}catch(c){return c instanceof Zt.ExecutableResponseError?o(c):o(new Zt.ExecutableResponseError(`The executable returned an invalid response: ${r}`))}else return o(new Fo(r,u.toString()))})})}async retrieveCachedResponse(){if(!this.outputFile||this.outputFile.length===0)return;let e;try{e=await ls.promises.realpath(this.outputFile)}catch{return}if(!(await ls.promises.lstat(e)).isFile())return;let n=await ls.promises.readFile(e,{encoding:"utf8"});if(n!=="")try{let o=JSON.parse(n);return new Zt.ExecutableResponse(o).isValid()?new Zt.ExecutableResponse(o):void 0}catch(o){throw o instanceof Zt.ExecutableResponseError?o:new Zt.ExecutableResponseError(`The output file contained an invalid response: ${n}`)}}static parseCommand(e){let n=e.match(/(?:[^\s"]+|"[^"]*")+/g);if(!n)throw new Error(`Provided command: "${e}" could not be parsed.`);for(let o=0;o<n.length;o++)n[o][0]==='"'&&n[o].slice(-1)==='"'&&(n[o]=n[o].slice(1,-1));return n}};fn.PluggableAuthHandler=us});var fs=W(pn=>{"use strict";Object.defineProperty(pn,"__esModule",{value:!0});pn.PluggableAuthClient=pn.ExecutableError=void 0;var N_=Mt(),x_=as(),cc=cs(),D_=cs();Object.defineProperty(pn,"ExecutableError",{enumerable:!0,get:function(){return D_.ExecutableError}});var M_=30*1e3,dc=5*1e3,fc=120*1e3,U_="GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES",pc=1,ds=class extends N_.BaseExternalAccountClient{command;timeoutMillis;outputFile;handler;constructor(e){if(super(e),!e.credential_source.executable)throw new Error('No valid Pluggable Auth "credential_source" provided.');if(this.command=e.credential_source.executable.command,!this.command)throw new Error('No valid Pluggable Auth "credential_source" provided.');if(e.credential_source.executable.timeout_millis===void 0)this.timeoutMillis=M_;else if(this.timeoutMillis=e.credential_source.executable.timeout_millis,this.timeoutMillis<dc||this.timeoutMillis>fc)throw new Error(`Timeout must be between ${dc} and ${fc} milliseconds.`);this.outputFile=e.credential_source.executable.output_file,this.handler=new cc.PluggableAuthHandler({command:this.command,timeoutMillis:this.timeoutMillis,outputFile:this.outputFile}),this.credentialSourceType="executable"}async retrieveSubjectToken(){if(process.env[U_]!=="1")throw new Error("Pluggable Auth executables need to be explicitly allowed to run by setting the GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES environment Variable to 1.");let e;if(this.outputFile&&(e=await this.handler.retrieveCachedResponse()),!e){let n=new Map;n.set("GOOGLE_EXTERNAL_ACCOUNT_AUDIENCE",this.audience),n.set("GOOGLE_EXTERNAL_ACCOUNT_TOKEN_TYPE",this.subjectTokenType),n.set("GOOGLE_EXTERNAL_ACCOUNT_INTERACTIVE","0"),this.outputFile&&n.set("GOOGLE_EXTERNAL_ACCOUNT_OUTPUT_FILE",this.outputFile);let o=this.getServiceAccountEmail();o&&n.set("GOOGLE_EXTERNAL_ACCOUNT_IMPERSONATED_EMAIL",o),e=await this.handler.retrieveResponseFromExecutable(n)}if(e.version>pc)throw new Error(`Version of executable is not currently supported, maximum supported version is ${pc}.`);if(!e.success)throw new cc.ExecutableError(e.errorMessage,e.errorCode);if(this.outputFile&&!e.expirationTime)throw new x_.InvalidExpirationTimeFieldError("The executable response must contain the `expiration_time` field for successful responses when an output_file has been specified in the configuration.");if(e.isExpired())throw new Error("Executable response is expired.");return e.subjectToken}};pn.PluggableAuthClient=ds});var hs=W(Ho=>{"use strict";Object.defineProperty(Ho,"__esModule",{value:!0});Ho.ExternalAccountClient=void 0;var G_=Mt(),b_=Qr(),L_=ns(),q_=fs(),ps=class{constructor(){throw new Error("ExternalAccountClients should be initialized via: ExternalAccountClient.fromJSON(), directly via explicit constructors, eg. new AwsClient(options), new IdentityPoolClient(options), newPluggableAuthClientOptions, or via new GoogleAuth(options).getClient()")}static fromJSON(e){return e&&e.type===G_.EXTERNAL_ACCOUNT_TYPE?e.credential_source?.environment_id?new L_.AwsClient(e):e.credential_source?.executable?new q_.PluggableAuthClient(e):new b_.IdentityPoolClient(e):null}};Ho.ExternalAccountClient=ps});var _s=W(hn=>{"use strict";Object.defineProperty(hn,"__esModule",{value:!0});hn.ExternalAccountAuthorizedUserClient=hn.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE=void 0;var mc=$e(),hc=Or(),gc=xe(),O_=me("stream"),F_=Mt();hn.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE="external_account_authorized_user";var H_="https://sts.{universeDomain}/v1/oauthtoken",ms=class t extends hc.OAuthClientAuthHandler{#e;constructor(e){super(e),this.#e=e.tokenRefreshEndpoint}async refreshToken(e,n){let o={...t.RETRY_CONFIG,url:this.#e,method:"POST",headers:n,data:new URLSearchParams({grant_type:"refresh_token",refresh_token:e}),responseType:"json"};mc.AuthClient.setMethodName(o,"refreshToken"),this.applyClientAuthenticationOptions(o);try{let i=await this.transporter.request(o),r=i.data;return r.res=i,r}catch(i){throw i instanceof gc.GaxiosError&&i.response?(0,hc.getErrorFromOAuthErrorResponse)(i.response.data,i):i}}},gs=class extends mc.AuthClient{cachedAccessToken;externalAccountAuthorizedUserHandler;refreshToken;constructor(e){super(e),e.universe_domain&&(this.universeDomain=e.universe_domain),this.refreshToken=e.refresh_token;let n={confidentialClientType:"basic",clientId:e.client_id,clientSecret:e.client_secret};this.externalAccountAuthorizedUserHandler=new ms({tokenRefreshEndpoint:e.token_url??H_.replace("{universeDomain}",this.universeDomain),transporter:this.transporter,clientAuthentication:n}),this.cachedAccessToken=null,this.quotaProjectId=e.quota_project_id,typeof e?.eagerRefreshThresholdMillis!="number"?this.eagerRefreshThresholdMillis=F_.EXPIRATION_TIME_OFFSET:this.eagerRefreshThresholdMillis=e.eagerRefreshThresholdMillis,this.forceRefreshOnFailure=!!e?.forceRefreshOnFailure}async getAccessToken(){return(!this.cachedAccessToken||this.isExpired(this.cachedAccessToken))&&await this.refreshAccessTokenAsync(),{token:this.cachedAccessToken.access_token,res:this.cachedAccessToken.res}}async getRequestHeaders(){let e=await this.getAccessToken(),n=new Headers({authorization:`Bearer ${e.token}`});return this.addSharedMetadataHeaders(n)}request(e,n){if(n)this.requestAsync(e).then(o=>n(null,o),o=>n(o,o.response));else return this.requestAsync(e)}async requestAsync(e,n=!1){let o;try{let i=await this.getRequestHeaders();e.headers=gc.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,i),o=await this.transporter.request(e)}catch(i){let r=i.response;if(r){let a=r.status,u=r.config.data instanceof O_.Readable;if(!n&&(a===401||a===403)&&!u&&this.forceRefreshOnFailure)return await this.refreshAccessTokenAsync(),await this.requestAsync(e,!0)}throw i}return o}async refreshAccessTokenAsync(){let e=await this.externalAccountAuthorizedUserHandler.refreshToken(this.refreshToken);return this.cachedAccessToken={access_token:e.access_token,expiry_date:new Date().getTime()+e.expires_in*1e3,res:e.res},e.refresh_token!==void 0&&(this.refreshToken=e.refresh_token),this.cachedAccessToken}isExpired(e){let n=new Date().getTime();return e.expiry_date?n>=e.expiry_date-this.eagerRefreshThresholdMillis:!1}};hn.ExternalAccountAuthorizedUserClient=gs});var vs=W(Ut=>{"use strict";Object.defineProperty(Ut,"__esModule",{value:!0});Ut.GdchClient=Ut.GDCH_SERVICE_ACCOUNT_TYPE=void 0;var V_=me("crypto"),B_=me("fs"),$_=me("https"),X_=xt(),J_=3600;Ut.GDCH_SERVICE_ACCOUNT_TYPE="gdch_service_account";var ys=class t extends X_.OAuth2Client{projectId;privateKeyId;privateKey;serviceIdentityName;tokenServerUri;caCertPath;apiAudience;lifetime;gdchOptions;caAgentPromise;cachedCaCertPath;lastCaCertReadTime=0;CA_CERT_TTL_MS=300*1e3;constructor(e={}){super(e),this.gdchOptions=e,this.projectId=e.projectId||void 0,this.privateKeyId=e.privateKeyId,this.privateKey=e.privateKey,this.serviceIdentityName=e.serviceIdentityName,this.tokenServerUri=e.tokenServerUri,this.caCertPath=e.caCertPath,this.apiAudience=e.apiAudience,this.lifetime=e.lifetime||J_,this.credentials={refresh_token:"gdch-placeholder",expiry_date:1}}createWithGdchAudience(e){if(!e)throw new Error("Audience cannot be null or empty for GDCH service account credentials.");return new t({...this.gdchOptions,projectId:this.projectId,privateKeyId:this.privateKeyId,privateKey:this.privateKey,serviceIdentityName:this.serviceIdentityName,tokenServerUri:this.tokenServerUri,caCertPath:this.caCertPath,lifetime:this.lifetime,apiAudience:e})}fromJSON(e){if(!e)throw new Error("Must pass in a JSON object containing the GDCH credentials settings.");if(e.type!==Ut.GDCH_SERVICE_ACCOUNT_TYPE)throw new Error(`The incoming JSON object does not have the "${Ut.GDCH_SERVICE_ACCOUNT_TYPE}" type`);if(e.format_version!=="1")throw new Error("Only format version 1 is supported.");if(!e.project)throw new Error("The incoming JSON object does not contain a project field");if(!e.private_key_id)throw new Error("The incoming JSON object does not contain a private_key_id field");if(!e.private_key)throw new Error("The incoming JSON object does not contain a private_key field");if(!e.name)throw new Error("The incoming JSON object does not contain a name field");if(!e.token_uri)throw new Error("The incoming JSON object does not contain a token_uri field");this.projectId=e.project,this.privateKeyId=e.private_key_id,this.privateKey=e.private_key,this.serviceIdentityName=e.name,this.tokenServerUri=e.token_uri,this.caCertPath=e.ca_cert_path,this.gdchOptions={...this.gdchOptions,projectId:e.project,privateKeyId:e.private_key_id,privateKey:e.private_key,serviceIdentityName:e.name,tokenServerUri:e.token_uri,caCertPath:e.ca_cert_path}}async refreshTokenNoCache(){if(!this.apiAudience)throw new Error("Audience cannot be null or empty for GDCH service account credentials. Specify the audience by calling createWithGdchAudience.");if(!this.privateKey)throw new Error("Private key is not configured for GDCH credentials.");if(!this.privateKeyId)throw new Error("Private key ID is not configured for GDCH credentials.");if(!this.projectId)throw new Error("Project is not configured for GDCH credentials.");if(!this.serviceIdentityName)throw new Error("Service identity name is not configured for GDCH credentials.");if(!this.tokenServerUri)throw new Error("Token server URI is not configured for GDCH credentials.");let e=this.createAssertion(),n={audience:this.apiAudience,grant_type:"urn:ietf:params:oauth:token-type:token-exchange",requested_token_type:"urn:ietf:params:oauth:token-type:access_token",subject_token:e,subject_token_type:"urn:k8s:params:oauth:token-type:serviceaccount"},o={url:this.tokenServerUri,method:"POST",headers:{"Content-Type":"application/json"},data:n,responseType:"json",timeout:1e4,retry:!0,retryConfig:{httpMethodsToRetry:["POST"],statusCodesToRetry:[[500,599]],noResponseRetries:3}};this.caCertPath&&(o.agent=await this.getCaAgent());try{let i=await this.transporter.request(o),r=i.data;if(!r.access_token)throw new Error("Token response did not contain an access_token.");if(!r.expires_in)throw new Error("Token response did not contain an expires_in field.");let a={access_token:r.access_token,token_type:"STS-Bearer",expiry_date:Date.now()+r.expires_in*1e3};return this.emit("tokens",a),{res:i,tokens:a}}catch(i){if(i&&i.config&&i.config.data)try{if(typeof i.config.data=="string"){let r=JSON.parse(i.config.data);r.subject_token&&(r.subject_token="***REDACTED***",i.config.data=JSON.stringify(r))}else typeof i.config.data=="object"&&i.config.data.subject_token&&(i.config.data.subject_token="***REDACTED***")}catch{}throw i instanceof Error&&(i.message=`Error getting access token for GDCH service account: ${i.message}, iss: ${this.serviceIdentityName}`),i}}createAssertion(){let e={alg:"ES256",typ:"JWT",kid:this.privateKeyId},n=`system:serviceaccount:${this.projectId}:${this.serviceIdentityName}`,o=Math.floor(Date.now()/1e3),i={iss:n,sub:n,iat:o,exp:o+this.lifetime,aud:this.tokenServerUri},r=this.base64UrlEncode(JSON.stringify(e)),a=this.base64UrlEncode(JSON.stringify(i)),u=`${r}.${a}`,c=V_.sign("sha256",Buffer.from(u),{key:this.privateKey,dsaEncoding:"ieee-p1363"}),d=this.base64UrlEncode(c);return`${u}.${d}`}async requestAsync(e,n=!1){if(this.caCertPath&&!e.agent){let o=(e.url||"").toString();!o.includes("googleapis.com")&&!o.includes("google.com")&&(e.agent=await this.getCaAgent())}return super.requestAsync(e,n)}getCaAgent(){if(!this.caCertPath){this.caAgentPromise=void 0,this.cachedCaCertPath=void 0,this.lastCaCertReadTime=0;return}let e=Date.now(),n=e-this.lastCaCertReadTime>this.CA_CERT_TTL_MS;if(this.caAgentPromise&&this.caCertPath===this.cachedCaCertPath&&!n)return this.caAgentPromise;this.cachedCaCertPath=this.caCertPath,this.lastCaCertReadTime=e;let o=this.caCertPath;return this.caAgentPromise=(async()=>{try{let i=await B_.promises.readFile(o);return new $_.Agent({ca:i})}catch(i){throw this.cachedCaCertPath===o&&(this.caAgentPromise=void 0,this.cachedCaCertPath=void 0,this.lastCaCertReadTime=0),i instanceof Error&&(i.message=`Error reading certificate file from CA cert path, value '${o}': ${i.message}`),i}})(),this.caAgentPromise}toJSON(){return{...this,privateKey:this.privateKey?"***REDACTED***":void 0,_clientSecret:this._clientSecret?"***REDACTED***":void 0,apiKey:this.apiKey?"***REDACTED***":void 0,gdchOptions:this.gdchOptions?{...this.gdchOptions,privateKey:this.gdchOptions.privateKey?"***REDACTED***":void 0,clientSecret:this.gdchOptions.clientSecret?"***REDACTED***":void 0,client_secret:this.gdchOptions.client_secret?"***REDACTED***":void 0,apiKey:this.gdchOptions.apiKey?"***REDACTED***":void 0,credentials:this.gdchOptions.credentials?{...this.gdchOptions.credentials,access_token:this.gdchOptions.credentials.access_token?"***REDACTED***":void 0,refresh_token:this.gdchOptions.credentials.refresh_token?"***REDACTED***":void 0}:void 0}:void 0,credentials:{...this.credentials,access_token:this.credentials?.access_token?"***REDACTED***":void 0,refresh_token:this.credentials?.refresh_token?"***REDACTED***":void 0}}}[Symbol.for("nodejs.util.inspect.custom")](){return this.toJSON()}base64UrlEncode(e){return(typeof e=="string"?Buffer.from(e):e).toString("base64url")}};Ut.GdchClient=ys});var Ec=W(ut=>{"use strict";Object.defineProperty(ut,"__esModule",{value:!0});ut.GoogleAuth=ut.GoogleAuthExceptionMessages=void 0;var K_=me("child_process"),qn=me("fs"),Y_=xe(),On=xn(),W_=me("os"),Vo=me("path"),z_=Dn(),Q_=hr(),Z_=gr(),j_=_r(),mn=Mr(),_c=Gr(),gn=Lr(),ey=hs(),Fn=Mt(),Es=$e(),yc=_s(),Ts=vs(),vc=at();ut.GoogleAuthExceptionMessages={API_KEY_WITH_CREDENTIALS:"API Keys and Credentials are mutually exclusive authentication methods and cannot be used together.",NO_PROJECT_ID_FOUND:`Unable to detect a Project Id in the current environment.
26
+ To learn more about authentication and Google APIs, visit:
27
+ https://cloud.google.com/docs/authentication/getting-started`,NO_CREDENTIALS_FOUND:`Unable to find credentials in current environment.
28
+ To learn more about authentication and Google APIs, visit:
29
+ https://cloud.google.com/docs/authentication/getting-started`,NO_ADC_FOUND:"Could not load the default credentials. Browse to https://cloud.google.com/docs/authentication/getting-started for more information.",NO_UNIVERSE_DOMAIN_FOUND:`Unable to detect a Universe Domain in the current environment.
30
+ To learn more about Universe Domain retrieval, visit:
31
+ https://cloud.google.com/compute/docs/metadata/predefined-metadata-keys`};var As=class{checkIsGCE=void 0;useJWTAccessWithScope;defaultServicePath;get isGCE(){return this.checkIsGCE}_findProjectIdPromise;_cachedProjectId;jsonContent=null;apiKey;cachedCredential=null;#e=null;defaultScopes;keyFilename;scopes;clientOptions={};constructor(e={}){if(this._cachedProjectId=e.projectId||null,this.cachedCredential=e.authClient||null,this.keyFilename=e.keyFilename||e.keyFile,this.scopes=e.scopes,this.clientOptions=e.clientOptions||{},this.jsonContent=e.credentials||null,this.apiKey=e.apiKey||this.clientOptions.apiKey||null,this.apiKey&&(this.jsonContent||this.clientOptions.credentials))throw new RangeError(ut.GoogleAuthExceptionMessages.API_KEY_WITH_CREDENTIALS);e.universeDomain&&(this.clientOptions.universeDomain=e.universeDomain)}setGapicJWTValues(e){e.defaultServicePath=this.defaultServicePath,e.useJWTAccessWithScope=this.useJWTAccessWithScope,e.defaultScopes=this.defaultScopes}getProjectId(e){if(e)this.getProjectIdAsync().then(n=>e(null,n),e);else return this.getProjectIdAsync()}async getProjectIdOptional(){try{return await this.getProjectId()}catch(e){if(e instanceof Error&&e.message===ut.GoogleAuthExceptionMessages.NO_PROJECT_ID_FOUND)return null;throw e}}async findAndCacheProjectId(){let e=null;if(e||=await this.getProductionProjectId(),e||=await this.getFileProjectId(),e||=await this.getDefaultServiceProjectId(),e||=await this.getGCEProjectId(),e||=await this.getExternalAccountClientProjectId(),e)return this._cachedProjectId=e,e;throw new Error(ut.GoogleAuthExceptionMessages.NO_PROJECT_ID_FOUND)}async getProjectIdAsync(){return this._cachedProjectId?this._cachedProjectId:(this._findProjectIdPromise||(this._findProjectIdPromise=this.findAndCacheProjectId()),this._findProjectIdPromise)}async getUniverseDomainFromMetadataServer(){let e;try{e=await On.universe("universe-domain"),e||=Es.DEFAULT_UNIVERSE}catch(n){if(n&&n?.response?.status===404)e=Es.DEFAULT_UNIVERSE;else throw n}return e}async getUniverseDomain(){let e=(0,vc.originalOrCamelOptions)(this.clientOptions).get("universe_domain");try{e??=(await this.getClient()).universeDomain}catch{e??=Es.DEFAULT_UNIVERSE}return e}getAnyScopes(){return this.scopes||this.defaultScopes}getApplicationDefault(e={},n){let o;if(typeof e=="function"?n=e:o=e,n)this.getApplicationDefaultAsync(o).then(i=>n(null,i.credential,i.projectId),n);else return this.getApplicationDefaultAsync(o)}async getApplicationDefaultAsync(e={}){if(this.cachedCredential)return await this.#t(this.cachedCredential,null);let n;if(n=await this._tryGetApplicationCredentialsFromEnvironmentVariable(e),n)return n instanceof mn.JWT?n.scopes=this.scopes:n instanceof Fn.BaseExternalAccountClient&&(n.scopes=this.getAnyScopes()),await this.#t(n);if(n=await this._tryGetApplicationCredentialsFromWellKnownFile(e),n)return n instanceof mn.JWT?n.scopes=this.scopes:n instanceof Fn.BaseExternalAccountClient&&(n.scopes=this.getAnyScopes()),await this.#t(n);if(await this._checkIsGCE())return e.scopes=this.getAnyScopes(),await this.#t(new Q_.Compute(e));throw new Error(ut.GoogleAuthExceptionMessages.NO_ADC_FOUND)}async#t(e,n=process.env.GOOGLE_CLOUD_QUOTA_PROJECT||null){let o=await this.getProjectIdOptional();return n&&(e.quotaProjectId=n),this.cachedCredential=e,{credential:e,projectId:o}}async _checkIsGCE(){return this.checkIsGCE===void 0&&(this.checkIsGCE=On.getGCPResidency()||await On.isAvailable()),this.checkIsGCE}async _tryGetApplicationCredentialsFromEnvironmentVariable(e){let n=process.env.GOOGLE_APPLICATION_CREDENTIALS||process.env.google_application_credentials;if(!n||n.length===0)return null;try{return await this._getApplicationCredentialsFromFilePath(n,e)}catch(o){throw o instanceof Error&&(o.message=`Unable to read the credential file specified by the GOOGLE_APPLICATION_CREDENTIALS environment variable: ${o.message}`),o}}async _tryGetApplicationCredentialsFromWellKnownFile(e){let n=process.env.CLOUDSDK_CONFIG;if(!n)if(this._isWindows())process.env.APPDATA&&(n=Vo.join(process.env.APPDATA,"gcloud"));else{let r=process.env.HOME;r&&(n=Vo.join(r,".config","gcloud"))}if(!n)return null;let o=Vo.join(n,"application_default_credentials.json");return qn.existsSync(o)?await this._getApplicationCredentialsFromFilePath(o,e):null}async _getApplicationCredentialsFromFilePath(e,n={}){if(!e||e.length===0)throw new Error("The file path is invalid.");try{if(e=qn.realpathSync(e),!qn.lstatSync(e).isFile())throw new Error}catch(i){throw i instanceof Error&&(i.message=`The file at ${e} does not exist, or it is not a file. ${i.message}`),i}let o=qn.createReadStream(e);return this.fromStream(o,n)}fromImpersonatedJSON(e){if(!e)throw new Error("Must pass in a JSON object containing an impersonated refresh token");if(e.type!==gn.IMPERSONATED_ACCOUNT_TYPE)throw new Error(`The incoming JSON object does not have the "${gn.IMPERSONATED_ACCOUNT_TYPE}" type`);if(!e.source_credentials)throw new Error("The incoming JSON object does not contain a source_credentials field");if(!e.service_account_impersonation_url)throw new Error("The incoming JSON object does not contain a service_account_impersonation_url field");let n=this.fromJSON(e.source_credentials);if(e.service_account_impersonation_url?.length>256)throw new RangeError(`Target principal is too long: ${e.service_account_impersonation_url}`);let o=/(?<target>[^/]+):(generateAccessToken|generateIdToken)$/.exec(e.service_account_impersonation_url)?.groups?.target;if(!o)throw new RangeError(`Cannot extract target principal from ${e.service_account_impersonation_url}`);let i=(this.scopes||e.scopes||this.defaultScopes)??[];return new gn.Impersonated({...e,sourceClient:n,targetPrincipal:o,targetScopes:Array.isArray(i)?i:[i]})}fromJSON(e,n={}){let o,i=(0,vc.originalOrCamelOptions)(n).get("universe_domain");return e.type===_c.USER_REFRESH_ACCOUNT_TYPE?(o=new _c.UserRefreshClient(n),o.fromJSON(e)):e.type===gn.IMPERSONATED_ACCOUNT_TYPE?o=this.fromImpersonatedJSON(e):e.type===Fn.EXTERNAL_ACCOUNT_TYPE?(o=ey.ExternalAccountClient.fromJSON({...e,...n}),o.scopes=this.getAnyScopes()):e.type===yc.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE?o=new yc.ExternalAccountAuthorizedUserClient({...e,...n}):e.type===Ts.GDCH_SERVICE_ACCOUNT_TYPE?(o=new Ts.GdchClient(n),o.fromJSON(e)):(n.scopes=this.scopes,o=new mn.JWT(n),this.setGapicJWTValues(o),o.fromJSON(e)),i&&(o.universeDomain=i),o}_cacheClientFromJSON(e,n){let o=this.fromJSON(e,n);return this.jsonContent=e,this.cachedCredential=o,o}fromStream(e,n={},o){let i={};if(typeof n=="function"?o=n:i=n,o)this.fromStreamAsync(e,i).then(r=>o(null,r),o);else return this.fromStreamAsync(e,i)}fromStreamAsync(e,n){return new Promise((o,i)=>{if(!e)throw new Error("Must pass in a stream containing the Google auth settings.");let r=[];e.setEncoding("utf8").on("error",i).on("data",a=>r.push(a)).on("end",()=>{try{try{let a=JSON.parse(r.join("")),u=this._cacheClientFromJSON(a,n);return o(u)}catch(a){if(!this.keyFilename)throw a;let u=new mn.JWT({...this.clientOptions,keyFile:this.keyFilename});return this.cachedCredential=u,this.setGapicJWTValues(u),o(u)}}catch(a){return i(a)}})})}fromAPIKey(e,n={}){return new mn.JWT({...n,apiKey:e})}_isWindows(){let e=W_.platform();return!!(e&&e.length>=3&&e.substring(0,3).toLowerCase()==="win")}async getDefaultServiceProjectId(){return new Promise(e=>{(0,K_.exec)("gcloud config config-helper --format json",(n,o)=>{if(!n&&o)try{let i=JSON.parse(o).configuration.properties.core.project;e(i);return}catch{}e(null)})})}getProductionProjectId(){return process.env.GCLOUD_PROJECT||process.env.GOOGLE_CLOUD_PROJECT||process.env.gcloud_project||process.env.google_cloud_project}async getFileProjectId(){if(this.cachedCredential)return this.cachedCredential.projectId;if(this.keyFilename){let n=await this.getClient();if(n&&n.projectId)return n.projectId}let e=await this._tryGetApplicationCredentialsFromEnvironmentVariable();return e?e.projectId:null}async getExternalAccountClientProjectId(){return!this.jsonContent||this.jsonContent.type!==Fn.EXTERNAL_ACCOUNT_TYPE?null:await(await this.getClient()).getProjectId()}async getGCEProjectId(){try{return await On.project("project-id")}catch{return null}}getCredentials(e){if(e)this.getCredentialsAsync().then(n=>e(null,n),e);else return this.getCredentialsAsync()}async getCredentialsAsync(){let e=await this.getClient();if(e instanceof gn.Impersonated)return{client_email:e.getTargetPrincipal()};if(e instanceof Fn.BaseExternalAccountClient){let n=e.getServiceAccountEmail();if(n)return{client_email:n,universe_domain:e.universeDomain}}if(this.jsonContent)return{client_email:this.jsonContent.client_email,private_key:this.jsonContent.private_key,universe_domain:this.jsonContent.universe_domain};if(await this._checkIsGCE()){let[n,o]=await Promise.all([On.instance("service-accounts/default/email"),this.getUniverseDomain()]);return{client_email:n,universe_domain:o}}throw new Error(ut.GoogleAuthExceptionMessages.NO_CREDENTIALS_FOUND)}async getClient(){if(this.cachedCredential)return this.cachedCredential;this.#e=this.#e||this.#n();try{let e=await this.#e;if(e instanceof Ts.GdchClient&&!e.apiAudience){let n=this.clientOptions,o=n.apiEndpoint||n.servicePath;if(o){let r=`${o.startsWith("http")?"":"https://"}${o}`.replace(/\/+$/,""),a=e.createWithGdchAudience(r);return this.cachedCredential=a,a}}return e}finally{this.#e=null}}async#n(){if(this.jsonContent)return this._cacheClientFromJSON(this.jsonContent,this.clientOptions);if(this.keyFilename){let e=Vo.resolve(this.keyFilename),n=qn.createReadStream(e);return await this.fromStreamAsync(n,this.clientOptions)}else if(this.apiKey){let e=await this.fromAPIKey(this.apiKey,this.clientOptions);e.scopes=this.scopes;let{credential:n}=await this.#t(e);return n}else{let{credential:e}=await this.getApplicationDefaultAsync(this.clientOptions);return e}}async getIdTokenClient(e){let n=await this.getClient();if(!("fetchIdToken"in n))throw new Error("Cannot fetch ID token in this environment, use GCE or set the GOOGLE_APPLICATION_CREDENTIALS environment variable to a service account credentials JSON file.");return new Z_.IdTokenClient({targetAudience:e,idTokenProvider:n})}async getAccessToken(){return(await(await this.getClient()).getAccessToken()).token}async getRequestHeaders(e){return(await this.getClient()).getRequestHeaders(e)}async authorizeRequest(e={}){let n=e.url,i=await(await this.getClient()).getRequestHeaders(n);return e.headers=Y_.Gaxios.mergeHeaders(e.headers,i),e}async fetch(...e){return(await this.getClient()).fetch(...e)}async request(e){return(await this.getClient()).request(e)}getEnv(){return(0,j_.getEnv)()}async sign(e,n){let o=await this.getClient(),i=await this.getUniverseDomain();if(n=n||`https://iamcredentials.${i}/v1/projects/-/serviceAccounts/`,o instanceof gn.Impersonated)return(await o.sign(e)).signedBlob;let r=(0,z_.createCrypto)();if(o instanceof mn.JWT&&o.key)return await r.sign(o.key,e);let a=await this.getCredentials();if(!a.client_email)throw new Error("Cannot sign data without `client_email`.");return this.signBlob(r,a.client_email,e,n)}async signBlob(e,n,o,i){let r=new URL(i+`${n}:signBlob`);return(await this.request({method:"POST",url:r.href,data:{payload:e.encodeBase64StringUtf8(o)},retry:!0,retryConfig:{httpMethodsToRetry:["POST"]}})).data.signedBlob}};ut.GoogleAuth=As});var Tc=W(Bo=>{"use strict";Object.defineProperty(Bo,"__esModule",{value:!0});Bo.IAMAuth=void 0;var Cs=class{selector;token;constructor(e,n){this.selector=e,this.token=n,this.selector=e,this.token=n}getRequestHeaders(){return{"x-goog-iam-authority-selector":this.selector,"x-goog-iam-authorization-token":this.token}}};Bo.IAMAuth=Cs});var Ac=W(vt=>{"use strict";Object.defineProperty(vt,"__esModule",{value:!0});vt.DownscopedClient=vt.EXPIRATION_TIME_OFFSET=vt.MAX_ACCESS_BOUNDARY_RULES_COUNT=void 0;var ty=xe(),ny=me("stream"),Is=$e(),oy=Ao(),iy="urn:ietf:params:oauth:grant-type:token-exchange",ry="urn:ietf:params:oauth:token-type:access_token",sy="urn:ietf:params:oauth:token-type:access_token";vt.MAX_ACCESS_BOUNDARY_RULES_COUNT=10;vt.EXPIRATION_TIME_OFFSET=300*1e3;var Ss=class extends Is.AuthClient{authClient;credentialAccessBoundary;cachedDownscopedAccessToken;stsCredential;constructor(e,n={accessBoundary:{accessBoundaryRules:[]}}){if(super(e instanceof Is.AuthClient?{}:e),e instanceof Is.AuthClient?(this.authClient=e,this.credentialAccessBoundary=n):(this.authClient=e.authClient,this.credentialAccessBoundary=e.credentialAccessBoundary),this.credentialAccessBoundary.accessBoundary.accessBoundaryRules.length===0)throw new Error("At least one access boundary rule needs to be defined.");if(this.credentialAccessBoundary.accessBoundary.accessBoundaryRules.length>vt.MAX_ACCESS_BOUNDARY_RULES_COUNT)throw new Error(`The provided access boundary has more than ${vt.MAX_ACCESS_BOUNDARY_RULES_COUNT} access boundary rules.`);for(let o of this.credentialAccessBoundary.accessBoundary.accessBoundaryRules)if(o.availablePermissions.length===0)throw new Error("At least one permission should be defined in access boundary rules.");this.stsCredential=new oy.StsCredentials({tokenExchangeEndpoint:`https://sts.${this.universeDomain}/v1/token`}),this.cachedDownscopedAccessToken=null}setCredentials(e){if(!e.expiry_date)throw new Error("The access token expiry_date field is missing in the provided credentials.");super.setCredentials(e),this.cachedDownscopedAccessToken=e}async getAccessToken(){return(!this.cachedDownscopedAccessToken||this.isExpired(this.cachedDownscopedAccessToken))&&await this.refreshAccessTokenAsync(),{token:this.cachedDownscopedAccessToken.access_token,expirationTime:this.cachedDownscopedAccessToken.expiry_date,res:this.cachedDownscopedAccessToken.res}}async getRequestHeaders(){let e=await this.getAccessToken(),n=new Headers({authorization:`Bearer ${e.token}`});return this.addSharedMetadataHeaders(n)}request(e,n){if(n)this.requestAsync(e).then(o=>n(null,o),o=>n(o,o.response));else return this.requestAsync(e)}async requestAsync(e,n=!1){let o;try{let i=await this.getRequestHeaders();e.headers=ty.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,i),o=await this.transporter.request(e)}catch(i){let r=i.response;if(r){let a=r.status,u=r.config.data instanceof ny.Readable;if(!n&&(a===401||a===403)&&!u&&this.forceRefreshOnFailure)return await this.refreshAccessTokenAsync(),await this.requestAsync(e,!0)}throw i}return o}async refreshAccessTokenAsync(){let e=(await this.authClient.getAccessToken()).token,n={grantType:iy,requestedTokenType:ry,subjectToken:e,subjectTokenType:sy},o=await this.stsCredential.exchangeToken(n,void 0,this.credentialAccessBoundary),i=this.authClient.credentials?.expiry_date||null,r=o.expires_in?new Date().getTime()+o.expires_in*1e3:i;return this.cachedDownscopedAccessToken={access_token:o.access_token,expiry_date:r,res:o.res},this.credentials={},Object.assign(this.credentials,this.cachedDownscopedAccessToken),delete this.credentials.res,this.emit("tokens",{refresh_token:null,expiry_date:this.cachedDownscopedAccessToken.expiry_date,access_token:this.cachedDownscopedAccessToken.access_token,token_type:"Bearer",id_token:null}),this.cachedDownscopedAccessToken}isExpired(e){let n=new Date().getTime();return e.expiry_date?n>=e.expiry_date-this.eagerRefreshThresholdMillis:!1}};vt.DownscopedClient=Ss});var Cc=W($o=>{"use strict";Object.defineProperty($o,"__esModule",{value:!0});$o.PassThroughClient=void 0;var ay=$e(),ws=class extends ay.AuthClient{async request(e){return this.transporter.request(e)}async getAccessToken(){return{}}async getRequestHeaders(){return new Headers}};$o.PassThroughClient=ws});var kc=W(J=>{"use strict";var ly=J&&J.__createBinding||(Object.create?(function(t,e,n,o){o===void 0&&(o=n);var i=Object.getOwnPropertyDescriptor(e,n);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,o,i)}):(function(t,e,n,o){o===void 0&&(o=n),t[o]=e[n]})),uy=J&&J.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&ly(e,t,n)};Object.defineProperty(J,"__esModule",{value:!0});J.GoogleAuth=J.auth=J.GDCH_SERVICE_ACCOUNT_TYPE=J.GdchClient=J.PassThroughClient=J.ExternalAccountAuthorizedUserClient=J.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE=J.ExecutableError=J.PluggableAuthClient=J.DownscopedClient=J.BaseExternalAccountClient=J.ExternalAccountClient=J.IdentityPoolClient=J.AwsRequestSigner=J.AwsClient=J.UserRefreshClient=J.LoginTicket=J.ClientAuthentication=J.OAuth2Client=J.CodeChallengeMethod=J.Impersonated=J.JWT=J.JWTAccess=J.IdTokenClient=J.IAMAuth=J.GCPEnv=J.Compute=J.DEFAULT_UNIVERSE=J.AuthClient=J.gaxios=J.gcpMetadata=void 0;var Ic=Ec();Object.defineProperty(J,"GoogleAuth",{enumerable:!0,get:function(){return Ic.GoogleAuth}});J.gcpMetadata=xn();J.gaxios=xe();var Sc=$e();Object.defineProperty(J,"AuthClient",{enumerable:!0,get:function(){return Sc.AuthClient}});Object.defineProperty(J,"DEFAULT_UNIVERSE",{enumerable:!0,get:function(){return Sc.DEFAULT_UNIVERSE}});var cy=hr();Object.defineProperty(J,"Compute",{enumerable:!0,get:function(){return cy.Compute}});var dy=_r();Object.defineProperty(J,"GCPEnv",{enumerable:!0,get:function(){return dy.GCPEnv}});var fy=Tc();Object.defineProperty(J,"IAMAuth",{enumerable:!0,get:function(){return fy.IAMAuth}});var py=gr();Object.defineProperty(J,"IdTokenClient",{enumerable:!0,get:function(){return py.IdTokenClient}});var hy=xr();Object.defineProperty(J,"JWTAccess",{enumerable:!0,get:function(){return hy.JWTAccess}});var my=Mr();Object.defineProperty(J,"JWT",{enumerable:!0,get:function(){return my.JWT}});var gy=Lr();Object.defineProperty(J,"Impersonated",{enumerable:!0,get:function(){return gy.Impersonated}});var Rs=xt();Object.defineProperty(J,"CodeChallengeMethod",{enumerable:!0,get:function(){return Rs.CodeChallengeMethod}});Object.defineProperty(J,"OAuth2Client",{enumerable:!0,get:function(){return Rs.OAuth2Client}});Object.defineProperty(J,"ClientAuthentication",{enumerable:!0,get:function(){return Rs.ClientAuthentication}});var _y=cr();Object.defineProperty(J,"LoginTicket",{enumerable:!0,get:function(){return _y.LoginTicket}});var yy=Gr();Object.defineProperty(J,"UserRefreshClient",{enumerable:!0,get:function(){return yy.UserRefreshClient}});var vy=ns();Object.defineProperty(J,"AwsClient",{enumerable:!0,get:function(){return vy.AwsClient}});var Ey=jr();Object.defineProperty(J,"AwsRequestSigner",{enumerable:!0,get:function(){return Ey.AwsRequestSigner}});var Ty=Qr();Object.defineProperty(J,"IdentityPoolClient",{enumerable:!0,get:function(){return Ty.IdentityPoolClient}});var Ay=hs();Object.defineProperty(J,"ExternalAccountClient",{enumerable:!0,get:function(){return Ay.ExternalAccountClient}});var Cy=Mt();Object.defineProperty(J,"BaseExternalAccountClient",{enumerable:!0,get:function(){return Cy.BaseExternalAccountClient}});var Iy=Ac();Object.defineProperty(J,"DownscopedClient",{enumerable:!0,get:function(){return Iy.DownscopedClient}});var wc=fs();Object.defineProperty(J,"PluggableAuthClient",{enumerable:!0,get:function(){return wc.PluggableAuthClient}});Object.defineProperty(J,"ExecutableError",{enumerable:!0,get:function(){return wc.ExecutableError}});var Rc=_s();Object.defineProperty(J,"EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE",{enumerable:!0,get:function(){return Rc.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE}});Object.defineProperty(J,"ExternalAccountAuthorizedUserClient",{enumerable:!0,get:function(){return Rc.ExternalAccountAuthorizedUserClient}});var Sy=Cc();Object.defineProperty(J,"PassThroughClient",{enumerable:!0,get:function(){return Sy.PassThroughClient}});var Pc=vs();Object.defineProperty(J,"GdchClient",{enumerable:!0,get:function(){return Pc.GdchClient}});Object.defineProperty(J,"GDCH_SERVICE_ACCOUNT_TYPE",{enumerable:!0,get:function(){return Pc.GDCH_SERVICE_ACCOUNT_TYPE}});uy(kr(),J);var wy=new Ic.GoogleAuth;J.auth=wy});var Lf=Sl(Fh(),1),qf=Sl(kc(),1);import{createWriteStream as Ry}from"fs";import*as Ci from"fs/promises";import{writeFile as Py}from"fs/promises";import{Readable as ky}from"node:stream";import{finished as Ny}from"node:stream/promises";import*as Of from"path";var xy,Dy;function My(){return{geminiUrl:xy,vertexUrl:Dy}}function Uy(t,e,n,o){var i,r;if(!t?.baseUrl){let a=My();return e?(i=a.vertexUrl)!==null&&i!==void 0?i:n:(r=a.geminiUrl)!==null&&r!==void 0?r:o}return t.baseUrl}var dt=class{};function X(t,e){let n=/\{([^}]+)\}/g;return t.replace(n,(o,i)=>{if(Object.prototype.hasOwnProperty.call(e,i)){let r=e[i];return r!=null?String(r):""}else throw new Error(`Key '${i}' not found in valueMap.`)})}function l(t,e,n){for(let r=0;r<e.length-1;r++){let a=e[r];if(a.endsWith("[]")){let 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])){let c=t[u];if(Array.isArray(n))for(let d=0;d<c.length;d++){let f=c[d];l(f,e.slice(r+1),n[d])}else for(let d of c)l(d,e.slice(r+1),n)}return}else if(a.endsWith("[0]")){let u=a.slice(0,-3);u in t||(t[u]=[{}]);let c=t[u];l(c[0],e.slice(r+1),n);return}(!t[a]||typeof t[a]!="object")&&(t[a]={}),t=t[a]}let o=e[e.length-1],i=t[o];if(i!==void 0){if(!n||typeof n=="object"&&Object.keys(n).length===0||n===i)return;if(typeof i=="object"&&typeof n=="object"&&i!==null&&n!==null)Object.assign(i,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 s(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;let i=e[o];if(i.endsWith("[]")){let r=i.slice(0,-2);if(r in t){let a=t[r];return Array.isArray(a)?a.map(u=>s(u,e.slice(o+1),n)):n}else return n}else t=t[i]}return t}catch(o){if(o instanceof TypeError)return n;throw o}}function Gy(t,e){for(let[n,o]of Object.entries(e)){let i=n.split("."),r=o.split("."),a=new Set,u=-1;for(let c=0;c<i.length;c++)if(i[c]==="*"){u=c;break}if(u!==-1&&r.length>u)for(let c=u;c<r.length;c++){let d=r[c];d!=="*"&&!d.endsWith("[]")&&!d.endsWith("[0]")&&a.add(d)}xs(t,i,r,0,a)}}function xs(t,e,n,o,i){if(o>=e.length||typeof t!="object"||t===null)return;let r=e[o];if(r.endsWith("[]")){let a=r.slice(0,-2),u=t;if(a in u&&Array.isArray(u[a]))for(let c of u[a])xs(c,e,n,o+1,i)}else if(r==="*"){if(typeof t=="object"&&t!==null&&!Array.isArray(t)){let a=t,u=Object.keys(a).filter(d=>!d.startsWith("_")&&!i.has(d)),c={};for(let d of u)c[d]=a[d];for(let[d,f]of Object.entries(c)){let p=[];for(let h of n.slice(o))h==="*"?p.push(d):p.push(h);l(a,p,f)}for(let d of u)delete a[d]}}else{let a=t;r in a&&xs(a[r],e,n,o+1,i)}}function fl(t){if(typeof t!="string")throw new Error("fromImageBytes must be a string");return t}function by(t){let e={},n=s(t,["operationName"]);n!=null&&l(e,["operationName"],n);let o=s(t,["resourceName"]);return o!=null&&l(e,["_url","resourceName"],o),e}function Ly(t){let e={},n=s(t,["name"]);n!=null&&l(e,["name"],n);let o=s(t,["metadata"]);o!=null&&l(e,["metadata"],o);let i=s(t,["done"]);i!=null&&l(e,["done"],i);let r=s(t,["error"]);r!=null&&l(e,["error"],r);let a=s(t,["response","generateVideoResponse"]);return a!=null&&l(e,["response"],Oy(a)),e}function qy(t){let e={},n=s(t,["name"]);n!=null&&l(e,["name"],n);let o=s(t,["metadata"]);o!=null&&l(e,["metadata"],o);let i=s(t,["done"]);i!=null&&l(e,["done"],i);let r=s(t,["error"]);r!=null&&l(e,["error"],r);let a=s(t,["response"]);return a!=null&&l(e,["response"],Fy(a)),e}function Oy(t){let e={},n=s(t,["generatedSamples"]);if(n!=null){let r=n;Array.isArray(r)&&(r=r.map(a=>Hy(a))),l(e,["generatedVideos"],r)}let o=s(t,["raiMediaFilteredCount"]);o!=null&&l(e,["raiMediaFilteredCount"],o);let i=s(t,["raiMediaFilteredReasons"]);return i!=null&&l(e,["raiMediaFilteredReasons"],i),e}function Fy(t){let e={},n=s(t,["videos"]);if(n!=null){let r=n;Array.isArray(r)&&(r=r.map(a=>Vy(a))),l(e,["generatedVideos"],r)}let o=s(t,["raiMediaFilteredCount"]);o!=null&&l(e,["raiMediaFilteredCount"],o);let i=s(t,["raiMediaFilteredReasons"]);return i!=null&&l(e,["raiMediaFilteredReasons"],i),e}function Hy(t){let e={},n=s(t,["video"]);return n!=null&&l(e,["video"],Yy(n)),e}function Vy(t){let e={},n=s(t,["_self"]);return n!=null&&l(e,["video"],Wy(n)),e}function By(t){let e={},n=s(t,["operationName"]);return n!=null&&l(e,["_url","operationName"],n),e}function $y(t){let e={},n=s(t,["operationName"]);return n!=null&&l(e,["_url","operationName"],n),e}function Xy(t){let e={},n=s(t,["name"]);n!=null&&l(e,["name"],n);let o=s(t,["metadata"]);o!=null&&l(e,["metadata"],o);let i=s(t,["done"]);i!=null&&l(e,["done"],i);let r=s(t,["error"]);r!=null&&l(e,["error"],r);let a=s(t,["response"]);return a!=null&&l(e,["response"],Jy(a)),e}function Jy(t){let e={},n=s(t,["sdkHttpResponse"]);n!=null&&l(e,["sdkHttpResponse"],n);let o=s(t,["parent"]);o!=null&&l(e,["parent"],o);let i=s(t,["documentName"]);return i!=null&&l(e,["documentName"],i),e}function pl(t){let e={},n=s(t,["name"]);n!=null&&l(e,["name"],n);let o=s(t,["metadata"]);o!=null&&l(e,["metadata"],o);let i=s(t,["done"]);i!=null&&l(e,["done"],i);let r=s(t,["error"]);r!=null&&l(e,["error"],r);let a=s(t,["response"]);return a!=null&&l(e,["response"],Ky(a)),e}function Ky(t){let e={},n=s(t,["sdkHttpResponse"]);n!=null&&l(e,["sdkHttpResponse"],n);let o=s(t,["parent"]);o!=null&&l(e,["parent"],o);let i=s(t,["documentName"]);return i!=null&&l(e,["documentName"],i),e}function Yy(t){let e={},n=s(t,["uri"]);n!=null&&l(e,["uri"],n);let o=s(t,["encodedVideo"]);o!=null&&l(e,["videoBytes"],fl(o));let i=s(t,["encoding"]);return i!=null&&l(e,["mimeType"],i),e}function Wy(t){let e={},n=s(t,["gcsUri"]);n!=null&&l(e,["uri"],n);let o=s(t,["bytesBase64Encoded"]);o!=null&&l(e,["videoBytes"],fl(o));let i=s(t,["mimeType"]);return i!=null&&l(e,["mimeType"],i),e}var Nc;(function(t){t.MEDIA_PROCESSING_UNSPECIFIED="MEDIA_PROCESSING_UNSPECIFIED",t.STATIC="STATIC",t.AGENTIC="AGENTIC"})(Nc||(Nc={}));var xc;(function(t){t.OUTCOME_UNSPECIFIED="OUTCOME_UNSPECIFIED",t.OUTCOME_OK="OUTCOME_OK",t.OUTCOME_FAILED="OUTCOME_FAILED",t.OUTCOME_DEADLINE_EXCEEDED="OUTCOME_DEADLINE_EXCEEDED"})(xc||(xc={}));var Dc;(function(t){t.LANGUAGE_UNSPECIFIED="LANGUAGE_UNSPECIFIED",t.PYTHON="PYTHON"})(Dc||(Dc={}));var Mc;(function(t){t.SCHEDULING_UNSPECIFIED="SCHEDULING_UNSPECIFIED",t.SILENT="SILENT",t.WHEN_IDLE="WHEN_IDLE",t.INTERRUPT="INTERRUPT"})(Mc||(Mc={}));var Gt;(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"})(Gt||(Gt={}));var Uc;(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"})(Uc||(Uc={}));var Gc;(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"})(Gc||(Gc={}));var bc;(function(t){t.API_SPEC_UNSPECIFIED="API_SPEC_UNSPECIFIED",t.SIMPLE_SEARCH="SIMPLE_SEARCH",t.ELASTIC_SEARCH="ELASTIC_SEARCH"})(bc||(bc={}));var Lc;(function(t){t.SAFETY_POLICY_UNSPECIFIED="SAFETY_POLICY_UNSPECIFIED",t.FINANCIAL_TRANSACTIONS="FINANCIAL_TRANSACTIONS",t.SENSITIVE_DATA_MODIFICATION="SENSITIVE_DATA_MODIFICATION",t.COMMUNICATION_TOOL="COMMUNICATION_TOOL",t.ACCOUNT_CREATION="ACCOUNT_CREATION",t.DATA_MODIFICATION="DATA_MODIFICATION",t.USER_CONSENT_MANAGEMENT="USER_CONSENT_MANAGEMENT",t.LEGAL_TERMS_AND_AGREEMENTS="LEGAL_TERMS_AND_AGREEMENTS"})(Lc||(Lc={}));var qc;(function(t){t.ENVIRONMENT_UNSPECIFIED="ENVIRONMENT_UNSPECIFIED",t.ENVIRONMENT_BROWSER="ENVIRONMENT_BROWSER",t.ENVIRONMENT_MOBILE="ENVIRONMENT_MOBILE",t.ENVIRONMENT_DESKTOP="ENVIRONMENT_DESKTOP"})(qc||(qc={}));var Oc;(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"})(Oc||(Oc={}));var Fc;(function(t){t.UNSPECIFIED="UNSPECIFIED",t.BLOCKING="BLOCKING",t.NON_BLOCKING="NON_BLOCKING"})(Fc||(Fc={}));var Hc;(function(t){t.MODE_UNSPECIFIED="MODE_UNSPECIFIED",t.MODE_DYNAMIC="MODE_DYNAMIC"})(Hc||(Hc={}));var Ot;(function(t){t.THINKING_LEVEL_UNSPECIFIED="THINKING_LEVEL_UNSPECIFIED",t.MINIMAL="MINIMAL",t.LOW="LOW",t.MEDIUM="MEDIUM",t.HIGH="HIGH"})(Ot||(Ot={}));var Vc;(function(t){t.DONT_ALLOW="DONT_ALLOW",t.ALLOW_ADULT="ALLOW_ADULT",t.ALLOW_ALL="ALLOW_ALL"})(Vc||(Vc={}));var Bc;(function(t){t.PROMINENT_PEOPLE_UNSPECIFIED="PROMINENT_PEOPLE_UNSPECIFIED",t.ALLOW_PROMINENT_PEOPLE="ALLOW_PROMINENT_PEOPLE",t.BLOCK_PROMINENT_PEOPLE="BLOCK_PROMINENT_PEOPLE"})(Bc||(Bc={}));var $c;(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_JAILBREAK="HARM_CATEGORY_JAILBREAK",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"})($c||($c={}));var Xc;(function(t){t.HARM_BLOCK_METHOD_UNSPECIFIED="HARM_BLOCK_METHOD_UNSPECIFIED",t.SEVERITY="SEVERITY",t.PROBABILITY="PROBABILITY"})(Xc||(Xc={}));var Jc;(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"})(Jc||(Jc={}));var Ft;(function(t){t.MODE_UNSPECIFIED="MODE_UNSPECIFIED",t.AUTO="AUTO",t.ANY="ANY",t.NONE="NONE",t.VALIDATED="VALIDATED"})(Ft||(Ft={}));var Kc;(function(t){t.MODE_UNSPECIFIED="MODE_UNSPECIFIED",t.VERBATIM="VERBATIM",t.SMART="SMART"})(Kc||(Kc={}));var Se;(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.TOO_MANY_TOOL_CALLS="TOO_MANY_TOOL_CALLS",t.IMAGE_PROHIBITED_CONTENT="IMAGE_PROHIBITED_CONTENT",t.NO_IMAGE="NO_IMAGE",t.IMAGE_RECITATION="IMAGE_RECITATION",t.IMAGE_OTHER="IMAGE_OTHER",t.CONTINUATION="CONTINUATION"})(Se||(Se={}));var Yc;(function(t){t.HARM_PROBABILITY_UNSPECIFIED="HARM_PROBABILITY_UNSPECIFIED",t.NEGLIGIBLE="NEGLIGIBLE",t.LOW="LOW",t.MEDIUM="MEDIUM",t.HIGH="HIGH"})(Yc||(Yc={}));var Wc;(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"})(Wc||(Wc={}));var zc;(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"})(zc||(zc={}));var Qc;(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"})(Qc||(Qc={}));var Zc;(function(t){t.TRAFFIC_TYPE_UNSPECIFIED="TRAFFIC_TYPE_UNSPECIFIED",t.ON_DEMAND="ON_DEMAND",t.ON_DEMAND_PRIORITY="ON_DEMAND_PRIORITY",t.ON_DEMAND_FLEX="ON_DEMAND_FLEX",t.ON_DEMAND_OFFPEAK="ON_DEMAND_OFFPEAK",t.PROVISIONED_THROUGHPUT="PROVISIONED_THROUGHPUT"})(Zc||(Zc={}));var jc;(function(t){t.MODALITY_UNSPECIFIED="MODALITY_UNSPECIFIED",t.TEXT="TEXT",t.IMAGE="IMAGE",t.VIDEO="VIDEO",t.AUDIO="AUDIO",t.DOCUMENT="DOCUMENT"})(jc||(jc={}));var ed;(function(t){t.MODEL_STAGE_UNSPECIFIED="MODEL_STAGE_UNSPECIFIED",t.UNSTABLE_EXPERIMENTAL="UNSTABLE_EXPERIMENTAL",t.EXPERIMENTAL="EXPERIMENTAL",t.PREVIEW="PREVIEW",t.STABLE="STABLE",t.LEGACY="LEGACY",t.DEPRECATED="DEPRECATED",t.RETIRED="RETIRED"})(ed||(ed={}));var td;(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"})(td||(td={}));var Qo;(function(t){t.MODALITY_UNSPECIFIED="MODALITY_UNSPECIFIED",t.TEXT="TEXT",t.IMAGE="IMAGE",t.AUDIO="AUDIO",t.VIDEO="VIDEO"})(Qo||(Qo={}));var nd;(function(t){t.DELIVERY_UNSPECIFIED="DELIVERY_UNSPECIFIED",t.INLINE="INLINE",t.URI="URI"})(nd||(nd={}));var od;(function(t){t.ASPECT_RATIO_UNSPECIFIED="ASPECT_RATIO_UNSPECIFIED",t.ASPECT_RATIO_ONE_BY_ONE="ASPECT_RATIO_ONE_BY_ONE",t.ASPECT_RATIO_TWO_BY_THREE="ASPECT_RATIO_TWO_BY_THREE",t.ASPECT_RATIO_THREE_BY_TWO="ASPECT_RATIO_THREE_BY_TWO",t.ASPECT_RATIO_THREE_BY_FOUR="ASPECT_RATIO_THREE_BY_FOUR",t.ASPECT_RATIO_FOUR_BY_THREE="ASPECT_RATIO_FOUR_BY_THREE",t.ASPECT_RATIO_FOUR_BY_FIVE="ASPECT_RATIO_FOUR_BY_FIVE",t.ASPECT_RATIO_FIVE_BY_FOUR="ASPECT_RATIO_FIVE_BY_FOUR",t.ASPECT_RATIO_NINE_BY_SIXTEEN="ASPECT_RATIO_NINE_BY_SIXTEEN",t.ASPECT_RATIO_SIXTEEN_BY_NINE="ASPECT_RATIO_SIXTEEN_BY_NINE",t.ASPECT_RATIO_TWENTY_ONE_BY_NINE="ASPECT_RATIO_TWENTY_ONE_BY_NINE",t.ASPECT_RATIO_ONE_BY_EIGHT="ASPECT_RATIO_ONE_BY_EIGHT",t.ASPECT_RATIO_EIGHT_BY_ONE="ASPECT_RATIO_EIGHT_BY_ONE",t.ASPECT_RATIO_ONE_BY_FOUR="ASPECT_RATIO_ONE_BY_FOUR",t.ASPECT_RATIO_FOUR_BY_ONE="ASPECT_RATIO_FOUR_BY_ONE"})(od||(od={}));var id;(function(t){t.IMAGE_SIZE_UNSPECIFIED="IMAGE_SIZE_UNSPECIFIED",t.IMAGE_SIZE_FIVE_TWELVE="IMAGE_SIZE_FIVE_TWELVE",t.IMAGE_SIZE_ONE_K="IMAGE_SIZE_ONE_K",t.IMAGE_SIZE_TWO_K="IMAGE_SIZE_TWO_K",t.IMAGE_SIZE_FOUR_K="IMAGE_SIZE_FOUR_K"})(id||(id={}));var rd;(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"})(rd||(rd={}));var sd;(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"})(sd||(sd={}));var ad;(function(t){t.RESPONSE_PARSE_TYPE_UNSPECIFIED="RESPONSE_PARSE_TYPE_UNSPECIFIED",t.IDENTITY="IDENTITY",t.REGEX_EXTRACT="REGEX_EXTRACT"})(ad||(ad={}));var ld;(function(t){t.MATCH_OPERATION_UNSPECIFIED="MATCH_OPERATION_UNSPECIFIED",t.REGEX_CONTAINS="REGEX_CONTAINS",t.PARTIAL_MATCH="PARTIAL_MATCH",t.EXACT_MATCH="EXACT_MATCH"})(ld||(ld={}));var ud;(function(t){t.REINFORCEMENT_TUNING_THINKING_LEVEL_UNSPECIFIED="REINFORCEMENT_TUNING_THINKING_LEVEL_UNSPECIFIED",t.MINIMAL="MINIMAL",t.HIGH="HIGH"})(ud||(ud={}));var Ds;(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"})(Ds||(Ds={}));var cd;(function(t){t.TUNING_JOB_STATE_UNSPECIFIED="TUNING_JOB_STATE_UNSPECIFIED",t.TUNING_JOB_STATE_WAITING_FOR_QUOTA="TUNING_JOB_STATE_WAITING_FOR_QUOTA",t.TUNING_JOB_STATE_PROCESSING_DATASET="TUNING_JOB_STATE_PROCESSING_DATASET",t.TUNING_JOB_STATE_WAITING_FOR_CAPACITY="TUNING_JOB_STATE_WAITING_FOR_CAPACITY",t.TUNING_JOB_STATE_TUNING="TUNING_JOB_STATE_TUNING",t.TUNING_JOB_STATE_POST_PROCESSING="TUNING_JOB_STATE_POST_PROCESSING"})(cd||(cd={}));var dd;(function(t){t.AGGREGATION_METRIC_UNSPECIFIED="AGGREGATION_METRIC_UNSPECIFIED",t.AVERAGE="AVERAGE",t.MODE="MODE",t.STANDARD_DEVIATION="STANDARD_DEVIATION",t.VARIANCE="VARIANCE",t.MINIMUM="MINIMUM",t.MAXIMUM="MAXIMUM",t.MEDIAN="MEDIAN",t.PERCENTILE_P90="PERCENTILE_P90",t.PERCENTILE_P95="PERCENTILE_P95",t.PERCENTILE_P99="PERCENTILE_P99"})(dd||(dd={}));var fd;(function(t){t.PAIRWISE_CHOICE_UNSPECIFIED="PAIRWISE_CHOICE_UNSPECIFIED",t.BASELINE="BASELINE",t.CANDIDATE="CANDIDATE",t.TIE="TIE"})(fd||(fd={}));var pd;(function(t){t.VIDEO_ORIENTATION_UNSPECIFIED="VIDEO_ORIENTATION_UNSPECIFIED",t.LANDSCAPE="LANDSCAPE",t.PORTRAIT="PORTRAIT"})(pd||(pd={}));var hd;(function(t){t.TUNING_SPEED_UNSPECIFIED="TUNING_SPEED_UNSPECIFIED",t.REGULAR="REGULAR",t.FAST="FAST"})(hd||(hd={}));var md;(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"})(md||(md={}));var gd;(function(t){t.STATE_UNSPECIFIED="STATE_UNSPECIFIED",t.STATE_PENDING="STATE_PENDING",t.STATE_ACTIVE="STATE_ACTIVE",t.STATE_FAILED="STATE_FAILED"})(gd||(gd={}));var _d;(function(t){t.UNSPECIFIED="unspecified",t.FLEX="flex",t.STANDARD="standard",t.PRIORITY="priority"})(_d||(_d={}));var yd;(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"})(yd||(yd={}));var vd;(function(t){t.TOOL_TYPE_UNSPECIFIED="TOOL_TYPE_UNSPECIFIED",t.GOOGLE_SEARCH_WEB="GOOGLE_SEARCH_WEB",t.GOOGLE_SEARCH_IMAGE="GOOGLE_SEARCH_IMAGE",t.URL_CONTEXT="URL_CONTEXT",t.GOOGLE_MAPS="GOOGLE_MAPS",t.FILE_SEARCH="FILE_SEARCH",t.MEDIA_PROCESSING="MEDIA_PROCESSING"})(vd||(vd={}));var Ms;(function(t){t.COLLECTION="COLLECTION"})(Ms||(Ms={}));var Ed;(function(t){t.FEATURE_SELECTION_PREFERENCE_UNSPECIFIED="FEATURE_SELECTION_PREFERENCE_UNSPECIFIED",t.PRIORITIZE_QUALITY="PRIORITIZE_QUALITY",t.BALANCED="BALANCED",t.PRIORITIZE_COST="PRIORITIZE_COST"})(Ed||(Ed={}));var Zo;(function(t){t.PREDICT="PREDICT",t.EMBED_CONTENT="EMBED_CONTENT"})(Zo||(Zo={}));var Td;(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"})(Td||(Td={}));var Ad;(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"})(Ad||(Ad={}));var Cd;(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"})(Cd||(Cd={}));var Id;(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"})(Id||(Id={}));var Sd;(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"})(Sd||(Sd={}));var wd;(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"})(wd||(wd={}));var Rd;(function(t){t.FOREGROUND="FOREGROUND",t.BACKGROUND="BACKGROUND",t.PROMPT="PROMPT",t.SEMANTIC="SEMANTIC",t.INTERACTIVE="INTERACTIVE"})(Rd||(Rd={}));var Pd;(function(t){t.ASSET="ASSET",t.STYLE="STYLE"})(Pd||(Pd={}));var kd;(function(t){t.INSERT="INSERT",t.REMOVE="REMOVE",t.REMOVE_STATIC="REMOVE_STATIC",t.OUTPAINT="OUTPAINT"})(kd||(kd={}));var Nd;(function(t){t.OPTIMIZED="OPTIMIZED",t.LOSSLESS="LOSSLESS"})(Nd||(Nd={}));var xd;(function(t){t.CROP="CROP",t.PAD="PAD"})(xd||(xd={}));var Dd;(function(t){t.SUPERVISED_FINE_TUNING="SUPERVISED_FINE_TUNING",t.PREFERENCE_TUNING="PREFERENCE_TUNING",t.DISTILLATION="DISTILLATION",t.REINFORCEMENT_TUNING="REINFORCEMENT_TUNING"})(Dd||(Dd={}));var Md;(function(t){t.STATE_UNSPECIFIED="STATE_UNSPECIFIED",t.PROCESSING="PROCESSING",t.ACTIVE="ACTIVE",t.FAILED="FAILED"})(Md||(Md={}));var Ud;(function(t){t.SOURCE_UNSPECIFIED="SOURCE_UNSPECIFIED",t.UPLOADED="UPLOADED",t.GENERATED="GENERATED",t.REGISTERED="REGISTERED"})(Ud||(Ud={}));var Gd;(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",t.PROHIBITED_INPUT_CONTENT="PROHIBITED_INPUT_CONTENT",t.IMAGE_PROHIBITED_INPUT_CONTENT="IMAGE_PROHIBITED_INPUT_CONTENT",t.INPUT_TEXT_CONTAIN_PROMINENT_PERSON_PROHIBITED="INPUT_TEXT_CONTAIN_PROMINENT_PERSON_PROHIBITED",t.INPUT_IMAGE_CELEBRITY="INPUT_IMAGE_CELEBRITY",t.INPUT_IMAGE_PHOTO_REALISTIC_CHILD_PROHIBITED="INPUT_IMAGE_PHOTO_REALISTIC_CHILD_PROHIBITED",t.INPUT_TEXT_NCII_PROHIBITED="INPUT_TEXT_NCII_PROHIBITED",t.INPUT_OTHER="INPUT_OTHER",t.INPUT_IP_PROHIBITED="INPUT_IP_PROHIBITED",t.BLOCKLIST="BLOCKLIST",t.UNSAFE_PROMPT_FOR_IMAGE_GENERATION="UNSAFE_PROMPT_FOR_IMAGE_GENERATION",t.GENERATED_IMAGE_SAFETY="GENERATED_IMAGE_SAFETY",t.GENERATED_CONTENT_SAFETY="GENERATED_CONTENT_SAFETY",t.GENERATED_AUDIO_SAFETY="GENERATED_AUDIO_SAFETY",t.GENERATED_VIDEO_SAFETY="GENERATED_VIDEO_SAFETY",t.GENERATED_CONTENT_PROHIBITED="GENERATED_CONTENT_PROHIBITED",t.GENERATED_CONTENT_BLOCKLIST="GENERATED_CONTENT_BLOCKLIST",t.GENERATED_IMAGE_PROHIBITED="GENERATED_IMAGE_PROHIBITED",t.GENERATED_IMAGE_CELEBRITY="GENERATED_IMAGE_CELEBRITY",t.GENERATED_IMAGE_PROMINENT_PEOPLE_DETECTED_BY_REWRITER="GENERATED_IMAGE_PROMINENT_PEOPLE_DETECTED_BY_REWRITER",t.GENERATED_IMAGE_IDENTIFIABLE_PEOPLE="GENERATED_IMAGE_IDENTIFIABLE_PEOPLE",t.GENERATED_IMAGE_MINORS="GENERATED_IMAGE_MINORS",t.OUTPUT_IMAGE_IP_PROHIBITED="OUTPUT_IMAGE_IP_PROHIBITED",t.GENERATED_OTHER="GENERATED_OTHER",t.MAX_REGENERATION_REACHED="MAX_REGENERATION_REACHED"})(Gd||(Gd={}));var bd;(function(t){t.INTERACTION_STATUS_UNSPECIFIED="INTERACTION_STATUS_UNSPECIFIED",t.IN_PROGRESS="IN_PROGRESS",t.REQUIRES_ACTION="REQUIRES_ACTION",t.IDLE="IDLE"})(bd||(bd={}));var Ld;(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"})(Ld||(Ld={}));var qd;(function(t){t.TYPE_UNSPECIFIED="TYPE_UNSPECIFIED",t.ACTIVITY_START="ACTIVITY_START",t.ACTIVITY_END="ACTIVITY_END"})(qd||(qd={}));var Od;(function(t){t.START_SENSITIVITY_UNSPECIFIED="START_SENSITIVITY_UNSPECIFIED",t.START_SENSITIVITY_HIGH="START_SENSITIVITY_HIGH",t.START_SENSITIVITY_LOW="START_SENSITIVITY_LOW"})(Od||(Od={}));var Fd;(function(t){t.END_SENSITIVITY_UNSPECIFIED="END_SENSITIVITY_UNSPECIFIED",t.END_SENSITIVITY_HIGH="END_SENSITIVITY_HIGH",t.END_SENSITIVITY_LOW="END_SENSITIVITY_LOW"})(Fd||(Fd={}));var Hd;(function(t){t.ACTIVITY_HANDLING_UNSPECIFIED="ACTIVITY_HANDLING_UNSPECIFIED",t.START_OF_ACTIVITY_INTERRUPTS="START_OF_ACTIVITY_INTERRUPTS",t.NO_INTERRUPTION="NO_INTERRUPTION"})(Hd||(Hd={}));var Vd;(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",t.TURN_INCLUDES_AUDIO_ACTIVITY_AND_ALL_VIDEO="TURN_INCLUDES_AUDIO_ACTIVITY_AND_ALL_VIDEO"})(Vd||(Vd={}));var Bd;(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"})(Bd||(Bd={}));var $d;(function(t){t.MUSIC_GENERATION_MODE_UNSPECIFIED="MUSIC_GENERATION_MODE_UNSPECIFIED",t.QUALITY="QUALITY",t.DIVERSITY="DIVERSITY",t.VOCALIZATION="VOCALIZATION"})($d||($d={}));var yn;(function(t){t.PLAYBACK_CONTROL_UNSPECIFIED="PLAYBACK_CONTROL_UNSPECIFIED",t.PLAY="PLAY",t.PAUSE="PAUSE",t.STOP="STOP",t.RESET_CONTEXT="RESET_CONTEXT"})(yn||(yn={}));var wt=class{constructor(e){let n={};for(let o of e.headers.entries())n[o[0]]=o[1];this.headers=n,this.responseInternal=e}json(){return this.responseInternal.json()}},Us=class{},jo=class{},ct=class{get text(){var e,n,o,i,r,a,u,c;if(((i=(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||i===void 0?void 0:i.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,p=[];for(let h of(c=(u=(a=(r=this.candidates)===null||r===void 0?void 0:r[0])===null||a===void 0?void 0:a.content)===null||u===void 0?void 0:u.parts)!==null&&c!==void 0?c:[]){for(let[g,_]of Object.entries(h))g!=="text"&&g!=="thought"&&g!=="thoughtSignature"&&(_!==null||_!==void 0)&&p.push(g);if(typeof h.text=="string"){if(typeof h.thought=="boolean"&&h.thought)continue;f=!0,d+=h.text}}return p.length>0&&console.warn(`there are non-text parts ${p} 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,i,r,a,u,c;if(((i=(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||i===void 0?void 0:i.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="",f=[];for(let p of(c=(u=(a=(r=this.candidates)===null||r===void 0?void 0:r[0])===null||a===void 0?void 0:a.content)===null||u===void 0?void 0:u.parts)!==null&&c!==void 0?c:[]){for(let[h,g]of Object.entries(p))h!=="inlineData"&&(g!==null||g!==void 0)&&f.push(h);p.inlineData&&typeof p.inlineData.data=="string"&&(d+=atob(p.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,i,r,a,u,c;if(((i=(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||i===void 0?void 0:i.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.");let d=(c=(u=(a=(r=this.candidates)===null||r===void 0?void 0:r[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?.length!==0)return d}get executableCode(){var e,n,o,i,r,a,u,c,d;if(((i=(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||i===void 0?void 0:i.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.");let f=(c=(u=(a=(r=this.candidates)===null||r===void 0?void 0:r[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(p=>p.executableCode).map(p=>p.executableCode).filter(p=>p!==void 0);if(f?.length!==0)return(d=f?.[0])===null||d===void 0?void 0:d.code}get codeExecutionResult(){var e,n,o,i,r,a,u,c,d;if(((i=(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||i===void 0?void 0:i.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.");let f=(c=(u=(a=(r=this.candidates)===null||r===void 0?void 0:r[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(p=>p.codeExecutionResult).map(p=>p.codeExecutionResult).filter(p=>p!==void 0);if(f?.length!==0)return(d=f?.[0])===null||d===void 0?void 0:d.output}get initialPromptTokenCount(){var e;if(this.usageMetadata)return(e=this.usageMetadata._initialPromptTokenCount)!==null&&e!==void 0?e:this.usageMetadata.promptTokenCount}},ei=class{},Gs=class{},bs=class{},Ls=class{},qs=class{},Os=class{},ti=class{},ni=class{};var oi=class{},Fs=class{};var ii=class t{_fromAPIResponse({apiResponse:e,_isVertexAI:n}){let o=new t,i,r=e;return n?i=qy(r):i=Ly(r),Object.assign(o,i),o}};var Hs=class{},ri=class{},Vs=class{},si=class{},ai=class{},Bs=class{},$s=class{},Xs=class{};var Js=class t{_fromAPIResponse({apiResponse:e,_isVertexAI:n}){let o=new t,r=Xy(e);return Object.assign(o,r),o}},Ks=class{},Ys=class{},Ws=class{},zs=class{};var li=class{};var Qs=class{get text(){var e,n,o;let i="",r=!1,a=[];for(let 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(let[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;r=!0,i+=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.`),r?i:void 0}get data(){var e,n,o;let i="",r=[];for(let 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(let[u,c]of Object.entries(a))u!=="inlineData"&&c!==null&&r.push(u);a.inlineData&&typeof a.inlineData.data=="string"&&(i+=atob(a.inlineData.data))}return r.length>0&&console.warn(`there are non-data parts ${r} in the response, returning concatenation of all data parts. Please refer to the non data parts for a full response from model.`),i.length>0?btoa(i):void 0}};var Zs=class{get audioChunk(){if(this.serverContent&&this.serverContent.audioChunks&&this.serverContent.audioChunks.length>0)return this.serverContent.audioChunks[0]}};var ui=class t{_fromAPIResponse({apiResponse:e,_isVertexAI:n}){let o=new t,r=pl(e);return Object.assign(o,r),o}};function ye(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){let 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 Ff(t,e){let n=ye(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 Hf(t){return Array.isArray(t)?t.map(e=>ci(e)):[ci(t)]}function ci(t){if(typeof t=="object"&&t!==null)return t;throw new Error(`Could not parse input as Blob. Unsupported blob type: ${typeof t}`)}function Vf(t){let e=ci(t);if(e.mimeType&&e.mimeType.startsWith("image/"))return e;throw new Error(`Unsupported mime type: ${e.mimeType}`)}function Bf(t){let e=ci(t);if(e.mimeType&&e.mimeType.startsWith("audio/"))return e;throw new Error(`Unsupported mime type: ${e.mimeType}`)}function Xd(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 $f(t){if(t==null||Array.isArray(t)&&t.length===0)throw new Error("PartListUnion is required");return Array.isArray(t)?t.map(e=>Xd(e)):[Xd(t)]}function js(t){return t!=null&&typeof t=="object"&&"parts"in t&&Array.isArray(t.parts)}function Jd(t){return t!=null&&typeof t=="object"&&"functionCall"in t}function Kd(t){return t!=null&&typeof t=="object"&&"functionResponse"in t}function ke(t){if(t==null)throw new Error("ContentUnion is required");return js(t)?t:{role:"user",parts:$f(t)}}function hl(t,e){if(!e)return[];if(t.isVertexAI()&&Array.isArray(e))return e.flatMap(n=>{let o=ke(n);return o.parts&&o.parts.length>0&&o.parts[0].text!==void 0?[o.parts[0].text]:[]});if(t.isVertexAI()){let n=ke(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=>ke(n)):[ke(e)]}function Oe(t){if(t==null||Array.isArray(t)&&t.length===0)throw new Error("contents are required");if(!Array.isArray(t)){if(Jd(t)||Kd(t))throw new Error("To specify functionCall or functionResponse parts, please wrap them in a Content object, specifying the role for them");return[ke(t)]}let e=[],n=[],o=js(t[0]);for(let i of t){let r=js(i);if(r!=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(r)e.push(i);else{if(Jd(i)||Kd(i))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(i)}}return o||e.push({role:"user",parts:$f(n)}),e}function zy(t,e){t.includes("null")&&(e.nullable=!0);let n=t.filter(o=>o!=="null");if(n.length===1)e.type=Object.values(Gt).includes(n[0].toUpperCase())?n[0].toUpperCase():Gt.TYPE_UNSPECIFIED;else{e.anyOf=[];for(let o of n)e.anyOf.push({type:Object.values(Gt).includes(o.toUpperCase())?o.toUpperCase():Gt.TYPE_UNSPECIFIED})}}function En(t){let e={},n=["items"],o=["anyOf"],i=["properties"];if(t.type&&t.anyOf)throw new Error("type and anyOf cannot be both populated.");let r=t.anyOf;r!=null&&r.length==2&&(r[0].type==="null"?(e.nullable=!0,t=r[1]):r[1].type==="null"&&(e.nullable=!0,t=r[0])),t.type instanceof Array&&zy(t.type,e);for(let[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(Gt).includes(u.toUpperCase())?u.toUpperCase():Gt.TYPE_UNSPECIFIED}else if(n.includes(a))e[a]=En(u);else if(o.includes(a)){let c=[];for(let d of u){if(d.type=="null"){e.nullable=!0;continue}c.push(En(d))}e[a]=c}else if(i.includes(a)){let c={};for(let[d,f]of Object.entries(u))c[d]=En(f);e[a]=c}else{if(a==="additionalProperties")continue;e[a]=u}return e}function ml(t){return En(t)}function gl(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 _l(t){if("multiSpeakerVoiceConfig"in t)throw new Error("multiSpeakerVoiceConfig is not supported in the live API.");return t}function Jt(t){if(t.functionDeclarations)for(let e of t.functionDeclarations)e.parameters&&(Object.keys(e.parameters).includes("$schema")?e.parametersJsonSchema||(e.parametersJsonSchema=e.parameters,delete e.parameters):e.parameters=En(e.parameters)),e.response&&(Object.keys(e.response).includes("$schema")?e.responseJsonSchema||(e.responseJsonSchema=e.response,delete e.response):e.response=En(e.response));return t}function Kt(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");let e=[];for(let n of t)e.push(n);return e}function Qy(t,e,n,o=1){let i=!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}`:i?`projects/${t.getProject()}/locations/${t.getLocation()}/${n}/${e}`:e:i?`${n}/${e}`:e}function kt(t,e){if(typeof e!="string")throw new Error("name must be a string");return Qy(t,e,"cachedContents")}function Xf(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 en(t){return fl(t)}function Zy(t){return t!=null&&typeof t=="object"&&"name"in t}function Jf(t){return t!=null&&typeof t=="object"&&"video"in t}function Kf(t){return t!=null&&typeof t=="object"&&"uri"in t}function yl(t){var e;let n;if(Zy(t)&&(n=t.name),!(Kf(t)&&(n=t.uri,n===void 0))&&!(Jf(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://")){let i=n.split("files/")[1].match(/[a-z0-9]+/);if(i===null)throw new Error(`Could not extract file name from URI ${n}`);n=i[0]}else n.startsWith("files/")&&(n=n.split("files/")[1]);return n}}function Yf(t,e){let n;return t.isVertexAI()?n=e?"publishers/google/models":"models":n=e?"models":"tunedModels",n}function Wf(t){for(let e of["models","tunedModels","publisherModels"])if(jy(t,e))return t[e];return[]}function jy(t,e){return t!==null&&typeof t=="object"&&e in t}function ev(t,e={}){let 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 tv(t,e={}){let n=[],o=new Set;for(let i of t){let r=i.name;if(o.has(r))throw new Error(`Duplicate function name ${r} found in MCP tools. Please ensure function names are unique.`);o.add(r);let a=ev(i,e);a.functionDeclarations&&n.push(...a.functionDeclarations)}return{functionDeclarations:n}}function zf(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 if(/^projects\/[^/]+\/locations\/[^/]+\/datasets\/[^/]+$/.test(e))n={format:"vertex-dataset",vertexDatasetName: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;let o=[n.gcsUri,n.bigqueryUri,n.vertexDatasetName].filter(Boolean).length,i=[n.inlinedRequests,n.fileName].filter(Boolean).length;if(t.isVertexAI()){if(i>0||o!==1)throw new Error("Exactly one of `gcsUri`, `bigqueryUri`, or `vertexDatasetName` must be set for Vertex AI.")}else if(o>0||i!==1)throw new Error("Exactly one of `inlinedRequests`, `fileName`, must be set for Gemini API.");return n}function nv(t){if(typeof t!="string")return t;let 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 Qf(t){if(typeof t!="object"||t===null)return{};let e=t,n=e.inlinedResponses;if(typeof n!="object"||n===null)return t;let i=n.inlinedResponses;if(!Array.isArray(i)||i.length===0)return t;let r=!1;for(let a of i){if(typeof a!="object"||a===null)continue;let c=a.response;if(typeof c!="object"||c===null)continue;if(c.embedding!==void 0){r=!0;break}}return r&&(e.inlinedEmbedContentResponses=e.inlinedResponses,delete e.inlinedResponses),t}function Sn(t,e){let 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 Zf(t){let 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}function ov(t){return t.includes("gemini")&&t!=="gemini-embedding-001"||t.includes("maas")}function iv(t){let e={},n=s(t,["apiKey"]);if(n!=null&&l(e,["apiKey"],n),s(t,["apiKeyConfig"])!==void 0)throw new Error("apiKeyConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["authType"])!==void 0)throw new Error("authType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["googleServiceAccountConfig"])!==void 0)throw new Error("googleServiceAccountConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["httpBasicAuthConfig"])!==void 0)throw new Error("httpBasicAuthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["oauthConfig"])!==void 0)throw new Error("oauthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["oidcConfig"])!==void 0)throw new Error("oidcConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return e}function rv(t){let e={},n=s(t,["responsesFile"]);n!=null&&l(e,["fileName"],n);let o=s(t,["inlinedResponses","inlinedResponses"]);if(o!=null){let r=o;Array.isArray(r)&&(r=r.map(a=>Lv(a))),l(e,["inlinedResponses"],r)}let i=s(t,["inlinedEmbedContentResponses","inlinedResponses"]);if(i!=null){let r=i;Array.isArray(r)&&(r=r.map(a=>a)),l(e,["inlinedEmbedContentResponses"],r)}return e}function sv(t){let e={},n=s(t,["predictionsFormat"]);n!=null&&l(e,["format"],n);let o=s(t,["gcsDestination","outputUriPrefix"]);o!=null&&l(e,["gcsUri"],o);let i=s(t,["bigqueryDestination","outputUri"]);i!=null&&l(e,["bigqueryUri"],i);let r=s(t,["vertexMultimodalDatasetDestination"]);return r!=null&&l(e,["vertexDataset"],Yv(r)),e}function av(t){let e={},n=s(t,["format"]);n!=null&&l(e,["predictionsFormat"],n);let o=s(t,["gcsUri"]);o!=null&&l(e,["gcsDestination","outputUriPrefix"],o);let i=s(t,["bigqueryUri"]);i!=null&&l(e,["bigqueryDestination","outputUri"],i);let r=s(t,["vertexDataset"]);if(r!=null&&l(e,["vertexMultimodalDatasetDestination"],Wv(r)),s(t,["fileName"])!==void 0)throw new Error("fileName parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(s(t,["inlinedResponses"])!==void 0)throw new Error("inlinedResponses parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(s(t,["inlinedEmbedContentResponses"])!==void 0)throw new Error("inlinedEmbedContentResponses parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return e}function Wo(t){let e={},n=s(t,["name"]);n!=null&&l(e,["name"],n);let o=s(t,["metadata","displayName"]);o!=null&&l(e,["displayName"],o);let i=s(t,["metadata","state"]);i!=null&&l(e,["state"],Zf(i));let r=s(t,["metadata","createTime"]);r!=null&&l(e,["createTime"],r);let a=s(t,["metadata","endTime"]);a!=null&&l(e,["endTime"],a);let u=s(t,["metadata","updateTime"]);u!=null&&l(e,["updateTime"],u);let c=s(t,["metadata","model"]);c!=null&&l(e,["model"],c);let d=s(t,["metadata","output"]);return d!=null&&l(e,["dest"],rv(Qf(d))),e}function ea(t){let e={},n=s(t,["name"]);n!=null&&l(e,["name"],n);let o=s(t,["displayName"]);o!=null&&l(e,["displayName"],o);let i=s(t,["state"]);i!=null&&l(e,["state"],Zf(i));let r=s(t,["error"]);r!=null&&l(e,["error"],r);let a=s(t,["createTime"]);a!=null&&l(e,["createTime"],a);let u=s(t,["startTime"]);u!=null&&l(e,["startTime"],u);let c=s(t,["endTime"]);c!=null&&l(e,["endTime"],c);let d=s(t,["updateTime"]);d!=null&&l(e,["updateTime"],d);let f=s(t,["model"]);f!=null&&l(e,["model"],f);let p=s(t,["inputConfig"]);p!=null&&l(e,["src"],lv(p));let h=s(t,["outputConfig"]);h!=null&&l(e,["dest"],sv(Qf(h)));let g=s(t,["outputInfo"]);g!=null&&l(e,["outputInfo"],g);let _=s(t,["completionStats"]);return _!=null&&l(e,["completionStats"],_),e}function lv(t){let e={},n=s(t,["instancesFormat"]);n!=null&&l(e,["format"],n);let o=s(t,["gcsSource","uris"]);o!=null&&l(e,["gcsUri"],o);let i=s(t,["bigquerySource","inputUri"]);i!=null&&l(e,["bigqueryUri"],i);let r=s(t,["vertexMultimodalDatasetSource","datasetName"]);return r!=null&&l(e,["vertexDatasetName"],r),e}function uv(t,e){let n={};if(s(e,["format"])!==void 0)throw new Error("format parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(e,["gcsUri"])!==void 0)throw new Error("gcsUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(e,["bigqueryUri"])!==void 0)throw new Error("bigqueryUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(e,["vertexDatasetName"])!==void 0)throw new Error("vertexDatasetName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let o=s(e,["fileName"]);o!=null&&l(n,["fileName"],o);let i=s(e,["inlinedRequests"]);if(i!=null){let r=i;Array.isArray(r)&&(r=r.map(a=>bv(t,a))),l(n,["requests","requests"],r)}return n}function cv(t){let e={},n=s(t,["format"]);n!=null&&l(e,["instancesFormat"],n);let o=s(t,["gcsUri"]);o!=null&&l(e,["gcsSource","uris"],o);let i=s(t,["bigqueryUri"]);i!=null&&l(e,["bigquerySource","inputUri"],i);let r=s(t,["vertexDatasetName"]);if(r!=null&&l(e,["vertexMultimodalDatasetSource","datasetName"],r),s(t,["fileName"])!==void 0)throw new Error("fileName parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(s(t,["inlinedRequests"])!==void 0)throw new Error("inlinedRequests parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return e}function dv(t,e){let n={},o=s(e,["name"]);return o!=null&&l(n,["_url","name"],Sn(t,o)),n}function fv(t,e){let n={},o=s(e,["name"]);return o!=null&&l(n,["_url","name"],Sn(t,o)),n}function pv(t){let e={},n=s(t,["content"]);n!=null&&l(e,["content"],n);let o=s(t,["citationMetadata"]);o!=null&&l(e,["citationMetadata"],hv(o));let i=s(t,["tokenCount"]);i!=null&&l(e,["tokenCount"],i);let r=s(t,["finishReason"]);r!=null&&l(e,["finishReason"],r);let a=s(t,["groundingMetadata"]);a!=null&&l(e,["groundingMetadata"],a);let u=s(t,["avgLogprobs"]);u!=null&&l(e,["avgLogprobs"],u);let c=s(t,["index"]);c!=null&&l(e,["index"],c);let d=s(t,["logprobsResult"]);d!=null&&l(e,["logprobsResult"],d);let f=s(t,["safetyRatings"]);if(f!=null){let g=f;Array.isArray(g)&&(g=g.map(_=>_)),l(e,["safetyRatings"],g)}let p=s(t,["urlContextMetadata"]);p!=null&&l(e,["urlContextMetadata"],p);let h=s(t,["continuationToken"]);return h!=null&&l(e,["continuationToken"],h),e}function hv(t){let e={},n=s(t,["citationSources"]);if(n!=null){let o=n;Array.isArray(o)&&(o=o.map(i=>i)),l(e,["citations"],o)}return e}function jf(t){let e={},n=s(t,["parts"]);if(n!=null){let i=n;Array.isArray(i)&&(i=i.map(r=>$v(r))),l(e,["parts"],i)}let o=s(t,["role"]);return o!=null&&l(e,["role"],o),e}function mv(t,e){let n={},o=s(t,["displayName"]);if(e!==void 0&&o!=null&&l(e,["batch","displayName"],o),s(t,["dest"])!==void 0)throw new Error("dest parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let i=s(t,["webhookConfig"]);return e!==void 0&&i!=null&&l(e,["batch","webhookConfig"],i),n}function gv(t,e){let n={},o=s(t,["displayName"]);e!==void 0&&o!=null&&l(e,["displayName"],o);let i=s(t,["dest"]);if(e!==void 0&&i!=null&&l(e,["outputConfig"],av(nv(i))),s(t,["webhookConfig"])!==void 0)throw new Error("webhookConfig parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return n}function Yd(t,e){let n={},o=s(e,["model"]);o!=null&&l(n,["_url","model"],ye(t,o));let i=s(e,["src"]);i!=null&&l(n,["batch","inputConfig"],uv(t,zf(t,i)));let r=s(e,["config"]);return r!=null&&mv(r,n),n}function _v(t,e){let n={},o=s(e,["model"]);o!=null&&l(n,["model"],ye(t,o));let i=s(e,["src"]);i!=null&&l(n,["inputConfig"],cv(zf(t,i)));let r=s(e,["config"]);return r!=null&&gv(r,n),n}function yv(t,e){let n={},o=s(t,["displayName"]);return e!==void 0&&o!=null&&l(e,["batch","displayName"],o),n}function vv(t,e){let n={},o=s(e,["model"]);o!=null&&l(n,["_url","model"],ye(t,o));let i=s(e,["src"]);i!=null&&l(n,["batch","inputConfig"],wv(t,i));let r=s(e,["config"]);return r!=null&&yv(r,n),n}function Ev(t,e){let n={},o=s(e,["name"]);return o!=null&&l(n,["_url","name"],Sn(t,o)),n}function Tv(t,e){let n={},o=s(e,["name"]);return o!=null&&l(n,["_url","name"],Sn(t,o)),n}function Av(t){let e={},n=s(t,["sdkHttpResponse"]);n!=null&&l(e,["sdkHttpResponse"],n);let o=s(t,["name"]);o!=null&&l(e,["name"],o);let i=s(t,["done"]);i!=null&&l(e,["done"],i);let r=s(t,["error"]);return r!=null&&l(e,["error"],r),e}function Cv(t){let e={},n=s(t,["sdkHttpResponse"]);n!=null&&l(e,["sdkHttpResponse"],n);let o=s(t,["name"]);o!=null&&l(e,["name"],o);let i=s(t,["done"]);i!=null&&l(e,["done"],i);let r=s(t,["error"]);return r!=null&&l(e,["error"],r),e}function Iv(t,e){let n={},o=s(e,["contents"]);if(o!=null){let r=hl(t,o);Array.isArray(r)&&(r=r.map(a=>a)),l(n,["requests[]","request","content"],r)}let i=s(e,["config"]);return i!=null&&(l(n,["_self"],Sv(i,n)),Gy(n,{"requests[].*":"requests[].request.*"})),n}function Sv(t,e){let n={},o=s(t,["taskType"]);e!==void 0&&o!=null&&l(e,["requests[]","taskType"],o);let i=s(t,["title"]);e!==void 0&&i!=null&&l(e,["requests[]","title"],i);let r=s(t,["outputDimensionality"]);if(e!==void 0&&r!=null&&l(e,["requests[]","outputDimensionality"],r),s(t,["mimeType"])!==void 0)throw new Error("mimeType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["autoTruncate"])!==void 0)throw new Error("autoTruncate parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["documentOcr"])!==void 0)throw new Error("documentOcr parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["audioTrackExtraction"])!==void 0)throw new Error("audioTrackExtraction parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return n}function wv(t,e){let n={},o=s(e,["fileName"]);o!=null&&l(n,["file_name"],o);let i=s(e,["inlinedRequests"]);return i!=null&&l(n,["requests"],Iv(t,i)),n}function Rv(t){let e={},n=s(t,["args"]);n!=null&&l(e,["args"],n);let o=s(t,["id"]);o!=null&&l(e,["id"],o);let i=s(t,["name"]);if(i!=null&&l(e,["name"],i),s(t,["partialArgs"])!==void 0)throw new Error("partialArgs parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["willContinue"])!==void 0)throw new Error("willContinue parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return e}function Pv(t){let e={},n=s(t,["allowedFunctionNames"]);n!=null&&l(e,["allowedFunctionNames"],n);let o=s(t,["mode"]);if(o!=null&&l(e,["mode"],o),s(t,["streamFunctionCallArguments"])!==void 0)throw new Error("streamFunctionCallArguments parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return e}function kv(t,e,n){let o={},i=s(e,["serviceTier"]);n!==void 0&&i!=null&&l(n,["serviceTier"],i);let r=s(e,["systemInstruction"]);n!==void 0&&r!=null&&l(n,["systemInstruction"],jf(ke(r)));let a=s(e,["temperature"]);a!=null&&l(o,["temperature"],a);let u=s(e,["topP"]);u!=null&&l(o,["topP"],u);let c=s(e,["topK"]);c!=null&&l(o,["topK"],c);let d=s(e,["candidateCount"]);d!=null&&l(o,["candidateCount"],d);let f=s(e,["maxOutputTokens"]);f!=null&&l(o,["maxOutputTokens"],f);let p=s(e,["stopSequences"]);p!=null&&l(o,["stopSequences"],p);let h=s(e,["responseLogprobs"]);h!=null&&l(o,["responseLogprobs"],h);let g=s(e,["logprobs"]);g!=null&&l(o,["logprobs"],g);let _=s(e,["presencePenalty"]);_!=null&&l(o,["presencePenalty"],_);let m=s(e,["frequencyPenalty"]);m!=null&&l(o,["frequencyPenalty"],m);let v=s(e,["seed"]);v!=null&&l(o,["seed"],v);let y=s(e,["responseMimeType"]);y!=null&&l(o,["responseMimeType"],y);let E=s(e,["responseSchema"]);E!=null&&l(o,["responseSchema"],ml(E));let A=s(e,["responseJsonSchema"]);if(A!=null&&l(o,["responseJsonSchema"],A),s(e,["routingConfig"])!==void 0)throw new Error("routingConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(e,["modelSelectionConfig"])!==void 0)throw new Error("modelSelectionConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let C=s(e,["safetySettings"]);if(n!==void 0&&C!=null){let ve=C;Array.isArray(ve)&&(ve=ve.map(fe=>Xv(fe))),l(n,["safetySettings"],ve)}let w=s(e,["tools"]);if(n!==void 0&&w!=null){let ve=Kt(w);Array.isArray(ve)&&(ve=ve.map(fe=>Kv(Jt(fe)))),l(n,["tools"],ve)}let N=s(e,["toolConfig"]);n!==void 0&&N!=null&&l(n,["toolConfig"],Jv(N));let q=s(e,["labels"]);n!==void 0&&q!=null&&l(n,["labels"],q);let V=s(e,["cachedContent"]);n!==void 0&&V!=null&&l(n,["cachedContent"],kt(t,V));let M=s(e,["responseModalities"]);M!=null&&l(o,["responseModalities"],M);let O=s(e,["mediaResolution"]);O!=null&&l(o,["mediaResolution"],O);let H=s(e,["speechConfig"]);if(H!=null&&l(o,["speechConfig"],gl(H)),s(e,["audioTimestamp"])!==void 0)throw new Error("audioTimestamp parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let $=s(e,["thinkingConfig"]);$!=null&&l(o,["thinkingConfig"],$);let j=s(e,["audioTranscriptionConfig"]);j!=null&&l(o,["audioTranscriptionConfig"],j);let D=s(e,["imageConfig"]);D!=null&&l(o,["imageConfig"],Gv(D));let Q=s(e,["enableEnhancedCivicAnswers"]);if(Q!=null&&l(o,["enableEnhancedCivicAnswers"],Q),s(e,["modelArmorConfig"])!==void 0)throw new Error("modelArmorConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let te=s(e,["continuationToken"]);if(n!==void 0&&te!=null&&l(n,["continuationToken"],te),s(e,["generationOutputConfig"])!==void 0)throw new Error("generationOutputConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let Ae=s(e,["store"]);return n!==void 0&&Ae!=null&&l(n,["store"],Ae),o}function Nv(t){let e={},n=s(t,["sdkHttpResponse"]);n!=null&&l(e,["sdkHttpResponse"],n);let o=s(t,["candidates"]);if(o!=null){let d=o;Array.isArray(d)&&(d=d.map(f=>pv(f))),l(e,["candidates"],d)}let i=s(t,["modelVersion"]);i!=null&&l(e,["modelVersion"],i);let r=s(t,["promptFeedback"]);r!=null&&l(e,["promptFeedback"],r);let a=s(t,["responseId"]);a!=null&&l(e,["responseId"],a);let u=s(t,["usageMetadata"]);u!=null&&l(e,["usageMetadata"],u);let c=s(t,["modelStatus"]);return c!=null&&l(e,["modelStatus"],c),e}function xv(t,e){let n={},o=s(e,["name"]);return o!=null&&l(n,["_url","name"],Sn(t,o)),n}function Dv(t,e){let n={},o=s(e,["name"]);return o!=null&&l(n,["_url","name"],Sn(t,o)),n}function Mv(t){let e={},n=s(t,["authConfig"]);n!=null&&l(e,["authConfig"],iv(n));let o=s(t,["enableWidget"]);if(o!=null&&l(e,["enableWidget"],o),s(t,["groundingTypes"])!==void 0)throw new Error("groundingTypes parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return e}function Uv(t){let e={};if(s(t,["blockingConfidence"])!==void 0)throw new Error("blockingConfidence parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["excludeDomains"])!==void 0)throw new Error("excludeDomains parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let n=s(t,["searchTypes"]);n!=null&&l(e,["searchTypes"],n);let o=s(t,["timeRangeFilter"]);return o!=null&&l(e,["timeRangeFilter"],o),e}function Gv(t){let e={},n=s(t,["aspectRatio"]);n!=null&&l(e,["aspectRatio"],n);let o=s(t,["imageSize"]);if(o!=null&&l(e,["imageSize"],o),s(t,["personGeneration"])!==void 0)throw new Error("personGeneration parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["outputMimeType"])!==void 0)throw new Error("outputMimeType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["outputCompressionQuality"])!==void 0)throw new Error("outputCompressionQuality parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["imageOutputOptions"])!==void 0)throw new Error("imageOutputOptions parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["prominentPeople"])!==void 0)throw new Error("prominentPeople parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return e}function bv(t,e){let n={},o=s(e,["model"]);o!=null&&l(n,["request","model"],ye(t,o));let i=s(e,["contents"]);if(i!=null){let u=Oe(i);Array.isArray(u)&&(u=u.map(c=>jf(c))),l(n,["request","contents"],u)}let r=s(e,["metadata"]);r!=null&&l(n,["metadata"],r);let a=s(e,["config"]);return a!=null&&l(n,["request","generationConfig"],kv(t,a,s(n,["request"],{}))),n}function Lv(t){let e={},n=s(t,["response"]);n!=null&&l(e,["response"],Nv(n));let o=s(t,["metadata"]);o!=null&&l(e,["metadata"],o);let i=s(t,["error"]);return i!=null&&l(e,["error"],i),e}function qv(t,e){let n={},o=s(t,["pageSize"]);e!==void 0&&o!=null&&l(e,["_query","pageSize"],o);let i=s(t,["pageToken"]);if(e!==void 0&&i!=null&&l(e,["_query","pageToken"],i),s(t,["filter"])!==void 0)throw new Error("filter parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return n}function Ov(t,e){let n={},o=s(t,["pageSize"]);e!==void 0&&o!=null&&l(e,["_query","pageSize"],o);let i=s(t,["pageToken"]);e!==void 0&&i!=null&&l(e,["_query","pageToken"],i);let r=s(t,["filter"]);return e!==void 0&&r!=null&&l(e,["_query","filter"],r),n}function Fv(t){let e={},n=s(t,["config"]);return n!=null&&qv(n,e),e}function Hv(t){let e={},n=s(t,["config"]);return n!=null&&Ov(n,e),e}function Vv(t){let e={},n=s(t,["sdkHttpResponse"]);n!=null&&l(e,["sdkHttpResponse"],n);let o=s(t,["nextPageToken"]);o!=null&&l(e,["nextPageToken"],o);let i=s(t,["operations"]);if(i!=null){let r=i;Array.isArray(r)&&(r=r.map(a=>Wo(a))),l(e,["batchJobs"],r)}return e}function Bv(t){let e={},n=s(t,["sdkHttpResponse"]);n!=null&&l(e,["sdkHttpResponse"],n);let o=s(t,["nextPageToken"]);o!=null&&l(e,["nextPageToken"],o);let i=s(t,["batchPredictionJobs"]);if(i!=null){let r=i;Array.isArray(r)&&(r=r.map(a=>ea(a))),l(e,["batchJobs"],r)}return e}function $v(t){let e={},n=s(t,["mediaResolution"]);n!=null&&l(e,["mediaResolution"],n);let o=s(t,["toolCall"]);o!=null&&l(e,["toolCall"],o);let i=s(t,["toolResponse"]);i!=null&&l(e,["toolResponse"],i);let r=s(t,["audioTranscription"]);r!=null&&l(e,["audioTranscription"],r);let a=s(t,["codeExecutionResult"]);a!=null&&l(e,["codeExecutionResult"],a);let u=s(t,["executableCode"]);u!=null&&l(e,["executableCode"],u);let c=s(t,["fileData"]);c!=null&&l(e,["fileData"],c);let d=s(t,["functionCall"]);d!=null&&l(e,["functionCall"],Rv(d));let f=s(t,["functionResponse"]);f!=null&&l(e,["functionResponse"],f);let p=s(t,["inlineData"]);p!=null&&l(e,["inlineData"],p);let h=s(t,["text"]);h!=null&&l(e,["text"],h);let g=s(t,["thought"]);g!=null&&l(e,["thought"],g);let _=s(t,["thoughtSignature"]);_!=null&&l(e,["thoughtSignature"],_);let m=s(t,["videoMetadata"]);m!=null&&l(e,["videoMetadata"],m);let v=s(t,["partMetadata"]);v!=null&&l(e,["partMetadata"],v);let y=s(t,["mediaProcessing"]);y!=null&&l(e,["mediaProcessing"],y);let E=s(t,["speechMetadata"]);return E!=null&&l(e,["speechMetadata"],E),e}function Xv(t){let e={},n=s(t,["category"]);if(n!=null&&l(e,["category"],n),s(t,["method"])!==void 0)throw new Error("method parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let o=s(t,["threshold"]);return o!=null&&l(e,["threshold"],o),e}function Jv(t){let e={},n=s(t,["functionCallingConfig"]);n!=null&&l(e,["functionCallingConfig"],Pv(n));let o=s(t,["retrievalConfig"]);o!=null&&l(e,["retrievalConfig"],o);let i=s(t,["includeServerSideToolInvocations"]);return i!=null&&l(e,["includeServerSideToolInvocations"],i),e}function Kv(t){let e={};if(s(t,["retrieval"])!==void 0)throw new Error("retrieval parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let n=s(t,["googleMaps"]);n!=null&&l(e,["googleMaps"],Mv(n));let o=s(t,["mcpServers"]);if(o!=null){let p=o;Array.isArray(p)&&(p=p.map(h=>h)),l(e,["mcpServers"],p)}let i=s(t,["codeExecution"]);i!=null&&l(e,["codeExecution"],i);let r=s(t,["computerUse"]);if(r!=null&&l(e,["computerUse"],r),s(t,["enterpriseWebSearch"])!==void 0)throw new Error("enterpriseWebSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["exaAiSearch"])!==void 0)throw new Error("exaAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let a=s(t,["functionDeclarations"]);if(a!=null){let p=a;Array.isArray(p)&&(p=p.map(h=>h)),l(e,["functionDeclarations"],p)}let u=s(t,["googleSearch"]);u!=null&&l(e,["googleSearch"],Uv(u));let c=s(t,["googleSearchRetrieval"]);if(c!=null&&l(e,["googleSearchRetrieval"],c),s(t,["parallelAiSearch"])!==void 0)throw new Error("parallelAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let d=s(t,["urlContext"]);d!=null&&l(e,["urlContext"],d);let f=s(t,["fileSearch"]);return f!=null&&l(e,["fileSearch"],f),e}function Yv(t){let e={},n=s(t,["bigqueryDestination","outputUri"]);n!=null&&l(e,["bigqueryDestination"],n);let o=s(t,["displayName"]);return o!=null&&l(e,["displayName"],o),e}function Wv(t){let e={},n=s(t,["bigqueryDestination"]);n!=null&&l(e,["bigqueryDestination","outputUri"],n);let o=s(t,["displayName"]);return o!=null&&l(e,["displayName"],o),e}var Rt;(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",t.PAGED_ITEM_SKILLS="skills"})(Rt||(Rt={}));var Pt=class{constructor(e,n,o,i){this.pageInternal=[],this.paramsInternal={},this.requestInternal=n,this.init(e,o,i)}init(e,n,o){var i,r;this.nameInternal=e,this.pageInternal=n[this.nameInternal]||[],this.sdkHttpResponseInternal=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=(r=(i=a.config)===null||i===void 0?void 0:i.pageSize)!==null&&r!==void 0?r: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};let 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.");let 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}};var ta=class extends dt{constructor(e){super(),this.apiClient=e,this.list=async(n={})=>new Pt(Rt.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("Gemini Enterprise Agent Platform (previously known as Vertex AI) does not support batches.createEmbeddings.");return this.createEmbeddingsInternal(n)}}createInlinedGenerateContentRequest(e){let n=Yd(this.apiClient,e),o=n._url,i=X("{model}:batchGenerateContent",o),u=n.batch.inputConfig.requests,c=u.requests,d=[];for(let f of c){let p=Object.assign({},f);if(p.systemInstruction){let h=p.systemInstruction;delete p.systemInstruction;let g=p.request;g.systemInstruction=h,p.request=g}d.push(p)}return u.requests=d,delete n.config,delete n._url,delete n._query,{path:i,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){let o=n?Object.assign({},n):{},i=Date.now().toString();if(o.displayName||(o.displayName=`genaiBatchJob_${i}`),o.dest===void 0){let r=this.getGcsUri(e),a=this.getBigqueryUri(e);if(r)r.endsWith(".jsonl")?o.dest=`${r.slice(0,-6)}/dest`:o.dest=`${r}_dest_${i}`;else if(a)o.dest=`${a}_dest_${i}`;else throw new Error("Unsupported source for Gemini Enterprise Agent Platform (previously known as Vertex AI): No GCS or BigQuery URI found.")}return o}async createInternal(e){var n,o,i,r;let a,u="",c={};if(this.apiClient.isVertexAI()){let d=_v(this.apiClient,e);return u=X("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=>ea(f))}else{let d=Yd(this.apiClient,e);return u=X("{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:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(f=>f.json()),a.then(f=>Wo(f))}}async createEmbeddingsInternal(e){var n,o;let i,r="",a={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let u=vv(this.apiClient,e);return r=X("{model}:asyncBatchEmbedContent",u._url),a=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:r,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()),i.then(c=>Wo(c))}}async get(e){var n,o,i,r;let a,u="",c={};if(this.apiClient.isVertexAI()){let d=Dv(this.apiClient,e);return u=X("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=>ea(f))}else{let d=xv(this.apiClient,e);return u=X("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:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(f=>f.json()),a.then(f=>Wo(f))}}async cancel(e){var n,o,i,r;let a="",u={};if(this.apiClient.isVertexAI()){let c=fv(this.apiClient,e);a=X("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{let c=dv(this.apiClient,e);a=X("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:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal})}}async listInternal(e){var n,o,i,r;let a,u="",c={};if(this.apiClient.isVertexAI()){let d=Hv(e);return u=X("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(p=>{let h=p;return h.sdkHttpResponse={headers:f.headers},h})),a.then(f=>{let p=Bv(f),h=new li;return Object.assign(h,p),h})}else{let d=Fv(e);return u=X("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:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(f=>f.json().then(p=>{let h=p;return h.sdkHttpResponse={headers:f.headers},h})),a.then(f=>{let p=Vv(f),h=new li;return Object.assign(h,p),h})}}async delete(e){var n,o,i,r;let a,u="",c={};if(this.apiClient.isVertexAI()){let d=Tv(this.apiClient,e);return u=X("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(p=>{let h=p;return h.sdkHttpResponse={headers:f.headers},h})),a.then(f=>Cv(f))}else{let d=Ev(this.apiClient,e);return u=X("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:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(f=>f.json().then(p=>{let h=p;return h.sdkHttpResponse={headers:f.headers},h})),a.then(f=>Av(f))}}};function zv(t){let e={},n=s(t,["apiKey"]);if(n!=null&&l(e,["apiKey"],n),s(t,["apiKeyConfig"])!==void 0)throw new Error("apiKeyConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["authType"])!==void 0)throw new Error("authType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["googleServiceAccountConfig"])!==void 0)throw new Error("googleServiceAccountConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["httpBasicAuthConfig"])!==void 0)throw new Error("httpBasicAuthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["oauthConfig"])!==void 0)throw new Error("oauthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["oidcConfig"])!==void 0)throw new Error("oidcConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return e}function Wd(t){let e={},n=s(t,["parts"]);if(n!=null){let i=n;Array.isArray(i)&&(i=i.map(r=>EE(r))),l(e,["parts"],i)}let o=s(t,["role"]);return o!=null&&l(e,["role"],o),e}function zd(t){let e={},n=s(t,["parts"]);if(n!=null){let i=n;Array.isArray(i)&&(i=i.map(r=>TE(r))),l(e,["parts"],i)}let o=s(t,["role"]);return o!=null&&l(e,["role"],o),e}function Qv(t,e){let n={},o=s(t,["ttl"]);e!==void 0&&o!=null&&l(e,["ttl"],o);let i=s(t,["expireTime"]);e!==void 0&&i!=null&&l(e,["expireTime"],i);let r=s(t,["displayName"]);e!==void 0&&r!=null&&l(e,["displayName"],r);let a=s(t,["contents"]);if(e!==void 0&&a!=null){let f=Oe(a);Array.isArray(f)&&(f=f.map(p=>Wd(p))),l(e,["contents"],f)}let u=s(t,["systemInstruction"]);e!==void 0&&u!=null&&l(e,["systemInstruction"],Wd(ke(u)));let c=s(t,["tools"]);if(e!==void 0&&c!=null){let f=c;Array.isArray(f)&&(f=f.map(p=>IE(p))),l(e,["tools"],f)}let d=s(t,["toolConfig"]);if(e!==void 0&&d!=null&&l(e,["toolConfig"],AE(d)),s(t,["kmsKeyName"])!==void 0)throw new Error("kmsKeyName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return n}function Zv(t,e){let n={},o=s(t,["ttl"]);e!==void 0&&o!=null&&l(e,["ttl"],o);let i=s(t,["expireTime"]);e!==void 0&&i!=null&&l(e,["expireTime"],i);let r=s(t,["displayName"]);e!==void 0&&r!=null&&l(e,["displayName"],r);let a=s(t,["contents"]);if(e!==void 0&&a!=null){let p=Oe(a);Array.isArray(p)&&(p=p.map(h=>zd(h))),l(e,["contents"],p)}let u=s(t,["systemInstruction"]);e!==void 0&&u!=null&&l(e,["systemInstruction"],zd(ke(u)));let c=s(t,["tools"]);if(e!==void 0&&c!=null){let p=c;Array.isArray(p)&&(p=p.map(h=>SE(h))),l(e,["tools"],p)}let d=s(t,["toolConfig"]);e!==void 0&&d!=null&&l(e,["toolConfig"],CE(d));let f=s(t,["kmsKeyName"]);return e!==void 0&&f!=null&&l(e,["encryption_spec","kmsKeyName"],f),n}function jv(t,e){let n={},o=s(e,["model"]);o!=null&&l(n,["model"],Ff(t,o));let i=s(e,["config"]);return i!=null&&Qv(i,n),n}function eE(t,e){let n={},o=s(e,["model"]);o!=null&&l(n,["model"],Ff(t,o));let i=s(e,["config"]);return i!=null&&Zv(i,n),n}function tE(t,e){let n={},o=s(e,["name"]);return o!=null&&l(n,["_url","name"],kt(t,o)),n}function nE(t,e){let n={},o=s(e,["name"]);return o!=null&&l(n,["_url","name"],kt(t,o)),n}function oE(t){let e={},n=s(t,["sdkHttpResponse"]);return n!=null&&l(e,["sdkHttpResponse"],n),e}function iE(t){let e={},n=s(t,["sdkHttpResponse"]);return n!=null&&l(e,["sdkHttpResponse"],n),e}function rE(t){let e={},n=s(t,["args"]);n!=null&&l(e,["args"],n);let o=s(t,["id"]);o!=null&&l(e,["id"],o);let i=s(t,["name"]);if(i!=null&&l(e,["name"],i),s(t,["partialArgs"])!==void 0)throw new Error("partialArgs parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["willContinue"])!==void 0)throw new Error("willContinue parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return e}function sE(t){let e={},n=s(t,["allowedFunctionNames"]);n!=null&&l(e,["allowedFunctionNames"],n);let o=s(t,["mode"]);if(o!=null&&l(e,["mode"],o),s(t,["streamFunctionCallArguments"])!==void 0)throw new Error("streamFunctionCallArguments parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return e}function aE(t){let e={},n=s(t,["fileData"]);n!=null&&l(e,["fileData"],n);let o=s(t,["inlineData"]);if(o!=null&&l(e,["inlineData"],o),s(t,["mediaProcessing"])!==void 0)throw new Error("mediaProcessing parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return e}function lE(t){let e={},n=s(t,["id"]);n!=null&&l(e,["id"],n);let o=s(t,["name"]);o!=null&&l(e,["name"],o);let i=s(t,["parts"]);if(i!=null){let u=i;Array.isArray(u)&&(u=u.map(c=>aE(c))),l(e,["parts"],u)}let r=s(t,["response"]);r!=null&&l(e,["response"],r);let a=s(t,["scheduling"]);if(a!=null&&l(e,["scheduling"],a),s(t,["willContinue"])!==void 0)throw new Error("willContinue parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return e}function uE(t,e){let n={},o=s(e,["name"]);return o!=null&&l(n,["_url","name"],kt(t,o)),n}function cE(t,e){let n={},o=s(e,["name"]);return o!=null&&l(n,["_url","name"],kt(t,o)),n}function dE(t){let e={},n=s(t,["authConfig"]);n!=null&&l(e,["authConfig"],zv(n));let o=s(t,["enableWidget"]);if(o!=null&&l(e,["enableWidget"],o),s(t,["groundingTypes"])!==void 0)throw new Error("groundingTypes parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return e}function fE(t){let e={};if(s(t,["blockingConfidence"])!==void 0)throw new Error("blockingConfidence parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["excludeDomains"])!==void 0)throw new Error("excludeDomains parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let n=s(t,["searchTypes"]);n!=null&&l(e,["searchTypes"],n);let o=s(t,["timeRangeFilter"]);return o!=null&&l(e,["timeRangeFilter"],o),e}function pE(t,e){let n={},o=s(t,["pageSize"]);e!==void 0&&o!=null&&l(e,["_query","pageSize"],o);let i=s(t,["pageToken"]);return e!==void 0&&i!=null&&l(e,["_query","pageToken"],i),n}function hE(t,e){let n={},o=s(t,["pageSize"]);e!==void 0&&o!=null&&l(e,["_query","pageSize"],o);let i=s(t,["pageToken"]);return e!==void 0&&i!=null&&l(e,["_query","pageToken"],i),n}function mE(t){let e={},n=s(t,["config"]);return n!=null&&pE(n,e),e}function gE(t){let e={},n=s(t,["config"]);return n!=null&&hE(n,e),e}function _E(t){let e={},n=s(t,["sdkHttpResponse"]);n!=null&&l(e,["sdkHttpResponse"],n);let o=s(t,["nextPageToken"]);o!=null&&l(e,["nextPageToken"],o);let i=s(t,["cachedContents"]);if(i!=null){let r=i;Array.isArray(r)&&(r=r.map(a=>a)),l(e,["cachedContents"],r)}return e}function yE(t){let e={},n=s(t,["sdkHttpResponse"]);n!=null&&l(e,["sdkHttpResponse"],n);let o=s(t,["nextPageToken"]);o!=null&&l(e,["nextPageToken"],o);let i=s(t,["cachedContents"]);if(i!=null){let r=i;Array.isArray(r)&&(r=r.map(a=>a)),l(e,["cachedContents"],r)}return e}function vE(t){let e={};if(s(t,["name"])!==void 0)throw new Error("name parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(s(t,["streamableHttpTransport"])!==void 0)throw new Error("streamableHttpTransport parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return e}function EE(t){let e={},n=s(t,["mediaResolution"]);n!=null&&l(e,["mediaResolution"],n);let o=s(t,["toolCall"]);o!=null&&l(e,["toolCall"],o);let i=s(t,["toolResponse"]);i!=null&&l(e,["toolResponse"],i);let r=s(t,["audioTranscription"]);r!=null&&l(e,["audioTranscription"],r);let a=s(t,["codeExecutionResult"]);a!=null&&l(e,["codeExecutionResult"],a);let u=s(t,["executableCode"]);u!=null&&l(e,["executableCode"],u);let c=s(t,["fileData"]);c!=null&&l(e,["fileData"],c);let d=s(t,["functionCall"]);d!=null&&l(e,["functionCall"],rE(d));let f=s(t,["functionResponse"]);f!=null&&l(e,["functionResponse"],f);let p=s(t,["inlineData"]);p!=null&&l(e,["inlineData"],p);let h=s(t,["text"]);h!=null&&l(e,["text"],h);let g=s(t,["thought"]);g!=null&&l(e,["thought"],g);let _=s(t,["thoughtSignature"]);_!=null&&l(e,["thoughtSignature"],_);let m=s(t,["videoMetadata"]);m!=null&&l(e,["videoMetadata"],m);let v=s(t,["partMetadata"]);v!=null&&l(e,["partMetadata"],v);let y=s(t,["mediaProcessing"]);y!=null&&l(e,["mediaProcessing"],y);let E=s(t,["speechMetadata"]);return E!=null&&l(e,["speechMetadata"],E),e}function TE(t){let e={},n=s(t,["mediaResolution"]);if(n!=null&&l(e,["mediaResolution"],n),s(t,["toolCall"])!==void 0)throw new Error("toolCall parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(s(t,["toolResponse"])!==void 0)throw new Error("toolResponse parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");let o=s(t,["audioTranscription"]);o!=null&&l(e,["audioTranscription"],o);let i=s(t,["codeExecutionResult"]);i!=null&&l(e,["codeExecutionResult"],i);let r=s(t,["executableCode"]);r!=null&&l(e,["executableCode"],r);let a=s(t,["fileData"]);a!=null&&l(e,["fileData"],a);let u=s(t,["functionCall"]);u!=null&&l(e,["functionCall"],u);let c=s(t,["functionResponse"]);c!=null&&l(e,["functionResponse"],lE(c));let d=s(t,["inlineData"]);d!=null&&l(e,["inlineData"],d);let f=s(t,["text"]);f!=null&&l(e,["text"],f);let p=s(t,["thought"]);p!=null&&l(e,["thought"],p);let h=s(t,["thoughtSignature"]);h!=null&&l(e,["thoughtSignature"],h);let g=s(t,["videoMetadata"]);if(g!=null&&l(e,["videoMetadata"],g),s(t,["partMetadata"])!==void 0)throw new Error("partMetadata parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");let _=s(t,["mediaProcessing"]);_!=null&&l(e,["mediaProcessing"],_);let m=s(t,["speechMetadata"]);return m!=null&&l(e,["speechMetadata"],m),e}function AE(t){let e={},n=s(t,["functionCallingConfig"]);n!=null&&l(e,["functionCallingConfig"],sE(n));let o=s(t,["retrievalConfig"]);o!=null&&l(e,["retrievalConfig"],o);let i=s(t,["includeServerSideToolInvocations"]);return i!=null&&l(e,["includeServerSideToolInvocations"],i),e}function CE(t){let e={},n=s(t,["functionCallingConfig"]);n!=null&&l(e,["functionCallingConfig"],n);let o=s(t,["retrievalConfig"]);if(o!=null&&l(e,["retrievalConfig"],o),s(t,["includeServerSideToolInvocations"])!==void 0)throw new Error("includeServerSideToolInvocations parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return e}function IE(t){let e={};if(s(t,["retrieval"])!==void 0)throw new Error("retrieval parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let n=s(t,["googleMaps"]);n!=null&&l(e,["googleMaps"],dE(n));let o=s(t,["mcpServers"]);if(o!=null){let p=o;Array.isArray(p)&&(p=p.map(h=>h)),l(e,["mcpServers"],p)}let i=s(t,["codeExecution"]);i!=null&&l(e,["codeExecution"],i);let r=s(t,["computerUse"]);if(r!=null&&l(e,["computerUse"],r),s(t,["enterpriseWebSearch"])!==void 0)throw new Error("enterpriseWebSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["exaAiSearch"])!==void 0)throw new Error("exaAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let a=s(t,["functionDeclarations"]);if(a!=null){let p=a;Array.isArray(p)&&(p=p.map(h=>h)),l(e,["functionDeclarations"],p)}let u=s(t,["googleSearch"]);u!=null&&l(e,["googleSearch"],fE(u));let c=s(t,["googleSearchRetrieval"]);if(c!=null&&l(e,["googleSearchRetrieval"],c),s(t,["parallelAiSearch"])!==void 0)throw new Error("parallelAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let d=s(t,["urlContext"]);d!=null&&l(e,["urlContext"],d);let f=s(t,["fileSearch"]);return f!=null&&l(e,["fileSearch"],f),e}function SE(t){let e={},n=s(t,["retrieval"]);n!=null&&l(e,["retrieval"],n);let o=s(t,["googleMaps"]);o!=null&&l(e,["googleMaps"],o);let i=s(t,["mcpServers"]);if(i!=null){let _=i;Array.isArray(_)&&(_=_.map(m=>vE(m))),l(e,["mcpServers"],_)}let r=s(t,["codeExecution"]);r!=null&&l(e,["codeExecution"],r);let a=s(t,["computerUse"]);a!=null&&l(e,["computerUse"],a);let u=s(t,["enterpriseWebSearch"]);u!=null&&l(e,["enterpriseWebSearch"],u);let c=s(t,["exaAiSearch"]);c!=null&&l(e,["exaAiSearch"],c);let d=s(t,["functionDeclarations"]);if(d!=null){let _=d;Array.isArray(_)&&(_=_.map(m=>m)),l(e,["functionDeclarations"],_)}let f=s(t,["googleSearch"]);f!=null&&l(e,["googleSearch"],f);let p=s(t,["googleSearchRetrieval"]);p!=null&&l(e,["googleSearchRetrieval"],p);let h=s(t,["parallelAiSearch"]);h!=null&&l(e,["parallelAiSearch"],h);let g=s(t,["urlContext"]);if(g!=null&&l(e,["urlContext"],g),s(t,["fileSearch"])!==void 0)throw new Error("fileSearch parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return e}function wE(t,e){let n={},o=s(t,["ttl"]);e!==void 0&&o!=null&&l(e,["ttl"],o);let i=s(t,["expireTime"]);return e!==void 0&&i!=null&&l(e,["expireTime"],i),n}function RE(t,e){let n={},o=s(t,["ttl"]);e!==void 0&&o!=null&&l(e,["ttl"],o);let i=s(t,["expireTime"]);return e!==void 0&&i!=null&&l(e,["expireTime"],i),n}function PE(t,e){let n={},o=s(e,["name"]);o!=null&&l(n,["_url","name"],kt(t,o));let i=s(e,["config"]);return i!=null&&wE(i,n),n}function kE(t,e){let n={},o=s(e,["name"]);o!=null&&l(n,["_url","name"],kt(t,o));let i=s(e,["config"]);return i!=null&&RE(i,n),n}var na=class extends dt{constructor(e){super(),this.apiClient=e,this.list=async(n={})=>new Pt(Rt.PAGED_ITEM_CACHED_CONTENTS,o=>this.listInternal(o),await this.listInternal(n),n)}async create(e){var n,o,i,r;let a,u="",c={};if(this.apiClient.isVertexAI()){let d=eE(this.apiClient,e);return u=X("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{let d=jv(this.apiClient,e);return u=X("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:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(f=>f.json()),a.then(f=>f)}}async get(e){var n,o,i,r;let a,u="",c={};if(this.apiClient.isVertexAI()){let d=cE(this.apiClient,e);return u=X("{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{let d=uE(this.apiClient,e);return u=X("{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:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(f=>f.json()),a.then(f=>f)}}async delete(e){var n,o,i,r;let a,u="",c={};if(this.apiClient.isVertexAI()){let d=nE(this.apiClient,e);return u=X("{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(p=>{let h=p;return h.sdkHttpResponse={headers:f.headers},h})),a.then(f=>{let p=iE(f),h=new si;return Object.assign(h,p),h})}else{let d=tE(this.apiClient,e);return u=X("{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:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(f=>f.json().then(p=>{let h=p;return h.sdkHttpResponse={headers:f.headers},h})),a.then(f=>{let p=oE(f),h=new si;return Object.assign(h,p),h})}}async update(e){var n,o,i,r;let a,u="",c={};if(this.apiClient.isVertexAI()){let d=kE(this.apiClient,e);return u=X("{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{let d=PE(this.apiClient,e);return u=X("{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:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(f=>f.json()),a.then(f=>f)}}async listInternal(e){var n,o,i,r;let a,u="",c={};if(this.apiClient.isVertexAI()){let d=gE(e);return u=X("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(p=>{let h=p;return h.sdkHttpResponse={headers:f.headers},h})),a.then(f=>{let p=yE(f),h=new ai;return Object.assign(h,p),h})}else{let d=mE(e);return u=X("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:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(f=>f.json().then(p=>{let h=p;return h.sdkHttpResponse={headers:f.headers},h})),a.then(f=>{let p=_E(f),h=new ai;return Object.assign(h,p),h})}}};function Ie(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 i=0,o=Object.getOwnPropertySymbols(t);i<o.length;i++)e.indexOf(o[i])<0&&Object.prototype.propertyIsEnumerable.call(t,o[i])&&(n[o[i]]=t[o[i]]);return n}function Qd(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 re(t){return this instanceof re?(this.v=t,this):new re(t)}function St(t,e,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var o=n.apply(t,e||[]),i,r=[];return i=Object.create((typeof AsyncIterator=="function"?AsyncIterator:Object).prototype),u("next"),u("throw"),u("return",a),i[Symbol.asyncIterator]=function(){return this},i;function a(g){return function(_){return Promise.resolve(_).then(g,p)}}function u(g,_){o[g]&&(i[g]=function(m){return new Promise(function(v,y){r.push([g,m,v,y])>1||c(g,m)})},_&&(i[g]=_(i[g])))}function c(g,_){try{d(o[g](_))}catch(m){h(r[0][3],m)}}function d(g){g.value instanceof re?Promise.resolve(g.value.v).then(f,p):h(r[0][2],g)}function f(g){c("next",g)}function p(g){c("throw",g)}function h(g,_){g(_),r.shift(),r.length&&c(r[0][0],r[0][1])}}function jt(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 Qd=="function"?Qd(t):t[Symbol.iterator](),n={},o("next"),o("throw"),o("return"),n[Symbol.asyncIterator]=function(){return this},n);function o(r){n[r]=t[r]&&function(a){return new Promise(function(u,c){a=t[r](a),i(u,c,a.done,a.value)})}}function i(r,a,u,c){Promise.resolve(c).then(function(d){r({value:d,done:u})},a)}}function NE(t){var e;if(t.candidates==null||t.candidates.length===0)return!1;let n=(e=t.candidates[0])===null||e===void 0?void 0:e.content;return n===void 0?!1:ep(n)}function ep(t){if(t.parts===void 0||t.parts.length===0)return!1;for(let e of t.parts)if(e===void 0||Object.keys(e).length===0)return!1;return!0}function xE(t){if(t.length!==0){for(let e of t)if(e.role!=="user"&&e.role!=="model")throw new Error(`Role must be user or model, but got ${e.role}.`)}}function Zd(t){if(t===void 0||t.length===0)return[];let e=[],n=t.length,o=0;for(;o<n;)if(t[o].role==="user")e.push(t[o]),o++;else{let i=[],r=!0;for(;o<n&&t[o].role==="model";)i.push(t[o]),r&&!ep(t[o])&&(r=!1),o++;r?e.push(...i):e.pop()}return e}var oa=class{constructor(e,n){this.modelsModule=e,this.apiClient=n}create(e){return new ia(this.apiClient,this.modelsModule,e.model,e.config,structuredClone(e.history))}},ia=class{constructor(e,n,o,i={},r=[]){this.apiClient=e,this.modelsModule=n,this.model=o,this.config=i,this.history=r,this.sendPromise=Promise.resolve(),xE(r)}async sendMessage(e){var n;await this.sendPromise;let o=ke(e.message),i=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 r,a,u;let c=await i,d=(a=(r=c.candidates)===null||r===void 0?void 0:r[0])===null||a===void 0?void 0:a.content,f=c.automaticFunctionCallingHistory,p=this.getHistory(!0).length,h=[];f!=null&&(h=(u=f.slice(p))!==null&&u!==void 0?u:[]);let g=d?[d]:[];this.recordHistory(o,g,h)})(),await this.sendPromise.catch(()=>{this.sendPromise=Promise.resolve()}),i}async sendMessageStream(e){var n;await this.sendPromise;let o=ke(e.message),i=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=i.then(()=>{}).catch(()=>{});let r=await i;return this.processStreamResponse(r,o)}getHistory(e=!1){let n=e?Zd(this.history):this.history;return structuredClone(n)}processStreamResponse(e,n){return St(this,arguments,function*(){var i,r,a,u,c,d,f,p;let h=[],g=!0,_=!1;try{for(var m=!0,v=jt(e),y;y=yield re(v.next()),i=y.done,!i;m=!0){u=y.value,m=!1;let E=u;if(NE(E)){let A=(d=(c=E.candidates)===null||c===void 0?void 0:c[0])===null||d===void 0?void 0:d.content;A!==void 0&&h.push(A)}else g=!1;((p=(f=E.candidates)===null||f===void 0?void 0:f[0])===null||p===void 0?void 0:p.finishReason)!==void 0&&(_=!0),yield yield re(E)}}catch(E){r={error:E}}finally{try{!m&&!i&&(a=v.return)&&(yield re(a.call(v)))}finally{if(r)throw r.error}}this.recordHistory(n,g&&_?h:[])})}recordHistory(e,n,o){let i=[];n.length>0&&n.every(r=>r.role!==void 0)?i=n:i.push({role:"model",parts:[]}),o&&o.length>0?this.history.push(...Zd(o)):this.history.push(e),this.history.push(...i)}};var Xn=class t extends Error{constructor(e){super(e.message),this.name="ApiError",this.status=e.status,Object.setPrototypeOf(this,t.prototype)}},di=class t extends Error{constructor(e){var n;super(e.message,{cause:e.cause}),this.name="ContinuationInterruptedError",typeof this.cause>"u"&&(this.cause=e.cause),this.partialInteraction=e.partialInteraction,this.continuationToken=e.continuationToken,this.interactionId=e.interactionId,this.continuationIds=[...(n=e.continuationIds)!==null&&n!==void 0?n:[]],Object.setPrototypeOf(this,t.prototype)}};function DE(t){let e={},n=s(t,["file"]);return n!=null&&l(e,["file"],n),e}function ME(t){let e={},n=s(t,["sdkHttpResponse"]);return n!=null&&l(e,["sdkHttpResponse"],n),e}function UE(t){let e={},n=s(t,["name"]);return n!=null&&l(e,["_url","file"],yl(n)),e}function GE(t){let e={},n=s(t,["sdkHttpResponse"]);return n!=null&&l(e,["sdkHttpResponse"],n),e}function bE(t){let e={},n=s(t,["name"]);return n!=null&&l(e,["_url","file"],yl(n)),e}function LE(t){let e={},n=s(t,["uris"]);return n!=null&&l(e,["uris"],n),e}function qE(t,e){let n={},o=s(t,["pageSize"]);e!==void 0&&o!=null&&l(e,["_query","pageSize"],o);let i=s(t,["pageToken"]);return e!==void 0&&i!=null&&l(e,["_query","pageToken"],i),n}function OE(t){let e={},n=s(t,["config"]);return n!=null&&qE(n,e),e}function FE(t){let e={},n=s(t,["sdkHttpResponse"]);n!=null&&l(e,["sdkHttpResponse"],n);let o=s(t,["nextPageToken"]);o!=null&&l(e,["nextPageToken"],o);let i=s(t,["files"]);if(i!=null){let r=i;Array.isArray(r)&&(r=r.map(a=>a)),l(e,["files"],r)}return e}function HE(t){let e={},n=s(t,["sdkHttpResponse"]);n!=null&&l(e,["sdkHttpResponse"],n);let o=s(t,["files"]);if(o!=null){let i=o;Array.isArray(i)&&(i=i.map(r=>r)),l(e,["files"],i)}return e}var VE=class extends dt{constructor(e){super(),this.apiClient=e,this.list=async(n={})=>new Pt(Rt.PAGED_ITEM_FILES,o=>this.listInternal(o),await this.listInternal(n),n)}async upload(e){if(this.apiClient.isVertexAI())throw new Error("Gemini Enterprise Agent Platform (previously known as 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 registerFiles(e){throw new Error("registerFiles is only supported in Node.js environments.")}async _registerFiles(e){return this.registerFilesInternal(e)}async listInternal(e){var n,o;let i,r="",a={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let u=OE(e);return r=X("files",u._url),a=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:r,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=>{let f=d;return f.sdkHttpResponse={headers:c.headers},f})),i.then(c=>{let d=FE(c),f=new Ks;return Object.assign(f,d),f})}}async createInternal(e){var n,o;let i,r="",a={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let u=DE(e);return r=X("upload/v1beta/files",u._url),a=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:r,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()),i.then(c=>{let d=ME(c),f=new Ys;return Object.assign(f,d),f})}}async get(e){var n,o;let i,r="",a={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let u=bE(e);return r=X("files/{file}",u._url),a=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:r,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()),i.then(c=>c)}}async delete(e){var n,o;let i,r="",a={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let u=UE(e);return r=X("files/{file}",u._url),a=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:r,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=>{let f=d;return f.sdkHttpResponse={headers:c.headers},f})),i.then(c=>{let d=GE(c),f=new Ws;return Object.assign(f,d),f})}}async registerFilesInternal(e){var n,o;let i,r="",a={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let u=LE(e);return r=X("files:register",u._url),a=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:r,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()),i.then(c=>{let d=HE(c),f=new zs;return Object.assign(f,d),f})}}};function BE(t){let e={},n=s(t,["apiKey"]);if(n!=null&&l(e,["apiKey"],n),s(t,["apiKeyConfig"])!==void 0)throw new Error("apiKeyConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["authType"])!==void 0)throw new Error("authType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["googleServiceAccountConfig"])!==void 0)throw new Error("googleServiceAccountConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["httpBasicAuthConfig"])!==void 0)throw new Error("httpBasicAuthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["oauthConfig"])!==void 0)throw new Error("oauthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["oidcConfig"])!==void 0)throw new Error("oidcConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return e}function tp(t){let e={},n=s(t,["parts"]);if(n!=null){let i=n;Array.isArray(i)&&(i=i.map(r=>dT(r))),l(e,["parts"],i)}let o=s(t,["role"]);return o!=null&&l(e,["role"],o),e}function np(t){let e={},n=s(t,["parts"]);if(n!=null){let i=n;Array.isArray(i)&&(i=i.map(r=>fT(r))),l(e,["parts"],i)}let o=s(t,["role"]);return o!=null&&l(e,["role"],o),e}function $E(t){let e={},n=s(t,["args"]);n!=null&&l(e,["args"],n);let o=s(t,["id"]);o!=null&&l(e,["id"],o);let i=s(t,["name"]);if(i!=null&&l(e,["name"],i),s(t,["partialArgs"])!==void 0)throw new Error("partialArgs parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["willContinue"])!==void 0)throw new Error("willContinue parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return e}function XE(t){let e={},n=s(t,["fileData"]);n!=null&&l(e,["fileData"],n);let o=s(t,["inlineData"]);if(o!=null&&l(e,["inlineData"],o),s(t,["mediaProcessing"])!==void 0)throw new Error("mediaProcessing parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return e}function JE(t){let e={},n=s(t,["id"]);n!=null&&l(e,["id"],n);let o=s(t,["name"]);o!=null&&l(e,["name"],o);let i=s(t,["parts"]);if(i!=null){let u=i;Array.isArray(u)&&(u=u.map(c=>XE(c))),l(e,["parts"],u)}let r=s(t,["response"]);r!=null&&l(e,["response"],r);let a=s(t,["scheduling"]);if(a!=null&&l(e,["scheduling"],a),s(t,["willContinue"])!==void 0)throw new Error("willContinue parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return e}function KE(t){let e={},n=s(t,["modelSelectionConfig"]);n!=null&&l(e,["modelConfig"],n);let o=s(t,["responseJsonSchema"]);o!=null&&l(e,["responseJsonSchema"],o);let i=s(t,["audioTranscriptionConfig"]);i!=null&&l(e,["audioTranscriptionConfig"],i);let r=s(t,["audioTimestamp"]);r!=null&&l(e,["audioTimestamp"],r);let a=s(t,["candidateCount"]);a!=null&&l(e,["candidateCount"],a);let u=s(t,["enableAffectiveDialog"]);u!=null&&l(e,["enableAffectiveDialog"],u);let c=s(t,["frequencyPenalty"]);c!=null&&l(e,["frequencyPenalty"],c);let d=s(t,["logprobs"]);d!=null&&l(e,["logprobs"],d);let f=s(t,["maxOutputTokens"]);f!=null&&l(e,["maxOutputTokens"],f);let p=s(t,["mediaResolution"]);p!=null&&l(e,["mediaResolution"],p);let h=s(t,["presencePenalty"]);h!=null&&l(e,["presencePenalty"],h);let g=s(t,["responseFormat"]);if(g!=null){let H=g;Array.isArray(H)&&(H=H.map($=>$)),l(e,["responseFormat"],H)}let _=s(t,["responseLogprobs"]);_!=null&&l(e,["responseLogprobs"],_);let m=s(t,["responseMimeType"]);m!=null&&l(e,["responseMimeType"],m);let v=s(t,["responseModalities"]);v!=null&&l(e,["responseModalities"],v);let y=s(t,["responseSchema"]);y!=null&&l(e,["responseSchema"],y);let E=s(t,["routingConfig"]);E!=null&&l(e,["routingConfig"],E);let A=s(t,["seed"]);A!=null&&l(e,["seed"],A);let C=s(t,["speechConfig"]);C!=null&&l(e,["speechConfig"],op(C));let w=s(t,["stopSequences"]);w!=null&&l(e,["stopSequences"],w);let N=s(t,["temperature"]);N!=null&&l(e,["temperature"],N);let q=s(t,["thinkingConfig"]);q!=null&&l(e,["thinkingConfig"],q);let V=s(t,["topK"]);V!=null&&l(e,["topK"],V);let M=s(t,["topP"]);if(M!=null&&l(e,["topP"],M),s(t,["enableEnhancedCivicAnswers"])!==void 0)throw new Error("enableEnhancedCivicAnswers parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");let O=s(t,["translationConfig"]);return O!=null&&l(e,["translationConfig"],O),e}function YE(t){let e={},n=s(t,["authConfig"]);n!=null&&l(e,["authConfig"],BE(n));let o=s(t,["enableWidget"]);if(o!=null&&l(e,["enableWidget"],o),s(t,["groundingTypes"])!==void 0)throw new Error("groundingTypes parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return e}function WE(t){let e={};if(s(t,["blockingConfidence"])!==void 0)throw new Error("blockingConfidence parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["excludeDomains"])!==void 0)throw new Error("excludeDomains parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let n=s(t,["searchTypes"]);n!=null&&l(e,["searchTypes"],n);let o=s(t,["timeRangeFilter"]);return o!=null&&l(e,["timeRangeFilter"],o),e}function zE(t){let e={},n=s(t,["systemInstruction"]);n!=null&&l(e,["systemInstruction"],tp(ke(n)));let o=s(t,["tools"]);return o!=null&&l(e,["tools"],ZE(o)),e}function QE(t){let e={},n=s(t,["systemInstruction"]);n!=null&&l(e,["systemInstruction"],np(ke(n)));let o=s(t,["tools"]);return o!=null&&l(e,["tools"],jE(o)),e}function ZE(t){let e={},n=s(t,["tools"]);if(n!=null){let o=Kt(n);Array.isArray(o)&&(o=o.map(i=>ip(Jt(i)))),l(e,["tools"],o)}return e}function jE(t){let e={},n=s(t,["tools"]);if(n!=null){let o=Kt(n);Array.isArray(o)&&(o=o.map(i=>rp(Jt(i)))),l(e,["tools"],o)}return e}function eT(t,e){let n={},o=s(t,["generationConfig"]);e!==void 0&&o!=null&&l(e,["setup","generationConfig"],o);let i=s(t,["responseModalities"]);e!==void 0&&i!=null&&l(e,["setup","generationConfig","responseModalities"],i);let r=s(t,["temperature"]);e!==void 0&&r!=null&&l(e,["setup","generationConfig","temperature"],r);let a=s(t,["topP"]);e!==void 0&&a!=null&&l(e,["setup","generationConfig","topP"],a);let u=s(t,["topK"]);e!==void 0&&u!=null&&l(e,["setup","generationConfig","topK"],u);let c=s(t,["maxOutputTokens"]);e!==void 0&&c!=null&&l(e,["setup","generationConfig","maxOutputTokens"],c);let d=s(t,["mediaResolution"]);e!==void 0&&d!=null&&l(e,["setup","generationConfig","mediaResolution"],d);let f=s(t,["seed"]);e!==void 0&&f!=null&&l(e,["setup","generationConfig","seed"],f);let p=s(t,["speechConfig"]);e!==void 0&&p!=null&&l(e,["setup","generationConfig","speechConfig"],_l(p));let h=s(t,["thinkingConfig"]);e!==void 0&&h!=null&&l(e,["setup","generationConfig","thinkingConfig"],h);let g=s(t,["enableAffectiveDialog"]);e!==void 0&&g!=null&&l(e,["setup","generationConfig","enableAffectiveDialog"],g);let _=s(t,["systemInstruction"]);e!==void 0&&_!=null&&l(e,["setup","systemInstruction"],tp(ke(_)));let m=s(t,["tools"]);if(e!==void 0&&m!=null){let O=Kt(m);Array.isArray(O)&&(O=O.map(H=>ip(Jt(H)))),l(e,["setup","tools"],O)}let v=s(t,["sessionResumption"]);e!==void 0&&v!=null&&l(e,["setup","sessionResumption"],mT(v));let y=s(t,["inputAudioTranscription"]);e!==void 0&&y!=null&&l(e,["setup","inputAudioTranscription"],y);let E=s(t,["outputAudioTranscription"]);e!==void 0&&E!=null&&l(e,["setup","outputAudioTranscription"],E);let A=s(t,["realtimeInputConfig"]);e!==void 0&&A!=null&&l(e,["setup","realtimeInputConfig"],A);let C=s(t,["contextWindowCompression"]);e!==void 0&&C!=null&&l(e,["setup","contextWindowCompression"],C);let w=s(t,["proactivity"]);if(e!==void 0&&w!=null&&l(e,["setup","proactivity"],w),s(t,["explicitVadSignal"])!==void 0)throw new Error("explicitVadSignal parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let N=s(t,["avatarConfig"]);e!==void 0&&N!=null&&l(e,["setup","avatarConfig"],N);let q=s(t,["safetySettings"]);if(e!==void 0&&q!=null){let O=q;Array.isArray(O)&&(O=O.map(H=>hT(H))),l(e,["setup","safetySettings"],O)}let V=s(t,["translationConfig"]);e!==void 0&&V!=null&&l(e,["setup","generationConfig","translationConfig"],V);let M=s(t,["labels"]);return e!==void 0&&M!=null&&l(e,["setup","labels"],M),n}function tT(t,e){let n={},o=s(t,["generationConfig"]);e!==void 0&&o!=null&&l(e,["setup","generationConfig"],KE(o));let i=s(t,["responseModalities"]);e!==void 0&&i!=null&&l(e,["setup","generationConfig","responseModalities"],i);let r=s(t,["temperature"]);e!==void 0&&r!=null&&l(e,["setup","generationConfig","temperature"],r);let a=s(t,["topP"]);e!==void 0&&a!=null&&l(e,["setup","generationConfig","topP"],a);let u=s(t,["topK"]);e!==void 0&&u!=null&&l(e,["setup","generationConfig","topK"],u);let c=s(t,["maxOutputTokens"]);e!==void 0&&c!=null&&l(e,["setup","generationConfig","maxOutputTokens"],c);let d=s(t,["mediaResolution"]);e!==void 0&&d!=null&&l(e,["setup","generationConfig","mediaResolution"],d);let f=s(t,["seed"]);e!==void 0&&f!=null&&l(e,["setup","generationConfig","seed"],f);let p=s(t,["speechConfig"]);e!==void 0&&p!=null&&l(e,["setup","generationConfig","speechConfig"],op(_l(p)));let h=s(t,["thinkingConfig"]);e!==void 0&&h!=null&&l(e,["setup","generationConfig","thinkingConfig"],h);let g=s(t,["enableAffectiveDialog"]);e!==void 0&&g!=null&&l(e,["setup","generationConfig","enableAffectiveDialog"],g);let _=s(t,["systemInstruction"]);e!==void 0&&_!=null&&l(e,["setup","systemInstruction"],np(ke(_)));let m=s(t,["tools"]);if(e!==void 0&&m!=null){let H=Kt(m);Array.isArray(H)&&(H=H.map($=>rp(Jt($)))),l(e,["setup","tools"],H)}let v=s(t,["sessionResumption"]);e!==void 0&&v!=null&&l(e,["setup","sessionResumption"],v);let y=s(t,["inputAudioTranscription"]);e!==void 0&&y!=null&&l(e,["setup","inputAudioTranscription"],y);let E=s(t,["outputAudioTranscription"]);e!==void 0&&E!=null&&l(e,["setup","outputAudioTranscription"],E);let A=s(t,["realtimeInputConfig"]);e!==void 0&&A!=null&&l(e,["setup","realtimeInputConfig"],A);let C=s(t,["contextWindowCompression"]);e!==void 0&&C!=null&&l(e,["setup","contextWindowCompression"],C);let w=s(t,["proactivity"]);e!==void 0&&w!=null&&l(e,["setup","proactivity"],w);let N=s(t,["explicitVadSignal"]);e!==void 0&&N!=null&&l(e,["setup","explicitVadSignal"],N);let q=s(t,["avatarConfig"]);e!==void 0&&q!=null&&l(e,["setup","avatarConfig"],q);let V=s(t,["safetySettings"]);if(e!==void 0&&V!=null){let H=V;Array.isArray(H)&&(H=H.map($=>$)),l(e,["setup","safetySettings"],H)}let M=s(t,["translationConfig"]);e!==void 0&&M!=null&&l(e,["setup","generationConfig","translationConfig"],M);let O=s(t,["labels"]);return e!==void 0&&O!=null&&l(e,["setup","labels"],O),n}function nT(t,e){let n={},o=s(e,["model"]);o!=null&&l(n,["setup","model"],ye(t,o));let i=s(e,["config"]);return i!=null&&l(n,["config"],eT(i,n)),n}function oT(t,e){let n={},o=s(e,["model"]);o!=null&&l(n,["setup","model"],ye(t,o));let i=s(e,["config"]);return i!=null&&l(n,["config"],tT(i,n)),n}function iT(t){let e={},n=s(t,["musicGenerationConfig"]);return n!=null&&l(e,["musicGenerationConfig"],n),e}function rT(t){let e={},n=s(t,["weightedPrompts"]);if(n!=null){let o=n;Array.isArray(o)&&(o=o.map(i=>i)),l(e,["weightedPrompts"],o)}return e}function sT(t){let e={},n=s(t,["media"]);if(n!=null){let d=Hf(n);Array.isArray(d)&&(d=d.map(f=>f)),l(e,["mediaChunks"],d)}let o=s(t,["audio"]);o!=null&&l(e,["audio"],Bf(o));let i=s(t,["audioStreamEnd"]);i!=null&&l(e,["audioStreamEnd"],i);let r=s(t,["video"]);r!=null&&l(e,["video"],Vf(r));let a=s(t,["text"]);a!=null&&l(e,["text"],a);let u=s(t,["activityStart"]);u!=null&&l(e,["activityStart"],u);let c=s(t,["activityEnd"]);return c!=null&&l(e,["activityEnd"],c),e}function aT(t){let e={},n=s(t,["media"]);if(n!=null){let d=Hf(n);Array.isArray(d)&&(d=d.map(f=>f)),l(e,["mediaChunks"],d)}let o=s(t,["audio"]);o!=null&&l(e,["audio"],Bf(o));let i=s(t,["audioStreamEnd"]);i!=null&&l(e,["audioStreamEnd"],i);let r=s(t,["video"]);r!=null&&l(e,["video"],Vf(r));let a=s(t,["text"]);a!=null&&l(e,["text"],a);let u=s(t,["activityStart"]);u!=null&&l(e,["activityStart"],u);let c=s(t,["activityEnd"]);return c!=null&&l(e,["activityEnd"],c),e}function lT(t){let e={},n=s(t,["setupComplete"]);n!=null&&l(e,["setupComplete"],n);let o=s(t,["serverContent"]);o!=null&&l(e,["serverContent"],o);let i=s(t,["toolCall"]);i!=null&&l(e,["toolCall"],i);let r=s(t,["toolCallCancellation"]);r!=null&&l(e,["toolCallCancellation"],r);let a=s(t,["usageMetadata"]);a!=null&&l(e,["usageMetadata"],_T(a));let u=s(t,["goAway"]);u!=null&&l(e,["goAway"],u);let c=s(t,["sessionResumptionUpdate"]);c!=null&&l(e,["sessionResumptionUpdate"],c);let d=s(t,["voiceActivityDetectionSignal"]);d!=null&&l(e,["voiceActivityDetectionSignal"],d);let f=s(t,["voiceActivity"]);return f!=null&&l(e,["voiceActivity"],yT(f)),e}function uT(t){let e={};if(s(t,["name"])!==void 0)throw new Error("name parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(s(t,["streamableHttpTransport"])!==void 0)throw new Error("streamableHttpTransport parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return e}function cT(t){let e={},n=s(t,["speakerVoiceConfigs"]);if(n!=null){let o=n;Array.isArray(o)&&(o=o.map(i=>gT(i))),l(e,["speakerVoiceConfigs"],o)}return e}function dT(t){let e={},n=s(t,["mediaResolution"]);n!=null&&l(e,["mediaResolution"],n);let o=s(t,["toolCall"]);o!=null&&l(e,["toolCall"],o);let i=s(t,["toolResponse"]);i!=null&&l(e,["toolResponse"],i);let r=s(t,["audioTranscription"]);r!=null&&l(e,["audioTranscription"],r);let a=s(t,["codeExecutionResult"]);a!=null&&l(e,["codeExecutionResult"],a);let u=s(t,["executableCode"]);u!=null&&l(e,["executableCode"],u);let c=s(t,["fileData"]);c!=null&&l(e,["fileData"],c);let d=s(t,["functionCall"]);d!=null&&l(e,["functionCall"],$E(d));let f=s(t,["functionResponse"]);f!=null&&l(e,["functionResponse"],f);let p=s(t,["inlineData"]);p!=null&&l(e,["inlineData"],p);let h=s(t,["text"]);h!=null&&l(e,["text"],h);let g=s(t,["thought"]);g!=null&&l(e,["thought"],g);let _=s(t,["thoughtSignature"]);_!=null&&l(e,["thoughtSignature"],_);let m=s(t,["videoMetadata"]);m!=null&&l(e,["videoMetadata"],m);let v=s(t,["partMetadata"]);v!=null&&l(e,["partMetadata"],v);let y=s(t,["mediaProcessing"]);y!=null&&l(e,["mediaProcessing"],y);let E=s(t,["speechMetadata"]);return E!=null&&l(e,["speechMetadata"],E),e}function fT(t){let e={},n=s(t,["mediaResolution"]);if(n!=null&&l(e,["mediaResolution"],n),s(t,["toolCall"])!==void 0)throw new Error("toolCall parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(s(t,["toolResponse"])!==void 0)throw new Error("toolResponse parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");let o=s(t,["audioTranscription"]);o!=null&&l(e,["audioTranscription"],o);let i=s(t,["codeExecutionResult"]);i!=null&&l(e,["codeExecutionResult"],i);let r=s(t,["executableCode"]);r!=null&&l(e,["executableCode"],r);let a=s(t,["fileData"]);a!=null&&l(e,["fileData"],a);let u=s(t,["functionCall"]);u!=null&&l(e,["functionCall"],u);let c=s(t,["functionResponse"]);c!=null&&l(e,["functionResponse"],JE(c));let d=s(t,["inlineData"]);d!=null&&l(e,["inlineData"],d);let f=s(t,["text"]);f!=null&&l(e,["text"],f);let p=s(t,["thought"]);p!=null&&l(e,["thought"],p);let h=s(t,["thoughtSignature"]);h!=null&&l(e,["thoughtSignature"],h);let g=s(t,["videoMetadata"]);if(g!=null&&l(e,["videoMetadata"],g),s(t,["partMetadata"])!==void 0)throw new Error("partMetadata parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");let _=s(t,["mediaProcessing"]);_!=null&&l(e,["mediaProcessing"],_);let m=s(t,["speechMetadata"]);return m!=null&&l(e,["speechMetadata"],m),e}function pT(t){let e={},n=s(t,["mimeType"]);n!=null&&l(e,["mimeType"],n);let o=s(t,["voiceSampleAudio"]);if(o!=null&&l(e,["voiceSampleAudio"],o),s(t,["consentAudio"])!==void 0)throw new Error("consentAudio parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(s(t,["voiceConsentSignature"])!==void 0)throw new Error("voiceConsentSignature parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return e}function hT(t){let e={},n=s(t,["category"]);if(n!=null&&l(e,["category"],n),s(t,["method"])!==void 0)throw new Error("method parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let o=s(t,["threshold"]);return o!=null&&l(e,["threshold"],o),e}function mT(t){let e={},n=s(t,["handle"]);if(n!=null&&l(e,["handle"],n),s(t,["transparent"])!==void 0)throw new Error("transparent parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return e}function gT(t){let e={},n=s(t,["speaker"]);n!=null&&l(e,["speaker"],n);let o=s(t,["voiceConfig"]);return o!=null&&l(e,["voiceConfig"],sp(o)),e}function op(t){let e={},n=s(t,["voiceConfig"]);n!=null&&l(e,["voiceConfig"],sp(n));let o=s(t,["languageCode"]);o!=null&&l(e,["languageCode"],o);let i=s(t,["multiSpeakerVoiceConfig"]);return i!=null&&l(e,["multiSpeakerVoiceConfig"],cT(i)),e}function ip(t){let e={};if(s(t,["retrieval"])!==void 0)throw new Error("retrieval parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let n=s(t,["googleMaps"]);n!=null&&l(e,["googleMaps"],YE(n));let o=s(t,["mcpServers"]);if(o!=null){let p=o;Array.isArray(p)&&(p=p.map(h=>h)),l(e,["mcpServers"],p)}let i=s(t,["codeExecution"]);i!=null&&l(e,["codeExecution"],i);let r=s(t,["computerUse"]);if(r!=null&&l(e,["computerUse"],r),s(t,["enterpriseWebSearch"])!==void 0)throw new Error("enterpriseWebSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["exaAiSearch"])!==void 0)throw new Error("exaAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let a=s(t,["functionDeclarations"]);if(a!=null){let p=a;Array.isArray(p)&&(p=p.map(h=>h)),l(e,["functionDeclarations"],p)}let u=s(t,["googleSearch"]);u!=null&&l(e,["googleSearch"],WE(u));let c=s(t,["googleSearchRetrieval"]);if(c!=null&&l(e,["googleSearchRetrieval"],c),s(t,["parallelAiSearch"])!==void 0)throw new Error("parallelAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let d=s(t,["urlContext"]);d!=null&&l(e,["urlContext"],d);let f=s(t,["fileSearch"]);return f!=null&&l(e,["fileSearch"],f),e}function rp(t){let e={},n=s(t,["retrieval"]);n!=null&&l(e,["retrieval"],n);let o=s(t,["googleMaps"]);o!=null&&l(e,["googleMaps"],o);let i=s(t,["mcpServers"]);if(i!=null){let _=i;Array.isArray(_)&&(_=_.map(m=>uT(m))),l(e,["mcpServers"],_)}let r=s(t,["codeExecution"]);r!=null&&l(e,["codeExecution"],r);let a=s(t,["computerUse"]);a!=null&&l(e,["computerUse"],a);let u=s(t,["enterpriseWebSearch"]);u!=null&&l(e,["enterpriseWebSearch"],u);let c=s(t,["exaAiSearch"]);c!=null&&l(e,["exaAiSearch"],c);let d=s(t,["functionDeclarations"]);if(d!=null){let _=d;Array.isArray(_)&&(_=_.map(m=>m)),l(e,["functionDeclarations"],_)}let f=s(t,["googleSearch"]);f!=null&&l(e,["googleSearch"],f);let p=s(t,["googleSearchRetrieval"]);p!=null&&l(e,["googleSearchRetrieval"],p);let h=s(t,["parallelAiSearch"]);h!=null&&l(e,["parallelAiSearch"],h);let g=s(t,["urlContext"]);if(g!=null&&l(e,["urlContext"],g),s(t,["fileSearch"])!==void 0)throw new Error("fileSearch parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return e}function _T(t){let e={},n=s(t,["candidatesTokenCount"]);n!=null&&l(e,["responseTokenCount"],n);let o=s(t,["candidatesTokensDetails"]);if(o!=null){let g=o;Array.isArray(g)&&(g=g.map(_=>_)),l(e,["responseTokensDetails"],g)}let i=s(t,["cacheTokensDetails"]);if(i!=null){let g=i;Array.isArray(g)&&(g=g.map(_=>_)),l(e,["cacheTokensDetails"],g)}let r=s(t,["cachedContentTokenCount"]);r!=null&&l(e,["cachedContentTokenCount"],r);let a=s(t,["promptTokenCount"]);a!=null&&l(e,["promptTokenCount"],a);let u=s(t,["promptTokensDetails"]);if(u!=null){let g=u;Array.isArray(g)&&(g=g.map(_=>_)),l(e,["promptTokensDetails"],g)}let c=s(t,["thoughtsTokenCount"]);c!=null&&l(e,["thoughtsTokenCount"],c);let d=s(t,["toolUsePromptTokenCount"]);d!=null&&l(e,["toolUsePromptTokenCount"],d);let f=s(t,["toolUsePromptTokensDetails"]);if(f!=null){let g=f;Array.isArray(g)&&(g=g.map(_=>_)),l(e,["toolUsePromptTokensDetails"],g)}let p=s(t,["totalTokenCount"]);p!=null&&l(e,["totalTokenCount"],p);let h=s(t,["trafficType"]);return h!=null&&l(e,["trafficType"],h),e}function yT(t){let e={},n=s(t,["type"]);n!=null&&l(e,["voiceActivityType"],n);let o=s(t,["audioOffset"]);return o!=null&&l(e,["audioOffset"],o),e}function sp(t){let e={},n=s(t,["replicatedVoiceConfig"]);n!=null&&l(e,["replicatedVoiceConfig"],pT(n));let o=s(t,["prebuiltVoiceConfig"]);o!=null&&l(e,["prebuiltVoiceConfig"],o);let i=s(t,["voice"]);return i!=null&&l(e,["voice"],i),e}function vT(t,e){let n={},o=s(t,["apiKey"]);if(o!=null&&l(n,["apiKey"],o),s(t,["apiKeyConfig"])!==void 0)throw new Error("apiKeyConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["authType"])!==void 0)throw new Error("authType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["googleServiceAccountConfig"])!==void 0)throw new Error("googleServiceAccountConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["httpBasicAuthConfig"])!==void 0)throw new Error("httpBasicAuthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["oauthConfig"])!==void 0)throw new Error("oauthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["oidcConfig"])!==void 0)throw new Error("oidcConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return n}function ET(t,e){let n={},o=s(t,["content"]);o!=null&&l(n,["content"],o);let i=s(t,["citationMetadata"]);i!=null&&l(n,["citationMetadata"],TT(i));let r=s(t,["tokenCount"]);r!=null&&l(n,["tokenCount"],r);let a=s(t,["finishReason"]);a!=null&&l(n,["finishReason"],a);let u=s(t,["groundingMetadata"]);u!=null&&l(n,["groundingMetadata"],u);let c=s(t,["avgLogprobs"]);c!=null&&l(n,["avgLogprobs"],c);let d=s(t,["index"]);d!=null&&l(n,["index"],d);let f=s(t,["logprobsResult"]);f!=null&&l(n,["logprobsResult"],f);let p=s(t,["safetyRatings"]);if(p!=null){let _=p;Array.isArray(_)&&(_=_.map(m=>m)),l(n,["safetyRatings"],_)}let h=s(t,["urlContextMetadata"]);h!=null&&l(n,["urlContextMetadata"],h);let g=s(t,["continuationToken"]);return g!=null&&l(n,["continuationToken"],g),n}function TT(t,e){let n={},o=s(t,["citationSources"]);if(o!=null){let i=o;Array.isArray(i)&&(i=i.map(r=>r)),l(n,["citations"],i)}return n}function AT(t,e,n){let o={},i=s(e,["model"]);i!=null&&l(o,["_url","model"],ye(t,i));let r=s(e,["contents"]);if(r!=null){let a=Oe(r);Array.isArray(a)&&(a=a.map(u=>wn(u))),l(o,["contents"],a)}return o}function CT(t,e){let n={},o=s(t,["sdkHttpResponse"]);o!=null&&l(n,["sdkHttpResponse"],o);let i=s(t,["tokensInfo"]);if(i!=null){let r=i;Array.isArray(r)&&(r=r.map(a=>a)),l(n,["tokensInfo"],r)}return n}function IT(t,e){let n={},o=s(t,["values"]);o!=null&&l(n,["values"],o);let i=s(t,["statistics"]);return i!=null&&l(n,["statistics"],ST(i)),n}function ST(t,e){let n={},o=s(t,["truncated"]);o!=null&&l(n,["truncated"],o);let i=s(t,["token_count"]);i!=null&&l(n,["tokenCount"],i);let r=s(t,["tokensDetails"]);if(r!=null){let a=r;Array.isArray(a)&&(a=a.map(u=>u)),l(n,["tokensDetails"],a)}return n}function zn(t,e){let n={},o=s(t,["parts"]);if(o!=null){let r=o;Array.isArray(r)&&(r=r.map(a=>xA(a))),l(n,["parts"],r)}let i=s(t,["role"]);return i!=null&&l(n,["role"],i),n}function wn(t,e){let n={},o=s(t,["parts"]);if(o!=null){let r=o;Array.isArray(r)&&(r=r.map(a=>DA(a))),l(n,["parts"],r)}let i=s(t,["role"]);return i!=null&&l(n,["role"],i),n}function wT(t,e){let n={},o=s(t,["controlType"]);o!=null&&l(n,["controlType"],o);let i=s(t,["enableControlImageComputation"]);return i!=null&&l(n,["computeControl"],i),n}function RT(t,e){let n={};if(s(t,["systemInstruction"])!==void 0)throw new Error("systemInstruction parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["tools"])!==void 0)throw new Error("tools parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["generationConfig"])!==void 0)throw new Error("generationConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return n}function PT(t,e,n){let o={},i=s(t,["systemInstruction"]);e!==void 0&&i!=null&&l(e,["systemInstruction"],wn(ke(i)));let r=s(t,["tools"]);if(e!==void 0&&r!=null){let u=r;Array.isArray(u)&&(u=u.map(c=>cp(c))),l(e,["tools"],u)}let a=s(t,["generationConfig"]);return e!==void 0&&a!=null&&l(e,["generationConfig"],mA(a)),o}function kT(t,e,n){let o={},i=s(e,["model"]);i!=null&&l(o,["_url","model"],ye(t,i));let r=s(e,["contents"]);if(r!=null){let u=Oe(r);Array.isArray(u)&&(u=u.map(c=>zn(c))),l(o,["contents"],u)}let a=s(e,["config"]);return a!=null&&RT(a),o}function NT(t,e,n){let o={},i=s(e,["model"]);i!=null&&l(o,["_url","model"],ye(t,i));let r=s(e,["contents"]);if(r!=null){let u=Oe(r);Array.isArray(u)&&(u=u.map(c=>wn(c))),l(o,["contents"],u)}let a=s(e,["config"]);return a!=null&&PT(a,o),o}function xT(t,e){let n={},o=s(t,["sdkHttpResponse"]);o!=null&&l(n,["sdkHttpResponse"],o);let i=s(t,["totalTokens"]);i!=null&&l(n,["totalTokens"],i);let r=s(t,["cachedContentTokenCount"]);return r!=null&&l(n,["cachedContentTokenCount"],r),n}function DT(t,e){let n={},o=s(t,["sdkHttpResponse"]);o!=null&&l(n,["sdkHttpResponse"],o);let i=s(t,["totalTokens"]);return i!=null&&l(n,["totalTokens"],i),n}function MT(t,e,n){let o={},i=s(e,["model"]);return i!=null&&l(o,["_url","name"],ye(t,i)),o}function UT(t,e,n){let o={},i=s(e,["model"]);return i!=null&&l(o,["_url","name"],ye(t,i)),o}function GT(t,e){let n={},o=s(t,["sdkHttpResponse"]);return o!=null&&l(n,["sdkHttpResponse"],o),n}function bT(t,e){let n={},o=s(t,["sdkHttpResponse"]);return o!=null&&l(n,["sdkHttpResponse"],o),n}function LT(t,e,n){let o={},i=s(t,["outputGcsUri"]);e!==void 0&&i!=null&&l(e,["parameters","storageUri"],i);let r=s(t,["negativePrompt"]);e!==void 0&&r!=null&&l(e,["parameters","negativePrompt"],r);let a=s(t,["numberOfImages"]);e!==void 0&&a!=null&&l(e,["parameters","sampleCount"],a);let u=s(t,["aspectRatio"]);e!==void 0&&u!=null&&l(e,["parameters","aspectRatio"],u);let c=s(t,["guidanceScale"]);e!==void 0&&c!=null&&l(e,["parameters","guidanceScale"],c);let d=s(t,["seed"]);e!==void 0&&d!=null&&l(e,["parameters","seed"],d);let f=s(t,["safetyFilterLevel"]);e!==void 0&&f!=null&&l(e,["parameters","safetySetting"],f);let p=s(t,["personGeneration"]);e!==void 0&&p!=null&&l(e,["parameters","personGeneration"],p);let h=s(t,["includeSafetyAttributes"]);e!==void 0&&h!=null&&l(e,["parameters","includeSafetyAttributes"],h);let g=s(t,["includeRaiReason"]);e!==void 0&&g!=null&&l(e,["parameters","includeRaiReason"],g);let _=s(t,["language"]);e!==void 0&&_!=null&&l(e,["parameters","language"],_);let m=s(t,["outputMimeType"]);e!==void 0&&m!=null&&l(e,["parameters","outputOptions","mimeType"],m);let v=s(t,["outputCompressionQuality"]);e!==void 0&&v!=null&&l(e,["parameters","outputOptions","compressionQuality"],v);let y=s(t,["addWatermark"]);e!==void 0&&y!=null&&l(e,["parameters","addWatermark"],y);let E=s(t,["labels"]);e!==void 0&&E!=null&&l(e,["labels"],E);let A=s(t,["editMode"]);e!==void 0&&A!=null&&l(e,["parameters","editMode"],A);let C=s(t,["baseSteps"]);return e!==void 0&&C!=null&&l(e,["parameters","editConfig","baseSteps"],C),o}function qT(t,e,n){let o={},i=s(e,["model"]);i!=null&&l(o,["_url","model"],ye(t,i));let r=s(e,["prompt"]);r!=null&&l(o,["instances[0]","prompt"],r);let a=s(e,["referenceImages"]);if(a!=null){let c=a;Array.isArray(c)&&(c=c.map(d=>qA(d))),l(o,["instances[0]","referenceImages"],c)}let u=s(e,["config"]);return u!=null&&LT(u,o),o}function OT(t,e){let n={},o=s(t,["sdkHttpResponse"]);o!=null&&l(n,["sdkHttpResponse"],o);let i=s(t,["predictions"]);if(i!=null){let r=i;Array.isArray(r)&&(r=r.map(a=>Ii(a))),l(n,["generatedImages"],r)}return n}function FT(t,e,n){let o={},i=s(t,["taskType"]);e!==void 0&&i!=null&&l(e,["requests[]","taskType"],i);let r=s(t,["title"]);e!==void 0&&r!=null&&l(e,["requests[]","title"],r);let a=s(t,["outputDimensionality"]);if(e!==void 0&&a!=null&&l(e,["requests[]","outputDimensionality"],a),s(t,["mimeType"])!==void 0)throw new Error("mimeType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["autoTruncate"])!==void 0)throw new Error("autoTruncate parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["documentOcr"])!==void 0)throw new Error("documentOcr parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["audioTrackExtraction"])!==void 0)throw new Error("audioTrackExtraction parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return o}function HT(t,e,n){let o={},i=s(n,["embeddingApiType"]);if(i===void 0&&(i="PREDICT"),i==="PREDICT"){let p=s(t,["taskType"]);e!==void 0&&p!=null&&l(e,["instances[]","task_type"],p)}else if(i==="EMBED_CONTENT"){let p=s(t,["taskType"]);e!==void 0&&p!=null&&l(e,["embedContentConfig","taskType"],p)}let r=s(n,["embeddingApiType"]);if(r===void 0&&(r="PREDICT"),r==="PREDICT"){let p=s(t,["title"]);e!==void 0&&p!=null&&l(e,["instances[]","title"],p)}else if(r==="EMBED_CONTENT"){let p=s(t,["title"]);e!==void 0&&p!=null&&l(e,["embedContentConfig","title"],p)}let a=s(n,["embeddingApiType"]);if(a===void 0&&(a="PREDICT"),a==="PREDICT"){let p=s(t,["outputDimensionality"]);e!==void 0&&p!=null&&l(e,["parameters","outputDimensionality"],p)}else if(a==="EMBED_CONTENT"){let p=s(t,["outputDimensionality"]);e!==void 0&&p!=null&&l(e,["embedContentConfig","outputDimensionality"],p)}let u=s(n,["embeddingApiType"]);if(u===void 0&&(u="PREDICT"),u==="PREDICT"){let p=s(t,["mimeType"]);e!==void 0&&p!=null&&l(e,["instances[]","mimeType"],p)}let c=s(n,["embeddingApiType"]);if(c===void 0&&(c="PREDICT"),c==="PREDICT"){let p=s(t,["autoTruncate"]);e!==void 0&&p!=null&&l(e,["parameters","autoTruncate"],p)}else if(c==="EMBED_CONTENT"){let p=s(t,["autoTruncate"]);e!==void 0&&p!=null&&l(e,["embedContentConfig","autoTruncate"],p)}let d=s(n,["embeddingApiType"]);if(d===void 0&&(d="PREDICT"),d==="EMBED_CONTENT"){let p=s(t,["documentOcr"]);e!==void 0&&p!=null&&l(e,["embedContentConfig","documentOcr"],p)}let f=s(n,["embeddingApiType"]);if(f===void 0&&(f="PREDICT"),f==="EMBED_CONTENT"){let p=s(t,["audioTrackExtraction"]);e!==void 0&&p!=null&&l(e,["embedContentConfig","audioTrackExtraction"],p)}return o}function VT(t,e,n){let o={},i=s(e,["model"]);i!=null&&l(o,["_url","model"],ye(t,i));let r=s(e,["contents"]);if(r!=null){let d=hl(t,r);Array.isArray(d)&&(d=d.map(f=>f)),l(o,["requests[]","content"],d)}let a=s(e,["content"]);a!=null&&zn(ke(a));let u=s(e,["config"]);u!=null&&FT(u,o);let c=s(e,["model"]);return c!==void 0&&l(o,["requests[]","model"],ye(t,c)),o}function BT(t,e,n){let o={},i=s(e,["model"]);i!=null&&l(o,["_url","model"],ye(t,i));let r=s(n,["embeddingApiType"]);if(r===void 0&&(r="PREDICT"),r==="PREDICT"){let c=s(e,["contents"]);if(c!=null){let d=hl(t,c);Array.isArray(d)&&(d=d.map(f=>f)),l(o,["instances[]","content"],d)}}let a=s(n,["embeddingApiType"]);if(a===void 0&&(a="PREDICT"),a==="EMBED_CONTENT"){let c=s(e,["content"]);c!=null&&l(o,["content"],wn(ke(c)))}let u=s(e,["config"]);return u!=null&&HT(u,o,n),o}function $T(t,e){let n={},o=s(t,["sdkHttpResponse"]);o!=null&&l(n,["sdkHttpResponse"],o);let i=s(t,["embeddings"]);if(i!=null){let a=i;Array.isArray(a)&&(a=a.map(u=>u)),l(n,["embeddings"],a)}let r=s(t,["metadata"]);return r!=null&&l(n,["metadata"],r),n}function XT(t,e){let n={},o=s(t,["sdkHttpResponse"]);o!=null&&l(n,["sdkHttpResponse"],o);let i=s(t,["predictions[]","embeddings"]);if(i!=null){let a=i;Array.isArray(a)&&(a=a.map(u=>IT(u))),l(n,["embeddings"],a)}let r=s(t,["metadata"]);if(r!=null&&l(n,["metadata"],r),e&&s(e,["embeddingApiType"])==="EMBED_CONTENT"){let a=s(t,["embedding"]),u=s(t,["usageMetadata"]),c=s(t,["truncated"]);if(a){let d={};u&&u.promptTokenCount&&(d.tokenCount=u.promptTokenCount),u&&u.promptTokensDetails&&(d.tokensDetails=u.promptTokensDetails),c&&(d.truncated=c),a.statistics=d,l(n,["embeddings"],[a])}}return n}function JT(t,e){let n={},o=s(t,["endpoint"]);o!=null&&l(n,["name"],o);let i=s(t,["deployedModelId"]);return i!=null&&l(n,["deployedModelId"],i),n}function KT(t,e){let n={},o=s(t,["args"]);o!=null&&l(n,["args"],o);let i=s(t,["id"]);i!=null&&l(n,["id"],i);let r=s(t,["name"]);if(r!=null&&l(n,["name"],r),s(t,["partialArgs"])!==void 0)throw new Error("partialArgs parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["willContinue"])!==void 0)throw new Error("willContinue parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return n}function YT(t,e){let n={},o=s(t,["allowedFunctionNames"]);o!=null&&l(n,["allowedFunctionNames"],o);let i=s(t,["mode"]);if(i!=null&&l(n,["mode"],i),s(t,["streamFunctionCallArguments"])!==void 0)throw new Error("streamFunctionCallArguments parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return n}function WT(t,e){let n={},o=s(t,["fileData"]);o!=null&&l(n,["fileData"],o);let i=s(t,["inlineData"]);if(i!=null&&l(n,["inlineData"],i),s(t,["mediaProcessing"])!==void 0)throw new Error("mediaProcessing parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return n}function zT(t,e){let n={},o=s(t,["id"]);o!=null&&l(n,["id"],o);let i=s(t,["name"]);i!=null&&l(n,["name"],i);let r=s(t,["parts"]);if(r!=null){let c=r;Array.isArray(c)&&(c=c.map(d=>WT(d))),l(n,["parts"],c)}let a=s(t,["response"]);a!=null&&l(n,["response"],a);let u=s(t,["scheduling"]);if(u!=null&&l(n,["scheduling"],u),s(t,["willContinue"])!==void 0)throw new Error("willContinue parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return n}function QT(t,e,n,o){let i={},r=s(e,["serviceTier"]);n!==void 0&&r!=null&&l(n,["serviceTier"],r);let a=s(e,["systemInstruction"]);n!==void 0&&a!=null&&l(n,["systemInstruction"],zn(ke(a)));let u=s(e,["temperature"]);u!=null&&l(i,["temperature"],u);let c=s(e,["topP"]);c!=null&&l(i,["topP"],c);let d=s(e,["topK"]);d!=null&&l(i,["topK"],d);let f=s(e,["candidateCount"]);f!=null&&l(i,["candidateCount"],f);let p=s(e,["maxOutputTokens"]);p!=null&&l(i,["maxOutputTokens"],p);let h=s(e,["stopSequences"]);h!=null&&l(i,["stopSequences"],h);let g=s(e,["responseLogprobs"]);g!=null&&l(i,["responseLogprobs"],g);let _=s(e,["logprobs"]);_!=null&&l(i,["logprobs"],_);let m=s(e,["presencePenalty"]);m!=null&&l(i,["presencePenalty"],m);let v=s(e,["frequencyPenalty"]);v!=null&&l(i,["frequencyPenalty"],v);let y=s(e,["seed"]);y!=null&&l(i,["seed"],y);let E=s(e,["responseMimeType"]);E!=null&&l(i,["responseMimeType"],E);let A=s(e,["responseSchema"]);A!=null&&l(i,["responseSchema"],ml(A));let C=s(e,["responseJsonSchema"]);if(C!=null&&l(i,["responseJsonSchema"],C),s(e,["routingConfig"])!==void 0)throw new Error("routingConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(e,["modelSelectionConfig"])!==void 0)throw new Error("modelSelectionConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let w=s(e,["safetySettings"]);if(n!==void 0&&w!=null){let fe=w;Array.isArray(fe)&&(fe=fe.map(He=>FA(He))),l(n,["safetySettings"],fe)}let N=s(e,["tools"]);if(n!==void 0&&N!=null){let fe=Kt(N);Array.isArray(fe)&&(fe=fe.map(He=>WA(Jt(He)))),l(n,["tools"],fe)}let q=s(e,["toolConfig"]);n!==void 0&&q!=null&&l(n,["toolConfig"],KA(q));let V=s(e,["labels"]);n!==void 0&&V!=null&&l(n,["labels"],V);let M=s(e,["cachedContent"]);n!==void 0&&M!=null&&l(n,["cachedContent"],kt(t,M));let O=s(e,["responseModalities"]);O!=null&&l(i,["responseModalities"],O);let H=s(e,["mediaResolution"]);H!=null&&l(i,["mediaResolution"],H);let $=s(e,["speechConfig"]);if($!=null&&l(i,["speechConfig"],gl($)),s(e,["audioTimestamp"])!==void 0)throw new Error("audioTimestamp parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let j=s(e,["thinkingConfig"]);j!=null&&l(i,["thinkingConfig"],j);let D=s(e,["audioTranscriptionConfig"]);D!=null&&l(i,["audioTranscriptionConfig"],D);let Q=s(e,["imageConfig"]);Q!=null&&l(i,["imageConfig"],EA(Q));let te=s(e,["enableEnhancedCivicAnswers"]);if(te!=null&&l(i,["enableEnhancedCivicAnswers"],te),s(e,["modelArmorConfig"])!==void 0)throw new Error("modelArmorConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let Ae=s(e,["continuationToken"]);if(n!==void 0&&Ae!=null&&l(n,["continuationToken"],Ae),s(e,["generationOutputConfig"])!==void 0)throw new Error("generationOutputConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let ve=s(e,["store"]);return n!==void 0&&ve!=null&&l(n,["store"],ve),i}function ZT(t,e,n,o){let i={},r=s(e,["serviceTier"]);n!==void 0&&r!=null&&l(n,["serviceTier"],r);let a=s(e,["systemInstruction"]);n!==void 0&&a!=null&&l(n,["systemInstruction"],wn(ke(a)));let u=s(e,["temperature"]);u!=null&&l(i,["temperature"],u);let c=s(e,["topP"]);c!=null&&l(i,["topP"],c);let d=s(e,["topK"]);d!=null&&l(i,["topK"],d);let f=s(e,["candidateCount"]);f!=null&&l(i,["candidateCount"],f);let p=s(e,["maxOutputTokens"]);p!=null&&l(i,["maxOutputTokens"],p);let h=s(e,["stopSequences"]);h!=null&&l(i,["stopSequences"],h);let g=s(e,["responseLogprobs"]);g!=null&&l(i,["responseLogprobs"],g);let _=s(e,["logprobs"]);_!=null&&l(i,["logprobs"],_);let m=s(e,["presencePenalty"]);m!=null&&l(i,["presencePenalty"],m);let v=s(e,["frequencyPenalty"]);v!=null&&l(i,["frequencyPenalty"],v);let y=s(e,["seed"]);y!=null&&l(i,["seed"],y);let E=s(e,["responseMimeType"]);E!=null&&l(i,["responseMimeType"],E);let A=s(e,["responseSchema"]);A!=null&&l(i,["responseSchema"],ml(A));let C=s(e,["responseJsonSchema"]);C!=null&&l(i,["responseJsonSchema"],C);let w=s(e,["routingConfig"]);w!=null&&l(i,["routingConfig"],w);let N=s(e,["modelSelectionConfig"]);N!=null&&l(i,["modelConfig"],N);let q=s(e,["safetySettings"]);if(n!==void 0&&q!=null){let Ge=q;Array.isArray(Ge)&&(Ge=Ge.map(B=>B)),l(n,["safetySettings"],Ge)}let V=s(e,["tools"]);if(n!==void 0&&V!=null){let Ge=Kt(V);Array.isArray(Ge)&&(Ge=Ge.map(B=>cp(Jt(B)))),l(n,["tools"],Ge)}let M=s(e,["toolConfig"]);n!==void 0&&M!=null&&l(n,["toolConfig"],YA(M));let O=s(e,["labels"]);n!==void 0&&O!=null&&l(n,["labels"],O);let H=s(e,["cachedContent"]);n!==void 0&&H!=null&&l(n,["cachedContent"],kt(t,H));let $=s(e,["responseModalities"]);$!=null&&l(i,["responseModalities"],$);let j=s(e,["mediaResolution"]);j!=null&&l(i,["mediaResolution"],j);let D=s(e,["speechConfig"]);D!=null&&l(i,["speechConfig"],up(gl(D)));let Q=s(e,["audioTimestamp"]);Q!=null&&l(i,["audioTimestamp"],Q);let te=s(e,["thinkingConfig"]);te!=null&&l(i,["thinkingConfig"],te);let Ae=s(e,["audioTranscriptionConfig"]);Ae!=null&&l(i,["audioTranscriptionConfig"],Ae);let ve=s(e,["imageConfig"]);if(ve!=null&&l(i,["imageConfig"],TA(ve)),s(e,["enableEnhancedCivicAnswers"])!==void 0)throw new Error("enableEnhancedCivicAnswers parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");let fe=s(e,["modelArmorConfig"]);n!==void 0&&fe!=null&&l(n,["modelArmorConfig"],fe);let He=s(e,["continuationToken"]);n!==void 0&&He!=null&&l(n,["continuationToken"],He);let Ue=s(e,["generationOutputConfig"]);if(n!==void 0&&Ue!=null&&l(n,["outputConfig"],Ue),s(e,["store"])!==void 0)throw new Error("store parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return i}function jd(t,e,n){let o={},i=s(e,["model"]);i!=null&&l(o,["_url","model"],ye(t,i));let r=s(e,["contents"]);if(r!=null){let u=Oe(r);Array.isArray(u)&&(u=u.map(c=>zn(c))),l(o,["contents"],u)}let a=s(e,["config"]);return a!=null&&l(o,["generationConfig"],QT(t,a,o)),o}function ef(t,e,n){let o={},i=s(e,["model"]);i!=null&&l(o,["_url","model"],ye(t,i));let r=s(e,["contents"]);if(r!=null){let u=Oe(r);Array.isArray(u)&&(u=u.map(c=>wn(c))),l(o,["contents"],u)}let a=s(e,["config"]);return a!=null&&l(o,["generationConfig"],ZT(t,a,o)),o}function tf(t,e){let n={},o=s(t,["sdkHttpResponse"]);o!=null&&l(n,["sdkHttpResponse"],o);let i=s(t,["candidates"]);if(i!=null){let f=i;Array.isArray(f)&&(f=f.map(p=>ET(p))),l(n,["candidates"],f)}let r=s(t,["modelVersion"]);r!=null&&l(n,["modelVersion"],r);let a=s(t,["promptFeedback"]);a!=null&&l(n,["promptFeedback"],a);let u=s(t,["responseId"]);u!=null&&l(n,["responseId"],u);let c=s(t,["usageMetadata"]);c!=null&&l(n,["usageMetadata"],c);let d=s(t,["modelStatus"]);return d!=null&&l(n,["modelStatus"],d),n}function nf(t,e){let n={},o=s(t,["sdkHttpResponse"]);o!=null&&l(n,["sdkHttpResponse"],o);let i=s(t,["candidates"]);if(i!=null){let f=i;Array.isArray(f)&&(f=f.map(p=>p)),l(n,["candidates"],f)}let r=s(t,["createTime"]);r!=null&&l(n,["createTime"],r);let a=s(t,["modelVersion"]);a!=null&&l(n,["modelVersion"],a);let u=s(t,["promptFeedback"]);u!=null&&l(n,["promptFeedback"],u);let c=s(t,["responseId"]);c!=null&&l(n,["responseId"],c);let d=s(t,["usageMetadata"]);return d!=null&&l(n,["usageMetadata"],d),n}function jT(t,e,n){let o={},i=s(t,["outputGcsUri"]);e!==void 0&&i!=null&&l(e,["parameters","storageUri"],i);let r=s(t,["negativePrompt"]);e!==void 0&&r!=null&&l(e,["parameters","negativePrompt"],r);let a=s(t,["numberOfImages"]);e!==void 0&&a!=null&&l(e,["parameters","sampleCount"],a);let u=s(t,["aspectRatio"]);e!==void 0&&u!=null&&l(e,["parameters","aspectRatio"],u);let c=s(t,["guidanceScale"]);e!==void 0&&c!=null&&l(e,["parameters","guidanceScale"],c);let d=s(t,["seed"]);e!==void 0&&d!=null&&l(e,["parameters","seed"],d);let f=s(t,["safetyFilterLevel"]);e!==void 0&&f!=null&&l(e,["parameters","safetySetting"],f);let p=s(t,["personGeneration"]);e!==void 0&&p!=null&&l(e,["parameters","personGeneration"],p);let h=s(t,["includeSafetyAttributes"]);e!==void 0&&h!=null&&l(e,["parameters","includeSafetyAttributes"],h);let g=s(t,["includeRaiReason"]);e!==void 0&&g!=null&&l(e,["parameters","includeRaiReason"],g);let _=s(t,["language"]);e!==void 0&&_!=null&&l(e,["parameters","language"],_);let m=s(t,["outputMimeType"]);e!==void 0&&m!=null&&l(e,["parameters","outputOptions","mimeType"],m);let v=s(t,["outputCompressionQuality"]);e!==void 0&&v!=null&&l(e,["parameters","outputOptions","compressionQuality"],v);let y=s(t,["addWatermark"]);e!==void 0&&y!=null&&l(e,["parameters","addWatermark"],y);let E=s(t,["labels"]);e!==void 0&&E!=null&&l(e,["labels"],E);let A=s(t,["imageSize"]);e!==void 0&&A!=null&&l(e,["parameters","sampleImageSize"],A);let C=s(t,["enhancePrompt"]);return e!==void 0&&C!=null&&l(e,["parameters","enhancePrompt"],C),o}function eA(t,e,n){let o={},i=s(e,["model"]);i!=null&&l(o,["_url","model"],ye(t,i));let r=s(e,["prompt"]);r!=null&&l(o,["instances[0]","prompt"],r);let a=s(e,["config"]);return a!=null&&jT(a,o),o}function tA(t,e){let n={},o=s(t,["sdkHttpResponse"]);o!=null&&l(n,["sdkHttpResponse"],o);let i=s(t,["predictions"]);if(i!=null){let a=i;Array.isArray(a)&&(a=a.map(u=>Ii(u))),l(n,["generatedImages"],a)}let r=s(t,["positivePromptSafetyAttributes"]);return r!=null&&l(n,["positivePromptSafetyAttributes"],lp(r)),n}function nA(t,e,n){let o={},i=s(t,["numberOfVideos"]);if(e!==void 0&&i!=null&&l(e,["parameters","sampleCount"],i),s(t,["outputGcsUri"])!==void 0)throw new Error("outputGcsUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["fps"])!==void 0)throw new Error("fps parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let r=s(t,["durationSeconds"]);if(e!==void 0&&r!=null&&l(e,["parameters","durationSeconds"],r),s(t,["seed"])!==void 0)throw new Error("seed parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let a=s(t,["aspectRatio"]);e!==void 0&&a!=null&&l(e,["parameters","aspectRatio"],a);let u=s(t,["resolution"]);e!==void 0&&u!=null&&l(e,["parameters","resolution"],u);let c=s(t,["personGeneration"]);if(e!==void 0&&c!=null&&l(e,["parameters","personGeneration"],c),s(t,["pubsubTopic"])!==void 0)throw new Error("pubsubTopic parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let d=s(t,["negativePrompt"]);e!==void 0&&d!=null&&l(e,["parameters","negativePrompt"],d);let f=s(t,["enhancePrompt"]);if(e!==void 0&&f!=null&&l(e,["parameters","enhancePrompt"],f),s(t,["generateAudio"])!==void 0)throw new Error("generateAudio parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let p=s(t,["lastFrame"]);e!==void 0&&p!=null&&l(e,["instances[0]","lastFrame"],Si(p));let h=s(t,["referenceImages"]);if(e!==void 0&&h!=null){let _=h;Array.isArray(_)&&(_=_.map(m=>lC(m))),l(e,["instances[0]","referenceImages"],_)}if(s(t,["mask"])!==void 0)throw new Error("mask parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["compressionQuality"])!==void 0)throw new Error("compressionQuality parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["labels"])!==void 0)throw new Error("labels parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let g=s(t,["webhookConfig"]);if(e!==void 0&&g!=null&&l(e,["webhookConfig"],g),s(t,["resizeMode"])!==void 0)throw new Error("resizeMode parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return o}function oA(t,e,n){let o={},i=s(t,["numberOfVideos"]);e!==void 0&&i!=null&&l(e,["parameters","sampleCount"],i);let r=s(t,["outputGcsUri"]);e!==void 0&&r!=null&&l(e,["parameters","storageUri"],r);let a=s(t,["fps"]);e!==void 0&&a!=null&&l(e,["parameters","fps"],a);let u=s(t,["durationSeconds"]);e!==void 0&&u!=null&&l(e,["parameters","durationSeconds"],u);let c=s(t,["seed"]);e!==void 0&&c!=null&&l(e,["parameters","seed"],c);let d=s(t,["aspectRatio"]);e!==void 0&&d!=null&&l(e,["parameters","aspectRatio"],d);let f=s(t,["resolution"]);e!==void 0&&f!=null&&l(e,["parameters","resolution"],f);let p=s(t,["personGeneration"]);e!==void 0&&p!=null&&l(e,["parameters","personGeneration"],p);let h=s(t,["pubsubTopic"]);e!==void 0&&h!=null&&l(e,["parameters","pubsubTopic"],h);let g=s(t,["negativePrompt"]);e!==void 0&&g!=null&&l(e,["parameters","negativePrompt"],g);let _=s(t,["enhancePrompt"]);e!==void 0&&_!=null&&l(e,["parameters","enhancePrompt"],_);let m=s(t,["generateAudio"]);e!==void 0&&m!=null&&l(e,["parameters","generateAudio"],m);let v=s(t,["lastFrame"]);e!==void 0&&v!=null&&l(e,["instances[0]","lastFrame"],ft(v));let y=s(t,["referenceImages"]);if(e!==void 0&&y!=null){let N=y;Array.isArray(N)&&(N=N.map(q=>uC(q))),l(e,["instances[0]","referenceImages"],N)}let E=s(t,["mask"]);e!==void 0&&E!=null&&l(e,["instances[0]","mask"],aC(E));let A=s(t,["compressionQuality"]);e!==void 0&&A!=null&&l(e,["parameters","compressionQuality"],A);let C=s(t,["labels"]);if(e!==void 0&&C!=null&&l(e,["labels"],C),s(t,["webhookConfig"])!==void 0)throw new Error("webhookConfig parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");let w=s(t,["resizeMode"]);return e!==void 0&&w!=null&&l(e,["parameters","resizeMode"],w),o}function iA(t,e){let n={},o=s(t,["name"]);o!=null&&l(n,["name"],o);let i=s(t,["metadata"]);i!=null&&l(n,["metadata"],i);let r=s(t,["done"]);r!=null&&l(n,["done"],r);let a=s(t,["error"]);a!=null&&l(n,["error"],a);let u=s(t,["response","generateVideoResponse"]);return u!=null&&l(n,["response"],lA(u)),n}function rA(t,e){let n={},o=s(t,["name"]);o!=null&&l(n,["name"],o);let i=s(t,["metadata"]);i!=null&&l(n,["metadata"],i);let r=s(t,["done"]);r!=null&&l(n,["done"],r);let a=s(t,["error"]);a!=null&&l(n,["error"],a);let u=s(t,["response"]);return u!=null&&l(n,["response"],uA(u)),n}function sA(t,e,n){let o={},i=s(e,["model"]);i!=null&&l(o,["_url","model"],ye(t,i));let r=s(e,["prompt"]);r!=null&&l(o,["instances[0]","prompt"],r);let a=s(e,["image"]);a!=null&&l(o,["instances[0]","image"],Si(a));let u=s(e,["video"]);u!=null&&l(o,["instances[0]","video"],dp(u));let c=s(e,["source"]);c!=null&&cA(c,o);let d=s(e,["config"]);return d!=null&&nA(d,o),o}function aA(t,e,n){let o={},i=s(e,["model"]);i!=null&&l(o,["_url","model"],ye(t,i));let r=s(e,["prompt"]);r!=null&&l(o,["instances[0]","prompt"],r);let a=s(e,["image"]);a!=null&&l(o,["instances[0]","image"],ft(a));let u=s(e,["video"]);u!=null&&l(o,["instances[0]","video"],fp(u));let c=s(e,["source"]);c!=null&&dA(c,o);let d=s(e,["config"]);return d!=null&&oA(d,o),o}function lA(t,e){let n={},o=s(t,["generatedSamples"]);if(o!=null){let a=o;Array.isArray(a)&&(a=a.map(u=>pA(u))),l(n,["generatedVideos"],a)}let i=s(t,["raiMediaFilteredCount"]);i!=null&&l(n,["raiMediaFilteredCount"],i);let r=s(t,["raiMediaFilteredReasons"]);return r!=null&&l(n,["raiMediaFilteredReasons"],r),n}function uA(t,e){let n={},o=s(t,["videos"]);if(o!=null){let a=o;Array.isArray(a)&&(a=a.map(u=>hA(u))),l(n,["generatedVideos"],a)}let i=s(t,["raiMediaFilteredCount"]);i!=null&&l(n,["raiMediaFilteredCount"],i);let r=s(t,["raiMediaFilteredReasons"]);return r!=null&&l(n,["raiMediaFilteredReasons"],r),n}function cA(t,e,n){let o={},i=s(t,["prompt"]);e!==void 0&&i!=null&&l(e,["instances[0]","prompt"],i);let r=s(t,["image"]);e!==void 0&&r!=null&&l(e,["instances[0]","image"],Si(r));let a=s(t,["video"]);return e!==void 0&&a!=null&&l(e,["instances[0]","video"],dp(a)),o}function dA(t,e,n){let o={},i=s(t,["prompt"]);e!==void 0&&i!=null&&l(e,["instances[0]","prompt"],i);let r=s(t,["image"]);e!==void 0&&r!=null&&l(e,["instances[0]","image"],ft(r));let a=s(t,["video"]);return e!==void 0&&a!=null&&l(e,["instances[0]","video"],fp(a)),o}function Ii(t,e){let n={},o=s(t,["_self"]);o!=null&&l(n,["image"],ap(o));let i=s(t,["raiFilteredReason"]);i!=null&&l(n,["raiFilteredReason"],i);let r=s(t,["_self"]);r!=null&&l(n,["safetyAttributes"],lp(r));let a=s(t,["prompt"]);return a!=null&&l(n,["enhancedPrompt"],a),n}function fA(t,e){let n={},o=s(t,["_self"]);o!=null&&l(n,["mask"],ap(o));let i=s(t,["labels"]);if(i!=null){let r=i;Array.isArray(r)&&(r=r.map(a=>a)),l(n,["labels"],r)}return n}function pA(t,e){let n={},o=s(t,["video"]);return o!=null&&l(n,["video"],rC(o)),n}function hA(t,e){let n={},o=s(t,["_self"]);return o!=null&&l(n,["video"],sC(o)),n}function mA(t,e){let n={},o=s(t,["modelSelectionConfig"]);o!=null&&l(n,["modelConfig"],o);let i=s(t,["responseJsonSchema"]);i!=null&&l(n,["responseJsonSchema"],i);let r=s(t,["audioTranscriptionConfig"]);r!=null&&l(n,["audioTranscriptionConfig"],r);let a=s(t,["audioTimestamp"]);a!=null&&l(n,["audioTimestamp"],a);let u=s(t,["candidateCount"]);u!=null&&l(n,["candidateCount"],u);let c=s(t,["enableAffectiveDialog"]);c!=null&&l(n,["enableAffectiveDialog"],c);let d=s(t,["frequencyPenalty"]);d!=null&&l(n,["frequencyPenalty"],d);let f=s(t,["logprobs"]);f!=null&&l(n,["logprobs"],f);let p=s(t,["maxOutputTokens"]);p!=null&&l(n,["maxOutputTokens"],p);let h=s(t,["mediaResolution"]);h!=null&&l(n,["mediaResolution"],h);let g=s(t,["presencePenalty"]);g!=null&&l(n,["presencePenalty"],g);let _=s(t,["responseFormat"]);if(_!=null){let $=_;Array.isArray($)&&($=$.map(j=>j)),l(n,["responseFormat"],$)}let m=s(t,["responseLogprobs"]);m!=null&&l(n,["responseLogprobs"],m);let v=s(t,["responseMimeType"]);v!=null&&l(n,["responseMimeType"],v);let y=s(t,["responseModalities"]);y!=null&&l(n,["responseModalities"],y);let E=s(t,["responseSchema"]);E!=null&&l(n,["responseSchema"],E);let A=s(t,["routingConfig"]);A!=null&&l(n,["routingConfig"],A);let C=s(t,["seed"]);C!=null&&l(n,["seed"],C);let w=s(t,["speechConfig"]);w!=null&&l(n,["speechConfig"],up(w));let N=s(t,["stopSequences"]);N!=null&&l(n,["stopSequences"],N);let q=s(t,["temperature"]);q!=null&&l(n,["temperature"],q);let V=s(t,["thinkingConfig"]);V!=null&&l(n,["thinkingConfig"],V);let M=s(t,["topK"]);M!=null&&l(n,["topK"],M);let O=s(t,["topP"]);if(O!=null&&l(n,["topP"],O),s(t,["enableEnhancedCivicAnswers"])!==void 0)throw new Error("enableEnhancedCivicAnswers parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");let H=s(t,["translationConfig"]);return H!=null&&l(n,["translationConfig"],H),n}function gA(t,e,n){let o={},i=s(e,["model"]);return i!=null&&l(o,["_url","name"],ye(t,i)),o}function _A(t,e,n){let o={},i=s(e,["model"]);return i!=null&&l(o,["_url","name"],ye(t,i)),o}function yA(t,e){let n={},o=s(t,["authConfig"]);o!=null&&l(n,["authConfig"],vT(o));let i=s(t,["enableWidget"]);if(i!=null&&l(n,["enableWidget"],i),s(t,["groundingTypes"])!==void 0)throw new Error("groundingTypes parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return n}function vA(t,e){let n={};if(s(t,["blockingConfidence"])!==void 0)throw new Error("blockingConfidence parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["excludeDomains"])!==void 0)throw new Error("excludeDomains parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let o=s(t,["searchTypes"]);o!=null&&l(n,["searchTypes"],o);let i=s(t,["timeRangeFilter"]);return i!=null&&l(n,["timeRangeFilter"],i),n}function EA(t,e){let n={},o=s(t,["aspectRatio"]);o!=null&&l(n,["aspectRatio"],o);let i=s(t,["imageSize"]);if(i!=null&&l(n,["imageSize"],i),s(t,["personGeneration"])!==void 0)throw new Error("personGeneration parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["outputMimeType"])!==void 0)throw new Error("outputMimeType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["outputCompressionQuality"])!==void 0)throw new Error("outputCompressionQuality parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["imageOutputOptions"])!==void 0)throw new Error("imageOutputOptions parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["prominentPeople"])!==void 0)throw new Error("prominentPeople parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return n}function TA(t,e){let n={},o=s(t,["aspectRatio"]);o!=null&&l(n,["aspectRatio"],o);let i=s(t,["imageSize"]);i!=null&&l(n,["imageSize"],i);let r=s(t,["personGeneration"]);r!=null&&l(n,["personGeneration"],r);let a=s(t,["outputMimeType"]);a!=null&&l(n,["imageOutputOptions","mimeType"],a);let u=s(t,["outputCompressionQuality"]);u!=null&&l(n,["imageOutputOptions","compressionQuality"],u);let c=s(t,["imageOutputOptions"]);c!=null&&l(n,["imageOutputOptions"],c);let d=s(t,["prominentPeople"]);return d!=null&&l(n,["prominentPeople"],d),n}function ap(t,e){let n={},o=s(t,["gcsUri"]);o!=null&&l(n,["gcsUri"],o);let i=s(t,["bytesBase64Encoded"]);i!=null&&l(n,["imageBytes"],en(i));let r=s(t,["mimeType"]);return r!=null&&l(n,["mimeType"],r),n}function Si(t,e){let n={};if(s(t,["gcsUri"])!==void 0)throw new Error("gcsUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let o=s(t,["imageBytes"]);o!=null&&l(n,["bytesBase64Encoded"],en(o));let i=s(t,["mimeType"]);return i!=null&&l(n,["mimeType"],i),n}function ft(t,e){let n={},o=s(t,["gcsUri"]);o!=null&&l(n,["gcsUri"],o);let i=s(t,["imageBytes"]);i!=null&&l(n,["bytesBase64Encoded"],en(i));let r=s(t,["mimeType"]);return r!=null&&l(n,["mimeType"],r),n}function AA(t,e,n,o){let i={},r=s(e,["pageSize"]);n!==void 0&&r!=null&&l(n,["_query","pageSize"],r);let a=s(e,["pageToken"]);n!==void 0&&a!=null&&l(n,["_query","pageToken"],a);let u=s(e,["filter"]);n!==void 0&&u!=null&&l(n,["_query","filter"],u);let c=s(e,["queryBase"]);return n!==void 0&&c!=null&&l(n,["_url","models_url"],Yf(t,c)),i}function CA(t,e,n,o){let i={},r=s(e,["pageSize"]);n!==void 0&&r!=null&&l(n,["_query","pageSize"],r);let a=s(e,["pageToken"]);n!==void 0&&a!=null&&l(n,["_query","pageToken"],a);let u=s(e,["filter"]);n!==void 0&&u!=null&&l(n,["_query","filter"],u);let c=s(e,["queryBase"]);return n!==void 0&&c!=null&&l(n,["_url","models_url"],Yf(t,c)),i}function IA(t,e,n){let o={},i=s(e,["config"]);return i!=null&&AA(t,i,o),o}function SA(t,e,n){let o={},i=s(e,["config"]);return i!=null&&CA(t,i,o),o}function wA(t,e){let n={},o=s(t,["sdkHttpResponse"]);o!=null&&l(n,["sdkHttpResponse"],o);let i=s(t,["nextPageToken"]);i!=null&&l(n,["nextPageToken"],i);let r=s(t,["_self"]);if(r!=null){let a=Wf(r);Array.isArray(a)&&(a=a.map(u=>ra(u))),l(n,["models"],a)}return n}function RA(t,e){let n={},o=s(t,["sdkHttpResponse"]);o!=null&&l(n,["sdkHttpResponse"],o);let i=s(t,["nextPageToken"]);i!=null&&l(n,["nextPageToken"],i);let r=s(t,["_self"]);if(r!=null){let a=Wf(r);Array.isArray(a)&&(a=a.map(u=>sa(u))),l(n,["models"],a)}return n}function PA(t,e){let n={},o=s(t,["maskMode"]);o!=null&&l(n,["maskMode"],o);let i=s(t,["segmentationClasses"]);i!=null&&l(n,["maskClasses"],i);let r=s(t,["maskDilation"]);return r!=null&&l(n,["dilation"],r),n}function kA(t,e){let n={};if(s(t,["name"])!==void 0)throw new Error("name parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(s(t,["streamableHttpTransport"])!==void 0)throw new Error("streamableHttpTransport parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return n}function ra(t,e){let n={},o=s(t,["name"]);o!=null&&l(n,["name"],o);let i=s(t,["displayName"]);i!=null&&l(n,["displayName"],i);let r=s(t,["description"]);r!=null&&l(n,["description"],r);let a=s(t,["version"]);a!=null&&l(n,["version"],a);let u=s(t,["_self"]);u!=null&&l(n,["tunedModelInfo"],zA(u));let c=s(t,["inputTokenLimit"]);c!=null&&l(n,["inputTokenLimit"],c);let d=s(t,["outputTokenLimit"]);d!=null&&l(n,["outputTokenLimit"],d);let f=s(t,["supportedGenerationMethods"]);f!=null&&l(n,["supportedActions"],f);let p=s(t,["temperature"]);p!=null&&l(n,["temperature"],p);let h=s(t,["maxTemperature"]);h!=null&&l(n,["maxTemperature"],h);let g=s(t,["topP"]);g!=null&&l(n,["topP"],g);let _=s(t,["topK"]);_!=null&&l(n,["topK"],_);let m=s(t,["thinking"]);return m!=null&&l(n,["thinking"],m),n}function sa(t,e){let n={},o=s(t,["name"]);o!=null&&l(n,["name"],o);let i=s(t,["displayName"]);i!=null&&l(n,["displayName"],i);let r=s(t,["description"]);r!=null&&l(n,["description"],r);let a=s(t,["versionId"]);a!=null&&l(n,["version"],a);let u=s(t,["deployedModels"]);if(u!=null){let h=u;Array.isArray(h)&&(h=h.map(g=>JT(g))),l(n,["endpoints"],h)}let c=s(t,["labels"]);c!=null&&l(n,["labels"],c);let d=s(t,["_self"]);d!=null&&l(n,["tunedModelInfo"],QA(d));let f=s(t,["defaultCheckpointId"]);f!=null&&l(n,["defaultCheckpointId"],f);let p=s(t,["checkpoints"]);if(p!=null){let h=p;Array.isArray(h)&&(h=h.map(g=>g)),l(n,["checkpoints"],h)}return n}function NA(t,e){let n={},o=s(t,["speakerVoiceConfigs"]);if(o!=null){let i=o;Array.isArray(i)&&(i=i.map(r=>JA(r))),l(n,["speakerVoiceConfigs"],i)}return n}function xA(t,e){let n={},o=s(t,["mediaResolution"]);o!=null&&l(n,["mediaResolution"],o);let i=s(t,["toolCall"]);i!=null&&l(n,["toolCall"],i);let r=s(t,["toolResponse"]);r!=null&&l(n,["toolResponse"],r);let a=s(t,["audioTranscription"]);a!=null&&l(n,["audioTranscription"],a);let u=s(t,["codeExecutionResult"]);u!=null&&l(n,["codeExecutionResult"],u);let c=s(t,["executableCode"]);c!=null&&l(n,["executableCode"],c);let d=s(t,["fileData"]);d!=null&&l(n,["fileData"],d);let f=s(t,["functionCall"]);f!=null&&l(n,["functionCall"],KT(f));let p=s(t,["functionResponse"]);p!=null&&l(n,["functionResponse"],p);let h=s(t,["inlineData"]);h!=null&&l(n,["inlineData"],h);let g=s(t,["text"]);g!=null&&l(n,["text"],g);let _=s(t,["thought"]);_!=null&&l(n,["thought"],_);let m=s(t,["thoughtSignature"]);m!=null&&l(n,["thoughtSignature"],m);let v=s(t,["videoMetadata"]);v!=null&&l(n,["videoMetadata"],v);let y=s(t,["partMetadata"]);y!=null&&l(n,["partMetadata"],y);let E=s(t,["mediaProcessing"]);E!=null&&l(n,["mediaProcessing"],E);let A=s(t,["speechMetadata"]);return A!=null&&l(n,["speechMetadata"],A),n}function DA(t,e){let n={},o=s(t,["mediaResolution"]);if(o!=null&&l(n,["mediaResolution"],o),s(t,["toolCall"])!==void 0)throw new Error("toolCall parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(s(t,["toolResponse"])!==void 0)throw new Error("toolResponse parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");let i=s(t,["audioTranscription"]);i!=null&&l(n,["audioTranscription"],i);let r=s(t,["codeExecutionResult"]);r!=null&&l(n,["codeExecutionResult"],r);let a=s(t,["executableCode"]);a!=null&&l(n,["executableCode"],a);let u=s(t,["fileData"]);u!=null&&l(n,["fileData"],u);let c=s(t,["functionCall"]);c!=null&&l(n,["functionCall"],c);let d=s(t,["functionResponse"]);d!=null&&l(n,["functionResponse"],zT(d));let f=s(t,["inlineData"]);f!=null&&l(n,["inlineData"],f);let p=s(t,["text"]);p!=null&&l(n,["text"],p);let h=s(t,["thought"]);h!=null&&l(n,["thought"],h);let g=s(t,["thoughtSignature"]);g!=null&&l(n,["thoughtSignature"],g);let _=s(t,["videoMetadata"]);if(_!=null&&l(n,["videoMetadata"],_),s(t,["partMetadata"])!==void 0)throw new Error("partMetadata parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");let m=s(t,["mediaProcessing"]);m!=null&&l(n,["mediaProcessing"],m);let v=s(t,["speechMetadata"]);return v!=null&&l(n,["speechMetadata"],v),n}function MA(t,e){let n={},o=s(t,["productImage"]);return o!=null&&l(n,["image"],ft(o)),n}function UA(t,e,n){let o={},i=s(t,["numberOfImages"]);e!==void 0&&i!=null&&l(e,["parameters","sampleCount"],i);let r=s(t,["baseSteps"]);e!==void 0&&r!=null&&l(e,["parameters","baseSteps"],r);let a=s(t,["outputGcsUri"]);e!==void 0&&a!=null&&l(e,["parameters","storageUri"],a);let u=s(t,["seed"]);e!==void 0&&u!=null&&l(e,["parameters","seed"],u);let c=s(t,["safetyFilterLevel"]);e!==void 0&&c!=null&&l(e,["parameters","safetySetting"],c);let d=s(t,["personGeneration"]);e!==void 0&&d!=null&&l(e,["parameters","personGeneration"],d);let f=s(t,["addWatermark"]);e!==void 0&&f!=null&&l(e,["parameters","addWatermark"],f);let p=s(t,["outputMimeType"]);e!==void 0&&p!=null&&l(e,["parameters","outputOptions","mimeType"],p);let h=s(t,["outputCompressionQuality"]);e!==void 0&&h!=null&&l(e,["parameters","outputOptions","compressionQuality"],h);let g=s(t,["enhancePrompt"]);e!==void 0&&g!=null&&l(e,["parameters","enhancePrompt"],g);let _=s(t,["labels"]);return e!==void 0&&_!=null&&l(e,["labels"],_),o}function GA(t,e,n){let o={},i=s(e,["model"]);i!=null&&l(o,["_url","model"],ye(t,i));let r=s(e,["source"]);r!=null&&LA(r,o);let a=s(e,["config"]);return a!=null&&UA(a,o),o}function bA(t,e){let n={},o=s(t,["predictions"]);if(o!=null){let i=o;Array.isArray(i)&&(i=i.map(r=>Ii(r))),l(n,["generatedImages"],i)}return n}function LA(t,e,n){let o={},i=s(t,["prompt"]);e!==void 0&&i!=null&&l(e,["instances[0]","prompt"],i);let r=s(t,["personImage"]);e!==void 0&&r!=null&&l(e,["instances[0]","personImage","image"],ft(r));let a=s(t,["productImages"]);if(e!==void 0&&a!=null){let u=a;Array.isArray(u)&&(u=u.map(c=>MA(c))),l(e,["instances[0]","productImages"],u)}return o}function qA(t,e){let n={},o=s(t,["referenceImage"]);o!=null&&l(n,["referenceImage"],ft(o));let i=s(t,["referenceId"]);i!=null&&l(n,["referenceId"],i);let r=s(t,["referenceType"]);r!=null&&l(n,["referenceType"],r);let a=s(t,["maskImageConfig"]);a!=null&&l(n,["maskImageConfig"],PA(a));let u=s(t,["controlImageConfig"]);u!=null&&l(n,["controlImageConfig"],wT(u));let c=s(t,["styleImageConfig"]);c!=null&&l(n,["styleImageConfig"],c);let d=s(t,["subjectImageConfig"]);return d!=null&&l(n,["subjectImageConfig"],d),n}function OA(t,e){let n={},o=s(t,["mimeType"]);o!=null&&l(n,["mimeType"],o);let i=s(t,["voiceSampleAudio"]);if(i!=null&&l(n,["voiceSampleAudio"],i),s(t,["consentAudio"])!==void 0)throw new Error("consentAudio parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(s(t,["voiceConsentSignature"])!==void 0)throw new Error("voiceConsentSignature parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return n}function lp(t,e){let n={},o=s(t,["safetyAttributes","categories"]);o!=null&&l(n,["categories"],o);let i=s(t,["safetyAttributes","scores"]);i!=null&&l(n,["scores"],i);let r=s(t,["contentType"]);return r!=null&&l(n,["contentType"],r),n}function FA(t,e){let n={},o=s(t,["category"]);if(o!=null&&l(n,["category"],o),s(t,["method"])!==void 0)throw new Error("method parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let i=s(t,["threshold"]);return i!=null&&l(n,["threshold"],i),n}function HA(t,e){let n={},o=s(t,["image"]);return o!=null&&l(n,["image"],ft(o)),n}function VA(t,e,n){let o={},i=s(t,["mode"]);e!==void 0&&i!=null&&l(e,["parameters","mode"],i);let r=s(t,["maxPredictions"]);e!==void 0&&r!=null&&l(e,["parameters","maxPredictions"],r);let a=s(t,["confidenceThreshold"]);e!==void 0&&a!=null&&l(e,["parameters","confidenceThreshold"],a);let u=s(t,["maskDilation"]);e!==void 0&&u!=null&&l(e,["parameters","maskDilation"],u);let c=s(t,["binaryColorThreshold"]);e!==void 0&&c!=null&&l(e,["parameters","binaryColorThreshold"],c);let d=s(t,["labels"]);return e!==void 0&&d!=null&&l(e,["labels"],d),o}function BA(t,e,n){let o={},i=s(e,["model"]);i!=null&&l(o,["_url","model"],ye(t,i));let r=s(e,["source"]);r!=null&&XA(r,o);let a=s(e,["config"]);return a!=null&&VA(a,o),o}function $A(t,e){let n={},o=s(t,["predictions"]);if(o!=null){let i=o;Array.isArray(i)&&(i=i.map(r=>fA(r))),l(n,["generatedMasks"],i)}return n}function XA(t,e,n){let o={},i=s(t,["prompt"]);e!==void 0&&i!=null&&l(e,["instances[0]","prompt"],i);let r=s(t,["image"]);e!==void 0&&r!=null&&l(e,["instances[0]","image"],ft(r));let a=s(t,["scribbleImage"]);return e!==void 0&&a!=null&&l(e,["instances[0]","scribble"],HA(a)),o}function JA(t,e){let n={},o=s(t,["speaker"]);o!=null&&l(n,["speaker"],o);let i=s(t,["voiceConfig"]);return i!=null&&l(n,["voiceConfig"],pp(i)),n}function up(t,e){let n={},o=s(t,["voiceConfig"]);o!=null&&l(n,["voiceConfig"],pp(o));let i=s(t,["languageCode"]);i!=null&&l(n,["languageCode"],i);let r=s(t,["multiSpeakerVoiceConfig"]);return r!=null&&l(n,["multiSpeakerVoiceConfig"],NA(r)),n}function KA(t,e){let n={},o=s(t,["functionCallingConfig"]);o!=null&&l(n,["functionCallingConfig"],YT(o));let i=s(t,["retrievalConfig"]);i!=null&&l(n,["retrievalConfig"],i);let r=s(t,["includeServerSideToolInvocations"]);return r!=null&&l(n,["includeServerSideToolInvocations"],r),n}function YA(t,e){let n={},o=s(t,["functionCallingConfig"]);o!=null&&l(n,["functionCallingConfig"],o);let i=s(t,["retrievalConfig"]);if(i!=null&&l(n,["retrievalConfig"],i),s(t,["includeServerSideToolInvocations"])!==void 0)throw new Error("includeServerSideToolInvocations parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return n}function WA(t,e){let n={};if(s(t,["retrieval"])!==void 0)throw new Error("retrieval parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let o=s(t,["googleMaps"]);o!=null&&l(n,["googleMaps"],yA(o));let i=s(t,["mcpServers"]);if(i!=null){let h=i;Array.isArray(h)&&(h=h.map(g=>g)),l(n,["mcpServers"],h)}let r=s(t,["codeExecution"]);r!=null&&l(n,["codeExecution"],r);let a=s(t,["computerUse"]);if(a!=null&&l(n,["computerUse"],a),s(t,["enterpriseWebSearch"])!==void 0)throw new Error("enterpriseWebSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["exaAiSearch"])!==void 0)throw new Error("exaAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let u=s(t,["functionDeclarations"]);if(u!=null){let h=u;Array.isArray(h)&&(h=h.map(g=>g)),l(n,["functionDeclarations"],h)}let c=s(t,["googleSearch"]);c!=null&&l(n,["googleSearch"],vA(c));let d=s(t,["googleSearchRetrieval"]);if(d!=null&&l(n,["googleSearchRetrieval"],d),s(t,["parallelAiSearch"])!==void 0)throw new Error("parallelAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let f=s(t,["urlContext"]);f!=null&&l(n,["urlContext"],f);let p=s(t,["fileSearch"]);return p!=null&&l(n,["fileSearch"],p),n}function cp(t,e){let n={},o=s(t,["retrieval"]);o!=null&&l(n,["retrieval"],o);let i=s(t,["googleMaps"]);i!=null&&l(n,["googleMaps"],i);let r=s(t,["mcpServers"]);if(r!=null){let m=r;Array.isArray(m)&&(m=m.map(v=>kA(v))),l(n,["mcpServers"],m)}let a=s(t,["codeExecution"]);a!=null&&l(n,["codeExecution"],a);let u=s(t,["computerUse"]);u!=null&&l(n,["computerUse"],u);let c=s(t,["enterpriseWebSearch"]);c!=null&&l(n,["enterpriseWebSearch"],c);let d=s(t,["exaAiSearch"]);d!=null&&l(n,["exaAiSearch"],d);let f=s(t,["functionDeclarations"]);if(f!=null){let m=f;Array.isArray(m)&&(m=m.map(v=>v)),l(n,["functionDeclarations"],m)}let p=s(t,["googleSearch"]);p!=null&&l(n,["googleSearch"],p);let h=s(t,["googleSearchRetrieval"]);h!=null&&l(n,["googleSearchRetrieval"],h);let g=s(t,["parallelAiSearch"]);g!=null&&l(n,["parallelAiSearch"],g);let _=s(t,["urlContext"]);if(_!=null&&l(n,["urlContext"],_),s(t,["fileSearch"])!==void 0)throw new Error("fileSearch parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return n}function zA(t,e){let n={},o=s(t,["baseModel"]);o!=null&&l(n,["baseModel"],o);let i=s(t,["createTime"]);i!=null&&l(n,["createTime"],i);let r=s(t,["updateTime"]);return r!=null&&l(n,["updateTime"],r),n}function QA(t,e){let n={},o=s(t,["labels","google-vertex-llm-tuning-base-model-id"]);o!=null&&l(n,["baseModel"],o);let i=s(t,["createTime"]);i!=null&&l(n,["createTime"],i);let r=s(t,["updateTime"]);return r!=null&&l(n,["updateTime"],r),n}function ZA(t,e,n){let o={},i=s(t,["displayName"]);e!==void 0&&i!=null&&l(e,["displayName"],i);let r=s(t,["description"]);e!==void 0&&r!=null&&l(e,["description"],r);let a=s(t,["defaultCheckpointId"]);return e!==void 0&&a!=null&&l(e,["defaultCheckpointId"],a),o}function jA(t,e,n){let o={},i=s(t,["displayName"]);e!==void 0&&i!=null&&l(e,["displayName"],i);let r=s(t,["description"]);e!==void 0&&r!=null&&l(e,["description"],r);let a=s(t,["defaultCheckpointId"]);return e!==void 0&&a!=null&&l(e,["defaultCheckpointId"],a),o}function eC(t,e,n){let o={},i=s(e,["model"]);i!=null&&l(o,["_url","name"],ye(t,i));let r=s(e,["config"]);return r!=null&&ZA(r,o),o}function tC(t,e,n){let o={},i=s(e,["model"]);i!=null&&l(o,["_url","model"],ye(t,i));let r=s(e,["config"]);return r!=null&&jA(r,o),o}function nC(t,e,n){let o={},i=s(t,["outputGcsUri"]);e!==void 0&&i!=null&&l(e,["parameters","storageUri"],i);let r=s(t,["safetyFilterLevel"]);e!==void 0&&r!=null&&l(e,["parameters","safetySetting"],r);let a=s(t,["personGeneration"]);e!==void 0&&a!=null&&l(e,["parameters","personGeneration"],a);let u=s(t,["includeRaiReason"]);e!==void 0&&u!=null&&l(e,["parameters","includeRaiReason"],u);let c=s(t,["outputMimeType"]);e!==void 0&&c!=null&&l(e,["parameters","outputOptions","mimeType"],c);let d=s(t,["outputCompressionQuality"]);e!==void 0&&d!=null&&l(e,["parameters","outputOptions","compressionQuality"],d);let f=s(t,["enhanceInputImage"]);e!==void 0&&f!=null&&l(e,["parameters","upscaleConfig","enhanceInputImage"],f);let p=s(t,["imagePreservationFactor"]);e!==void 0&&p!=null&&l(e,["parameters","upscaleConfig","imagePreservationFactor"],p);let h=s(t,["labels"]);e!==void 0&&h!=null&&l(e,["labels"],h);let g=s(t,["numberOfImages"]);e!==void 0&&g!=null&&l(e,["parameters","sampleCount"],g);let _=s(t,["mode"]);return e!==void 0&&_!=null&&l(e,["parameters","mode"],_),o}function oC(t,e,n){let o={},i=s(e,["model"]);i!=null&&l(o,["_url","model"],ye(t,i));let r=s(e,["image"]);r!=null&&l(o,["instances[0]","image"],ft(r));let a=s(e,["upscaleFactor"]);a!=null&&l(o,["parameters","upscaleConfig","upscaleFactor"],a);let u=s(e,["config"]);return u!=null&&nC(u,o),o}function iC(t,e){let n={},o=s(t,["sdkHttpResponse"]);o!=null&&l(n,["sdkHttpResponse"],o);let i=s(t,["predictions"]);if(i!=null){let r=i;Array.isArray(r)&&(r=r.map(a=>Ii(a))),l(n,["generatedImages"],r)}return n}function rC(t,e){let n={},o=s(t,["uri"]);o!=null&&l(n,["uri"],o);let i=s(t,["encodedVideo"]);i!=null&&l(n,["videoBytes"],en(i));let r=s(t,["encoding"]);return r!=null&&l(n,["mimeType"],r),n}function sC(t,e){let n={},o=s(t,["gcsUri"]);o!=null&&l(n,["uri"],o);let i=s(t,["bytesBase64Encoded"]);i!=null&&l(n,["videoBytes"],en(i));let r=s(t,["mimeType"]);return r!=null&&l(n,["mimeType"],r),n}function aC(t,e){let n={},o=s(t,["image"]);o!=null&&l(n,["_self"],ft(o));let i=s(t,["maskMode"]);return i!=null&&l(n,["maskMode"],i),n}function lC(t,e){let n={},o=s(t,["image"]);o!=null&&l(n,["image"],Si(o));let i=s(t,["referenceType"]);return i!=null&&l(n,["referenceType"],i),n}function uC(t,e){let n={},o=s(t,["image"]);o!=null&&l(n,["image"],ft(o));let i=s(t,["referenceType"]);return i!=null&&l(n,["referenceType"],i),n}function dp(t,e){let n={},o=s(t,["uri"]);o!=null&&l(n,["uri"],o);let i=s(t,["videoBytes"]);i!=null&&l(n,["encodedVideo"],en(i));let r=s(t,["mimeType"]);return r!=null&&l(n,["encoding"],r),n}function fp(t,e){let n={},o=s(t,["uri"]);o!=null&&l(n,["gcsUri"],o);let i=s(t,["videoBytes"]);i!=null&&l(n,["bytesBase64Encoded"],en(i));let r=s(t,["mimeType"]);return r!=null&&l(n,["mimeType"],r),n}function pp(t,e){let n={},o=s(t,["replicatedVoiceConfig"]);o!=null&&l(n,["replicatedVoiceConfig"],OA(o));let i=s(t,["prebuiltVoiceConfig"]);i!=null&&l(n,["prebuiltVoiceConfig"],i);let r=s(t,["voice"]);return r!=null&&l(n,["voice"],r),n}function cC(t,e,n){let o={},i=s(e,["displayName"]);n!==void 0&&i!=null&&l(n,["displayName"],i);let r=s(e,["embeddingModel"]);return n!==void 0&&r!=null&&l(n,["embeddingModel"],ye(t,r)),o}function dC(t,e){let n={},o=s(e,["config"]);return o!=null&&cC(t,o,n),n}function fC(t,e){let n={},o=s(t,["force"]);return e!==void 0&&o!=null&&l(e,["_query","force"],o),n}function pC(t){let e={},n=s(t,["name"]);n!=null&&l(e,["_url","name"],n);let o=s(t,["config"]);return o!=null&&fC(o,e),e}function hC(t){let e={},n=s(t,["name"]);return n!=null&&l(e,["_url","name"],n),e}function mC(t,e){let n={},o=s(t,["customMetadata"]);if(e!==void 0&&o!=null){let r=o;Array.isArray(r)&&(r=r.map(a=>a)),l(e,["customMetadata"],r)}let i=s(t,["chunkingConfig"]);return e!==void 0&&i!=null&&l(e,["chunkingConfig"],i),n}function gC(t){let e={},n=s(t,["name"]);n!=null&&l(e,["name"],n);let o=s(t,["metadata"]);o!=null&&l(e,["metadata"],o);let i=s(t,["done"]);i!=null&&l(e,["done"],i);let r=s(t,["error"]);r!=null&&l(e,["error"],r);let a=s(t,["response"]);return a!=null&&l(e,["response"],yC(a)),e}function _C(t){let e={},n=s(t,["fileSearchStoreName"]);n!=null&&l(e,["_url","file_search_store_name"],n);let o=s(t,["fileName"]);o!=null&&l(e,["fileName"],o);let i=s(t,["config"]);return i!=null&&mC(i,e),e}function yC(t){let e={},n=s(t,["sdkHttpResponse"]);n!=null&&l(e,["sdkHttpResponse"],n);let o=s(t,["parent"]);o!=null&&l(e,["parent"],o);let i=s(t,["documentName"]);return i!=null&&l(e,["documentName"],i),e}function vC(t,e){let n={},o=s(t,["pageSize"]);e!==void 0&&o!=null&&l(e,["_query","pageSize"],o);let i=s(t,["pageToken"]);return e!==void 0&&i!=null&&l(e,["_query","pageToken"],i),n}function EC(t){let e={},n=s(t,["config"]);return n!=null&&vC(n,e),e}function TC(t){let e={},n=s(t,["sdkHttpResponse"]);n!=null&&l(e,["sdkHttpResponse"],n);let o=s(t,["nextPageToken"]);o!=null&&l(e,["nextPageToken"],o);let i=s(t,["fileSearchStores"]);if(i!=null){let r=i;Array.isArray(r)&&(r=r.map(a=>a)),l(e,["fileSearchStores"],r)}return e}function hp(t,e){let n={},o=s(t,["mimeType"]);e!==void 0&&o!=null&&l(e,["mimeType"],o);let i=s(t,["displayName"]);e!==void 0&&i!=null&&l(e,["displayName"],i);let r=s(t,["customMetadata"]);if(e!==void 0&&r!=null){let u=r;Array.isArray(u)&&(u=u.map(c=>c)),l(e,["customMetadata"],u)}let a=s(t,["chunkingConfig"]);return e!==void 0&&a!=null&&l(e,["chunkingConfig"],a),n}function AC(t){let e={},n=s(t,["fileSearchStoreName"]);n!=null&&l(e,["_url","file_search_store_name"],n);let o=s(t,["config"]);return o!=null&&hp(o,e),e}function CC(t){let e={},n=s(t,["sdkHttpResponse"]);return n!=null&&l(e,["sdkHttpResponse"],n),e}var IC="Content-Type",SC="X-Server-Timeout",wC="User-Agent",aa="x-goog-api-client",RC="2.32.0",PC=`google-genai-sdk/${RC}`,kC="v1beta1",NC="v1beta",xC=new Set(["us","eu"]),of=Symbol.for("undici.globalDispatcher.1");function DC(){var t,e;return typeof((e=(t=globalThis.process)===null||t===void 0?void 0:t.versions)===null||e===void 0?void 0:e.node)=="string"}function MC(){return{dispatch(t,e){let n=globalThis[of];if(!n&&typeof Headers<"u"&&(new Headers,n=globalThis[of]),!n||typeof n.dispatch!="function")throw new Error("Undici globalDispatcher is not available.");return n.dispatch(Object.assign(Object.assign({},t),{headersTimeout:0,bodyTimeout:0}),e)}}}function UC(t,e){let n=()=>{};if(!(t&&t>0)&&!e)return{signal:void 0,dispose:n};let o=new AbortController,i;t&&t>0&&(i=setTimeout(()=>o.abort(),t),i&&typeof i.unref=="function"&&i.unref());let r=()=>o.abort();return e&&(e.aborted?o.abort():e.addEventListener("abort",r)),{signal:o.signal,dispose:()=>{i!==void 0&&clearTimeout(i),e?.removeEventListener("abort",r)}}}var GC=5,bC=1,LC=60,qC=2,OC=1,FC=[408,429,500,502,503,504],la=class{constructor(e){var n,o,i;this.clientOptions=Object.assign({},e),this.customBaseUrl=(n=e.httpOptions)===null||n===void 0?void 0:n.baseUrl;let r={};if(this.clientOptions.vertexai){if(!this.clientOptions.location&&!this.clientOptions.apiKey&&!this.customBaseUrl&&(this.clientOptions.location="global"),!(this.clientOptions.project&&this.clientOptions.location||this.clientOptions.apiKey)&&!this.customBaseUrl)throw new Error("Authentication is not set up. Please provide either a project and location, or an API key, or a custom base URL.");let u=e.project&&e.location||!!e.apiKey;this.customBaseUrl&&!u?(r.baseUrl=this.customBaseUrl,this.clientOptions.project=void 0,this.clientOptions.location=void 0):this.clientOptions.apiKey&&!this.clientOptions.project||this.clientOptions.location==="global"?r.baseUrl="https://aiplatform.googleapis.com/":this.clientOptions.project&&this.clientOptions.location&&xC.has(this.clientOptions.location)?r.baseUrl=`https://aiplatform.${this.clientOptions.location}.rep.googleapis.com/`:this.clientOptions.project&&this.clientOptions.location&&(r.baseUrl=`https://${this.clientOptions.location}-aiplatform.googleapis.com/`),r.apiVersion=(o=this.clientOptions.apiVersion)!==null&&o!==void 0?o:kC}else this.clientOptions.apiKey||console.warn("API key should be set when using the Gemini API."),r.apiVersion=(i=this.clientOptions.apiVersion)!==null&&i!==void 0?i:NC,r.baseUrl="https://generativelanguage.googleapis.com/";r.headers=this.getDefaultHeaders(),this.clientOptions.httpOptions=r,e.httpOptions&&(this.clientOptions.httpOptions=this.patchHttpOptions(r,e.httpOptions))}isVertexAI(){var e;return(e=this.clientOptions.vertexai)!==null&&e!==void 0?e:!1}getProject(){return this.clientOptions.project}getLocation(){return this.clientOptions.location}getCustomBaseUrl(){return this.customBaseUrl}async getAuthHeaders(){let 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.")}getFetch(){var e;return(e=this.clientOptions.httpOptions)===null||e===void 0?void 0:e.fetch}getTimeout(){var e;return(e=this.clientOptions.httpOptions)===null||e===void 0?void 0:e.timeout}getRequestUrlInternal(e){if(!e||e.baseUrl===void 0||e.apiVersion===void 0)throw new Error("HTTP options are not correctly set.");let 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(){let 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){let i=[this.getRequestUrlInternal(n)];return o&&i.push(this.getBaseResourcePath()),e!==""&&i.push(e),new URL(`${i.join("/")}`)}shouldPrependVertexProjectPath(e,n){return!(n.baseUrl&&n.baseUrlResourceScope===Ms.COLLECTION||!this.clientOptions.vertexai||!this.clientOptions.project||!this.clientOptions.location||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));let o=this.shouldPrependVertexProjectPath(e,n),i=this.constructUrl(e.path,n,o);if(e.queryParams)for(let[a,u]of Object.entries(e.queryParams))i.searchParams.append(a,String(u));let r={};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 r.body=e.body;return r=await this.includeExtraHttpOptionsToRequestInit(r,n,i.toString()),this.unaryApiCall(i,r,e.httpMethod,n.retryOptions,n.timeout,e.abortSignal,n.fetch)}patchHttpOptions(e,n){let o=JSON.parse(JSON.stringify(e));e.fetch&&(o.fetch=e.fetch);for(let[i,r]of Object.entries(n))typeof r=="object"?o[i]=Object.assign(Object.assign({},o[i]),r):r!==void 0&&(o[i]=r);return o}async requestStream(e){let n=this.clientOptions.httpOptions;e.httpOptions&&(n=this.patchHttpOptions(this.clientOptions.httpOptions,e.httpOptions));let o=this.shouldPrependVertexProjectPath(e,n),i=this.constructUrl(e.path,n,o);(!i.searchParams.has("alt")||i.searchParams.get("alt")!=="sse")&&i.searchParams.set("alt","sse");let r={};return r.body=e.body,r=await this.includeExtraHttpOptionsToRequestInit(r,n,i.toString()),this.streamApiCall(i,r,e.httpMethod,n.retryOptions,n.timeout,e.abortSignal,n.fetch)}async includeExtraHttpOptionsToRequestInit(e,n,o){return DC()&&!n?.fetch&&!("dispatcher"in e)&&(e.dispatcher=MC()),n&&n.extraBody!==null&&HC(e,n.extraBody),e.headers=await this.getHeadersInternal(n,o),e}async unaryApiCall(e,n,o,i,r,a,u){return this.apiCall(e.toString(),Object.assign(Object.assign({},n),{method:o}),i,r,a,u).then(async c=>(await Ps(c),new wt(c))).catch(c=>{throw c instanceof Error?c:new Error(`exception ${c} sending request`,{cause:c})})}async streamApiCall(e,n,o,i,r,a,u){return this.apiCall(e.toString(),Object.assign(Object.assign({},n),{method:o}),i,r,a,u).then(async c=>(await Ps(c),this.processStreamResponse(c))).catch(c=>{throw c instanceof Error?c:new Error(`exception ${c} sending request`,{cause:c})})}processStreamResponse(e){return St(this,arguments,function*(){var o;let i=(o=e?.body)===null||o===void 0?void 0:o.getReader(),r=new TextDecoder("utf-8");if(!i)throw new Error("Response body is empty");try{let a="",u="data:",c=[`
32
+
33
+ `,"\r\r",`\r
34
+ \r
35
+ `];for(;;){let{done:d,value:f}=yield re(i.read());if(d){if(a.trim().length>0)throw new Error("Incomplete JSON segment at the end");break}let p=r.decode(f,{stream:!0});rf(p),a+=p;let h=-1,g=0;for(;;){h=-1,g=0;for(let v of c){let y=a.indexOf(v);y!==-1&&(h===-1||y<h)&&(h=y,g=v.length)}if(h===-1)break;let _=a.substring(0,h);a=a.substring(h+g);let m=_.trim();if(m.startsWith(u)){let v=m.substring(u.length).trim();rf(v);try{let y=new Response(v,{headers:e?.headers,status:e?.status,statusText:e?.statusText});yield yield re(new wt(y))}catch(y){throw new Error(`exception parsing stream chunk ${v}. ${y}`)}}}}}finally{i.releaseLock()}})}async apiCall(e,n,o,i,r,a){var u,c,d,f,p,h;let g=a??fetch,_=(u=o?.httpStatusCodes)!==null&&u!==void 0?u:FC,m=async()=>{let A=UC(i,r),C;try{C=await g(e,Object.assign(Object.assign({},n),{signal:A.signal}))}catch(w){throw A.dispose(),w}if(!o||C.ok||!_.includes(C.status))return C;try{await Ps(C)}finally{A.dispose()}return C};if(!o)return m();let v=Math.max(1,(c=o.attempts)!==null&&c!==void 0?c:GC),y=Math.round(((d=o.initialDelay)!==null&&d!==void 0?d:bC)*1e3),E=Math.max(y,Math.round(((f=o.maxDelay)!==null&&f!==void 0?f:LC)*1e3));return(0,Lf.default)(m,{retries:v-1,factor:(p=o.expBase)!==null&&p!==void 0?p:qC,minTimeout:y,maxTimeout:E,randomize:((h=o.jitter)!==null&&h!==void 0?h:OC)>0,onFailedAttempt:A=>{var C;if(r?.aborted)throw(C=A.error)!==null&&C!==void 0?C:A}})}getDefaultHeaders(){let e={},n=PC+" "+this.clientOptions.userAgentExtra;return e[wC]=n,e[aa]=n,e[IC]="application/json",e}async getHeadersInternal(e,n){let o=new Headers;if(e&&e.headers)for(let[i,r]of Object.entries(e.headers))o.append(i,r);return e?.timeout&&e.timeout>0&&o.append(SC,String(Math.ceil(e.timeout/1e3))),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;let i={};n!=null&&(i.mimeType=n.mimeType,i.name=n.name,i.displayName=n.displayName),i.name&&!i.name.startsWith("files/")&&(i.name=`files/${i.name}`);let r=this.clientOptions.uploader,a=await r.stat(e);i.sizeBytes=String(a.size);let u=(o=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.");i.mimeType=u;let c={file:i},d=this.getFileName(e),f=X("upload/v1beta/files",c._url),p=await this.fetchUploadUrl(f,i.sizeBytes,i.mimeType,d,c,n?.httpOptions);return r.upload(e,p,this)}async uploadFileToFileSearchStore(e,n,o){var i;let r=this.clientOptions.uploader,a=await r.stat(n),u=String(a.size),c=(i=o?.mimeType)!==null&&i!==void 0?i:a.type;if(c===void 0||c==="")throw new Error("Can not determine mimeType. Please provide mimeType in the config.");let d=`upload/v1beta/${e}:uploadToFileSearchStore`,f=this.getFileName(n),p={};o!=null&&hp(o,p);let h=await this.fetchUploadUrl(d,u,c,f,p,o?.httpOptions);return r.uploadToFileSearchStore(n,h,this)}async downloadFile(e){await this.clientOptions.downloader.download(e,this)}async fetchUploadUrl(e,n,o,i,r,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}`},i?{"X-Goog-Upload-File-Name":i}:{})};let d=await this.request({path:e,body:JSON.stringify(r),httpMethod:"POST",httpOptions:c});if(!d||!d?.headers)throw new Error("Server did not return an HttpResponse or the returned HttpResponse did not have headers.");let f=(u=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}};function rf(t){try{let e=JSON.parse(t);if(e!==null&&typeof e=="object"&&"error"in e&&e.error!==null&&typeof e.error=="object"){let n=e.error,o=n.status,i=n.code,r=`got status: ${o}. ${JSON.stringify(e)}`;if(typeof i=="number"&&i>=400&&i<600)throw new Xn({message:r,status:i})}}catch(e){let n=e;if(n?.name==="ApiError")throw e}}async function Ps(t){var e;if(t===void 0)throw new Error("response is undefined");if(!t.ok){let n=t.status,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}};let i=JSON.stringify(o);throw n>=400&&n<600?new Xn({message:i,status:n}):new Error(i)}}function HC(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{let r=JSON.parse(t.body);if(typeof r=="object"&&r!==null&&!Array.isArray(r))n=r;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(r,a){let u=Object.assign({},r);for(let c in a)if(Object.prototype.hasOwnProperty.call(a,c)){let 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}let i=o(n,e);t.body=JSON.stringify(i)}var VC="mcp_used/unknown",BC=!1;function mp(t){for(let e of t)if($C(e)||typeof e=="object"&&"inputSchema"in e)return!0;return BC}function gp(t){var e;let n=(e=t[aa])!==null&&e!==void 0?e:"";t[aa]=(n+` ${VC}`).trimStart()}function $C(t){return t!==null&&typeof t=="object"&&t instanceof ua}function XC(t){return St(this,arguments,function*(n,o=100){let i,r=0;for(;r<o;){let a=yield re(n.listTools({cursor:i}));for(let u of a.tools)yield yield re(u),r++;if(!a.nextCursor)break;i=a.nextCursor}})}var ua=class t{constructor(e=[],n){this.mcpTools=[],this.functionNameToMcpClient={},this.mcpClients=e,this.config=n}static create(e,n){return new t(e,n)}async initialize(){var e,n,o,i;if(this.mcpTools.length>0)return;let r={},a=[];for(let f of this.mcpClients)try{for(var u=!0,c=(n=void 0,jt(XC(f))),d;d=await c.next(),e=d.done,!e;u=!0){i=d.value,u=!1;let p=i;a.push(p);let h=p.name;if(r[h])throw new Error(`Duplicate function name ${h} found in MCP tools. Please ensure function names are unique.`);r[h]=f}}catch(p){n={error:p}}finally{try{!u&&!e&&(o=c.return)&&await o.call(c)}finally{if(n)throw n.error}}this.mcpTools=a,this.functionNameToMcpClient=r}async tool(){return await this.initialize(),tv(this.mcpTools,this.config)}async callTool(e){await this.initialize();let n=[];for(let o of e)if(o.name in this.functionNameToMcpClient){let i=this.functionNameToMcpClient[o.name],r;this.config.timeout&&(r={timeout:this.config.timeout});let a=await i.callTool({name:o.name,arguments:o.args},void 0,r);n.push({functionResponse:{name:o.name,response:a.isError?{error:a}:a}})}return n}};async function JC(t,e,n){let o=new Zs,i;n.data instanceof Blob?i=JSON.parse(await n.data.text()):i=JSON.parse(n.data),Object.assign(o,i),e(o)}var ca=class{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.");let i=this.apiClient.getWebsocketBaseUrl(),r=this.apiClient.getApiVersion(),a=YC(this.apiClient.getDefaultHeaders()),u=this.apiClient.getApiKey(),c=`${i}/ws/google.ai.generativelanguage.${r}.GenerativeService.BidiGenerateMusic?key=${u}`,d=()=>{},f=new Promise(A=>{d=A}),p=e.callbacks,h=function(){d({})},g=this.apiClient,_={onopen:h,onmessage:A=>{JC(g,p.onmessage,A)},onerror:(n=p?.onerror)!==null&&n!==void 0?n:function(A){},onclose:(o=p?.onclose)!==null&&o!==void 0?o:function(A){}},m=this.webSocketFactory.create(c,KC(a),_);m.connect(),await f;let E={setup:{model:ye(this.apiClient,e.model)}};return m.send(JSON.stringify(E)),new da(m,this.apiClient)}},da=class{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.");let n=rT(e);this.conn.send(JSON.stringify({clientContent:n}))}async setMusicGenerationConfig(e){e.musicGenerationConfig||(e.musicGenerationConfig={});let n=iT(e);this.conn.send(JSON.stringify(n))}sendPlaybackControl(e){let n={playbackControl:e};this.conn.send(JSON.stringify(n))}play(){this.sendPlaybackControl(yn.PLAY)}pause(){this.sendPlaybackControl(yn.PAUSE)}stop(){this.sendPlaybackControl(yn.STOP)}resetContext(){this.sendPlaybackControl(yn.RESET_CONTEXT)}close(){this.conn.close()}};function KC(t){let e={};return t.forEach((n,o)=>{e[o]=n}),e}function YC(t){let e=new Headers;for(let[n,o]of Object.entries(t))e.append(n,o);return e}var WC="FunctionResponse request must have an `id` field from the response of a ToolCall.FunctionalCalls in Google AI.";async function zC(t,e,n){let o=new Qs,i;n.data instanceof Blob?i=await n.data.text():n.data instanceof ArrayBuffer?i=new TextDecoder().decode(n.data):i=n.data;let r=JSON.parse(i);if(t.isVertexAI()){let a=lT(r);Object.assign(o,a)}else Object.assign(o,r);e(o)}var fa=class{constructor(e,n,o){this.apiClient=e,this.auth=n,this.webSocketFactory=o,this.music=new ca(this.apiClient,this.auth,this.webSocketFactory)}async connect(e){var n,o,i,r,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.");let c=this.apiClient.getWebsocketBaseUrl(),d=this.apiClient.getApiVersion(),f,p=this.apiClient.getHeaders();e.config&&e.config.tools&&mp(e.config.tools)&&gp(p);let h=jC(p);if(this.apiClient.isVertexAI()){let D=this.apiClient.getProject(),Q=this.apiClient.getLocation(),te=this.apiClient.getApiKey(),Ae=!!D&&!!Q||!!te;this.apiClient.getCustomBaseUrl()&&!Ae?f=c:(f=`${c}/ws/google.cloud.aiplatform.${d}.LlmBidiService/BidiGenerateContent`,await this.auth.addAuthHeaders(h,f))}else{let D=this.apiClient.getApiKey(),Q="BidiGenerateContent",te="key";D?.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."),Q="BidiGenerateContentConstrained",te="access_token"),f=`${c}/ws/google.ai.generativelanguage.${d}.GenerativeService.${Q}?${te}=${D}`}let g=()=>{},_=new Promise(D=>{g=D}),m=e.callbacks,v=function(){var D;(D=m?.onopen)===null||D===void 0||D.call(m),g({})},y=this.apiClient,E=!1,A=[],C=()=>{},w=new Promise(D=>{C=D}),N={onopen:v,onmessage:D=>{zC(y,Q=>{Q.setupComplete&&!j.setupComplete&&(j.setupComplete=Q.setupComplete,C({})),E?m.onmessage(Q):A.push(Q)},D)},onerror:(n=m?.onerror)!==null&&n!==void 0?n:function(D){},onclose:(o=m?.onclose)!==null&&o!==void 0?o:function(D){}},q=this.webSocketFactory.create(f,ZC(h),N);q.connect(),await _;let V=ye(this.apiClient,e.model);if(this.apiClient.isVertexAI()&&V.startsWith("publishers/")){let D=this.apiClient.getProject(),Q=this.apiClient.getLocation();D&&Q&&(V=`projects/${D}/locations/${Q}/`+V)}let M={};this.apiClient.isVertexAI()&&((i=e.config)===null||i===void 0?void 0:i.responseModalities)===void 0&&(e.config===void 0?e.config={responseModalities:[Qo.AUDIO]}:e.config.responseModalities=[Qo.AUDIO]),!((r=e.config)===null||r===void 0)&&r.generationConfig&&console.warn("Setting `LiveConnectConfig.generation_config` is deprecated, please set the fields on `LiveConnectConfig` directly. It will be removed in the next major version (not before 7/31/2026).");let O=(u=(a=e.config)===null||a===void 0?void 0:a.tools)!==null&&u!==void 0?u:[],H=[];for(let D of O)if(this.isCallableTool(D)){let Q=D;H.push(await Q.tool())}else H.push(D);H.length>0&&(e.config.tools=H);let $={model:V,config:e.config,callbacks:e.callbacks};this.apiClient.isVertexAI()?M=oT(this.apiClient,$):M=nT(this.apiClient,$),delete M.config;let j=new pa(q,this.apiClient);q.send(JSON.stringify(M)),await w,E=!0;for(let D of A)m.onmessage(D);return j}isCallableTool(e){return"callTool"in e&&typeof e.callTool=="function"}},QC={turnComplete:!0},pa=class{constructor(e,n){this.conn=e,this.apiClient=n}tLiveClientContent(e,n){if(n.turns!==null&&n.turns!==void 0){let o=[];try{o=Oe(n.turns),e.isVertexAI()||(o=o.map(i=>zn(i)))}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(let r of o){if(typeof r!="object"||r===null||!("name"in r)||!("response"in r))throw new Error(`Could not parse function response, type '${typeof r}'.`);if(!e.isVertexAI()&&!("id"in r))throw new Error(WC)}return{toolResponse:{functionResponses:o}}}sendClientContent(e){e=Object.assign(Object.assign({},QC),e);let n=this.tLiveClientContent(this.apiClient,e);this.conn.send(JSON.stringify(n))}sendRealtimeInput(e){let n={};this.apiClient.isVertexAI()?n={realtimeInput:aT(e)}:n={realtimeInput:sT(e)},this.conn.send(JSON.stringify(n))}sendToolResponse(e){if(e.functionResponses==null)throw new Error("Tool response parameters are required.");let n=this.tLiveClienttToolResponse(this.apiClient,e);this.conn.send(JSON.stringify(n))}sendContextUpdate(e){let n={};this.apiClient.isVertexAI()?n={contextUpdate:QE(e)}:n={contextUpdate:zE(e)},this.conn.send(JSON.stringify(n))}close(){this.conn.close()}};function ZC(t){let e={};return t.forEach((n,o)=>{e[o]=n}),e}function jC(t){let e=new Headers;for(let[n,o]of Object.entries(t))e.append(n,o);return e}var sf=10;function af(t){var e,n,o;if(!((e=t?.automaticFunctionCalling)===null||e===void 0)&&e.disable)return!0;let i=!1;for(let a of(n=t?.tools)!==null&&n!==void 0?n:[])if(Tn(a)){i=!0;break}if(!i)return!0;let r=(o=t?.automaticFunctionCalling)===null||o===void 0?void 0:o.maximumRemoteCalls;return r&&(r<0||!Number.isInteger(r))||r==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:",r),!0):!1}function Tn(t){return"callTool"in t&&typeof t.callTool=="function"}function e0(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(i=>Tn(i)))!==null&&o!==void 0?o:!1}function lf(t){var e;let n=[];return!((e=t?.config)===null||e===void 0)&&e.tools&&t.config.tools.forEach((o,i)=>{if(Tn(o))return;let r=o;r.functionDeclarations&&r.functionDeclarations.length>0&&n.push(i)}),n}function uf(t){var e;return!(!((e=t?.automaticFunctionCalling)===null||e===void 0)&&e.ignoreCallHistory)}function zo(t,e=!0){return!t||t.automaticContinuation===void 0||t.automaticContinuation===null?e:!!t.automaticContinuation}function vl(t){return t===void 0||t===Se.CONTINUATION}function _p(t,e,n,o=!1){return t&&!o&&!!e&&vl(n)}var t0=3;function n0(t,e,n){var o;let i=(o=t.candidates)===null||o===void 0?void 0:o[0];i?.finishReason!==void 0&&_p(e,n,i.finishReason)&&(i.finishReason=void 0)}function o0(t,e){var n;return!!(!((n=e?.abortSignal)===null||n===void 0)&&n.aborted)||t instanceof Error&&t.name==="AbortError"}var i0=class{constructor(e){this.config=e,this.reconnectsWithoutProgress=0,this.hop=cf(void 0),this.enableContinuation=zo(e,!0)}startHop(){return this.hop=cf(this.resumeToken),yp(this.config,this.resumeToken)}observe(e){var n,o;let i=this.hop;if(i.receivedAnyChunk=!0,e.promptFeedback!==void 0&&e.promptFeedback!==null&&(i.hasPromptFeedback=!0),e.usageMetadata)if(this.accumulatedUsageAcrossHops){let a=vp(this.accumulatedUsageAcrossHops,e.usageMetadata);e=Object.assign(new ct,e,{usageMetadata:a}),i.usage=a}else Bn(e.usageMetadata),i.usage=e.usageMetadata;let r=(n=e.candidates)===null||n===void 0?void 0:n[0];return r&&(!((o=r.content)===null||o===void 0)&&o.parts&&r.content.parts.length>0&&(i.hasYieldedContent=!0),r.finishReason!==void 0&&(i.finishReason=r.finishReason),r.continuationToken?i.token=r.continuationToken:r.finishReason!==void 0&&!vl(r.finishReason)&&(i.token=void 0),n0(e,this.enableContinuation,i.token)),e}endHop(e){let n=this.hop;if(n.usage&&(this.accumulatedUsageAcrossHops=n.usage),e&&(o0(e.error,this.config)||e.error instanceof Xn&&!n.receivedAnyChunk))throw e.error;let o=n.hasYieldedContent||!!n.token&&n.token!==n.startToken;if(e?this.lastError=e:o&&(this.lastError=void 0),[this.resumeToken,this.reconnectsWithoutProgress]=this.nextResumeToken(),_p(this.enableContinuation,this.resumeToken,n.finishReason,n.hasPromptFeedback))return!0;if(e)throw e.error;if(n.finishReason===void 0&&!n.hasPromptFeedback&&this.lastError)throw this.lastError.error;return!1}nextResumeToken(){let e=this.hop,n=this.reconnectsWithoutProgress;return e.finishReason!==void 0||e.hasPromptFeedback?e.finishReason===Se.CONTINUATION&&!e.hasPromptFeedback&&e.token&&e.token!==e.startToken?[e.token,0]:[void 0,0]:e.token&&e.token!==e.startToken?[e.token,0]:e.hasYieldedContent||n>=t0?[void 0,n]:[e.startToken,n+1]}};function cf(t){return{startToken:t,hasPromptFeedback:!1,hasYieldedContent:!1,receivedAnyChunk:!1}}function r0(t){var e;let n=(e=t?.candidates)===null||e===void 0?void 0:e[0];if(n?.continuationToken&&vl(n.finishReason))return n.continuationToken}function yp(t,e,n=!1){let o=t?.automaticContinuation!==void 0&&t?.automaticContinuation!==null,i=n&&o;if(!e&&!i)return t;if(!t)return e?{continuationToken:e}:void 0;let r=Object.assign({},t);return e&&(r.continuationToken=e),i&&delete r.automaticContinuation,r}function s0(t,e){var n,o;let i=new Map,r=[];for(let a of[...t,...e]){let u=a.modality;i.has(u)||(i.set(u,0),r.push(u)),i.set(u,((n=i.get(u))!==null&&n!==void 0?n:0)+((o=a.tokenCount)!==null&&o!==void 0?o:0))}return r.map(a=>{var u;return{modality:a,tokenCount:(u=i.get(a))!==null&&u!==void 0?u:0}})}function a0(t,e){let n=new Map,o=[];for(let i of[...t,...e]){let r=i.category;n.has(r)||o.push(r),n.set(r,i)}return o.map(i=>n.get(i))}function df(t){if(typeof t!="object"||t===null||Array.isArray(t)||t instanceof wt)return!1;let e=Object.getPrototypeOf(t);return e===null||e===Object.prototype||t instanceof ct||t instanceof Us||t instanceof jo}function ff(t,e){return t.endsWith("TokensDetails")?!0:e.length>0&&typeof e[0]=="object"&&e[0]!==null&&"modality"in e[0]}function l0(t,e){if(t.length===0)return e;if(e.length===0)return t.map(i=>Jn(i,{},!0,!1));let n=[],o=Math.min(t.length,e.length);for(let i=0;i<o;i++)n.push(Jn(t[i],e[i],!0,!1));return t.length>o&&n.push(...t.slice(o)),e.length>o&&n.push(...e.slice(o)),n}function fi(t){var e;if(t)return(e=t._initialPromptTokenCount)!==null&&e!==void 0?e:t.promptTokenCount}function Bn(t,e){let n=e??fi(t);return n!==void 0&&Object.defineProperty(t,"_initialPromptTokenCount",{value:n,enumerable:!1,configurable:!0,writable:!0}),!(t instanceof jo)&&!Object.prototype.hasOwnProperty.call(t,"initialPromptTokenCount")&&Object.defineProperty(t,"initialPromptTokenCount",{get(){return fi(this)},enumerable:!1,configurable:!0}),t}function vp(t,e){var n;if(!e)return t&&Bn(t);if(!t)return Bn(e);let o=(n=fi(t))!==null&&n!==void 0?n:fi(e),i=Jn(t,e,!1,!0);return Bn(i,o)}function u0(t,e){let n=e.groundingMetadata,o=n?.groundingSupports;if(!Array.isArray(o)||o.length===0)return e;let i=t.content,r=Array.isArray(i?.parts)?i.parts.length:0,a=t.groundingMetadata,u=Array.isArray(a?.groundingChunks)?a.groundingChunks.length:0;if(r===0&&u===0)return e;let c=o.map(d=>{var f;if(!d||typeof d!="object")return d;let p=Object.assign({},d);return u>0&&Array.isArray(d.groundingChunkIndices)&&d.groundingChunkIndices.length>0&&(p.groundingChunkIndices=d.groundingChunkIndices.map(h=>h+u)),r>0&&d.segment&&typeof d.segment=="object"&&(p.segment=Object.assign(Object.assign({},d.segment),{partIndex:((f=d.segment.partIndex)!==null&&f!==void 0?f:0)+r})),p});return Object.assign(Object.assign({},e),{groundingMetadata:Object.assign(Object.assign({},n),{groundingSupports:c})})}function Jn(t,e,n=!1,o=!1){n&&(e=u0(t,e));let i={},r=new Set([...Object.keys(t),...Object.keys(e)]);for(let a of r){let u=t[a],c=e[a];if(n&&(a==="continuationToken"||a==="finishReason"||a==="finishMessage")){c!==void 0&&(i[a]=c);continue}if(!n&&!o&&a==="candidates"&&Array.isArray(u)){i[a]=l0(u,Array.isArray(c)?c:[]);continue}if(a==="usageMetadata"){let d=vp(u,c);d!==void 0&&(i[a]=d);continue}c==null?u!==void 0&&(i[a]=u):u==null?i[a]=c:typeof u=="number"&&typeof c=="number"&&(o||a==="tokenCount"||a.endsWith("TokenCount")||a.endsWith("Count")||a.endsWith("Sum"))?i[a]=u+c:Array.isArray(u)&&Array.isArray(c)?ff(a,u)||ff(a,c)?i[a]=s0(u,c):a==="safetyRatings"?i[a]=a0(u,c):i[a]=[...u,...c]:df(u)&&df(c)?i[a]=Jn(u,c,!1,a==="usageMetadata"||o):i[a]=c}return i}function c0(t){if(t.length===0)return new ct;if(t.length===1)return t[0].usageMetadata&&Bn(t[0].usageMetadata),t[0];let e=t[0];for(let o=1;o<t.length;o++)e=Jn(e,t[o],!1,!1);let n=new ct;return Object.assign(n,e),n}var An=class t extends dt{constructor(e){super(),this.apiClient=e,this.embedContent=async n=>{if(!this.apiClient.isVertexAI())return n.model.includes("gemini-embedding-2")&&(n.contents=Oe(n.contents)),await this.embedContentInternal(n);if(n.model.includes("gemini")&&n.model!=="gemini-embedding-001"||n.model.includes("maas")){let i=Oe(n.contents);if(i.length>1)throw new Error("The embedContent API for this model only supports one content at a time.");let r=Object.assign(Object.assign({},n),{content:i[0],embeddingApiType:Zo.EMBED_CONTENT});return await this.embedContentInternal(r)}else{let i=Object.assign(Object.assign({},n),{embeddingApiType:Zo.PREDICT});return await this.embedContentInternal(i)}},this.generateContent=async n=>{var o,i,r,a,u;let c=await this.processParamsMaybeAddMcpUsage(n);if(this.maybeMoveToResponseJsonSchema(n),!e0(n)||af(n.config))return zo(n.config,!0)?await this.generateContentWithContinuation(c):await this.generateContentInternal(c);let d=lf(n);if(d.length>0){let m=d.map(v=>`tools[${v}]`).join(", ");throw new Error(`Automatic function calling with CallableTools (or MCP objects) and basic FunctionDeclarations is not yet supported. Incompatible tools found at ${m}.`)}let f,p,h=Oe(c.contents),g=(r=(i=(o=c.config)===null||o===void 0?void 0:o.automaticFunctionCalling)===null||i===void 0?void 0:i.maximumRemoteCalls)!==null&&r!==void 0?r:sf,_=0;for(;_<g&&(f=await this.generateContentWithContinuation(c),!(!f.functionCalls||f.functionCalls.length===0));){let m=f.candidates[0].content,v=[];for(let y of(u=(a=n.config)===null||a===void 0?void 0:a.tools)!==null&&u!==void 0?u:[])if(Tn(y)){let A=await y.callTool(f.functionCalls);v.push(...A)}_++,p={role:"user",parts:v},c.contents=Oe(c.contents),c.contents.push(m),c.contents.push(p),uf(c.config)&&(h.push(m),h.push(p))}return uf(c.config)&&(f.automaticFunctionCallingHistory=h),f},this.generateContentStream=async n=>{var o,i,r,a,u;if(this.maybeMoveToResponseJsonSchema(n),af(n.config)){let p=await this.processParamsMaybeAddMcpUsage(n);return zo(n.config,!0)?await this.generateContentStreamWithContinuation(p):await this.generateContentStreamInternal(p)}let c=lf(n);if(c.length>0){let p=c.map(h=>`tools[${h}]`).join(", ");throw new Error(`Incompatible tools found at ${p}. Automatic function calling with CallableTools (or MCP objects) and basic FunctionDeclarations" is not yet supported.`)}let d=(r=(i=(o=n?.config)===null||o===void 0?void 0:o.toolConfig)===null||i===void 0?void 0:i.functionCallingConfig)===null||r===void 0?void 0:r.streamFunctionCallArguments,f=(u=(a=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=>(t.loggedGenerateImagesWarning||(t.loggedGenerateImagesWarning=!0,console.warn("The generateImages method is deprecated and will be removed in the next major release (not before Jan. 1 2027). Please use the generateContent method with image models instead. See https://ai.google.dev/gemini-api/docs/deprecations#imagen-models and https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/capabilities/image-generation#generate-images")),await this.generateImagesInternal(n).then(o=>{var i;let r,a=[];if(o?.generatedImages)for(let c of o.generatedImages)c&&c?.safetyAttributes&&((i=c?.safetyAttributes)===null||i===void 0?void 0:i.contentType)==="Positive Prompt"?r=c?.safetyAttributes:a.push(c);let u;return r?u={generatedImages:a,positivePromptSafetyAttributes:r,sdkHttpResponse:o.sdkHttpResponse}:u={generatedImages:a,sdkHttpResponse:o.sdkHttpResponse},u})),this.list=async n=>{var o;let a={config:Object.assign(Object.assign({},{queryBase:!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 is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");a.config.filter="labels.tune-type:*"}return new Pt(Rt.PAGED_ITEM_MODELS,u=>this.listInternal(u),await this.listInternal(a),a)},this.editImage=async n=>{t.loggedEditImageWarning||(t.loggedEditImageWarning=!0,console.warn("The editImage method is deprecated and will be removed in the next major release (not before Jan. 1 2027). Please use the generateContent method with image models instead. See https://ai.google.dev/gemini-api/docs/deprecations#imagen-models and https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/capabilities/gemini-edit-images#edit-an-image"));let o={model:n.model,prompt:n.prompt,referenceImages:[],config:n.config};return n.referenceImages&&n.referenceImages&&(o.referenceImages=n.referenceImages.map(i=>i.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));let i={model:n.model,image:n.image,upscaleFactor:n.upscaleFactor,config:o};return await this.upscaleImageInternal(i)},this.generateVideos=async n=>{var o,i,r,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(n.prompt||n.image||n.video)&&(t.loggedGenerateVideosWarning||(t.loggedGenerateVideosWarning=!0,console.warn("The generateVideos method with prompt/image/video arguments is deprecated and will be removed in a future major release (not before 2026-07-31). Please use the source argument instead."))),this.apiClient.isVertexAI()||(!((o=n.video)===null||o===void 0)&&o.uri&&(!((i=n.video)===null||i===void 0)&&i.videoBytes)?n.video={uri:n.video.uri,mimeType:n.video.mimeType}:!((a=(r=n.source)===null||r===void 0?void 0:r.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)}}async generateContentWithContinuation(e){let n=zo(e.config,!0),o,i=[];for(;i.length===0||n&&o;){let r=yp(e.config,o),a=r===e.config?e:Object.assign(Object.assign({},e),{config:r}),u=await this.generateContentInternal(a);i.push(u),o=r0(u)}return c0(i)}async generateContentStreamWithContinuation(e){let n=new i0(e.config);n.startHop();let o=await this.generateContentStreamInternal(e);return(function(i,r,a){return St(this,arguments,function*(){var u,c,d,f;let p=async()=>a;for(;;){let m;try{try{for(var h=!0,g=(c=void 0,jt(yield re(p()))),_;_=yield re(g.next()),u=_.done,!u;h=!0){f=_.value,h=!1;let y=f;yield yield re(n.observe(y))}}catch(y){c={error:y}}finally{try{!h&&!u&&(d=g.return)&&(yield re(d.call(g)))}finally{if(c)throw c.error}}}catch(y){m={error:y}}if(!n.endHop(m))return yield re(void 0);let v=Object.assign(Object.assign({},r),{config:n.startHop()});p=()=>i.generateContentStreamInternal(v)}})})(this,e,o)}maybeMoveToResponseJsonSchema(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,i;let r=(n=e.config)===null||n===void 0?void 0:n.tools;if(!r)return e;let a=await Promise.all(r.map(async c=>Tn(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&&mp(e.config.tools)){let c=(i=(o=e.config.httpOptions)===null||o===void 0?void 0:o.headers)!==null&&i!==void 0?i:{},d=Object.assign({},c);Object.keys(d).length===0&&(d=this.apiClient.getDefaultHeaders()),gp(d),u.config.httpOptions=Object.assign(Object.assign({},e.config.httpOptions),{headers:d})}return u}async initAfcToolsMap(e){var n,o,i;let r=new Map;for(let a of(o=(n=e.config)===null||n===void 0?void 0:n.tools)!==null&&o!==void 0?o:[])if(Tn(a)){let u=a,c=await u.tool();for(let d of(i=c.functionDeclarations)!==null&&i!==void 0?i:[]){if(!d.name)throw new Error("Function declaration name is required.");if(r.has(d.name))throw new Error(`Duplicate tool declaration name: ${d.name}`);r.set(d.name,u)}}return r}async processAfcStream(e){var n,o,i;let r=(i=(o=(n=e.config)===null||n===void 0?void 0:n.automaticFunctionCalling)===null||o===void 0?void 0:o.maximumRemoteCalls)!==null&&i!==void 0?i:sf,a=!1,u=0,c=await this.initAfcToolsMap(e);return(function(d,f,p){return St(this,arguments,function*(){for(var h,g,_,m,v,y;u<r;){a&&(u++,a=!1);let w=yield re(d.processParamsMaybeAddMcpUsage(p)),N=yield re(d.generateContentStreamWithContinuation(w)),q=[],V=[];try{for(var E=!0,A=(g=void 0,jt(N)),C;C=yield re(A.next()),h=C.done,!h;E=!0){m=C.value,E=!1;let M=m;if(yield yield re(M),M.candidates&&(!((v=M.candidates[0])===null||v===void 0)&&v.content)){V.push(M.candidates[0].content);for(let O of(y=M.candidates[0].content.parts)!==null&&y!==void 0?y:[])if(u<r&&O.functionCall){if(!O.functionCall.name)throw new Error("Function call name was not returned by the model.");if(f.has(O.functionCall.name)){let H=yield re(f.get(O.functionCall.name).callTool([O.functionCall]));q.push(...H)}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()}, missing tool: ${O.functionCall.name}`)}}}}catch(M){g={error:M}}finally{try{!E&&!h&&(_=A.return)&&(yield re(_.call(A)))}finally{if(g)throw g.error}}if(q.length>0){a=!0;let M=new ct;M.candidates=[{content:{role:"user",parts:q}}],yield yield re(M);let O=[];O.push(...V),O.push({role:"user",parts:q});let H=Oe(p.contents).concat(O);p.contents=H}else break}})})(this,c,e)}async generateContentInternal(e){var n,o,i,r;let a,u="",c={};if(this.apiClient.isVertexAI()){let d=ef(this.apiClient,e);return u=X("{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(p=>{let h=p;return h.sdkHttpResponse={headers:f.headers},h})),a.then(f=>{let p=nf(f),h=new ct;return Object.assign(h,p),h})}else{let d=jd(this.apiClient,e);return u=X("{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:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(f=>f.json().then(p=>{let h=p;return h.sdkHttpResponse={headers:f.headers},h})),a.then(f=>{let p=tf(f),h=new ct;return Object.assign(h,p),h})}}async generateContentStreamInternal(e){var n,o,i,r;let a,u="",c={};if(this.apiClient.isVertexAI()){let d=ef(this.apiClient,e);return u=X("{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(p){return St(this,arguments,function*(){var h,g,_,m;try{for(var v=!0,y=jt(p),E;E=yield re(y.next()),h=E.done,!h;v=!0){m=E.value,v=!1;let A=m,C=nf(yield re(A.json()),e);C.sdkHttpResponse={headers:A.headers};let w=new ct;Object.assign(w,C),yield yield re(w)}}catch(A){g={error:A}}finally{try{!v&&!h&&(_=y.return)&&(yield re(_.call(y)))}finally{if(g)throw g.error}}})})}else{let d=jd(this.apiClient,e);return u=X("{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:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}),a.then(function(p){return St(this,arguments,function*(){var h,g,_,m;try{for(var v=!0,y=jt(p),E;E=yield re(y.next()),h=E.done,!h;v=!0){m=E.value,v=!1;let A=m,C=tf(yield re(A.json()),e);C.sdkHttpResponse={headers:A.headers};let w=new ct;Object.assign(w,C),yield yield re(w)}}catch(A){g={error:A}}finally{try{!v&&!h&&(_=y.return)&&(yield re(_.call(y)))}finally{if(g)throw g.error}}})})}}async embedContentInternal(e){var n,o,i,r;let a,u="",c={};if(this.apiClient.isVertexAI()){let d=BT(this.apiClient,e,e),f=ov(e.model)?"{model}:embedContent":"{model}:predict";return u=X(f,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(p=>p.json().then(h=>{let g=h;return g.sdkHttpResponse={headers:p.headers},g})),a.then(p=>{let h=XT(p,e),g=new ei;return Object.assign(g,h),g})}else{let d=VT(this.apiClient,e);return u=X("{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:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(f=>f.json().then(p=>{let h=p;return h.sdkHttpResponse={headers:f.headers},h})),a.then(f=>{let p=$T(f),h=new ei;return Object.assign(h,p),h})}}async generateImagesInternal(e){var n,o;let i,r="",a={};if(this.apiClient.isVertexAI()){let u=eA(this.apiClient,e);return r=X("{model}:predict",u._url),a=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:r,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=>{let f=d;return f.sdkHttpResponse={headers:c.headers},f})),i.then(c=>{let d=tA(c),f=new Gs;return Object.assign(f,d),f})}else throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async editImageInternal(e){var n,o;let i,r="",a={};if(this.apiClient.isVertexAI()){let u=qT(this.apiClient,e);return r=X("{model}:predict",u._url),a=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:r,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=>{let f=d;return f.sdkHttpResponse={headers:c.headers},f})),i.then(c=>{let d=OT(c),f=new bs;return Object.assign(f,d),f})}else throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async upscaleImageInternal(e){var n,o;let i,r="",a={};if(this.apiClient.isVertexAI()){let u=oC(this.apiClient,e);return r=X("{model}:predict",u._url),a=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:r,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=>{let f=d;return f.sdkHttpResponse={headers:c.headers},f})),i.then(c=>{let d=iC(c),f=new Ls;return Object.assign(f,d),f})}else throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async recontextImage(e){var n,o;let i,r="",a={};if(this.apiClient.isVertexAI()){let u=GA(this.apiClient,e);return r=X("{model}:predict",u._url),a=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:r,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()),i.then(c=>{let d=bA(c),f=new qs;return Object.assign(f,d),f})}else throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async segmentImage(e){var n,o;let i,r="",a={};if(this.apiClient.isVertexAI()){let u=BA(this.apiClient,e);return r=X("{model}:predict",u._url),a=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:r,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()),i.then(c=>{let d=$A(c),f=new Os;return Object.assign(f,d),f})}else throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async get(e){var n,o,i,r;let a,u="",c={};if(this.apiClient.isVertexAI()){let d=_A(this.apiClient,e);return u=X("{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=>sa(f))}else{let d=gA(this.apiClient,e);return u=X("{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:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(f=>f.json()),a.then(f=>ra(f))}}async listInternal(e){var n,o,i,r;let a,u="",c={};if(this.apiClient.isVertexAI()){let d=SA(this.apiClient,e);return u=X("{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(p=>{let h=p;return h.sdkHttpResponse={headers:f.headers},h})),a.then(f=>{let p=RA(f),h=new ti;return Object.assign(h,p),h})}else{let d=IA(this.apiClient,e);return u=X("{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:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(f=>f.json().then(p=>{let h=p;return h.sdkHttpResponse={headers:f.headers},h})),a.then(f=>{let p=wA(f),h=new ti;return Object.assign(h,p),h})}}async update(e){var n,o,i,r;let a,u="",c={};if(this.apiClient.isVertexAI()){let d=tC(this.apiClient,e);return u=X("{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=>sa(f))}else{let d=eC(this.apiClient,e);return u=X("{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:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(f=>f.json()),a.then(f=>ra(f))}}async delete(e){var n,o,i,r;let a,u="",c={};if(this.apiClient.isVertexAI()){let d=UT(this.apiClient,e);return u=X("{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(p=>{let h=p;return h.sdkHttpResponse={headers:f.headers},h})),a.then(f=>{let p=bT(f),h=new ni;return Object.assign(h,p),h})}else{let d=MT(this.apiClient,e);return u=X("{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:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(f=>f.json().then(p=>{let h=p;return h.sdkHttpResponse={headers:f.headers},h})),a.then(f=>{let p=GT(f),h=new ni;return Object.assign(h,p),h})}}async countTokens(e){var n,o,i,r;let a,u="",c={};if(this.apiClient.isVertexAI()){let d=NT(this.apiClient,e);return u=X("{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(p=>{let h=p;return h.sdkHttpResponse={headers:f.headers},h})),a.then(f=>{let p=DT(f),h=new oi;return Object.assign(h,p),h})}else{let d=kT(this.apiClient,e);return u=X("{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:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(f=>f.json().then(p=>{let h=p;return h.sdkHttpResponse={headers:f.headers},h})),a.then(f=>{let p=xT(f),h=new oi;return Object.assign(h,p),h})}}async computeTokens(e){var n,o;let i,r="",a={};if(this.apiClient.isVertexAI()){let u=AT(this.apiClient,e);return r=X("{model}:computeTokens",u._url),a=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:r,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=>{let f=d;return f.sdkHttpResponse={headers:c.headers},f})),i.then(c=>{let d=CT(c),f=new Fs;return Object.assign(f,d),f})}else throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async generateVideosInternal(e){var n,o,i,r;let a,u="",c={};if(this.apiClient.isVertexAI()){let d=aA(this.apiClient,e);return u=X("{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=>{let p=rA(f),h=new ii;return Object.assign(h,p),h})}else{let d=sA(this.apiClient,e);return u=X("{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:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(f=>f.json()),a.then(f=>{let p=iA(f),h=new ii;return Object.assign(h,p),h})}}};An.loggedGenerateImagesWarning=!1;An.loggedEditImageWarning=!1;An.loggedGenerateVideosWarning=!1;var ha=class extends dt{constructor(e){super(),this.apiClient=e}async getVideosOperation(e){let n=e.operation,o=e.config;if(n.name===void 0||n.name==="")throw new Error("Operation name is required.");if(this.apiClient.isVertexAI()){let i=n.name.split("/operations/")[0],r;o&&"httpOptions"in o&&(r=o.httpOptions);let a=await this.fetchPredictVideosOperationInternal({operationName:n.name,resourceName:i,config:{httpOptions:r}});return n._fromAPIResponse({apiResponse:a,_isVertexAI:!0})}else{let i=await this.getVideosOperationInternal({operationName:n.name,config:o});return n._fromAPIResponse({apiResponse:i,_isVertexAI:!1})}}async get(e){let n=e.operation,o=e.config;if(n.name===void 0||n.name==="")throw new Error("Operation name is required.");if(this.apiClient.isVertexAI()){let i=n.name.split("/operations/")[0],r;o&&"httpOptions"in o&&(r=o.httpOptions);let a=await this.fetchPredictVideosOperationInternal({operationName:n.name,resourceName:i,config:{httpOptions:r}});return n._fromAPIResponse({apiResponse:a,_isVertexAI:!0})}else{let i=await this.getVideosOperationInternal({operationName:n.name,config:o});return n._fromAPIResponse({apiResponse:i,_isVertexAI:!1})}}async getVideosOperationInternal(e){var n,o,i,r;let a,u="",c={};if(this.apiClient.isVertexAI()){let d=$y(e);return u=X("{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{let d=By(e);return u=X("{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:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(f=>f.json()),a}}async fetchPredictVideosOperationInternal(e){var n,o;let i,r="",a={};if(this.apiClient.isVertexAI()){let u=by(e);return r=X("{resourceName}:fetchPredictOperation",u._url),a=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:r,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()),i}else throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}};function d0(t){let e={},n=s(t,["apiKey"]);if(n!=null&&l(e,["apiKey"],n),s(t,["apiKeyConfig"])!==void 0)throw new Error("apiKeyConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["authType"])!==void 0)throw new Error("authType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["googleServiceAccountConfig"])!==void 0)throw new Error("googleServiceAccountConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["httpBasicAuthConfig"])!==void 0)throw new Error("httpBasicAuthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["oauthConfig"])!==void 0)throw new Error("oauthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["oidcConfig"])!==void 0)throw new Error("oidcConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return e}function f0(t){let e={},n=s(t,["parts"]);if(n!=null){let i=n;Array.isArray(i)&&(i=i.map(r=>E0(r))),l(e,["parts"],i)}let o=s(t,["role"]);return o!=null&&l(e,["role"],o),e}function p0(t,e,n){let o={},i=s(e,["expireTime"]);n!==void 0&&i!=null&&l(n,["expireTime"],i);let r=s(e,["newSessionExpireTime"]);n!==void 0&&r!=null&&l(n,["newSessionExpireTime"],r);let a=s(e,["uses"]);n!==void 0&&a!=null&&l(n,["uses"],a);let u=s(e,["liveConnectConstraints"]);n!==void 0&&u!=null&&l(n,["bidiGenerateContentSetup"],v0(t,u));let c=s(e,["lockAdditionalFields"]);return n!==void 0&&c!=null&&l(n,["fieldMask"],c),o}function h0(t,e){let n={},o=s(e,["config"]);return o!=null&&l(n,["config"],p0(t,o,n)),n}function m0(t){let e={},n=s(t,["args"]);n!=null&&l(e,["args"],n);let o=s(t,["id"]);o!=null&&l(e,["id"],o);let i=s(t,["name"]);if(i!=null&&l(e,["name"],i),s(t,["partialArgs"])!==void 0)throw new Error("partialArgs parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["willContinue"])!==void 0)throw new Error("willContinue parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return e}function g0(t){let e={},n=s(t,["authConfig"]);n!=null&&l(e,["authConfig"],d0(n));let o=s(t,["enableWidget"]);if(o!=null&&l(e,["enableWidget"],o),s(t,["groundingTypes"])!==void 0)throw new Error("groundingTypes parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return e}function _0(t){let e={};if(s(t,["blockingConfidence"])!==void 0)throw new Error("blockingConfidence parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["excludeDomains"])!==void 0)throw new Error("excludeDomains parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let n=s(t,["searchTypes"]);n!=null&&l(e,["searchTypes"],n);let o=s(t,["timeRangeFilter"]);return o!=null&&l(e,["timeRangeFilter"],o),e}function y0(t,e){let n={},o=s(t,["generationConfig"]);e!==void 0&&o!=null&&l(e,["setup","generationConfig"],o);let i=s(t,["responseModalities"]);e!==void 0&&i!=null&&l(e,["setup","generationConfig","responseModalities"],i);let r=s(t,["temperature"]);e!==void 0&&r!=null&&l(e,["setup","generationConfig","temperature"],r);let a=s(t,["topP"]);e!==void 0&&a!=null&&l(e,["setup","generationConfig","topP"],a);let u=s(t,["topK"]);e!==void 0&&u!=null&&l(e,["setup","generationConfig","topK"],u);let c=s(t,["maxOutputTokens"]);e!==void 0&&c!=null&&l(e,["setup","generationConfig","maxOutputTokens"],c);let d=s(t,["mediaResolution"]);e!==void 0&&d!=null&&l(e,["setup","generationConfig","mediaResolution"],d);let f=s(t,["seed"]);e!==void 0&&f!=null&&l(e,["setup","generationConfig","seed"],f);let p=s(t,["speechConfig"]);e!==void 0&&p!=null&&l(e,["setup","generationConfig","speechConfig"],_l(p));let h=s(t,["thinkingConfig"]);e!==void 0&&h!=null&&l(e,["setup","generationConfig","thinkingConfig"],h);let g=s(t,["enableAffectiveDialog"]);e!==void 0&&g!=null&&l(e,["setup","generationConfig","enableAffectiveDialog"],g);let _=s(t,["systemInstruction"]);e!==void 0&&_!=null&&l(e,["setup","systemInstruction"],f0(ke(_)));let m=s(t,["tools"]);if(e!==void 0&&m!=null){let O=Kt(m);Array.isArray(O)&&(O=O.map(H=>C0(Jt(H)))),l(e,["setup","tools"],O)}let v=s(t,["sessionResumption"]);e!==void 0&&v!=null&&l(e,["setup","sessionResumption"],A0(v));let y=s(t,["inputAudioTranscription"]);e!==void 0&&y!=null&&l(e,["setup","inputAudioTranscription"],y);let E=s(t,["outputAudioTranscription"]);e!==void 0&&E!=null&&l(e,["setup","outputAudioTranscription"],E);let A=s(t,["realtimeInputConfig"]);e!==void 0&&A!=null&&l(e,["setup","realtimeInputConfig"],A);let C=s(t,["contextWindowCompression"]);e!==void 0&&C!=null&&l(e,["setup","contextWindowCompression"],C);let w=s(t,["proactivity"]);if(e!==void 0&&w!=null&&l(e,["setup","proactivity"],w),s(t,["explicitVadSignal"])!==void 0)throw new Error("explicitVadSignal parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let N=s(t,["avatarConfig"]);e!==void 0&&N!=null&&l(e,["setup","avatarConfig"],N);let q=s(t,["safetySettings"]);if(e!==void 0&&q!=null){let O=q;Array.isArray(O)&&(O=O.map(H=>T0(H))),l(e,["setup","safetySettings"],O)}let V=s(t,["translationConfig"]);e!==void 0&&V!=null&&l(e,["setup","generationConfig","translationConfig"],V);let M=s(t,["labels"]);return e!==void 0&&M!=null&&l(e,["setup","labels"],M),n}function v0(t,e){let n={},o=s(e,["model"]);o!=null&&l(n,["setup","model"],ye(t,o));let i=s(e,["config"]);return i!=null&&l(n,["config"],y0(i,n)),n}function E0(t){let e={},n=s(t,["mediaResolution"]);n!=null&&l(e,["mediaResolution"],n);let o=s(t,["toolCall"]);o!=null&&l(e,["toolCall"],o);let i=s(t,["toolResponse"]);i!=null&&l(e,["toolResponse"],i);let r=s(t,["audioTranscription"]);r!=null&&l(e,["audioTranscription"],r);let a=s(t,["codeExecutionResult"]);a!=null&&l(e,["codeExecutionResult"],a);let u=s(t,["executableCode"]);u!=null&&l(e,["executableCode"],u);let c=s(t,["fileData"]);c!=null&&l(e,["fileData"],c);let d=s(t,["functionCall"]);d!=null&&l(e,["functionCall"],m0(d));let f=s(t,["functionResponse"]);f!=null&&l(e,["functionResponse"],f);let p=s(t,["inlineData"]);p!=null&&l(e,["inlineData"],p);let h=s(t,["text"]);h!=null&&l(e,["text"],h);let g=s(t,["thought"]);g!=null&&l(e,["thought"],g);let _=s(t,["thoughtSignature"]);_!=null&&l(e,["thoughtSignature"],_);let m=s(t,["videoMetadata"]);m!=null&&l(e,["videoMetadata"],m);let v=s(t,["partMetadata"]);v!=null&&l(e,["partMetadata"],v);let y=s(t,["mediaProcessing"]);y!=null&&l(e,["mediaProcessing"],y);let E=s(t,["speechMetadata"]);return E!=null&&l(e,["speechMetadata"],E),e}function T0(t){let e={},n=s(t,["category"]);if(n!=null&&l(e,["category"],n),s(t,["method"])!==void 0)throw new Error("method parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let o=s(t,["threshold"]);return o!=null&&l(e,["threshold"],o),e}function A0(t){let e={},n=s(t,["handle"]);if(n!=null&&l(e,["handle"],n),s(t,["transparent"])!==void 0)throw new Error("transparent parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return e}function C0(t){let e={};if(s(t,["retrieval"])!==void 0)throw new Error("retrieval parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let n=s(t,["googleMaps"]);n!=null&&l(e,["googleMaps"],g0(n));let o=s(t,["mcpServers"]);if(o!=null){let p=o;Array.isArray(p)&&(p=p.map(h=>h)),l(e,["mcpServers"],p)}let i=s(t,["codeExecution"]);i!=null&&l(e,["codeExecution"],i);let r=s(t,["computerUse"]);if(r!=null&&l(e,["computerUse"],r),s(t,["enterpriseWebSearch"])!==void 0)throw new Error("enterpriseWebSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["exaAiSearch"])!==void 0)throw new Error("exaAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let a=s(t,["functionDeclarations"]);if(a!=null){let p=a;Array.isArray(p)&&(p=p.map(h=>h)),l(e,["functionDeclarations"],p)}let u=s(t,["googleSearch"]);u!=null&&l(e,["googleSearch"],_0(u));let c=s(t,["googleSearchRetrieval"]);if(c!=null&&l(e,["googleSearchRetrieval"],c),s(t,["parallelAiSearch"])!==void 0)throw new Error("parallelAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let d=s(t,["urlContext"]);d!=null&&l(e,["urlContext"],d);let f=s(t,["fileSearch"]);return f!=null&&l(e,["fileSearch"],f),e}function I0(t){let e=[];for(let n in t)if(Object.prototype.hasOwnProperty.call(t,n)){let o=t[n];if(typeof o=="object"&&o!=null&&Object.keys(o).length>0){let i=Object.keys(o).map(r=>`${n}.${r}`);e.push(...i)}else e.push(n)}return e.join(",")}function S0(t,e){let n=null,o=t.bidiGenerateContentSetup;if(typeof o=="object"&&o!==null&&"setup"in o){let r=o.setup;typeof r=="object"&&r!==null?(t.bidiGenerateContentSetup=r,n=r):delete t.bidiGenerateContentSetup}else o!==void 0&&delete t.bidiGenerateContentSetup;let i=t.fieldMask;if(n){let r=I0(n);if(Array.isArray(e?.lockAdditionalFields)&&e?.lockAdditionalFields.length===0)r?t.fieldMask=r:delete t.fieldMask;else if(e?.lockAdditionalFields&&e.lockAdditionalFields.length>0&&i!==null&&Array.isArray(i)&&i.length>0){let a=["temperature","topK","topP","maxOutputTokens","responseModalities","seed","speechConfig"],u=[];i.length>0&&(u=i.map(d=>a.includes(d)?`generationConfig.${d}`:d));let c=[];r&&c.push(r),u.length>0&&c.push(...u),c.length>0?t.fieldMask=c.join(","):delete t.fieldMask}else delete t.fieldMask}else i!==null&&Array.isArray(i)&&i.length>0?t.fieldMask=i.join(","):delete t.fieldMask;return t}var ma=class extends dt{constructor(e){super(),this.apiClient=e}async create(e){var n,o;let i,r="",a={};if(this.apiClient.isVertexAI())throw new Error("The client.tokens.create method is only supported by the Gemini Developer API.");{let u=h0(this.apiClient,e);r=X("auth_tokens",u._url),a=u._query,delete u.config,delete u._url,delete u._query;let c=S0(u,e.config);return i=this.apiClient.request({path:r,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()),i.then(d=>d)}}};function w0(t,e){let n={},o=s(t,["force"]);return e!==void 0&&o!=null&&l(e,["_query","force"],o),n}function R0(t){let e={},n=s(t,["name"]);n!=null&&l(e,["_url","name"],n);let o=s(t,["config"]);return o!=null&&w0(o,e),e}function P0(t){let e={},n=s(t,["name"]);return n!=null&&l(e,["_url","name"],n),e}function k0(t,e){let n={},o=s(t,["pageSize"]);e!==void 0&&o!=null&&l(e,["_query","pageSize"],o);let i=s(t,["pageToken"]);return e!==void 0&&i!=null&&l(e,["_query","pageToken"],i),n}function N0(t){let e={},n=s(t,["parent"]);n!=null&&l(e,["_url","parent"],n);let o=s(t,["config"]);return o!=null&&k0(o,e),e}function x0(t){let e={},n=s(t,["sdkHttpResponse"]);n!=null&&l(e,["sdkHttpResponse"],n);let o=s(t,["nextPageToken"]);o!=null&&l(e,["nextPageToken"],o);let i=s(t,["documents"]);if(i!=null){let r=i;Array.isArray(r)&&(r=r.map(a=>a)),l(e,["documents"],r)}return e}var ga=class extends dt{constructor(e){super(),this.apiClient=e,this.list=async n=>new Pt(Rt.PAGED_ITEM_DOCUMENTS,o=>this.listInternal({parent:n.parent,config:o.config}),await this.listInternal(n),n)}async get(e){var n,o;let i,r="",a={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let u=P0(e);return r=X("{name}",u._url),a=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:r,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()),i.then(c=>c)}}async delete(e){var n,o;let i="",r={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let a=R0(e);i=X("{name}",a._url),r=a._query,delete a._url,delete a._query,await this.apiClient.request({path:i,queryParams:r,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 i,r="",a={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let u=N0(e);return r=X("{parent}/documents",u._url),a=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:r,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()),i.then(c=>{let d=x0(c),f=new Bs;return Object.assign(f,d),f})}}};var _a=class extends dt{constructor(e,n=new ga(e)){super(),this.apiClient=e,this.documents=n,this.list=async(o={})=>new Pt(Rt.PAGED_ITEM_FILE_SEARCH_STORES,i=>this.listInternal(i),await this.listInternal(o),o)}async uploadToFileSearchStore(e){if(this.apiClient.isVertexAI())throw new Error("Gemini Enterprise Agent Platform (previously known as Vertex AI) does not support uploading files to a file search store.");return this.apiClient.uploadFileToFileSearchStore(e.fileSearchStoreName,e.file,e.config)}async downloadMedia(e,n){if(this.apiClient.isVertexAI())throw new Error("This method is only supported in the Gemini Developer client.");let o=new URL(e,"http://dummy.com"),i=o.pathname;if(i.startsWith("/")&&(i=i.slice(1)),!i.includes("/media/"))throw new Error(`Invalid uri format: ${e}. Expected to contain /media/`);let r={};o.searchParams.forEach((c,d)=>{r[d]=c}),r.alt="media";let a=Object.assign({},n?.httpOptions),u=await this.apiClient.request({path:i,httpMethod:"GET",queryParams:r,httpOptions:a});if(u instanceof wt){let c=await u.responseInternal.arrayBuffer();return new Uint8Array(c)}else throw new Error("Unexpected response type from downloadMedia")}async create(e){var n,o;let i,r="",a={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let u=dC(this.apiClient,e);return r=X("fileSearchStores",u._url),a=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:r,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()),i.then(c=>c)}}async get(e){var n,o;let i,r="",a={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let u=hC(e);return r=X("{name}",u._url),a=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:r,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()),i.then(c=>c)}}async delete(e){var n,o;let i="",r={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let a=pC(e);i=X("{name}",a._url),r=a._query,delete a._url,delete a._query,await this.apiClient.request({path:i,queryParams:r,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 i,r="",a={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let u=EC(e);return r=X("fileSearchStores",u._url),a=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:r,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()),i.then(c=>{let d=TC(c),f=new $s;return Object.assign(f,d),f})}}async uploadToFileSearchStoreInternal(e){var n,o;let i,r="",a={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let u=AC(e);return r=X("upload/v1beta/{file_search_store_name}:uploadToFileSearchStore",u._url),a=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:r,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()),i.then(c=>{let d=CC(c),f=new Xs;return Object.assign(f,d),f})}}async importFile(e){var n,o;let i,r="",a={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let u=_C(e);return r=X("{file_search_store_name}:importFile",u._url),a=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:r,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()),i.then(c=>{let d=gC(c),f=new Js;return Object.assign(f,d),f})}}};var D0=3,M0="automatic_continuation: false cannot be used with background: true.",U0="Interaction stopped before completion (status='requires_continuation') with a continuation_token because the per-request decode token limit was reached. To resume decoding automatically, pass automatic_continuation: true (note: each continuation hop re-prefills and bills input tokens), or use background: true (the most cost-efficient option for server-managed continuation), or resume manually by passing continuation_token to interactions.create() (with previous_interaction_id set to this interaction's id and no input, or with the original input when store: false).",G0=new Set([void 0,"in_progress","requires_continuation"]),b0=new Set(["interaction.created","interaction.status_update"]),pf={cached_tokens_by_modality:["modality","tokens"],input_tokens_by_modality:["modality","tokens"],output_tokens_by_modality:["modality","tokens"],tool_use_tokens_by_modality:["modality","tokens"],grounding_tool_count:["type","count"]},hf=!1;function wi(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Ce(t,e){return wi(t)?t[e]:void 0}function Je(t){return typeof t=="string"&&t?t:void 0}function ya(t){return typeof t=="number"&&Number.isInteger(t)}function $n(t){return t==null}var Cn=class t extends Error{constructor(e){super(e),this.name="ContinuationTimeoutError",Object.setPrototypeOf(this,t.prototype)}},Kn=class{constructor(e,n={}){var o,i;this.timeoutMs=e,this.now=(o=n.now)!==null&&o!==void 0?o:Date.now,(!((i=n.enabled)!==null&&i!==void 0)||i)&&typeof e=="number"&&Number.isFinite(e)&&(this.deadlineMs=this.now()+e)}get bounded(){return this.deadlineMs!==void 0}remainingMs(){if(this.deadlineMs!==void 0)return this.deadlineMs-this.now()}expired(){let e=this.remainingMs();return e!==void 0&&e<=0}hopTimeoutMs(){let e=this.remainingMs();return e===void 0?this.timeoutMs:Math.max(1,Math.ceil(e))}check(){if(this.expired())throw new Cn(`interactions.create() timed out after ${this.timeoutMs} ms before automatic continuation finished. Increase the timeout (it bounds the whole call, across continuation hops) or resume from the continuation_token.`)}};function L0(t){return!$n(Ce(t,"agent"))||!$n(Ce(t,"agent_config"))}function q0(t,e,n){if(!(!!n&&t.store!==!1))return Object.assign(Object.assign({},t),{continuation_token:e});let{input:i}=t,r=Ie(t,["input"]);return Object.assign(Object.assign({},r),{continuation_token:e,previous_interaction_id:n})}function O0(t,e){let n=t.background===!0,o=t.stream===!0;if(n&&e===!1)throw new Error(M0);let i=(e??!0)!==!1&&!n&&!L0(t);return{body:t,stream:o,callerToken:Je(t.continuation_token),enableContinuation:i}}function mf(t,e,n){return e===void 0?t.body:q0(t.body,e,n)}function Ep(){hf||(hf=!0,console.warn(U0))}function F0(t){Cp(t)&&Ep()}function H0(t){return St(this,arguments,function*(){var n,o,i,r;let a,u;try{for(var c=!0,d=jt(t),f;f=yield re(d.next()),n=f.done,!n;c=!0){r=f.value,c=!1;let p=r;[a,u]=Tp(p,a,u),yield yield re(p)}}catch(p){o={error:p}}finally{try{!c&&!n&&(i=d.return)&&(yield re(i.call(d)))}finally{if(o)throw o.error}}a==="requires_continuation"&&u&&Ep()})}function Tp(t,e,n){let o=Ce(t,"event_type");if(o==="error")return["error",void 0];let i=Ce(t,"interaction");if(i!=null){let u=Je(Ce(i,"status"));u&&(e=u);let c=Je(Ce(i,"continuation_token"));(o==="interaction.completed"||c)&&(n=c)}let r=Je(Ce(t,"status"));r&&(e=r);let a=Je(Ce(t,"continuation_token"));return a&&(n=a),[e,n]}function V0(t,e){let n=Ce(t,"event_type");return n==="interaction.status_update"?Je(Ce(t,"continuation_token"))?!1:e:n==="interaction.completed"?!1:typeof n=="string"&&b0.has(n)?e:!0}function B0(t){var e;return(e=Je(Ce(t,"interaction_id")))!==null&&e!==void 0?e:Je(Ce(Ce(t,"interaction"),"id"))}function gf(t,e){return!!e&&G0.has(t)}function $0(t,e,n,o){return e==="requires_continuation"||o!==n?0:t+1}var va=class{constructor(e){this.options=e,this.hopIds=[],this.noProgressReconnects=0,this.nextToken=e.initialContinuationToken,this.initialToken=e.initialContinuationToken,this.hop={startToken:this.nextToken,startTokenOwnerId:void 0,token:this.nextToken,tokenOwnerId:void 0,interactionId:void 0,status:void 0,streamOpened:!1,contentSinceCheckpoint:!1}}startHop(e=!1){return this.hop={startToken:this.nextToken,startTokenOwnerId:this.nextTokenOwnerId,token:this.nextToken,tokenOwnerId:this.nextTokenOwnerId,interactionId:void 0,status:void 0,streamOpened:e,contentSinceCheckpoint:!1},[this.nextToken,this.nextTokenOwnerId]}markStreamOpened(){this.hop.streamOpened=!0}observe(e){let n=this.hop;n.streamOpened=!0;let o=B0(e);o&&(n.interactionId=o,this.hopIds.includes(o)||this.hopIds.push(o));let i=n.token;return[n.status,n.token]=Tp(e,n.status,n.token),n.token&&n.token!==i&&(n.tokenOwnerId=n.interactionId),n.contentSinceCheckpoint=V0(e,n.contentSinceCheckpoint),e}canResumeHop(){let e=this.hop;return!e.contentSinceCheckpoint&&gf(e.status,e.token)}fail(e){let n=this.hop,o=gf(n.status,n.token)?n.token:void 0;return!o||o===this.initialToken?e.error:new di({message:`Automatic continuation of the stream was interrupted: ${Ap(e.error)}. The continuationToken can be used to resume (output yielded after a mid-hop checkpoint is re-generated).`,cause:e.error,partialInteraction:void 0,continuationToken:o,interactionId:this.options.store!==!1?n.tokenOwnerId:void 0,continuationIds:[...this.hopIds]})}endHop(e){var n,o;let i=this.hop;if(e&&(e.error instanceof Cn||!((o=(n=this.options).isFatalError)===null||o===void 0)&&o.call(n,e.error)))throw this.fail(e);if(e&&!i.streamOpened&&!this.options.isConnectionError(e.error))throw this.fail(e);if(!this.canResumeHop()){if(e)throw this.fail(e);return!1}if(i.status==="requires_continuation"&&i.token===i.startToken){if(e)throw this.fail(e);return!1}if(this.noProgressReconnects=$0(this.noProgressReconnects,i.status,i.startToken,i.token),this.noProgressReconnects===0&&(this.lastError=void 0),e&&(this.lastError=e),this.noProgressReconnects>D0){if(this.lastError)throw this.fail(this.lastError);return!1}return this.nextToken=i.token,this.nextTokenOwnerId=i.tokenOwnerId,!0}};function Ap(t){return t instanceof Error?t.message||t.name:String(t)}async function _f(t){if(t?.return)try{await t.return()}catch{}}function X0(t,e,n){return St(this,arguments,function*(){var i,r;let a=(i=n.deadline)!==null&&i!==void 0?i:new Kn(void 0),u=(r=n.wrapIterationError)!==null&&r!==void 0?r:(p=>p),c=new va({initialContinuationToken:n.initialContinuationToken,isConnectionError:n.isConnectionError,isFatalError:n.isFatalError,store:n.store}),d,f=!0;try{for(;;){let[p,h]=c.startHop(f),g;if(f)f=!1,d=t[Symbol.asyncIterator]();else{yield re(_f(d)),d=void 0;try{a.check();let _=yield re(e(p,h));c.markStreamOpened(),d=_[Symbol.asyncIterator]()}catch(_){g={error:_}}}if(!g&&d)for(;;){let _;try{a.check(),_=yield re(d.next())}catch(m){g={error:m instanceof Cn?m:u(m)};break}if(_.done)break;yield yield re(c.observe(_.value))}if(!c.endHop(g))break}}finally{yield re(_f(d))}})}function Cp(t){if(Ce(t,"status")==="requires_continuation")return Je(Ce(t,"continuation_token"))}function J0(t,e){let n=Cp(t);if(n!==e)return n}function K0(t){return wi(t)&&Array.isArray(t.steps)?t:void 0}function Y0(t,e,n,o){let i=Sp(e,o),r=o.store!==!1&&Ce(e[0],"store")!==!1;return new di({message:`Automatic continuation was interrupted after ${e.length} completed hop(s): ${Ap(t)}. The partial interaction (status 'requires_continuation') and its continuationToken can be used to resume.`,cause:t,partialInteraction:i,continuationToken:n,interactionId:r?Je(Ce(e[e.length-1],"id")):void 0,continuationIds:Ip(e)})}async function W0(t,e,n={}){var o;let i=(o=n.deadline)!==null&&o!==void 0?o:new Kn(void 0),r=[t],a=n.initialContinuationToken;for(;;){let u=J0(r[r.length-1],a);if(!u)return Sp(r,n);let c;try{i.check(),c=await e(u,Je(Ce(r[r.length-1],"id")))}catch(d){throw Y0(d,r,u,n)}r.push(c),a=u}}function z0(t){let e=0;for(;e<t.length&&Ce(t[e],"type")==="user_input";)e++;return t.slice(e)}function Ip(t){let e=[];for(let n of t){let o=Ce(n,"continuation_ids");if(Array.isArray(o))for(let r of o)Je(r)&&e.push(r);let i=Je(Ce(n,"id"));i&&e.push(i)}return Array.from(new Set(e))}function Sp(t,e={}){var n,o;let i=(n=e.normalizeInteraction)!==null&&n!==void 0?n:K0,r=(o=e.finalizeInteraction)!==null&&o!==void 0?o:(p=>p),a=t[t.length-1],u=i(a);if(!u)return a;let c=[];t.forEach((p,h)=>{let g=Ce(p,"steps");Array.isArray(g)&&(h>0&&(g=z0(g)),c.push(...g))});let d=Object.assign(Object.assign({},u),{steps:c,continuation_ids:Ip(t)});if(t.length>1)for(let p of["previous_interaction_id","created","input"]){let h=Ce(t[0],p);h===void 0?delete d[p]:d[p]=h}let f=Z0(t.map(p=>Ce(p,"usage")).filter(wi));return f!==void 0&&(d.usage=f),r(d)}function Q0(t,e,n){let o=new Map;for(let i of t)for(let r of i){let a=Ce(r,e),u=Ce(r,n),c=o.get(a);if(c===void 0){o.set(a,r);continue}let d=Ce(c,n);ya(d)&&ya(u)&&wi(c)&&o.set(a,Object.assign(Object.assign({},c),{[n]:d+u}))}return Array.from(o.values())}function Z0(t){if(t.length===0)return;let e=t[0],n=t[t.length-1],o=[];for(let u of t)for(let c of Object.keys(u))o.includes(c)||o.push(c);let i={};for(let u of o){if(u==="initial_input_tokens")continue;let c=t.map(d=>d[u]).filter(d=>!$n(d));if(c.length!==0){if(c.every(ya))i[u]=c.reduce((d,f)=>d+f,0);else if(u in pf&&c.every(d=>Array.isArray(d))){let[d,f]=pf[u];i[u]=Q0(c,d,f)}}}let r=$n(e.initial_input_tokens)?e.total_input_tokens:e.initial_input_tokens,a=Object.assign(Object.assign({},n),i);return $n(r)?delete a.initial_input_tokens:a.initial_input_tokens=r,a}var j0=Object.prototype.hasOwnProperty;function se(t,e){let n=/\{([a-zA-Z0-9_][a-zA-Z0-9_-]*?)\}/g;return function(i={}){return t.replace(n,function(r,a){if(!j0.call(i,a))throw new Error(`Parameter '${a}' is required`);let u=i[a];if(typeof u!="string"&&typeof u!="number")throw new Error(`Parameter '${a}' must be a string or number`);return`${u}`}).replace(/^\/+/,"")}}var yf=["https://generativelanguage.googleapis.com"];function eI(t){var e;let n=t.server_url,o={};if(!n){let r=(e=t.server_idx)!==null&&e!==void 0?e:0;if(r<0||r>=yf.length)throw new Error(`Invalid server index ${r}`);n=yf[r]||""}let i=se(n)(o);return new URL(i)}var wp={userAgent:"speakeasy-sdk/typescript 2.4.1-preview.4 internal v1beta @google/genai"};function tI(){return"Deno"in globalThis}var Xo;function Yn(){var t,e,n,o,i,r;if(Xo)return Xo;let a=globalThis,u={};return tI()?u=(o=(n=(e=(t=a.Deno)===null||t===void 0?void 0:t.env)===null||e===void 0?void 0:e.toObject)===null||n===void 0?void 0:n.call(e))!==null&&o!==void 0?o:{}:u=(r=(i=a.process)===null||i===void 0?void 0:i.env)!==null&&r!==void 0?r:{},Xo=u,Xo}function nI(t){var e,n;let o=Object.assign({},t),i=Yn();return typeof i.GOOGLE_GENAI_API_VERSION<"u"&&((e=o.api_version)!==null&&e!==void 0||(o.api_version=i.GOOGLE_GENAI_API_VERSION)),typeof i.GOOGLE_GENAI_USER_PROJECT<"u"&&((n=o.user_project)!==null&&n!==void 0||(o.user_project=i.GOOGLE_GENAI_USER_PROJECT)),o}var oI=Symbol.for("undici.globalDispatcher.1"),Ea=class{constructor(e){this.options=e}getDefaultHeaders(){return this.options.defaultHeaders}async resolveGoogleGenAISecurity(e){return aI(await this.options.getAuthHeaders(e))}},Ta=class{beforeCreateRequest(e,n){var o;let i=Object.assign({},(o=n.options)!==null&&o!==void 0?o:{});return fI()&&!pI(e.options.http_client)&&!("dispatcher"in i)&&(i.dispatcher=hI()),Object.assign(Object.assign({},n),{url:iI(n.url),options:i})}async beforeRequest(e,n){if(Ef(n.headers,sI(e.security_source)),lI(e,n.headers),cI(n.headers))return n;let o=await rI(e.security_source,n.url);return Ef(n.headers,o?.default_headers),uI(n.headers,o),n}};function iI(t){let[,e,...n]=t.pathname.split("/");if(!e)return t;let o=decodeURIComponent(e);if(!o.includes("/"))return t;let i=new URL(t);return i.pathname=`/${o}/${n.join("/")}`,i}async function rI(t,e){if(Pp(t))return t.resolveGoogleGenAISecurity(e);let n=typeof t=="function"?await t():t;return Rp(n)?vf(n):vf(void 0)}function sI(t){var e,n;if(Pp(t))return(n=(e=t.getDefaultHeaders)===null||e===void 0?void 0:e.call(t))!==null&&n!==void 0?n:t.defaultHeaders;if(Rp(t))return t.default_headers}function vf(t){var e,n;let o=Yn(),i=Object.assign(Object.assign({},t),{api_key:(e=t?.api_key)!==null&&e!==void 0?e:o.GOOGLE_GENAI_API_KEY,access_token:(n=t?.access_token)!==null&&n!==void 0?n:o.GOOGLE_GENAI_ACCESS_TOKEN});return kp(i)?i:void 0}function aI(t){var e,n;let o={};for(let[r,a]of t){let u=r.toLowerCase();u!=="authorization"&&u!=="x-goog-api-key"&&(o[r]=a)}let i={access_token:(e=t.get("authorization"))!==null&&e!==void 0?e:void 0,api_key:(n=t.get("x-goog-api-key"))!==null&&n!==void 0?n:void 0,default_headers:Object.keys(o).length?o:void 0};return kp(i)?i:void 0}function Ef(t,e){if(e)for(let[n,o]of new Headers(e)){let i=t.get(n);(i===null||n.toLowerCase()==="user-agent"&&i===wp.userAgent)&&t.set(n,o)}}function lI(t,e){t.options.user_project!==void 0&&e.get("x-goog-user-project")===null&&e.set("x-goog-user-project",t.options.user_project)}function uI(t,e){if(e){if(e.api_key){t.set("x-goog-api-key",e.api_key);return}e.access_token&&t.set("Authorization",dI(e.access_token))}}function cI(t){return t.get("authorization")!==null||t.get("x-goog-api-key")!==null}function dI(t){return t.slice(0,7).toLowerCase()==="bearer "?t:`Bearer ${t}`}function Rp(t){return typeof t=="object"&&t!==null}function Pp(t){return typeof t=="object"&&t!==null&&"resolveGoogleGenAISecurity"in t&&typeof t.resolveGoogleGenAISecurity=="function"}function kp(t){return t.api_key!==void 0||t.access_token!==void 0||t.default_headers!==void 0}function fI(){var t,e;return typeof((e=(t=globalThis.process)===null||t===void 0?void 0:t.versions)===null||e===void 0?void 0:e.node)=="string"}function pI(t){if(!t||typeof t!="object")return!1;if("options"in t){let e=t.options;return!!e?.fetcher}return!0}function hI(){return{dispatch(t,e){let n=globalThis[oI];if(!n||typeof n.dispatch!="function")throw new TypeError("Undici globalDispatcher is not available in this Node.js runtime.");return n.dispatch(Object.assign(Object.assign({},t),{headersTimeout:0,bodyTimeout:0}),e)}}}var Ht=class extends Error{constructor(e,n){let o=e;n?.cause&&(o+=`: ${n.cause}`),super(o,n),this.name="HTTPClientError",typeof this.cause>"u"&&(this.cause=n?.cause)}},pi=class extends Ht{constructor(){super(...arguments),this.name="UnexpectedClientError"}},vn=class extends Ht{constructor(){super(...arguments),this.name="InvalidRequestError"}},hi=class extends Ht{constructor(){super(...arguments),this.name="RequestAbortedError"}},mi=class extends Ht{constructor(){super(...arguments),this.name="RequestTimeoutError"}},gi=class extends Ht{constructor(){super(...arguments),this.name="ConnectionError"}};var tt=class extends Error{constructor(e,n){var o,i,r,a;super(e),this.statusCode=(o=n?.response)===null||o===void 0?void 0:o.status,this.body=(i=n?.body)!==null&&i!==void 0?i:"",this.headers=(r=n?.response)===null||r===void 0?void 0:r.headers,this.contentType=((a=n?.response)===null||a===void 0?void 0:a.headers.get("content-type"))||"",this.rawResponse=n?.response,this.name="GoogleGenAiError",Object.setPrototypeOf(this,new.target.prototype)}};var Aa=class extends Error{constructor(e){super(e),this.name=this.constructor.name,Object.setPrototypeOf(this,new.target.prototype)}},qe=class t extends Aa{constructor(e,n,o,i){super(t.makeMessage(e,n,o)),this.status=e,this.headers=i,this.error=n,this.statusCode=e,this.body=Af(n),this.contentType=i?.get("content-type")||"",this.rawResponse=void 0,this.cause=void 0,this.name=this.constructor.name,Object.setPrototypeOf(this,new.target.prototype)}static makeMessage(e,n,o){var i;let r=n&&TI(n)&&typeof n.message=="string"?n.message:void 0,a=Af(n),u=(i=r??o)!==null&&i!==void 0?i:a||"An error occurred";return`${e?`${e} `:""}${u}`}static generate(e,n,o,i){return!e||!i?new Vt({message:o,cause:n instanceof Error?n:void 0}):e===400?new Ia(e,n,o,i):e===401?new Sa(e,n,o,i):e===403?new wa(e,n,o,i):e===404?new Ra(e,n,o,i):e===409?new Pa(e,n,o,i):e===422?new ka(e,n,o,i):e===429?new Na(e,n,o,i):e>=500?new xa(e,n,o,i):new t(e,n,o,i)}},In=class extends qe{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},Vt=class extends qe{constructor({message:e,cause:n}){super(void 0,void 0,e||"Connection error.",void 0),this.cause=n}},Ca=class extends Vt{constructor({message:e}={}){super({message:e||"Request timed out. This is a client-side timeout. You can increase the timeout by setting the `timeout` argument in your request or client http options."})}},Ia=class extends qe{},Sa=class extends qe{},wa=class extends qe{},Ra=class extends qe{},Pa=class extends qe{},ka=class extends qe{},Na=class extends qe{},xa=class extends qe{};function bt(t){return AI(t)?t:mI(t)?gI(t):yI(t)?vI(t):t}function mI(t){return t instanceof tt?!0:t instanceof Error&&typeof t.statusCode=="number"&&typeof t.body=="string"}function gI(t){let e=EI(t),n=qe.generate(t.statusCode,e,t.message,t.headers);return Hn(n,"body",t.body),Hn(n,"contentType",t.contentType),Hn(n,"rawResponse",t.rawResponse),Hn(n,"statusCode",t.statusCode),Hn(n,"cause",t),n}var _I=new Set(["HTTPClientError","UnexpectedClientError","InvalidRequestError","RequestAbortedError","RequestTimeoutError","ConnectionError"]);function yI(t){return t instanceof Ht?!0:t instanceof Error&&_I.has(t.name)}function vI(t){return t instanceof mi||t.name==="RequestTimeoutError"?new Ca({message:t.message}):t instanceof hi||t.name==="RequestAbortedError"?new In({message:t.message}):t instanceof gi||t.name==="ConnectionError"?new Vt({message:t.message,cause:t}):new Vt({message:t.message,cause:t})}function EI(t){let e=Tf(t,"data$");if(e&&typeof e=="object")return e;try{let o=JSON.parse(t.body);if(o&&typeof o=="object")return o}catch{}let n=Tf(t,"error");return n&&typeof n=="object"?n:void 0}function Tf(t,e){return t&&typeof t=="object"?t[e]:void 0}function Af(t){if(!t)return"";try{return JSON.stringify(t)}catch{return String(t)}}function TI(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function AI(t){return typeof t=="object"&&t!==null?qe.prototype.isPrototypeOf(t):!1}function Hn(t,e,n){Object.defineProperty(t,e,{configurable:!0,enumerable:!0,value:n,writable:!1})}function Cf(t){try{return JSON.parse(t)}catch{return t}}function CI(t,e={}){var n,o;let i=e.flattened===!0,r=(n=e.sentinel)!==null&&n!==void 0?n:"";return new _i(t,a=>r!==""&&a.data===r?{done:!0,value:void 0}:i?{done:!1,value:a.data==null?void 0:Cf(a.data)}:{done:!1,value:Object.assign(Object.assign({},a),{data:a.data==null?a.data:Cf(a.data)})},{dataRequired:(o=e.dataRequired)!==null&&o!==void 0?o:!0})}var Np=function(t,e){let n=new ReadableStream(t,e);return Object.setPrototypeOf(n,Object.getPrototypeOf(this)),n};Np.prototype=ReadableStream.prototype;var _i=class extends Np{constructor(e,n,o){var i;let r=e.getReader(),a=new Uint8Array(4096),u=0,c=0,d={eventId:void 0},f=(i=o?.dataRequired)!==null&&i!==void 0?i:!0;super({async pull(p){try{for(;;){let h=SI(a,u,c);if(!h){c=Math.max(0,u-II+1);let m=await r.read();if(m.done)return p.close();if(u+m.value.length>a.length){let v=new Uint8Array(Math.max(a.length*2,u+m.value.length));v.set(a.subarray(0,u)),a=v}a.set(m.value,u),u+=m.value.length;continue}let g=a.slice(0,h.index);if(a.copyWithin(0,h.index+h.length,u),u-=h.index+h.length,a.length>4096&&u<=a.length>>2){let m=new Uint8Array(Math.max(4096,u*2));m.set(a.subarray(0,u)),a=m}c=0;let _=wI(g,n,d,f);if(_&&!_.done)return p.enqueue(_.value);if(_?.done)return await r.cancel("done"),p.close()}}catch(h){p.error(h),await r.cancel(h)}},cancel:p=>r.cancel(p)})}[Symbol.asyncIterator](e){let n=ReadableStream.prototype[Symbol.asyncIterator];if(typeof n=="function")return n.call(this,e);let o=this.getReader(),i={next:async()=>{let a=await o.read();return a.done?(o.releaseLock(),{done:!0,value:void 0}):{done:!1,value:a.value}},throw:async a=>(await o.cancel(a),o.releaseLock(),{done:!0,value:void 0}),return:async()=>(await o.cancel("done"),o.releaseLock(),{done:!0,value:void 0}),[Symbol.asyncIterator](){return this}},r=Symbol.asyncDispose;return r&&(i[r]=async()=>{var a;await((a=i.return)===null||a===void 0?void 0:a.call(i))}),i}values(e){return this[Symbol.asyncIterator](e)}},je=13,et=10,xp=[[je,et,je,et],[je,et,je],[je,et,et],[je,je,et],[et,je,et],[je,je],[et,je],[et,et]],II=xp.reduce((t,e)=>Math.max(t,e.length),0);function SI(t,e,n){for(let o=n;o<e;o++)if(!(t[o]!==je&&t[o]!==et))for(let i of xp){if(o+i.length>e)continue;let r=!0;for(let a=0;a<i.length;a++)if(t[o+a]!==i[a]){r=!1;break}if(r)return{index:o,length:i.length}}return null}function wI(t,e,n,o){let r=new TextDecoder().decode(t).split(/\r\n|\r|\n/),a=[],u={},c=!0;for(let d of r){if(!d||d.startsWith(":"))continue;c=!1;let f=d.indexOf(":"),p=d,h="";f>0&&(p=d.slice(0,f),h=d[f+1]===" "?d.slice(f+2):d.slice(f+1)),p==="data"?a.push(h):p==="event"?u.event=h:p==="id"&&!h.includes("\0")?n.eventId=h:p==="retry"&&/^\d+$/.test(h)&&(u.retry=Number(h))}if(!c){if(u.id=n.eventId,a.length)u.data=a.join(`
36
+ `);else if(o)return;return e(u)}}var RI=(t,e)=>e==null?fetch(t):fetch(t,e),yi=class t{constructor(e={}){this.requestHooks=[],this.requestErrorHooks=[],this.responseHooks=[],this.options=e,this.fetcher=e.fetcher||RI}async request(e){let n=e;for(let o of this.requestHooks){let i=await o(n);i&&(n=i)}try{let o=await this.fetcher(n);for(let i of this.responseHooks)await i(o,n);return o}catch(o){for(let i of this.requestErrorHooks)await i(o,n);throw o}}addHook(...e){if(e[0]==="beforeRequest")this.requestHooks.push(e[1]);else if(e[0]==="requestError")this.requestErrorHooks.push(e[1]);else if(e[0]==="response")this.responseHooks.push(e[1]);else throw new Error(`Invalid hook type: ${e[0]}`);return this}removeHook(...e){let n;if(e[0]==="beforeRequest")n=this.requestHooks;else if(e[0]==="requestError")n=this.requestErrorHooks;else if(e[0]==="response")n=this.responseHooks;else throw new Error(`Invalid hook type: ${e[0]}`);let o=n.findIndex(i=>i===e[1]);return o>=0&&n.splice(o,1),this}clone(){let e=new t(this.options);return e.requestHooks=this.requestHooks.slice(),e.requestErrorHooks=this.requestErrorHooks.slice(),e.responseHooks=this.responseHooks.slice(),e}},If=/\s*;\s*/g;function _n(t,e){var n;if(e==="*")return!0;let o=((n=t.headers.get("content-type"))===null||n===void 0?void 0:n.trim())||"application/octet-stream";o=o.toLowerCase();let i=e.toLowerCase().trim().split(If),[r="",...a]=i;if(r.split("/").length!==2)return!1;let u=o.split(If),[c="",...d]=u,[f="",p=""]=c.split("/");if(!f||!p||r!=="*/*"&&c!==r&&`${f}/*`!==r&&`*/${p}`!==r||d.length<a.length)return!1;let h=new Set(d);for(let g of a)if(!h.has(g))return!1;return!0}var PI=new RegExp("^[0-9]xx$","i");function ie(t,e){let n=`${t.status}`,o=Array.isArray(e)?e:[e];return o.length?o.some(i=>{let r=`${i}`;if(r==="default")return!0;if(!PI.test(`${r}`))return r===n;let a=r.charAt(0);if(!a)throw new Error("Invalid status code range");let u=n.charAt(0);if(!u)throw new Error(`Invalid response status code: ${n}`);return u===a}):!1}function kI(t,e,n){return ie(t,e)&&_n(t,n)}function Dp(t){if(typeof t!="object"||t==null)return!1;let e=t instanceof TypeError&&t.message.toLowerCase().startsWith("failed to fetch"),n=t instanceof TypeError&&t.message.toLowerCase().startsWith("fetch failed"),o="name"in t&&t.name==="ConnectionError",i="code"in t&&typeof t.code=="string"&&t.code.toLowerCase()==="econnreset";return e||n||i||o}function Mp(t){if(typeof t!="object"||t==null)return!1;let e="name"in t&&t.name==="TimeoutError",n="code"in t&&t.code===23,o="code"in t&&typeof t.code=="string"&&t.code.toLowerCase()==="econnaborted";return e||n||o}function NI(t){if(typeof t!="object"||t==null)return!1;let e="name"in t&&t.name==="AbortError",n="code"in t&&t.code===20,o="code"in t&&typeof t.code=="string"&&t.code.toLowerCase()==="econnaborted";return e||n||o}function xI(t){let e=new Ta;t.registerBeforeCreateRequestHook(e),t.registerBeforeRequestHook(e)}var vi=class{constructor(){this.sdkInitHooks=[],this.beforeCreateRequestHooks=[],this.beforeRequestHooks=[],this.afterSuccessHooks=[],this.afterErrorHooks=[];let e=[];for(let n of e)"sdkInit"in n&&this.registerSDKInitHook(n),"beforeCreateRequest"in n&&this.registerBeforeCreateRequestHook(n),"beforeRequest"in n&&this.registerBeforeRequestHook(n),"afterSuccess"in n&&this.registerAfterSuccessHook(n),"afterError"in n&&this.registerAfterErrorHook(n);xI(this)}registerSDKInitHook(e){this.sdkInitHooks.push(e)}registerBeforeCreateRequestHook(e){this.beforeCreateRequestHooks.push(e)}registerBeforeRequestHook(e){this.beforeRequestHooks.push(e)}registerAfterSuccessHook(e){this.afterSuccessHooks.push(e)}registerAfterErrorHook(e){this.afterErrorHooks.push(e)}sdkInit(e){return this.sdkInitHooks.reduce((n,o)=>o.sdkInit(n),e)}beforeCreateRequest(e,n){let o=n;for(let i of this.beforeCreateRequestHooks)o=i.beforeCreateRequest(e,o);return o}async beforeRequest(e,n){let o=n;for(let i of this.beforeRequestHooks)o=await i.beforeRequest(e,o);return o}async afterSuccess(e,n){let o=n;for(let i of this.afterSuccessHooks)o=await i.afterSuccess(e,o);return o}async afterError(e,n,o){let i=n,r=o;for(let a of this.afterErrorHooks){let u=await a.afterError(e,i,r);i=u.response,r=u.error}return{response:i,error:r}}};function Sf(t){return{ok:!0,value:t}}function It(t){return{ok:!1,error:t}}function El(t){return btoa(String.fromCodePoint(...t))}function DI(t){return new TextEncoder().encode(t)}function MI(t){return El(DI(t))}function UI(...t){let e=[];for(let n of t)n&&e.push(n);switch(e.length){case 0:case 1:return e[0]||null;default:return"any"in AbortSignal&&typeof AbortSignal.any=="function"?AbortSignal.any(e):GI(e)}}function GI(t){let e=new AbortController,n=e.signal;if(!t.length)return e.signal;if(t.length===1)return t[0]||e.signal;for(let a of t)if(a.aborted)return a;function o(){e.abort(this.reason),r()}let i=[];function r(){for(let a of i){let u=a.deref();u&&u.removeEventListener("abort",o)}}for(let a of t)i.push(new WeakRef(a)),a.addEventListener("abort",o);return n}function le(t){let e={};for(let[n,o]of Object.entries(t))typeof o<"u"&&(e[n]=o);return e}function Bt(t){if(t===null||typeof t!="object"||Object.prototype.toString.call(t)!=="[object Object]")return!1;let e=Object.getPrototypeOf(t);if(e===null||e===Object.prototype)return!0;try{return Object.getPrototypeOf(e)===null}catch{return!1}}var bI=/%(2[346bcf]|3[abdf]|40|5[bd])/gi;function Up(t,e){return Ri(t,e==="percentExceptReserved"?"percent":e)}function Ri(t,e){switch(e){case"percent":return encodeURIComponent(t);case"percentExceptReserved":return encodeURIComponent(t).replace(bI,n=>decodeURIComponent(n));default:return t}}function LI(t){return(e,n,o)=>{let i="",r=o?.explode?bp(e,n):[[e,n]];if(r.every(([d,f])=>f==null))return;let a=d=>Ri(d,o?.charEncoding),u=d=>a(Lp(d)),c=a(t);return r.forEach(([d,f])=>{var p,h;let g="",_=null;f!=null&&(Array.isArray(f)?_=(p=Op(f,m=>`${u(m)}`))===null||p===void 0?void 0:p.join(c):Bt(f)?_=(h=Fp(Object.entries(f),([m,v])=>`${a(m)}${c}${u(v)}`))===null||h===void 0?void 0:h.join(c):_=`${u(f)}`,_!=null&&(g=`${Up(d,o?.charEncoding)}=${_}`,!(!g||g==="=")&&(i+=`&${g}`)))}),i.slice(1)}}var Gp=LI(",");function ot(t,e,n){if(typeof e>"u")return;let i=(r=>Ri(r,n?.charEncoding))(JSON.stringify(e,qp));return n?.explode?i:`${Up(t,n?.charEncoding)}=${i}`}var K=(t,e,n)=>{let o="",i=n?.explode?bp(t,e):[[t,e]];if(i.every(([u,c])=>c==null))return;let r=u=>Ri(u,n?.charEncoding),a=u=>r(Lp(u));return i.forEach(([u,c])=>{var d;let f="";if(c!=null){if(Array.isArray(c))f=(d=Op(c,p=>`${a(p)}`))===null||d===void 0?void 0:d.join(",");else if(Bt(c)){let p=Fp(Object.entries(c),([h,g])=>`,${r(h)},${a(g)}`);f=p?.join("").slice(1)}else f=`${n?.explode&&Bt(e)?`${u}=`:""}${a(c)}`;o+=f?`,${f}`:""}}),o.slice(1)};function bp(t,e){return Array.isArray(e)?e.map(n=>[t,n]):Bt(e)?Object.entries(e??{}).map(([o,i])=>[o,i]):[[t,e]]}function Lp(t){return t==null?"":t instanceof Date?t.toISOString():t instanceof Uint8Array?El(t):typeof t=="object"?JSON.stringify(t,qp):`${t}`}function qp(t,e){return e instanceof Uint8Array?El(e):e}function Op(t,e){let n=t.reduce((o,i)=>{if(i==null)return o;let r=e(i);return r==null||o.push(r),o},[]);return n.length?n:null}function Fp(t,e){let n=[];for(let[o,i]of t){if(i==null)continue;let r=e([o,i]);r!=null&&n.push(r)}return n.length?n:null}function qI(...t){return t.filter(Boolean).join("&")}function OI(t){return function(n,o){var i,r,a;let u=Object.assign(Object.assign({},o),{explode:(i=o?.explode)!==null&&i!==void 0?i:!0,charEncoding:(r=o?.charEncoding)!==null&&r!==void 0?r:"percent"}),c=new Set((a=o?.allowEmptyValue)!==null&&a!==void 0?a:[]),d=Object.entries(n).map(([f,p])=>c.has(f)&&(p==null||p===""||Array.isArray(p)&&p.length===0)?`${encodeURIComponent(f)}=`:t(f,p,u));return qI(...d)}}var it=OI(Gp);var wf={initialInterval:500,maxInterval:6e4,exponent:1.5,maxElapsedTime:36e5},Wn=class t extends Error{constructor(e,n){let o=e;n?.cause&&(o+=`: ${n.cause}`),super(o,n),this.name="PermanentError",typeof this.cause>"u"&&(this.cause=n?.cause),Object.setPrototypeOf(this,t.prototype)}},$t=class t extends Error{constructor(e,n){super(e),this.response=n,this.name="TemporaryError",Object.setPrototypeOf(this,t.prototype)}};async function FI(t,e){var n;switch(e.config.strategy){case"backoff":return BI(Rf(t,{statusCodes:e.statusCodes,retryConnectionErrors:!!e.config.retryConnectionErrors}),(n=e.config.backoff)!==null&&n!==void 0?n:wf);case"attempt-count-backoff":return $I(Rf(t,{statusCodes:e.statusCodes,retryConnectionErrors:!!e.config.retryConnectionErrors}),Object.assign(Object.assign({},wf),e.config.backoff),e.config);default:return await t(0)}}function Rf(t,e){return async n=>{try{let o=await t(n);if(VI(o,e.statusCodes))throw new $t("Response failed with retryable status code",o);return o}catch(o){throw o instanceof $t||e.retryConnectionErrors&&(Mp(o)||Dp(o))?o:new Wn("Permanent error",{cause:o})}}}var HI=new RegExp("^[0-9]xx$","i");function VI(t,e){let n=`${t.status}`;return e.some(o=>{if(!HI.test(o))return o===n;let i=o.charAt(0);if(!i)throw new Error("Invalid status code range");let r=n.charAt(0);if(!r)throw new Error(`Invalid response status code: ${n}`);return r===i})}async function BI(t,e){let{maxElapsedTime:n,initialInterval:o,exponent:i,maxInterval:r}=e,a=Date.now(),u=0;for(;;)try{return await t(u)}catch(c){if(c instanceof Wn)throw c.cause;if(Date.now()-a>n){if(c instanceof $t)return c.response;throw c}let f=0;c instanceof $t&&(f=Hp(c.response)),f<=0&&(f=o*Math.pow(u,i)+Math.random()*1e3);let p=Math.min(f,r);await Vp(p),u++}}async function $I(t,e,n){let o=0;for(;;)try{return await t(o)}catch(i){if(i instanceof Wn)throw i.cause;if(o>=n.maxRetries){if(i instanceof $t)return i.response;throw i}let r=0;i instanceof $t&&(r=Hp(i.response)),r<=0&&(r=e.initialInterval*Math.pow(e.exponent,o)*(1-Math.random()*.25));let a=Math.min(r,e.maxInterval);await Vp(a),o++}}function Hp(t){let e=t.headers.get("retry-after-ms");if(e){let r=Number(e);if(Number.isFinite(r)&&r>=0)return r}let n=t.headers.get("retry-after")||"";if(!n)return 0;let o=Number(n);if(Number.isInteger(o))return o*1e3;let i=Date.parse(n);if(Number.isInteger(i)){let r=i-Date.now();return r>0?Math.ceil(r):0}return 0}async function Vp(t){return new Promise(e=>setTimeout(e,t))}var Jo=typeof globalThis>"u"?null:globalThis,XI=typeof Jo=="object"&&Jo!=null&&"importScripts"in Jo&&typeof Jo.importScripts=="function",JI=XI||typeof navigator<"u"&&"serviceWorker"in navigator||typeof window=="object"&&typeof window.document<"u",nt=class{constructor(e={}){let n=e;typeof n=="object"&&n!=null&&"hooks"in n&&n.hooks instanceof vi?this._hooks=n.hooks:this._hooks=new vi;let o=new yi;e.http_client=e.http_client||o,e=this._hooks.sdkInit(e);let i=eI(e);i&&(i.pathname=i.pathname.replace(/\/+$/,"")+"/"),this._baseURL=i,this._httpClient=e.http_client||o,this._options=Object.assign(Object.assign({},nI(e)),{hooks:this._hooks}),this._logger=this._options.debug_logger,!this._logger&&Yn().GOOGLE_GENAI_DEBUG&&(this._logger=console)}_createRequest(e,n,o){var i,r,a,u,c;let{method:d,path:f,query:p,headers:h,security:g}=n,_=(i=n.baseURL)!==null&&i!==void 0?i:this._baseURL;if(!_)return It(new vn("No base URL provided for operation"));let m=new URL(_),v;f?(m.pathname=m.pathname.replace(/\/+$/,"")+"/",v=new URL(f,m),!v.search&&m.search&&(v.search=m.search)):v=m,v.hash="";let y=(D,Q)=>{if(!Q)return D;let te=new Set(Q.split("&").filter(ve=>ve!=="").map(ve=>{var fe;return(fe=ve.split("=")[0])!==null&&fe!==void 0?fe:""}));return[...D.split("&").filter(ve=>{var fe;return ve!==""&&!te.has((fe=ve.split("=")[0])!==null&&fe!==void 0?fe:"")}),Q].join("&")},E=D=>Object.entries(D).map(([Q,te])=>{if(te==null)return;let Ae=Bt(te)?JSON.stringify(te):te;return Gp(Q,Ae,{explode:Array.isArray(Ae),charEncoding:"percent"})}).filter(Q=>typeof Q<"u").join("&"),A=[p||"",E(o?.extra_query||{}),E(g?.queryParams||{})].reduce(y,v.search.slice(1));A&&(v.search=`?${A}`);let C=new Headers(h),w=g?.basic.username,N=g?.basic.password;if(w!=null||N!=null){let D=MI([w||"",N||""].join(":"));C.set("Authorization",`Basic ${D}`)}let q=new Headers(g?.headers||{});for(let[D,Q]of q)C.set(D,Q);let V=C.get("cookie")||"";for(let[D,Q]of Object.entries(g?.cookies||{}))V+=`; ${D}=${Q}`;V=V.startsWith("; ")?V.slice(2):V,C.set("cookie",V);let M=new Headers((r=o?.headers)!==null&&r!==void 0?r:(a=o?.fetch_options)===null||a===void 0?void 0:a.headers);for(let[D,Q]of M)C.set(D,Q);JI||C.set((u=n.uaHeader)!==null&&u!==void 0?u:"user-agent",(c=n.userAgent)!==null&&c!==void 0?c:wp.userAgent);let O=n.body,H=Object.fromEntries(Object.entries(o?.extra_body||{}).filter(([,D])=>typeof D<"u"));if(Object.keys(H).length>0){let D=new Headers(h).get("content-type")||"";if(!/^(application|text)\/([^+]+\+)*json/.test(D)||typeof O!="string"&&O!=null)return It(new vn("extra_body can only be merged into JSON object request bodies"));let te;try{te=O?JSON.parse(O):{}}catch(Ae){return It(new vn("extra_body can only be merged into JSON object request bodies",{cause:Ae}))}if(!Bt(te))return It(new vn("extra_body can only be merged into JSON object request bodies"));O=JSON.stringify(Object.assign(Object.assign({},te),H)),C.delete("content-length")}let $=Object.assign(Object.assign({},o?.fetch_options),o);!$?.signal&&n.timeout_ms!=null&&n.timeout_ms>0&&(e.timeout_ms=n.timeout_ms),n.body instanceof ReadableStream&&Object.assign($,{duplex:"half"});let j;try{j=this._hooks.beforeCreateRequest(e,{url:v,options:Object.assign(Object.assign({},$),{body:O??null,headers:C,method:d})})}catch(D){return It(new pi("Create request hook failed to execute",{cause:D}))}return Sf(new Request(j.url,j.options))}async _do(e,n){let{context:o,isErrorStatusCode:i}=n,r=o.timeout_ms;return FI(async()=>{var a;let u=e.clone(),c=u;if(r!=null&&r>0){let p=AbortSignal.timeout(r),h=(a=UI(u.signal,p))!==null&&a!==void 0?a:p;c=new Request(u,{signal:h})}let d=await this._hooks.beforeRequest(o,c);await KI(this._logger,d).catch(p=>{var h;return(h=this._logger)===null||h===void 0?void 0:h.log("Failed to log request:",p)});let f=await this._httpClient.request(d);try{if(i(f.status)){let p=await this._hooks.afterError(o,f,null);if(p.error)throw p.error;f=p.response||f}else f=await this._hooks.afterSuccess(o,f)}finally{await YI(this._logger,f,d).catch(p=>{var h;return(h=this._logger)===null||h===void 0?void 0:h.log("Failed to log response:",p)})}return f},{config:n.retryConfig,statusCodes:n.retryCodes}).then(a=>Sf(a),a=>{switch(!0){case NI(a):return It(new hi("Request aborted by client",{cause:a}));case Mp(a):return It(new mi("Request timed out",{cause:a}));case Dp(a):return It(new gi("Unable to make request",{cause:a}));default:return It(new pi("Unexpected HTTP client error",{cause:a}))}})}},Bp=/^(application|text)\/([^+]+\+)*json.*/,Pf=/^(application|text)\/([^+]+\+)*(jsonl|x-ndjson)\b.*/;async function KI(t,e){if(!t)return;let n=e.headers.get("content-type"),o=n?.split(";")[0]||"";t.group(`> Request: ${e.method} ${e.url}`),t.group("Headers:");for(let[i,r]of e.headers.entries())t.log(`${i}: ${r}`);switch(t.groupEnd(),t.group("Body:"),!0){case Bp.test(o):t.log(await e.clone().json());break;case o.startsWith("text/"):t.log(await e.clone().text());break;case o==="multipart/form-data":{let i=await e.clone().formData();for(let[r,a]of i){let u=a instanceof Blob?"<Blob>":a;t.log(`${r}: ${u}`)}break}default:t.log(`<${n}>`);break}t.groupEnd(),t.groupEnd()}async function YI(t,e,n){if(!t)return;let o=e.headers.get("content-type"),i=o?.split(";")[0]||"";t.group(`< Response: ${n.method} ${n.url}`),t.log("Status Code:",e.status,e.statusText),t.group("Headers:");for(let[r,a]of e.headers.entries())t.log(`${r}: ${a}`);switch(t.groupEnd(),t.group("Body:"),!0){case(_n(e,"application/json")||Bp.test(i)&&!Pf.test(i)):t.log(await e.clone().json());break;case(_n(e,"application/jsonl")||Pf.test(i)):case _n(e,"text/event-stream"):t.log(`<${o}>`);break;case _n(e,"text/*"):t.log(await e.clone().text());break;case _n(e,"multipart/form-data"):{let r=await e.clone().formData();for(let[a,u]of r){let c=u instanceof Blob?"<Blob>":u;t.log(`${a}: ${c}`)}break}default:t.log(`<${o}>`);break}t.groupEnd(),t.groupEnd()}var Ei=class extends tt{constructor(e,n){e&&(e+=": "),e+=`Status ${n.response.status}`;let o=n.response.headers.get("content-type")||'""';o!=="application/json"&&(e+=` Content-Type ${o.includes(" ")?`"${o}"`:o}`);let i=n.body||'""';e+=i.length>100?`
37
+ `:". ";let r=i;if(i.length>1e4){let a=i.substring(0,1e4),u=i.length-1e4;r=`${a}...and ${u} more chars`}e+=`Body: ${r}`,e=e.trim(),super(e,n),this.name="GoogleGenAiDefaultError",Object.setPrototypeOf(this,new.target.prototype)}};var WI={jsonl:"application/jsonl",json:"application/json",text:"text/plain",bytes:"application/octet-stream",stream:"application/octet-stream",sse:"text/event-stream",nil:"*",fail:"*"};function Xt(t,e,n){return Object.assign(Object.assign({},n),{err:!0,enc:"json",codes:t,errorClass:e})}function he(t,e){return Object.assign(Object.assign({},e),{enc:"json",codes:t})}function $p(t,e,n){return Object.assign(Object.assign(Object.assign({},n),{enc:"sse",codes:t}),e?{sse:e}:{})}function Xp(t,e){return Object.assign(Object.assign({},e),{enc:"nil",codes:t})}function Y(t){return{enc:"fail",codes:t}}function ue(...t){return async function(n,o,i){let r,a;for(let h of t){let{codes:g}=h,_="ctype"in h?h.ctype:WI[h.enc];if(_&&kI(n,g,_)){a=h;break}else if(!_&&ie(n,g)){a=h;break}}if(!a)return[{ok:!1,error:new Ei("Unexpected Status or Content-Type",{response:n,request:o,body:await n.text().catch(()=>"")})},r];let u=a.enc,c="";switch(u){case"json":c=await n.text();try{r=JSON.parse(c)}catch(h){if(!("err"in a))throw h;r=c}break;case"jsonl":r=n.body;break;case"bytes":r=new Uint8Array(await n.arrayBuffer());break;case"stream":r=n.body;break;case"text":c=await n.text(),r=c;break;case"sse":if(n.body){let h="sse"in a&&a.sse||{};r=CI(n.body,h)}else r=null;break;case"nil":c=await n.text(),r=void 0;break;case"fail":c=await n.text(),r=c;break;default:throw new Error(`Unsupported response type: ${u}`)}if(a.enc==="fail")return[{ok:!1,error:new Ei("API error occurred",{request:o,response:n,body:c})},r];let d=a.key||i?.resultKey,f,p=a.hdrs?{headers:QI(n.headers)}:null;return"err"in a?f=Object.assign(Object.assign(Object.assign({},i?.extraFields),p),Bt(r)?r:null):d?f=Object.assign(Object.assign(Object.assign({},i?.extraFields),p),{[d]:r}):a.hdrs?f=Object.assign(Object.assign(Object.assign({},i?.extraFields),p),Bt(r)?r:null):f=r,"err"in a?[{ok:!1,error:a.errorClass?new a.errorClass(f,{request:o,response:n,body:c}):f},r]:[{ok:!0,value:f},r]}}var zI=/, */;function QI(t){let e={};for(let[n,o]of t.entries())e[n]=o.split(zI);return e}var kf={Incomplete:"incomplete",UnrecognisedSecurityType:"unrecognized_security_type"},Da=class t extends Error{constructor(e,n){super(n),this.code=e,this.name="SecurityError"}static incomplete(){return new t(kf.Incomplete,"Security requirements not met in order to perform the operation")}static unrecognizedType(e){return new t(kf.UnrecognisedSecurityType,`Unrecognised security type: ${e}`)}};function ZI(...t){let e={basic:{},headers:{},queryParams:{},cookies:{},oauth2:{type:"none"}},n=t.find(o=>o.every(i=>{if(i.value==null)return!1;if(i.type==="http:basic")return i.value.username!=null||i.value.password!=null;if(i.type==="http:custom")return null;if(i.type==="oauth2:password")return typeof i.value=="string"&&!!i.value;if(i.type==="oauth2:client_credentials")return typeof i.value=="string"?!!i.value:i.value.client_id!=null||i.value.client_secret!=null;if(typeof i.value=="string")return!!i.value;throw new Error(`Unrecognized security type: ${i.type} (value type: ${typeof i.value})`)}));return n==null?null:(n.forEach(o=>{if(o.value==null)return;let{type:i}=o;switch(i){case"apiKey:header":e.headers[o.fieldName]=o.value;break;case"apiKey:query":e.queryParams[o.fieldName]=o.value;break;case"apiKey:cookie":e.cookies[o.fieldName]=o.value;break;case"http:basic":jI(e,o);break;case"http:custom":break;case"http:bearer":Ko(e,o);break;case"oauth2":Ko(e,o);break;case"oauth2:password":Ko(e,o);break;case"oauth2:client_credentials":break;case"openIdConnect":Ko(e,o);break;default:throw Da.unrecognizedType(i)}}),e)}function jI(t,e){e.value!=null&&(t.basic=e.value)}function Ko(t,e){if(typeof e.value!="string"||!e.value)return;let n=e.value;n.slice(0,7).toLowerCase()!=="bearer "&&(n=`Bearer ${n}`),e.fieldName!==void 0&&(t.headers[e.fieldName]=n)}function ce(t,e){var n,o;let i=[[{fieldName:"accessToken",type:"http:custom",value:(n=t?.access_token)!==null&&n!==void 0?n:Yn().GOOGLE_GENAI_ACCESS_TOKEN},{fieldName:"apiKey",type:"http:custom",value:(o=t?.api_key)!==null&&o!==void 0?o:Yn().GOOGLE_GENAI_API_KEY},{fieldName:"defaultHeaders",type:"http:custom",value:t?.default_headers}]];return ZI(...i)}async function de(t){if(t!=null)return typeof t=="function"?t():t}var Jp,ne=class t{constructor(e,n){this[Jp]="APIPromise",this._promise=e instanceof Promise?e:Promise.resolve(e),this._unwrapped=e instanceof Promise?null:Promise.resolve(e[0]),this._callSource=n??null}_getUnwrapped(){var e;return(e=this._unwrapped)!==null&&e!==void 0?e:this._unwrapped=this._promise.then(([n])=>n)}then(e,n){return this._promise.then(e?([o])=>e(o):void 0,n)}catch(e){return this._getUnwrapped().catch(e)}finally(e){return this._getUnwrapped().finally(e)}$inspect(){return this._promise}asResponse(){var e;return((e=this._callSource)!==null&&e!==void 0?e:this._callSource=this._promise.then(([,o])=>o)).then(o=>{if(!o.response)throw new Error("APIPromise.asResponse: response unavailable");return o.response})}async withResponse(){let[[e],n]=await Promise.all([this._promise,this.asResponse()]);return{data:e,response:n}}_thenUnwrap(e){var n;let o=this._promise.then(([i,r])=>[e(i),r]);return o.catch(()=>{}),new t(o,(n=this._callSource)!==null&&n!==void 0?n:void 0)}};Jp=Symbol.toStringTag;function ae(t){let e=t.$inspect(),n=e.then(([i,r])=>{if(!i.ok)throw i.error;return[i.value,r]}),o=e.then(([i,r])=>{var a;if(!i.ok&&!(!((a=r.response)===null||a===void 0)&&a.ok))throw i.error;return r});return n.catch(()=>{}),o.catch(()=>{}),new ne(n,o)}function Kp(t,e,n,o){return new ne(eS(t,e,n,o))}async function eS(t,e,n,o){var i,r,a;let c={body:e,api_version:n},d=ot("body",c.body,{explode:!0}),f={api_version:K("api_version",(i=c.api_version)!==null&&i!==void 0?i:t._options.api_version,{explode:!1,charEncoding:"percent"})},p=se("/{api_version}/agents")(f),h=new Headers(le({"Content-Type":"application/json",Accept:"application/json"})),g=await de(t._options.security),_=ce(g),m={options:t._options,base_url:(a=(r=o?.server_url)!==null&&r!==void 0?r:t._baseURL)!==null&&a!==void 0?a:"",operation_id:"CreateAgent",o_auth2_scopes:null,resolved_security:_,security_source:t._options.security,retry_config:o?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:o?.retry_codes||["408","409","429","5XX"]},v=t._createRequest(m,{security:_,method:"POST",baseURL:o?.server_url,path:p,headers:h,body:d,userAgent:t._options.user_agent,timeout_ms:o?.timeout_ms||t._options.timeout_ms||-1},o);if(!v.ok)return[v,{status:"invalid"}];let y=v.value,E=await t._do(y,{context:m,isErrorStatusCode:w=>ie({status:w},["4XX","5XX"]),retryConfig:m.retry_config,retryCodes:m.retry_codes});if(!E.ok)return[E,{status:"request-error",request:y}];let A=E.value,[C]=await ue(Y("4XX"),Y("5XX"),he("default"))(A,y);return C.ok?[C,{status:"complete",request:y,response:A}]:[C,{status:"complete",request:y,response:A}]}function Yp(t,e,n,o){return new ne(tS(t,e,n,o))}async function tS(t,e,n,o){var i,r,a;let c={id:e,api_version:n},d=null,f={api_version:K("api_version",(i=c.api_version)!==null&&i!==void 0?i:t._options.api_version,{explode:!1,charEncoding:"percent"}),agentsId:K("agentsId",c.id,{explode:!1,charEncoding:"percent"})},p=se("/{api_version}/agents/{agentsId}")(f),h=new Headers(le({Accept:"application/json"})),g=await de(t._options.security),_=ce(g),m={options:t._options,base_url:(a=(r=o?.server_url)!==null&&r!==void 0?r:t._baseURL)!==null&&a!==void 0?a:"",operation_id:"DeleteAgent",o_auth2_scopes:null,resolved_security:_,security_source:t._options.security,retry_config:o?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:o?.retry_codes||["408","409","429","5XX"]},v=t._createRequest(m,{security:_,method:"DELETE",baseURL:o?.server_url,path:p,headers:h,body:d,userAgent:t._options.user_agent,timeout_ms:o?.timeout_ms||t._options.timeout_ms||-1},o);if(!v.ok)return[v,{status:"invalid"}];let y=v.value,E=await t._do(y,{context:m,isErrorStatusCode:w=>ie({status:w},["4XX","5XX"]),retryConfig:m.retry_config,retryCodes:m.retry_codes});if(!E.ok)return[E,{status:"request-error",request:y}];let A=E.value,[C]=await ue(Y("4XX"),Y("5XX"),he("default"))(A,y);return C.ok?[C,{status:"complete",request:y,response:A}]:[C,{status:"complete",request:y,response:A}]}function Wp(t,e,n,o){return new ne(nS(t,e,n,o))}async function nS(t,e,n,o){var i,r,a;let c={id:e,api_version:n},d=null,f={api_version:K("api_version",(i=c.api_version)!==null&&i!==void 0?i:t._options.api_version,{explode:!1,charEncoding:"percent"}),agentsId:K("agentsId",c.id,{explode:!1,charEncoding:"percent"})},p=se("/{api_version}/agents/{agentsId}")(f),h=new Headers(le({Accept:"application/json"})),g=await de(t._options.security),_=ce(g),m={options:t._options,base_url:(a=(r=o?.server_url)!==null&&r!==void 0?r:t._baseURL)!==null&&a!==void 0?a:"",operation_id:"GetAgent",o_auth2_scopes:null,resolved_security:_,security_source:t._options.security,retry_config:o?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:o?.retry_codes||["408","409","429","5XX"]},v=t._createRequest(m,{security:_,method:"GET",baseURL:o?.server_url,path:p,headers:h,body:d,userAgent:t._options.user_agent,timeout_ms:o?.timeout_ms||t._options.timeout_ms||-1},o);if(!v.ok)return[v,{status:"invalid"}];let y=v.value,E=await t._do(y,{context:m,isErrorStatusCode:w=>ie({status:w},["4XX","5XX"]),retryConfig:m.retry_config,retryCodes:m.retry_codes});if(!E.ok)return[E,{status:"request-error",request:y}];let A=E.value,[C]=await ue(Y("4XX"),Y("5XX"),he("default"))(A,y);return C.ok?[C,{status:"complete",request:y,response:A}]:[C,{status:"complete",request:y,response:A}]}function zp(t,e,n,o,i,r){return new ne(oS(t,e,n,o,i,r))}async function oS(t,e,n,o,i,r){var a,u,c;let f={api_version:e,page_size:n,page_token:o,parent:i},p=null,h={api_version:K("api_version",(a=f?.api_version)!==null&&a!==void 0?a:t._options.api_version,{explode:!1,charEncoding:"percent"})},g=se("/{api_version}/agents")(h),_=it({page_size:f?.page_size,page_token:f?.page_token,parent:f?.parent}),m=new Headers(le({Accept:"application/json"})),v=await de(t._options.security),y=ce(v),E={options:t._options,base_url:(c=(u=r?.server_url)!==null&&u!==void 0?u:t._baseURL)!==null&&c!==void 0?c:"",operation_id:"ListAgents",o_auth2_scopes:null,resolved_security:y,security_source:t._options.security,retry_config:r?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:r?.retry_codes||["408","409","429","5XX"]},A=t._createRequest(E,{security:y,method:"GET",baseURL:r?.server_url,path:g,headers:m,query:_,body:p,userAgent:t._options.user_agent,timeout_ms:r?.timeout_ms||t._options.timeout_ms||-1},r);if(!A.ok)return[A,{status:"invalid"}];let C=A.value,w=await t._do(C,{context:E,isErrorStatusCode:V=>ie({status:V},["4XX","5XX"]),retryConfig:E.retry_config,retryCodes:E.retry_codes});if(!w.ok)return[w,{status:"request-error",request:C}];let N=w.value,[q]=await ue(Y("4XX"),Y("5XX"),he("default"))(N,C);return q.ok?[q,{status:"complete",request:C,response:N}]:[q,{status:"complete",request:C,response:N}]}var Ma=class extends nt{list(e,n){return ae(zp(this,e?.api_version,e?.page_size,e?.page_token,e?.parent,n))}create(e,n){let{api_version:o}=e,i=Ie(e,["api_version"]);return ae(Kp(this,i,o,n))}delete(e,n,o){return ae(Yp(this,e,n?.api_version,o))}get(e,n,o){return ae(Wp(this,e,n?.api_version,o))}};function Qp(t,e,n,o){return new ne(iS(t,e,n,o))}async function iS(t,e,n,o){var i,r,a;let c={body:e,api_version:n},d=ot("body",c.body,{explode:!0}),f={api_version:K("api_version",(i=c.api_version)!==null&&i!==void 0?i:t._options.api_version,{explode:!1,charEncoding:"percent"})},p=se("/{api_version}/credentials")(f),h=new Headers(le({"Content-Type":"application/json",Accept:"application/json"})),g=await de(t._options.security),_=ce(g),m={options:t._options,base_url:(a=(r=o?.server_url)!==null&&r!==void 0?r:t._baseURL)!==null&&a!==void 0?a:"",operation_id:"CreateCredential",o_auth2_scopes:null,resolved_security:_,security_source:t._options.security,retry_config:o?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:o?.retry_codes||["408","409","429","5XX"]},v=t._createRequest(m,{security:_,method:"POST",baseURL:o?.server_url,path:p,headers:h,body:d,userAgent:t._options.user_agent,timeout_ms:o?.timeout_ms||t._options.timeout_ms||-1},o);if(!v.ok)return[v,{status:"invalid"}];let y=v.value,E=await t._do(y,{context:m,isErrorStatusCode:w=>ie({status:w},["4XX","5XX"]),retryConfig:m.retry_config,retryCodes:m.retry_codes});if(!E.ok)return[E,{status:"request-error",request:y}];let A=E.value,[C]=await ue(Y("4XX"),Y("5XX"),he("default"))(A,y);return C.ok?[C,{status:"complete",request:y,response:A}]:[C,{status:"complete",request:y,response:A}]}function Zp(t,e,n,o){return new ne(rS(t,e,n,o))}async function rS(t,e,n,o){var i,r,a;let c={id:e,api_version:n},d=null,f={api_version:K("api_version",(i=c.api_version)!==null&&i!==void 0?i:t._options.api_version,{explode:!1,charEncoding:"percent"}),id:K("id",c.id,{explode:!1,charEncoding:"percent"})},p=se("/{api_version}/credentials/{id}")(f),h=new Headers(le({Accept:"application/json"})),g=await de(t._options.security),_=ce(g),m={options:t._options,base_url:(a=(r=o?.server_url)!==null&&r!==void 0?r:t._baseURL)!==null&&a!==void 0?a:"",operation_id:"DeleteCredential",o_auth2_scopes:null,resolved_security:_,security_source:t._options.security,retry_config:o?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:o?.retry_codes||["408","409","429","5XX"]},v=t._createRequest(m,{security:_,method:"DELETE",baseURL:o?.server_url,path:p,headers:h,body:d,userAgent:t._options.user_agent,timeout_ms:o?.timeout_ms||t._options.timeout_ms||-1},o);if(!v.ok)return[v,{status:"invalid"}];let y=v.value,E=await t._do(y,{context:m,isErrorStatusCode:w=>ie({status:w},["4XX","5XX"]),retryConfig:m.retry_config,retryCodes:m.retry_codes});if(!E.ok)return[E,{status:"request-error",request:y}];let A=E.value,[C]=await ue(Y("4XX"),Y("5XX"),he("default"))(A,y);return C.ok?[C,{status:"complete",request:y,response:A}]:[C,{status:"complete",request:y,response:A}]}function jp(t,e,n,o){return new ne(sS(t,e,n,o))}async function sS(t,e,n,o){var i,r,a;let c={id:e,api_version:n},d=null,f={api_version:K("api_version",(i=c.api_version)!==null&&i!==void 0?i:t._options.api_version,{explode:!1,charEncoding:"percent"}),id:K("id",c.id,{explode:!1,charEncoding:"percent"})},p=se("/{api_version}/credentials/{id}")(f),h=new Headers(le({Accept:"application/json"})),g=await de(t._options.security),_=ce(g),m={options:t._options,base_url:(a=(r=o?.server_url)!==null&&r!==void 0?r:t._baseURL)!==null&&a!==void 0?a:"",operation_id:"GetCredential",o_auth2_scopes:null,resolved_security:_,security_source:t._options.security,retry_config:o?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:o?.retry_codes||["408","409","429","5XX"]},v=t._createRequest(m,{security:_,method:"GET",baseURL:o?.server_url,path:p,headers:h,body:d,userAgent:t._options.user_agent,timeout_ms:o?.timeout_ms||t._options.timeout_ms||-1},o);if(!v.ok)return[v,{status:"invalid"}];let y=v.value,E=await t._do(y,{context:m,isErrorStatusCode:w=>ie({status:w},["4XX","5XX"]),retryConfig:m.retry_config,retryCodes:m.retry_codes});if(!E.ok)return[E,{status:"request-error",request:y}];let A=E.value,[C]=await ue(Y("4XX"),Y("5XX"),he("default"))(A,y);return C.ok?[C,{status:"complete",request:y,response:A}]:[C,{status:"complete",request:y,response:A}]}function eh(t,e,n,o,i){return new ne(aS(t,e,n,o,i))}async function aS(t,e,n,o,i){var r,a,u;let d={api_version:e,page_size:n,page_token:o},f=null,p={api_version:K("api_version",(r=d?.api_version)!==null&&r!==void 0?r:t._options.api_version,{explode:!1,charEncoding:"percent"})},h=se("/{api_version}/credentials")(p),g=it({page_size:d?.page_size,page_token:d?.page_token}),_=new Headers(le({Accept:"application/json"})),m=await de(t._options.security),v=ce(m),y={options:t._options,base_url:(u=(a=i?.server_url)!==null&&a!==void 0?a:t._baseURL)!==null&&u!==void 0?u:"",operation_id:"ListCredentials",o_auth2_scopes:null,resolved_security:v,security_source:t._options.security,retry_config:i?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:i?.retry_codes||["408","409","429","5XX"]},E=t._createRequest(y,{security:v,method:"GET",baseURL:i?.server_url,path:h,headers:_,query:g,body:f,userAgent:t._options.user_agent,timeout_ms:i?.timeout_ms||t._options.timeout_ms||-1},i);if(!E.ok)return[E,{status:"invalid"}];let A=E.value,C=await t._do(A,{context:y,isErrorStatusCode:q=>ie({status:q},["4XX","5XX"]),retryConfig:y.retry_config,retryCodes:y.retry_codes});if(!C.ok)return[C,{status:"request-error",request:A}];let w=C.value,[N]=await ue(Y("4XX"),Y("5XX"),he("default"))(w,A);return N.ok?[N,{status:"complete",request:A,response:w}]:[N,{status:"complete",request:A,response:w}]}function th(t,e,n,o,i,r){return new ne(lS(t,e,n,o,i,r))}async function lS(t,e,n,o,i,r){var a,u,c;let f={id:e,body:n,api_version:o,update_mask:i},p=ot("body",f.body,{explode:!0}),h={api_version:K("api_version",(a=f.api_version)!==null&&a!==void 0?a:t._options.api_version,{explode:!1,charEncoding:"percent"}),id:K("id",f.id,{explode:!1,charEncoding:"percent"})},g=se("/{api_version}/credentials/{id}")(h),_=it({update_mask:f.update_mask}),m=new Headers(le({"Content-Type":"application/json",Accept:"application/json"})),v=await de(t._options.security),y=ce(v),E={options:t._options,base_url:(c=(u=r?.server_url)!==null&&u!==void 0?u:t._baseURL)!==null&&c!==void 0?c:"",operation_id:"UpdateCredential",o_auth2_scopes:null,resolved_security:y,security_source:t._options.security,retry_config:r?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:r?.retry_codes||["408","409","429","5XX"]},A=t._createRequest(E,{security:y,method:"PATCH",baseURL:r?.server_url,path:g,headers:m,query:_,body:p,userAgent:t._options.user_agent,timeout_ms:r?.timeout_ms||t._options.timeout_ms||-1},r);if(!A.ok)return[A,{status:"invalid"}];let C=A.value,w=await t._do(C,{context:E,isErrorStatusCode:V=>ie({status:V},["4XX","5XX"]),retryConfig:E.retry_config,retryCodes:E.retry_codes});if(!w.ok)return[w,{status:"request-error",request:C}];let N=w.value,[q]=await ue(Y("4XX"),Y("5XX"),he("default"))(N,C);return q.ok?[q,{status:"complete",request:C,response:N}]:[q,{status:"complete",request:C,response:N}]}var Ua=class extends nt{list(e,n){return ae(eh(this,e?.api_version,e?.page_size,e?.page_token,n))}create(e,n){let{api_version:o}=e,i=Ie(e,["api_version"]);return ae(Qp(this,i,o,n))}delete(e,n,o){return ae(Zp(this,e,n?.api_version,o))}get(e,n,o){return ae(jp(this,e,n?.api_version,o))}update(e,n,o){let{api_version:i,update_mask:r}=n,a=Ie(n,["api_version","update_mask"]);return ae(th(this,e,a,i,r,o))}};function nh(t,e,n,o){return new ne(uS(t,e,n,o))}async function uS(t,e,n,o){var i,r,a;let c={body:e,api_version:n},d=ot("body",c.body,{explode:!0}),f={api_version:K("api_version",(i=c.api_version)!==null&&i!==void 0?i:t._options.api_version,{explode:!1,charEncoding:"percent"})},p=se("/{api_version}/environments")(f),h=new Headers(le({"Content-Type":"application/json",Accept:"application/json"})),g=await de(t._options.security),_=ce(g),m={options:t._options,base_url:(a=(r=o?.server_url)!==null&&r!==void 0?r:t._baseURL)!==null&&a!==void 0?a:"",operation_id:"CreateEnvironment",o_auth2_scopes:null,resolved_security:_,security_source:t._options.security,retry_config:o?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:o?.retry_codes||["408","409","429","5XX"]},v=t._createRequest(m,{security:_,method:"POST",baseURL:o?.server_url,path:p,headers:h,body:d,userAgent:t._options.user_agent,timeout_ms:o?.timeout_ms||t._options.timeout_ms||-1},o);if(!v.ok)return[v,{status:"invalid"}];let y=v.value,E=await t._do(y,{context:m,isErrorStatusCode:w=>ie({status:w},["4XX","5XX"]),retryConfig:m.retry_config,retryCodes:m.retry_codes});if(!E.ok)return[E,{status:"request-error",request:y}];let A=E.value,[C]=await ue(Y("4XX"),Y("5XX"),he("default"))(A,y);return C.ok?[C,{status:"complete",request:y,response:A}]:[C,{status:"complete",request:y,response:A}]}function oh(t,e,n,o){return new ne(cS(t,e,n,o))}async function cS(t,e,n,o){var i,r,a;let c={id:e,api_version:n},d=null,f={api_version:K("api_version",(i=c.api_version)!==null&&i!==void 0?i:t._options.api_version,{explode:!1,charEncoding:"percent"}),id:K("id",c.id,{explode:!1,charEncoding:"percent"})},p=se("/{api_version}/environments/{id}")(f),h=new Headers(le({Accept:"application/json"})),g=await de(t._options.security),_=ce(g),m={options:t._options,base_url:(a=(r=o?.server_url)!==null&&r!==void 0?r:t._baseURL)!==null&&a!==void 0?a:"",operation_id:"DeleteEnvironment",o_auth2_scopes:null,resolved_security:_,security_source:t._options.security,retry_config:o?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:o?.retry_codes||["408","409","429","5XX"]},v=t._createRequest(m,{security:_,method:"DELETE",baseURL:o?.server_url,path:p,headers:h,body:d,userAgent:t._options.user_agent,timeout_ms:o?.timeout_ms||t._options.timeout_ms||-1},o);if(!v.ok)return[v,{status:"invalid"}];let y=v.value,E=await t._do(y,{context:m,isErrorStatusCode:w=>ie({status:w},["4XX","5XX"]),retryConfig:m.retry_config,retryCodes:m.retry_codes});if(!E.ok)return[E,{status:"request-error",request:y}];let A=E.value,[C]=await ue(Y("4XX"),Y("5XX"),he("default"))(A,y);return C.ok?[C,{status:"complete",request:y,response:A}]:[C,{status:"complete",request:y,response:A}]}function ih(t,e,n,o){return new ne(dS(t,e,n,o))}async function dS(t,e,n,o){var i,r,a;let c={id:e,api_version:n},d=null,f={api_version:K("api_version",(i=c.api_version)!==null&&i!==void 0?i:t._options.api_version,{explode:!1,charEncoding:"percent"}),id:K("id",c.id,{explode:!1,charEncoding:"percent"})},p=se("/{api_version}/environments/{id}")(f),h=new Headers(le({Accept:"application/json"})),g=await de(t._options.security),_=ce(g),m={options:t._options,base_url:(a=(r=o?.server_url)!==null&&r!==void 0?r:t._baseURL)!==null&&a!==void 0?a:"",operation_id:"GetEnvironment",o_auth2_scopes:null,resolved_security:_,security_source:t._options.security,retry_config:o?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:o?.retry_codes||["408","409","429","5XX"]},v=t._createRequest(m,{security:_,method:"GET",baseURL:o?.server_url,path:p,headers:h,body:d,userAgent:t._options.user_agent,timeout_ms:o?.timeout_ms||t._options.timeout_ms||-1},o);if(!v.ok)return[v,{status:"invalid"}];let y=v.value,E=await t._do(y,{context:m,isErrorStatusCode:w=>ie({status:w},["4XX","5XX"]),retryConfig:m.retry_config,retryCodes:m.retry_codes});if(!E.ok)return[E,{status:"request-error",request:y}];let A=E.value,[C]=await ue(Y("4XX"),Y("5XX"),he("default"))(A,y);return C.ok?[C,{status:"complete",request:y,response:A}]:[C,{status:"complete",request:y,response:A}]}function rh(t,e,n,o,i){return new ne(fS(t,e,n,o,i))}async function fS(t,e,n,o,i){var r,a,u;let d={api_version:e,page_size:n,page_token:o},f=null,p={api_version:K("api_version",(r=d?.api_version)!==null&&r!==void 0?r:t._options.api_version,{explode:!1,charEncoding:"percent"})},h=se("/{api_version}/environments")(p),g=it({page_size:d?.page_size,page_token:d?.page_token}),_=new Headers(le({Accept:"application/json"})),m=await de(t._options.security),v=ce(m),y={options:t._options,base_url:(u=(a=i?.server_url)!==null&&a!==void 0?a:t._baseURL)!==null&&u!==void 0?u:"",operation_id:"ListEnvironments",o_auth2_scopes:null,resolved_security:v,security_source:t._options.security,retry_config:i?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:i?.retry_codes||["408","409","429","5XX"]},E=t._createRequest(y,{security:v,method:"GET",baseURL:i?.server_url,path:h,headers:_,query:g,body:f,userAgent:t._options.user_agent,timeout_ms:i?.timeout_ms||t._options.timeout_ms||-1},i);if(!E.ok)return[E,{status:"invalid"}];let A=E.value,C=await t._do(A,{context:y,isErrorStatusCode:q=>ie({status:q},["4XX","5XX"]),retryConfig:y.retry_config,retryCodes:y.retry_codes});if(!C.ok)return[C,{status:"request-error",request:A}];let w=C.value,[N]=await ue(Y("4XX"),Y("5XX"),he("default"))(w,A);return N.ok?[N,{status:"complete",request:A,response:w}]:[N,{status:"complete",request:A,response:w}]}function sh(t,e,n,o,i,r,a,u){return new ne(pS(t,e,n,o,i,r,a,u))}async function pS(t,e,n,o,i,r,a,u){var c,d,f;let h={environment:e,path:n,api_version:o,page_size:i,page_token:r,recursive:a},g=null,_={api_version:K("api_version",(c=h.api_version)!==null&&c!==void 0?c:t._options.api_version,{explode:!1,charEncoding:"percent"}),environment:K("environment",h.environment,{explode:!1,charEncoding:"percent"}),path:K("path",h.path,{explode:!1,charEncoding:"percentExceptReserved"})},m=se("/{api_version}/environments/{environment}/files/{path}")(_),v=it({page_size:h.page_size,page_token:h.page_token,recursive:h.recursive}),y=new Headers(le({Accept:"application/json"})),E=await de(t._options.security),A=ce(E),C={options:t._options,base_url:(f=(d=u?.server_url)!==null&&d!==void 0?d:t._baseURL)!==null&&f!==void 0?f:"",operation_id:"GetEnvironmentFiles",o_auth2_scopes:null,resolved_security:A,security_source:t._options.security,retry_config:u?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:u?.retry_codes||["408","409","429","5XX"]},w=t._createRequest(C,{security:A,method:"GET",baseURL:u?.server_url,path:m,headers:y,query:v,body:g,userAgent:t._options.user_agent,timeout_ms:u?.timeout_ms||t._options.timeout_ms||-1},u);if(!w.ok)return[w,{status:"invalid"}];let N=w.value,q=await t._do(N,{context:C,isErrorStatusCode:O=>ie({status:O},["4XX","5XX"]),retryConfig:C.retry_config,retryCodes:C.retry_codes});if(!q.ok)return[q,{status:"request-error",request:N}];let V=q.value,[M]=await ue(he(200),Y("4XX"),Y("5XX"))(V,N);return M.ok?[M,{status:"complete",request:N,response:V}]:[M,{status:"complete",request:N,response:V}]}var Ga=class extends nt{list(e,n,o,i){return ae(sh(this,e,n,o?.api_version,o?.page_size,o?.page_token,o?.recursive,i))}};function ah(t,e,n,o,i,r,a,u,c,d,f){return new ne(hS(t,e,n,o,i,r,a,u,c,d,f))}async function hS(t,e,n,o,i,r,a,u,c,d,f){var p,h,g;let m={environment:e,path:n,"X-Goog-Upload-Command":o,"X-Goog-Upload-Header-Content-Length":i,"X-Goog-Upload-Header-Content-Type":r,"X-Goog-Upload-Protocol":a,api_version:u,extract:c,overwrite:d},v=null,y={api_version:K("api_version",(p=m.api_version)!==null&&p!==void 0?p:t._options.api_version,{explode:!1,charEncoding:"percent"}),environment:K("environment",m.environment,{explode:!1,charEncoding:"percent"}),path:K("path",m.path,{explode:!1,charEncoding:"percentExceptReserved"})},E=se("/upload/{api_version}/environments/{environment}/files/{path}")(y),A=it({extract:m.extract,overwrite:m.overwrite}),C=new Headers(le({Accept:"*/*","X-Goog-Upload-Command":K("X-Goog-Upload-Command",m["X-Goog-Upload-Command"],{explode:!1,charEncoding:"none"}),"X-Goog-Upload-Header-Content-Length":K("X-Goog-Upload-Header-Content-Length",m["X-Goog-Upload-Header-Content-Length"],{explode:!1,charEncoding:"none"}),"X-Goog-Upload-Header-Content-Type":K("X-Goog-Upload-Header-Content-Type",m["X-Goog-Upload-Header-Content-Type"],{explode:!1,charEncoding:"none"}),"X-Goog-Upload-Protocol":K("X-Goog-Upload-Protocol",m["X-Goog-Upload-Protocol"],{explode:!1,charEncoding:"none"})})),w=await de(t._options.security),N=ce(w),q={options:t._options,base_url:(g=(h=f?.server_url)!==null&&h!==void 0?h:t._baseURL)!==null&&g!==void 0?g:"",operation_id:"StartEnvironmentFileUpload",o_auth2_scopes:null,resolved_security:N,security_source:t._options.security,retry_config:f?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:f?.retry_codes||["408","409","429","5XX"]},V=t._createRequest(q,{security:N,method:"PUT",baseURL:f?.server_url,path:E,headers:C,query:A,body:v,userAgent:t._options.user_agent,timeout_ms:f?.timeout_ms||t._options.timeout_ms||-1},f);if(!V.ok)return[V,{status:"invalid"}];let M=V.value,O=await t._do(M,{context:q,isErrorStatusCode:D=>ie({status:D},["4XX","5XX"]),retryConfig:q.retry_config,retryCodes:q.retry_codes});if(!O.ok)return[O,{status:"request-error",request:M}];let H=O.value,$={httpMeta:{response:H,request:M}},[j]=await ue(Xp(200,{hdrs:!0}),Y("4XX"),Y("5XX"))(H,M,{extraFields:$});return j.ok?[j,{status:"complete",request:M,response:H}]:[j,{status:"complete",request:M,response:H}]}var ba=class extends nt{startUpload(e,n,o,i){return ae(ah(this,e,n,o["X-Goog-Upload-Command"],o["X-Goog-Upload-Header-Content-Length"],o["X-Goog-Upload-Header-Content-Type"],o["X-Goog-Upload-Protocol"],o.api_version,o.extract,o.overwrite,i))}};var La=class extends nt{get internal(){var e;return(e=this._internal)!==null&&e!==void 0?e:this._internal=new ba(this._options)}get files(){var e;return(e=this._files)!==null&&e!==void 0?e:this._files=new Ga(this._options)}listEnvironments(e,n){return ae(rh(this,e?.api_version,e?.page_size,e?.page_token,n))}createEnvironment(e,n,o){return ae(nh(this,e,n,o))}deleteEnvironment(e,n,o){return ae(oh(this,e,n?.api_version,o))}getEnvironment(e,n,o){return ae(ih(this,e,n?.api_version,o))}};var qa=class extends tt{constructor(e,n){var o;let i=((o=e.error)===null||o===void 0?void 0:o.message)||`API error occurred: ${JSON.stringify(e)}`;super(i,n),this.data$=e,this.error=e.error,this.name="CancelInteractionByIdServerError"}},Oa=class extends tt{constructor(e,n){var o;let i=((o=e.error)===null||o===void 0?void 0:o.message)||`API error occurred: ${JSON.stringify(e)}`;super(i,n),this.data$=e,this.error=e.error,this.name="CancelInteractionByIdClientError"}};var Fa=class extends tt{constructor(e,n){var o;let i=((o=e.error)===null||o===void 0?void 0:o.message)||`API error occurred: ${JSON.stringify(e)}`;super(i,n),this.data$=e,this.error=e.error,this.name="CreateInteractionServerError"}},Ha=class extends tt{constructor(e,n){var o;let i=((o=e.error)===null||o===void 0?void 0:o.message)||`API error occurred: ${JSON.stringify(e)}`;super(i,n),this.data$=e,this.error=e.error,this.name="CreateInteractionClientError"}};var Va=class extends tt{constructor(e,n){var o;let i=((o=e.error)===null||o===void 0?void 0:o.message)||`API error occurred: ${JSON.stringify(e)}`;super(i,n),this.data$=e,this.error=e.error,this.name="DeleteInteractionServerError"}},Ba=class extends tt{constructor(e,n){var o;let i=((o=e.error)===null||o===void 0?void 0:o.message)||`API error occurred: ${JSON.stringify(e)}`;super(i,n),this.data$=e,this.error=e.error,this.name="DeleteInteractionClientError"}};var $a=class extends tt{constructor(e,n){var o;let i=((o=e.error)===null||o===void 0?void 0:o.message)||`API error occurred: ${JSON.stringify(e)}`;super(i,n),this.data$=e,this.error=e.error,this.name="GetInteractionByIdServerError"}},Xa=class extends tt{constructor(e,n){var o;let i=((o=e.error)===null||o===void 0?void 0:o.message)||`API error occurred: ${JSON.stringify(e)}`;super(i,n),this.data$=e,this.error=e.error,this.name="GetInteractionByIdClientError"}};function lh(t,e,n,o){return new ne(mS(t,e,n,o))}async function mS(t,e,n,o){var i,r,a;let c={id:e,api_version:n},d=null,f={api_version:K("api_version",(i=c.api_version)!==null&&i!==void 0?i:t._options.api_version,{explode:!1,charEncoding:"percent"}),interactionsId:K("interactionsId",c.id,{explode:!1,charEncoding:"percent"})},p=se("/{api_version}/interactions/{interactionsId}/cancel")(f),h=new Headers(le({Accept:"application/json"})),g=await de(t._options.security),_=ce(g),m={options:t._options,base_url:(a=(r=o?.server_url)!==null&&r!==void 0?r:t._baseURL)!==null&&a!==void 0?a:"",operation_id:"cancelInteractionById",o_auth2_scopes:null,resolved_security:_,security_source:t._options.security,retry_config:o?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:o?.retry_codes||["408","409","429","5XX"]},v=t._createRequest(m,{security:_,method:"POST",baseURL:o?.server_url,path:p,headers:h,body:d,userAgent:t._options.user_agent,timeout_ms:o?.timeout_ms||t._options.timeout_ms||-1},o);if(!v.ok)return[v,{status:"invalid"}];let y=v.value,E=await t._do(y,{context:m,isErrorStatusCode:N=>ie({status:N},["4XX","5XX"]),retryConfig:m.retry_config,retryCodes:m.retry_codes});if(!E.ok)return[E,{status:"request-error",request:y}];let A=E.value,C={httpMeta:{response:A,request:y}},[w]=await ue(he(200),Xt("4XX",Oa),Xt("5XX",qa))(A,y,{extraFields:C});return w.ok?[w,{status:"complete",request:y,response:A}]:[w,{status:"complete",request:y,response:A}]}function uh(t,e,n,o){return new ne(gS(t,e,n,o))}async function gS(t,e,n,o){var i,r,a,u;let c={body:e,api_version:n},d=c,f=ot("body",d.body,{explode:!0}),p={api_version:K("api_version",(i=d.api_version)!==null&&i!==void 0?i:t._options.api_version,{explode:!1,charEncoding:"percent"})},h=se("/{api_version}/interactions")(p),g=new Headers(le({"Content-Type":"application/json",Accept:!((r=c?.body)===null||r===void 0)&&r.stream?"text/event-stream":"application/json"})),_=await de(t._options.security),m=ce(_),v={options:t._options,base_url:(u=(a=o?.server_url)!==null&&a!==void 0?a:t._baseURL)!==null&&u!==void 0?u:"",operation_id:"CreateInteraction",o_auth2_scopes:null,resolved_security:m,security_source:t._options.security,retry_config:o?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:o?.retry_codes||["408","409","429","5XX"]},y=t._createRequest(v,{security:m,method:"POST",baseURL:o?.server_url,path:h,headers:g,body:f,userAgent:t._options.user_agent,timeout_ms:o?.timeout_ms||t._options.timeout_ms||-1},o);if(!y.ok)return[y,{status:"invalid"}];let E=y.value,A=await t._do(E,{context:v,isErrorStatusCode:q=>ie({status:q},["4XX","5XX"]),retryConfig:v.retry_config,retryCodes:v.retry_codes});if(!A.ok)return[A,{status:"request-error",request:E}];let C=A.value,w={httpMeta:{response:C,request:E}},[N]=await ue(he(200),$p(200,{sentinel:"[DONE]",flattened:!0}),Xt("4XX",Ha),Xt("5XX",Fa))(C,E,{extraFields:w});return N.ok?[N,{status:"complete",request:E,response:C}]:[N,{status:"complete",request:E,response:C}]}function _S(t,e,n,o){return new ne(yS(t,e,n,o))}async function yS(t,e,n,o){var i,r,a;let c={id:e,api_version:n},d=null,f={api_version:K("api_version",(i=c.api_version)!==null&&i!==void 0?i:t._options.api_version,{explode:!1,charEncoding:"percent"}),interactionsId:K("interactionsId",c.id,{explode:!1,charEncoding:"percent"})},p=se("/{api_version}/interactions/{interactionsId}")(f),h=new Headers(le({Accept:"application/json"})),g=await de(t._options.security),_=ce(g),m={options:t._options,base_url:(a=(r=o?.server_url)!==null&&r!==void 0?r:t._baseURL)!==null&&a!==void 0?a:"",operation_id:"deleteInteraction",o_auth2_scopes:null,resolved_security:_,security_source:t._options.security,retry_config:o?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:o?.retry_codes||["408","409","429","5XX"]},v=t._createRequest(m,{security:_,method:"DELETE",baseURL:o?.server_url,path:p,headers:h,body:d,userAgent:t._options.user_agent,timeout_ms:o?.timeout_ms||t._options.timeout_ms||-1},o);if(!v.ok)return[v,{status:"invalid"}];let y=v.value,E=await t._do(y,{context:m,isErrorStatusCode:N=>ie({status:N},["4XX","5XX"]),retryConfig:m.retry_config,retryCodes:m.retry_codes});if(!E.ok)return[E,{status:"request-error",request:y}];let A=E.value,C={httpMeta:{response:A,request:y}},[w]=await ue(Xp(200),Xt("4XX",Ba),Xt("5XX",Va))(A,y,{extraFields:C});return w.ok?[w,{status:"complete",request:y,response:A}]:[w,{status:"complete",request:y,response:A}]}function ch(t,e,n,o,i,r,a){return new ne(vS(t,e,n,o,i,r,a))}async function vS(t,e,n,o,i,r,a){var u,c,d;let f={id:e,api_version:n,include_input:o,last_event_id:i,stream:r},p=f,h=null,g={api_version:K("api_version",(u=p.api_version)!==null&&u!==void 0?u:t._options.api_version,{explode:!1,charEncoding:"percent"}),interactionsId:K("interactionsId",p.id,{explode:!1,charEncoding:"percent"})},_=se("/{api_version}/interactions/{interactionsId}")(g),m=it({include_input:p.include_input,last_event_id:p.last_event_id,stream:p.stream}),v=new Headers(le({Accept:f?.stream?"text/event-stream":"application/json"})),y=await de(t._options.security),E=ce(y),A={options:t._options,base_url:(d=(c=a?.server_url)!==null&&c!==void 0?c:t._baseURL)!==null&&d!==void 0?d:"",operation_id:"getInteractionById",o_auth2_scopes:null,resolved_security:E,security_source:t._options.security,retry_config:a?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:a?.retry_codes||["408","409","429","5XX"]},C=t._createRequest(A,{security:E,method:"GET",baseURL:a?.server_url,path:_,headers:v,query:m,body:h,userAgent:t._options.user_agent,timeout_ms:a?.timeout_ms||t._options.timeout_ms||-1},a);if(!C.ok)return[C,{status:"invalid"}];let w=C.value,N=await t._do(w,{context:A,isErrorStatusCode:O=>ie({status:O},["4XX","5XX"]),retryConfig:A.retry_config,retryCodes:A.retry_codes});if(!N.ok)return[N,{status:"request-error",request:w}];let q=N.value,V={httpMeta:{response:q,request:w}},[M]=await ue(he(200),$p(200,{sentinel:"[DONE]",flattened:!0}),Xt("4XX",Xa),Xt("5XX",$a))(q,w,{extraFields:V});return M.ok?[M,{status:"complete",request:w,response:q}]:[M,{status:"complete",request:w,response:q}]}var Ja=class extends nt{create(e,n){let{api_version:o}=e,i=Ie(e,["api_version"]);return ae(uh(this,i,o,n))}delete(e,n,o){return ae(_S(this,e,n?.api_version,o))}get(e,n,o){return ae(ch(this,e,n?.api_version,n?.include_input,n?.last_event_id,n?.stream,o))}cancel(e,n,o){return ae(lh(this,e,n?.api_version,o))}};function dh(t,e,n,o){return new ne(ES(t,e,n,o))}async function ES(t,e,n,o){var i,r,a;let c={body:e,api_version:n},d=ot("body",c.body,{explode:!0}),f={api_version:K("api_version",(i=c.api_version)!==null&&i!==void 0?i:t._options.api_version,{explode:!1,charEncoding:"percent"})},p=se("/{api_version}/triggers")(f),h=new Headers(le({"Content-Type":"application/json",Accept:"application/json"})),g=await de(t._options.security),_=ce(g),m={options:t._options,base_url:(a=(r=o?.server_url)!==null&&r!==void 0?r:t._baseURL)!==null&&a!==void 0?a:"",operation_id:"CreateTrigger",o_auth2_scopes:null,resolved_security:_,security_source:t._options.security,retry_config:o?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:o?.retry_codes||["408","409","429","5XX"]},v=t._createRequest(m,{security:_,method:"POST",baseURL:o?.server_url,path:p,headers:h,body:d,userAgent:t._options.user_agent,timeout_ms:o?.timeout_ms||t._options.timeout_ms||-1},o);if(!v.ok)return[v,{status:"invalid"}];let y=v.value,E=await t._do(y,{context:m,isErrorStatusCode:w=>ie({status:w},["4XX","5XX"]),retryConfig:m.retry_config,retryCodes:m.retry_codes});if(!E.ok)return[E,{status:"request-error",request:y}];let A=E.value,[C]=await ue(Y("4XX"),Y("5XX"),he("default"))(A,y);return C.ok?[C,{status:"complete",request:y,response:A}]:[C,{status:"complete",request:y,response:A}]}function fh(t,e,n,o){return new ne(TS(t,e,n,o))}async function TS(t,e,n,o){var i,r,a;let c={id:e,api_version:n},d=null,f={api_version:K("api_version",(i=c.api_version)!==null&&i!==void 0?i:t._options.api_version,{explode:!1,charEncoding:"percent"}),id:K("id",c.id,{explode:!1,charEncoding:"percent"})},p=se("/{api_version}/triggers/{id}")(f),h=new Headers(le({Accept:"application/json"})),g=await de(t._options.security),_=ce(g),m={options:t._options,base_url:(a=(r=o?.server_url)!==null&&r!==void 0?r:t._baseURL)!==null&&a!==void 0?a:"",operation_id:"DeleteTrigger",o_auth2_scopes:null,resolved_security:_,security_source:t._options.security,retry_config:o?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:o?.retry_codes||["408","409","429","5XX"]},v=t._createRequest(m,{security:_,method:"DELETE",baseURL:o?.server_url,path:p,headers:h,body:d,userAgent:t._options.user_agent,timeout_ms:o?.timeout_ms||t._options.timeout_ms||-1},o);if(!v.ok)return[v,{status:"invalid"}];let y=v.value,E=await t._do(y,{context:m,isErrorStatusCode:w=>ie({status:w},["4XX","5XX"]),retryConfig:m.retry_config,retryCodes:m.retry_codes});if(!E.ok)return[E,{status:"request-error",request:y}];let A=E.value,[C]=await ue(Y("4XX"),Y("5XX"),he("default"))(A,y);return C.ok?[C,{status:"complete",request:y,response:A}]:[C,{status:"complete",request:y,response:A}]}function ph(t,e,n,o){return new ne(AS(t,e,n,o))}async function AS(t,e,n,o){var i,r,a;let c={id:e,api_version:n},d=null,f={api_version:K("api_version",(i=c.api_version)!==null&&i!==void 0?i:t._options.api_version,{explode:!1,charEncoding:"percent"}),id:K("id",c.id,{explode:!1,charEncoding:"percent"})},p=se("/{api_version}/triggers/{id}")(f),h=new Headers(le({Accept:"application/json"})),g=await de(t._options.security),_=ce(g),m={options:t._options,base_url:(a=(r=o?.server_url)!==null&&r!==void 0?r:t._baseURL)!==null&&a!==void 0?a:"",operation_id:"GetTrigger",o_auth2_scopes:null,resolved_security:_,security_source:t._options.security,retry_config:o?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:o?.retry_codes||["408","409","429","5XX"]},v=t._createRequest(m,{security:_,method:"GET",baseURL:o?.server_url,path:p,headers:h,body:d,userAgent:t._options.user_agent,timeout_ms:o?.timeout_ms||t._options.timeout_ms||-1},o);if(!v.ok)return[v,{status:"invalid"}];let y=v.value,E=await t._do(y,{context:m,isErrorStatusCode:w=>ie({status:w},["4XX","5XX"]),retryConfig:m.retry_config,retryCodes:m.retry_codes});if(!E.ok)return[E,{status:"request-error",request:y}];let A=E.value,[C]=await ue(Y("4XX"),Y("5XX"),he("default"))(A,y);return C.ok?[C,{status:"complete",request:y,response:A}]:[C,{status:"complete",request:y,response:A}]}function hh(t,e,n,o,i,r){return new ne(CS(t,e,n,o,i,r))}async function CS(t,e,n,o,i,r){var a,u,c;let f={trigger_id:e,api_version:n,page_size:o,page_token:i},p=null,h={api_version:K("api_version",(a=f.api_version)!==null&&a!==void 0?a:t._options.api_version,{explode:!1,charEncoding:"percent"}),triggerId:K("triggerId",f.trigger_id,{explode:!1,charEncoding:"percent"})},g=se("/{api_version}/triggers/{triggerId}/executions")(h),_=it({page_size:f.page_size,page_token:f.page_token}),m=new Headers(le({Accept:"application/json"})),v=await de(t._options.security),y=ce(v),E={options:t._options,base_url:(c=(u=r?.server_url)!==null&&u!==void 0?u:t._baseURL)!==null&&c!==void 0?c:"",operation_id:"ListTriggerExecutions",o_auth2_scopes:null,resolved_security:y,security_source:t._options.security,retry_config:r?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:r?.retry_codes||["408","409","429","5XX"]},A=t._createRequest(E,{security:y,method:"GET",baseURL:r?.server_url,path:g,headers:m,query:_,body:p,userAgent:t._options.user_agent,timeout_ms:r?.timeout_ms||t._options.timeout_ms||-1},r);if(!A.ok)return[A,{status:"invalid"}];let C=A.value,w=await t._do(C,{context:E,isErrorStatusCode:V=>ie({status:V},["4XX","5XX"]),retryConfig:E.retry_config,retryCodes:E.retry_codes});if(!w.ok)return[w,{status:"request-error",request:C}];let N=w.value,[q]=await ue(Y("4XX"),Y("5XX"),he("default"))(N,C);return q.ok?[q,{status:"complete",request:C,response:N}]:[q,{status:"complete",request:C,response:N}]}function mh(t,e,n,o,i,r){return new ne(IS(t,e,n,o,i,r))}async function IS(t,e,n,o,i,r){var a,u,c;let f={api_version:e,filter:n,page_size:o,page_token:i},p=null,h={api_version:K("api_version",(a=f?.api_version)!==null&&a!==void 0?a:t._options.api_version,{explode:!1,charEncoding:"percent"})},g=se("/{api_version}/triggers")(h),_=it({filter:f?.filter,page_size:f?.page_size,page_token:f?.page_token}),m=new Headers(le({Accept:"application/json"})),v=await de(t._options.security),y=ce(v),E={options:t._options,base_url:(c=(u=r?.server_url)!==null&&u!==void 0?u:t._baseURL)!==null&&c!==void 0?c:"",operation_id:"ListTriggers",o_auth2_scopes:null,resolved_security:y,security_source:t._options.security,retry_config:r?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:r?.retry_codes||["408","409","429","5XX"]},A=t._createRequest(E,{security:y,method:"GET",baseURL:r?.server_url,path:g,headers:m,query:_,body:p,userAgent:t._options.user_agent,timeout_ms:r?.timeout_ms||t._options.timeout_ms||-1},r);if(!A.ok)return[A,{status:"invalid"}];let C=A.value,w=await t._do(C,{context:E,isErrorStatusCode:V=>ie({status:V},["4XX","5XX"]),retryConfig:E.retry_config,retryCodes:E.retry_codes});if(!w.ok)return[w,{status:"request-error",request:C}];let N=w.value,[q]=await ue(Y("4XX"),Y("5XX"),he("default"))(N,C);return q.ok?[q,{status:"complete",request:C,response:N}]:[q,{status:"complete",request:C,response:N}]}function gh(t,e,n,o){return new ne(SS(t,e,n,o))}async function SS(t,e,n,o){var i,r,a;let c={trigger_id:e,api_version:n},d=null,f={api_version:K("api_version",(i=c.api_version)!==null&&i!==void 0?i:t._options.api_version,{explode:!1,charEncoding:"percent"}),triggerId:K("triggerId",c.trigger_id,{explode:!1,charEncoding:"percent"})},p=se("/{api_version}/triggers/{triggerId}/executions")(f),h=new Headers(le({Accept:"application/json"})),g=await de(t._options.security),_=ce(g),m={options:t._options,base_url:(a=(r=o?.server_url)!==null&&r!==void 0?r:t._baseURL)!==null&&a!==void 0?a:"",operation_id:"RunTrigger",o_auth2_scopes:null,resolved_security:_,security_source:t._options.security,retry_config:o?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:o?.retry_codes||["408","409","429","5XX"]},v=t._createRequest(m,{security:_,method:"POST",baseURL:o?.server_url,path:p,headers:h,body:d,userAgent:t._options.user_agent,timeout_ms:o?.timeout_ms||t._options.timeout_ms||-1},o);if(!v.ok)return[v,{status:"invalid"}];let y=v.value,E=await t._do(y,{context:m,isErrorStatusCode:w=>ie({status:w},["4XX","5XX"]),retryConfig:m.retry_config,retryCodes:m.retry_codes});if(!E.ok)return[E,{status:"request-error",request:y}];let A=E.value,[C]=await ue(Y("4XX"),Y("5XX"),he("default"))(A,y);return C.ok?[C,{status:"complete",request:y,response:A}]:[C,{status:"complete",request:y,response:A}]}function _h(t,e,n,o,i){return new ne(wS(t,e,n,o,i))}async function wS(t,e,n,o,i){var r,a,u;let d={id:e,body:n,api_version:o},f=ot("body",d.body,{explode:!0}),p={api_version:K("api_version",(r=d.api_version)!==null&&r!==void 0?r:t._options.api_version,{explode:!1,charEncoding:"percent"}),id:K("id",d.id,{explode:!1,charEncoding:"percent"})},h=se("/{api_version}/triggers/{id}")(p),g=new Headers(le({"Content-Type":"application/json",Accept:"application/json"})),_=await de(t._options.security),m=ce(_),v={options:t._options,base_url:(u=(a=i?.server_url)!==null&&a!==void 0?a:t._baseURL)!==null&&u!==void 0?u:"",operation_id:"UpdateTrigger",o_auth2_scopes:null,resolved_security:m,security_source:t._options.security,retry_config:i?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:i?.retry_codes||["408","409","429","5XX"]},y=t._createRequest(v,{security:m,method:"PATCH",baseURL:i?.server_url,path:h,headers:g,body:f,userAgent:t._options.user_agent,timeout_ms:i?.timeout_ms||t._options.timeout_ms||-1},i);if(!y.ok)return[y,{status:"invalid"}];let E=y.value,A=await t._do(E,{context:v,isErrorStatusCode:N=>ie({status:N},["4XX","5XX"]),retryConfig:v.retry_config,retryCodes:v.retry_codes});if(!A.ok)return[A,{status:"request-error",request:E}];let C=A.value,[w]=await ue(Y("4XX"),Y("5XX"),he("default"))(C,E);return w.ok?[w,{status:"complete",request:E,response:C}]:[w,{status:"complete",request:E,response:C}]}var Ka=class extends nt{list(e,n){return ae(mh(this,e?.api_version,e?.filter,e?.page_size,e?.page_token,n))}create(e,n){let{api_version:o}=e,i=Ie(e,["api_version"]);return ae(dh(this,i,o,n))}delete(e,n,o){return ae(fh(this,e,n?.api_version,o))}get(e,n,o){return ae(ph(this,e,n?.api_version,o))}update(e,n,o){let{api_version:i}=n,r=Ie(n,["api_version"]);return ae(_h(this,e,r,i,o))}listExecutions(e,n,o){return ae(hh(this,e,n?.api_version,n?.page_size,n?.page_token,o))}run(e,n,o){return ae(gh(this,e,n?.api_version,o))}};function yh(t,e,n,o){return new ne(RS(t,e,n,o))}async function RS(t,e,n,o){var i,r,a;let c={body:e,api_version:n},d=ot("body",c.body,{explode:!0}),f={api_version:K("api_version",(i=c.api_version)!==null&&i!==void 0?i:t._options.api_version,{explode:!1,charEncoding:"percent"})},p=se("/{api_version}/voices")(f),h=new Headers(le({"Content-Type":"application/json",Accept:"application/json"})),g=await de(t._options.security),_=ce(g),m={options:t._options,base_url:(a=(r=o?.server_url)!==null&&r!==void 0?r:t._baseURL)!==null&&a!==void 0?a:"",operation_id:"CreateVoice",o_auth2_scopes:null,resolved_security:_,security_source:t._options.security,retry_config:o?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:o?.retry_codes||["408","409","429","5XX"]},v=t._createRequest(m,{security:_,method:"POST",baseURL:o?.server_url,path:p,headers:h,body:d,userAgent:t._options.user_agent,timeout_ms:o?.timeout_ms||t._options.timeout_ms||-1},o);if(!v.ok)return[v,{status:"invalid"}];let y=v.value,E=await t._do(y,{context:m,isErrorStatusCode:w=>ie({status:w},["4XX","5XX"]),retryConfig:m.retry_config,retryCodes:m.retry_codes});if(!E.ok)return[E,{status:"request-error",request:y}];let A=E.value,[C]=await ue(Y("4XX"),Y("5XX"),he("default"))(A,y);return C.ok?[C,{status:"complete",request:y,response:A}]:[C,{status:"complete",request:y,response:A}]}function vh(t,e,n,o){return new ne(PS(t,e,n,o))}async function PS(t,e,n,o){var i,r,a;let c={id:e,api_version:n},d=null,f={api_version:K("api_version",(i=c.api_version)!==null&&i!==void 0?i:t._options.api_version,{explode:!1,charEncoding:"percent"}),voicesId:K("voicesId",c.id,{explode:!1,charEncoding:"percent"})},p=se("/{api_version}/voices/{voicesId}")(f),h=new Headers(le({Accept:"application/json"})),g=await de(t._options.security),_=ce(g),m={options:t._options,base_url:(a=(r=o?.server_url)!==null&&r!==void 0?r:t._baseURL)!==null&&a!==void 0?a:"",operation_id:"DeleteVoice",o_auth2_scopes:null,resolved_security:_,security_source:t._options.security,retry_config:o?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:o?.retry_codes||["408","409","429","5XX"]},v=t._createRequest(m,{security:_,method:"DELETE",baseURL:o?.server_url,path:p,headers:h,body:d,userAgent:t._options.user_agent,timeout_ms:o?.timeout_ms||t._options.timeout_ms||-1},o);if(!v.ok)return[v,{status:"invalid"}];let y=v.value,E=await t._do(y,{context:m,isErrorStatusCode:w=>ie({status:w},["4XX","5XX"]),retryConfig:m.retry_config,retryCodes:m.retry_codes});if(!E.ok)return[E,{status:"request-error",request:y}];let A=E.value,[C]=await ue(Y("4XX"),Y("5XX"),he("default"))(A,y);return C.ok?[C,{status:"complete",request:y,response:A}]:[C,{status:"complete",request:y,response:A}]}function Eh(t,e,n,o){return new ne(kS(t,e,n,o))}async function kS(t,e,n,o){var i,r,a;let c={id:e,api_version:n},d=null,f={api_version:K("api_version",(i=c.api_version)!==null&&i!==void 0?i:t._options.api_version,{explode:!1,charEncoding:"percent"}),voicesId:K("voicesId",c.id,{explode:!1,charEncoding:"percent"})},p=se("/{api_version}/voices/{voicesId}")(f),h=new Headers(le({Accept:"application/json"})),g=await de(t._options.security),_=ce(g),m={options:t._options,base_url:(a=(r=o?.server_url)!==null&&r!==void 0?r:t._baseURL)!==null&&a!==void 0?a:"",operation_id:"GetVoice",o_auth2_scopes:null,resolved_security:_,security_source:t._options.security,retry_config:o?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:o?.retry_codes||["408","409","429","5XX"]},v=t._createRequest(m,{security:_,method:"GET",baseURL:o?.server_url,path:p,headers:h,body:d,userAgent:t._options.user_agent,timeout_ms:o?.timeout_ms||t._options.timeout_ms||-1},o);if(!v.ok)return[v,{status:"invalid"}];let y=v.value,E=await t._do(y,{context:m,isErrorStatusCode:w=>ie({status:w},["4XX","5XX"]),retryConfig:m.retry_config,retryCodes:m.retry_codes});if(!E.ok)return[E,{status:"request-error",request:y}];let A=E.value,[C]=await ue(Y("4XX"),Y("5XX"),he("default"))(A,y);return C.ok?[C,{status:"complete",request:y,response:A}]:[C,{status:"complete",request:y,response:A}]}function Th(t,e,n,o,i,r,a,u,c,d,f,p,h,g){return new ne(NS(t,e,n,o,i,r,a,u,c,d,f,p,h,g))}async function NS(t,e,n,o,i,r,a,u,c,d,f,p,h,g){var _,m,v;let E={api_version:e,accent:n,contexts:o,gender:i,language_code:r,page_size:a,page_token:u,persona:c,pitch:d,region_code:f,search:p,type:h},A=null,C={api_version:K("api_version",(_=E?.api_version)!==null&&_!==void 0?_:t._options.api_version,{explode:!1,charEncoding:"percent"})},w=se("/{api_version}/voices")(C),N=it({accent:E?.accent,context:E?.contexts,gender:E?.gender,language_code:E?.language_code,page_size:E?.page_size,page_token:E?.page_token,persona:E?.persona,pitch:E?.pitch,region_code:E?.region_code,search:E?.search,type:E?.type}),q=new Headers(le({Accept:"application/json"})),V=await de(t._options.security),M=ce(V),O={options:t._options,base_url:(v=(m=g?.server_url)!==null&&m!==void 0?m:t._baseURL)!==null&&v!==void 0?v:"",operation_id:"ListVoices",o_auth2_scopes:null,resolved_security:M,security_source:t._options.security,retry_config:g?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:g?.retry_codes||["408","409","429","5XX"]},H=t._createRequest(O,{security:M,method:"GET",baseURL:g?.server_url,path:w,headers:q,query:N,body:A,userAgent:t._options.user_agent,timeout_ms:g?.timeout_ms||t._options.timeout_ms||-1},g);if(!H.ok)return[H,{status:"invalid"}];let $=H.value,j=await t._do($,{context:O,isErrorStatusCode:te=>ie({status:te},["4XX","5XX"]),retryConfig:O.retry_config,retryCodes:O.retry_codes});if(!j.ok)return[j,{status:"request-error",request:$}];let D=j.value,[Q]=await ue(Y("4XX"),Y("5XX"),he("default"))(D,$);return Q.ok?[Q,{status:"complete",request:$,response:D}]:[Q,{status:"complete",request:$,response:D}]}var Ya=class extends nt{list(e,n){return ae(Th(this,e?.api_version,e?.accent,e?.contexts,e?.gender,e?.language_code,e?.page_size,e?.page_token,e?.persona,e?.pitch,e?.region_code,e?.search,e?.type,n))}create(e,n,o){return ae(yh(this,e,n,o))}delete(e,n,o){return ae(vh(this,e,n?.api_version,o))}get(e,n,o){return ae(Eh(this,e,n?.api_version,o))}};function Ah(t,e,n,o){return new ne(xS(t,e,n,o))}async function xS(t,e,n,o){var i,r,a;let c={body:e,api_version:n},d=ot("body",c.body,{explode:!0}),f={api_version:K("api_version",(i=c.api_version)!==null&&i!==void 0?i:t._options.api_version,{explode:!1,charEncoding:"percent"})},p=se("/{api_version}/webhooks")(f),h=new Headers(le({"Content-Type":"application/json",Accept:"application/json"})),g=await de(t._options.security),_=ce(g),m={options:t._options,base_url:(a=(r=o?.server_url)!==null&&r!==void 0?r:t._baseURL)!==null&&a!==void 0?a:"",operation_id:"CreateWebhook",o_auth2_scopes:null,resolved_security:_,security_source:t._options.security,retry_config:o?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:o?.retry_codes||["408","409","429","5XX"]},v=t._createRequest(m,{security:_,method:"POST",baseURL:o?.server_url,path:p,headers:h,body:d,userAgent:t._options.user_agent,timeout_ms:o?.timeout_ms||t._options.timeout_ms||-1},o);if(!v.ok)return[v,{status:"invalid"}];let y=v.value,E=await t._do(y,{context:m,isErrorStatusCode:w=>ie({status:w},["4XX","5XX"]),retryConfig:m.retry_config,retryCodes:m.retry_codes});if(!E.ok)return[E,{status:"request-error",request:y}];let A=E.value,[C]=await ue(Y("4XX"),Y("5XX"),he("default"))(A,y);return C.ok?[C,{status:"complete",request:y,response:A}]:[C,{status:"complete",request:y,response:A}]}function Ch(t,e,n,o){return new ne(DS(t,e,n,o))}async function DS(t,e,n,o){var i,r,a;let c={id:e,api_version:n},d=null,f={api_version:K("api_version",(i=c.api_version)!==null&&i!==void 0?i:t._options.api_version,{explode:!1,charEncoding:"percent"}),id:K("id",c.id,{explode:!1,charEncoding:"percent"})},p=se("/{api_version}/webhooks/{id}")(f),h=new Headers(le({Accept:"application/json"})),g=await de(t._options.security),_=ce(g),m={options:t._options,base_url:(a=(r=o?.server_url)!==null&&r!==void 0?r:t._baseURL)!==null&&a!==void 0?a:"",operation_id:"DeleteWebhook",o_auth2_scopes:null,resolved_security:_,security_source:t._options.security,retry_config:o?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:o?.retry_codes||["408","409","429","5XX"]},v=t._createRequest(m,{security:_,method:"DELETE",baseURL:o?.server_url,path:p,headers:h,body:d,userAgent:t._options.user_agent,timeout_ms:o?.timeout_ms||t._options.timeout_ms||-1},o);if(!v.ok)return[v,{status:"invalid"}];let y=v.value,E=await t._do(y,{context:m,isErrorStatusCode:w=>ie({status:w},["4XX","5XX"]),retryConfig:m.retry_config,retryCodes:m.retry_codes});if(!E.ok)return[E,{status:"request-error",request:y}];let A=E.value,[C]=await ue(Y("4XX"),Y("5XX"),he("default"))(A,y);return C.ok?[C,{status:"complete",request:y,response:A}]:[C,{status:"complete",request:y,response:A}]}function Ih(t,e,n,o){return new ne(MS(t,e,n,o))}async function MS(t,e,n,o){var i,r,a;let c={id:e,api_version:n},d=null,f={api_version:K("api_version",(i=c.api_version)!==null&&i!==void 0?i:t._options.api_version,{explode:!1,charEncoding:"percent"}),id:K("id",c.id,{explode:!1,charEncoding:"percent"})},p=se("/{api_version}/webhooks/{id}")(f),h=new Headers(le({Accept:"application/json"})),g=await de(t._options.security),_=ce(g),m={options:t._options,base_url:(a=(r=o?.server_url)!==null&&r!==void 0?r:t._baseURL)!==null&&a!==void 0?a:"",operation_id:"GetWebhook",o_auth2_scopes:null,resolved_security:_,security_source:t._options.security,retry_config:o?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:o?.retry_codes||["408","409","429","5XX"]},v=t._createRequest(m,{security:_,method:"GET",baseURL:o?.server_url,path:p,headers:h,body:d,userAgent:t._options.user_agent,timeout_ms:o?.timeout_ms||t._options.timeout_ms||-1},o);if(!v.ok)return[v,{status:"invalid"}];let y=v.value,E=await t._do(y,{context:m,isErrorStatusCode:w=>ie({status:w},["4XX","5XX"]),retryConfig:m.retry_config,retryCodes:m.retry_codes});if(!E.ok)return[E,{status:"request-error",request:y}];let A=E.value,[C]=await ue(Y("4XX"),Y("5XX"),he("default"))(A,y);return C.ok?[C,{status:"complete",request:y,response:A}]:[C,{status:"complete",request:y,response:A}]}function Sh(t,e,n,o,i){return new ne(US(t,e,n,o,i))}async function US(t,e,n,o,i){var r,a,u;let d={api_version:e,page_size:n,page_token:o},f=null,p={api_version:K("api_version",(r=d?.api_version)!==null&&r!==void 0?r:t._options.api_version,{explode:!1,charEncoding:"percent"})},h=se("/{api_version}/webhooks")(p),g=it({page_size:d?.page_size,page_token:d?.page_token}),_=new Headers(le({Accept:"application/json"})),m=await de(t._options.security),v=ce(m),y={options:t._options,base_url:(u=(a=i?.server_url)!==null&&a!==void 0?a:t._baseURL)!==null&&u!==void 0?u:"",operation_id:"ListWebhooks",o_auth2_scopes:null,resolved_security:v,security_source:t._options.security,retry_config:i?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:i?.retry_codes||["408","409","429","5XX"]},E=t._createRequest(y,{security:v,method:"GET",baseURL:i?.server_url,path:h,headers:_,query:g,body:f,userAgent:t._options.user_agent,timeout_ms:i?.timeout_ms||t._options.timeout_ms||-1},i);if(!E.ok)return[E,{status:"invalid"}];let A=E.value,C=await t._do(A,{context:y,isErrorStatusCode:q=>ie({status:q},["4XX","5XX"]),retryConfig:y.retry_config,retryCodes:y.retry_codes});if(!C.ok)return[C,{status:"request-error",request:A}];let w=C.value,[N]=await ue(Y("4XX"),Y("5XX"),he("default"))(w,A);return N.ok?[N,{status:"complete",request:A,response:w}]:[N,{status:"complete",request:A,response:w}]}function wh(t,e,n,o,i){return new ne(GS(t,e,n,o,i))}async function GS(t,e,n,o,i){var r,a,u;let d={id:e,api_version:n,body:o},f=ot("body",d.body,{explode:!0}),p={api_version:K("api_version",(r=d.api_version)!==null&&r!==void 0?r:t._options.api_version,{explode:!1,charEncoding:"percent"}),id:K("id",d.id,{explode:!1,charEncoding:"percent"})},h=se("/{api_version}/webhooks/{id}:ping")(p),g=new Headers(le({"Content-Type":"application/json",Accept:"application/json"})),_=await de(t._options.security),m=ce(_),v={options:t._options,base_url:(u=(a=i?.server_url)!==null&&a!==void 0?a:t._baseURL)!==null&&u!==void 0?u:"",operation_id:"PingWebhook",o_auth2_scopes:null,resolved_security:m,security_source:t._options.security,retry_config:i?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:i?.retry_codes||["408","409","429","5XX"]},y=t._createRequest(v,{security:m,method:"POST",baseURL:i?.server_url,path:h,headers:g,body:f,userAgent:t._options.user_agent,timeout_ms:i?.timeout_ms||t._options.timeout_ms||-1},i);if(!y.ok)return[y,{status:"invalid"}];let E=y.value,A=await t._do(E,{context:v,isErrorStatusCode:N=>ie({status:N},["4XX","5XX"]),retryConfig:v.retry_config,retryCodes:v.retry_codes});if(!A.ok)return[A,{status:"request-error",request:E}];let C=A.value,[w]=await ue(Y("4XX"),Y("5XX"),he("default"))(C,E);return w.ok?[w,{status:"complete",request:E,response:C}]:[w,{status:"complete",request:E,response:C}]}function Rh(t,e,n,o,i){return new ne(bS(t,e,n,o,i))}async function bS(t,e,n,o,i){var r,a,u;let d={id:e,body:n,api_version:o},f=ot("body",d.body,{explode:!0}),p={api_version:K("api_version",(r=d.api_version)!==null&&r!==void 0?r:t._options.api_version,{explode:!1,charEncoding:"percent"}),id:K("id",d.id,{explode:!1,charEncoding:"percent"})},h=se("/{api_version}/webhooks/{id}:rotateSigningSecret")(p),g=new Headers(le({"Content-Type":"application/json",Accept:"application/json"})),_=await de(t._options.security),m=ce(_),v={options:t._options,base_url:(u=(a=i?.server_url)!==null&&a!==void 0?a:t._baseURL)!==null&&u!==void 0?u:"",operation_id:"RotateSigningSecret",o_auth2_scopes:null,resolved_security:m,security_source:t._options.security,retry_config:i?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:i?.retry_codes||["408","409","429","5XX"]},y=t._createRequest(v,{security:m,method:"POST",baseURL:i?.server_url,path:h,headers:g,body:f,userAgent:t._options.user_agent,timeout_ms:i?.timeout_ms||t._options.timeout_ms||-1},i);if(!y.ok)return[y,{status:"invalid"}];let E=y.value,A=await t._do(E,{context:v,isErrorStatusCode:N=>ie({status:N},["4XX","5XX"]),retryConfig:v.retry_config,retryCodes:v.retry_codes});if(!A.ok)return[A,{status:"request-error",request:E}];let C=A.value,[w]=await ue(Y("4XX"),Y("5XX"),he("default"))(C,E);return w.ok?[w,{status:"complete",request:E,response:C}]:[w,{status:"complete",request:E,response:C}]}function Ph(t,e,n,o,i,r){return new ne(LS(t,e,n,o,i,r))}async function LS(t,e,n,o,i,r){var a,u,c;let f={id:e,body:n,api_version:o,update_mask:i},p=ot("body",f.body,{explode:!0}),h={api_version:K("api_version",(a=f.api_version)!==null&&a!==void 0?a:t._options.api_version,{explode:!1,charEncoding:"percent"}),id:K("id",f.id,{explode:!1,charEncoding:"percent"})},g=se("/{api_version}/webhooks/{id}")(h),_=it({update_mask:f.update_mask}),m=new Headers(le({"Content-Type":"application/json",Accept:"application/json"})),v=await de(t._options.security),y=ce(v),E={options:t._options,base_url:(c=(u=r?.server_url)!==null&&u!==void 0?u:t._baseURL)!==null&&c!==void 0?c:"",operation_id:"UpdateWebhook",o_auth2_scopes:null,resolved_security:y,security_source:t._options.security,retry_config:r?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:r?.retry_codes||["408","409","429","5XX"]},A=t._createRequest(E,{security:y,method:"PATCH",baseURL:r?.server_url,path:g,headers:m,query:_,body:p,userAgent:t._options.user_agent,timeout_ms:r?.timeout_ms||t._options.timeout_ms||-1},r);if(!A.ok)return[A,{status:"invalid"}];let C=A.value,w=await t._do(C,{context:E,isErrorStatusCode:V=>ie({status:V},["4XX","5XX"]),retryConfig:E.retry_config,retryCodes:E.retry_codes});if(!w.ok)return[w,{status:"request-error",request:C}];let N=w.value,[q]=await ue(Y("4XX"),Y("5XX"),he("default"))(N,C);return q.ok?[q,{status:"complete",request:C,response:N}]:[q,{status:"complete",request:C,response:N}]}var Wa=class extends nt{list(e,n){return ae(Sh(this,e?.api_version,e?.page_size,e?.page_token,n))}create(e,n){let{api_version:o}=e,i=Ie(e,["api_version"]);return ae(Ah(this,i,o,n))}delete(e,n,o){return ae(Ch(this,e,n?.api_version,o))}get(e,n,o){return ae(Ih(this,e,n?.api_version,o))}update(e,n,o){let{api_version:i,update_mask:r}=n,a=Ie(n,["api_version","update_mask"]);return ae(Ph(this,e,a,i,r,o))}ping(e,n,o,i){return ae(wh(this,e,n,o,i))}rotateSigningSecret(e,n,o,i){return ae(Rh(this,e,n,o,i))}};var qS=class extends nt{get environments(){var e;return(e=this._environments)!==null&&e!==void 0?e:this._environments=new La(this._options)}get agents(){var e;return(e=this._agents)!==null&&e!==void 0?e:this._agents=new Ma(this._options)}get credentials(){var e;return(e=this._credentials)!==null&&e!==void 0?e:this._credentials=new Ua(this._options)}get interactions(){var e;return(e=this._interactions)!==null&&e!==void 0?e:this._interactions=new Ja(this._options)}get triggers(){var e;return(e=this._triggers)!==null&&e!==void 0?e:this._triggers=new Ka(this._options)}get voices(){var e;return(e=this._voices)!==null&&e!==void 0?e:this._voices=new Ya(this._options)}get webhooks(){var e;return(e=this._webhooks)!==null&&e!==void 0?e:this._webhooks=new Wa(this._options)}};var OS=new Set(["lyria-3-pro-preview","lyria-3-clip-preview"]);function FS(t){let e=t.getBaseUrl();if(!e)throw new Error("Base URL must be set.");return e.replace(/\/+$/,"")}function HS(t){let e=VS(t.getApiVersion()),n=t.getProject(),o=t.getLocation();return t.isVertexAI()&&e&&n&&o?`${e}/projects/${encodeURIComponent(n)}/locations/${encodeURIComponent(o)}`:e}function Fe(t,e={}){var n,o,i,r,a,u,c,d,f,p;let{timeout:h}=e,g=Ie(e,["timeout"]),_=g.http_client||(n=t.getFetch)===null||n===void 0?void 0:n.call(t),m=(o=g.http_client)!==null&&o!==void 0?o:_?new yi({fetcher:_}):void 0,v=(r=(i=g.timeout_ms)!==null&&i!==void 0?i:h)!==null&&r!==void 0?r:(a=t.getTimeout)===null||a===void 0?void 0:a.call(t);return new qS(Object.assign(Object.assign({},g),{http_client:m,api_version:(u=g.api_version)!==null&&u!==void 0?u:HS(t),security:(c=g.security)!==null&&c!==void 0?c:new Ea({defaultHeaders:Object.assign(Object.assign({},(d=t.getDefaultHeaders)===null||d===void 0?void 0:d.call(t)),(f=t.getHeaders)===null||f===void 0?void 0:f.call(t)),getAuthHeaders:E=>t.getAuthHeaders(E)}),server_url:(p=g.server_url)!==null&&p!==void 0?p:FS(t),timeout_ms:v}))}var za=class{constructor(e,n){this.parentClient=e}async create(e,n){var o;let{api_version:i,automatic_continuation:r}=e,a=Ie(e,["api_version","automatic_continuation"]),u=O0(a,r),c=new Kn((o=n?.timeout_ms)!==null&&o!==void 0?o:n?.timeout,{enabled:u.enableContinuation}),d=()=>{if(!c.bounded)return n;let _=n??{},{timeout:m}=_,v=Ie(_,["timeout"]);return Object.assign(Object.assign({},v),{timeout_ms:c.hopTimeoutMs()})},f=this.getClient(i);if(u.stream){let _=async(v,y)=>{let E=await ks(()=>f.interactions.create(Object.assign(Object.assign({},mf(u,v,y)),{stream:!0,api_version:i}),oe(d(),!0)));return xf(E)},m=await _();return u.enableContinuation?Df(X0(m,_,{initialContinuationToken:u.callerToken,isConnectionError:v=>v instanceof Vt&&!(v instanceof In),isFatalError:v=>v instanceof In,wrapIterationError:BS,deadline:c,store:u.body.store!==!1})):u.callerToken?m:Df(H0(m))}let p=async(_,m)=>pe(uh(f,mf(u,_,m),i,oe(d()))),h=await p();if(u.enableContinuation)return await W0(h,p,{initialContinuationToken:u.callerToken,normalizeInteraction:kh,finalizeInteraction:Nh,deadline:c,store:u.body.store!==!1});let g=Ns(h);return u.callerToken||F0(g),g}async get(e,n={},o){let{api_version:i,stream:r=!1,last_event_id:a,include_input:u}=n??{};if(r===!0){let d=await ks(()=>this.getClient(i).interactions.get(e,{stream:r,last_event_id:a,include_input:u,api_version:i},oe(o,!0)));return xf(d)}let c=await pe(ch(this.getClient(i),e,i,u,a,r,oe(o)));return Ns(c)}async delete(e,n={},o){return ks(()=>this.getClient(n?.api_version).interactions.delete(e,{api_version:n?.api_version},oe(o)))}async cancel(e,n={},o){return Ns(await pe(lh(this.getClient(n?.api_version),e,n?.api_version,oe(o))))}getClient(e){var n;return e?Fe(this.parentClient,{api_version:e}):((n=this.sdk)!==null&&n!==void 0||(this.sdk=Fe(this.parentClient)),this.sdk)}},Qa=class{constructor(e){this.parentClient=e}async create(e={},n){let o=e??{},{api_version:i}=o,r=Ie(o,["api_version"]);return pe(Kp(this.getClient(i),r,i,oe(n)))}async list(e={},n){let{api_version:o,page_size:i,page_token:r,parent:a}=e??{};return pe(zp(this.getClient(o),o,i,r,a,oe(n)))}async get(e,n={},o){return pe(Wp(this.getClient(n?.api_version),e,n?.api_version,oe(o)))}async delete(e,n={},o){return pe(Yp(this.getClient(n?.api_version),e,n?.api_version,oe(o)))}getClient(e){var n;return e?Fe(this.parentClient,{api_version:e}):((n=this.sdk)!==null&&n!==void 0||(this.sdk=Fe(this.parentClient)),this.sdk)}},Za=class{constructor(e){this.parentClient=e}async create(e,n){let{api_version:o}=e,i=Ie(e,["api_version"]);return pe(Ah(this.getClient(),i,o,oe(n)))}async list(e={},n){let{api_version:o,page_size:i,page_token:r}=e??{};return pe(Sh(this.getClient(),o,i,r,oe(n)))}async get(e,n={},o){return pe(Ih(this.getClient(),e,n?.api_version,oe(o)))}async update(e,n={},o){let i=n??{},{api_version:r,update_mask:a}=i,u=Ie(i,["api_version","update_mask"]);return pe(Ph(this.getClient(),e,u,r,a,oe(o)))}async delete(e,n={},o){return pe(Ch(this.getClient(),e,n?.api_version,oe(o)))}async rotateSigningSecret(e,n={},o){let i=n??{},{api_version:r}=i,a=Ie(i,["api_version"]);return pe(Rh(this.getClient(),e,a,r,oe(o)))}async ping(e,n=void 0,o){let{api_version:i,body:r}=n??{};return pe(wh(this.getClient(),e,i,r,oe(o)))}getClient(){var e;return(e=this.sdk)!==null&&e!==void 0||(this.sdk=Fe(this.parentClient)),this.sdk}},ja=class{constructor(e){this.parentClient=e}async create(e,n){let{api_version:o}=e,i=Ie(e,["api_version"]);return pe(dh(this.getClient(o),i,o,oe(n)))}async list(e={},n){let{api_version:o,filter:i,page_size:r,page_token:a}=e??{};return pe(mh(this.getClient(o),o,i,r,a,oe(n)))}async get(e,n={},o){return pe(ph(this.getClient(n?.api_version),e,n?.api_version,oe(o)))}async update(e,n,o){let{api_version:i}=n,r=Ie(n,["api_version"]);return pe(_h(this.getClient(i),e,r,i,oe(o)))}async delete(e,n={},o){return pe(fh(this.getClient(n?.api_version),e,n?.api_version,oe(o)))}async run(e,n={},o){return pe(gh(this.getClient(n?.api_version),e,n?.api_version,oe(o)))}async listExecutions(e,n={},o){let{api_version:i,page_size:r,page_token:a}=n??{};return pe(hh(this.getClient(i),e,i,r,a,oe(o)))}getClient(e){var n;return e?Fe(this.parentClient,{api_version:e}):((n=this.sdk)!==null&&n!==void 0||(this.sdk=Fe(this.parentClient)),this.sdk)}};function VS(t){return t.replace(/^\/+|\/+$/g,"")}function oe(t,e=!1){var n,o,i,r;if(!t&&!e)return;let a=t??{},{timeout:u,maxRetries:c,defaultBaseURL:d,query:f,body:p,fetchOptions:h}=a,g=Ie(a,["timeout","maxRetries","defaultBaseURL","query","body","fetchOptions"]),_=Object.assign({},g);Ti(f)?_.extra_query=f:Nf("query",f),Ti(p)?_.extra_body=p:Nf("body",p);let m=(n=g.fetch_options)!==null&&n!==void 0?n:h;m&&(_.fetch_options=m);let v=(o=g.server_url)!==null&&o!==void 0?o:d;v&&(_.server_url=v);let y=(i=g.timeout_ms)!==null&&i!==void 0?i:u;if(y!==void 0&&(_.timeout_ms=y),c!==void 0&&(_.retries={strategy:"attempt-count-backoff",retryConnectionErrors:!0,maxRetries:c}),e){let E=new Headers((r=_.headers)!==null&&r!==void 0?r:m?.headers);E.set("Accept","text/event-stream"),_.headers=E}return _}function Nf(t,e){e!=null&&console.warn(`GoogleGenAI.interactions: request option ${t} is not supported by the Google GenAI interactions bridge and will be ignored.`)}async function pe(t){let[e,n]=await t.$inspect();if(!e.ok)throw bt(e.error);return $S(e.value,n)}async function ks(t){try{return await t()}catch(e){throw bt(e)}}function xf(t){let e=t;return new Proxy(t,{get(n,o){if(o!==Symbol.asyncIterator){let i=Reflect.get(n,o,n);return typeof i=="function"?i.bind(n):i}return function(){let r=e[Symbol.asyncIterator]();return{async next(...a){try{return await r.next(...a)}catch(u){throw bt(u)}},async return(a){if(!r.return)return{done:!0,value:a};try{return await r.return(a)}catch(u){throw bt(u)}},async throw(a){if(!r.throw)throw bt(a);try{return await r.throw(a)}catch(u){throw bt(u)}},[Symbol.asyncIterator](){return this}}}}})}function BS(t){let e=bt(t);if(e instanceof qe||e instanceof Cn)return e;if(e instanceof Error&&e.name==="AbortError")return new In({message:e.message});let n=e instanceof Error?e.message:String(e);return new Vt({message:n,cause:e})}function Df(t){let e=t[Symbol.asyncIterator](),n=new ReadableStream({async pull(o){let i=await e.next();i.done?o.close():o.enqueue(i.value)},async cancel(){var o;await((o=e.return)===null||o===void 0?void 0:o.call(e))}},{highWaterMark:0});return Object.setPrototypeOf(n,_i.prototype),n}function $S(t,e){return!Ti(t)||e.status!=="complete"?t:Object.assign(Object.assign({},t),{sdkHttpResponse:XS(e.response,t)})}function XS(t,e){let n={};for(let[o,i]of t.headers.entries())n[o]=i;return{headers:n,responseInternal:t,json:async()=>e}}function Ns(t){let e=kh(t);return e?Nh(e):t}function kh(t){if(Ti(t)){if(Array.isArray(t.steps))return t;if(JS(t)){let e=t.outputs;if(Array.isArray(e)){let{outputs:n}=t,o=Ie(t,["outputs"]);return Object.assign(Object.assign({},o),{steps:[{type:"model_output",content:e}]})}}return Object.assign(Object.assign({},t),{steps:[]})}}function JS(t){let e=t.model;return typeof e=="string"&&OS.has(e)}function Ti(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Nh(t){var e,n;let o=KS(t),i=(e=o.steps)!==null&&e!==void 0?e:[],r=[],a=!1;e:for(let p=i.length-1;p>=0;p--){let h=i[p];if(h.type==="user_input")break;if(h.type==="thought")continue;if(h.type!=="model_output"){if(a)break;continue}if(!h.content)continue;let g=h.content;for(let _=g.length-1;_>=0;_--){let m=g[_];if(m.type==="text")a=!0,r.push((n=m.text)!==null&&n!==void 0?n:"");else if(a)break e}}let u,c,d;for(let p=i.length-1;p>=0;p--){let h=i[p];if(h.type==="user_input")break;if(h.type==="model_output"&&h.content)for(let g=h.content.length-1;g>=0;g--){let _=h.content[g];_.type==="image"&&!u&&(u=_),_.type==="audio"&&!c&&(c=_),_.type==="video"&&!d&&(d=_)}}let f=r.reverse().join("");return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},o),f&&{output_text:f}),u?{output_image:u}:{}),c?{output_audio:c}:{}),d?{output_video:d}:{})}function KS(t){return Object.assign(Object.assign({},t),{created:Mf(t.created),updated:Mf(t.updated)})}function Mf(t){return t instanceof Date?t.toISOString():t}function YS(t){let e=t.slice(t.lastIndexOf(".")+1).toLowerCase();return{txt:"text/plain",json:"application/json",js:"text/javascript",mjs:"text/javascript",ts:"text/plain",py:"text/x-python",html:"text/html",htm:"text/html",css:"text/css",csv:"text/csv",xml:"application/xml",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",pdf:"application/pdf",zip:"application/zip",tar:"application/x-tar",gz:"application/gzip"}[e]}var el=class{constructor(e,n){this.resolveClient=e,this.parentClient=n}async list(e,n){return pe(sh(this.resolveClient(e.api_version),e.environment,e.path,e.api_version,e.page_size,e.page_token,e.recursive,oe(n)))}async download(e,n){var o,i;let r=e.environment;if(!r)throw new Error("environment is required.");let a=r.startsWith("environments/")?r:`environments/${r}`,u=e.path.replace(/^\/+/,""),c=`${a}/files/${u}`,d=this.parentClient;if(!d||typeof d.request!="function")throw new Error("apiClient is required to download files.");let f=await d.request({path:c,httpMethod:"GET",queryParams:{alt:"media"},httpOptions:Object.assign(Object.assign({},n?.httpOptions),{apiVersion:(o=e.api_version)!==null&&o!==void 0?o:(i=n?.httpOptions)===null||i===void 0?void 0:i.apiVersion})});if(f&&f.responseInternal&&typeof f.responseInternal.arrayBuffer=="function"){let p=await f.responseInternal.arrayBuffer();return new Uint8Array(p)}throw new Error("Unexpected response type from download")}async upload(e,n){var o,i,r,a,u,c,d,f;let p=e.environment;if(!p)throw new Error("environment is required.");p.startsWith("environments/")||`${p}`;let h=e.path.replace(/^\/+/,""),g=this.parentClient;if(!g||typeof g.request!="function")throw new Error("apiClient is required to upload files.");let _,m=0,v=e.mime_type;if(typeof e.file=="string"){let O;try{let H=globalThis.require;H&&(O=H("fs").readFileSync(e.file))}catch{}if(!O&&typeof globalThis.process<"u")try{let H=(i=(o=globalThis.process.mainModule)===null||o===void 0?void 0:o.require)!==null&&i!==void 0?i:globalThis.require;H&&(O=H("fs").readFileSync(e.file))}catch{}if(O)_=new Uint8Array(O.buffer,O.byteOffset,O.byteLength),m=_.byteLength;else throw new Error(`Unable to read file from path "${e.file}". File path string inputs are only supported in Node.js environments.`);v||(v=YS(e.file))}else if(typeof Blob<"u"&&e.file instanceof Blob)_=e.file,m=e.file.size,!v&&e.file.type&&(v=e.file.type);else if(e.file instanceof Uint8Array||e.file instanceof ArrayBuffer)_=e.file instanceof ArrayBuffer?new Uint8Array(e.file):e.file,m=_.byteLength;else if(typeof globalThis.Buffer<"u"&&typeof globalThis.Buffer.isBuffer=="function"&&globalThis.Buffer.isBuffer(e.file)){let O=e.file;_=new Uint8Array(O.buffer,O.byteOffset,O.byteLength),m=_.byteLength}else throw new Error("Unsupported file type for upload.");v||(v="application/octet-stream");let y=p.startsWith("environments/")?p.replace(/^environments\//,""):p,[E,A]=await ah(this.resolveClient(e.api_version),y,h,"start",m,v,"resumable",e.api_version,e.extract,e.overwrite,oe(n)).$inspect();if(!E.ok)throw bt(E.error);let C=A.status==="complete"?(u=(a=(r=A.response)===null||r===void 0?void 0:r.headers)===null||a===void 0?void 0:a.get("x-goog-upload-url"))!==null&&u!==void 0?u:(d=(c=A.response)===null||c===void 0?void 0:c.headers)===null||d===void 0?void 0:d.get("X-Goog-Upload-URL"):void 0;if(!C)throw new Error("Failed to get upload URL from upload handshake response.");let w=8*1024*1024,N=0,q,V=_ instanceof Blob?_:new Blob([_]);for(;N<m||m===0&&N===0;){let O=Math.min(N+w,m),H=V.slice(N,O),$=O>=m,j=$?"upload, finalize":"upload";if(q=await g.request({path:"",body:H,httpMethod:"POST",httpOptions:Object.assign(Object.assign({},n?.httpOptions),{apiVersion:"",baseUrl:C,headers:Object.assign(Object.assign({},((f=n?.httpOptions)===null||f===void 0?void 0:f.headers)||{}),{"X-Goog-Upload-Command":j,"X-Goog-Upload-Offset":`${N}`})})}),N=O,$)break}let M;if(q&&typeof q.json=="function"?M=await q.json():q&&q.responseInternal&&typeof q.responseInternal.json=="function"&&(M=await q.responseInternal.json()),M&&typeof M=="object"){if(Array.isArray(M.files))return M;if(M.name||M.path)return{files:[M]};if(M.file&&typeof M.file=="object")return{files:[M.file]}}return M}},tl=class{constructor(e){this.parentClient=e,this.files=new el(n=>this.getClient(n),this.parentClient)}async create(e,n){let{api_version:o}=e,i=Ie(e,["api_version"]);return pe(nh(this.getClient(o),i,o,oe(n)))}async list(e={},n){let{api_version:o,page_size:i,page_token:r}=e??{};return pe(rh(this.getClient(o),o,i,r,oe(n)))}async get(e,n={},o){return pe(ih(this.getClient(n?.api_version),e,n?.api_version,oe(o)))}async delete(e,n={},o){return pe(oh(this.getClient(n?.api_version),e,n?.api_version,oe(o)))}getClient(e){var n;return e?Fe(this.parentClient,{api_version:e}):((n=this.sdk)!==null&&n!==void 0||(this.sdk=Fe(this.parentClient)),this.sdk)}},nl=class{constructor(e){this.parentClient=e}async create(e,n){let{api_version:o}=e,i=Ie(e,["api_version"]);return pe(Qp(this.getClient(o),i,o,oe(n)))}async list(e={},n){let{api_version:o,page_size:i,page_token:r}=e??{};return pe(eh(this.getClient(o),o,i,r,oe(n)))}async get(e,n={},o){return pe(jp(this.getClient(n?.api_version),e,n?.api_version,oe(o)))}async update(e,n,o){let{api_version:i,update_mask:r}=n,a=Ie(n,["api_version","update_mask"]);return pe(th(this.getClient(i),e,a,i,r,oe(o)))}async delete(e,n={},o){return pe(Zp(this.getClient(n?.api_version),e,n?.api_version,oe(o)))}getClient(e){var n;return e?Fe(this.parentClient,{api_version:e}):((n=this.sdk)!==null&&n!==void 0||(this.sdk=Fe(this.parentClient)),this.sdk)}},ol=class{constructor(e){this.parentClient=e}async create(e,n){let{api_version:o}=e,i=Ie(e,["api_version"]);return pe(yh(this.getClient(o),i,o,oe(n)))}async list(e={},n){let{api_version:o,accent:i,contexts:r,gender:a,language_code:u,page_size:c,page_token:d,persona:f,pitch:p,region_code:h,search:g,type:_}=e??{};return pe(Th(this.getClient(o),o,i,r,a,u,c,d,f,p,h,g,_,oe(n)))}async get(e,n={},o){return pe(Eh(this.getClient(n?.api_version),e,n?.api_version,oe(o)))}async delete(e,n={},o){return pe(vh(this.getClient(n?.api_version),e,n?.api_version,oe(o)))}getClient(e){var n;return e?Fe(this.parentClient,{api_version:e}):((n=this.sdk)!==null&&n!==void 0||(this.sdk=Fe(this.parentClient)),this.sdk)}};var Uf="x-goog-api-key",Vn="https://www.googleapis.com/auth/cloud-platform",il=class{constructor(e){if(e.apiKey!==void 0){this.apiKey=e.apiKey;return}let n=WS(e.googleAuthOptions);this.googleAuth=new qf.GoogleAuth(n)}async addAuthHeaders(e,n){if(this.apiKey!==void 0){if(this.apiKey.startsWith("auth_tokens/"))throw new Error("Ephemeral tokens are only supported by the live API.");this.addKeyHeader(e);return}return this.addGoogleAuthHeaders(e,n)}addKeyHeader(e){if(e.get(Uf)===null){if(this.apiKey===void 0)throw new Error("Trying to set API key header but apiKey is not set");e.append(Uf,this.apiKey)}}async addGoogleAuthHeaders(e,n){if(this.googleAuth===void 0)throw new Error("Trying to set google-auth headers but googleAuth is unset");let o=await this.googleAuth.getRequestHeaders(n);for(let[i,r]of o)e.get(i)===null&&e.append(i,r)}};function WS(t){let e;if(t){if(e=t,e.scopes){if(typeof e.scopes=="string"&&e.scopes!==Vn||Array.isArray(e.scopes)&&e.scopes.indexOf(Vn)<0)throw new Error(`Invalid auth scopes. Scopes must include: ${Vn}`)}else return e.scopes=[Vn],e;return e}else return e={scopes:[Vn]},e}var rl=class{async download(e,n){if(e.downloadPath){let o=await zS(e,n);if(o instanceof wt){let i=Ry(e.downloadPath);ky.fromWeb(o.responseInternal.body).pipe(i),await Ny(i)}else try{await Py(e.downloadPath,o,{encoding:"base64"})}catch(i){throw new Error(`Failed to write file to ${e.downloadPath}: ${i}`)}}}};async function zS(t,e){var n,o,i;let r=yl(t.file);if(r!==void 0)return await e.request({path:`files/${r}:download`,httpMethod:"GET",queryParams:{alt:"media"},httpOptions:(n=t.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=t.config)===null||o===void 0?void 0:o.abortSignal});if(Jf(t.file)){let a=(i=t.file.video)===null||i===void 0?void 0:i.videoBytes;if(typeof a=="string")return a;throw new Error("Failed to download generated video, Uri or videoBytes not found.")}else if(Kf(t.file)){let a=t.file.videoBytes;if(typeof a=="string")return a;throw new Error("Failed to download video, Uri or videoBytes not found.")}else throw new Error("Unsupported file type")}var Ai=class{create(e,n,o){return new sl(e,n,o)}},sl=class{constructor(e,n,o){this.url=e,this.headers=n,this.callbacks=o}connect(){this.ws=new Rl.default(this.url,{headers:this.headers}),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()}};function QS(t,e){let n={},o=s(t,["name"]);return o!=null&&l(n,["_url","name"],o),n}function ZS(t,e){let n={},o=s(t,["name"]);return o!=null&&l(n,["_url","name"],o),n}function jS(t,e){let n={},o=s(t,["sdkHttpResponse"]);return o!=null&&l(n,["sdkHttpResponse"],o),n}function ew(t,e){let n={},o=s(t,["sdkHttpResponse"]);return o!=null&&l(n,["sdkHttpResponse"],o),n}function al(t,e){let n={},o=s(t,["parts"]);if(o!=null){let r=o;Array.isArray(r)&&(r=r.map(a=>gw(a))),l(n,["parts"],r)}let i=s(t,["role"]);return i!=null&&l(n,["role"],i),n}function tw(t,e,n){let o={};if(s(t,["validationDataset"])!==void 0)throw new Error("validationDataset parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let i=s(t,["tunedModelDisplayName"]);if(e!==void 0&&i!=null&&l(e,["displayName"],i),s(t,["description"])!==void 0)throw new Error("description parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let r=s(t,["epochCount"]);e!==void 0&&r!=null&&l(e,["tuningTask","hyperparameters","epochCount"],r);let a=s(t,["learningRateMultiplier"]);if(a!=null&&l(o,["tuningTask","hyperparameters","learningRateMultiplier"],a),s(t,["exportLastCheckpointOnly"])!==void 0)throw new Error("exportLastCheckpointOnly parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["preTunedModelCheckpointId"])!==void 0)throw new Error("preTunedModelCheckpointId parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["adapterSize"])!==void 0)throw new Error("adapterSize parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["tuningMode"])!==void 0)throw new Error("tuningMode parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["customBaseModel"])!==void 0)throw new Error("customBaseModel parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let u=s(t,["batchSize"]);e!==void 0&&u!=null&&l(e,["tuningTask","hyperparameters","batchSize"],u);let c=s(t,["learningRate"]);if(e!==void 0&&c!=null&&l(e,["tuningTask","hyperparameters","learningRate"],c),s(t,["labels"])!==void 0)throw new Error("labels parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["beta"])!==void 0)throw new Error("beta parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["baseTeacherModel"])!==void 0)throw new Error("baseTeacherModel parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["tunedTeacherModelSource"])!==void 0)throw new Error("tunedTeacherModelSource parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["sftLossWeightMultiplier"])!==void 0)throw new Error("sftLossWeightMultiplier parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["outputUri"])!==void 0)throw new Error("outputUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["rewardConfig"])!==void 0)throw new Error("rewardConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["compositeRewardConfig"])!==void 0)throw new Error("compositeRewardConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["samplesPerPrompt"])!==void 0)throw new Error("samplesPerPrompt parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["evaluateInterval"])!==void 0)throw new Error("evaluateInterval parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["checkpointInterval"])!==void 0)throw new Error("checkpointInterval parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["maxOutputTokens"])!==void 0)throw new Error("maxOutputTokens parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["thinkingLevel"])!==void 0)throw new Error("thinkingLevel parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["validationDatasetUri"])!==void 0)throw new Error("validationDatasetUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["encryptionSpec"])!==void 0)throw new Error("encryptionSpec parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return o}function nw(t,e,n){let o={},i=s(n,["config","method"]);if(i===void 0&&(i="SUPERVISED_FINE_TUNING"),i==="SUPERVISED_FINE_TUNING"){let D=s(t,["validationDataset"]);e!==void 0&&D!=null&&l(e,["supervisedTuningSpec"],Yo(D))}else if(i==="PREFERENCE_TUNING"){let D=s(t,["validationDataset"]);e!==void 0&&D!=null&&l(e,["preferenceOptimizationSpec"],Yo(D))}else if(i==="DISTILLATION"){let D=s(t,["validationDataset"]);e!==void 0&&D!=null&&l(e,["distillationSpec"],Yo(D))}else if(i==="REINFORCEMENT_TUNING"){let D=s(t,["validationDataset"]);e!==void 0&&D!=null&&l(e,["reinforcementTuningSpec"],Yo(D))}let r=s(t,["tunedModelDisplayName"]);e!==void 0&&r!=null&&l(e,["tunedModelDisplayName"],r);let a=s(t,["description"]);e!==void 0&&a!=null&&l(e,["description"],a);let u=s(n,["config","method"]);if(u===void 0&&(u="SUPERVISED_FINE_TUNING"),u==="SUPERVISED_FINE_TUNING"){let D=s(t,["epochCount"]);e!==void 0&&D!=null&&l(e,["supervisedTuningSpec","hyperParameters","epochCount"],D)}else if(u==="PREFERENCE_TUNING"){let D=s(t,["epochCount"]);e!==void 0&&D!=null&&l(e,["preferenceOptimizationSpec","hyperParameters","epochCount"],D)}else if(u==="DISTILLATION"){let D=s(t,["epochCount"]);e!==void 0&&D!=null&&l(e,["distillationSpec","hyperParameters","epochCount"],D)}else if(u==="REINFORCEMENT_TUNING"){let D=s(t,["epochCount"]);e!==void 0&&D!=null&&l(e,["reinforcementTuningSpec","hyperParameters","epochCount"],D)}let c=s(n,["config","method"]);if(c===void 0&&(c="SUPERVISED_FINE_TUNING"),c==="SUPERVISED_FINE_TUNING"){let D=s(t,["learningRateMultiplier"]);e!==void 0&&D!=null&&l(e,["supervisedTuningSpec","hyperParameters","learningRateMultiplier"],D)}else if(c==="PREFERENCE_TUNING"){let D=s(t,["learningRateMultiplier"]);e!==void 0&&D!=null&&l(e,["preferenceOptimizationSpec","hyperParameters","learningRateMultiplier"],D)}else if(c==="DISTILLATION"){let D=s(t,["learningRateMultiplier"]);e!==void 0&&D!=null&&l(e,["distillationSpec","hyperParameters","learningRateMultiplier"],D)}else if(c==="REINFORCEMENT_TUNING"){let D=s(t,["learningRateMultiplier"]);e!==void 0&&D!=null&&l(e,["reinforcementTuningSpec","hyperParameters","learningRateMultiplier"],D)}let d=s(n,["config","method"]);if(d===void 0&&(d="SUPERVISED_FINE_TUNING"),d==="SUPERVISED_FINE_TUNING"){let D=s(t,["exportLastCheckpointOnly"]);e!==void 0&&D!=null&&l(e,["supervisedTuningSpec","exportLastCheckpointOnly"],D)}else if(d==="PREFERENCE_TUNING"){let D=s(t,["exportLastCheckpointOnly"]);e!==void 0&&D!=null&&l(e,["preferenceOptimizationSpec","exportLastCheckpointOnly"],D)}else if(d==="DISTILLATION"){let D=s(t,["exportLastCheckpointOnly"]);e!==void 0&&D!=null&&l(e,["distillationSpec","exportLastCheckpointOnly"],D)}let f=s(n,["config","method"]);if(f===void 0&&(f="SUPERVISED_FINE_TUNING"),f==="SUPERVISED_FINE_TUNING"){let D=s(t,["adapterSize"]);e!==void 0&&D!=null&&l(e,["supervisedTuningSpec","hyperParameters","adapterSize"],D)}else if(f==="PREFERENCE_TUNING"){let D=s(t,["adapterSize"]);e!==void 0&&D!=null&&l(e,["preferenceOptimizationSpec","hyperParameters","adapterSize"],D)}else if(f==="DISTILLATION"){let D=s(t,["adapterSize"]);e!==void 0&&D!=null&&l(e,["distillationSpec","hyperParameters","adapterSize"],D)}else if(f==="REINFORCEMENT_TUNING"){let D=s(t,["adapterSize"]);e!==void 0&&D!=null&&l(e,["reinforcementTuningSpec","hyperParameters","adapterSize"],D)}let p=s(n,["config","method"]);if(p===void 0&&(p="SUPERVISED_FINE_TUNING"),p==="SUPERVISED_FINE_TUNING"){let D=s(t,["tuningMode"]);e!==void 0&&D!=null&&l(e,["supervisedTuningSpec","tuningMode"],D)}else if(p==="DISTILLATION"){let D=s(t,["tuningMode"]);e!==void 0&&D!=null&&l(e,["distillationSpec","tuningMode"],D)}let h=s(t,["customBaseModel"]);e!==void 0&&h!=null&&l(e,["customBaseModel"],h);let g=s(n,["config","method"]);if(g===void 0&&(g="SUPERVISED_FINE_TUNING"),g==="SUPERVISED_FINE_TUNING"){let D=s(t,["batchSize"]);e!==void 0&&D!=null&&l(e,["supervisedTuningSpec","hyperParameters","batchSize"],D)}else if(g==="DISTILLATION"){let D=s(t,["batchSize"]);e!==void 0&&D!=null&&l(e,["distillationSpec","hyperParameters","batchSize"],D)}else if(g==="REINFORCEMENT_TUNING"){let D=s(t,["batchSize"]);e!==void 0&&D!=null&&l(e,["reinforcementTuningSpec","hyperParameters","batchSize"],D)}let _=s(n,["config","method"]);if(_===void 0&&(_="SUPERVISED_FINE_TUNING"),_==="SUPERVISED_FINE_TUNING"){let D=s(t,["learningRate"]);e!==void 0&&D!=null&&l(e,["supervisedTuningSpec","hyperParameters","learningRate"],D)}else if(_==="DISTILLATION"){let D=s(t,["learningRate"]);e!==void 0&&D!=null&&l(e,["distillationSpec","hyperParameters","learningRate"],D)}let m=s(t,["labels"]);e!==void 0&&m!=null&&l(e,["labels"],m);let v=s(t,["beta"]);e!==void 0&&v!=null&&l(e,["preferenceOptimizationSpec","hyperParameters","beta"],v);let y=s(t,["baseTeacherModel"]);e!==void 0&&y!=null&&l(e,["distillationSpec","baseTeacherModel"],y);let E=s(t,["tunedTeacherModelSource"]);e!==void 0&&E!=null&&l(e,["distillationSpec","tunedTeacherModelSource"],E);let A=s(t,["sftLossWeightMultiplier"]);e!==void 0&&A!=null&&l(e,["distillationSpec","hyperParameters","sftLossWeightMultiplier"],A);let C=s(t,["outputUri"]);e!==void 0&&C!=null&&l(e,["outputUri"],C);let w=s(t,["rewardConfig"]);e!==void 0&&w!=null&&l(e,["reinforcementTuningSpec","singleRewardConfig"],w);let N=s(t,["compositeRewardConfig"]);e!==void 0&&N!=null&&l(e,["reinforcementTuningSpec","compositeRewardConfig"],N);let q=s(t,["samplesPerPrompt"]);e!==void 0&&q!=null&&l(e,["reinforcementTuningSpec","hyperParameters","samplesPerPrompt"],q);let V=s(t,["evaluateInterval"]);e!==void 0&&V!=null&&l(e,["reinforcementTuningSpec","hyperParameters","evaluateInterval"],V);let M=s(t,["checkpointInterval"]);e!==void 0&&M!=null&&l(e,["reinforcementTuningSpec","hyperParameters","checkpointInterval"],M);let O=s(t,["maxOutputTokens"]);e!==void 0&&O!=null&&l(e,["reinforcementTuningSpec","hyperParameters","maxOutputTokens"],O);let H=s(t,["thinkingLevel"]);e!==void 0&&H!=null&&l(e,["reinforcementTuningSpec","hyperParameters","thinkingLevel"],H);let $=s(t,["validationDatasetUri"]);e!==void 0&&$!=null&&l(e,["reinforcementTuningSpec","validationDatasetUri"],$);let j=s(t,["encryptionSpec"]);return e!==void 0&&j!=null&&l(e,["encryptionSpec"],j),o}function ow(t,e){let n={},o=s(t,["baseModel"]);o!=null&&l(n,["baseModel"],o);let i=s(t,["preTunedModel"]);i!=null&&l(n,["preTunedModel"],i);let r=s(t,["trainingDataset"]);r!=null&&Ew(r);let a=s(t,["config"]);return a!=null&&tw(a,n),n}function iw(t,e){let n={},o=s(t,["baseModel"]);o!=null&&l(n,["baseModel"],o);let i=s(t,["preTunedModel"]);i!=null&&l(n,["preTunedModel"],i);let r=s(t,["trainingDataset"]);r!=null&&Tw(r,n,e);let a=s(t,["config"]);return a!=null&&nw(a,n,e),n}function xh(t,e){let n={},o=s(t,["epochCount"]);o!=null&&l(n,["epochCount"],o);let i=s(t,["learningRateMultiplier"]);i!=null&&l(n,["learningRateMultiplier"],i);let r=s(t,["adapterSize"]);r!=null&&l(n,["adapterSize"],r);let a=s(t,["batchSize"]);a!=null&&l(n,["batchSize"],a);let u=s(t,["learningRate"]);u!=null&&l(n,["learningRate"],u);let c=s(t,["generationConfig"]);return c!=null&&l(n,["generationConfig"],uw(c)),n}function rw(t,e){let n={},o=s(t,["promptDatasetUri"]);o!=null&&l(n,["promptDatasetUri"],o);let i=s(t,["validationDatasetUri"]);i!=null&&l(n,["validationDatasetUri"],i);let r=s(t,["baseTeacherModel"]);r!=null&&l(n,["baseTeacherModel"],r);let a=s(t,["tunedTeacherModelSource"]);a!=null&&l(n,["tunedTeacherModelSource"],a);let u=s(t,["hyperparameters"]);return u!=null&&l(n,["hyperparameters"],xh(u)),n}function sw(t,e){let n={},o=s(t,["baseTeacherModel"]);o!=null&&l(n,["baseTeacherModel"],o);let i=s(t,["hyperParameters"]);i!=null&&l(n,["hyperParameters"],xh(i));let r=s(t,["pipelineRootDirectory"]);r!=null&&l(n,["pipelineRootDirectory"],r);let a=s(t,["promptDatasetUri"]);a!=null&&l(n,["promptDatasetUri"],a);let u=s(t,["studentModel"]);u!=null&&l(n,["studentModel"],u);let c=s(t,["trainingDatasetUri"]);c!=null&&l(n,["trainingDatasetUri"],c);let d=s(t,["tunedTeacherModelSource"]);d!=null&&l(n,["tunedTeacherModelSource"],d);let f=s(t,["tuningMode"]);f!=null&&l(n,["tuningMode"],f);let p=s(t,["validationDatasetUri"]);return p!=null&&l(n,["validationDatasetUri"],p),n}function aw(t,e){let n={},o=s(t,["fileData"]);o!=null&&l(n,["fileData"],o);let i=s(t,["inlineData"]);if(i!=null&&l(n,["inlineData"],i),s(t,["mediaProcessing"])!==void 0)throw new Error("mediaProcessing parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return n}function lw(t,e){let n={},o=s(t,["id"]);o!=null&&l(n,["id"],o);let i=s(t,["name"]);i!=null&&l(n,["name"],i);let r=s(t,["parts"]);if(r!=null){let c=r;Array.isArray(c)&&(c=c.map(d=>aw(d))),l(n,["parts"],c)}let a=s(t,["response"]);a!=null&&l(n,["response"],a);let u=s(t,["scheduling"]);if(u!=null&&l(n,["scheduling"],u),s(t,["willContinue"])!==void 0)throw new Error("willContinue parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return n}function uw(t,e){let n={},o=s(t,["modelConfig"]);o!=null&&l(n,["modelSelectionConfig"],o);let i=s(t,["responseJsonSchema"]);i!=null&&l(n,["responseJsonSchema"],i);let r=s(t,["audioTranscriptionConfig"]);r!=null&&l(n,["audioTranscriptionConfig"],r);let a=s(t,["audioTimestamp"]);a!=null&&l(n,["audioTimestamp"],a);let u=s(t,["candidateCount"]);u!=null&&l(n,["candidateCount"],u);let c=s(t,["enableAffectiveDialog"]);c!=null&&l(n,["enableAffectiveDialog"],c);let d=s(t,["frequencyPenalty"]);d!=null&&l(n,["frequencyPenalty"],d);let f=s(t,["logprobs"]);f!=null&&l(n,["logprobs"],f);let p=s(t,["maxOutputTokens"]);p!=null&&l(n,["maxOutputTokens"],p);let h=s(t,["mediaResolution"]);h!=null&&l(n,["mediaResolution"],h);let g=s(t,["presencePenalty"]);g!=null&&l(n,["presencePenalty"],g);let _=s(t,["responseFormat"]);if(_!=null){let $=_;Array.isArray($)&&($=$.map(j=>j)),l(n,["responseFormat"],$)}let m=s(t,["responseLogprobs"]);m!=null&&l(n,["responseLogprobs"],m);let v=s(t,["responseMimeType"]);v!=null&&l(n,["responseMimeType"],v);let y=s(t,["responseModalities"]);y!=null&&l(n,["responseModalities"],y);let E=s(t,["responseSchema"]);E!=null&&l(n,["responseSchema"],E);let A=s(t,["routingConfig"]);A!=null&&l(n,["routingConfig"],A);let C=s(t,["seed"]);C!=null&&l(n,["seed"],C);let w=s(t,["speechConfig"]);w!=null&&l(n,["speechConfig"],w);let N=s(t,["stopSequences"]);N!=null&&l(n,["stopSequences"],N);let q=s(t,["temperature"]);q!=null&&l(n,["temperature"],q);let V=s(t,["thinkingConfig"]);V!=null&&l(n,["thinkingConfig"],V);let M=s(t,["topK"]);M!=null&&l(n,["topK"],M);let O=s(t,["topP"]);O!=null&&l(n,["topP"],O);let H=s(t,["translationConfig"]);return H!=null&&l(n,["translationConfig"],H),n}function cw(t,e){let n={},o=s(t,["name"]);return o!=null&&l(n,["_url","name"],o),n}function dw(t,e){let n={},o=s(t,["name"]);return o!=null&&l(n,["_url","name"],o),n}function fw(t,e,n){let o={},i=s(t,["pageSize"]);e!==void 0&&i!=null&&l(e,["_query","pageSize"],i);let r=s(t,["pageToken"]);e!==void 0&&r!=null&&l(e,["_query","pageToken"],r);let a=s(t,["filter"]);return e!==void 0&&a!=null&&l(e,["_query","filter"],a),o}function pw(t,e){let n={},o=s(t,["config"]);return o!=null&&fw(o,n),n}function hw(t,e){let n={},o=s(t,["sdkHttpResponse"]);o!=null&&l(n,["sdkHttpResponse"],o);let i=s(t,["nextPageToken"]);i!=null&&l(n,["nextPageToken"],i);let r=s(t,["tuningJobs"]);if(r!=null){let a=r;Array.isArray(a)&&(a=a.map(u=>ll(u))),l(n,["tuningJobs"],a)}return n}function mw(t,e){let n={};if(s(t,["name"])!==void 0)throw new Error("name parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(s(t,["streamableHttpTransport"])!==void 0)throw new Error("streamableHttpTransport parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return n}function gw(t,e){let n={},o=s(t,["mediaResolution"]);if(o!=null&&l(n,["mediaResolution"],o),s(t,["toolCall"])!==void 0)throw new Error("toolCall parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(s(t,["toolResponse"])!==void 0)throw new Error("toolResponse parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");let i=s(t,["audioTranscription"]);i!=null&&l(n,["audioTranscription"],i);let r=s(t,["codeExecutionResult"]);r!=null&&l(n,["codeExecutionResult"],r);let a=s(t,["executableCode"]);a!=null&&l(n,["executableCode"],a);let u=s(t,["fileData"]);u!=null&&l(n,["fileData"],u);let c=s(t,["functionCall"]);c!=null&&l(n,["functionCall"],c);let d=s(t,["functionResponse"]);d!=null&&l(n,["functionResponse"],lw(d));let f=s(t,["inlineData"]);f!=null&&l(n,["inlineData"],f);let p=s(t,["text"]);p!=null&&l(n,["text"],p);let h=s(t,["thought"]);h!=null&&l(n,["thought"],h);let g=s(t,["thoughtSignature"]);g!=null&&l(n,["thoughtSignature"],g);let _=s(t,["videoMetadata"]);if(_!=null&&l(n,["videoMetadata"],_),s(t,["partMetadata"])!==void 0)throw new Error("partMetadata parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");let m=s(t,["mediaProcessing"]);m!=null&&l(n,["mediaProcessing"],m);let v=s(t,["speechMetadata"]);return v!=null&&l(n,["speechMetadata"],v),n}function _w(t,e){let n={},o=s(t,["references"]);o!=null&&l(n,["references"],o);let i=s(t,["contents"]);if(i!=null){let u=i;Array.isArray(u)&&(u=u.map(c=>al(c))),l(n,["contents"],u)}let r=s(t,["systemInstruction"]);r!=null&&l(n,["systemInstruction"],al(r));let a=s(t,["tools"]);if(a!=null){let u=a;Array.isArray(u)&&(u=u.map(c=>yw(c))),l(n,["tools"],u)}return n}function yw(t,e){let n={},o=s(t,["retrieval"]);o!=null&&l(n,["retrieval"],o);let i=s(t,["googleMaps"]);i!=null&&l(n,["googleMaps"],i);let r=s(t,["mcpServers"]);if(r!=null){let m=r;Array.isArray(m)&&(m=m.map(v=>mw(v))),l(n,["mcpServers"],m)}let a=s(t,["codeExecution"]);a!=null&&l(n,["codeExecution"],a);let u=s(t,["computerUse"]);u!=null&&l(n,["computerUse"],u);let c=s(t,["enterpriseWebSearch"]);c!=null&&l(n,["enterpriseWebSearch"],c);let d=s(t,["exaAiSearch"]);d!=null&&l(n,["exaAiSearch"],d);let f=s(t,["functionDeclarations"]);if(f!=null){let m=f;Array.isArray(m)&&(m=m.map(v=>v)),l(n,["functionDeclarations"],m)}let p=s(t,["googleSearch"]);p!=null&&l(n,["googleSearch"],p);let h=s(t,["googleSearchRetrieval"]);h!=null&&l(n,["googleSearchRetrieval"],h);let g=s(t,["parallelAiSearch"]);g!=null&&l(n,["parallelAiSearch"],g);let _=s(t,["urlContext"]);if(_!=null&&l(n,["urlContext"],_),s(t,["fileSearch"])!==void 0)throw new Error("fileSearch parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return n}function vw(t,e){let n={},o=s(t,["name"]);o!=null&&l(n,["model"],o);let i=s(t,["name"]);return i!=null&&l(n,["endpoint"],i),n}function Ew(t,e){let n={};if(s(t,["gcsUri"])!==void 0)throw new Error("gcsUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["vertexDatasetResource"])!==void 0)throw new Error("vertexDatasetResource parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let o=s(t,["examples"]);if(o!=null){let i=o;Array.isArray(i)&&(i=i.map(r=>r)),l(n,["examples","examples"],i)}return n}function Tw(t,e,n){let o={},i=s(n,["config","method"]);if(i===void 0&&(i="SUPERVISED_FINE_TUNING"),i==="SUPERVISED_FINE_TUNING"){let a=s(t,["gcsUri"]);e!==void 0&&a!=null&&l(e,["supervisedTuningSpec","trainingDatasetUri"],a)}else if(i==="PREFERENCE_TUNING"){let a=s(t,["gcsUri"]);e!==void 0&&a!=null&&l(e,["preferenceOptimizationSpec","trainingDatasetUri"],a)}else if(i==="DISTILLATION"){let a=s(t,["gcsUri"]);e!==void 0&&a!=null&&l(e,["distillationSpec","promptDatasetUri"],a)}else if(i==="REINFORCEMENT_TUNING"){let a=s(t,["gcsUri"]);e!==void 0&&a!=null&&l(e,["reinforcementTuningSpec","trainingDatasetUri"],a)}let r=s(n,["config","method"]);if(r===void 0&&(r="SUPERVISED_FINE_TUNING"),r==="SUPERVISED_FINE_TUNING"){let a=s(t,["vertexDatasetResource"]);e!==void 0&&a!=null&&l(e,["supervisedTuningSpec","trainingDatasetUri"],a)}else if(r==="PREFERENCE_TUNING"){let a=s(t,["vertexDatasetResource"]);e!==void 0&&a!=null&&l(e,["preferenceOptimizationSpec","trainingDatasetUri"],a)}else if(r==="DISTILLATION"){let a=s(t,["vertexDatasetResource"]);e!==void 0&&a!=null&&l(e,["distillationSpec","promptDatasetUri"],a)}else if(r==="REINFORCEMENT_TUNING"){let a=s(t,["vertexDatasetResource"]);e!==void 0&&a!=null&&l(e,["reinforcementTuningSpec","trainingDatasetUri"],a)}if(s(t,["examples"])!==void 0)throw new Error("examples parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return o}function Aw(t,e){let n={},o=s(t,["sdkHttpResponse"]);o!=null&&l(n,["sdkHttpResponse"],o);let i=s(t,["name"]);i!=null&&l(n,["name"],i);let r=s(t,["state"]);r!=null&&l(n,["state"],Xf(r));let a=s(t,["createTime"]);a!=null&&l(n,["createTime"],a);let u=s(t,["tuningTask","startTime"]);u!=null&&l(n,["startTime"],u);let c=s(t,["tuningTask","completeTime"]);c!=null&&l(n,["endTime"],c);let d=s(t,["updateTime"]);d!=null&&l(n,["updateTime"],d);let f=s(t,["description"]);f!=null&&l(n,["description"],f);let p=s(t,["baseModel"]);p!=null&&l(n,["baseModel"],p);let h=s(t,["_self"]);return h!=null&&l(n,["tunedModel"],vw(h)),n}function ll(t,e){let n={},o=s(t,["sdkHttpResponse"]);o!=null&&l(n,["sdkHttpResponse"],o);let i=s(t,["name"]);i!=null&&l(n,["name"],i);let r=s(t,["state"]);r!=null&&l(n,["state"],Xf(r));let a=s(t,["createTime"]);a!=null&&l(n,["createTime"],a);let u=s(t,["startTime"]);u!=null&&l(n,["startTime"],u);let c=s(t,["endTime"]);c!=null&&l(n,["endTime"],c);let d=s(t,["updateTime"]);d!=null&&l(n,["updateTime"],d);let f=s(t,["error"]);f!=null&&l(n,["error"],f);let p=s(t,["description"]);p!=null&&l(n,["description"],p);let h=s(t,["baseModel"]);h!=null&&l(n,["baseModel"],h);let g=s(t,["tunedModel"]);g!=null&&l(n,["tunedModel"],g);let _=s(t,["preTunedModel"]);_!=null&&l(n,["preTunedModel"],_);let m=s(t,["supervisedTuningSpec"]);m!=null&&l(n,["supervisedTuningSpec"],m);let v=s(t,["preferenceOptimizationSpec"]);v!=null&&l(n,["preferenceOptimizationSpec"],v);let y=s(t,["distillationSamplingSpec"]);y!=null&&l(n,["distillationSamplingSpec"],rw(y));let E=s(t,["distillationSpec"]);E!=null&&l(n,["distillationSpec"],sw(E));let A=s(t,["reinforcementTuningSpec"]);A!=null&&l(n,["reinforcementTuningSpec"],A);let C=s(t,["tuningDataStats"]);C!=null&&l(n,["tuningDataStats"],C);let w=s(t,["encryptionSpec"]);w!=null&&l(n,["encryptionSpec"],w);let N=s(t,["partnerModelTuningSpec"]);N!=null&&l(n,["partnerModelTuningSpec"],N);let q=s(t,["customBaseModel"]);q!=null&&l(n,["customBaseModel"],q);let V=s(t,["evaluateDatasetRuns"]);if(V!=null){let Ue=V;Array.isArray(Ue)&&(Ue=Ue.map(Ge=>Ge)),l(n,["evaluateDatasetRuns"],Ue)}let M=s(t,["experiment"]);M!=null&&l(n,["experiment"],M);let O=s(t,["fullFineTuningSpec"]);O!=null&&l(n,["fullFineTuningSpec"],O);let H=s(t,["labels"]);H!=null&&l(n,["labels"],H);let $=s(t,["outputUri"]);$!=null&&l(n,["outputUri"],$);let j=s(t,["pipelineJob"]);j!=null&&l(n,["pipelineJob"],j);let D=s(t,["serviceAccount"]);D!=null&&l(n,["serviceAccount"],D);let Q=s(t,["tunedModelDisplayName"]);Q!=null&&l(n,["tunedModelDisplayName"],Q);let te=s(t,["tuningJobMetadata"]);te!=null&&l(n,["tuningJobMetadata"],te);let Ae=s(t,["tuningJobState"]);Ae!=null&&l(n,["tuningJobState"],Ae);let ve=s(t,["veoLoraTuningSpec"]);ve!=null&&l(n,["veoLoraTuningSpec"],ve);let fe=s(t,["veoTuningSpec"]);fe!=null&&l(n,["veoTuningSpec"],fe);let He=s(t,["gcsMetricsUri"]);return He!=null&&l(n,["gcsMetricsUri"],He),n}function Cw(t,e){let n={},o=s(t,["sdkHttpResponse"]);o!=null&&l(n,["sdkHttpResponse"],o);let i=s(t,["name"]);i!=null&&l(n,["name"],i);let r=s(t,["metadata"]);r!=null&&l(n,["metadata"],r);let a=s(t,["done"]);a!=null&&l(n,["done"],a);let u=s(t,["error"]);return u!=null&&l(n,["error"],u),n}function Yo(t,e){let n={},o=s(t,["gcsUri"]);o!=null&&l(n,["validationDatasetUri"],o);let i=s(t,["vertexDatasetResource"]);return i!=null&&l(n,["validationDatasetUri"],i),n}function Iw(t,e){let n={},o=s(t,["parent"]);o!=null&&l(n,["_url","parent"],o);let i=s(t,["sampleResponse"]);i!=null&&l(n,["sampleResponse"],al(i));let r=s(t,["example"]);r!=null&&l(n,["example"],_w(r));let a=s(t,["singleRewardConfig"]);a!=null&&l(n,["singleRewardConfig"],a);let u=s(t,["compositeRewardConfig"]);return u!=null&&l(n,["compositeRewardConfig"],u),n}function Sw(t,e){let n={},o=s(t,["sdkHttpResponse"]);o!=null&&l(n,["sdkHttpResponse"],o);let i=s(t,["overallReward"]);i!=null&&l(n,["overallReward"],i);let r=s(t,["error"]);r!=null&&l(n,["error"],r);let a=s(t,["rewardInfoDetails"]);return a!=null&&l(n,["rewardInfoDetails"],a),n}var ul=class extends dt{constructor(e){super(),this.apiClient=e,this.list=async(n={})=>new Pt(Rt.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/")){let i={tunedModelName:n.baseModel};!((o=n.config)===null||o===void 0)&&o.preTunedModelCheckpointId&&(i.checkpointId=n.config.preTunedModelCheckpointId);let r=Object.assign(Object.assign({},n),{preTunedModel:i});return r.baseModel=void 0,await this.tuneInternal(r)}else{let i=Object.assign({},n);return await this.tuneInternal(i)}else{let i=Object.assign({},n),r=await this.tuneMldevInternal(i),a="";return r.metadata!==void 0&&r.metadata.tunedModel!==void 0?a=r.metadata.tunedModel:r.name!==void 0&&r.name.includes("/operations/")&&(a=r.name.split("/operations/")[0]),{name:a,state:Ds.JOB_STATE_QUEUED}}}}async getInternal(e){var n,o,i,r;let a,u="",c={};if(this.apiClient.isVertexAI()){let d=dw(e);return u=X("{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(p=>{let h=p;return h.sdkHttpResponse={headers:f.headers},h})),a.then(f=>ll(f))}else{let d=cw(e);return u=X("{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:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(f=>f.json().then(p=>{let h=p;return h.sdkHttpResponse={headers:f.headers},h})),a.then(f=>Aw(f))}}async listInternal(e){var n,o;let i,r="",a={};if(this.apiClient.isVertexAI()){let u=pw(e);return r=X("tuningJobs",u._url),a=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:r,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=>{let f=d;return f.sdkHttpResponse={headers:c.headers},f})),i.then(c=>{let d=hw(c),f=new Hs;return Object.assign(f,d),f})}else throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async cancel(e){var n,o,i,r;let a,u="",c={};if(this.apiClient.isVertexAI()){let d=ZS(e);return u=X("{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(p=>{let h=p;return h.sdkHttpResponse={headers:f.headers},h})),a.then(f=>{let p=ew(f),h=new ri;return Object.assign(h,p),h})}else{let d=QS(e);return u=X("{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:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(f=>f.json().then(p=>{let h=p;return h.sdkHttpResponse={headers:f.headers},h})),a.then(f=>{let p=jS(f),h=new ri;return Object.assign(h,p),h})}}async tuneInternal(e){var n,o;let i,r="",a={};if(this.apiClient.isVertexAI()){let u=iw(e,e);return r=X("tuningJobs",u._url),a=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:r,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=>{let f=d;return f.sdkHttpResponse={headers:c.headers},f})),i.then(c=>ll(c))}else throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async tuneMldevInternal(e){var n,o;let i,r="",a={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let u=ow(e);return r=X("tunedModels",u._url),a=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:r,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=>{let f=d;return f.sdkHttpResponse={headers:c.headers},f})),i.then(c=>Cw(c))}}async validateReward(e){var n,o;let i,r="",a={};if(this.apiClient.isVertexAI()){let u=Iw(e);return r=X("{parent}/tuningJobs:validateReinforcementTuningReward",u._url),a=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:r,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=>{let f=d;return f.sdkHttpResponse={headers:c.headers},f})),i.then(c=>{let d=Sw(c),f=new Vs;return Object.assign(f,d),f})}else throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}},Dh=1024*1024*8,Mh=3,Uh=1e3,Gh=2,Lt="x-goog-upload-status";async function ww(t,e,n,o){var i;let r=await bh(t,e,n,o),a=await r?.json();if(((i=r?.headers)===null||i===void 0?void 0:i[Lt])!=="final")throw new Error("Failed to upload file: Upload status is not finalized.");return a.file}async function Rw(t,e,n,o){var i;let r=await bh(t,e,n,o),a=await r?.json();if(((i=r?.headers)===null||i===void 0?void 0:i[Lt])!=="final")throw new Error("Failed to upload file: Upload status is not finalized.");let u=pl(a),c=new ui;return Object.assign(c,u),c}async function bh(t,e,n,o){var i,r,a;let u=e,c=o?.baseUrl||((i=n.clientOptions.httpOptions)===null||i===void 0?void 0:i.baseUrl);if(c){let g=new URL(c),_=new URL(e);_.protocol=g.protocol,_.host=g.host,_.port=g.port,u=_.toString()}let d=0,f=0,p=new wt(new Response),h="upload";for(d=t.size;f<d;){let g=Math.min(Dh,d-f),_=t.slice(f,f+g);f+g>=d&&(h+=", finalize");let m=0,v=Uh;for(;m<Mh;){let y=Object.assign(Object.assign({},o?.headers||{}),{"X-Goog-Upload-Command":h,"X-Goog-Upload-Offset":String(f)});if(p=await n.request({path:"",body:_,httpMethod:"POST",httpOptions:Object.assign(Object.assign({},o),{apiVersion:"",baseUrl:u,headers:y})}),!((r=p?.headers)===null||r===void 0)&&r[Lt])break;m++,await Lh(v),v=v*Gh}if(f+=g,((a=p?.headers)===null||a===void 0?void 0:a[Lt])!=="active")break;if(d<=f)throw new Error("All content has been uploaded, but the upload status is not finalized.")}return p}async function Pw(t){return{size:t.size,type:t.type}}function Lh(t){return new Promise(e=>setTimeout(e,t))}var cl=class{async stat(e){let n={size:0,type:void 0};if(typeof e=="string"){let o=await Ci.stat(e);return n.size=o.size,n.type=this.inferMimeType(e),n}else return await Pw(e)}async upload(e,n,o,i){return typeof e=="string"?await this.uploadFileFromPath(e,n,o,i):ww(e,n,o,i)}async uploadToFileSearchStore(e,n,o,i){return typeof e=="string"?await this.uploadFileToFileSearchStoreFromPath(e,n,o,i):Rw(e,n,o,i)}inferMimeType(e){let n=e.slice(e.lastIndexOf(".")+1);return{aac:"audio/aac",abw:"application/x-abiword",arc:"application/x-freearc",avi:"video/x-msvideo",azw:"application/vnd.amazon.ebook",bin:"application/octet-stream",bmp:"image/bmp",bz:"application/x-bzip",bz2:"application/x-bzip2",csh:"application/x-csh",css:"text/css",csv:"text/csv",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",eot:"application/vnd.ms-fontobject",epub:"application/epub+zip",gz:"application/gzip",gif:"image/gif",htm:"text/html",html:"text/html",ico:"image/vnd.microsoft.icon",ics:"text/calendar",jar:"application/java-archive",jpeg:"image/jpeg",jpg:"image/jpeg",js:"text/javascript",json:"application/json",jsonld:"application/ld+json",kml:"application/vnd.google-earth.kml+xml",kmz:"application/vnd.google-earth.kmz+xml",mjs:"text/javascript",mp3:"audio/mpeg",mp4:"video/mp4",mpeg:"video/mpeg",mpkg:"application/vnd.apple.installer+xml",odt:"application/vnd.oasis.opendocument.text",oga:"audio/ogg",ogv:"video/ogg",ogx:"application/ogg",opus:"audio/opus",otf:"font/otf",png:"image/png",pdf:"application/pdf",php:"application/x-httpd-php",ppt:"application/vnd.ms-powerpoint",pptx:"application/vnd.openxmlformats-officedocument.presentationml.presentation",rar:"application/vnd.rar",rtf:"application/rtf",sh:"application/x-sh",svg:"image/svg+xml",swf:"application/x-shockwave-flash",tar:"application/x-tar",tif:"image/tiff",tiff:"image/tiff",ts:"video/mp2t",ttf:"font/ttf",txt:"text/plain",vsd:"application/vnd.visio",wav:"audio/wav",weba:"audio/webm",webm:"video/webm",webp:"image/webp",woff:"font/woff",woff2:"font/woff2",xhtml:"application/xhtml+xml",xls:"application/vnd.ms-excel",xlsx:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",xml:"application/xml",xul:"application/vnd.mozilla.xul+xml",zip:"application/zip","3gp":"video/3gpp","3g2":"video/3gpp2","7z":"application/x-7z-compressed"}[n.toLowerCase()]}async uploadFileFromPath(e,n,o,i){var r;let a=await this.uploadFileFromPathInternal(e,n,o,i),u=await a?.json();if(((r=a?.headers)===null||r===void 0?void 0:r[Lt])!=="final")throw new Error("Failed to upload file: Upload status is not finalized.");return u.file}async uploadFileToFileSearchStoreFromPath(e,n,o,i){var r;let a=await this.uploadFileFromPathInternal(e,n,o,i),u=await a?.json();if(((r=a?.headers)===null||r===void 0?void 0:r[Lt])!=="final")throw new Error("Failed to upload file: Upload status is not finalized.");let c=pl(u),d=new ui;return Object.assign(d,c),d}async uploadFileFromPathInternal(e,n,o,i){var r,a,u;let c=n,d=i?.baseUrl||((r=o.clientOptions.httpOptions)===null||r===void 0?void 0:r.baseUrl);if(d){let v=new URL(d),y=new URL(n);y.protocol=v.protocol,y.host=v.host,y.port=v.port,c=y.toString()}let f=0,p=0,h=new wt(new Response),g="upload",_,m=Of.basename(e);try{if(_=await Ci.open(e,"r"),!_)throw new Error("Failed to open file");for(f=(await _.stat()).size;p<f;){let v=Math.min(Dh,f-p);p+v>=f&&(g+=", finalize");let y=new Uint8Array(v),{bytesRead:E}=await _.read(y,0,v,p);if(E!==v)throw new Error(`Failed to read ${v} bytes from file at offset ${p}. bytes actually read: ${E}`);let A=new Blob([y]),C=0,w=Uh;for(;C<Mh;){let N=Object.assign(Object.assign({},i?.headers||{}),{"X-Goog-Upload-Command":g,"X-Goog-Upload-Offset":String(p),"X-Goog-Upload-File-Name":m});if(h=await o.request({path:"",body:A,httpMethod:"POST",httpOptions:Object.assign(Object.assign({},i),{apiVersion:"",baseUrl:c,headers:N})}),!((a=h?.headers)===null||a===void 0)&&a[Lt])break;C++,await Lh(w),w=w*Gh}if(p+=E,((u=h?.headers)===null||u===void 0?void 0:u[Lt])!=="active")break;if(f<=p)throw new Error("All content has been uploaded, but the upload status is not finalized.")}return h}finally{_&&await _.close()}}};var dl=class extends VE{async registerFiles(e){if(typeof process>"u"||!process.versions||!process.versions.node)throw new Error("registerFiles is only supported in Node.js environments.");let o=await e.auth.getRequestHeaders(),i=e.config||{},r=i.httpOptions||{},a=Object.assign({},r.headers||{});if(o)if(typeof o[Symbol.iterator]=="function")for(let[u,c]of o)a[u]=c;else for(let[u,c]of Object.entries(o))a[u]=c;return this._registerFiles({uris:e.uris,config:Object.assign(Object.assign({},i),{httpOptions:Object.assign(Object.assign({},r),{headers:a})})})}};var kw="gl-node/";function Nw(t){var e;if(t&&(t.enterprise!==void 0||t.vertexai!==void 0)){if(t.enterprise!==void 0&&t.vertexai!==void 0&&t.enterprise!==t.vertexai)throw new Error("enterprise and vertexAI flags have conflicting values, please set enterprise value only.");return(e=t.enterprise)!==null&&e!==void 0?e:t.vertexai}let n=qt("GOOGLE_GENAI_USE_ENTERPRISE"),o=qt("GOOGLE_GENAI_USE_VERTEXAI"),i=bf(n),r=bf(o);return n!==void 0&&o!==void 0&&i!==r&&console.warn("Warning: Both GOOGLE_GENAI_USE_ENTERPRISE and GOOGLE_GENAI_USE_VERTEXAI are set with conflicting values. The value of GOOGLE_GENAI_USE_ENTERPRISE will be used."),n!==void 0?i:o!==void 0?r:!1}var Gf=class{getNextGenClient(){let e=this.httpOptions;return this._nextGenClient===void 0&&(this._nextGenClient=Fe(this.apiClient,{timeout_ms:e?.timeout})),e?.extraBody&&console.warn("GoogleGenAI: Client level httpOptions.extraBody is not supported by the Gemini NextGen client and will be ignored."),this._nextGenClient}get interactions(){return this._interactions!==void 0?this._interactions:(this._interactions=new za(this.apiClient,new Ai),this._interactions)}get webhooks(){return this._webhooks!==void 0?this._webhooks:(this._webhooks=new Za(this.apiClient),this._webhooks)}get agents(){return this._agents!==void 0?this._agents:(console.warn("GoogleGenAI.agents: Agents usage is experimental and may change in future versions."),this._agents=new Qa(this.apiClient),this._agents)}get triggers(){return this._triggers!==void 0?this._triggers:(console.warn("GoogleGenAI.triggers: Triggers usage is experimental and may change in future versions."),this._triggers=new ja(this.apiClient),this._triggers)}get environments(){return this._environments!==void 0?this._environments:(console.warn("GoogleGenAI.environments: Environments usage is experimental and may change in future versions."),this._environments=new tl(this.apiClient),this._environments)}get credentials(){return this._credentials!==void 0?this._credentials:(console.warn("GoogleGenAI.credentials: Credentials usage is experimental and may change in future versions."),this._credentials=new nl(this.apiClient),this._credentials)}get voices(){return this._voices!==void 0?this._voices:(this._voices=new ol(this.apiClient),this._voices)}constructor(e={}){var n,o,i,r;if(this.vertexai=Nw(e),(e.project||e.location)&&!this.vertexai)throw new Error("Project and location are not supported for Gemini API backend.");let a=xw(),u=qt("GOOGLE_CLOUD_PROJECT"),c=qt("GOOGLE_CLOUD_LOCATION");this.apiKey=(n=e.apiKey)!==null&&n!==void 0?n:a,this.project=(o=e.project)!==null&&o!==void 0?o:u,this.location=(i=e.location)!==null&&i!==void 0?i:c,!this.vertexai&&!this.apiKey&&console.warn("API key should be set when using the Gemini API."),this.vertexai&&(!((r=e.googleAuthOptions)===null||r===void 0)&&r.credentials&&(console.debug("The user provided Google Cloud credentials will take precedence over the API key from the environment variable."),this.apiKey=void 0),!e.project&&!e.location&&(u||c)&&e.apiKey?(console.debug("The user provided Vertex AI API key will take precedence over the project/location from the environment variables."),this.project=void 0,this.location=void 0):(e.project||e.location)&&!e.apiKey&&a?(console.debug("The user provided project/location will take precedence over the API key from the environment variables."),this.apiKey=void 0):!e.project&&!e.location&&!e.apiKey&&(u||c)&&a&&(console.debug("The project/location from the environment variables will take precedence over the API key from the environment variables."),this.apiKey=void 0),!this.location&&!this.apiKey&&(this.location="global"));let d=Uy(e.httpOptions,this.vertexai,qt("GOOGLE_VERTEX_BASE_URL"),qt("GOOGLE_GEMINI_BASE_URL"));d&&(e.httpOptions?e.httpOptions.baseUrl=d:e.httpOptions={baseUrl:d}),this.apiVersion=e.apiVersion,this.httpOptions=e.httpOptions;let f=new il({apiKey:this.apiKey,googleAuthOptions:e.googleAuthOptions});this.apiClient=new la({auth:f,project:this.project,location:this.location,apiVersion:this.apiVersion,apiKey:this.apiKey,vertexai:this.vertexai,httpOptions:this.httpOptions,userAgentExtra:kw+process.version,uploader:new cl,downloader:new rl}),this.models=new An(this.apiClient),this.live=new fa(this.apiClient,f,new Ai),this.batches=new ta(this.apiClient),this.chats=new oa(this.models,this.apiClient),this.caches=new na(this.apiClient),this.files=new dl(this.apiClient),this.operations=new ha(this.apiClient),this.authTokens=new ma(this.apiClient),this.tunings=new ul(this.apiClient),this.fileSearchStores=new _a(this.apiClient)}};function qt(t){var e,n,o;return(o=(n=(e=process==null?void 0: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}function bf(t){return t===void 0?!1:t.toLowerCase()==="true"}function xw(){let t=qt("GOOGLE_API_KEY"),e=qt("GEMINI_API_KEY");return t&&e&&console.warn("Both GOOGLE_API_KEY and GEMINI_API_KEY are set. Using GOOGLE_API_KEY."),t||e||void 0}var Dw={THINKING_LEVEL_UNSPECIFIED:Ot.THINKING_LEVEL_UNSPECIFIED,MINIMAL:Ot.MINIMAL,LOW:Ot.LOW,MEDIUM:Ot.MEDIUM,HIGH:Ot.HIGH};function Mw(t,e){let n=t.thinkingLevelMap?.[e],o=typeof n=="string"?n.toLowerCase():e;switch(o){case"minimal":case"low":case"medium":case"high":return o;default:throw new Error(`Unsupported Google thinking level mapping for ${t.provider}/${t.id}: ${e} -> ${String(n)}`)}}function Uw(t){let e=t.id.toLowerCase();return/gemini-3(?:\.\d+)?-(?:pro|flash)/.test(e)||/gemini-(?:[4-9]|[1-9]\d)/.test(e)||e==="gemini-flash-latest"||e==="gemini-flash-lite-latest"||/gemma-?4/.test(e)}function Gw(t){switch(t){case"minimal":return"MINIMAL";case"low":return"LOW";case"medium":return"MEDIUM";case"high":return"HIGH"}}function bw(t){return Dw[t]}function pP(t){if(!Uw(t))return{thinkingBudget:0};let e=Nl(t,"off");if(e==="off")return{thinkingBudget:0};let n=Mw(t,e),o=Gw(n);return{thinkingLevel:bw(o)}}function hP(t){return t.thought===!0}function mP(t,e){return typeof e=="string"&&e.length>0?e:t}var Lw=/^[A-Za-z0-9+/]+={0,2}$/;function qw(t){return!t||t.length%4!==0?!1:Lw.test(t)}function Tl(t,e){return t&&qw(e)?e:void 0}function Al(t){let e=Cl(t);return t.startsWith("claude-")||t.startsWith("gpt-oss-")||e!==void 0&&e>=3}function Cl(t){let e=t.toLowerCase().match(/^gemini(?:-live)?-(\d+)/);if(e)return Number.parseInt(e[1],10)}function Ow(t){let e=Cl(t);return e!==void 0?e>=3:!0}function gP(t,e){let n=Pl(kl(e).messages),o=[],r=Ml(n,t,a=>Al(t.id)?a.replace(/[^a-zA-Z0-9_-]/g,"_").slice(0,64):a);for(let a of r)if(a.role==="user")if(typeof a.content=="string")o.push({role:"user",parts:[{text:Yt(a.content)}]});else{let u=a.content.map(c=>c.type==="text"?{text:Yt(c.text)}:{inlineData:{mimeType:c.mimeType,data:c.data}});if(u.length===0)continue;o.push({role:"user",parts:u})}else if(a.role==="assistant"){let u=[],c=a.provider===t.provider&&a.model===t.id;for(let d of a.content)if(d.type==="text"){let f=Tl(c,d.textSignature);if((!d.text||d.text.trim()==="")&&!f)continue;u.push({text:Yt(d.text),...f&&{thoughtSignature:f}})}else if(d.type==="thinking")if(c){let f=Tl(c,d.thinkingSignature);if((!d.thinking||d.thinking.trim()==="")&&!f)continue;u.push({thought:!0,text:Yt(d.thinking),...f&&{thoughtSignature:f}})}else{if(!d.thinking||d.thinking.trim()==="")continue;u.push({text:Yt(d.thinking)})}else if(d.type==="toolCall"){let f=Tl(c,d.thoughtSignature),p={functionCall:{name:d.name,args:d.arguments??{},...Al(t.id)?{id:d.id}:{}},...f&&{thoughtSignature:f}};u.push(p)}if(u.length===0)continue;o.push({role:"model",parts:u})}else if(a.role==="toolResult"){let c=a.content.filter(E=>E.type==="text").map(E=>E.text).join(`
38
+ `),d=t.input.includes("image")?a.content.filter(E=>E.type==="image"):[],f=c.trim().length>0,p=d.length>0,h=Ow(t.id),g=f?Yt(c):p?"(see attached image)":"",_=d.map(E=>({inlineData:{mimeType:E.mimeType,data:E.data}})),m=Al(t.id),v={functionResponse:{name:a.toolName,response:a.isError?{error:g}:{output:g},...p&&h&&{parts:_},...m?{id:a.toolCallId}:{}}},y=o[o.length-1];y?.role==="user"&&y.parts?.some(E=>E.functionResponse)?y.parts.push(v):o.push({role:"user",parts:[v]}),p&&!h&&o.push({role:"user",parts:[{text:"Tool result image:"},..._]})}return o}var Fw=new Set(["$schema","$id","$anchor","$dynamicAnchor","$vocabulary","$comment","$defs","definitions"]);function Oh(t){if(typeof t!="object"||t===null||Array.isArray(t))return t;let e={};for(let[n,o]of Object.entries(t))Fw.has(n)||(e[n]=Oh(o));return e}var Hw=new Set(["properties","patternProperties","$defs","definitions","dependentSchemas","dependencies"]),Vw=new Set(["additionalProperties","unevaluatedProperties","propertyNames","items","prefixItems","additionalItems","unevaluatedItems","contains","allOf","anyOf","oneOf","not","if","then","else","contentSchema"]);function Pi(t,e=!1){if(Array.isArray(t))return t.map(o=>Pi(o));if(typeof t!="object"||t===null)return t;let n=Object.fromEntries(Object.entries(t).map(([o,i])=>e||Vw.has(o)?[o,Pi(i)]:Hw.has(o)?[o,Pi(i,!0)]:[o,i]));if(!e&&"const"in n&&n.enum===void 0){let o=n.const;(typeof o=="string"||typeof o=="number")&&(delete n.const,n.enum=[o])}return n}function _P(t,e=!1,n=!0){if(t.length!==0)return[{functionDeclarations:t.map(o=>{let i=Mi(o,n),r=Dl(o,i);return{name:o.name,description:o.description,...e?{parameters:Oh(r)}:{parametersJsonSchema:Pi(r)}}})}]}function yP(t){let e=Cl(t);return e!==void 0&&e>=3}function qh(t){switch(t){case"auto":return Ft.AUTO;case"none":return Ft.NONE;case"any":return Ft.ANY;default:return Ft.AUTO}}function vP(t,e,n){let o=t.some(i=>Mi(i,n)===!0);return e==="none"||e==="any"?qh(e):o?Ft.VALIDATED:e?qh(e):void 0}function EP(t){switch(t){case Se.STOP:return"stop";case Se.MAX_TOKENS:case Se.CONTINUATION:return"length";case Se.BLOCKLIST:case Se.PROHIBITED_CONTENT:case Se.SPII:case Se.SAFETY:case Se.IMAGE_SAFETY:case Se.IMAGE_PROHIBITED_CONTENT:case Se.IMAGE_RECITATION:case Se.IMAGE_OTHER:case Se.RECITATION:case Se.FINISH_REASON_UNSPECIFIED:case Se.OTHER:case Se.LANGUAGE:case Se.MALFORMED_FUNCTION_CALL:case Se.UNEXPECTED_TOOL_CALL:case Se.TOO_MANY_TOOL_CALLS:case Se.NO_IMAGE:return"error";default:{let e=t;throw new Error(`Unhandled stop reason: ${e}`)}}}function TP(t,e){return xl(async()=>{try{return await t()}catch(n){throw n instanceof Error&&"status"in n&&!("headers"in n)&&(n.headers=void 0),n}},{maxRetries:e?.maxRetries,maxRetryDelayMs:e?.maxRetryDelayMs,signal:e?.signal})}export{Ms as a,Gf as b,Mw as c,Uw as d,Gw as e,bw as f,pP as g,hP as h,mP as i,gP as j,_P as k,yP as l,vP as m,EP as n,TP as o};
39
+ /*! Bundled license information:
40
+
41
+ @google/genai/dist/node/index.mjs:
42
+ @google/genai/dist/node/index.mjs:
43
+ @google/genai/dist/node/index.mjs:
44
+ @google/genai/dist/node/index.mjs:
45
+ @google/genai/dist/node/index.mjs:
46
+ (**
47
+ * @license
48
+ * Copyright 2025 Google LLC
49
+ * SPDX-License-Identifier: Apache-2.0
50
+ *)
51
+
52
+ @google/genai/dist/node/index.mjs:
53
+ (**
54
+ * @license
55
+ * Copyright 2025 Google LLC
56
+ * SPDX-License-Identifier: Apache-2.0
57
+ *)
58
+ (**
59
+ * @license
60
+ * Copyright 2026 Google LLC
61
+ * SPDX-License-Identifier: Apache-2.0
62
+ *)
63
+ (**
64
+ * @license
65
+ * Copyright 2026 Google LLC
66
+ * SPDX-License-Identifier: Apache-2.0
67
+ *
68
+ * g3-prettier-ignore-file
69
+ *)
70
+ */