@cline/core 0.0.95 → 0.2.0-nightly.1793312794

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 (175) hide show
  1. package/dist/ClineCore.d.ts +6 -1
  2. package/dist/account/rpc.d.ts +3 -1
  3. package/dist/account/types.d.ts +2 -0
  4. package/dist/artifacts/cloud/fetch.d.ts +8 -0
  5. package/dist/artifacts/cloud/publish.d.ts +6 -0
  6. package/dist/artifacts/publish.d.ts +30 -0
  7. package/dist/cline-core/runtime-services.d.ts +4 -2
  8. package/dist/cloud/computer-use-prompt.d.ts +9 -0
  9. package/dist/cloud/controller.d.ts +26 -4
  10. package/dist/cloud/hub-client.d.ts +53 -0
  11. package/dist/cloud/hub-protocol.d.ts +32 -0
  12. package/dist/cloud/index.d.ts +5 -0
  13. package/dist/cloud/index.js +34 -17
  14. package/dist/cloud/types.d.ts +4 -1
  15. package/dist/extensions/context/compaction-shared.d.ts +1 -0
  16. package/dist/extensions/context/compaction.d.ts +7 -0
  17. package/dist/extensions/context/summarize-conversation.d.ts +7 -0
  18. package/dist/extensions/context/summary-generation.d.ts +14 -0
  19. package/dist/extensions/mcp/apps.d.ts +16 -0
  20. package/dist/extensions/mcp/client.d.ts +1 -0
  21. package/dist/extensions/mcp/index.d.ts +5 -1
  22. package/dist/extensions/mcp/manager.d.ts +2 -1
  23. package/dist/extensions/mcp/session-apps.d.ts +28 -0
  24. package/dist/extensions/mcp/types.d.ts +22 -0
  25. package/dist/extensions/plugin/plugin-command-origin.d.ts +8 -0
  26. package/dist/extensions/plugin/plugin-registry.d.ts +1 -0
  27. package/dist/extensions/plugin/plugin-runtime.d.ts +7 -0
  28. package/dist/hub/client/index.d.ts +6 -0
  29. package/dist/hub/client/managed-hub-build-watcher.d.ts +2 -0
  30. package/dist/hub/client/plugin-commands.d.ts +4 -0
  31. package/dist/hub/client/session-client.d.ts +2 -0
  32. package/dist/hub/daemon/entry.js +248 -229
  33. package/dist/hub/daemon/index.d.ts +2 -0
  34. package/dist/hub/index.d.ts +1 -0
  35. package/dist/hub/index.js +238 -219
  36. package/dist/hub/runtime-host/hub-runtime-host.d.ts +6 -0
  37. package/dist/hub/server/cloud-session-service.d.ts +52 -0
  38. package/dist/hub/server/handlers/capability-handlers.d.ts +18 -1
  39. package/dist/hub/server/handlers/context.d.ts +13 -2
  40. package/dist/hub/server/handlers/mcp-apps-handlers.d.ts +5 -0
  41. package/dist/hub/server/handlers/session-handlers.d.ts +4 -0
  42. package/dist/hub/server/hub-server-options.d.ts +3 -0
  43. package/dist/hub/server/hub-server-transport.d.ts +2 -0
  44. package/dist/index.d.ts +10 -5
  45. package/dist/index.js +284 -258
  46. package/dist/plugin-runtime/node_modules/@cline/agents/dist/index.js +76 -0
  47. package/dist/plugin-runtime/node_modules/@cline/agents/package.json +1 -0
  48. package/dist/plugin-runtime/node_modules/@cline/core/dist/ai-sdk-bdvd54cj.js +1 -0
  49. package/dist/plugin-runtime/node_modules/@cline/core/dist/anthropic-d88t4w67.js +1 -0
  50. package/dist/plugin-runtime/node_modules/@cline/core/dist/bedrock-4rh6dw0e.js +1 -0
  51. package/dist/plugin-runtime/node_modules/@cline/core/dist/cline-dex049wz.js +1 -0
  52. package/dist/plugin-runtime/node_modules/@cline/core/dist/cloud/index.js +38 -0
  53. package/dist/plugin-runtime/node_modules/@cline/core/dist/community-adrseffv.js +1 -0
  54. package/dist/plugin-runtime/node_modules/@cline/core/dist/foundation-models-embedding-model-strategy-SAVQFBF4-vf44v1q1.js +1 -0
  55. package/dist/plugin-runtime/node_modules/@cline/core/dist/foundation-models-language-model-strategy-BPQO66W7-np6pavev.js +1 -0
  56. package/dist/plugin-runtime/node_modules/@cline/core/dist/getMachineId-bsd-1xg0n8py.js +1 -0
  57. package/dist/plugin-runtime/node_modules/@cline/core/dist/getMachineId-bsd-2h2811k3.js +1 -0
  58. package/dist/plugin-runtime/node_modules/@cline/core/dist/getMachineId-darwin-918h9zb6.js +2 -0
  59. package/dist/plugin-runtime/node_modules/@cline/core/dist/getMachineId-darwin-9g9qz8kw.js +2 -0
  60. package/dist/plugin-runtime/node_modules/@cline/core/dist/getMachineId-linux-8p52y0t4.js +1 -0
  61. package/dist/plugin-runtime/node_modules/@cline/core/dist/getMachineId-linux-cr4wnstr.js +1 -0
  62. package/dist/plugin-runtime/node_modules/@cline/core/dist/getMachineId-unsupported-aa72jh2v.js +1 -0
  63. package/dist/plugin-runtime/node_modules/@cline/core/dist/getMachineId-unsupported-k2y10eep.js +1 -0
  64. package/dist/plugin-runtime/node_modules/@cline/core/dist/getMachineId-win-1hvm2h6v.js +1 -0
  65. package/dist/plugin-runtime/node_modules/@cline/core/dist/getMachineId-win-7nqbajdc.js +1 -0
  66. package/dist/plugin-runtime/node_modules/@cline/core/dist/google-nqn5r579.js +1 -0
  67. package/dist/plugin-runtime/node_modules/@cline/core/dist/hub/daemon/entry.js +1166 -0
  68. package/dist/plugin-runtime/node_modules/@cline/core/dist/hub/index.js +1153 -0
  69. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-0ahmqye5.js +2 -0
  70. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-1jwj53tz.js +2 -0
  71. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-3qy7846d.js +14 -0
  72. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-418gvd4a.js +2 -0
  73. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-4etvmc8g.js +2 -0
  74. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-4pm9q9we.js +1 -0
  75. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-4tgv599k.js +2 -0
  76. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-5hwscy9s.js +15 -0
  77. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-6dpcn5cw.js +9 -0
  78. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-7ycwqbm0.js +1 -0
  79. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-8qjtgvqw.js +9 -0
  80. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-8zb5grad.js +1210 -0
  81. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-94jdgxt6.js +2 -0
  82. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-9g67p34k.js +2 -0
  83. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-a9d2sjh0.js +85 -0
  84. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-agemt17a.js +3 -0
  85. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-bhf7enwn.js +1 -0
  86. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-bnwxdgvg.js +1 -0
  87. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-brjxtvsh.js +4 -0
  88. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-bvb7f701.js +1 -0
  89. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-bwet95hr.js +2 -0
  90. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-cadyf2yp.js +14 -0
  91. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-cxfnnrmh.js +9 -0
  92. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-cyyvppz9.js +6 -0
  93. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-d4pbedxj.js +137 -0
  94. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-ddwn220p.js +12 -0
  95. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-edf1hmcw.js +62 -0
  96. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-ejyd73x5.js +1 -0
  97. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-f25bf131.js +4 -0
  98. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-f4rfmj6q.js +3 -0
  99. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-fet3kwk6.js +1 -0
  100. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-ffna8yzn.js +121 -0
  101. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-g2y6ptdc.js +213 -0
  102. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-ge184xvn.js +6 -0
  103. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-gevnedsc.js +13 -0
  104. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-hkmarmve.js +190 -0
  105. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-kqacxn3s.js +39 -0
  106. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-m3gtj35r.js +14 -0
  107. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-neczvge6.js +21 -0
  108. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-p5k5hnam.js +75 -0
  109. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-sdvqs19c.js +20 -0
  110. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-t75m2pgm.js +146 -0
  111. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-v4-qqb2kabr.js +1 -0
  112. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-v6mehmme.js +12 -0
  113. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-v80fh3x3.js +16 -0
  114. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-vd605jwp.js +2 -0
  115. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-vryppqt1.js +1 -0
  116. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-w55v4n1n.js +2 -0
  117. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-w9n2kgjk.js +140 -0
  118. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-yjbp9r76.js +142 -0
  119. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-ztb3cjfh.js +3 -0
  120. package/dist/plugin-runtime/node_modules/@cline/core/dist/index.js +1 -0
  121. package/dist/plugin-runtime/node_modules/@cline/core/dist/jiti-static-kj4rdeey.js +473 -0
  122. package/dist/plugin-runtime/node_modules/@cline/core/dist/jiti-y9tt7gmq.js +1 -0
  123. package/dist/plugin-runtime/node_modules/@cline/core/dist/langfuse-stream-telemetry-bg81k3qh.js +1 -0
  124. package/dist/plugin-runtime/node_modules/@cline/core/dist/langfuse-telemetry-tkbfbx5w.js +1 -0
  125. package/dist/plugin-runtime/node_modules/@cline/core/dist/mistral-mkw95amh.js +1 -0
  126. package/dist/plugin-runtime/node_modules/@cline/core/dist/multipart-parser-9z19cm6q.js +2 -0
  127. package/dist/plugin-runtime/node_modules/@cline/core/dist/ollama-sjp09b7p.js +1 -0
  128. package/dist/plugin-runtime/node_modules/@cline/core/dist/openai-1eyn4hw0.js +1 -0
  129. package/dist/plugin-runtime/node_modules/@cline/core/dist/openai-compatible-f99c7syq.js +1 -0
  130. package/dist/plugin-runtime/node_modules/@cline/core/dist/orchestration-embedding-model-strategy-GT27AFII-19936r1a.js +1 -0
  131. package/dist/plugin-runtime/node_modules/@cline/core/dist/orchestration-language-model-strategy-YEQPUCOT-eavx3zc3.js +1 -0
  132. package/dist/plugin-runtime/node_modules/@cline/core/dist/services/feature-flags/posthog.js +2 -0
  133. package/dist/plugin-runtime/node_modules/@cline/core/dist/services/telemetry/index.js +1 -0
  134. package/dist/plugin-runtime/node_modules/@cline/core/dist/token-04d0mwe8.js +1 -0
  135. package/dist/plugin-runtime/node_modules/@cline/core/dist/token-util-mt7pvm61.js +1 -0
  136. package/dist/plugin-runtime/node_modules/@cline/core/dist/vertex-6armtc3s.js +1 -0
  137. package/dist/plugin-runtime/node_modules/@cline/core/package.json +1 -0
  138. package/dist/plugin-runtime/node_modules/@cline/llms/dist/index.browser.js +16 -0
  139. package/dist/plugin-runtime/node_modules/@cline/llms/dist/index.js +1 -0
  140. package/dist/plugin-runtime/node_modules/@cline/llms/package.json +1 -0
  141. package/dist/plugin-runtime/node_modules/@cline/sdk/dist/index.js +1 -0
  142. package/dist/plugin-runtime/node_modules/@cline/sdk/package.json +1 -0
  143. package/dist/plugin-runtime/node_modules/@cline/shared/dist/automation/index.js +57 -0
  144. package/dist/plugin-runtime/node_modules/@cline/shared/dist/db/index.js +127 -0
  145. package/dist/plugin-runtime/node_modules/@cline/shared/dist/index.browser.js +110 -0
  146. package/dist/plugin-runtime/node_modules/@cline/shared/dist/index.js +1 -0
  147. package/dist/plugin-runtime/node_modules/@cline/shared/dist/node.js +1 -0
  148. package/dist/plugin-runtime/node_modules/@cline/shared/dist/remote-config/index.js +68 -0
  149. package/dist/plugin-runtime/node_modules/@cline/shared/dist/storage/index.js +1 -0
  150. package/dist/plugin-runtime/node_modules/@cline/shared/dist/types/index.js +1 -0
  151. package/dist/plugin-runtime/node_modules/@cline/shared/package.json +1 -0
  152. package/dist/plugin-runtime/package.json +1 -0
  153. package/dist/{extensions → plugin-runtime}/plugin-sandbox-bootstrap.js +129 -129
  154. package/dist/remote/remote-environments.d.ts +1 -0
  155. package/dist/runtime/config/agent-runtime-config-builder.d.ts +2 -0
  156. package/dist/runtime/host/local-runtime-host.d.ts +10 -0
  157. package/dist/runtime/host/runtime-host.d.ts +6 -0
  158. package/dist/runtime/orchestration/runtime-oauth-token-manager.d.ts +3 -0
  159. package/dist/runtime/orchestration/session-runtime-orchestrator.d.ts +10 -1
  160. package/dist/runtime/orchestration/session-runtime.d.ts +2 -0
  161. package/dist/runtime/tools/subprocess-sandbox.d.ts +22 -0
  162. package/dist/services/cloud-handoff/git-preparation.d.ts +22 -0
  163. package/dist/services/global-settings.d.ts +6 -0
  164. package/dist/services/llms/cline-recommended-models.d.ts +2 -0
  165. package/dist/services/local-runtime-bootstrap.d.ts +1 -0
  166. package/dist/services/plugin-command-api.d.ts +47 -0
  167. package/dist/services/plugin-commands.d.ts +25 -27
  168. package/dist/services/skills-cli.d.ts +2 -0
  169. package/dist/services/telemetry/core-events.d.ts +26 -0
  170. package/dist/services/telemetry/index.js +1 -1
  171. package/dist/services/telemetry/run-health.d.ts +40 -0
  172. package/dist/services/telemetry/stall-signals.d.ts +12 -0
  173. package/dist/types/config.d.ts +1 -0
  174. package/dist/types/session.d.ts +7 -0
  175. package/package.json +6 -5
@@ -0,0 +1,39 @@
1
+ import{vy,xc}from"./index-brjxtvsh.js";import{Bw,Oi}from"./index-ztb3cjfh.js";import{D,F,we,pt,b,H,Q,I,Ci,vn,ia,ke,it,j,gp,At,Vt,Kt,Pi,We,Di,Ee,nt,fe,Ae,Do,C,Ce,Nr,Ls,dt,so,Pe,ut,nn,Qe,u,l,yt,T,O,G,M,ee,qe,oe,ze,E,te,Ye}from"./index-w9n2kgjk.js";import{v,i,c,e,n,r,m,le,o,t,ae,p,d,s,a,Fe}from"./index-edf1hmcw.js";var ir=i(function(ry,Ys){var kn=Object.prototype.hasOwnProperty,Ks=Object.prototype.toString,{defineProperty:$s,getOwnPropertyDescriptor:Hs}=Object,Bs=function(f){if(typeof Array.isArray==="function")return Array.isArray(f);return Ks.call(f)==="[object Array]"},Vs=function(f){if(!f||Ks.call(f)!=="[object Object]")return!1;var g=kn.call(f,"constructor"),y=f.constructor&&f.constructor.prototype&&kn.call(f.constructor.prototype,"isPrototypeOf");if(f.constructor&&!g&&!y)return!1;var _;for(_ in f);return typeof _>"u"||kn.call(f,_)},Ws=function(f,g){if($s&&g.name==="__proto__")$s(f,g.name,{enumerable:!0,configurable:!0,value:g.newValue,writable:!0});else f[g.name]=g.newValue},Js=function(f,g){if(g==="__proto__"){if(!kn.call(f,g))return;else if(Hs)return Hs(f,g).value}return f[g]};Ys.exports=function h(){var f,g,y,_,w,A,S=arguments[0],k=1,V=arguments.length,P=!1;if(typeof S==="boolean")P=S,S=arguments[1]||{},k=2;if(S==null||typeof S!=="object"&&typeof S!=="function")S={};for(;k<V;++k)if(f=arguments[k],f!=null){for(g in f)if(y=Js(S,g),_=Js(f,g),S!==_){if(P&&_&&(Vs(_)||(w=Bs(_)))){if(w)w=!1,A=y&&Bs(y)?y:[];else A=y&&Vs(y)?y:{};Ws(S,{name:g,newValue:h(P,A,_)})}else if(typeof _<"u")Ws(S,{name:g,newValue:_})}}return S}});var zs=i(function(sy,ru){ru.exports={name:"gaxios",version:"8.3.2",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/cjs/src","build/esm/src","build/esm/package.json","!build/**/*.map"],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"}},"./build/src/common":{import:"./build/esm/src/common.js",require:"./build/cjs/src/common.js"},"./package.json":"./package.json"},repository:{type:"git",directory:"core/packages/gaxios",url:"https://github.com/googleapis/google-cloud-node.git"},keywords:["google"],engines:{node:">=22"},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":"^6.0.0","jsdoc-region-tag":"^5.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",scripts:{lint:"gts check --no-inline-config",test:"node ../../../bin/run-test.cjs 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",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"}}});var Qs=i(function(iy,Xs){var su=zs();Xs.exports={pkg:su}});var cr=i(function(Et){var ei=Et&&Et.__importDefault||function(h){return h&&h.__esModule?h:{default:h}};Object.defineProperty(Et,"__esModule",{value:!0});Et.GaxiosError=Et.GAXIOS_ERROR_SYMBOL=void 0;Et.defaultErrorRedactor=ti;var Zs=ei(ir()),iu=ei(Qs()),or=iu.default.pkg;Et.GAXIOS_ERROR_SYMBOL=Symbol.for(`${or.name}-gaxios-error`);class ar extends Error{config;response;code;status;error;[Et.GAXIOS_ERROR_SYMBOL]=or.version;static[Symbol.hasInstance](h){if(h&&typeof h==="object"&&Et.GAXIOS_ERROR_SYMBOL in h&&h[Et.GAXIOS_ERROR_SYMBOL]===or.version)return!0;return Function.prototype[Symbol.hasInstance].call(ar,h)}constructor(h,f,g,y){super(h,{cause:y});if(this.config=f,this.response=g,this.error=y instanceof Error?y:void 0,this.config=(0,Zs.default)(!0,{},f),this.response)this.response.config=(0,Zs.default)(!0,{},this.response.config);if(this.response){try{this.response.data=ou(this.config.responseType,this.response?.bodyUsed?this.response?.data:void 0)}catch{}this.status=this.response.status}if(y instanceof DOMException)this.code=y.name;else if(y&&typeof y==="object"&&"code"in y&&(typeof y.code==="string"||typeof y.code==="number"))this.code=y.code}static extractAPIErrorFromResponse(h,f="The request failed"){let g=f;if(typeof h.data==="string")g=h.data;if(h.data&&typeof h.data==="object"&&"error"in h.data&&h.data.error&&!h.ok){if(typeof h.data.error==="string")return{message:h.data.error,code:h.status,status:h.statusText};if(typeof h.data.error==="object"){g="message"in h.data.error&&typeof h.data.error.message==="string"?h.data.error.message:g;let y="status"in h.data.error&&typeof h.data.error.status==="string"?h.data.error.status:h.statusText,_="code"in h.data.error&&typeof h.data.error.code==="number"?h.data.error.code:h.status;if("errors"in h.data.error&&Array.isArray(h.data.error.errors)){let w=[];for(let A of h.data.error.errors)if(typeof A==="object"&&"message"in A&&typeof A.message==="string")w.push(A.message);return Object.assign({message:w.join(`
2
+ `)||g,code:_,status:y},h.data.error)}return Object.assign({message:g,code:_,status:y},h.data.error)}}return{message:g,code:h.status,status:h.statusText}}}Et.GaxiosError=ar;function ou(h,f){switch(h){case"stream":return f;case"json":return JSON.parse(JSON.stringify(f));case"arraybuffer":return JSON.parse(Buffer.from(f).toString("utf8"));case"blob":return JSON.parse(f.text());default:return f}}function ti(h){function g(w){if(!w)return;w.forEach((A,S)=>{if(/^authentication$/i.test(S)||/^authorization$/i.test(S)||/secret/i.test(S))w.set(S,"<<REDACTED> - See `errorRedactor` option in `gaxios` for configuration>.")})}function y(w,A){if(typeof w==="object"&&w!==null&&typeof w[A]==="string"){let S=w[A];if(/grant_type=/i.test(S)||/assertion=/i.test(S)||/secret/i.test(S))w[A]="<<REDACTED> - See `errorRedactor` option in `gaxios` for configuration>."}}function _(w){if(!w||typeof w!=="object")return;else if(w instanceof FormData||w instanceof URLSearchParams||"forEach"in w&&"set"in w)w.forEach((A,S)=>{if(["grant_type","assertion"].includes(S)||/secret/.test(S))w.set(S,"<<REDACTED> - See `errorRedactor` option in `gaxios` for configuration>.")});else{if("grant_type"in w)w.grant_type="<<REDACTED> - See `errorRedactor` option in `gaxios` for configuration>.";if("assertion"in w)w.assertion="<<REDACTED> - See `errorRedactor` option in `gaxios` for configuration>.";if("client_secret"in w)w.client_secret="<<REDACTED> - See `errorRedactor` option in `gaxios` for configuration>."}}if(h.config){if(g(h.config.headers),y(h.config,"data"),_(h.config.data),y(h.config,"body"),_(h.config.body),h.config.url.searchParams.has("token"))h.config.url.searchParams.set("token","<<REDACTED> - See `errorRedactor` option in `gaxios` for configuration>.");if(h.config.url.searchParams.has("client_secret"))h.config.url.searchParams.set("client_secret","<<REDACTED> - See `errorRedactor` option in `gaxios` for configuration>.")}if(h.response){if(ti({config:h.response.config}),g(h.response.headers),h.response.bodyUsed)y(h.response,"data"),_(h.response.data)}return h}});var si=i(function(ri){Object.defineProperty(ri,"__esModule",{value:!0});ri.getRetryConfig=au;async function au(h){let f=ni(h);if(!h||!h.config||!f&&!h.config.retry)return{shouldRetry:!1};f=f||{},f.currentRetryAttempt=f.currentRetryAttempt||0,f.retry=f.retry===void 0||f.retry===null?3:f.retry,f.httpMethodsToRetry=f.httpMethodsToRetry||["GET","HEAD","PUT","OPTIONS","DELETE"],f.noResponseRetries=f.noResponseRetries===void 0||f.noResponseRetries===null?2:f.noResponseRetries,f.retryDelayMultiplier=f.retryDelayMultiplier?f.retryDelayMultiplier:2,f.timeOfFirstRequest=f.timeOfFirstRequest?f.timeOfFirstRequest:Date.now(),f.totalTimeout=f.totalTimeout?f.totalTimeout:Number.MAX_SAFE_INTEGER,f.maxRetryDelay=f.maxRetryDelay?f.maxRetryDelay:Number.MAX_SAFE_INTEGER;let g=[[100,199],[408,408],[429,429],[500,599]];if(f.statusCodesToRetry=f.statusCodesToRetry||g,h.config.retryConfig=f,!await(f.shouldRetry||cu)(h))return{shouldRetry:!1,config:h.config};let _=lu(f);h.config.retryConfig.currentRetryAttempt+=1;let w=f.retryBackoff?f.retryBackoff(h,_):new Promise((A)=>{setTimeout(A,_)});if(f.onRetryAttempt)await f.onRetryAttempt(h);return await w,{shouldRetry:!0,config:h.config}}function cu(h){let f=ni(h),g=h.code==="TimeoutError"||h.config?.signal?.reason?.name==="TimeoutError";if(h.config?.signal?.aborted&&!g||h.code==="AbortError"&&!g)return!1;if(!f||f.retry===0)return!1;if(!h.response&&(f.currentRetryAttempt||0)>=f.noResponseRetries)return!1;if(!f.httpMethodsToRetry||!f.httpMethodsToRetry.includes(h.config.method?.toUpperCase()||"GET"))return!1;if(h.response&&h.response.status){let y=!1;for(let[_,w]of f.statusCodesToRetry){let A=h.response.status;if(A>=_&&A<=w){y=!0;break}}if(!y)return!1}if(f.currentRetryAttempt=f.currentRetryAttempt||0,f.currentRetryAttempt>=f.retry)return!1;return!0}function ni(h){if(h&&h.config&&h.config.retryConfig)return h.config.retryConfig;return}function lu(h){let g=(h.currentRetryAttempt?0:h.retryDelay??100)+(Math.pow(h.retryDelayMultiplier,h.currentRetryAttempt)-1)/2*1000,y=h.totalTimeout-(Date.now()-h.timeOfFirstRequest);return Math.min(g,y,h.maxRetryDelay)}});var lr=i(function(oi){Object.defineProperty(oi,"__esModule",{value:!0});oi.GaxiosInterceptorManager=void 0;class ii extends Set{}oi.GaxiosInterceptorManager=ii});var li=i(function(tn){var du=tn&&tn.__importDefault||function(h){return h&&h.__esModule?h:{default:h}},en;Object.defineProperty(tn,"__esModule",{value:!0});tn.Gaxios=void 0;var hu=du(ir()),pu=c("https"),Gt=cr(),fu=si(),Rt=c("stream"),ci=lr(),gu=async()=>globalThis.crypto?.randomUUID()||(await import("crypto")).randomUUID(),mu=204;class ur{agentCache=new Map;defaults;interceptors;constructor(h){this.defaults=h||{},this.interceptors={request:new ci.GaxiosInterceptorManager,response:new ci.GaxiosInterceptorManager}}fetch(...h){let f=h[0],g=h[1],y=void 0,_=new Headers;if(typeof f==="string")y=new URL(f);else if(f instanceof URL)y=f;else if(f&&f.url)y=new URL(f.url);if(f&&typeof f==="object"&&"headers"in f)en.mergeHeaders(_,f.headers);if(g)en.mergeHeaders(_,new Headers(g.headers));if(typeof f==="object"&&!(f instanceof URL))return this.request({...g,...f,headers:_,url:y});else return this.request({...g,headers:_,url:y})}async request(h={}){let f=await this.#r(h);return f=await this.#t(f),this.#n(this._request(f))}async _defaultAdapter(h){let f=h.fetchImplementation||this.defaults.fetchImplementation||await en.#d(),g={...h};delete g.data;let y=await f(h.url,g),_=await this.getResponseData(h,y);if(!Object.getOwnPropertyDescriptor(y,"data")?.configurable)Object.defineProperties(y,{data:{configurable:!0,writable:!0,enumerable:!0,value:_}});return Object.assign(y,{config:h,data:_})}async _request(h){try{let f;if(h.adapter)f=await h.adapter(h,this._defaultAdapter.bind(this));else f=await this._defaultAdapter(h);if(!h.validateStatus(f.status)){if(h.responseType==="stream"){let y=[];for await(let _ of f.data)y.push(_);f.data=Buffer.concat(y.map((_)=>typeof _==="string"?Buffer.from(_):_)).toString("utf8")}let g=Gt.GaxiosError.extractAPIErrorFromResponse(f,`Request failed with status code ${f.status}`);throw new Gt.GaxiosError(g?.message,h,f,g)}return f}catch(f){let g;if(f instanceof Gt.GaxiosError)g=f;else if(f instanceof Error)g=new Gt.GaxiosError(f.message,h,void 0,f);else if(h.signal?.aborted)g=new Gt.GaxiosError(`The operation was aborted: ${f}`,h,void 0,f),g.code="AbortError";else g=new Gt.GaxiosError("Unexpected Gaxios Error",h,void 0,f);if(!g.response&&h.signal?.aborted&&h.signal.reason?.name==="TimeoutError"){if(g.code="TimeoutError",!/timeout|timed out/i.test(g.message))g.message="The operation was aborted due to timeout"}else if(!g.response&&h.signal?.aborted&&g.code!=="TimeoutError")g.code||="AbortError";let{shouldRetry:y,config:_}=await fu.getRetryConfig(g);if(y&&_){if(g.config.retryConfig.currentRetryAttempt=_.retryConfig.currentRetryAttempt,h.retryConfig=g.config?.retryConfig,typeof g.config?.timeout==="number")h.timeout=g.config.timeout;return this.#o(h),this._request(h)}if(h.errorRedactor)h.errorRedactor(g);throw g}}async getResponseData(h,f){if(f.status===mu)return"";if(h.maxContentLength&&f.headers.has("content-length")&&h.maxContentLength<Number.parseInt(f.headers?.get("content-length")||""))throw new Gt.GaxiosError("Response's `Content-Length` is over the limit.",h,Object.assign(f,{config:h}));switch(h.responseType){case"stream":return f.body;case"json":{let g=await f.text();try{return JSON.parse(g)}catch{return g}}case"arraybuffer":return f.arrayBuffer();case"blob":return f.blob();case"text":return f.text();default:return this.getResponseDataFromContentType(f)}}#e(h,f=[]){let g=new URL(h),y=[...f],_=(process.env.NO_PROXY??process.env.no_proxy)?.split(",")||[];for(let w of _)y.push(w.trim());for(let w of y)if(w instanceof RegExp){if(w.test(g.toString()))return!1}else if(w instanceof URL){if(w.origin===g.origin)return!1}else if(w.startsWith("*.")||w.startsWith(".")){let A=w.replace(/^\*\./,".");if(g.hostname.endsWith(A))return!1}else if(w===g.origin||w===g.hostname||w===g.href)return!1;return!0}async#t(h){let f=Promise.resolve(h);for(let g of this.interceptors.request.values())if(g)f=f.then(g.resolved,g.rejected);return f}async#n(h){let f=Promise.resolve(h);for(let g of this.interceptors.response.values())if(g)f=f.then(g.resolved,g.rejected);return f}async#r(h){let f=new Headers(this.defaults.headers);en.mergeHeaders(f,h.headers);let g=(0,hu.default)(!0,{},this.defaults,h);if(!g.url)throw Error("URL is required.");if(g.baseURL)g.url=new URL(g.url,g.baseURL);if(g.url=new URL(g.url),g.params)if(g.paramsSerializer){let w=g.paramsSerializer(g.params);if(w.startsWith("?"))w=w.slice(1);let A=g.url.toString().includes("?")?"&":"?";g.url=g.url+A+w}else{let w=g.url instanceof URL?g.url:new URL(g.url);for(let[A,S]of new URLSearchParams(g.params))w.searchParams.append(A,S);g.url=w}if(typeof h.maxContentLength==="number")g.size=h.maxContentLength;if(typeof h.maxRedirects==="number")g.follow=h.maxRedirects;let y=typeof g.data==="string"||g.data instanceof ArrayBuffer||g.data instanceof Blob||globalThis.File&&g.data instanceof File||g.data instanceof FormData||g.data instanceof Rt.Readable||g.data instanceof ReadableStream||g.data instanceof String||g.data instanceof URLSearchParams||ArrayBuffer.isView(g.data)||["Blob","File","FormData"].includes(g.data?.constructor?.name||"");if(g.multipart?.length){let w=await gu();f.set("content-type",`multipart/related; boundary=${w}`),g.body=Rt.Readable.from(this.getMultipartRequest(g.multipart,w))}else if(y)g.body=g.data;else if(typeof g.data==="object")if(f.get("Content-Type")==="application/x-www-form-urlencoded")g.body=g.paramsSerializer?g.paramsSerializer(g.data):new URLSearchParams(g.data);else{if(!f.has("content-type"))f.set("content-type","application/json");g.body=JSON.stringify(g.data)}else if(g.data)g.body=g.data;if(g.validateStatus=g.validateStatus||this.validateStatus,g.responseType=g.responseType||"unknown",!f.has("accept")&&g.responseType==="json")f.set("accept","application/json");let _=g.proxy||process?.env?.HTTPS_PROXY||process?.env?.https_proxy||process?.env?.HTTP_PROXY||process?.env?.http_proxy;if(g.agent);else if(_&&this.#e(g.url,g.noProxy)){let w=await en.#l();if(this.agentCache.has(_))g.agent=this.agentCache.get(_);else g.agent=new w(_,{cert:g.cert,key:g.key}),this.agentCache.set(_,g.agent)}else if(g.cert&&g.key)if(this.agentCache.has(g.key))g.agent=this.agentCache.get(g.key);else g.agent=new pu.Agent({cert:g.cert,key:g.key}),this.agentCache.set(g.key,g.agent);if(typeof g.errorRedactor!=="function"&&g.errorRedactor!==!1)g.errorRedactor=Gt.defaultErrorRedactor;if(g.body&&!("duplex"in g))g.duplex="half";return this.#o(g),Object.assign(g,{headers:f,url:g.url instanceof URL?g.url:new URL(g.url)})}#s=new WeakMap;#o(h){if(h.timeout){if(!this.#s.has(h))this.#s.set(h,h.signal??void 0);let f=this.#s.get(h),g=AbortSignal.timeout(h.timeout);if(f)h.signal=AbortSignal.any([f,g]);else h.signal=g}}validateStatus(h){return h>=200&&h<300}async getResponseDataFromContentType(h){let f=h.headers.get("Content-Type");if(f===null)return h.text();if(f=f.toLowerCase(),f.includes("application/json")){let g=await h.text();try{g=JSON.parse(g)}catch{}return g}else if(f.match(/^text\//))return h.text();else return h.blob()}async*getMultipartRequest(h,f){let g=`--${f}--`;for(let y of h){let _=y.headers.get("Content-Type")||"application/octet-stream";if(yield`--${f}\r
3
+ Content-Type: ${_}\r
4
+ \r
5
+ `,typeof y.content==="string")yield y.content;else yield*y.content;yield`\r
6
+ `}yield g}static#a;static#i;static#c;static async#l(){return this.#a||=(await import("./index-bnwxdgvg.js").then((m)=>v(m.default))).HttpsProxyAgent,this.#a}static#u(){return async(h,f)=>{let g=f?{...f}:void 0;if(g){let w=g.agent;if(w?.proxy)g.proxy=w.proxy.toString();else delete g.proxy;let A=g.cert??w?.connectOpts?.cert,S=g.key??w?.connectOpts?.key;if(A&&S)g.tls={...g.tls,cert:A,key:S}}let y=g;if(y?.body&&typeof y.body==="object"&&typeof y.body.pipe==="function"&&typeof Rt.Readable.toWeb==="function"&&(typeof ReadableStream>"u"||!(y.body instanceof ReadableStream))){let w;if(y.body instanceof Rt.Readable&&!y.body.readableObjectMode)w=y.body;else{let A=new Rt.PassThrough,S=y.body;Rt.pipeline(S,A,()=>{}),w=A}y={...y,body:Rt.Readable.toWeb(w)}}let _;try{_=await globalThis.fetch(h,y)}catch(w){let A=w;if(A?.code==="ConnectionRefused"||A?.code==="FailedToOpenSocket")A.code="ECONNREFUSED";else if(A?.code==="ConnectionReset"||A?.code==="ConnectionClosed")A.code="ECONNRESET";if(!(w instanceof Error)&&w&&typeof w==="object"&&!f?.signal?.aborted)throw Object.assign(Error(A.message||A.code||"Error"),w);throw w}if(_?.body&&typeof Rt.Readable.fromWeb==="function"&&!(_.body instanceof Rt.Readable)){let w,A=_.body,S=_.text.bind(_),k=_.json.bind(_),V=_.arrayBuffer.bind(_),P=_.blob.bind(_),ne=async()=>{let Z=[];for await(let K of w)Z.push(Buffer.isBuffer(K)?K:Buffer.from(K));return Buffer.concat(Z)};Object.defineProperty(_,"body",{get(){return w||=Rt.Readable.fromWeb(A),w},configurable:!0,enumerable:!0}),_.text=async()=>{if(!w)return S();return(await ne()).toString("utf8")},_.json=async()=>{if(!w)return k();return JSON.parse(await _.text())},_.arrayBuffer=async()=>{if(!w)return V();let Z=await ne();return Z.buffer.slice(Z.byteOffset,Z.byteOffset+Z.byteLength)},_.blob=async()=>{if(!w)return P();let Z=await ne(),K=_.headers?.get?.("content-type")??"";return new Blob([Z],K?{type:K}:void 0)}}return _}}static async#d(){if(typeof window<"u"&&!!window)return this.#i||=window.fetch,this.#i;if("Bun"in globalThis&&typeof globalThis.fetch==="function")return this.#c||=this.#u(),this.#c;return this.#i||=(await import("./index-agemt17a.js")).default,this.#i}static mergeHeaders(h,...f){h=h instanceof Headers?h:new Headers(h);for(let g of f)(g instanceof Headers?g:new Headers(g)).forEach((_,w)=>{w==="set-cookie"?h.append(w,_):h.set(w,_)});return h}}tn.Gaxios=ur;en=ur});var ct=i(function(gt){var yu=gt&&gt.__createBinding||(Object.create?function(h,f,g,y){if(y===void 0)y=g;var _=Object.getOwnPropertyDescriptor(f,g);if(!_||("get"in _?!f.__esModule:_.writable||_.configurable))_={enumerable:!0,get:function(){return f[g]}};Object.defineProperty(h,y,_)}:function(h,f,g,y){if(y===void 0)y=g;h[y]=f[g]}),_u=gt&&gt.__exportStar||function(h,f){for(var g in h)if(g!=="default"&&!Object.prototype.hasOwnProperty.call(f,g))yu(f,h,g)};Object.defineProperty(gt,"__esModule",{value:!0});gt.instance=gt.Gaxios=gt.GaxiosError=void 0;gt.request=wu;var ui=li();Object.defineProperty(gt,"Gaxios",{enumerable:!0,get:function(){return ui.Gaxios}});var Tu=cr();Object.defineProperty(gt,"GaxiosError",{enumerable:!0,get:function(){return Tu.GaxiosError}});_u(lr(),gt);gt.instance=new ui.Gaxios;async function wu(h){return gt.instance.request(h)}});var dr=i(function(di,xn){(function(h){var f,g=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,{ceil:y,floor:_}=Math,w="[BigNumber Error] ",A=w+"Number primitive has more than 15 significant digits: ",S=100000000000000,k=14,V=9007199254740991,P=[1,10,100,1000,1e4,1e5,1e6,1e7,1e8,1e9,10000000000,100000000000,1000000000000,10000000000000],ne=1e7,Z=1e9;function K(U){var ue,ye,ve,_e=ge.prototype={constructor:ge,toString:null,valueOf:null},Ne=new ge(1),Re=20,Ie=4,Be=-7,je=21,Ve=-1e7,Ue=1e7,Je=!1,Ze=1,tt=0,ot={prefix:"",groupSize:3,secondaryGroupSize:0,groupSeparator:",",decimalSeparator:".",fractionGroupSize:0,fractionGroupSeparator:" ",suffix:""},et="0123456789abcdefghijklmnopqrstuvwxyz",mt=!0;function ge(x,N){var R,J,Y,se,pe,W,z,ce,ie=this;if(!(ie instanceof ge))return new ge(x,N);if(N==null){if(x&&x._isBigNumber===!0){if(ie.s=x.s,!x.c||x.e>Ue)ie.c=ie.e=null;else if(x.e<Ve)ie.c=[ie.e=0];else ie.e=x.e,ie.c=x.c.slice();return}if((W=typeof x=="number")&&x*0==0){if(ie.s=1/x<0?(x=-x,-1):1,x===~~x){for(se=0,pe=x;pe>=10;pe/=10,se++);if(se>Ue)ie.c=ie.e=null;else ie.e=se,ie.c=[x];return}ce=String(x)}else{if(!g.test(ce=String(x)))return ve(ie,ce,W);ie.s=ce.charCodeAt(0)==45?(ce=ce.slice(1),-1):1}if((se=ce.indexOf("."))>-1)ce=ce.replace(".","");if((pe=ce.search(/e/i))>0){if(se<0)se=pe;se+=+ce.slice(pe+1),ce=ce.substring(0,pe)}else if(se<0)se=ce.length}else{if(L(N,2,et.length,"Base"),N==10&&mt)return ie=new ge(x),Me(ie,Re+ie.e+1,Ie);if(ce=String(x),W=typeof x=="number"){if(x*0!=0)return ve(ie,ce,W,N);if(ie.s=1/x<0?(ce=ce.slice(1),-1):1,ge.DEBUG&&ce.replace(/^0\.0*|\./,"").length>15)throw Error(A+x)}else ie.s=ce.charCodeAt(0)===45?(ce=ce.slice(1),-1):1;R=et.slice(0,N),se=pe=0;for(z=ce.length;pe<z;pe++)if(R.indexOf(J=ce.charAt(pe))<0){if(J=="."){if(pe>se){se=z;continue}}else if(!Y){if(ce==ce.toUpperCase()&&(ce=ce.toLowerCase())||ce==ce.toLowerCase()&&(ce=ce.toUpperCase())){Y=!0,pe=-1,se=0;continue}}return ve(ie,String(x),W,N)}if(W=!1,ce=ye(ce,N,10,ie.s),(se=ce.indexOf("."))>-1)ce=ce.replace(".","");else se=ce.length}for(pe=0;ce.charCodeAt(pe)===48;pe++);for(z=ce.length;ce.charCodeAt(--z)===48;);if(ce=ce.slice(pe,++z)){if(z-=pe,W&&ge.DEBUG&&z>15&&(x>V||x!==_(x)))throw Error(A+ie.s*x);if((se=se-pe-1)>Ue)ie.c=ie.e=null;else if(se<Ve)ie.c=[ie.e=0];else{if(ie.e=se,ie.c=[],pe=(se+1)%k,se<0)pe+=k;if(pe<z){if(pe)ie.c.push(+ce.slice(0,pe));for(z-=k;pe<z;)ie.c.push(+ce.slice(pe,pe+=k));pe=k-(ce=ce.slice(pe)).length}else pe-=z;for(;pe--;ce+="0");ie.c.push(+ce)}}else ie.c=[ie.e=0]}ge.clone=K,ge.ROUND_UP=0,ge.ROUND_DOWN=1,ge.ROUND_CEIL=2,ge.ROUND_FLOOR=3,ge.ROUND_HALF_UP=4,ge.ROUND_HALF_DOWN=5,ge.ROUND_HALF_EVEN=6,ge.ROUND_HALF_CEIL=7,ge.ROUND_HALF_FLOOR=8,ge.EUCLID=9,ge.config=ge.set=function(x){var N,R;if(x!=null)if(typeof x=="object"){if(x.hasOwnProperty(N="DECIMAL_PLACES"))R=x[N],L(R,0,Z,N),Re=R;if(x.hasOwnProperty(N="ROUNDING_MODE"))R=x[N],L(R,0,8,N),Ie=R;if(x.hasOwnProperty(N="EXPONENTIAL_AT"))if(R=x[N],R&&R.pop)L(R[0],-Z,0,N),L(R[1],0,Z,N),Be=R[0],je=R[1];else L(R,-Z,Z,N),Be=-(je=R<0?-R:R);if(x.hasOwnProperty(N="RANGE"))if(R=x[N],R&&R.pop)L(R[0],-Z,-1,N),L(R[1],1,Z,N),Ve=R[0],Ue=R[1];else if(L(R,-Z,Z,N),R)Ve=-(Ue=R<0?-R:R);else throw Error(w+N+" cannot be zero: "+R);if(x.hasOwnProperty(N="CRYPTO"))if(R=x[N],R===!!R)if(R)if(typeof crypto<"u"&&crypto&&(crypto.getRandomValues||crypto.randomBytes))Je=R;else throw Je=!R,Error(w+"crypto unavailable");else Je=R;else throw Error(w+N+" not true or false: "+R);if(x.hasOwnProperty(N="MODULO_MODE"))R=x[N],L(R,0,9,N),Ze=R;if(x.hasOwnProperty(N="POW_PRECISION"))R=x[N],L(R,0,Z,N),tt=R;if(x.hasOwnProperty(N="FORMAT"))if(R=x[N],typeof R=="object")ot=R;else throw Error(w+N+" not an object: "+R);if(x.hasOwnProperty(N="ALPHABET"))if(R=x[N],typeof R=="string"&&!/^.?$|[+\-.\s]|(.).*\1/.test(R))mt=R.slice(0,10)=="0123456789",et=R;else throw Error(w+N+" invalid: "+R)}else throw Error(w+"Object expected: "+x);return{DECIMAL_PLACES:Re,ROUNDING_MODE:Ie,EXPONENTIAL_AT:[Be,je],RANGE:[Ve,Ue],CRYPTO:Je,MODULO_MODE:Ze,POW_PRECISION:tt,FORMAT:ot,ALPHABET:et}},ge.isBigNumber=function(x){if(!x||x._isBigNumber!==!0)return!1;if(!ge.DEBUG)return!0;var N,R,{c:J,e:Y,s:se}=x;e:if({}.toString.call(J)=="[object Array]"){if((se===1||se===-1)&&Y>=-Z&&Y<=Z&&Y===_(Y)){if(J[0]===0){if(Y===0&&J.length===1)return!0;break e}if(N=(Y+1)%k,N<1)N+=k;if(String(J[0]).length==N){for(N=0;N<J.length;N++)if(R=J[N],R<0||R>=S||R!==_(R))break e;if(R!==0)return!0}}}else if(J===null&&Y===null&&(se===null||se===1||se===-1))return!0;throw Error(w+"Invalid BigNumber: "+x)},ge.maximum=ge.max=function(){return at(arguments,-1)},ge.minimum=ge.min=function(){return at(arguments,1)},ge.random=function(){var x=9007199254740992,N=Math.random()*x&2097151?function(){return _(Math.random()*x)}:function(){return(Math.random()*1073741824|0)*8388608+(Math.random()*8388608|0)};return function(R){var J,Y,se,pe,W,z=0,ce=[],ie=new ge(Ne);if(R==null)R=Re;else L(R,0,Z);if(pe=y(R/k),Je)if(crypto.getRandomValues){J=crypto.getRandomValues(new Uint32Array(pe*=2));for(;z<pe;)if(W=J[z]*131072+(J[z+1]>>>11),W>=9000000000000000)Y=crypto.getRandomValues(new Uint32Array(2)),J[z]=Y[0],J[z+1]=Y[1];else ce.push(W%100000000000000),z+=2;z=pe/2}else if(crypto.randomBytes){J=crypto.randomBytes(pe*=7);for(;z<pe;)if(W=(J[z]&31)*281474976710656+J[z+1]*1099511627776+J[z+2]*4294967296+J[z+3]*16777216+(J[z+4]<<16)+(J[z+5]<<8)+J[z+6],W>=9000000000000000)crypto.randomBytes(7).copy(J,z);else ce.push(W%100000000000000),z+=7;z=pe/7}else throw Je=!1,Error(w+"crypto unavailable");if(!Je){for(;z<pe;)if(W=N(),W<9000000000000000)ce[z++]=W%100000000000000}if(pe=ce[--z],R%=k,pe&&R)W=P[k-R],ce[z]=_(pe/W)*W;for(;ce[z]===0;ce.pop(),z--);if(z<0)ce=[se=0];else{for(se=-1;ce[0]===0;ce.splice(0,1),se-=k);for(z=1,W=ce[0];W>=10;W/=10,z++);if(z<k)se-=k-z}return ie.e=se,ie.c=ce,ie}}(),ge.sum=function(){var x=1,N=arguments,R=new ge(N[0]);for(;x<N.length;)R=R.plus(N[x++]);return R},ye=function(){var x="0123456789";function N(R,J,Y,se){var pe,W=[0],z,ce=0,ie=R.length;for(;ce<ie;){for(z=W.length;z--;W[z]*=J);W[0]+=se.indexOf(R.charAt(ce++));for(pe=0;pe<W.length;pe++)if(W[pe]>Y-1){if(W[pe+1]==null)W[pe+1]=0;W[pe+1]+=W[pe]/Y|0,W[pe]%=Y}}return W.reverse()}return function(R,J,Y,se,pe){var W,z,ce,ie,me,Se,xe,Le,Ke=R.indexOf("."),st=Re,De=Ie;if(Ke>=0)ie=tt,tt=0,R=R.replace(".",""),Le=new ge(J),Se=Le.pow(R.length-Ke),tt=ie,Le.c=N(q(re(Se.c),Se.e,"0"),10,Y,x),Le.e=Le.c.length;xe=N(R,J,Y,pe?(W=et,x):(W=x,et)),ce=ie=xe.length;for(;xe[--ie]==0;xe.pop());if(!xe[0])return W.charAt(0);if(Ke<0)--ce;else Se.c=xe,Se.e=ce,Se.s=se,Se=ue(Se,Le,st,De,Y),xe=Se.c,me=Se.r,ce=Se.e;if(z=ce+st+1,Ke=xe[z],ie=Y/2,me=me||z<0||xe[z+1]!=null,me=De<4?(Ke!=null||me)&&(De==0||De==(Se.s<0?3:2)):Ke>ie||Ke==ie&&(De==4||me||De==6&&xe[z-1]&1||De==(Se.s<0?8:7)),z<1||!xe[0])R=me?q(W.charAt(1),-st,W.charAt(0)):W.charAt(0);else{if(xe.length=z,me){for(--Y;++xe[--z]>Y;)if(xe[z]=0,!z)++ce,xe=[1].concat(xe)}for(ie=xe.length;!xe[--ie];);for(Ke=0,R="";Ke<=ie;R+=W.charAt(xe[Ke++]));R=q(R,ce,W.charAt(0))}return R}}(),ue=function(){function x(J,Y,se){var pe,W,z,ce,ie=0,me=J.length,Se=Y%ne,xe=Y/ne|0;for(J=J.slice();me--;)z=J[me]%ne,ce=J[me]/ne|0,pe=xe*z+ce*Se,W=Se*z+pe%ne*ne+ie,ie=(W/se|0)+(pe/ne|0)+xe*ce,J[me]=W%se;if(ie)J=[ie].concat(J);return J}function N(J,Y,se,pe){var W,z;if(se!=pe)z=se>pe?1:-1;else for(W=z=0;W<se;W++)if(J[W]!=Y[W]){z=J[W]>Y[W]?1:-1;break}return z}function R(J,Y,se,pe){var W=0;for(;se--;)J[se]-=W,W=J[se]<Y[se]?1:0,J[se]=W*pe+J[se]-Y[se];for(;!J[0]&&J.length>1;J.splice(0,1));}return function(J,Y,se,pe,W){var z,ce,ie,me,Se,xe,Le,Ke,st,De,Ge,ht,Sn,rr,sr,Ot,hn,vt=J.s==Y.s?1:-1,ft=J.c,Xe=Y.c;if(!ft||!ft[0]||!Xe||!Xe[0])return new ge(!J.s||!Y.s||(ft?Xe&&ft[0]==Xe[0]:!Xe)?NaN:ft&&ft[0]==0||!Xe?vt*0:vt/0);if(Ke=new ge(vt),st=Ke.c=[],ce=J.e-Y.e,vt=se+ce+1,!W)W=S,ce=X(J.e/k)-X(Y.e/k),vt=vt/k|0;for(ie=0;Xe[ie]==(ft[ie]||0);ie++);if(Xe[ie]>(ft[ie]||0))ce--;if(vt<0)st.push(1),me=!0;else{if(rr=ft.length,Ot=Xe.length,ie=0,vt+=2,Se=_(W/(Xe[0]+1)),Se>1)Xe=x(Xe,Se,W),ft=x(ft,Se,W),Ot=Xe.length,rr=ft.length;Sn=Ot,De=ft.slice(0,Ot),Ge=De.length;for(;Ge<Ot;De[Ge++]=0);if(hn=Xe.slice(),hn=[0].concat(hn),sr=Xe[0],Xe[1]>=W/2)sr++;do{if(Se=0,z=N(Xe,De,Ot,Ge),z<0){if(ht=De[0],Ot!=Ge)ht=ht*W+(De[1]||0);if(Se=_(ht/sr),Se>1){if(Se>=W)Se=W-1;xe=x(Xe,Se,W),Le=xe.length,Ge=De.length;while(N(xe,De,Le,Ge)==1)Se--,R(xe,Ot<Le?hn:Xe,Le,W),Le=xe.length,z=1}else{if(Se==0)z=Se=1;xe=Xe.slice(),Le=xe.length}if(Le<Ge)xe=[0].concat(xe);if(R(De,xe,Ge,W),Ge=De.length,z==-1)while(N(Xe,De,Ot,Ge)<1)Se++,R(De,Ot<Ge?hn:Xe,Ge,W),Ge=De.length}else if(z===0)Se++,De=[0];if(st[ie++]=Se,De[0])De[Ge++]=ft[Sn]||0;else De=[ft[Sn]],Ge=1}while((Sn++<rr||De[0]!=null)&&vt--);if(me=De[0]!=null,!st[0])st.splice(0,1)}if(W==S){for(ie=1,vt=st[0];vt>=10;vt/=10,ie++);Me(Ke,se+(Ke.e=ie+ce*k-1)+1,pe,me)}else Ke.e=ce,Ke.r=+me;return Ke}}();function be(x,N,R,J){var Y,se,pe,W,z;if(R==null)R=Ie;else L(R,0,8);if(!x.c)return x.toString();if(Y=x.c[0],pe=x.e,N==null)z=re(x.c),z=J==1||J==2&&(pe<=Be||pe>=je)?he(z,pe):q(z,pe,"0");else if(x=Me(new ge(x),N,R),se=x.e,z=re(x.c),W=z.length,J==1||J==2&&(N<=se||se<=Be)){for(;W<N;z+="0",W++);z=he(z,se)}else if(N-=pe+(J===2&&se>pe),z=q(z,se,"0"),se+1>W){if(--N>0)for(z+=".";N--;z+="0");}else if(N+=se-W,N>0){if(se+1==W)z+=".";for(;N--;z+="0");}return x.s<0&&Y?"-"+z:z}function at(x,N){var R,J,Y=1,se=new ge(x[0]);for(;Y<x.length;Y++)if(J=new ge(x[Y]),!J.s||(R=de(se,J))===N||R===0&&se.s===N)se=J;return se}function rt(x,N,R){var J=1,Y=N.length;for(;!N[--Y];N.pop());for(Y=N[0];Y>=10;Y/=10,J++);if((R=J+R*k-1)>Ue)x.c=x.e=null;else if(R<Ve)x.c=[x.e=0];else x.e=R,x.c=N;return x}ve=function(){var x=/^(-?)0([xbo])(?=\w[\w.]*$)/i,N=/^([^.]+)\.$/,R=/^\.([^.]+)$/,J=/^-?(Infinity|NaN)$/,Y=/^\s*\+(?=[\w.])|^\s+|\s+$/g;return function(se,pe,W,z){var ce,ie=W?pe:pe.replace(Y,"");if(J.test(ie))se.s=isNaN(ie)?null:ie<0?-1:1;else{if(!W){if(ie=ie.replace(x,function(me,Se,xe){return ce=(xe=xe.toLowerCase())=="x"?16:xe=="b"?2:8,!z||z==ce?Se:me}),z)ce=z,ie=ie.replace(N,"$1").replace(R,"0.$1");if(pe!=ie)return new ge(ie,ce)}if(ge.DEBUG)throw Error(w+"Not a"+(z?" base "+z:"")+" number: "+pe);se.s=null}se.c=se.e=null}}();function Me(x,N,R,J){var Y,se,pe,W,z,ce,ie,me=x.c,Se=P;if(me){e:{for(Y=1,W=me[0];W>=10;W/=10,Y++);if(se=N-Y,se<0)se+=k,pe=N,z=me[ce=0],ie=_(z/Se[Y-pe-1]%10);else if(ce=y((se+1)/k),ce>=me.length)if(J){for(;me.length<=ce;me.push(0));z=ie=0,Y=1,se%=k,pe=se-k+1}else break e;else{z=W=me[ce];for(Y=1;W>=10;W/=10,Y++);se%=k,pe=se-k+Y,ie=pe<0?0:_(z/Se[Y-pe-1]%10)}if(J=J||N<0||me[ce+1]!=null||(pe<0?z:z%Se[Y-pe-1]),J=R<4?(ie||J)&&(R==0||R==(x.s<0?3:2)):ie>5||ie==5&&(R==4||J||R==6&&(se>0?pe>0?z/Se[Y-pe]:0:me[ce-1])%10&1||R==(x.s<0?8:7)),N<1||!me[0]){if(me.length=0,J)N-=x.e+1,me[0]=Se[(k-N%k)%k],x.e=-N||0;else me[0]=x.e=0;return x}if(se==0)me.length=ce,W=1,ce--;else me.length=ce+1,W=Se[k-se],me[ce]=pe>0?_(z/Se[Y-pe]%Se[pe])*W:0;if(J)for(;;)if(ce==0){for(se=1,pe=me[0];pe>=10;pe/=10,se++);pe=me[0]+=W;for(W=1;pe>=10;pe/=10,W++);if(se!=W){if(x.e++,me[0]==S)me[0]=1}break}else{if(me[ce]+=W,me[ce]!=S)break;me[ce--]=0,W=1}for(se=me.length;me[--se]===0;me.pop());}if(x.e>Ue)x.c=x.e=null;else if(x.e<Ve)x.c=[x.e=0]}return x}function _t(x){var N,R=x.e;if(R===null)return x.toString();return N=re(x.c),N=R<=Be||R>=je?he(N,R):q(N,R,"0"),x.s<0?"-"+N:N}if(_e.absoluteValue=_e.abs=function(){var x=new ge(this);if(x.s<0)x.s=1;return x},_e.comparedTo=function(x,N){return de(this,new ge(x,N))},_e.decimalPlaces=_e.dp=function(x,N){var R,J,Y,se=this;if(x!=null){if(L(x,0,Z),N==null)N=Ie;else L(N,0,8);return Me(new ge(se),x+se.e+1,N)}if(!(R=se.c))return null;if(J=((Y=R.length-1)-X(this.e/k))*k,Y=R[Y])for(;Y%10==0;Y/=10,J--);if(J<0)J=0;return J},_e.dividedBy=_e.div=function(x,N){return ue(this,new ge(x,N),Re,Ie)},_e.dividedToIntegerBy=_e.idiv=function(x,N){return ue(this,new ge(x,N),0,1)},_e.exponentiatedBy=_e.pow=function(x,N){var R,J,Y,se,pe,W,z,ce,ie,me=this;if(x=new ge(x),x.c&&!x.isInteger())throw Error(w+"Exponent not an integer: "+_t(x));if(N!=null)N=new ge(N);if(W=x.e>14,!me.c||!me.c[0]||me.c[0]==1&&!me.e&&me.c.length==1||!x.c||!x.c[0])return ie=new ge(Math.pow(+_t(me),W?x.s*(2-B(x)):+_t(x))),N?ie.mod(N):ie;if(z=x.s<0,N){if(N.c?!N.c[0]:!N.s)return new ge(NaN);if(J=!z&&me.isInteger()&&N.isInteger(),J)me=me.mod(N)}else if(x.e>9&&(me.e>0||me.e<-1||(me.e==0?me.c[0]>1||W&&me.c[1]>=240000000:me.c[0]<80000000000000||W&&me.c[0]<=99999750000000))){if(se=me.s<0&&B(x)?-0:0,me.e>-1)se=1/se;return new ge(z?1/se:se)}else if(tt)se=y(tt/k+2);if(W){if(R=new ge(0.5),z)x.s=1;ce=B(x)}else Y=Math.abs(+_t(x)),ce=Y%2;ie=new ge(Ne);for(;;){if(ce){if(ie=ie.times(me),!ie.c)break;if(se){if(ie.c.length>se)ie.c.length=se}else if(J)ie=ie.mod(N)}if(Y){if(Y=_(Y/2),Y===0)break;ce=Y%2}else if(x=x.times(R),Me(x,x.e+1,1),x.e>14)ce=B(x);else{if(Y=+_t(x),Y===0)break;ce=Y%2}if(me=me.times(me),se){if(me.c&&me.c.length>se)me.c.length=se}else if(J)me=me.mod(N)}if(J)return ie;if(z)ie=Ne.div(ie);return N?ie.mod(N):se?Me(ie,tt,Ie,pe):ie},_e.integerValue=function(x){var N=new ge(this);if(x==null)x=Ie;else L(x,0,8);return Me(N,N.e+1,x)},_e.isEqualTo=_e.eq=function(x,N){return de(this,new ge(x,N))===0},_e.isFinite=function(){return!!this.c},_e.isGreaterThan=_e.gt=function(x,N){return de(this,new ge(x,N))>0},_e.isGreaterThanOrEqualTo=_e.gte=function(x,N){return(N=de(this,new ge(x,N)))===1||N===0},_e.isInteger=function(){return!!this.c&&X(this.e/k)>this.c.length-2},_e.isLessThan=_e.lt=function(x,N){return de(this,new ge(x,N))<0},_e.isLessThanOrEqualTo=_e.lte=function(x,N){return(N=de(this,new ge(x,N)))===-1||N===0},_e.isNaN=function(){return!this.s},_e.isNegative=function(){return this.s<0},_e.isPositive=function(){return this.s>0},_e.isZero=function(){return!!this.c&&this.c[0]==0},_e.minus=function(x,N){var R,J,Y,se,pe=this,W=pe.s;if(x=new ge(x,N),N=x.s,!W||!N)return new ge(NaN);if(W!=N)return x.s=-N,pe.plus(x);var z=pe.e/k,ce=x.e/k,ie=pe.c,me=x.c;if(!z||!ce){if(!ie||!me)return ie?(x.s=-N,x):new ge(me?pe:NaN);if(!ie[0]||!me[0])return me[0]?(x.s=-N,x):new ge(ie[0]?pe:Ie==3?-0:0)}if(z=X(z),ce=X(ce),ie=ie.slice(),W=z-ce){if(se=W<0)W=-W,Y=ie;else ce=z,Y=me;Y.reverse();for(N=W;N--;Y.push(0));Y.reverse()}else{J=(se=(W=ie.length)<(N=me.length))?W:N;for(W=N=0;N<J;N++)if(ie[N]!=me[N]){se=ie[N]<me[N];break}}if(se)Y=ie,ie=me,me=Y,x.s=-x.s;if(N=(J=me.length)-(R=ie.length),N>0)for(;N--;ie[R++]=0);N=S-1;for(;J>W;){if(ie[--J]<me[J]){for(R=J;R&&!ie[--R];ie[R]=N);--ie[R],ie[J]+=S}ie[J]-=me[J]}for(;ie[0]==0;ie.splice(0,1),--ce);if(!ie[0])return x.s=Ie==3?-1:1,x.c=[x.e=0],x;return rt(x,ie,ce)},_e.modulo=_e.mod=function(x,N){var R,J,Y=this;if(x=new ge(x,N),!Y.c||!x.s||x.c&&!x.c[0])return new ge(NaN);else if(!x.c||Y.c&&!Y.c[0])return new ge(Y);if(Ze==9)J=x.s,x.s=1,R=ue(Y,x,0,3),x.s=J,R.s*=J;else R=ue(Y,x,0,Ze);if(x=Y.minus(R.times(x)),!x.c[0]&&Ze==1)x.s=Y.s;return x},_e.multipliedBy=_e.times=function(x,N){var R,J,Y,se,pe,W,z,ce,ie,me,Se,xe,Le,Ke,st,De=this,Ge=De.c,ht=(x=new ge(x,N)).c;if(!Ge||!ht||!Ge[0]||!ht[0]){if(!De.s||!x.s||Ge&&!Ge[0]&&!ht||ht&&!ht[0]&&!Ge)x.c=x.e=x.s=null;else if(x.s*=De.s,!Ge||!ht)x.c=x.e=null;else x.c=[0],x.e=0;return x}if(J=X(De.e/k)+X(x.e/k),x.s*=De.s,z=Ge.length,me=ht.length,z<me)Le=Ge,Ge=ht,ht=Le,Y=z,z=me,me=Y;for(Y=z+me,Le=[];Y--;Le.push(0));Ke=S,st=ne;for(Y=me;--Y>=0;){R=0,Se=ht[Y]%st,xe=ht[Y]/st|0;for(pe=z,se=Y+pe;se>Y;)ce=Ge[--pe]%st,ie=Ge[pe]/st|0,W=xe*ce+ie*Se,ce=Se*ce+W%st*st+Le[se]+R,R=(ce/Ke|0)+(W/st|0)+xe*ie,Le[se--]=ce%Ke;Le[se]=R}if(R)++J;else Le.splice(0,1);return rt(x,Le,J)},_e.negated=function(){var x=new ge(this);return x.s=-x.s||null,x},_e.plus=function(x,N){var R,J=this,Y=J.s;if(x=new ge(x,N),N=x.s,!Y||!N)return new ge(NaN);if(Y!=N)return x.s=-N,J.minus(x);var se=J.e/k,pe=x.e/k,W=J.c,z=x.c;if(!se||!pe){if(!W||!z)return new ge(Y/0);if(!W[0]||!z[0])return z[0]?x:new ge(W[0]?J:Y*0)}if(se=X(se),pe=X(pe),W=W.slice(),Y=se-pe){if(Y>0)pe=se,R=z;else Y=-Y,R=W;R.reverse();for(;Y--;R.push(0));R.reverse()}if(Y=W.length,N=z.length,Y-N<0)R=z,z=W,W=R,N=Y;for(Y=0;N;)Y=(W[--N]=W[N]+z[N]+Y)/S|0,W[N]=S===W[N]?0:W[N]%S;if(Y)W=[Y].concat(W),++pe;return rt(x,W,pe)},_e.precision=_e.sd=function(x,N){var R,J,Y,se=this;if(x!=null&&x!==!!x){if(L(x,1,Z),N==null)N=Ie;else L(N,0,8);return Me(new ge(se),x,N)}if(!(R=se.c))return null;if(Y=R.length-1,J=Y*k+1,Y=R[Y]){for(;Y%10==0;Y/=10,J--);for(Y=R[0];Y>=10;Y/=10,J++);}if(x&&se.e+1>J)J=se.e+1;return J},_e.shiftedBy=function(x){return L(x,-V,V),this.times("1e"+x)},_e.squareRoot=_e.sqrt=function(){var x,N,R,J,Y,se=this,{c:pe,s:W,e:z}=se,ce=Re+4,ie=new ge("0.5");if(W!==1||!pe||!pe[0])return new ge(!W||W<0&&(!pe||pe[0])?NaN:pe?se:1/0);if(W=Math.sqrt(+_t(se)),W==0||W==1/0){if(N=re(pe),(N.length+z)%2==0)N+="0";if(W=Math.sqrt(+N),z=X((z+1)/2)-(z<0||z%2),W==1/0)N="5e"+z;else N=W.toExponential(),N=N.slice(0,N.indexOf("e")+1)+z;R=new ge(N)}else R=new ge(W+"");if(R.c[0]){if(z=R.e,W=z+ce,W<3)W=0;for(;;)if(Y=R,R=ie.times(Y.plus(ue(se,Y,ce,1))),re(Y.c).slice(0,W)===(N=re(R.c)).slice(0,W)){if(R.e<z)--W;if(N=N.slice(W-3,W+1),N=="9999"||!J&&N=="4999"){if(!J){if(Me(Y,Y.e+Re+2,0),Y.times(Y).eq(se)){R=Y;break}}ce+=4,W+=4,J=1}else{if(!+N||!+N.slice(1)&&N.charAt(0)=="5")Me(R,R.e+Re+2,1),x=!R.times(R).eq(se);break}}}return Me(R,R.e+Re+1,Ie,x)},_e.toExponential=function(x,N){if(x!=null)L(x,0,Z),x++;return be(this,x,N,1)},_e.toFixed=function(x,N){if(x!=null)L(x,0,Z),x=x+this.e+1;return be(this,x,N)},_e.toFormat=function(x,N,R){var J,Y=this;if(R==null)if(x!=null&&N&&typeof N=="object")R=N,N=null;else if(x&&typeof x=="object")R=x,x=N=null;else R=ot;else if(typeof R!="object")throw Error(w+"Argument not an object: "+R);if(J=Y.toFixed(x,N),Y.c){var se,pe=J.split("."),W=+R.groupSize,z=+R.secondaryGroupSize,ce=R.groupSeparator||"",ie=pe[0],me=pe[1],Se=Y.s<0,xe=Se?ie.slice(1):ie,Le=xe.length;if(z)se=W,W=z,z=se,Le-=se;if(W>0&&Le>0){se=Le%W||W,ie=xe.substr(0,se);for(;se<Le;se+=W)ie+=ce+xe.substr(se,W);if(z>0)ie+=ce+xe.slice(se);if(Se)ie="-"+ie}J=me?ie+(R.decimalSeparator||"")+((z=+R.fractionGroupSize)?me.replace(new RegExp("\\d{"+z+"}\\B","g"),"$&"+(R.fractionGroupSeparator||"")):me):ie}return(R.prefix||"")+J+(R.suffix||"")},_e.toFraction=function(x){var N,R,J,Y,se,pe,W,z,ce,ie,me,Se,xe=this,Le=xe.c;if(x!=null){if(W=new ge(x),!W.isInteger()&&(W.c||W.s!==1)||W.lt(Ne))throw Error(w+"Argument "+(W.isInteger()?"out of range: ":"not an integer: ")+_t(W))}if(!Le)return new ge(xe);N=new ge(Ne),ce=R=new ge(Ne),J=z=new ge(Ne),Se=re(Le),se=N.e=Se.length-xe.e-1,N.c[0]=P[(pe=se%k)<0?k+pe:pe],x=!x||W.comparedTo(N)>0?se>0?N:ce:W,pe=Ue,Ue=1/0,W=new ge(Se),z.c[0]=0;for(;;){if(ie=ue(W,N,0,1),Y=R.plus(ie.times(J)),Y.comparedTo(x)==1)break;R=J,J=Y,ce=z.plus(ie.times(Y=ce)),z=Y,N=W.minus(ie.times(Y=N)),W=Y}return Y=ue(x.minus(R),J,0,1),z=z.plus(Y.times(ce)),R=R.plus(Y.times(J)),z.s=ce.s=xe.s,se=se*2,me=ue(ce,J,se,Ie).minus(xe).abs().comparedTo(ue(z,R,se,Ie).minus(xe).abs())<1?[ce,J]:[z,R],Ue=pe,me},_e.toNumber=function(){return+_t(this)},_e.toPrecision=function(x,N){if(x!=null)L(x,1,Z);return be(this,x,N,2)},_e.toString=function(x){var N,R=this,J=R.s,Y=R.e;if(Y===null)if(J){if(N="Infinity",J<0)N="-"+N}else N="NaN";else{if(x==null)N=Y<=Be||Y>=je?he(re(R.c),Y):q(re(R.c),Y,"0");else if(x===10&&mt)R=Me(new ge(R),Re+Y+1,Ie),N=q(re(R.c),R.e,"0");else L(x,2,et.length,"Base"),N=ye(q(re(R.c),Y,"0"),10,x,J,!0);if(J<0&&R.c[0])N="-"+N}return N},_e.valueOf=_e.toJSON=function(){return _t(this)},_e._isBigNumber=!0,U!=null)ge.set(U);return ge}function X(U){var ue=U|0;return U>0||U===ue?ue:ue-1}function re(U){var ue,ye,ve=1,_e=U.length,Ne=U[0]+"";for(;ve<_e;){ue=U[ve++]+"",ye=k-ue.length;for(;ye--;ue="0"+ue);Ne+=ue}for(_e=Ne.length;Ne.charCodeAt(--_e)===48;);return Ne.slice(0,_e+1||1)}function de(U,ue){var ye,ve,_e=U.c,Ne=ue.c,Re=U.s,Ie=ue.s,Be=U.e,je=ue.e;if(!Re||!Ie)return null;if(ye=_e&&!_e[0],ve=Ne&&!Ne[0],ye||ve)return ye?ve?0:-Ie:Re;if(Re!=Ie)return Re;if(ye=Re<0,ve=Be==je,!_e||!Ne)return ve?0:!_e^ye?1:-1;if(!ve)return Be>je^ye?1:-1;Ie=(Be=_e.length)<(je=Ne.length)?Be:je;for(Re=0;Re<Ie;Re++)if(_e[Re]!=Ne[Re])return _e[Re]>Ne[Re]^ye?1:-1;return Be==je?0:Be>je^ye?1:-1}function L(U,ue,ye,ve){if(U<ue||U>ye||U!==_(U))throw Error(w+(ve||"Argument")+(typeof U=="number"?U<ue||U>ye?" out of range: ":" not an integer: ":" not a primitive number: ")+String(U))}function B(U){var ue=U.c.length-1;return X(U.e/k)==ue&&U.c[ue]%2!=0}function he(U,ue){return(U.length>1?U.charAt(0)+"."+U.slice(1):U)+(ue<0?"e":"e+")+ue}function q(U,ue,ye){var ve,_e;if(ue<0){for(_e=ye+".";++ue;_e+=ye);U=_e+U}else if(ve=U.length,++ue>ve){for(_e=ye,ue-=ve;--ue;_e+=ye);U+=_e}else if(ue<ve)U=U.slice(0,ue)+"."+U.slice(ue);return U}if(f=K(),f.default=f.BigNumber=f,typeof define=="function"&&define.amd)define(function(){return f});else if(typeof xn<"u"&&xn.exports)xn.exports=f;else{if(!h)h=typeof self<"u"&&self?self:window;h.BigNumber=f}})(di)});var gi=i(function(dy,fi){var hi=dr(),pi=dy;(function(){function h(V){return V<10?"0"+V:V}var f=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,g=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,y,_,w={"\b":"\\b","\t":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':"\\\"","\\":"\\\\"},A;function S(V){return g.lastIndex=0,g.test(V)?'"'+V.replace(g,function(P){var ne=w[P];return typeof ne==="string"?ne:"\\u"+("0000"+P.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+V+'"'}function k(V,P){var ne,Z,K,X,re=y,de,L=P[V],B=L!=null&&(L instanceof hi||hi.isBigNumber(L));if(L&&typeof L==="object"&&typeof L.toJSON==="function")L=L.toJSON(V);if(typeof A==="function")L=A.call(P,V,L);switch(typeof L){case"string":if(B)return L;else return S(L);case"number":return isFinite(L)?String(L):"null";case"boolean":case"null":case"bigint":return String(L);case"object":if(!L)return"null";if(y+=_,de=[],Object.prototype.toString.apply(L)==="[object Array]"){X=L.length;for(ne=0;ne<X;ne+=1)de[ne]=k(ne,L)||"null";return K=de.length===0?"[]":y?`[
7
+ `+y+de.join(`,
8
+ `+y)+`
9
+ `+re+"]":"["+de.join(",")+"]",y=re,K}if(A&&typeof A==="object"){X=A.length;for(ne=0;ne<X;ne+=1)if(typeof A[ne]==="string"){if(Z=A[ne],K=k(Z,L),K)de.push(S(Z)+(y?": ":":")+K)}}else Object.keys(L).forEach(function(he){var q=k(he,L);if(q)de.push(S(he)+(y?": ":":")+q)});return K=de.length===0?"{}":y?`{
10
+ `+y+de.join(`,
11
+ `+y)+`
12
+ `+re+"}":"{"+de.join(",")+"}",y=re,K}}if(typeof pi.stringify!=="function")pi.stringify=function(V,P,ne){var Z;if(y="",_="",typeof ne==="number")for(Z=0;Z<ne;Z+=1)_+=" ";else if(typeof ne==="string")_=ne;if(A=P,P&&typeof P!=="function"&&(typeof P!=="object"||typeof P.length!=="number"))throw Error("JSON.stringify");return k("",{"":V})}})()});var yi=i(function(hy,mi){var On=null,vu=/(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])/,Eu=/(?: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)/,Cu=function(h){var f={strict:!1,storeAsString:!1,alwaysParseAsBig:!1,useNativeBigInt:!1,protoAction:"error",constructorAction:"error"};if(h!==void 0&&h!==null){if(h.strict===!0)f.strict=!0;if(h.storeAsString===!0)f.storeAsString=!0;if(f.alwaysParseAsBig=h.alwaysParseAsBig===!0?h.alwaysParseAsBig:!1,f.useNativeBigInt=h.useNativeBigInt===!0?h.useNativeBigInt:!1,typeof h.constructorAction<"u")if(h.constructorAction==="error"||h.constructorAction==="ignore"||h.constructorAction==="preserve")f.constructorAction=h.constructorAction;else throw Error(`Incorrect value for constructorAction option, must be "error", "ignore" or undefined but passed ${h.constructorAction}`);if(typeof h.protoAction<"u")if(h.protoAction==="error"||h.protoAction==="ignore"||h.protoAction==="preserve")f.protoAction=h.protoAction;else throw Error(`Incorrect value for protoAction option, must be "error", "ignore" or undefined but passed ${h.protoAction}`)}var g,y,_={'"':'"',"\\":"\\","/":"/",b:"\b",f:"\f",n:`
13
+ `,r:"\r",t:"\t"},w,A=function(re){throw{name:"SyntaxError",message:re,at:g,text:w}},S=function(re){if(re&&re!==y)A("Expected '"+re+"' instead of '"+y+"'");return y=w.charAt(g),g+=1,y},k=function(){var re,de="";if(y==="-")de="-",S("-");while(y>="0"&&y<="9")de+=y,S();if(y==="."){de+=".";while(S()&&y>="0"&&y<="9")de+=y}if(y==="e"||y==="E"){if(de+=y,S(),y==="-"||y==="+")de+=y,S();while(y>="0"&&y<="9")de+=y,S()}if(re=+de,!isFinite(re))A("Bad number");else{if(On==null)On=dr();if(de.length>15)return f.storeAsString?de:f.useNativeBigInt?BigInt(de):new On(de);else return!f.alwaysParseAsBig?re:f.useNativeBigInt?BigInt(re):new On(re)}},V=function(){var re,de,L="",B;if(y==='"'){var he=g;while(S()){if(y==='"'){if(g-1>he)L+=w.substring(he,g-1);return S(),L}if(y==="\\"){if(g-1>he)L+=w.substring(he,g-1);if(S(),y==="u"){B=0;for(de=0;de<4;de+=1){if(re=parseInt(S(),16),!isFinite(re))break;B=B*16+re}L+=String.fromCharCode(B)}else if(typeof _[y]==="string")L+=_[y];else break;he=g}}}A("Bad string")},P=function(){while(y&&y<=" ")S()},ne=function(){switch(y){case"t":return S("t"),S("r"),S("u"),S("e"),!0;case"f":return S("f"),S("a"),S("l"),S("s"),S("e"),!1;case"n":return S("n"),S("u"),S("l"),S("l"),null}A("Unexpected '"+y+"'")},Z,K=function(){var re=[];if(y==="["){if(S("["),P(),y==="]")return S("]"),re;while(y){if(re.push(Z()),P(),y==="]")return S("]"),re;S(","),P()}}A("Bad array")},X=function(){var re,de=Object.create(null);if(y==="{"){if(S("{"),P(),y==="}")return S("}"),de;while(y){if(re=V(),P(),S(":"),f.strict===!0&&Object.hasOwnProperty.call(de,re))A('Duplicate key "'+re+'"');if(vu.test(re)===!0)if(f.protoAction==="error")A("Object contains forbidden prototype property");else if(f.protoAction==="ignore")Z();else de[re]=Z();else if(Eu.test(re)===!0)if(f.constructorAction==="error")A("Object contains forbidden constructor property");else if(f.constructorAction==="ignore")Z();else de[re]=Z();else de[re]=Z();if(P(),y==="}")return S("}"),de;S(","),P()}}A("Bad object")};return Z=function(){switch(P(),y){case"{":return X();case"[":return K();case'"':return V();case"-":return k();default:return y>="0"&&y<="9"?k():ne()}},function(re,de){var L;if(w=re+"",g=0,y=" ",L=Z(),P(),y)A("Syntax error");return typeof de==="function"?function B(he,q){var U,ue,ye=he[q];if(ye&&typeof ye==="object")Object.keys(ye).forEach(function(ve){if(ue=B(ye,ve),ue!==void 0)ye[ve]=ue;else delete ye[ve]});return de.call(he,q,ye)}({"":L},""):L}};mi.exports=Cu});var wi=i(function(py,Rn){var _i=gi().stringify,Ti=yi();Rn.exports=function(h){return{parse:Ti(h),stringify:_i}};Rn.exports.parse=Ti();Rn.exports.stringify=_i});var hr=i(function(xi){Object.defineProperty(xi,"__esModule",{value:!0});xi.GCE_LINUX_BIOS_PATHS=void 0;xi.isGoogleCloudServerless=bi;xi.isGoogleComputeEngineLinux=Ai;xi.isGoogleComputeEngineMACAddress=Si;xi.isGoogleComputeEngine=ki;xi.detectGCPResidency=Su;var vi=c("fs"),Ei=c("os");xi.GCE_LINUX_BIOS_PATHS={BIOS_DATE:"/sys/class/dmi/id/bios_date",BIOS_VENDOR:"/sys/class/dmi/id/bios_vendor"};var bu=/^42:01/,Au=["CLOUD_RUN_JOB","FUNCTION_NAME","K_SERVICE","CLOUD_RUN_WORKER_POOL"];function bi(){return Au.some((h)=>Boolean(process.env[h]))}function Ai(){if(Ei.platform()!=="linux")return!1;try{vi.statSync(xi.GCE_LINUX_BIOS_PATHS.BIOS_DATE);let h=vi.readFileSync(xi.GCE_LINUX_BIOS_PATHS.BIOS_VENDOR,"utf8");return/Google/.test(h)}catch{return!1}}function Si(){let h=Ei.networkInterfaces();for(let f of Object.values(h)){if(!f)continue;for(let{mac:g}of f)if(bu.test(g))return!0}return!1}function ki(){return Ai()||Si()}function Su(){return bi()||ki()}});var Ni=i(function(Ri){Object.defineProperty(Ri,"__esModule",{value:!0});Ri.Colours=void 0;class $e{static enabled=!1;static reset="";static bright="";static dim="";static red="";static green="";static yellow="";static blue="";static magenta="";static cyan="";static white="";static grey="";static isEnabled(h){return h&&h.isTTY&&(typeof h.getColorDepth==="function"?h.getColorDepth()>2:!0)}static refresh(){if($e.enabled=$e.isEnabled(process?.stderr),!this.enabled)$e.reset="",$e.bright="",$e.dim="",$e.red="",$e.green="",$e.yellow="",$e.blue="",$e.magenta="",$e.cyan="",$e.white="",$e.grey="";else $e.reset="\x1B[0m",$e.bright="\x1B[1m",$e.dim="\x1B[2m",$e.red="\x1B[31m",$e.green="\x1B[32m",$e.yellow="\x1B[33m",$e.blue="\x1B[34m",$e.magenta="\x1B[35m",$e.cyan="\x1B[36m",$e.white="\x1B[37m",$e.grey="\x1B[90m"}}Ri.Colours=$e;$e.refresh()});var pr=i(function(Ui){Object.defineProperty(Ui,"__esModule",{value:!0});Ui.LogSeverity=void 0;var ji;(function(h){h.DEFAULT="DEFAULT",h.DEBUG="DEBUG",h.INFO="INFO",h.WARNING="WARNING",h.ERROR="ERROR"})(ji||(Ui.LogSeverity=ji={}))});var Bi=i(function(He){var Nu=He&&He.__createBinding||(Object.create?function(h,f,g,y){if(y===void 0)y=g;var _=Object.getOwnPropertyDescriptor(f,g);if(!_||("get"in _?!f.__esModule:_.writable||_.configurable))_={enumerable:!0,get:function(){return f[g]}};Object.defineProperty(h,y,_)}:function(h,f,g,y){if(y===void 0)y=g;h[y]=f[g]}),Pu=He&&He.__setModuleDefault||(Object.create?function(h,f){Object.defineProperty(h,"default",{enumerable:!0,value:f})}:function(h,f){h.default=f}),Li=He&&He.__importStar||function(){var h=function(f){return h=Object.getOwnPropertyNames||function(g){var y=[];for(var _ in g)if(Object.prototype.hasOwnProperty.call(g,_))y[y.length]=_;return y},h(f)};return function(f){if(f&&f.__esModule)return f;var g={};if(f!=null){for(var y=h(f),_=0;_<y.length;_++)if(y[_]!=="default")Nu(g,f,y[_])}return Pu(g,f),g}}();Object.defineProperty(He,"__esModule",{value:!0});He.env=He.DebugLogBackendBase=He.placeholder=He.AdhocDebugLogger=void 0;He.getNodeBackend=fr;He.getDebugBackend=Uu;He.getStructuredBackend=Mu;He.setBackend=Du;He.log=Hi;var ju=c("events"),pn=Li(c("process")),qi=Li(c("util")),Tt=Ni(),jt=pr();class Nn extends ju.EventEmitter{namespace;upstream;func;constructor(h,f){super();this.namespace=h,this.upstream=f,this.func=Object.assign(this.invoke.bind(this),{instance:this,on:(g,y)=>this.on(g,y)}),this.func.debug=(...g)=>this.invokeSeverity(jt.LogSeverity.DEBUG,...g),this.func.info=(...g)=>this.invokeSeverity(jt.LogSeverity.INFO,...g),this.func.warn=(...g)=>this.invokeSeverity(jt.LogSeverity.WARNING,...g),this.func.error=(...g)=>this.invokeSeverity(jt.LogSeverity.ERROR,...g),this.func.sublog=(g)=>Hi(g,this.func)}invoke(h,...f){if(this.upstream)try{this.upstream(h,...f)}catch(g){}try{this.emit("log",h,f)}catch(g){}}invokeSeverity(h,...f){this.invoke({severity:h},...f)}}He.AdhocDebugLogger=Nn;He.placeholder=new Nn("",()=>{}).func;class fn{cached=new Map;filters=[];filtersSet=!1;constructor(){let h=pn.env[He.env.nodeEnables]??"*";if(h==="all"||h==="true")h="*";this.filters=h.split(",")}log(h,f,...g){try{if(!this.filtersSet)this.setFilters(),this.filtersSet=!0;let y=this.cached.get(h);if(!y)y=this.makeLogger(h),this.cached.set(h,y);y(f,...g)}catch(y){console.error(y)}}}He.DebugLogBackendBase=fn;class Fi extends fn{enabledRegexp=/.*/g;isEnabled(h){return this.enabledRegexp.test(h)}makeLogger(h){if(!this.enabledRegexp.test(h))return()=>{};return(f,...g)=>{let y=`${Tt.Colours.green}${h}${Tt.Colours.reset}`,_=`${Tt.Colours.yellow}${pn.pid}${Tt.Colours.reset}`,w;switch(f.severity){case jt.LogSeverity.ERROR:w=`${Tt.Colours.red}${f.severity}${Tt.Colours.reset}`;break;case jt.LogSeverity.INFO:w=`${Tt.Colours.magenta}${f.severity}${Tt.Colours.reset}`;break;case jt.LogSeverity.WARNING:w=`${Tt.Colours.yellow}${f.severity}${Tt.Colours.reset}`;break;default:w=f.severity??jt.LogSeverity.DEFAULT;break}let A=qi.formatWithOptions({colors:Tt.Colours.enabled},...g),S=Object.assign({},f);delete S.severity;let k=Object.getOwnPropertyNames(S).length?JSON.stringify(S):"",V=k?`${Tt.Colours.grey}${k}${Tt.Colours.reset}`:"";console.error("%s [%s|%s] %s%s",_,y,w,A,k?` ${V}`:"")}}setFilters(){let f=this.filters.join(",").replace(/[|\\{}()[\]^$+?.]/g,"\\$&").replace(/\*/g,".*").replace(/,/g,"$|^");this.enabledRegexp=new RegExp(`^${f}$`,"i")}}function fr(){return new Fi}class Gi extends fn{debugPkg;constructor(h){super();this.debugPkg=h}makeLogger(h){let f=this.debugPkg(h);return(g,...y)=>{f(y[0],...y.slice(1))}}setFilters(){let h=pn.env.NODE_DEBUG??"";pn.env.NODE_DEBUG=`${h}${h?",":""}${this.filters.join(",")}`}}function Uu(h){return new Gi(h)}class $i extends fn{upstream;constructor(h){super();this.upstream=h??void 0}makeLogger(h){let f=this.upstream?.makeLogger(h);return(g,...y)=>{let _=g.severity??jt.LogSeverity.INFO,w=Object.assign({severity:_,message:qi.format(...y)},g),A=JSON.stringify(w);if(f)f(g,A);else console.log("%s",A)}}setFilters(){this.upstream?.setFilters()}}function Mu(h){return new $i(h)}He.env={nodeEnables:"GOOGLE_SDK_NODE_LOGGING"};var gr=new Map,kt=void 0;function Du(h){kt=h,gr.clear()}function Hi(h,f){if(!kt){if(!pn.env[He.env.nodeEnables])return He.placeholder}if(!h)return He.placeholder;if(f)h=`${f.instance.namespace}:${h}`;let g=gr.get(h);if(g)return g.func;if(kt===null)return He.placeholder;else if(kt===void 0)kt=fr();let y=(()=>{let _=void 0;return new Nn(h,(A,...S)=>{if(_!==kt){if(kt===null)return;else if(kt===void 0)kt=fr();_=kt}kt?.log(h,A,...S)})})();return gr.set(h,y),y.func}});var mr=i(function(Ut){var Lu=Ut&&Ut.__createBinding||(Object.create?function(h,f,g,y){if(y===void 0)y=g;var _=Object.getOwnPropertyDescriptor(f,g);if(!_||("get"in _?!f.__esModule:_.writable||_.configurable))_={enumerable:!0,get:function(){return f[g]}};Object.defineProperty(h,y,_)}:function(h,f,g,y){if(y===void 0)y=g;h[y]=f[g]}),qu=Ut&&Ut.__exportStar||function(h,f){for(var g in h)if(g!=="default"&&!Object.prototype.hasOwnProperty.call(f,g))Lu(f,h,g)};Object.defineProperty(Ut,"__esModule",{value:!0});Ut.LogSeverity=void 0;qu(Bi(),Ut);var Fu=pr();Object.defineProperty(Ut,"LogSeverity",{enumerable:!0,get:function(){return Fu.LogSeverity}})});var mn=i(function(Oe){var Ji=Oe&&Oe.__createBinding||(Object.create?function(h,f,g,y){if(y===void 0)y=g;var _=Object.getOwnPropertyDescriptor(f,g);if(!_||("get"in _?!f.__esModule:_.writable||_.configurable))_={enumerable:!0,get:function(){return f[g]}};Object.defineProperty(h,y,_)}:function(h,f,g,y){if(y===void 0)y=g;h[y]=f[g]}),Gu=Oe&&Oe.__setModuleDefault||(Object.create?function(h,f){Object.defineProperty(h,"default",{enumerable:!0,value:f})}:function(h,f){h.default=f}),$u=Oe&&Oe.__importStar||function(){var h=function(f){return h=Object.getOwnPropertyNames||function(g){var y=[];for(var _ in g)if(Object.prototype.hasOwnProperty.call(g,_))y[y.length]=_;return y},h(f)};return function(f){if(f&&f.__esModule)return f;var g={};if(f!=null){for(var y=h(f),_=0;_<y.length;_++)if(y[_]!=="default")Ji(g,f,y[_])}return Gu(g,f),g}}(),Hu=Oe&&Oe.__exportStar||function(h,f){for(var g in h)if(g!=="default"&&!Object.prototype.hasOwnProperty.call(f,g))Ji(f,h,g)};Object.defineProperty(Oe,"__esModule",{value:!0});Oe.gcpResidencyCache=Oe.METADATA_SERVER_DETECTION=Oe.HEADERS=Oe.HEADER_VALUE=Oe.HEADER_NAME=Oe.SECONDARY_HOST_ADDRESS=Oe.HOST_ADDRESS=Oe.BASE_PATH=void 0;Oe.instance=Yu;Oe.project=zu;Oe.universe=Xu;Oe.bulk=Qu;Oe.isAvailable=rd;Oe.resetIsAvailableCache=sd;Oe.getGCPResidency=wr;Oe.setGCPResidency=Yi;Oe.requestTimeout=zi;var yr=ct(),Bu=wi(),Vu=hr(),Wu=$u(mr());Oe.BASE_PATH="/computeMetadata/v1";Oe.HOST_ADDRESS="http://169.254.169.254";Oe.SECONDARY_HOST_ADDRESS="http://metadata.google.internal.";Oe.HEADER_NAME="Metadata-Flavor";Oe.HEADER_VALUE="Google";Oe.HEADERS=Object.freeze({[Oe.HEADER_NAME]:Oe.HEADER_VALUE});var Vi=Wu.log("gcp-metadata");Oe.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 _r(h){if(!h)h=process.env.GCE_METADATA_IP||process.env.GCE_METADATA_HOST||Oe.HOST_ADDRESS;if(!/^https?:\/\//.test(h))h=`http://${h}`;return new URL(Oe.BASE_PATH,h).href}function Ju(h){Object.keys(h).forEach((f)=>{switch(f){case"params":case"property":case"headers":break;case"qs":throw Error("'qs' is not a valid configuration option. Please use 'params' instead.");default:throw Error(`'${f}' is not a valid configuration option.`)}})}async function gn(h,f={},g=3,y=!1){let _=new Headers(Oe.HEADERS),w="",A={};if(typeof h==="object"){let ne=h;new Headers(ne.headers).forEach((Z,K)=>_.set(K,Z)),w=ne.metadataKey,A=ne.params||A,g=ne.noResponseRetries||g,y=ne.fastFail||y}else w=h;if(typeof f==="string")w+=`/${f}`;else{if(Ju(f),f.property)w+=`/${f.property}`;new Headers(f.headers).forEach((ne,Z)=>_.set(Z,ne)),A=f.params||A}let S=y?Ku:yr.request,k={url:`${_r()}/${w}`,headers:_,retryConfig:{noResponseRetries:g},params:A,responseType:"text",timeout:zi()};Vi.debug("instance request %j",k);let V=await S(k);Vi.debug("instance metadata is %s",V.data);let P=V.headers.get(Oe.HEADER_NAME);if(P!==Oe.HEADER_VALUE)throw RangeError(`Invalid response from metadata service: incorrect ${Oe.HEADER_NAME} header. Expected '${Oe.HEADER_VALUE}', got ${P?`'${P}'`:"no header"}`);if(typeof V.data==="string")try{return Bu.parse(V.data)}catch{}return V.data}async function Ku(h){let f={...h,url:h.url?.toString().replace(_r(),_r(Oe.SECONDARY_HOST_ADDRESS))},g=yr.request(h),y=yr.request(f);try{return await Promise.any([g,y])}catch(_){if(_ instanceof AggregateError&&!_.message)_.message="All promises were rejected";throw _}}function Yu(h){return gn("instance",h)}function zu(h){return gn("project",h)}function Xu(h){return gn("universe",h)}async function Qu(h){let f={};return await Promise.all(h.map((g)=>(async()=>{let y=await gn(g),_=g.metadataKey;f[_]=y})())),f}function Zu(){return process.env.DETECT_GCP_RETRIES?Number(process.env.DETECT_GCP_RETRIES):0}var Pn,ed=new Set(["EHOSTDOWN","EHOSTUNREACH","ENETUNREACH","ENOENT","ENOTFOUND","ECONNREFUSED","ConnectionRefused","FailedToOpenSocket"]),Wi=new Set(["AbortError","TimeoutError"]),td=new Set(["aborted","request-timeout"]),nd=20;function Ki(h){return typeof h==="object"&&h!==null}function Tr(h,f=new Set,g=0){if(!Ki(h)||f.has(h)||g>nd)return["UNKNOWN"];if(f.add(h),h.name==="AggregateError"&&Array.isArray(h.errors)){if(h.errors.length===0)return["UNKNOWN"];return h.errors.flatMap((_)=>Tr(_,f,g+1))}if(h.name!==void 0&&Wi.has(h.name)||h.code!==void 0&&Wi.has(h.code)||h.type!==void 0&&td.has(h.type))return["ETIMEDOUT"];if((typeof h.code==="string"||typeof h.code==="number")&&h.code!=="")return[String(h.code)];let y=h.cause??h.error;if(y!==void 0)return Tr(y,f,g+1);return["UNKNOWN"]}async function rd(){if(process.env.METADATA_SERVER_DETECTION){let h=process.env.METADATA_SERVER_DETECTION.trim().toLocaleLowerCase();if(!(h in Oe.METADATA_SERVER_DETECTION))throw RangeError(`Unknown \`METADATA_SERVER_DETECTION\` env variable. Got \`${h}\`, but it should be \`${Object.keys(Oe.METADATA_SERVER_DETECTION).join("`, `")}\`, or unset`);switch(h){case"assume-present":return!0;case"none":return!1;case"bios-only":return wr();case"ping-only":}}try{if(Pn===void 0)Pn=(async()=>{try{return await gn("instance",void 0,Zu(),!(process.env.GCE_METADATA_IP||process.env.GCE_METADATA_HOST)),!0}catch(h){if(process.env.DEBUG_AUTH)console.info(h);if(!Ki(h))return process.emitWarning(`received unexpected error = ${String(h)} code = UNKNOWN`,"MetadataLookupWarning"),!1;if(h.type==="request-timeout"||h.response?.status===404)return!1;let f=Tr(h);if(!(f.length>0&&f.every((y)=>ed.has(y)))){let y=[...new Set(f)].join(", ");process.emitWarning(`received unexpected error = ${h.message} code = ${y}`,"MetadataLookupWarning")}return!1}})();return await Pn}catch(h){return!1}}function sd(){Pn=void 0}Oe.gcpResidencyCache=null;function wr(){if(Oe.gcpResidencyCache===null)Yi();return Oe.gcpResidencyCache}function Yi(h=null){Oe.gcpResidencyCache=h!==null?h:Vu.detectGCPResidency()}function zi(){return wr()?0:3000}Hu(hr(),Oe)});var Qi=i(function(hd){hd.byteLength=od;hd.toByteArray=cd;hd.fromByteArray=dd;var It=[],Ct=[],id=typeof Uint8Array<"u"?Uint8Array:Array,vr="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for($t=0,Er=vr.length;$t<Er;++$t)It[$t]=vr[$t],Ct[vr.charCodeAt($t)]=$t;var $t,Er;Ct[45]=62;Ct[95]=63;function Xi(h){var f=h.length;if(f%4>0)throw Error("Invalid string. Length must be a multiple of 4");var g=h.indexOf("=");if(g===-1)g=f;var y=g===f?0:4-g%4;return[g,y]}function od(h){var f=Xi(h),g=f[0],y=f[1];return(g+y)*3/4-y}function ad(h,f,g){return(f+g)*3/4-g}function cd(h){var f,g=Xi(h),y=g[0],_=g[1],w=new id(ad(h,y,_)),A=0,S=_>0?y-4:y,k;for(k=0;k<S;k+=4)f=Ct[h.charCodeAt(k)]<<18|Ct[h.charCodeAt(k+1)]<<12|Ct[h.charCodeAt(k+2)]<<6|Ct[h.charCodeAt(k+3)],w[A++]=f>>16&255,w[A++]=f>>8&255,w[A++]=f&255;if(_===2)f=Ct[h.charCodeAt(k)]<<2|Ct[h.charCodeAt(k+1)]>>4,w[A++]=f&255;if(_===1)f=Ct[h.charCodeAt(k)]<<10|Ct[h.charCodeAt(k+1)]<<4|Ct[h.charCodeAt(k+2)]>>2,w[A++]=f>>8&255,w[A++]=f&255;return w}function ld(h){return It[h>>18&63]+It[h>>12&63]+It[h>>6&63]+It[h&63]}function ud(h,f,g){var y,_=[];for(var w=f;w<g;w+=3)y=(h[w]<<16&16711680)+(h[w+1]<<8&65280)+(h[w+2]&255),_.push(ld(y));return _.join("")}function dd(h){var f,g=h.length,y=g%3,_=[],w=16383;for(var A=0,S=g-y;A<S;A+=w)_.push(ud(h,A,A+w>S?S:A+w));if(y===1)f=h[g-1],_.push(It[f>>2]+It[f<<4&63]+"==");else if(y===2)f=(h[g-2]<<8)+h[g-1],_.push(It[f>>10]+It[f>>4&63]+It[f<<2&63]+"=");return _.join("")}});var Cr=i(function(Zi){Object.defineProperty(Zi,"__esModule",{value:!0});Zi.fromArrayBufferToHex=md;function md(h){return Array.from(new Uint8Array(h)).map((g)=>g.toString(16).padStart(2,"0")).join("")}});var no=i(function(eo){Object.defineProperty(eo,"__esModule",{value:!0});eo.BrowserCrypto=void 0;var rn=Qi(),_d=Cr();class jn{constructor(){if(typeof window>"u"||window.crypto===void 0||window.crypto.subtle===void 0)throw Error("SubtleCrypto not found. Make sure it's an https:// website.")}async sha256DigestBase64(h){let f=new TextEncoder().encode(h),g=await window.crypto.subtle.digest("SHA-256",f);return rn.fromByteArray(new Uint8Array(g))}randomBytesBase64(h){let f=new Uint8Array(h);return window.crypto.getRandomValues(f),rn.fromByteArray(f)}static padBase64(h){while(h.length%4!==0)h+="=";return h}async verify(h,f,g){let y={name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},_=new TextEncoder().encode(f),w=rn.toByteArray(jn.padBase64(g)),A=await window.crypto.subtle.importKey("jwk",h,y,!0,["verify"]);return await window.crypto.subtle.verify(y,A,Buffer.from(w),_)}async sign(h,f){let g={name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},y=new TextEncoder().encode(f),_=await window.crypto.subtle.importKey("jwk",h,g,!0,["sign"]),w=await window.crypto.subtle.sign(g,_,y);return rn.fromByteArray(new Uint8Array(w))}decodeBase64StringUtf8(h){let f=rn.toByteArray(jn.padBase64(h));return new TextDecoder().decode(f)}encodeBase64StringUtf8(h){let f=new TextEncoder().encode(h);return rn.fromByteArray(f)}async sha256DigestHex(h){let f=new TextEncoder().encode(h),g=await window.crypto.subtle.digest("SHA-256",f);return _d.fromArrayBufferToHex(g)}async signWithHmacSha256(h,f){let g=typeof h==="string"?h:String.fromCharCode(...new Uint16Array(h)),y=new TextEncoder,_=await window.crypto.subtle.importKey("raw",y.encode(g),{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return window.crypto.subtle.sign("HMAC",_,y.encode(f))}}eo.BrowserCrypto=jn});var ao=i(function(io){Object.defineProperty(io,"__esModule",{value:!0});io.NodeCrypto=void 0;var sn=c("crypto");class ro{async sha256DigestBase64(h){return sn.createHash("sha256").update(h).digest("base64")}randomBytesBase64(h){return sn.randomBytes(h).toString("base64")}async verify(h,f,g){let y=sn.createVerify("RSA-SHA256");return y.update(f),y.end(),y.verify(h,g,"base64")}async sign(h,f){let g=sn.createSign("RSA-SHA256");return g.update(f),g.end(),g.sign(h,"base64")}decodeBase64StringUtf8(h){return Buffer.from(h,"base64").toString("utf-8")}encodeBase64StringUtf8(h){return Buffer.from(h,"utf-8").toString("base64")}async sha256DigestHex(h){return sn.createHash("sha256").update(h).digest("hex")}async signWithHmacSha256(h,f){let g=typeof h==="string"?h:wd(h);return Td(sn.createHmac("sha256",g).update(f).digest())}}io.NodeCrypto=ro;function Td(h){let f=new ArrayBuffer(h.length),g=new Uint8Array(f);for(let y=0;y<h.length;++y)g[y]=h[y];return f}function wd(h){return Buffer.from(h)}});var yn=i(function(Mt){var vd=Mt&&Mt.__createBinding||(Object.create?function(h,f,g,y){if(y===void 0)y=g;var _=Object.getOwnPropertyDescriptor(f,g);if(!_||("get"in _?!f.__esModule:_.writable||_.configurable))_={enumerable:!0,get:function(){return f[g]}};Object.defineProperty(h,y,_)}:function(h,f,g,y){if(y===void 0)y=g;h[y]=f[g]}),Ed=Mt&&Mt.__exportStar||function(h,f){for(var g in h)if(g!=="default"&&!Object.prototype.hasOwnProperty.call(f,g))vd(f,h,g)};Object.defineProperty(Mt,"__esModule",{value:!0});Mt.createCrypto=Ad;Mt.hasBrowserCrypto=co;var Cd=no(),bd=ao();Ed(Cr(),Mt);function Ad(){if(co())return new Cd.BrowserCrypto;return new bd.NodeCrypto}function co(){return typeof window<"u"&&typeof window.crypto<"u"&&typeof window.crypto.subtle<"u"}});var bt=i(function(po){Object.defineProperty(po,"__esModule",{value:!0});po.LRUCache=void 0;po.snakeToCamel=uo;po.originalOrCamelOptions=Od;po.removeUndefinedValuesInObject=Rd;po.isValidFile=Id;po.getWellKnownCertificateConfigFileLocation=Nd;po.isAdcWarningSuppressed=jd;po.suppressAdcWarning=Ud;po.isFromJsonWarningSuppressed=Md;po.suppressFromJsonWarning=Dd;var Sd=c("fs"),kd=c("os"),br=c("path"),xd="certificate_config.json",lo="gcloud";function uo(h){return h.replace(/([_][^_])/g,(f)=>f.slice(1).toUpperCase())}function Od(h){function f(g){let y=h||{};return y[g]??y[uo(g)]}return{get:f}}class ho{capacity;#e=new Map;maxAge;constructor(h){this.capacity=h.capacity,this.maxAge=h.maxAge}#t(h,f){this.#e.delete(h),this.#e.set(h,{value:f,lastAccessed:Date.now()})}set(h,f){this.#t(h,f),this.#n()}get(h){let f=this.#e.get(h);if(!f)return;return this.#t(h,f.value),this.#n(),f.value}#n(){let h=this.maxAge?Date.now()-this.maxAge:0,f=this.#e.entries().next();while(!f.done&&(this.#e.size>this.capacity||f.value[1].lastAccessed<h))this.#e.delete(f.value[0]),f=this.#e.entries().next()}}po.LRUCache=ho;function Rd(h){return Object.entries(h).forEach(([f,g])=>{if(g===void 0||g==="undefined")delete h[f]}),h}async function Id(h){try{return(await Sd.promises.lstat(h)).isFile()}catch(f){return!1}}function Nd(){let h=process.env.CLOUDSDK_CONFIG||(Pd()?br.join(process.env.APPDATA||"",lo):br.join(process.env.HOME||"",".config",lo));return br.join(h,xd)}function Pd(){return kd.platform().startsWith("win")}var Un=0,Ar=0;function jd(){return Un>0}function Ud(h){Un++;try{return h()}finally{Un--}}function Md(){return Un>0||Ar>0}function Dd(h){Ar++;try{return h()}finally{Ar--}}});var go=i(function(ky,Jd){Jd.exports={name:"google-auth-library",version:"11.3.2",author:"Google Inc.",description:"Google APIs Authentication Client Library for Node.js",engines:{node:">=22"},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:"^8.3.1","gcp-metadata":"^9.2.1","google-logging-utils":"^2.1.0",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":"^6.1.0","jsdoc-region-tag":"^5.1.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.0",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"],license:"Apache-2.0",homepage:"https://github.com/googleapis/google-cloud-node/tree/main/core/packages/google-auth-library-nodejs",scripts:{test:"node ../../../bin/run-test.cjs build/test",clean:"gts clean",lint:"gts check --no-inline-config",compile:"tsc -p .",fix:"gts fix",pretest:"pnpm run compile --sourceMap",docs:"jsdoc -c .jsdoc.js","samples-setup":"cd samples/ && pnpm link ../ && pnpm run setup && cd ../","samples-test":"cd samples/ && pnpm link ../ && pnpm test && cd ../","system-test":"mocha build/system-test --timeout 60000","presystem-test":"pnpm run compile --sourceMap",webpack:"webpack","browser-test":"karma start",prelint:"cd samples; pnpm link ../; pnpm install"}}});var Sr=i(function(_o){Object.defineProperty(_o,"__esModule",{value:!0});_o.USER_AGENT=_o.PRODUCT_NAME=_o.pkg=void 0;var mo=go();_o.pkg=mo;var yo="google-api-nodejs-client";_o.PRODUCT_NAME=yo;var Kd=`${yo}/${mo.version}`;_o.USER_AGENT=Kd});var wt=i(function(wo){Object.defineProperty(wo,"__esModule",{value:!0});wo.AuthClient=wo.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS=wo.DEFAULT_UNIVERSE=void 0;var Xd=c("events"),kr=ct(),Qd=bt(),Zd=mr(),xr=Sr();wo.DEFAULT_UNIVERSE="googleapis.com";wo.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS=300000;class lt extends Xd.EventEmitter{apiKey;projectId;quotaProjectId;transporter;credentials={};eagerRefreshThresholdMillis=wo.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS;forceRefreshOnFailure=!1;universeDomain=wo.DEFAULT_UNIVERSE;static RequestMethodNameSymbol=Symbol("request method name");static RequestLogIdSymbol=Symbol("request log id");constructor(h={}){super();let f=Qd.originalOrCamelOptions(h);if(this.apiKey=h.apiKey,this.projectId=f.get("project_id")??null,this.quotaProjectId=f.get("quota_project_id"),this.credentials=f.get("credentials")??{},this.universeDomain=f.get("universe_domain")??wo.DEFAULT_UNIVERSE,this.transporter=h.transporter??new kr.Gaxios(h.transporterOptions),f.get("useAuthRequestParameters")!==!1)this.transporter.interceptors.request.add(lt.DEFAULT_REQUEST_INTERCEPTOR),this.transporter.interceptors.response.add(lt.DEFAULT_RESPONSE_INTERCEPTOR);if(h.eagerRefreshThresholdMillis)this.eagerRefreshThresholdMillis=h.eagerRefreshThresholdMillis;this.forceRefreshOnFailure=h.forceRefreshOnFailure??!1}fetch(...h){let f=h[0],g=h[1],y=void 0,_=new Headers;if(typeof f==="string")y=new URL(f);else if(f instanceof URL)y=f;else if(f&&f.url)y=new URL(f.url);if(f&&typeof f==="object"&&"headers"in f)kr.Gaxios.mergeHeaders(_,f.headers);if(g)kr.Gaxios.mergeHeaders(_,new Headers(g.headers));if(typeof f==="object"&&!(f instanceof URL))return this.request({...g,...f,headers:_,url:y});else return this.request({...g,headers:_,url:y})}setCredentials(h){this.credentials=h}addSharedMetadataHeaders(h){if(!h.has("x-goog-user-project")&&this.quotaProjectId)h.set("x-goog-user-project",this.quotaProjectId);return h}addUserProjectAndAuthHeaders(h,f){let g=f.get("x-goog-user-project"),y=f.get("authorization");if(g)h.set("x-goog-user-project",g);if(y)h.set("authorization",y);return h}static log=Zd.log("auth");static DEFAULT_REQUEST_INTERCEPTOR={resolved:async(h)=>{if(!h.headers.has("x-goog-api-client")){let g=process.version.replace(/^v/,"");h.headers.set("x-goog-api-client",`gl-node/${g}`)}let f=h.headers.get("User-Agent");if(!f)h.headers.set("User-Agent",xr.USER_AGENT);else if(!f.includes(`${xr.PRODUCT_NAME}/`))h.headers.set("User-Agent",`${f} ${xr.USER_AGENT}`);try{let g=h,y=g[lt.RequestMethodNameSymbol],_=`${Math.floor(Math.random()*1000)}`;g[lt.RequestLogIdSymbol]=_;let w={url:h.url,headers:h.headers};if(y)lt.log.debug("%s [%s] request %j",y,_,w);else lt.log.debug("[%s] request %j",_,w)}catch(g){}return h}};static DEFAULT_RESPONSE_INTERCEPTOR={resolved:async(h)=>{try{let f=h.config,g=f[lt.RequestMethodNameSymbol],y=f[lt.RequestLogIdSymbol];if(g)lt.log.debug("%s [%s] response %j",g,y,h.data);else lt.log.debug("[%s] response %j",y,h.data)}catch(f){}return h},rejected:async(h)=>{try{let f=h.config,g=f[lt.RequestMethodNameSymbol],y=f[lt.RequestLogIdSymbol];if(g)lt.log.debug("%s [%s] error %j",g,y,h.response?.data);else lt.log.debug("[%s] error %j",y,h.response?.data)}catch(f){}throw h}};static setMethodName(h,f){try{let g=h;g[lt.RequestMethodNameSymbol]=f}catch(g){}}static get RETRY_CONFIG(){return{retry:!0,retryConfig:{httpMethodsToRetry:["GET","PUT","POST","HEAD","OPTIONS","DELETE"]}}}}wo.AuthClient=lt});var Rr=i(function(bo){Object.defineProperty(bo,"__esModule",{value:!0});bo.LoginTicket=void 0;class Co{envelope;payload;constructor(h,f){this.envelope=h,this.payload=f}getEnvelope(){return this.envelope}getPayload(){return this.payload}getUserId(){let h=this.getPayload();if(h&&h.sub)return h.sub;return null}getAttributes(){return{envelope:this.getEnvelope(),payload:this.getPayload()}}}bo.LoginTicket=Co});var Ht=i(function(Oo){Object.defineProperty(Oo,"__esModule",{value:!0});Oo.OAuth2Client=Oo.ClientAuthentication=Oo.CertificateFormat=Oo.CodeChallengeMethod=void 0;var xo=ct(),eh=c("querystring"),th=c("stream"),nh=vy(),So=bt(),Ir=yn(),on=wt(),rh=Rr(),ko;(function(h){h.Plain="plain",h.S256="S256"})(ko||(Oo.CodeChallengeMethod=ko={}));var Dt;(function(h){h.PEM="PEM",h.JWK="JWK"})(Dt||(Oo.CertificateFormat=Dt={}));var _n;(function(h){h.ClientSecretPost="ClientSecretPost",h.ClientSecretBasic="ClientSecretBasic",h.None="None"})(_n||(Oo.ClientAuthentication=_n={}));class St extends on.AuthClient{redirectUri;certificateCache={};certificateExpiry=null;certificateCacheFormat=Dt.PEM;refreshTokenPromises=new Map;endpoints;issuers;clientAuthentication;_clientId;_clientSecret;refreshHandler;constructor(h={},f,g){super(typeof h==="object"?h:{});if(typeof h!=="object")h={clientId:h,clientSecret:f,redirectUri:g};this._clientId=h.clientId||h.client_id,this._clientSecret=h.clientSecret||h.client_secret,this.redirectUri=h.redirectUri||h.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",...h.endpoints},this.clientAuthentication=h.clientAuthentication||_n.ClientSecretPost,this.issuers=h.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(h={}){if(h.code_challenge_method&&!h.code_challenge)throw Error("If a code_challenge_method is provided, code_challenge must be included.");if(h.response_type=h.response_type||"code",h.client_id=h.client_id||this._clientId,h.redirect_uri=h.redirect_uri||this.redirectUri,Array.isArray(h.scope))h.scope=h.scope.join(" ");return this.endpoints.oauth2AuthBaseUrl.toString()+"?"+eh.stringify(h)}generateCodeVerifier(){throw Error("generateCodeVerifier is removed, please use generateCodeVerifierAsync instead.")}async generateCodeVerifierAsync(){let h=Ir.createCrypto(),g=h.randomBytesBase64(96).replace(/\+/g,"~").replace(/=/g,"_").replace(/\//g,"-"),_=(await h.sha256DigestBase64(g)).split("=")[0].replace(/\+/g,"-").replace(/\//g,"_");return{codeVerifier:g,codeChallenge:_}}getToken(h,f){let g=typeof h==="string"?{code:h}:h;if(f)this.getTokenAsync(g).then((y)=>f(null,y.tokens,y.res),(y)=>f(y,null,y.response));else return this.getTokenAsync(g)}async getTokenAsync(h){let f=this.endpoints.oauth2TokenUrl.toString(),g=new Headers,y={client_id:h.client_id||this._clientId,code_verifier:h.codeVerifier,code:h.code,grant_type:"authorization_code",redirect_uri:h.redirect_uri||this.redirectUri};if(this.clientAuthentication===_n.ClientSecretBasic){let S=Buffer.from(`${this._clientId}:${this._clientSecret}`);g.set("authorization",`Basic ${S.toString("base64")}`)}if(this.clientAuthentication===_n.ClientSecretPost)y.client_secret=this._clientSecret;let _={...St.RETRY_CONFIG,method:"POST",url:f,data:new URLSearchParams(So.removeUndefinedValuesInObject(y)),headers:g};on.AuthClient.setMethodName(_,"getTokenAsync");let w=await this.transporter.request(_),A=w.data;if(w.data&&w.data.expires_in)A.expiry_date=new Date().getTime()+w.data.expires_in*1000,delete A.expires_in;return this.emit("tokens",A),{tokens:A,res:w}}async refreshToken(h){if(!h)return this.refreshTokenNoCache(h);if(this.refreshTokenPromises.has(h))return this.refreshTokenPromises.get(h);let f=this.refreshTokenNoCache(h).then((g)=>(this.refreshTokenPromises.delete(h),g),(g)=>{throw this.refreshTokenPromises.delete(h),g});return this.refreshTokenPromises.set(h,f),f}async refreshTokenNoCache(h){if(!h)throw Error("No refresh token is set.");let f=this.endpoints.oauth2TokenUrl.toString(),g={refresh_token:h,client_id:this._clientId,client_secret:this._clientSecret,grant_type:"refresh_token"},y;try{let w={...St.RETRY_CONFIG,method:"POST",url:f,data:new URLSearchParams(So.removeUndefinedValuesInObject(g))};on.AuthClient.setMethodName(w,"refreshTokenNoCache"),y=await this.transporter.request(w)}catch(w){if(w instanceof xo.GaxiosError&&w.message==="invalid_grant"&&w.response?.data&&/ReAuth/i.test(w.response.data.error_description))w.message=JSON.stringify(w.response.data);throw w}let _=y.data;if(y.data&&y.data.expires_in)_.expiry_date=new Date().getTime()+y.data.expires_in*1000,delete _.expires_in;return this.emit("tokens",_),{tokens:_,res:y}}refreshAccessToken(h){if(h)this.refreshAccessTokenAsync().then((f)=>h(null,f.credentials,f.res),h);else return this.refreshAccessTokenAsync()}async refreshAccessTokenAsync(){let h=await this.refreshToken(this.credentials.refresh_token),f=h.tokens;return f.refresh_token=this.credentials.refresh_token,this.credentials=f,{credentials:this.credentials,res:h.res}}getAccessToken(h){if(h)this.getAccessTokenAsync().then((f)=>h(null,f.token,f.res),h);else return this.getAccessTokenAsync()}async getAccessTokenAsync(){if(!this.credentials.access_token||this.isTokenExpiring()){if(!this.credentials.refresh_token)if(this.refreshHandler){let g=await this.processAndValidateRefreshHandler();if(g?.access_token)return this.setCredentials(g),{token:this.credentials.access_token}}else throw Error("No refresh token or refresh handler callback is set.");let f=await this.refreshAccessTokenAsync();if(!f.credentials||f.credentials&&!f.credentials.access_token)throw Error("Could not refresh access token.");return{token:f.credentials.access_token,res:f.res}}else return{token:this.credentials.access_token}}async getRequestHeaders(h){return(await this.getRequestMetadataAsync(h)).headers}async getRequestMetadataAsync(h){let f=this.credentials;if(!f.access_token&&!f.refresh_token&&!this.apiKey&&!this.refreshHandler)throw Error("No access, refresh token, API key or refresh handler callback is set.");if(f.access_token&&!this.isTokenExpiring()){f.token_type=f.token_type||"Bearer";let A=new Headers({authorization:f.token_type+" "+f.access_token});return{headers:this.addSharedMetadataHeaders(A)}}if(this.refreshHandler){let A=await this.processAndValidateRefreshHandler();if(A?.access_token){this.setCredentials(A);let S=new Headers({authorization:"Bearer "+this.credentials.access_token});return{headers:this.addSharedMetadataHeaders(S)}}}if(this.apiKey)return{headers:new Headers({"X-Goog-Api-Key":this.apiKey})};let g=null,y=null;try{g=await this.refreshToken(f.refresh_token),y=g.tokens}catch(A){let S=A;if(S.response&&(S.response.status===403||S.response.status===404))S.message=`Could not refresh access token: ${S.message}`;throw S}let _=this.credentials;_.token_type=_.token_type||"Bearer",y.refresh_token=_.refresh_token,this.credentials=y;let w=new Headers({authorization:_.token_type+" "+y.access_token});return{headers:this.addSharedMetadataHeaders(w),res:g.res}}static getRevokeTokenUrl(h){return new St().getRevokeTokenURL(h).toString()}getRevokeTokenURL(h){let f=new URL(this.endpoints.oauth2RevokeUrl);return f.searchParams.append("token",h),f}revokeToken(h,f){let g={...St.RETRY_CONFIG,url:this.getRevokeTokenURL(h).toString(),method:"POST"};if(on.AuthClient.setMethodName(g,"revokeToken"),f)this.transporter.request(g).then((y)=>f(null,y),f);else return this.transporter.request(g)}revokeCredentials(h){if(h)this.revokeCredentialsAsync().then((f)=>h(null,f),h);else return this.revokeCredentialsAsync()}async revokeCredentialsAsync(){let h=this.credentials.access_token;if(this.credentials={},h)return this.revokeToken(h);else throw Error("No access token to revoke.")}request(h,f){if(f)this.requestAsync(h).then((g)=>f(null,g),(g)=>f(g,g.response));else return this.requestAsync(h)}async requestAsync(h,f=!1){try{let g=await this.getRequestMetadataAsync();if(h.headers=xo.Gaxios.mergeHeaders(h.headers),this.addUserProjectAndAuthHeaders(h.headers,g.headers),this.apiKey)h.headers.set("X-Goog-Api-Key",this.apiKey);return await this.transporter.request(h)}catch(g){let y=g.response;if(y){let _=y.status,w=this.credentials&&this.credentials.access_token&&this.credentials.refresh_token&&(!this.credentials.expiry_date||this.forceRefreshOnFailure),A=this.credentials&&this.credentials.access_token&&!this.credentials.refresh_token&&(!this.credentials.expiry_date||this.forceRefreshOnFailure)&&this.refreshHandler,S=y.config.data instanceof th.Readable,k=_===401||_===403;if(!f&&k&&!S&&w)return await this.refreshAccessTokenAsync(),this.requestAsync(h,!0);else if(!f&&k&&!S&&A){let V=await this.processAndValidateRefreshHandler();if(V?.access_token)this.setCredentials(V);return this.requestAsync(h,!0)}}throw g}}verifyIdToken(h,f){if(f&&typeof f!=="function")throw Error("This method accepts an options object as the first parameter, which includes the idToken, audience, and maxExpiry.");if(f)this.verifyIdTokenAsync(h).then((g)=>f(null,g),f);else return this.verifyIdTokenAsync(h)}async verifyIdTokenAsync(h){if(!h.idToken)throw Error("The verifyIdToken method requires an ID Token");let f=await this.getFederatedSignonCertsAsync();return await this.verifySignedJwtWithCertsAsync(h.idToken,f.certs,h.audience,this.issuers,h.maxExpiry)}async getTokenInfo(h){let{data:f}=await this.transporter.request({...St.RETRY_CONFIG,method:"POST",headers:{"content-type":"application/x-www-form-urlencoded;charset=UTF-8",authorization:`Bearer ${h}`},url:this.endpoints.tokenInfoUrl.toString()}),g=Object.assign({expiry_date:new Date().getTime()+f.expires_in*1000,scopes:f.scope.split(" ")},f);return delete g.expires_in,delete g.scope,g}getFederatedSignonCerts(h){if(h)this.getFederatedSignonCertsAsync().then((f)=>h(null,f.certs,f.res),h);else return this.getFederatedSignonCertsAsync()}async getFederatedSignonCertsAsync(){let h=new Date().getTime(),f=Ir.hasBrowserCrypto()?Dt.JWK:Dt.PEM;if(this.certificateExpiry&&h<this.certificateExpiry.getTime()&&this.certificateCacheFormat===f)return{certs:this.certificateCache,format:f};let g,y;switch(f){case Dt.PEM:y=this.endpoints.oauth2FederatedSignonPemCertsUrl.toString();break;case Dt.JWK:y=this.endpoints.oauth2FederatedSignonJwkCertsUrl.toString();break;default:throw Error(`Unsupported certificate format ${f}`)}try{let k={...St.RETRY_CONFIG,url:y};on.AuthClient.setMethodName(k,"getFederatedSignonCertsAsync"),g=await this.transporter.request(k)}catch(k){if(k instanceof Error)k.message=`Failed to retrieve verification certificates: ${k.message}`;throw k}let _=g?.headers.get("cache-control"),w=-1;if(_){let k=/max-age=(?<maxAge>[0-9]+)/.exec(_)?.groups?.maxAge;if(k)w=Number(k)*1000}let A={};switch(f){case Dt.PEM:A=g.data;break;case Dt.JWK:for(let k of g.data.keys)A[k.kid]=k;break;default:throw Error(`Unsupported certificate format ${f}`)}let S=new Date;return this.certificateExpiry=w===-1?null:new Date(S.getTime()+w),this.certificateCache=A,this.certificateCacheFormat=f,{certs:A,format:f,res:g}}getIapPublicKeys(h){if(h)this.getIapPublicKeysAsync().then((f)=>h(null,f.pubkeys,f.res),h);else return this.getIapPublicKeysAsync()}async getIapPublicKeysAsync(){let h,f=this.endpoints.oauth2IapPublicKeyUrl.toString();try{let g={...St.RETRY_CONFIG,url:f};on.AuthClient.setMethodName(g,"getIapPublicKeysAsync"),h=await this.transporter.request(g)}catch(g){if(g instanceof Error)g.message=`Failed to retrieve verification certificates: ${g.message}`;throw g}return{pubkeys:h.data,res:h}}verifySignedJwtWithCerts(){throw Error("verifySignedJwtWithCerts is removed, please use verifySignedJwtWithCertsAsync instead.")}async verifySignedJwtWithCertsAsync(h,f,g,y,_){let w=Ir.createCrypto();if(!_)_=St.DEFAULT_MAX_TOKEN_LIFETIME_SECS_;let A=h.split(".");if(A.length!==3)throw Error("Wrong number of segments in token: "+h);let S=A[0]+"."+A[1],k=A[2],V,P;try{V=JSON.parse(w.decodeBase64StringUtf8(A[0]))}catch(B){if(B instanceof Error)B.message=`Can't parse token envelope: ${A[0]}': ${B.message}`;throw B}if(!V)throw Error("Can't parse token envelope: "+A[0]);try{P=JSON.parse(w.decodeBase64StringUtf8(A[1]))}catch(B){if(B instanceof Error)B.message=`Can't parse token payload '${A[0]}`;throw B}if(!P)throw Error("Can't parse token payload: "+A[1]);if(!Object.prototype.hasOwnProperty.call(f,V.kid))throw Error("No pem found for envelope: "+JSON.stringify(V));let ne=f[V.kid];if(V.alg==="ES256")k=nh.joseToDer(k,"ES256").toString("base64");if(!await w.verify(ne,S,k))throw Error("Invalid token signature: "+h);if(!P.iat)throw Error("No issue time in token: "+JSON.stringify(P));if(!P.exp)throw Error("No expiration time in token: "+JSON.stringify(P));let K=Number(P.iat);if(isNaN(K))throw Error("iat field using invalid format");let X=Number(P.exp);if(isNaN(X))throw Error("exp field using invalid format");let re=new Date().getTime()/1000;if(X>=re+_)throw Error("Expiration time too far in future: "+JSON.stringify(P));let de=K-St.CLOCK_SKEW_SECS_,L=X+St.CLOCK_SKEW_SECS_;if(re<de)throw Error("Token used too early, "+re+" < "+de+": "+JSON.stringify(P));if(re>L)throw Error("Token used too late, "+re+" > "+L+": "+JSON.stringify(P));if(y&&y.indexOf(P.iss)<0)throw Error("Invalid issuer, expected one of ["+y+"], but got "+P.iss);if(typeof g<"u"&&g!==null){let B=P.aud,he=!1;if(g.constructor===Array)he=g.indexOf(B)>-1;else he=B===g;if(!he)throw Error("Wrong recipient, payload audience != requiredAudience")}return new rh.LoginTicket(V,P)}async processAndValidateRefreshHandler(){if(this.refreshHandler){let h=await this.refreshHandler();if(!h.access_token)throw Error("No access token is returned by the refreshHandler callback.");return h}return}isTokenExpiring(){let h=this.credentials.expiry_date;return h?h<=new Date().getTime()+this.eagerRefreshThresholdMillis:!1}}Oo.OAuth2Client=St});var Pr=i(function(Po){Object.defineProperty(Po,"__esModule",{value:!0});Po.Compute=void 0;var ah=ct(),Io=mn(),ch=Ht();class No extends ch.OAuth2Client{serviceAccountEmail;scopes;constructor(h={}){super(h);this.credentials={expiry_date:1,refresh_token:"compute-placeholder"},this.serviceAccountEmail=h.serviceAccountEmail||"default",this.scopes=Array.isArray(h.scopes)?h.scopes:h.scopes?[h.scopes]:[]}async refreshTokenNoCache(){let h=`service-accounts/${this.serviceAccountEmail}/token`,f;try{let y={property:h};if(this.scopes.length>0)y.params={scopes:this.scopes.join(",")};f=await Io.instance(y)}catch(y){if(y instanceof ah.GaxiosError)y.message=`Could not refresh access token: ${y.message}`,this.wrapError(y);throw y}let g=f;if(f&&f.expires_in)g.expiry_date=new Date().getTime()+f.expires_in*1000,delete g.expires_in;return this.emit("tokens",g),{tokens:g,res:null}}async fetchIdToken(h){let f=`service-accounts/${this.serviceAccountEmail}/identity?format=full&audience=${h}`,g;try{g=await Io.instance({property:f})}catch(y){if(y instanceof Error)y.message=`Could not fetch ID token: ${y.message}`;throw y}return g}wrapError(h){let f=h.response;if(f&&f.status){if(h.status=f.status,f.status===403)h.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: "+h.message;else if(f.status===404)h.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: "+h.message}}}Po.Compute=No});var jr=i(function(Mo){Object.defineProperty(Mo,"__esModule",{value:!0});Mo.IdTokenClient=void 0;var lh=Ht();class Uo extends lh.OAuth2Client{targetAudience;idTokenProvider;constructor(h){super(h);this.targetAudience=h.targetAudience,this.idTokenProvider=h.idTokenProvider}async getRequestMetadataAsync(){if(!this.credentials.id_token||!this.credentials.expiry_date||this.isTokenExpiring()){let f=await this.idTokenProvider.fetchIdToken(this.targetAudience);this.credentials={id_token:f,expiry_date:this.getIdTokenExpiryDate(f)}}return{headers:new Headers({authorization:"Bearer "+this.credentials.id_token})}}getIdTokenExpiryDate(h){let f=h.split(".")[1];if(f)return JSON.parse(Buffer.from(f,"base64").toString("ascii")).exp*1000}}Mo.IdTokenClient=Uo});var Ur=i(function(Fo){Object.defineProperty(Fo,"__esModule",{value:!0});Fo.GCPEnv=void 0;Fo.clear=uh;Fo.getEnv=dh;var qo=mn(),Nt;(function(h){h.APP_ENGINE="APP_ENGINE",h.KUBERNETES_ENGINE="KUBERNETES_ENGINE",h.CLOUD_FUNCTIONS="CLOUD_FUNCTIONS",h.COMPUTE_ENGINE="COMPUTE_ENGINE",h.CLOUD_RUN="CLOUD_RUN",h.CLOUD_RUN_JOBS="CLOUD_RUN_JOBS",h.NONE="NONE"})(Nt||(Fo.GCPEnv=Nt={}));var Tn;function uh(){Tn=void 0}async function dh(){if(Tn)return Tn;return Tn=hh(),Tn}async function hh(){let h=Nt.NONE;if(ph())h=Nt.APP_ENGINE;else if(fh())h=Nt.CLOUD_FUNCTIONS;else if(await _h())if(await yh())h=Nt.KUBERNETES_ENGINE;else if(gh())h=Nt.CLOUD_RUN;else if(mh())h=Nt.CLOUD_RUN_JOBS;else h=Nt.COMPUTE_ENGINE;else h=Nt.NONE;return h}function ph(){return!!(process.env.GAE_SERVICE||process.env.GAE_MODULE_NAME)}function fh(){return!!(process.env.FUNCTION_NAME||process.env.FUNCTION_TARGET)}function gh(){return!!process.env.K_CONFIGURATION}function mh(){return!!process.env.CLOUD_RUN_JOB}async function yh(){try{return await qo.instance("attributes/cluster-name"),!0}catch(h){return!1}}async function _h(){return qo.isAvailable()}});var Bo=i(function(Ho){Object.defineProperty(Ho,"__esModule",{value:!0});Ho.buildPayloadForJwsSign=$o;Ho.getJwsSign=bh;var vh=xc(),Eh="RS256",Ch="https://oauth2.googleapis.com/token";function $o(h){let f=Math.floor(new Date().getTime()/1000);return{iss:h.iss,scope:h.scope,aud:Ch,exp:f+3600,iat:f,sub:h.sub,...h.additionalClaims}}function bh(h){let f=$o(h);return vh.sign({header:{alg:Eh},payload:f,secret:h.key})}});var Wo=i(function(Vo){Object.defineProperty(Vo,"__esModule",{value:!0});Vo.getToken=Ih;var kh=Bo(),xh="https://oauth2.googleapis.com/token",Oh="urn:ietf:params:oauth:grant-type:jwt-bearer",Rh=(h)=>({method:"POST",url:xh,data:new URLSearchParams({grant_type:Oh,assertion:kh.getJwsSign(h)}),responseType:"json",retryConfig:{httpMethodsToRetry:["POST"]}});async function Ih(h){if(!h.transporter)throw Error("No transporter set.");try{let f=Rh(h);return(await h.transporter.request(f)).data}catch(f){let g=f,y=g.response?.data;if(y?.error)g.message=`${y.error}: ${y.error_description}`;throw g}}});var zo=i(function(Ko){Object.defineProperty(Ko,"__esModule",{value:!0});Ko.ErrorWithCode=void 0;class Jo extends Error{code;constructor(h,f){super(h);this.code=f}}Ko.ErrorWithCode=Jo});var Mr=i(function(ra){Object.defineProperty(ra,"__esModule",{value:!0});ra.getCredentials=Uh;var Ph=c("path"),Xo=c("fs"),jh=c("util"),Mn=zo(),Qo=Xo.readFile?jh.promisify(Xo.readFile):async()=>{throw new Mn.ErrorWithCode("use key rather than keyFile.","MISSING_CREDENTIALS")},Bt;(function(h){h.JSON=".json",h.DER=".der",h.CRT=".crt",h.PEM=".pem",h.P12=".p12",h.PFX=".pfx"})(Bt||(Bt={}));class Zo{keyFilePath;constructor(h){this.keyFilePath=h}async getCredentials(){let h=await Qo(this.keyFilePath,"utf8"),f;try{f=JSON.parse(h)}catch(_){throw Error(`Invalid JSON key file: ${_.message}`)}let g=f.private_key,y=f.client_email;if(!g||!y)throw new Mn.ErrorWithCode("private_key and client_email are required.","MISSING_CREDENTIALS");return{privateKey:g,clientEmail:y}}}class ea{keyFilePath;constructor(h){this.keyFilePath=h}async getCredentials(){return{privateKey:await Qo(this.keyFilePath,"utf8")}}}class ta{async getCredentials(){throw new Mn.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")}}class na{static create(h){switch(Ph.extname(h)){case Bt.JSON:return new Zo(h);case Bt.DER:case Bt.CRT:case Bt.PEM:return new ea(h);case Bt.P12:case Bt.PFX:return new ta;default:throw new Mn.ErrorWithCode("Unknown certificate type. Type is determined based on file extension. Current supported extensions are *.json, and *.pem.","UNKNOWN_CERTIFICATE_TYPE")}}}async function Uh(h){return na.create(h).getCredentials()}});var ca=i(function(oa){Object.defineProperty(oa,"__esModule",{value:!0});oa.TokenHandler=void 0;var Dh=Wo(),Lh=Mr();class sa{token;tokenExpiresAt;inFlightRequest;tokenOptions;constructor(h){this.tokenOptions=h}async processCredentials(){if(!this.tokenOptions.key&&!this.tokenOptions.keyFile)throw Error("No key or keyFile set.");if(!this.tokenOptions.key&&this.tokenOptions.keyFile){let h=await Lh.getCredentials(this.tokenOptions.keyFile);this.tokenOptions.key=h.privateKey,this.tokenOptions.email=h.clientEmail}}isTokenExpiring(){if(!this.token||!this.tokenExpiresAt)return!0;let h=new Date().getTime(),f=this.tokenOptions.eagerRefreshThresholdMillis??0;return this.tokenExpiresAt<=h+f}hasExpired(){let h=new Date().getTime();if(this.token&&this.tokenExpiresAt)return new Date().getTime()>=this.tokenExpiresAt;return!0}async getToken(h){if(await this.processCredentials(),this.inFlightRequest&&!h)return this.inFlightRequest;if(this.token&&!this.isTokenExpiring()&&!h)return this.token;try{this.inFlightRequest=Dh.getToken(this.tokenOptions);let f=await this.inFlightRequest;return this.token=f,this.tokenExpiresAt=new Date().getTime()+(f.expires_in??0)*1000,f}finally{this.inFlightRequest=void 0}}}oa.TokenHandler=sa});var ua=i(function(la){Object.defineProperty(la,"__esModule",{value:!0});la.revokeToken=Gh;var qh="https://oauth2.googleapis.com/revoke?token=",Fh=!0;async function Gh(h,f){let g=qh+h;return await f.request({url:g,retry:Fh})}});var Dr=i(function(pa){Object.defineProperty(pa,"__esModule",{value:!0});pa.GoogleToken=void 0;var Hh=ct(),da=ca(),Bh=ua();class ha{tokenOptions;tokenHandler;constructor(h){if(this.tokenOptions=h||{},this.tokenOptions.transporter=this.tokenOptions.transporter||{request:(f)=>Hh.request(f)},!this.tokenOptions.iss)this.tokenOptions.iss=this.tokenOptions.email;if(typeof this.tokenOptions.scope==="object")this.tokenOptions.scope=this.tokenOptions.scope.join(" ");this.tokenHandler=new da.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(h,f={forceRefresh:!1}){let g;if(typeof h==="function")g=h;else if(typeof h==="object")f=h;let y=this.tokenHandler.getToken(f.forceRefresh??!1);if(g)y.then((_)=>g(null,_),g);return y}revokeToken(h){if(!this.accessToken)return Promise.reject(Error("No token to revoke."));let f=Bh.revokeToken(this.accessToken,this.tokenOptions.transporter);if(h)f.then(()=>h(),h);this.tokenHandler=new da.TokenHandler(this.tokenOptions)}get googleTokenOptions(){return this.tokenOptions}}pa.GoogleToken=ha});var qr=i(function(ma){Object.defineProperty(ma,"__esModule",{value:!0});ma.JWTAccess=void 0;var Vh=xc(),Wh=bt(),ga={alg:"RS256",typ:"JWT"};class Lr{email;key;keyId;projectId;eagerRefreshThresholdMillis;cache=new Wh.LRUCache({capacity:500,maxAge:3600000});constructor(h,f,g,y){this.email=h,this.key=f,this.keyId=g,this.eagerRefreshThresholdMillis=y??300000}getCachedKey(h,f){let g=h;if(f&&Array.isArray(f)&&f.length)g=h?`${h}_${f.join("_")}`:`${f.join("_")}`;else if(typeof f==="string")g=h?`${h}_${f}`:f;if(!g)throw Error("Scopes or url must be provided");return g}getRequestHeaders(h,f,g){let y=this.getCachedKey(h,g),_=this.cache.get(y),w=Date.now();if(_&&_.expiration-w>this.eagerRefreshThresholdMillis)return new Headers(_.headers);let A=Math.floor(Date.now()/1000),S=Lr.getExpirationTime(A),k;if(Array.isArray(g))g=g.join(" ");if(g)k={iss:this.email,sub:this.email,scope:g,exp:S,iat:A};else k={iss:this.email,sub:this.email,aud:h,exp:S,iat:A};if(f){for(let K in k)if(f[K])throw Error(`The '${K}' property is not allowed when passing additionalClaims. This claim is included in the JWT by default.`)}let V=this.keyId?{...ga,kid:this.keyId}:ga,P=Object.assign(k,f),ne=Vh.sign({header:V,payload:P,secret:this.key}),Z=new Headers({authorization:`Bearer ${ne}`});return this.cache.set(y,{expiration:S*1000,headers:Z}),Z}static getExpirationTime(h){return h+3600}fromJSON(h){if(!h)throw Error("Must pass in a JSON object containing the service account auth settings.");if(!h.client_email)throw Error("The incoming JSON object does not contain a client_email field");if(!h.private_key)throw Error("The incoming JSON object does not contain a private_key field");this.email=h.client_email,this.key=h.private_key,this.keyId=h.private_key_id,this.projectId=h.project_id}fromStream(h,f){if(f)this.fromStreamAsync(h).then(()=>f(),f);else return this.fromStreamAsync(h)}fromStreamAsync(h){return new Promise((f,g)=>{if(!h)g(Error("Must pass in a stream containing the service account auth settings."));let y="";h.setEncoding("utf8").on("data",(_)=>y+=_).on("error",g).on("end",()=>{try{let _=JSON.parse(y);this.fromJSON(_),f()}catch(_){g(_)}})})}}ma.JWTAccess=Lr});var Gr=i(function(Ta){Object.defineProperty(Ta,"__esModule",{value:!0});Ta.JWT=void 0;var _a=Dr(),Jh=Mr(),Kh=qr(),Yh=Ht(),Dn=wt();class Fr extends Yh.OAuth2Client{email;keyFile;key;keyId;defaultScopes;scopes;scope;subject;gtoken;additionalClaims;useJWTAccessWithScope;defaultServicePath;access;constructor(h={}){super(h);this.email=h.email,this.keyFile=h.keyFile,this.key=h.key,this.keyId=h.keyId,this.scopes=h.scopes,this.subject=h.subject,this.additionalClaims=h.additionalClaims,this.credentials={refresh_token:"jwt-placeholder",expiry_date:1}}createScoped(h){let f=new Fr(this);return f.scopes=h,f}async getRequestMetadataAsync(h){h=this.defaultServicePath?`https://${this.defaultServicePath}/`:h;let f=!this.hasUserScopes()&&h||this.useJWTAccessWithScope&&this.hasAnyScopes()||this.universeDomain!==Dn.DEFAULT_UNIVERSE;if(this.subject&&this.universeDomain!==Dn.DEFAULT_UNIVERSE)throw RangeError(`Service Account user is configured for the credential. Domain-wide delegation is not supported in universes other than ${Dn.DEFAULT_UNIVERSE}`);if(!this.apiKey&&f)if(this.additionalClaims&&this.additionalClaims.target_audience){let{tokens:g}=await this.refreshToken();return{headers:this.addSharedMetadataHeaders(new Headers({authorization:`Bearer ${g.id_token}`}))}}else{if(!this.access)this.access=new Kh.JWTAccess(this.email,this.key,this.keyId,this.eagerRefreshThresholdMillis);let g;if(this.hasUserScopes())g=this.scopes;else if(!h)g=this.defaultScopes;let y=this.useJWTAccessWithScope||this.universeDomain!==Dn.DEFAULT_UNIVERSE,_=await this.access.getRequestHeaders(h??void 0,this.additionalClaims,y?g:void 0);return{headers:this.addSharedMetadataHeaders(_)}}else if(this.hasAnyScopes()||this.apiKey)return super.getRequestMetadataAsync(h);else return{headers:new Headers}}async fetchIdToken(h){let f=new _a.GoogleToken({iss:this.email,sub:this.subject,scope:this.scopes||this.defaultScopes,keyFile:this.keyFile,key:this.key,additionalClaims:{target_audience:h},transporter:this.transporter});if(await f.getToken({forceRefresh:!0}),!f.idToken)throw Error("Unknown error: Failed to fetch ID token");return f.idToken}hasUserScopes(){if(!this.scopes)return!1;return this.scopes.length>0}hasAnyScopes(){if(this.scopes&&this.scopes.length>0)return!0;if(this.defaultScopes&&this.defaultScopes.length>0)return!0;return!1}authorize(h){if(h)this.authorizeAsync().then((f)=>h(null,f),h);else return this.authorizeAsync()}async authorizeAsync(){let h=await this.refreshToken();if(!h)throw Error("No result returned");return this.credentials=h.tokens,this.credentials.refresh_token="jwt-placeholder",this.key=this.gtoken.googleTokenOptions?.key,this.email=this.gtoken.googleTokenOptions?.iss,h.tokens}async refreshTokenNoCache(){let h=this.createGToken(),g={access_token:(await h.getToken({forceRefresh:this.isTokenExpiring()})).access_token,token_type:"Bearer",expiry_date:h.expiresAt,id_token:h.idToken};return this.emit("tokens",g),{res:null,tokens:g}}createGToken(){if(!this.gtoken)this.gtoken=new _a.GoogleToken({iss:this.email,sub:this.subject,scope:this.scopes||this.defaultScopes,keyFile:this.keyFile,key:this.key,additionalClaims:this.additionalClaims,transporter:this.transporter});return this.gtoken}fromJSON(h){if(!h)throw Error("Must pass in a JSON object containing the service account auth settings.");if(!h.client_email)throw Error("The incoming JSON object does not contain a client_email field");if(!h.private_key)throw Error("The incoming JSON object does not contain a private_key field");this.email=h.client_email,this.key=h.private_key,this.keyId=h.private_key_id,this.projectId=h.project_id,this.quotaProjectId=h.quota_project_id,this.universeDomain=h.universe_domain||this.universeDomain}fromStream(h,f){if(f)this.fromStreamAsync(h).then(()=>f(),f);else return this.fromStreamAsync(h)}fromStreamAsync(h){return new Promise((f,g)=>{if(!h)throw Error("Must pass in a stream containing the service account auth settings.");let y="";h.setEncoding("utf8").on("error",g).on("data",(_)=>y+=_).on("end",()=>{try{let _=JSON.parse(y);this.fromJSON(_),f()}catch(_){g(_)}})})}fromAPIKey(h){if(typeof h!=="string")throw Error("Must provide an API Key string.");this.apiKey=h}async getCredentials(){if(this.key)return{private_key:this.key,client_email:this.email};else if(this.keyFile){let h=this.createGToken(),f=await Jh.getCredentials(this.keyFile);return{private_key:f.privateKey,client_email:f.clientEmail}}throw Error("A key or a keyFile must be provided to getCredentials.")}}Ta.JWT=Fr});var $r=i(function(va){Object.defineProperty(va,"__esModule",{value:!0});va.UserRefreshClient=va.USER_REFRESH_ACCOUNT_TYPE=void 0;var zh=Ht(),Xh=wt();va.USER_REFRESH_ACCOUNT_TYPE="authorized_user";class Ln extends zh.OAuth2Client{_refreshToken;constructor(h,f,g,y,_){let w=h&&typeof h==="object"?h:{clientId:h,clientSecret:f,refreshToken:g,eagerRefreshThresholdMillis:y,forceRefreshOnFailure:_};super(w);this._refreshToken=w.refreshToken,this.credentials.refresh_token=w.refreshToken}async refreshTokenNoCache(){return super.refreshTokenNoCache(this._refreshToken)}async fetchIdToken(h){let f={...Ln.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:h}),responseType:"json"};return Xh.AuthClient.setMethodName(f,"fetchIdToken"),(await this.transporter.request(f)).data.id_token}fromJSON(h){if(!h)throw Error("Must pass in a JSON object containing the user refresh token");if(h.type!=="authorized_user")throw Error('The incoming JSON object does not have the "authorized_user" type');if(!h.client_id)throw Error("The incoming JSON object does not contain a client_id field");if(!h.client_secret)throw Error("The incoming JSON object does not contain a client_secret field");if(!h.refresh_token)throw Error("The incoming JSON object does not contain a refresh_token field");this._clientId=h.client_id,this._clientSecret=h.client_secret,this._refreshToken=h.refresh_token,this.credentials.refresh_token=h.refresh_token,this.quotaProjectId=h.quota_project_id,this.universeDomain=h.universe_domain||this.universeDomain}fromStream(h,f){if(f)this.fromStreamAsync(h).then(()=>f(),f);else return this.fromStreamAsync(h)}async fromStreamAsync(h){return new Promise((f,g)=>{if(!h)return g(Error("Must pass in a stream containing the user refresh token."));let y="";h.setEncoding("utf8").on("error",g).on("data",(_)=>y+=_).on("end",()=>{try{let _=JSON.parse(y);return this.fromJSON(_),f()}catch(_){return g(_)}})})}static fromJSON(h){let f=new Ln;return f.fromJSON(h),f}}va.UserRefreshClient=Ln});var Hr=i(function(Aa){Object.defineProperty(Aa,"__esModule",{value:!0});Aa.Impersonated=Aa.IMPERSONATED_ACCOUNT_TYPE=void 0;var Ca=Ht(),Zh=ct(),ba=bt();Aa.IMPERSONATED_ACCOUNT_TYPE="impersonated_service_account";class wn extends Ca.OAuth2Client{sourceClient;targetPrincipal;targetScopes;delegates;lifetime;endpoint;constructor(h={}){super(h);if(!ba.isAdcWarningSuppressed())console.warn("The `Impersonated` constructor does not validate the credential configuration. A security risk occurs when a credential configuration configured with malicious URLs is used. When the credential configuration is accepted from an untrusted source, you should validate it before using it with this method. For more details, see https://cloud.google.com/docs/authentication/external/externally-sourced-credentials.");if(this.credentials={expiry_date:1,refresh_token:"impersonated-placeholder"},this.sourceClient=h.sourceClient??new Ca.OAuth2Client,this.targetPrincipal=h.targetPrincipal??"",this.delegates=h.delegates??[],this.targetScopes=h.targetScopes??[],this.lifetime=h.lifetime??3600,!ba.originalOrCamelOptions(h).get("universe_domain"))this.universeDomain=this.sourceClient.universeDomain;else if(this.sourceClient.universeDomain!==this.universeDomain)throw RangeError(`Universe domain ${this.sourceClient.universeDomain} in source credentials does not match ${this.universeDomain} universe domain set for impersonated credentials.`);this.endpoint=h.endpoint??`https://iamcredentials.${this.universeDomain}`}async sign(h){await this.sourceClient.getAccessToken();let f=`projects/-/serviceAccounts/${this.targetPrincipal}`,g=`${this.endpoint}/v1/${f}:signBlob`,y={delegates:this.delegates,payload:Buffer.from(h).toString("base64")};return(await this.sourceClient.request({...wn.RETRY_CONFIG,url:g,data:y,method:"POST"})).data}getTargetPrincipal(){return this.targetPrincipal}async refreshToken(){try{await this.sourceClient.getAccessToken();let h="projects/-/serviceAccounts/"+this.targetPrincipal,f=`${this.endpoint}/v1/${h}:generateAccessToken`,g={delegates:this.delegates,scope:this.targetScopes,lifetime:this.lifetime+"s"},y=await this.sourceClient.request({...wn.RETRY_CONFIG,url:f,data:g,method:"POST"}),_=y.data;return this.credentials.access_token=_.accessToken,this.credentials.expiry_date=Date.parse(_.expireTime),{tokens:this.credentials,res:y}}catch(h){if(!(h instanceof Error))throw h;let f=0,g="";if(h instanceof Zh.GaxiosError)f=h?.response?.data?.error?.status,g=h?.response?.data?.error?.message;if(f&&g)throw h.message=`${f}: unable to impersonate: ${g}`,h;else throw h.message=`unable to impersonate: ${h}`,h}}async fetchIdToken(h,f){await this.sourceClient.getAccessToken();let g=`projects/-/serviceAccounts/${this.targetPrincipal}`,y=`${this.endpoint}/v1/${g}:generateIdToken`,_={delegates:this.delegates,audience:h,includeEmail:f?.includeEmail??!0,useEmailAzp:f?.includeEmail??!0};return(await this.sourceClient.request({...wn.RETRY_CONFIG,url:y,data:_,method:"POST"})).data.token}}Aa.Impersonated=wn});var Br=i(function(xa){Object.defineProperty(xa,"__esModule",{value:!0});xa.OAuthClientAuthHandler=void 0;xa.getErrorFromOAuthErrorResponse=rp;var an=ct(),tp=yn(),np=["PUT","POST","PATCH"];class ka{#e=tp.createCrypto();#t;transporter;constructor(h){if(h&&"clientId"in h)this.#t=h,this.transporter=new an.Gaxios;else this.#t=h?.clientAuthentication,this.transporter=h?.transporter||new an.Gaxios}applyClientAuthenticationOptions(h,f){if(h.headers=an.Gaxios.mergeHeaders(h.headers),this.injectAuthenticatedHeaders(h,f),!f)this.injectAuthenticatedRequestBody(h)}injectAuthenticatedHeaders(h,f){if(f)h.headers=an.Gaxios.mergeHeaders(h.headers,{authorization:`Bearer ${f}`});else if(this.#t?.confidentialClientType==="basic"){h.headers=an.Gaxios.mergeHeaders(h.headers);let g=this.#t.clientId,y=this.#t.clientSecret||"",_=this.#e.encodeBase64StringUtf8(`${g}:${y}`);an.Gaxios.mergeHeaders(h.headers,{authorization:`Basic ${_}`})}}injectAuthenticatedRequestBody(h){if(this.#t?.confidentialClientType==="request-body"){let f=(h.method||"GET").toUpperCase();if(!np.includes(f))throw Error(`${f} HTTP method does not support ${this.#t.confidentialClientType} client authentication`);let y=new Headers(h.headers).get("content-type");if(y?.startsWith("application/x-www-form-urlencoded")||h.data instanceof URLSearchParams){let _=new URLSearchParams(h.data??"");_.append("client_id",this.#t.clientId),_.append("client_secret",this.#t.clientSecret||""),h.data=_}else if(y?.startsWith("application/json"))h.data=h.data||{},Object.assign(h.data,{client_id:this.#t.clientId,client_secret:this.#t.clientSecret||""});else throw Error(`${y} 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"]}}}}xa.OAuthClientAuthHandler=ka;function rp(h,f){let{error:g,error_description:y,error_uri:_}=h,w=`Error code ${g}`;if(typeof y<"u")w+=`: ${y}`;if(typeof _<"u")w+=` - ${_}`;let A=Error(w);if(f){let S=Object.keys(f);if(f.stack)S.push("stack");S.forEach((k)=>{if(k!=="message")Object.defineProperty(A,k,{value:f[k],writable:!1,enumerable:!0})})}return A}});var qn=i(function(Ia){Object.defineProperty(Ia,"__esModule",{value:!0});Ia.StsCredentials=void 0;var ip=ct(),op=wt(),Ra=Br(),ap=bt();class Vr extends Ra.OAuthClientAuthHandler{#e;constructor(h={tokenExchangeEndpoint:""},f){if(typeof h!=="object"||h instanceof URL)h={tokenExchangeEndpoint:h,clientAuthentication:f};super(h);this.#e=h.tokenExchangeEndpoint}async exchangeToken(h,f,g){let y={grant_type:h.grantType,resource:h.resource,audience:h.audience,scope:h.scope?.join(" "),requested_token_type:h.requestedTokenType,subject_token:h.subjectToken,subject_token_type:h.subjectTokenType,actor_token:h.actingParty?.actorToken,actor_token_type:h.actingParty?.actorTokenType,options:g&&JSON.stringify(g)},_={...Vr.RETRY_CONFIG,url:this.#e.toString(),method:"POST",headers:f,data:new URLSearchParams(ap.removeUndefinedValuesInObject(y)),responseType:"json"};op.AuthClient.setMethodName(_,"exchangeToken"),this.applyClientAuthenticationOptions(_);try{let w=await this.transporter.request(_),A=w.data;return A.res=w,A}catch(w){if(w instanceof ip.GaxiosError&&w.response)throw Ra.getErrorFromOAuthErrorResponse(w.response.data,w);throw w}}}Ia.StsCredentials=Vr});var Wt=i(function(ja){Object.defineProperty(ja,"__esModule",{value:!0});ja.BaseExternalAccountClient=ja.CLOUD_RESOURCE_MANAGER=ja.EXTERNAL_ACCOUNT_TYPE=ja.EXPIRATION_TIME_OFFSET=void 0;var cp=ct(),lp=c("stream"),Wr=wt(),up=qn(),Pa=bt(),dp=Sr(),hp="urn:ietf:params:oauth:grant-type:token-exchange",pp="urn:ietf:params:oauth:token-type:access_token",Jr="https://www.googleapis.com/auth/cloud-platform",fp=3600;ja.EXPIRATION_TIME_OFFSET=300000;ja.EXTERNAL_ACCOUNT_TYPE="external_account";ja.CLOUD_RESOURCE_MANAGER="https://cloudresourcemanager.googleapis.com/v1/projects/";var mp="//iam\\.googleapis\\.com/locations/[^/]+/workforcePools/[^/]+/providers/.+",yp="https://sts.{universeDomain}/v1/token";class Fn extends Wr.AuthClient{scopes;projectNumber;audience;subjectTokenType;stsCredential;clientAuth;credentialSourceType;cachedAccessToken;serviceAccountImpersonationUrl;serviceAccountImpersonationLifetime;workforcePoolUserProject;configLifetimeRequested;tokenUrl;cloudResourceManagerURL;supplierContext;#e=null;constructor(h){super(h);let f=Pa.originalOrCamelOptions(h),g=f.get("type");if(g&&g!==ja.EXTERNAL_ACCOUNT_TYPE)throw Error(`Expected "${ja.EXTERNAL_ACCOUNT_TYPE}" type but received "${h.type}"`);let y=f.get("client_id"),_=f.get("client_secret");this.tokenUrl=f.get("token_url")??yp.replace("{universeDomain}",this.universeDomain);let w=f.get("subject_token_type"),A=f.get("workforce_pool_user_project"),S=f.get("service_account_impersonation_url"),k=f.get("service_account_impersonation"),V=Pa.originalOrCamelOptions(k).get("token_lifetime_seconds");if(this.cloudResourceManagerURL=new URL(f.get("cloud_resource_manager_url")||`https://cloudresourcemanager.${this.universeDomain}/v1/projects/`),y)this.clientAuth={confidentialClientType:"basic",clientId:y,clientSecret:_};this.stsCredential=new up.StsCredentials({tokenExchangeEndpoint:this.tokenUrl,clientAuthentication:this.clientAuth}),this.scopes=f.get("scopes")||[Jr],this.cachedAccessToken=null,this.audience=f.get("audience"),this.subjectTokenType=w,this.workforcePoolUserProject=A;let P=new RegExp(mp);if(this.workforcePoolUserProject&&!this.audience.match(P))throw Error("workforcePoolUserProject should not be set for non-workforce pool credentials.");if(this.serviceAccountImpersonationUrl=S,this.serviceAccountImpersonationLifetime=V,this.serviceAccountImpersonationLifetime)this.configLifetimeRequested=!0;else this.configLifetimeRequested=!1,this.serviceAccountImpersonationLifetime=fp;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 RangeError(`URL is too long: ${this.serviceAccountImpersonationUrl}`);return/serviceAccounts\/(?<email>[^:]+):generateAccessToken$/.exec(this.serviceAccountImpersonationUrl)?.groups?.email||null}return null}setCredentials(h){super.setCredentials(h),this.cachedAccessToken=h}async getAccessToken(){if(!this.cachedAccessToken||this.isExpired(this.cachedAccessToken))await this.refreshAccessTokenAsync();return{token:this.cachedAccessToken.access_token,res:this.cachedAccessToken.res}}async getRequestHeaders(){let h=await this.getAccessToken(),f=new Headers({authorization:`Bearer ${h.token}`});return this.addSharedMetadataHeaders(f)}request(h,f){if(f)this.requestAsync(h).then((g)=>f(null,g),(g)=>f(g,g.response));else return this.requestAsync(h)}async getProjectId(){let h=this.projectNumber||this.workforcePoolUserProject;if(this.projectId)return this.projectId;else if(h){let f=await this.getRequestHeaders(),g={...Fn.RETRY_CONFIG,headers:f,url:`${this.cloudResourceManagerURL.toString()}${h}`,responseType:"json"};Wr.AuthClient.setMethodName(g,"getProjectId");let y=await this.transporter.request(g);return this.projectId=y.data.projectId,this.projectId}return null}async requestAsync(h,f=!1){let g;try{let y=await this.getRequestHeaders();h.headers=cp.Gaxios.mergeHeaders(h.headers),this.addUserProjectAndAuthHeaders(h.headers,y),g=await this.transporter.request(h)}catch(y){let _=y.response;if(_){let w=_.status,A=_.config.data instanceof lp.Readable;if(!f&&(w===401||w===403)&&!A&&this.forceRefreshOnFailure)return await this.refreshAccessTokenAsync(),await this.requestAsync(h,!0)}throw y}return g}async refreshAccessTokenAsync(){this.#e=this.#e||this.#t();try{return await this.#e}finally{this.#e=null}}async#t(){let h=await this.retrieveSubjectToken(),f={grantType:hp,audience:this.audience,requestedTokenType:pp,subjectToken:h,subjectTokenType:this.subjectTokenType,scope:this.serviceAccountImpersonationUrl?[Jr]:this.getScopesArray()},g=!this.clientAuth&&this.workforcePoolUserProject?{userProject:this.workforcePoolUserProject}:void 0,y=new Headers({"x-goog-api-client":this.getMetricsHeaderValue()}),_=await this.stsCredential.exchangeToken(f,y,g);if(this.serviceAccountImpersonationUrl)this.cachedAccessToken=await this.getImpersonatedAccessToken(_.access_token);else if(_.expires_in)this.cachedAccessToken={access_token:_.access_token,expiry_date:new Date().getTime()+_.expires_in*1000,res:_.res};else this.cachedAccessToken={access_token:_.access_token,res:_.res};return 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(h){let f=h.match(/\/projects\/([^/]+)/);if(!f)return null;return f[1]}async getImpersonatedAccessToken(h){let f={...Fn.RETRY_CONFIG,url:this.serviceAccountImpersonationUrl,method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${h}`},data:{scope:this.getScopesArray(),lifetime:this.serviceAccountImpersonationLifetime+"s"},responseType:"json"};Wr.AuthClient.setMethodName(f,"getImpersonatedAccessToken");let g=await this.transporter.request(f),y=g.data;return{access_token:y.accessToken,expiry_date:new Date(y.expireTime).getTime(),res:g}}isExpired(h){let f=new Date().getTime();return h.expiry_date?f>=h.expiry_date-this.eagerRefreshThresholdMillis:!1}getScopesArray(){if(typeof this.scopes==="string")return[this.scopes];return this.scopes||[Jr]}getMetricsHeaderValue(){let h=process.version.replace(/^v/,""),f=this.serviceAccountImpersonationUrl!==void 0,g=this.credentialSourceType?this.credentialSourceType:"unknown";return`gl-node/${h} auth/${dp.pkg.version} google-byoid-sdk source/${g} sa-impersonation/${f} config-lifetime/${this.configLifetimeRequested}`}getTokenUrl(){return this.tokenUrl}}ja.BaseExternalAccountClient=Fn});var qa=i(function(Da){Object.defineProperty(Da,"__esModule",{value:!0});Da.FileSubjectTokenSupplier=void 0;var Yr=c("util"),zr=c("fs"),wp=Yr.promisify(zr.readFile??(()=>{})),vp=Yr.promisify(zr.realpath??(()=>{})),Ep=Yr.promisify(zr.lstat??(()=>{}));class Ma{filePath;formatType;subjectTokenFieldName;constructor(h){this.filePath=h.filePath,this.formatType=h.formatType,this.subjectTokenFieldName=h.subjectTokenFieldName}async getSubjectToken(){let h=this.filePath;try{if(h=await vp(h),!(await Ep(h)).isFile())throw Error()}catch(y){if(y instanceof Error)y.message=`The file at ${h} does not exist, or it is not a file. ${y.message}`;throw y}let f,g=await wp(h,{encoding:"utf8"});if(this.formatType==="text")f=g;else if(this.formatType==="json"&&this.subjectTokenFieldName)f=JSON.parse(g)[this.subjectTokenFieldName];if(!f)throw Error("Unable to parse the subject_token from the credential_source file");return f}}Da.FileSubjectTokenSupplier=Ma});var Ha=i(function(Ga){Object.defineProperty(Ga,"__esModule",{value:!0});Ga.UrlSubjectTokenSupplier=void 0;var Cp=wt();class Fa{url;headers;formatType;subjectTokenFieldName;additionalGaxiosOptions;constructor(h){this.url=h.url,this.formatType=h.formatType,this.subjectTokenFieldName=h.subjectTokenFieldName,this.headers=h.headers,this.additionalGaxiosOptions=h.additionalGaxiosOptions}async getSubjectToken(h){let f={...this.additionalGaxiosOptions,url:this.url,method:"GET",headers:this.headers,responseType:this.formatType};Cp.AuthClient.setMethodName(f,"getSubjectToken");let g;if(this.formatType==="text")g=(await h.transporter.request(f)).data;else if(this.formatType==="json"&&this.subjectTokenFieldName)g=(await h.transporter.request(f)).data[this.subjectTokenFieldName];if(!g)throw Error("Unable to parse the subject_token from the credential_source URL");return g}}Ga.UrlSubjectTokenSupplier=Fa});var Ja=i(function(Va){Object.defineProperty(Va,"__esModule",{value:!0});Va.CertificateSubjectTokenSupplier=Va.InvalidConfigurationError=Va.CertificateSourceUnavailableError=Va.CERTIFICATE_CONFIGURATION_ENV_VARIABLE=void 0;var $n=bt(),Gn=c("fs"),Hn=c("crypto"),bp=c("https");Va.CERTIFICATE_CONFIGURATION_ENV_VARIABLE="GOOGLE_API_CERTIFICATE_CONFIG";class Lt extends Error{constructor(h){super(h);this.name="CertificateSourceUnavailableError"}}Va.CertificateSourceUnavailableError=Lt;class xt extends Error{constructor(h){super(h);this.name="InvalidConfigurationError"}}Va.InvalidConfigurationError=xt;class Ba{certificateConfigPath;trustChainPath;cert;key;constructor(h){if(!h.useDefaultCertificateConfig&&!h.certificateConfigLocation)throw new xt("Either `useDefaultCertificateConfig` must be true or a `certificateConfigLocation` must be provided.");if(h.useDefaultCertificateConfig&&h.certificateConfigLocation)throw new xt("Both `useDefaultCertificateConfig` and `certificateConfigLocation` cannot be provided.");this.trustChainPath=h.trustChainPath,this.certificateConfigPath=h.certificateConfigLocation??""}async createMtlsHttpsAgent(){if(!this.key||!this.cert)throw new xt("Cannot create mTLS Agent with missing certificate or key");return new bp.Agent({key:this.key,cert:this.cert})}async getSubjectToken(){this.certificateConfigPath=await this.#e();let{certPath:h,keyPath:f}=await this.#t();return{cert:this.cert,key:this.key}=await this.#n(h,f),await this.#r(this.cert)}async#e(){let h=this.certificateConfigPath;if(h){if(await $n.isValidFile(h))return h;throw new Lt(`Provided certificate config path is invalid: ${h}`)}let f=process.env[Va.CERTIFICATE_CONFIGURATION_ENV_VARIABLE];if(f){if(await $n.isValidFile(f))return f;throw new Lt(`Path from environment variable "${Va.CERTIFICATE_CONFIGURATION_ENV_VARIABLE}" is invalid: ${f}`)}let g=$n.getWellKnownCertificateConfigFileLocation();if(await $n.isValidFile(g))return g;throw new Lt(`Could not find certificate configuration file. Searched override path, the "${Va.CERTIFICATE_CONFIGURATION_ENV_VARIABLE}" env var, and the gcloud path (${g}).`)}async#t(){let h=this.certificateConfigPath,f;try{f=await Gn.promises.readFile(h,"utf8")}catch(g){throw new Lt(`Failed to read certificate config file at: ${h}`)}try{let g=JSON.parse(f),y=g?.cert_configs?.workload?.cert_path,_=g?.cert_configs?.workload?.key_path;if(!y||!_)throw new xt(`Certificate config file (${h}) is missing required "cert_path" or "key_path" in the workload config.`);return{certPath:y,keyPath:_}}catch(g){if(g instanceof xt)throw g;throw new xt(`Failed to parse certificate config from ${h}: ${g.message}`)}}async#n(h,f){let g,y;try{g=await Gn.promises.readFile(h),new Hn.X509Certificate(g)}catch(_){let w=_ instanceof Error?_.message:String(_);throw new Lt(`Failed to read certificate file at ${h}: ${w}`)}try{y=await Gn.promises.readFile(f),Hn.createPrivateKey(y)}catch(_){let w=_ instanceof Error?_.message:String(_);throw new Lt(`Failed to read private key file at ${f}: ${w}`)}return{cert:g,key:y}}async#r(h){let f=new Hn.X509Certificate(h);if(!this.trustChainPath)return JSON.stringify([f.raw.toString("base64")]);try{let _=((await Gn.promises.readFile(this.trustChainPath,"utf8")).match(/-----BEGIN CERTIFICATE-----[^-]+-----END CERTIFICATE-----/g)??[]).map((S,k)=>{try{return new Hn.X509Certificate(S)}catch(V){let P=V instanceof Error?V.message:String(V);throw new xt(`Failed to parse certificate at index ${k} in trust chain file ${this.trustChainPath}: ${P}`)}}),w=_.findIndex((S)=>f.raw.equals(S.raw)),A;if(w===-1)A=[f,..._];else if(w===0)A=_;else throw new xt(`Leaf certificate exists in the trust chain but is not the first entry (found at index ${w}).`);return JSON.stringify(A.map((S)=>S.raw.toString("base64")))}catch(g){if(g instanceof xt)throw g;let y=g instanceof Error?g.message:String(g);throw new Lt(`Failed to process certificate chain from ${this.trustChainPath}: ${y}`)}}}Va.CertificateSubjectTokenSupplier=Ba});var Zr=i(function(za){Object.defineProperty(za,"__esModule",{value:!0});za.IdentityPoolClient=void 0;var kp=Wt(),Xr=bt(),xp=qa(),Op=Ha(),Ka=Ja(),Rp=qn(),Ya=ct();class Qr extends kp.BaseExternalAccountClient{subjectTokenSupplier;constructor(h){super(h);let f=Xr.originalOrCamelOptions(h),g=f.get("credential_source"),y=f.get("subject_token_supplier");if(!g&&!y)throw Error("A credential source or subject token supplier must be specified.");if(g&&y)throw Error("Only one of credential source or subject token supplier can be specified.");if(y)this.subjectTokenSupplier=y,this.credentialSourceType="programmatic";else{let _=Xr.originalOrCamelOptions(g),w=Xr.originalOrCamelOptions(_.get("format")),A=w.get("type")||"text",S=w.get("subject_token_field_name");if(A!=="json"&&A!=="text")throw Error(`Invalid credential_source format "${A}"`);if(A==="json"&&!S)throw Error("Missing subject_token_field_name for JSON credential_source format");let k=_.get("file"),V=_.get("url"),P=_.get("certificate"),ne=_.get("headers");if(k&&V||V&&P||k&&P)throw Error('No valid Identity Pool "credential_source" provided, must be either file, url, or certificate.');else if(k)this.credentialSourceType="file",this.subjectTokenSupplier=new xp.FileSubjectTokenSupplier({filePath:k,formatType:A,subjectTokenFieldName:S});else if(V)this.credentialSourceType="url",this.subjectTokenSupplier=new Op.UrlSubjectTokenSupplier({url:V,formatType:A,subjectTokenFieldName:S,headers:ne,additionalGaxiosOptions:Qr.RETRY_CONFIG});else if(P){this.credentialSourceType="certificate";let Z=new Ka.CertificateSubjectTokenSupplier({useDefaultCertificateConfig:P.use_default_certificate_config,certificateConfigLocation:P.certificate_config_location,trustChainPath:P.trust_chain_path});this.subjectTokenSupplier=Z}else throw Error('No valid Identity Pool "credential_source" provided, must be either file, url, or certificate.')}}async retrieveSubjectToken(){let h=await this.subjectTokenSupplier.getSubjectToken(this.supplierContext);if(this.subjectTokenSupplier instanceof Ka.CertificateSubjectTokenSupplier){let f=await this.subjectTokenSupplier.createMtlsHttpsAgent();this.stsCredential=new Rp.StsCredentials({tokenExchangeEndpoint:this.getTokenUrl(),clientAuthentication:this.clientAuth,transporter:new Ya.Gaxios({agent:f})}),this.transporter=new Ya.Gaxios({...this.transporter.defaults||{},agent:f})}return h}}za.IdentityPoolClient=Qr});var es=i(function(tc){Object.defineProperty(tc,"__esModule",{value:!0});tc.AwsRequestSigner=void 0;var Vn=ct(),Za=yn(),Qa="AWS4-HMAC-SHA256",Ip="aws4_request";class ec{getCredentials;region;crypto;constructor(h,f){this.getCredentials=h,this.region=f,this.crypto=Za.createCrypto()}async getRequestOptions(h){if(!h.url)throw RangeError('"url" is required in "amzOptions"');let f=typeof h.data==="object"?JSON.stringify(h.data):h.data,g=h.url,y=h.method||"GET",_=h.body||f,w=h.headers,A=await this.getCredentials(),S=new URL(g);if(typeof _!=="string"&&_!==void 0)throw TypeError(`'requestPayload' is expected to be a string if provided. Got: ${_}`);let k=await Pp({crypto:this.crypto,host:S.host,canonicalUri:S.pathname,canonicalQuerystring:S.search.slice(1),method:y,region:this.region,securityCredentials:A,requestPayload:_,additionalAmzHeaders:w}),V=Vn.Gaxios.mergeHeaders(k.amzDate?{"x-amz-date":k.amzDate}:{},{authorization:k.authorizationHeader,host:S.host},w||{});if(A.token)Vn.Gaxios.mergeHeaders(V,{"x-amz-security-token":A.token});let P={url:g,method:y,headers:V};if(_!==void 0)P.body=_;return P}}tc.AwsRequestSigner=ec;async function En(h,f,g){return await h.signWithHmacSha256(f,g)}async function Np(h,f,g,y,_){let w=await En(h,`AWS4${f}`,g),A=await En(h,w,y),S=await En(h,A,_);return await En(h,S,"aws4_request")}async function Pp(h){let f=Vn.Gaxios.mergeHeaders(h.additionalAmzHeaders),g=h.requestPayload||"",y=h.host.split(".")[0],_=new Date,w=_.toISOString().replace(/[-:]/g,"").replace(/\.[0-9]+/,""),A=_.toISOString().replace(/[-]/g,"").replace(/T.*/,"");if(h.securityCredentials.token)f.set("x-amz-security-token",h.securityCredentials.token);let S=Vn.Gaxios.mergeHeaders({host:h.host},f.has("date")?{}:{"x-amz-date":w},f),k="",V=[...S.keys()].sort();V.forEach((B)=>{k+=`${B}:${S.get(B)}
14
+ `});let P=V.join(";"),ne=await h.crypto.sha256DigestHex(g),Z=`${h.method.toUpperCase()}
15
+ ${h.canonicalUri}
16
+ ${h.canonicalQuerystring}
17
+ ${k}
18
+ ${P}
19
+ ${ne}`,K=`${A}/${h.region}/${y}/${Ip}`,X=`${Qa}
20
+ ${w}
21
+ ${K}
22
+ `+await h.crypto.sha256DigestHex(Z),re=await Np(h.crypto,h.securityCredentials.secretAccessKey,A,h.region,y),de=await En(h.crypto,re,X),L=`${Qa} Credential=${h.securityCredentials.accessKeyId}/${K}, SignedHeaders=${P}, Signature=${Za.fromArrayBufferToHex(de)}`;return{amzDate:f.has("date")?void 0:w,authorizationHeader:L,canonicalQuerystring:h.canonicalQuerystring}}});var oc=i(function(sc){Object.defineProperty(sc,"__esModule",{value:!0});sc.DefaultAwsSecurityCredentialsSupplier=void 0;var Wn=wt();class rc{regionUrl;securityCredentialsUrl;imdsV2SessionTokenUrl;additionalGaxiosOptions;constructor(h){this.regionUrl=h.regionUrl,this.securityCredentialsUrl=h.securityCredentialsUrl,this.imdsV2SessionTokenUrl=h.imdsV2SessionTokenUrl,this.additionalGaxiosOptions=h.additionalGaxiosOptions}async getAwsRegion(h){if(this.#r)return this.#r;let f=new Headers;if(!this.#r&&this.imdsV2SessionTokenUrl)f.set("x-aws-ec2-metadata-token",await this.#e(h.transporter));if(!this.regionUrl)throw RangeError('Unable to determine AWS region due to missing "options.credential_source.region_url"');let g={...this.additionalGaxiosOptions,url:this.regionUrl,method:"GET",responseType:"text",headers:f};Wn.AuthClient.setMethodName(g,"getAwsRegion");let y=await h.transporter.request(g);return y.data.substr(0,y.data.length-1)}async getAwsSecurityCredentials(h){if(this.#s)return this.#s;let f=new Headers;if(this.imdsV2SessionTokenUrl)f.set("x-aws-ec2-metadata-token",await this.#e(h.transporter));let g=await this.#t(f,h.transporter),y=await this.#n(g,f,h.transporter);return{accessKeyId:y.AccessKeyId,secretAccessKey:y.SecretAccessKey,token:y.Token}}async#e(h){let f={...this.additionalGaxiosOptions,url:this.imdsV2SessionTokenUrl,method:"PUT",responseType:"text",headers:{"x-aws-ec2-metadata-token-ttl-seconds":"300"}};return Wn.AuthClient.setMethodName(f,"#getImdsV2SessionToken"),(await h.request(f)).data}async#t(h,f){if(!this.securityCredentialsUrl)throw Error('Unable to determine AWS role name due to missing "options.credential_source.url"');let g={...this.additionalGaxiosOptions,url:this.securityCredentialsUrl,method:"GET",responseType:"text",headers:h};return Wn.AuthClient.setMethodName(g,"#getAwsRoleName"),(await f.request(g)).data}async#n(h,f,g){let y={...this.additionalGaxiosOptions,url:`${this.securityCredentialsUrl}/${h}`,headers:f,responseType:"json"};return Wn.AuthClient.setMethodName(y,"#retrieveAwsSecurityCredentials"),(await g.request(y)).data}get#r(){return process.env.AWS_REGION||process.env.AWS_DEFAULT_REGION||null}get#s(){if(process.env.AWS_ACCESS_KEY_ID&&process.env.AWS_SECRET_ACCESS_KEY)return{accessKeyId:process.env.AWS_ACCESS_KEY_ID,secretAccessKey:process.env.AWS_SECRET_ACCESS_KEY,token:process.env.AWS_SESSION_TOKEN};return null}}sc.DefaultAwsSecurityCredentialsSupplier=rc});var ts=i(function(cc){Object.defineProperty(cc,"__esModule",{value:!0});cc.AwsClient=void 0;var jp=es(),Up=Wt(),Mp=oc(),ac=bt(),Dp=ct();class Jn extends Up.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(h){super(h);let f=ac.originalOrCamelOptions(h),g=f.get("credential_source"),y=f.get("aws_security_credentials_supplier");if(!g&&!y)throw Error("A credential source or AWS security credentials supplier must be specified.");if(g&&y)throw Error("Only one of credential source or AWS security credentials supplier can be specified.");if(y)this.awsSecurityCredentialsSupplier=y,this.regionalCredVerificationUrl=Jn.#e,this.credentialSourceType="programmatic";else{let _=ac.originalOrCamelOptions(g);this.environmentId=_.get("environment_id");let w=_.get("region_url"),A=_.get("url"),S=_.get("imdsv2_session_token_url");this.awsSecurityCredentialsSupplier=new Mp.DefaultAwsSecurityCredentialsSupplier({regionUrl:w,securityCredentialsUrl:A,imdsV2SessionTokenUrl:S}),this.regionalCredVerificationUrl=_.get("regional_cred_verification_url"),this.credentialSourceType="aws",this.validateEnvironmentId()}this.awsRequestSigner=null,this.region=""}validateEnvironmentId(){let h=this.environmentId?.match(/^(aws)(\d+)$/);if(!h||!this.regionalCredVerificationUrl)throw Error('No valid AWS "credential_source" provided');else if(parseInt(h[2],10)!==1)throw Error(`aws version "${h[2]}" is not supported in the current build.`)}async retrieveSubjectToken(){if(!this.awsRequestSigner)this.region=await this.awsSecurityCredentialsSupplier.getAwsRegion(this.supplierContext),this.awsRequestSigner=new jp.AwsRequestSigner(async()=>this.awsSecurityCredentialsSupplier.getAwsSecurityCredentials(this.supplierContext),this.region);let h=await this.awsRequestSigner.getRequestOptions({...Jn.RETRY_CONFIG,url:this.regionalCredVerificationUrl.replace("{region}",this.region),method:"POST"}),f=[];return Dp.Gaxios.mergeHeaders({"x-goog-cloud-target-resource":this.audience},h.headers).forEach((y,_)=>f.push({key:_,value:y})),encodeURIComponent(JSON.stringify({url:h.url,method:h.method,headers:f}))}}cc.AwsClient=Jn});var ls=i(function(hc){Object.defineProperty(hc,"__esModule",{value:!0});hc.InvalidSubjectTokenError=hc.InvalidMessageFieldError=hc.InvalidCodeFieldError=hc.InvalidTokenTypeFieldError=hc.InvalidExpirationTimeFieldError=hc.InvalidSuccessFieldError=hc.InvalidVersionFieldError=hc.ExecutableResponseError=hc.ExecutableResponse=void 0;var Kn="urn:ietf:params:oauth:token-type:saml2",ns="urn:ietf:params:oauth:token-type:id_token",rs="urn:ietf:params:oauth:token-type:jwt";class uc{version;success;expirationTime;tokenType;errorCode;errorMessage;subjectToken;constructor(h){if(!h.version)throw new ss("Executable response must contain a 'version' field.");if(h.success===void 0)throw new is("Executable response must contain a 'success' field.");if(this.version=h.version,this.success=h.success,this.success){if(this.expirationTime=h.expiration_time,this.tokenType=h.token_type,this.tokenType!==Kn&&this.tokenType!==ns&&this.tokenType!==rs)throw new os(`Executable response must contain a 'token_type' field when successful and it must be one of ${ns}, ${rs}, or ${Kn}.`);if(this.tokenType===Kn){if(!h.saml_response)throw new Yn(`Executable response must contain a 'saml_response' field when token_type=${Kn}.`);this.subjectToken=h.saml_response}else{if(!h.id_token)throw new Yn(`Executable response must contain a 'id_token' field when token_type=${ns} or ${rs}.`);this.subjectToken=h.id_token}}else{if(!h.code)throw new as("Executable response must contain a 'code' field when unsuccessful.");if(!h.message)throw new cs("Executable response must contain a 'message' field when unsuccessful.");this.errorCode=h.code,this.errorMessage=h.message}}isValid(){return!this.isExpired()&&this.success}isExpired(){return this.expirationTime!==void 0&&this.expirationTime<Math.round(Date.now()/1000)}}hc.ExecutableResponse=uc;class qt extends Error{constructor(h){super(h);Object.setPrototypeOf(this,new.target.prototype)}}hc.ExecutableResponseError=qt;class ss extends qt{}hc.InvalidVersionFieldError=ss;class is extends qt{}hc.InvalidSuccessFieldError=is;class dc extends qt{}hc.InvalidExpirationTimeFieldError=dc;class os extends qt{}hc.InvalidTokenTypeFieldError=os;class as extends qt{}hc.InvalidCodeFieldError=as;class cs extends qt{}hc.InvalidMessageFieldError=cs;class Yn extends qt{}hc.InvalidSubjectTokenError=Yn});var ps=i(function(fc){Object.defineProperty(fc,"__esModule",{value:!0});fc.PluggableAuthHandler=fc.ExecutableError=void 0;var Qt=ls(),Wp=c("child_process"),us=c("fs");class ds extends Error{code;constructor(h,f){super(`The executable failed with exit code: ${f} and error message: ${h}.`);this.code=f,Object.setPrototypeOf(this,new.target.prototype)}}fc.ExecutableError=ds;class hs{commandComponents;timeoutMillis;outputFile;constructor(h){if(!h.command)throw Error("No command provided.");if(this.commandComponents=hs.parseCommand(h.command),this.timeoutMillis=h.timeoutMillis,!this.timeoutMillis)throw Error("No timeoutMillis provided.");this.outputFile=h.outputFile}retrieveResponseFromExecutable(h){return new Promise((f,g)=>{let y=Wp.spawn(this.commandComponents[0],this.commandComponents.slice(1),{env:{...process.env,...Object.fromEntries(h)}}),_="";y.stdout.on("data",(A)=>{_+=A}),y.stderr.on("data",(A)=>{_+=A});let w=setTimeout(()=>(y.removeAllListeners(),y.kill(),g(Error("The executable failed to finish within the timeout specified."))),this.timeoutMillis);y.on("close",(A)=>{if(clearTimeout(w),A===0)try{let S=JSON.parse(_),k=new Qt.ExecutableResponse(S);return f(k)}catch(S){if(S instanceof Qt.ExecutableResponseError)return g(S);return g(new Qt.ExecutableResponseError(`The executable returned an invalid response: ${_}`))}else return g(new ds(_,A.toString()))})})}async retrieveCachedResponse(){if(!this.outputFile||this.outputFile.length===0)return;let h;try{h=await us.promises.realpath(this.outputFile)}catch{return}if(!(await us.promises.lstat(h)).isFile())return;let f=await us.promises.readFile(h,{encoding:"utf8"});if(f==="")return;try{let g=JSON.parse(f);if(new Qt.ExecutableResponse(g).isValid())return new Qt.ExecutableResponse(g);return}catch(g){if(g instanceof Qt.ExecutableResponseError)throw g;throw new Qt.ExecutableResponseError(`The output file contained an invalid response: ${f}`)}}static parseCommand(h){let f=h.match(/(?:[^\s"]+|"[^"]*")+/g);if(!f)throw Error(`Provided command: "${h}" could not be parsed.`);for(let g=0;g<f.length;g++)if(f[g][0]==='"'&&f[g].slice(-1)==='"')f[g]=f[g].slice(1,-1);return f}}fc.PluggableAuthHandler=hs});var gs=i(function(fs){Object.defineProperty(fs,"__esModule",{value:!0});fs.PluggableAuthClient=fs.ExecutableError=void 0;var Kp=Wt(),Yp=ls(),Tc=ps(),zp=ps();Object.defineProperty(fs,"ExecutableError",{enumerable:!0,get:function(){return zp.ExecutableError}});var Xp=30000,mc=5000,yc=120000,Qp="GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES",_c=1;class wc extends Kp.BaseExternalAccountClient{command;timeoutMillis;outputFile;handler;constructor(h){super(h);if(!h.credential_source.executable)throw Error('No valid Pluggable Auth "credential_source" provided.');if(this.command=h.credential_source.executable.command,!this.command)throw Error('No valid Pluggable Auth "credential_source" provided.');if(h.credential_source.executable.timeout_millis===void 0)this.timeoutMillis=Xp;else if(this.timeoutMillis=h.credential_source.executable.timeout_millis,this.timeoutMillis<mc||this.timeoutMillis>yc)throw Error(`Timeout must be between ${mc} and ${yc} milliseconds.`);this.outputFile=h.credential_source.executable.output_file,this.handler=new Tc.PluggableAuthHandler({command:this.command,timeoutMillis:this.timeoutMillis,outputFile:this.outputFile}),this.credentialSourceType="executable"}async retrieveSubjectToken(){if(process.env[Qp]!=="1")throw Error("Pluggable Auth executables need to be explicitly allowed to run by setting the GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES environment Variable to 1.");let h=void 0;if(this.outputFile)h=await this.handler.retrieveCachedResponse();if(!h){let f=new Map;if(f.set("GOOGLE_EXTERNAL_ACCOUNT_AUDIENCE",this.audience),f.set("GOOGLE_EXTERNAL_ACCOUNT_TOKEN_TYPE",this.subjectTokenType),f.set("GOOGLE_EXTERNAL_ACCOUNT_INTERACTIVE","0"),this.outputFile)f.set("GOOGLE_EXTERNAL_ACCOUNT_OUTPUT_FILE",this.outputFile);let g=this.getServiceAccountEmail();if(g)f.set("GOOGLE_EXTERNAL_ACCOUNT_IMPERSONATED_EMAIL",g);h=await this.handler.retrieveResponseFromExecutable(f)}if(h.version>_c)throw Error(`Version of executable is not currently supported, maximum supported version is ${_c}.`);if(!h.success)throw new Tc.ExecutableError(h.errorMessage,h.errorCode);if(this.outputFile){if(!h.expirationTime)throw new Yp.InvalidExpirationTimeFieldError("The executable response must contain the `expiration_time` field for successful responses when an output_file has been specified in the configuration.")}if(h.isExpired())throw Error("Executable response is expired.");return h.subjectToken}}fs.PluggableAuthClient=wc});var ms=i(function(Cc){Object.defineProperty(Cc,"__esModule",{value:!0});Cc.ExternalAccountClient=void 0;var Zp=Wt(),ef=Zr(),tf=ts(),nf=gs(),rf=bt();class Ec{constructor(){throw 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(h){if(!rf.isAdcWarningSuppressed())console.warn("The `fromJSON` method does not validate the credential configuration. A security risk occurs when a credential configuration configured with malicious URLs is used. When the credential configuration is accepted from an untrusted source, you should validate it before using it with this method. For more details, see https://cloud.google.com/docs/authentication/external/externally-sourced-credentials.");if(h&&h.type===Zp.EXTERNAL_ACCOUNT_TYPE)if(h.credential_source?.environment_id)return new tf.AwsClient(h);else if(h.credential_source?.executable)return new nf.PluggableAuthClient(h);else return new ef.IdentityPoolClient(h);else return null}}Cc.ExternalAccountClient=Ec});var _s=i(function(Rc){Object.defineProperty(Rc,"__esModule",{value:!0});Rc.ExternalAccountAuthorizedUserClient=Rc.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE=void 0;var Ac=wt(),Sc=Br(),kc=ct(),sf=c("stream"),of=Wt();Rc.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE="external_account_authorized_user";var af="https://sts.{universeDomain}/v1/oauthtoken";class ys extends Sc.OAuthClientAuthHandler{#e;constructor(h){super(h);this.#e=h.tokenRefreshEndpoint}async refreshToken(h,f){let g={...ys.RETRY_CONFIG,url:this.#e,method:"POST",headers:f,data:new URLSearchParams({grant_type:"refresh_token",refresh_token:h}),responseType:"json"};Ac.AuthClient.setMethodName(g,"refreshToken"),this.applyClientAuthenticationOptions(g);try{let y=await this.transporter.request(g),_=y.data;return _.res=y,_}catch(y){if(y instanceof kc.GaxiosError&&y.response)throw Sc.getErrorFromOAuthErrorResponse(y.response.data,y);throw y}}}class Oc extends Ac.AuthClient{cachedAccessToken;externalAccountAuthorizedUserHandler;refreshToken;constructor(h){super(h);if(h.universe_domain)this.universeDomain=h.universe_domain;this.refreshToken=h.refresh_token;let f={confidentialClientType:"basic",clientId:h.client_id,clientSecret:h.client_secret};if(this.externalAccountAuthorizedUserHandler=new ys({tokenRefreshEndpoint:h.token_url??af.replace("{universeDomain}",this.universeDomain),transporter:this.transporter,clientAuthentication:f}),this.cachedAccessToken=null,this.quotaProjectId=h.quota_project_id,typeof h?.eagerRefreshThresholdMillis!=="number")this.eagerRefreshThresholdMillis=of.EXPIRATION_TIME_OFFSET;else this.eagerRefreshThresholdMillis=h.eagerRefreshThresholdMillis;this.forceRefreshOnFailure=!!h?.forceRefreshOnFailure}async getAccessToken(){if(!this.cachedAccessToken||this.isExpired(this.cachedAccessToken))await this.refreshAccessTokenAsync();return{token:this.cachedAccessToken.access_token,res:this.cachedAccessToken.res}}async getRequestHeaders(){let h=await this.getAccessToken(),f=new Headers({authorization:`Bearer ${h.token}`});return this.addSharedMetadataHeaders(f)}request(h,f){if(f)this.requestAsync(h).then((g)=>f(null,g),(g)=>f(g,g.response));else return this.requestAsync(h)}async requestAsync(h,f=!1){let g;try{let y=await this.getRequestHeaders();h.headers=kc.Gaxios.mergeHeaders(h.headers),this.addUserProjectAndAuthHeaders(h.headers,y),g=await this.transporter.request(h)}catch(y){let _=y.response;if(_){let w=_.status,A=_.config.data instanceof sf.Readable;if(!f&&(w===401||w===403)&&!A&&this.forceRefreshOnFailure)return await this.refreshAccessTokenAsync(),await this.requestAsync(h,!0)}throw y}return g}async refreshAccessTokenAsync(){let h=await this.externalAccountAuthorizedUserHandler.refreshToken(this.refreshToken);if(this.cachedAccessToken={access_token:h.access_token,expiry_date:new Date().getTime()+h.expires_in*1000,res:h.res},h.refresh_token!==void 0)this.refreshToken=h.refresh_token;return this.cachedAccessToken}isExpired(h){let f=new Date().getTime();return h.expiry_date?f>=h.expiry_date-this.eagerRefreshThresholdMillis:!1}}Rc.ExternalAccountAuthorizedUserClient=Oc});var vs=i(function(Nc){Object.defineProperty(Nc,"__esModule",{value:!0});Nc.GdchClient=Nc.GDCH_SERVICE_ACCOUNT_TYPE=void 0;var lf=c("crypto"),uf=c("fs"),df=c("https"),hf=Ht(),pf=3600;Nc.GDCH_SERVICE_ACCOUNT_TYPE="gdch_service_account";class ws extends hf.OAuth2Client{projectId;privateKeyId;privateKey;serviceIdentityName;tokenServerUri;caCertPath;apiAudience;lifetime;gdchOptions;caAgentPromise;cachedCaCertPath;lastCaCertReadTime=0;CA_CERT_TTL_MS=300000;constructor(h={}){super(h);this.gdchOptions=h,this.projectId=h.projectId||void 0,this.privateKeyId=h.privateKeyId,this.privateKey=h.privateKey,this.serviceIdentityName=h.serviceIdentityName,this.tokenServerUri=h.tokenServerUri,this.caCertPath=h.caCertPath,this.apiAudience=h.apiAudience,this.lifetime=h.lifetime||pf,this.credentials={refresh_token:"gdch-placeholder",expiry_date:1}}createWithGdchAudience(h){if(!h)throw Error("Audience cannot be null or empty for GDCH service account credentials.");return new ws({...this.gdchOptions,projectId:this.projectId,privateKeyId:this.privateKeyId,privateKey:this.privateKey,serviceIdentityName:this.serviceIdentityName,tokenServerUri:this.tokenServerUri,caCertPath:this.caCertPath,lifetime:this.lifetime,apiAudience:h})}fromJSON(h){if(!h)throw Error("Must pass in a JSON object containing the GDCH credentials settings.");if(h.type!==Nc.GDCH_SERVICE_ACCOUNT_TYPE)throw Error(`The incoming JSON object does not have the "${Nc.GDCH_SERVICE_ACCOUNT_TYPE}" type`);if(h.format_version!=="1")throw Error("Only format version 1 is supported.");if(!h.project)throw Error("The incoming JSON object does not contain a project field");if(!h.private_key_id)throw Error("The incoming JSON object does not contain a private_key_id field");if(!h.private_key)throw Error("The incoming JSON object does not contain a private_key field");if(!h.name)throw Error("The incoming JSON object does not contain a name field");if(!h.token_uri)throw Error("The incoming JSON object does not contain a token_uri field");this.projectId=h.project,this.privateKeyId=h.private_key_id,this.privateKey=h.private_key,this.serviceIdentityName=h.name,this.tokenServerUri=h.token_uri,this.caCertPath=h.ca_cert_path,this.gdchOptions={...this.gdchOptions,projectId:h.project,privateKeyId:h.private_key_id,privateKey:h.private_key,serviceIdentityName:h.name,tokenServerUri:h.token_uri,caCertPath:h.ca_cert_path}}async refreshTokenNoCache(){if(!this.apiAudience)throw Error("Audience cannot be null or empty for GDCH service account credentials. Specify the audience by calling createWithGdchAudience.");if(!this.privateKey)throw Error("Private key is not configured for GDCH credentials.");if(!this.privateKeyId)throw Error("Private key ID is not configured for GDCH credentials.");if(!this.projectId)throw Error("Project is not configured for GDCH credentials.");if(!this.serviceIdentityName)throw Error("Service identity name is not configured for GDCH credentials.");if(!this.tokenServerUri)throw Error("Token server URI is not configured for GDCH credentials.");let h=this.createAssertion(),f={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:h,subject_token_type:"urn:k8s:params:oauth:token-type:serviceaccount"},g={url:this.tokenServerUri,method:"POST",headers:{"Content-Type":"application/json"},data:f,responseType:"json",timeout:1e4,retry:!0,retryConfig:{httpMethodsToRetry:["POST"],statusCodesToRetry:[[500,599]],noResponseRetries:3}};if(this.caCertPath)g.agent=await this.getCaAgent();try{let y=await this.transporter.request(g),_=y.data;if(!_.access_token)throw Error("Token response did not contain an access_token.");if(!_.expires_in)throw Error("Token response did not contain an expires_in field.");let w={access_token:_.access_token,token_type:"STS-Bearer",expiry_date:Date.now()+_.expires_in*1000};return this.emit("tokens",w),{res:y,tokens:w}}catch(y){if(y&&y.config&&y.config.data)try{if(typeof y.config.data==="string"){let _=JSON.parse(y.config.data);if(_.subject_token)_.subject_token="***REDACTED***",y.config.data=JSON.stringify(_)}else if(typeof y.config.data==="object"&&y.config.data.subject_token)y.config.data.subject_token="***REDACTED***"}catch{}if(y instanceof Error)y.message=`Error getting access token for GDCH service account: ${y.message}, iss: ${this.serviceIdentityName}`;throw y}}createAssertion(){let h={alg:"ES256",typ:"JWT",kid:this.privateKeyId},f=`system:serviceaccount:${this.projectId}:${this.serviceIdentityName}`,g=Math.floor(Date.now()/1000),y={iss:f,sub:f,iat:g,exp:g+this.lifetime,aud:this.tokenServerUri},_=this.base64UrlEncode(JSON.stringify(h)),w=this.base64UrlEncode(JSON.stringify(y)),A=`${_}.${w}`,S=lf.sign("sha256",Buffer.from(A),{key:this.privateKey,dsaEncoding:"ieee-p1363"}),k=this.base64UrlEncode(S);return`${A}.${k}`}async requestAsync(h,f=!1){if(this.caCertPath&&!h.agent){let g=(h.url||"").toString();if(!g.includes("googleapis.com")&&!g.includes("google.com"))h.agent=await this.getCaAgent()}return super.requestAsync(h,f)}getCaAgent(){if(!this.caCertPath){this.caAgentPromise=void 0,this.cachedCaCertPath=void 0,this.lastCaCertReadTime=0;return}let h=Date.now(),f=h-this.lastCaCertReadTime>this.CA_CERT_TTL_MS;if(this.caAgentPromise&&this.caCertPath===this.cachedCaCertPath&&!f)return this.caAgentPromise;this.cachedCaCertPath=this.caCertPath,this.lastCaCertReadTime=h;let g=this.caCertPath;return this.caAgentPromise=(async()=>{try{let y=await uf.promises.readFile(g);return new df.Agent({ca:y})}catch(y){if(this.cachedCaCertPath===g)this.caAgentPromise=void 0,this.cachedCaCertPath=void 0,this.lastCaCertReadTime=0;if(y instanceof Error)y.message=`Error reading certificate file from CA cert path, value '${g}': ${y.message}`;throw y}})(),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(h){return(typeof h==="string"?Buffer.from(h):h).toString("base64url")}}Nc.GdchClient=ws});var qc=i(function(Dc){Object.defineProperty(Dc,"__esModule",{value:!0});Dc.GoogleAuth=Dc.GoogleAuthExceptionMessages=void 0;var ff=c("child_process"),bn=c("fs"),gf=ct(),An=mn(),mf=c("os"),zn=c("path"),yf=yn(),_f=Pr(),Tf=jr(),wf=Ur(),Jt=Gr(),jc=$r(),ln=Hr(),vf=ms(),Cn=Wt(),Es=wt(),Uc=_s(),Cs=vs(),Yt=bt();Dc.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.
23
+ To learn more about authentication and Google APIs, visit:
24
+ https://cloud.google.com/docs/authentication/getting-started`,NO_CREDENTIALS_FOUND:`Unable to find credentials in current environment.
25
+ To learn more about authentication and Google APIs, visit:
26
+ 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.
27
+ To learn more about Universe Domain retrieval, visit:
28
+ https://cloud.google.com/compute/docs/metadata/predefined-metadata-keys`};class Mc{checkIsGCE=void 0;useJWTAccessWithScope;defaultServicePath;get isGCE(){return this.checkIsGCE}_findProjectIdPromise;_cachedProjectId;jsonContent=null;apiKey;cachedCredential=null;#e=null;defaultScopes;keyFilename;scopes;clientOptions={};constructor(h={}){if(this._cachedProjectId=h.projectId||null,this.cachedCredential=h.authClient||null,this.keyFilename=h.keyFilename||h.keyFile,this.keyFilename)console.warn("The `keyFilename` option is deprecated. Please use the `auth` object constructor instead. For more details, see https://cloud.google.com/docs/authentication/external/externally-sourced-credentials.");if(this.scopes=h.scopes,this.clientOptions=h.clientOptions||{},this.jsonContent=h.credentials||null,this.jsonContent)console.warn("The `credentials` option is deprecated. Please use the `auth` object constructor instead. For more details, see https://cloud.google.com/docs/authentication/external/externally-sourced-credentials.");if(this.apiKey=h.apiKey||this.clientOptions.apiKey||null,this.apiKey&&(this.jsonContent||this.clientOptions.credentials))throw RangeError(Dc.GoogleAuthExceptionMessages.API_KEY_WITH_CREDENTIALS);if(h.universeDomain)this.clientOptions.universeDomain=h.universeDomain}setGapicJWTValues(h){h.defaultServicePath??=this.defaultServicePath,h.useJWTAccessWithScope??=this.useJWTAccessWithScope,h.defaultScopes??=this.defaultScopes}getProjectId(h){if(h)this.getProjectIdAsync().then((f)=>h(null,f),h);else return this.getProjectIdAsync()}async getProjectIdOptional(){try{return await this.getProjectId()}catch(h){if(h instanceof Error&&h.message===Dc.GoogleAuthExceptionMessages.NO_PROJECT_ID_FOUND)return null;else throw h}}async findAndCacheProjectId(){let h=null;if(h||=await this.getProductionProjectId(),h||=await this.getFileProjectId(),h||=await this.getDefaultServiceProjectId(),h||=await this.getGCEProjectId(),h||=await this.getExternalAccountClientProjectId(),h)return this._cachedProjectId=h,h;else throw Error(Dc.GoogleAuthExceptionMessages.NO_PROJECT_ID_FOUND)}async getProjectIdAsync(){if(this._cachedProjectId)return this._cachedProjectId;if(!this._findProjectIdPromise)this._findProjectIdPromise=this.findAndCacheProjectId();return this._findProjectIdPromise}async getUniverseDomainFromMetadataServer(){let h;try{h=await An.universe("universe-domain"),h||=Es.DEFAULT_UNIVERSE}catch(f){if(f&&f?.response?.status===404)h=Es.DEFAULT_UNIVERSE;else throw f}return h}async getUniverseDomain(){let h=Yt.originalOrCamelOptions(this.clientOptions).get("universe_domain");try{h??=(await this.getClient()).universeDomain}catch{h??=Es.DEFAULT_UNIVERSE}return h}getAnyScopes(){return this.scopes||this.defaultScopes}getApplicationDefault(h={},f){let g;if(typeof h==="function")f=h;else g=h;if(f)this.getApplicationDefaultAsync(g).then((y)=>f(null,y.credential,y.projectId),f);else return this.getApplicationDefaultAsync(g)}async getApplicationDefaultAsync(h={}){if(this.cachedCredential)return await this.#t(this.cachedCredential,null);let f;if(f=await this._tryGetApplicationCredentialsFromEnvironmentVariable(h),f){if(f instanceof Jt.JWT)f.scopes=this.scopes;else if(f instanceof Cn.BaseExternalAccountClient)f.scopes=this.getAnyScopes();return await this.#t(f)}if(f=await this._tryGetApplicationCredentialsFromWellKnownFile(h),f){if(f instanceof Jt.JWT)f.scopes=this.scopes;else if(f instanceof Cn.BaseExternalAccountClient)f.scopes=this.getAnyScopes();return await this.#t(f)}if(await this._checkIsGCE())return h.scopes=this.getAnyScopes(),await this.#t(new _f.Compute(h));throw Error(Dc.GoogleAuthExceptionMessages.NO_ADC_FOUND)}async#t(h,f=process.env.GOOGLE_CLOUD_QUOTA_PROJECT||null){let g=await this.getProjectIdOptional();if(f)h.quotaProjectId=f;return this.cachedCredential=h,{credential:h,projectId:g}}async _checkIsGCE(){if(this.checkIsGCE===void 0)this.checkIsGCE=An.getGCPResidency()||await An.isAvailable();return this.checkIsGCE}async _tryGetApplicationCredentialsFromEnvironmentVariable(h){let f=process.env.GOOGLE_APPLICATION_CREDENTIALS||process.env.google_application_credentials;if(!f||f.length===0)return null;try{return await this._getApplicationCredentialsFromFilePath(f,h)}catch(g){if(g instanceof Error)g.message=`Unable to read the credential file specified by the GOOGLE_APPLICATION_CREDENTIALS environment variable: ${g.message}`;throw g}}async _tryGetApplicationCredentialsFromWellKnownFile(h){let f=process.env.CLOUDSDK_CONFIG;if(!f)if(this._isWindows()){if(process.env.APPDATA)f=zn.join(process.env.APPDATA,"gcloud")}else{let _=process.env.HOME;if(_)f=zn.join(_,".config","gcloud")}if(!f)return null;let g=zn.join(f,"application_default_credentials.json");if(!bn.existsSync(g))return null;return await this._getApplicationCredentialsFromFilePath(g,h)}async _getApplicationCredentialsFromFilePath(h,f={}){if(!h||h.length===0)throw Error("The file path is invalid.");try{if(h=bn.realpathSync(h),!bn.lstatSync(h).isFile())throw Error()}catch(y){if(y instanceof Error)y.message=`The file at ${h} does not exist, or it is not a file. ${y.message}`;throw y}let g=bn.createReadStream(h);return Yt.suppressAdcWarning(()=>this.fromStream(g,f))}fromImpersonatedJSON(h){if(!h)throw Error("Must pass in a JSON object containing an impersonated refresh token");if(h.type!==ln.IMPERSONATED_ACCOUNT_TYPE)throw Error(`The incoming JSON object does not have the "${ln.IMPERSONATED_ACCOUNT_TYPE}" type`);if(!h.source_credentials)throw Error("The incoming JSON object does not contain a source_credentials field");if(!h.service_account_impersonation_url)throw Error("The incoming JSON object does not contain a service_account_impersonation_url field");let f=Yt.suppressFromJsonWarning(()=>this.fromJSON(h.source_credentials));if(h.service_account_impersonation_url?.length>256)throw RangeError(`Target principal is too long: ${h.service_account_impersonation_url}`);let g=/(?<target>[^/]+):(generateAccessToken|generateIdToken)$/.exec(h.service_account_impersonation_url)?.groups?.target;if(!g)throw RangeError(`Cannot extract target principal from ${h.service_account_impersonation_url}`);let y=(this.scopes||h.scopes||this.defaultScopes)??[];return new ln.Impersonated({...h,sourceClient:f,targetPrincipal:g,targetScopes:Array.isArray(y)?y:[y]})}fromJSON(h,f={}){let g;if(!Yt.isFromJsonWarningSuppressed())console.warn("The `fromJSON` method is deprecated. Please use the `JWT` constructor instead. For more details, see https://cloud.google.com/docs/authentication/external/externally-sourced-credentials.");let y=Yt.originalOrCamelOptions(f).get("universe_domain");if(h.type===jc.USER_REFRESH_ACCOUNT_TYPE)g=new jc.UserRefreshClient(f),g.fromJSON(h);else if(h.type===ln.IMPERSONATED_ACCOUNT_TYPE)g=this.fromImpersonatedJSON(h);else if(h.type===Cn.EXTERNAL_ACCOUNT_TYPE)g=vf.ExternalAccountClient.fromJSON({...h,...f}),g.scopes=this.getAnyScopes();else if(h.type===Uc.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE)g=new Uc.ExternalAccountAuthorizedUserClient({...h,...f});else if(h.type===Cs.GDCH_SERVICE_ACCOUNT_TYPE)g=new Cs.GdchClient(f),g.fromJSON(h);else f.scopes=this.scopes,g=new Jt.JWT(f),this.setGapicJWTValues(g),g.fromJSON(h);if(y)g.universeDomain=y;return g}_cacheClientFromJSON(h,f){let g=Yt.suppressFromJsonWarning(()=>this.fromJSON(h,f));return this.jsonContent=h,this.cachedCredential=g,g}fromStream(h,f={},g){let y=Yt.isAdcWarningSuppressed();if(!y)console.warn("The `fromStream` method is deprecated. Please use the `JWT` constructor with a parsed stream instead. For more details, see https://cloud.google.com/docs/authentication/external/externally-sourced-credentials.");let _={};if(typeof f==="function")g=f;else _=f;if(g)this.fromStreamAsync(h,_,y).then((w)=>g(null,w),g);else return this.fromStreamAsync(h,_,y)}fromStreamAsync(h,f,g=!1){return new Promise((y,_)=>{if(!h)throw Error("Must pass in a stream containing the Google auth settings.");let w=[];h.setEncoding("utf8").on("error",_).on("data",(A)=>w.push(A)).on("end",()=>{try{try{let A=JSON.parse(w.join("")),S=g?Yt.suppressAdcWarning(()=>this._cacheClientFromJSON(A,f)):this._cacheClientFromJSON(A,f);return y(S)}catch(A){if(!this.keyFilename)throw A;let S=new Jt.JWT({...this.clientOptions,keyFile:this.keyFilename});return this.cachedCredential=S,this.setGapicJWTValues(S),y(S)}}catch(A){return _(A)}})})}fromAPIKey(h,f={}){return new Jt.JWT({...f,apiKey:h})}_isWindows(){let h=mf.platform();if(h&&h.length>=3){if(h.substring(0,3).toLowerCase()==="win")return!0}return!1}async getDefaultServiceProjectId(){return new Promise((h)=>{ff.exec("gcloud config config-helper --format json",(f,g)=>{if(!f&&g)try{let y=JSON.parse(g).configuration.properties.core.project;h(y);return}catch(y){}h(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 f=await this.getClient();if(f&&f.projectId)return f.projectId}let h=await this._tryGetApplicationCredentialsFromEnvironmentVariable();if(h)return h.projectId;else return null}async getExternalAccountClientProjectId(){if(!this.jsonContent||this.jsonContent.type!==Cn.EXTERNAL_ACCOUNT_TYPE)return null;return await(await this.getClient()).getProjectId()}async getGCEProjectId(){try{return await An.project("project-id")}catch(h){return null}}getCredentials(h){if(h)this.getCredentialsAsync().then((f)=>h(null,f),h);else return this.getCredentialsAsync()}async getCredentialsAsync(){let h=await this.getClient();if(h instanceof ln.Impersonated)return{client_email:h.getTargetPrincipal()};if(h instanceof Cn.BaseExternalAccountClient){let f=h.getServiceAccountEmail();if(f)return{client_email:f,universe_domain:h.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[f,g]=await Promise.all([An.instance("service-accounts/default/email"),this.getUniverseDomain()]);return{client_email:f,universe_domain:g}}throw Error(Dc.GoogleAuthExceptionMessages.NO_CREDENTIALS_FOUND)}async getClient(){if(this.cachedCredential){if(this.cachedCredential instanceof Jt.JWT)this.setGapicJWTValues(this.cachedCredential);return this.cachedCredential}this.#e=this.#e||this.#n();try{let h=await this.#e;if(h instanceof Jt.JWT)this.setGapicJWTValues(h);if(h instanceof Cs.GdchClient&&!h.apiAudience){let f=this.clientOptions,g=f.apiEndpoint||f.servicePath;if(g){let _=`${g.startsWith("http")?"":"https://"}${g}`.replace(/\/+$/,""),w=h.createWithGdchAudience(_);return this.cachedCredential=w,w}}return h}finally{this.#e=null}}async#n(){if(this.jsonContent)return this._cacheClientFromJSON(this.jsonContent,this.clientOptions);else if(this.keyFilename){let h=zn.resolve(this.keyFilename),f=bn.createReadStream(h);return await this.fromStreamAsync(f,this.clientOptions)}else if(this.apiKey){let h=await this.fromAPIKey(this.apiKey,this.clientOptions);h.scopes=this.scopes;let{credential:f}=await this.#t(h);return f}else{let{credential:h}=await this.getApplicationDefaultAsync(this.clientOptions);return h}}async getIdTokenClient(h){let f=await this.getClient();if(!("fetchIdToken"in f))throw 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 Tf.IdTokenClient({targetAudience:h,idTokenProvider:f})}async getAccessToken(){return(await(await this.getClient()).getAccessToken()).token}async getRequestHeaders(h){return(await this.getClient()).getRequestHeaders(h)}async authorizeRequest(h={}){let f=h.url,y=await(await this.getClient()).getRequestHeaders(f);return h.headers=gf.Gaxios.mergeHeaders(h.headers,y),h}async fetch(...h){return(await this.getClient()).fetch(...h)}async request(h){return(await this.getClient()).request(h)}getEnv(){return wf.getEnv()}async sign(h,f){let g=await this.getClient(),y=await this.getUniverseDomain();if(f=f||`https://iamcredentials.${y}/v1/projects/-/serviceAccounts/`,g instanceof ln.Impersonated)return(await g.sign(h)).signedBlob;let _=yf.createCrypto();if(g instanceof Jt.JWT&&g.key)return await _.sign(g.key,h);let w=await this.getCredentials();if(!w.client_email)throw Error("Cannot sign data without `client_email`.");return this.signBlob(_,w.client_email,h,f)}async signBlob(h,f,g,y){let _=new URL(y+`${f}:signBlob`);return(await this.request({method:"POST",url:_.href,data:{payload:h.encodeBase64StringUtf8(g)},retry:!0,retryConfig:{httpMethodsToRetry:["POST"]}})).data.signedBlob}}Dc.GoogleAuth=Mc});var Hc=i(function(Gc){Object.defineProperty(Gc,"__esModule",{value:!0});Gc.IAMAuth=void 0;class Fc{selector;token;constructor(h,f){this.selector=h,this.token=f,this.selector=h,this.token=f}getRequestHeaders(){return{"x-goog-iam-authority-selector":this.selector,"x-goog-iam-authorization-token":this.token}}}Gc.IAMAuth=Fc});var Jc=i(function(Vc){Object.defineProperty(Vc,"__esModule",{value:!0});Vc.DownscopedClient=Vc.EXPIRATION_TIME_OFFSET=Vc.MAX_ACCESS_BOUNDARY_RULES_COUNT=void 0;var Ef=ct(),Cf=c("stream"),bs=wt(),bf=qn(),Af="urn:ietf:params:oauth:grant-type:token-exchange",Sf="urn:ietf:params:oauth:token-type:access_token",kf="urn:ietf:params:oauth:token-type:access_token";Vc.MAX_ACCESS_BOUNDARY_RULES_COUNT=10;Vc.EXPIRATION_TIME_OFFSET=300000;class Bc extends bs.AuthClient{authClient;credentialAccessBoundary;cachedDownscopedAccessToken;stsCredential;constructor(h,f={accessBoundary:{accessBoundaryRules:[]}}){super(h instanceof bs.AuthClient?{}:h);if(h instanceof bs.AuthClient)this.authClient=h,this.credentialAccessBoundary=f;else this.authClient=h.authClient,this.credentialAccessBoundary=h.credentialAccessBoundary;if(this.credentialAccessBoundary.accessBoundary.accessBoundaryRules.length===0)throw Error("At least one access boundary rule needs to be defined.");else if(this.credentialAccessBoundary.accessBoundary.accessBoundaryRules.length>Vc.MAX_ACCESS_BOUNDARY_RULES_COUNT)throw Error(`The provided access boundary has more than ${Vc.MAX_ACCESS_BOUNDARY_RULES_COUNT} access boundary rules.`);for(let g of this.credentialAccessBoundary.accessBoundary.accessBoundaryRules)if(g.availablePermissions.length===0)throw Error("At least one permission should be defined in access boundary rules.");this.stsCredential=new bf.StsCredentials({tokenExchangeEndpoint:`https://sts.${this.universeDomain}/v1/token`}),this.cachedDownscopedAccessToken=null}setCredentials(h){if(!h.expiry_date)throw Error("The access token expiry_date field is missing in the provided credentials.");super.setCredentials(h),this.cachedDownscopedAccessToken=h}async getAccessToken(){if(!this.cachedDownscopedAccessToken||this.isExpired(this.cachedDownscopedAccessToken))await this.refreshAccessTokenAsync();return{token:this.cachedDownscopedAccessToken.access_token,expirationTime:this.cachedDownscopedAccessToken.expiry_date,res:this.cachedDownscopedAccessToken.res}}async getRequestHeaders(){let h=await this.getAccessToken(),f=new Headers({authorization:`Bearer ${h.token}`});return this.addSharedMetadataHeaders(f)}request(h,f){if(f)this.requestAsync(h).then((g)=>f(null,g),(g)=>f(g,g.response));else return this.requestAsync(h)}async requestAsync(h,f=!1){let g;try{let y=await this.getRequestHeaders();h.headers=Ef.Gaxios.mergeHeaders(h.headers),this.addUserProjectAndAuthHeaders(h.headers,y),g=await this.transporter.request(h)}catch(y){let _=y.response;if(_){let w=_.status,A=_.config.data instanceof Cf.Readable;if(!f&&(w===401||w===403)&&!A&&this.forceRefreshOnFailure)return await this.refreshAccessTokenAsync(),await this.requestAsync(h,!0)}throw y}return g}async refreshAccessTokenAsync(){let h=(await this.authClient.getAccessToken()).token,f={grantType:Af,requestedTokenType:Sf,subjectToken:h,subjectTokenType:kf},g=await this.stsCredential.exchangeToken(f,void 0,this.credentialAccessBoundary),y=this.authClient.credentials?.expiry_date||null,_=g.expires_in?new Date().getTime()+g.expires_in*1000:y;return this.cachedDownscopedAccessToken={access_token:g.access_token,expiry_date:_,res:g.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(h){let f=new Date().getTime();return h.expiry_date?f>=h.expiry_date-this.eagerRefreshThresholdMillis:!1}}Vc.DownscopedClient=Bc});var Xc=i(function(Yc){Object.defineProperty(Yc,"__esModule",{value:!0});Yc.PassThroughClient=void 0;var Of=wt();class Kc extends Of.AuthClient{async request(h){return this.transporter.request(h)}async getAccessToken(){return{}}async getRequestHeaders(){return new Headers}}Yc.PassThroughClient=Kc});var ks=i(function(Te){var Rf=Te&&Te.__createBinding||(Object.create?function(h,f,g,y){if(y===void 0)y=g;var _=Object.getOwnPropertyDescriptor(f,g);if(!_||("get"in _?!f.__esModule:_.writable||_.configurable))_={enumerable:!0,get:function(){return f[g]}};Object.defineProperty(h,y,_)}:function(h,f,g,y){if(y===void 0)y=g;h[y]=f[g]}),If=Te&&Te.__exportStar||function(h,f){for(var g in h)if(g!=="default"&&!Object.prototype.hasOwnProperty.call(f,g))Rf(f,h,g)};Object.defineProperty(Te,"__esModule",{value:!0});Te.GoogleAuth=Te.auth=Te.GDCH_SERVICE_ACCOUNT_TYPE=Te.GdchClient=Te.PassThroughClient=Te.ExternalAccountAuthorizedUserClient=Te.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE=Te.ExecutableError=Te.PluggableAuthClient=Te.DownscopedClient=Te.BaseExternalAccountClient=Te.ExternalAccountClient=Te.IdentityPoolClient=Te.AwsRequestSigner=Te.AwsClient=Te.UserRefreshClient=Te.LoginTicket=Te.ClientAuthentication=Te.OAuth2Client=Te.CodeChallengeMethod=Te.Impersonated=Te.JWT=Te.JWTAccess=Te.IdTokenClient=Te.IAMAuth=Te.GCPEnv=Te.Compute=Te.DEFAULT_UNIVERSE=Te.AuthClient=Te.gaxios=Te.gcpMetadata=void 0;var Qc=qc();Object.defineProperty(Te,"GoogleAuth",{enumerable:!0,get:function(){return Qc.GoogleAuth}});Te.gcpMetadata=mn();Te.gaxios=ct();var Zc=wt();Object.defineProperty(Te,"AuthClient",{enumerable:!0,get:function(){return Zc.AuthClient}});Object.defineProperty(Te,"DEFAULT_UNIVERSE",{enumerable:!0,get:function(){return Zc.DEFAULT_UNIVERSE}});var Nf=Pr();Object.defineProperty(Te,"Compute",{enumerable:!0,get:function(){return Nf.Compute}});var Pf=Ur();Object.defineProperty(Te,"GCPEnv",{enumerable:!0,get:function(){return Pf.GCPEnv}});var jf=Hc();Object.defineProperty(Te,"IAMAuth",{enumerable:!0,get:function(){return jf.IAMAuth}});var Uf=jr();Object.defineProperty(Te,"IdTokenClient",{enumerable:!0,get:function(){return Uf.IdTokenClient}});var Mf=qr();Object.defineProperty(Te,"JWTAccess",{enumerable:!0,get:function(){return Mf.JWTAccess}});var Df=Gr();Object.defineProperty(Te,"JWT",{enumerable:!0,get:function(){return Df.JWT}});var Lf=Hr();Object.defineProperty(Te,"Impersonated",{enumerable:!0,get:function(){return Lf.Impersonated}});var Ss=Ht();Object.defineProperty(Te,"CodeChallengeMethod",{enumerable:!0,get:function(){return Ss.CodeChallengeMethod}});Object.defineProperty(Te,"OAuth2Client",{enumerable:!0,get:function(){return Ss.OAuth2Client}});Object.defineProperty(Te,"ClientAuthentication",{enumerable:!0,get:function(){return Ss.ClientAuthentication}});var qf=Rr();Object.defineProperty(Te,"LoginTicket",{enumerable:!0,get:function(){return qf.LoginTicket}});var Ff=$r();Object.defineProperty(Te,"UserRefreshClient",{enumerable:!0,get:function(){return Ff.UserRefreshClient}});var Gf=ts();Object.defineProperty(Te,"AwsClient",{enumerable:!0,get:function(){return Gf.AwsClient}});var $f=es();Object.defineProperty(Te,"AwsRequestSigner",{enumerable:!0,get:function(){return $f.AwsRequestSigner}});var Hf=Zr();Object.defineProperty(Te,"IdentityPoolClient",{enumerable:!0,get:function(){return Hf.IdentityPoolClient}});var Bf=ms();Object.defineProperty(Te,"ExternalAccountClient",{enumerable:!0,get:function(){return Bf.ExternalAccountClient}});var Vf=Wt();Object.defineProperty(Te,"BaseExternalAccountClient",{enumerable:!0,get:function(){return Vf.BaseExternalAccountClient}});var Wf=Jc();Object.defineProperty(Te,"DownscopedClient",{enumerable:!0,get:function(){return Wf.DownscopedClient}});var el=gs();Object.defineProperty(Te,"PluggableAuthClient",{enumerable:!0,get:function(){return el.PluggableAuthClient}});Object.defineProperty(Te,"ExecutableError",{enumerable:!0,get:function(){return el.ExecutableError}});var tl=_s();Object.defineProperty(Te,"EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE",{enumerable:!0,get:function(){return tl.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE}});Object.defineProperty(Te,"ExternalAccountAuthorizedUserClient",{enumerable:!0,get:function(){return tl.ExternalAccountAuthorizedUserClient}});var Jf=Xc();Object.defineProperty(Te,"PassThroughClient",{enumerable:!0,get:function(){return Jf.PassThroughClient}});var nl=vs();Object.defineProperty(Te,"GdchClient",{enumerable:!0,get:function(){return nl.GdchClient}});Object.defineProperty(Te,"GDCH_SERVICE_ACCOUNT_TYPE",{enumerable:!0,get:function(){return nl.GDCH_SERVICE_ACCOUNT_TYPE}});If(Dr(),Te);var Kf=new Qc.GoogleAuth;Te.auth=Kf});var tu=v(ks(),1);function Yf({stream:h,getContinuationToken:f,continueStream:g}){let y=h.getReader(),_;return new ReadableStream({async pull(w){while(!0){let{done:A,value:S}=await y.read();if(!A){if(S.success){let V=f(S.value);if(V!=null)_=V}w.enqueue(S);return}if(_==null){w.close();return}let k=_;_=void 0;try{y=(await g(k)).getReader(),w.enqueue({type:"continuation-start"});return}catch(V){w.enqueue({success:!1,error:V,rawValue:void 0}),w.close();return}}},async cancel(w){await y.cancel(w)}})}function rl(h){if(h==null)return At();let f=h.promptTokenCount??0,g=h.candidatesTokenCount??0,y=h.toolUsePromptTokenCount??0,_=h.cachedContentTokenCount??0,w=h.thoughtsTokenCount??0,A=f+y;return{inputTokens:{total:A,noCache:A-_,cacheRead:_,cacheWrite:void 0},outputTokens:{total:g+w,text:g,reasoning:w},raw:h}}function xs(h,f){if(h==null||f==null)return f??h;return{...h,...f,promptTokenCount:un(h.promptTokenCount,f.promptTokenCount),candidatesTokenCount:un(h.candidatesTokenCount,f.candidatesTokenCount),toolUsePromptTokenCount:un(h.toolUsePromptTokenCount,f.toolUsePromptTokenCount),totalTokenCount:un(h.totalTokenCount,f.totalTokenCount),cachedContentTokenCount:un(h.cachedContentTokenCount,f.cachedContentTokenCount),thoughtsTokenCount:un(h.thoughtsTokenCount,f.thoughtsTokenCount),promptTokensDetails:Xn(h.promptTokensDetails,f.promptTokensDetails),cacheTokensDetails:Xn(h.cacheTokensDetails,f.cacheTokensDetails),candidatesTokensDetails:Xn(h.candidatesTokensDetails,f.candidatesTokensDetails),toolUsePromptTokensDetails:Xn(h.toolUsePromptTokensDetails,f.toolUsePromptTokensDetails)}}function un(h,f){return h==null&&f==null?f??h:(h??0)+(f??0)}function Xn(h,f){if(h==null||f==null)return f??h;let g=new Map;for(let{modality:y,tokenCount:_}of[...h,...f])g.set(y,(g.get(y)??0)+_);return Array.from(g,([y,_])=>({modality:y,tokenCount:_}))}var zf=t({startOffset:e().optional(),endOffset:e().optional(),fps:n().gt(0).max(24).optional()}),El=t({language:e().describe("The programming language of the code."),code:e().describe("The code to be executed.")}),Cl=t({outcome:e().describe('The outcome of the execution (e.g., "OUTCOME_OK").'),output:e().describe("The output from the code execution.")}),Xf=G({id:"google.code_execution",inputSchema:El,outputSchema:Cl}),Qf="skip_thought_signature_validator",Zf=/^data:([^;,]+);base64,(.+)$/s;function eg(h){let f=Zf.exec(h);if(f==null)return;return{mediaType:f[1],data:f[2]}}function tg(h){let f=eg(h);if(f==null)return;return{inlineData:{mimeType:f.mediaType,data:f.data}}}function Rs(h){if(Array.isArray(h))return h.some(Rs);if(typeof h!=="object"||h===null)return!1;return Object.entries(h).some(([f,g])=>f==="$ref"||Rs(g))}function sl(h){return Rs(h)?JSON.stringify(h):h}function ng(h,f,g,y,_=!0,w={}){let A=[],S=[];for(let k of g)switch(k.type){case"text":S.push(k.text);break;case"file":if(k.data.type==="data")A.push({inlineData:{mimeType:ee({part:k}),data:j(k.data.data)}});else if(k.data.type==="url"){let V=k.data.url.toString(),P=tg(V),ne=k.data.url.protocol==="gs:"&&k.data.originalUrl!=null?k.data.originalUrl:V;if(P!=null)A.push(P);else if(Ae(k.mediaType)&&Nr({url:ne,mediaType:k.mediaType,supportedUrls:w}))A.push({fileData:{mimeType:k.mediaType,fileUri:ne}});else S.push(JSON.stringify(k))}else S.push(JSON.stringify(k));break;default:S.push(JSON.stringify(k))}h.push({functionResponse:{..._&&y!=null?{id:y}:{},name:f,response:{name:f,content:S.length>0?S.join(`
29
+ `):"Tool executed successfully."},...A.length>0?{parts:A}:{}}})}function rg(h,f,g,y,_=!0){for(let w of g)switch(w.type){case"text":h.push({functionResponse:{..._&&y!=null?{id:y}:{},name:f,response:{name:f,content:w.text}}});break;case"file":if(w.data.type==="data"){let A=fe(w.mediaType);h.push({inlineData:{mimeType:ee({part:w}),data:j(w.data.data)}},{text:`Tool executed successfully and returned this ${A==="image"?"image":"file"} as a response`})}else h.push({text:JSON.stringify(w)});break;default:h.push({text:JSON.stringify(w)})}}function sg(h,f){let g=[],y=[],_=!0,w=f?.isGemmaModel??!1,A=f?.isGemini3Model??!1,S=f?.onWarning,k=f?.providerOptionsNames??["google"],V=!k.includes("google"),P=f?.supportsFunctionResponseParts??!0,ne=f?.includeFunctionCallIds??!0,Z=f?.supportedFunctionResponseUrls??{},K=!1,X=[],re=(L)=>(X.push(L),K=!0,Qf),de=(L)=>{for(let B of k){let he=L.providerOptions?.[B];if(he!=null)return he}if(V)return L.providerOptions?.google;return L.providerOptions?.googleVertex??L.providerOptions?.vertex};for(let{role:L,content:B}of h)switch(L){case"system":if(!_)throw new b({functionality:"system messages are only supported at the beginning of the conversation"});g.push({text:B});break;case"user":{_=!1;let he=[];for(let q of B)switch(q.type){case"text":he.push({text:q.text});break;case"file":{let U=de(q)?.videoMetadata,ue=U==null?void 0:zf.parse(U);switch(q.data.type){case"url":he.push({fileData:{mimeType:ee({part:q}),fileUri:q.data.url.protocol==="gs:"&&q.data.originalUrl!=null?q.data.originalUrl:q.data.url.toString()},...ue!=null?{videoMetadata:ue}:{}});break;case"reference":if(V)throw new b({functionality:"file parts with provider references"});he.push({fileData:{mimeType:ee({part:q}),fileUri:qe({reference:q.data.reference,provider:"google"})},...ue!=null?{videoMetadata:ue}:{}});break;case"text":he.push({inlineData:{mimeType:Ae(q.mediaType)?q.mediaType:"text/plain",data:j(new TextEncoder().encode(q.data.text))},...ue!=null?{videoMetadata:ue}:{}});break;case"data":he.push({inlineData:{mimeType:ee({part:q}),data:j(q.data.data)},...ue!=null?{videoMetadata:ue}:{}})}break}}y.push({role:"user",parts:he});break}case"assistant":{_=!1;let he=!1;y.push({role:"model",parts:B.map((q)=>{let U=de(q),ue=U?.thoughtSignature!=null?String(U.thoughtSignature):void 0;switch(q.type){case"text":return q.text.length===0?void 0:{text:q.text,thoughtSignature:ue};case"reasoning":return q.text.length===0?void 0:{text:q.text,thought:!0,thoughtSignature:ue};case"reasoning-file":switch(q.data.type){case"url":throw new b({functionality:"File data URLs in assistant messages are not supported"});case"data":return{inlineData:{mimeType:q.mediaType,data:j(q.data.data)},thought:!0,thoughtSignature:ue}}break;case"file":switch(q.data.type){case"url":throw new b({functionality:"File data URLs in assistant messages are not supported"});case"reference":if(V)throw new b({functionality:"file parts with provider references"});return{fileData:{mimeType:q.mediaType,fileUri:qe({reference:q.data.reference,provider:"google"})},...U?.thought===!0?{thought:!0}:{},thoughtSignature:ue};case"text":return{inlineData:{mimeType:Ae(q.mediaType)?q.mediaType:"text/plain",data:j(new TextEncoder().encode(q.data.text))},...U?.thought===!0?{thought:!0}:{},thoughtSignature:ue};case"data":return{inlineData:{mimeType:q.mediaType,data:j(q.data.data)},...U?.thought===!0?{thought:!0}:{},thoughtSignature:ue}}break;case"tool-call":{if(q.providerExecuted===!0&&q.toolName==="code_execution")return{executableCode:El.parse(typeof q.input==="string"?Qe(q.input):q.input)};let ye=U?.serverToolCallId!=null?String(U.serverToolCallId):void 0,ve=U?.serverToolType!=null?String(U.serverToolType):void 0,_e=ye!=null&&ve!=null,Ne=ue??(A&&!(!_e&&ue==null&&he)?re(q.toolName):void 0);if(!_e&&ue!=null)he=!0;if(_e)return{toolCall:{toolType:ve,args:typeof q.input==="string"?Qe(q.input):q.input,id:ye},thoughtSignature:Ne};return{functionCall:{...ne&&q.toolCallId!=null?{id:q.toolCallId}:{},name:q.toolName,args:q.input},thoughtSignature:Ne}}case"tool-result":{if(q.toolName==="code_execution"&&q.output.type==="json")return{codeExecutionResult:Cl.parse(q.output.value)};let ye=U?.serverToolCallId!=null?String(U.serverToolCallId):void 0,ve=U?.serverToolType!=null?String(U.serverToolType):void 0;if(ye&&ve)return{toolResponse:{toolType:ve,response:q.output.type==="json"?q.output.value:{},id:ye},thoughtSignature:ue};return}}}).filter((q)=>q!==void 0)});break}case"tool":{_=!1;let he=[];for(let q of B){if(q.type==="tool-approval-response")continue;let U=de(q),ue=U?.serverToolCallId!=null?String(U.serverToolCallId):void 0,ye=U?.serverToolType!=null?String(U.serverToolType):void 0;if(ue&&ye){let _e=U?.thoughtSignature!=null?String(U.thoughtSignature):void 0;if(y.length>0){let Ne=y[y.length-1];if(Ne.role==="model"){Ne.parts.push({toolResponse:{toolType:ye,response:q.output.type==="json"?q.output.value:{},id:ue},thoughtSignature:_e});continue}}}let ve=q.output;if(ve.type==="content")if(P)ng(he,q.toolName,ve.value,q.toolCallId,ne,Z);else rg(he,q.toolName,ve.value,q.toolCallId,ne);else{let _e=ve.type==="error-text"||ve.type==="error-json"||ve.type==="execution-denied";he.push({functionResponse:{...ne&&q.toolCallId!=null?{id:q.toolCallId}:{},name:q.toolName,response:{name:q.toolName,..._e?{error:ve.type==="execution-denied"?ve.reason??"Tool call execution denied.":sl(ve.value)}:{content:sl(ve.value)}}}})}}y.push({role:"user",parts:he});break}}if(w&&g.length>0&&y.length>0&&y[0].role==="user"){let L=g.map((B)=>B.text).join(`
30
+
31
+ `);y[0].parts.unshift({text:L+`
32
+
33
+ `})}if(K&&S!=null){let L=Array.from(new Set(X));S({type:"other",message:`Replayed ${X.length} \`functionCall\` part(s) for a Gemini 3 model without a \`thoughtSignature\` (tools: ${L.map((B)=>`\`${B}\``).join(", ")}). Injected the documented \`skip_thought_signature_validator\` sentinel to keep the request from failing with HTTP 400. The likely cause is application code that drops \`providerOptions.google.thoughtSignature\` when persisting or serializing assistant tool-call messages. See https://ai.google.dev/gemini-api/docs/thought-signatures.`})}return{systemInstruction:g.length>0&&!w?{parts:g}:void 0,contents:y}}async function ig(h,{abortSignal:f,maxBytes:g,supportedUrls:y={}}){let _=[];for(let w of h){if(w.role==="assistant"){let A=[];for(let S of w.content)A.push(S.type==="tool-result"?{...S,output:await il(S.output,{abortSignal:f,maxBytes:g,supportedUrls:y})}:S);_.push({...w,content:A});continue}if(w.role==="tool"){let A=[];for(let S of w.content){if(S.type!=="tool-result"){A.push(S);continue}A.push({...S,output:await il(S.output,{abortSignal:f,maxBytes:g,supportedUrls:y})})}_.push({...w,content:A});continue}_.push(w)}return _}async function il(h,{abortSignal:f,maxBytes:g,supportedUrls:y}){if(h.type!=="content")return h;let _=[];for(let w of h.value){if(w.type!=="file"||w.data.type!=="url"){_.push(w);continue}if(Nr({url:w.data.url.toString(),mediaType:w.mediaType,supportedUrls:y})){_.push(w);continue}let A=await Do(w.data.url.toString(),{abortSignal:f,maxBytes:g}),S=new Uint8Array(await A.arrayBuffer()),k=nt({data:S,topLevelType:"image"});_.push({...w,data:{type:"data",data:S},mediaType:k??(A.type&&!Ae(w.mediaType)?A.type:w.mediaType)})}return{...h,value:_}}function ol(h){return h.includes("/")?h:`models/${h}`}var bl=()=>t({code:n().nullable(),message:e(),status:e(),details:o(m()).nullish()}),og=u(()=>l(t({error:bl()}))),zt=oe({errorSchema:og,errorToMessage:(h)=>h.error.message});function Al(h){let{const:f,properties:g,items:y,additionalProperties:_,anyOf:w,oneOf:A,...S}=h;return{...S,...f!==void 0?{enum:[f]}:{},...g!=null?{properties:al(g)}:{},...y!=null?{items:Array.isArray(y)?y.map(dn):dn(y)}:{},..._!=null?{additionalProperties:typeof _==="boolean"?_:dn(_)}:{},...w!=null?{anyOf:w.map(dn)}:{},...A!=null?{oneOf:A.map(dn)}:{},...S.$defs!=null?{$defs:al(S.$defs)}:{}}}function al(h){return Object.fromEntries(Object.entries(h).map(([f,g])=>[f,dn(g)]))}function dn(h){return typeof h==="boolean"?h:Al(h)}var cl=u(()=>l(t({responseModalities:o(s(["TEXT","IMAGE","AUDIO"])).optional(),thinkingConfig:t({thinkingBudget:n().optional(),includeThoughts:r().optional(),thinkingLevel:s(["minimal","low","medium","high"]).optional()}).optional(),cachedContent:e().optional(),structuredOutputs:r().optional(),safetySettings:o(t({category:s(["HARM_CATEGORY_UNSPECIFIED","HARM_CATEGORY_HATE_SPEECH","HARM_CATEGORY_DANGEROUS_CONTENT","HARM_CATEGORY_HARASSMENT","HARM_CATEGORY_SEXUALLY_EXPLICIT","HARM_CATEGORY_CIVIC_INTEGRITY"]),threshold:s(["HARM_BLOCK_THRESHOLD_UNSPECIFIED","BLOCK_LOW_AND_ABOVE","BLOCK_MEDIUM_AND_ABOVE","BLOCK_ONLY_HIGH","BLOCK_NONE","OFF"])})).optional(),threshold:s(["HARM_BLOCK_THRESHOLD_UNSPECIFIED","BLOCK_LOW_AND_ABOVE","BLOCK_MEDIUM_AND_ABOVE","BLOCK_ONLY_HIGH","BLOCK_NONE","OFF"]).optional(),audioTimestamp:r().optional(),labels:d(e(),e()).optional(),mediaResolution:s(["MEDIA_RESOLUTION_UNSPECIFIED","MEDIA_RESOLUTION_LOW","MEDIA_RESOLUTION_MEDIUM","MEDIA_RESOLUTION_HIGH"]).optional(),imageConfig:t({aspectRatio:s(["1:1","2:3","3:2","3:4","4:3","4:5","5:4","9:16","16:9","21:9","1:8","8:1","1:4","4:1"]).optional(),imageSize:s(["1K","2K","4K","512"]).optional(),personGeneration:s(["PERSON_GENERATION_UNSPECIFIED","ALLOW_ALL","ALLOW_ADULT","ALLOW_NONE"]).optional(),prominentPeople:s(["PROMINENT_PEOPLE_UNSPECIFIED","ALLOW_PROMINENT_PEOPLE","BLOCK_PROMINENT_PEOPLE"]).optional(),imageOutputOptions:t({mimeType:s(["image/jpeg","image/png"]).optional(),compressionQuality:n().optional()}).optional()}).optional(),retrievalConfig:t({latLng:t({latitude:n(),longitude:n()}).optional()}).optional(),streamFunctionCallArguments:r().optional(),serviceTier:s(["standard","flex","priority"]).optional(),continuationToken:e().optional(),sharedRequestType:s(["priority","flex","standard"]).optional(),requestType:s(["shared"]).optional()}))),ag=/(^|[/.])gemini-1(?:[.-]|$)/i,cg=/(^|[/.])gemini-2(?:[.-]|$)/i,lg=/(^|[/.])gemini-2\.5(?:[.-]|$)/i,ug=/(^|[/.])gemini-/i;function dg(h){return ag.test(h)||/(^|[/.])gemini-pro(?:-vision)?$/i.test(h)||/(^|[/.])gemini-robotics-er-1\.5(?:[.-]|$)/i.test(h)}function tr(h){let f=ug.test(h),g=cg.test(h),y=dg(h),_=f&&!(y||g);return{supportsGemini2Tools:f&&!y||h.toLowerCase().includes("nano-banana"),supportsFileSearch:lg.test(h)||_,usesGemini3Features:_}}function hg({tools:h,toolChoice:f,modelId:g,isVertexProvider:y=!1}){h=h?.length?h:void 0;let _=[],{supportsGemini2Tools:w,supportsFileSearch:A,usesGemini3Features:S}=tr(g);if(h==null)return{tools:void 0,toolConfig:void 0,toolWarnings:_};let k=h.some((K)=>K.type==="function"),V=h.some((K)=>K.type==="provider");if(k&&V&&!S)_.push({type:"unsupported",feature:"combination of function and provider-defined tools"});if(V){let K=[];if(h.filter((X)=>X.type==="provider").forEach((X)=>{switch(X.id){case"google.google_search":if(w)K.push({googleSearch:{...X.args}});else _.push({type:"unsupported",feature:`provider-defined tool ${X.id}`,details:"Google Search requires Gemini 2.0 or newer."});break;case"google.enterprise_web_search":if(w)K.push({enterpriseWebSearch:{}});else _.push({type:"unsupported",feature:`provider-defined tool ${X.id}`,details:"Enterprise Web Search requires Gemini 2.0 or newer."});break;case"google.url_context":if(w)K.push({urlContext:{}});else _.push({type:"unsupported",feature:`provider-defined tool ${X.id}`,details:"The URL context tool is not supported with other Gemini models than Gemini 2."});break;case"google.code_execution":if(w)K.push({codeExecution:{}});else _.push({type:"unsupported",feature:`provider-defined tool ${X.id}`,details:"The code execution tool is not supported with other Gemini models than Gemini 2."});break;case"google.file_search":if(A)K.push({fileSearch:{...X.args}});else _.push({type:"unsupported",feature:`provider-defined tool ${X.id}`,details:"The file search tool is only supported with Gemini 2.5 models and Gemini 3 models."});break;case"google.vertex_rag_store":if(w)K.push({retrieval:{vertex_rag_store:{rag_resources:{rag_corpus:X.args.ragCorpus},similarity_top_k:X.args.topK}}});else _.push({type:"unsupported",feature:`provider-defined tool ${X.id}`,details:"The RAG store tool is not supported with other Gemini models than Gemini 2."});break;case"google.google_maps":if(w)K.push({googleMaps:{}});else _.push({type:"unsupported",feature:`provider-defined tool ${X.id}`,details:"The Google Maps grounding tool is not supported with Gemini models other than Gemini 2 or newer."});break;default:_.push({type:"unsupported",feature:`provider-defined tool ${X.id}`})}}),k&&S&&K.length>0){let X=[];for(let de of h)if(de.type==="function")X.push(ll(de));let re={functionCallingConfig:{mode:"VALIDATED"},...!y&&{includeServerSideToolInvocations:!0}};if(f!=null)switch(f.type){case"auto":break;case"none":re.functionCallingConfig={mode:"NONE"};break;case"required":re.functionCallingConfig={mode:"ANY"};break;case"tool":re.functionCallingConfig={mode:"ANY",allowedFunctionNames:[f.toolName]}}return{tools:[...K,{functionDeclarations:X}],toolConfig:re,toolWarnings:_}}return{tools:K.length>0?K:void 0,toolConfig:void 0,toolWarnings:_}}let P=[],ne=!1;for(let K of h)switch(K.type){case"function":if(P.push(ll(K)),K.strict===!0)ne=!0;break;default:_.push({type:"unsupported",feature:`function tool ${K.name}`})}if(f==null)return{tools:[{functionDeclarations:P}],toolConfig:ne?{functionCallingConfig:{mode:"VALIDATED"}}:void 0,toolWarnings:_};let Z=f.type;switch(Z){case"auto":return{tools:[{functionDeclarations:P}],toolConfig:{functionCallingConfig:{mode:ne?"VALIDATED":"AUTO"}},toolWarnings:_};case"none":return{tools:[{functionDeclarations:P}],toolConfig:{functionCallingConfig:{mode:"NONE"}},toolWarnings:_};case"required":return{tools:[{functionDeclarations:P}],toolConfig:{functionCallingConfig:{mode:"ANY"}},toolWarnings:_};case"tool":return{tools:[{functionDeclarations:P}],toolConfig:{functionCallingConfig:{mode:"ANY",allowedFunctionNames:[f.toolName]}},toolWarnings:_};default:throw new b({functionality:`tool choice type: ${Z}`})}}function ll(h){return{name:h.name,description:h.description??"",parametersJsonSchema:h.inputSchema}}var pg=class{constructor(){this.accumulatedArgs={},this.jsonText="",this.pathStack=[],this.stringOpen=!1}processPartialArgs(h){let f="";for(let g of h){let y=g.jsonPath.endsWith("[]"),_=(y?g.jsonPath.slice(0,-2):g.jsonPath).replace(/^\$\./,"");if(!_||_==="$")continue;let w=fg(_),A=mg(this.accumulatedArgs,w);if(g.stringValue!=null&&A!==void 0){let k=JSON.stringify(g.stringValue).slice(1,-1);if(Os(this.accumulatedArgs,w,A+g.stringValue),f+=k,g.willContinue!==!0)f+=this.closeOpenString();continue}let S=yg(g);if(S==null){if(A!==void 0){if(typeof A==="string"&&g.willContinue!==!0)f+=this.closeOpenString();continue}if(g.willContinue===!0)continue;Os(this.accumulatedArgs,w,y?[]:{}),f+=this.emitContainer(w,y);continue}Os(this.accumulatedArgs,w,S.value),f+=this.emitNavigationTo(w,g,S.json)}return this.jsonText+=f,{currentJSON:this.accumulatedArgs,textDelta:f}}finalize(){let h=JSON.stringify(this.accumulatedArgs);return{finalJSON:h,closingDelta:h.slice(this.jsonText.length)}}closeOpenString(){if(!this.stringOpen)return"";return this.stringOpen=!1,'"'}ensureRoot(){if(this.pathStack.length===0)return this.pathStack.push({segment:"",isArray:!1,childCount:0}),"{";return""}emitNavigationTo(h,f,g){let y=this.closeOpenString();y+=this.ensureRoot();let _=h.slice(0,-1),w=h[h.length-1],A=this.findCommonStackDepth(_);return y+=this.closeDownTo(A),y+=this.openDownTo(_,w),y+=this.emitLeaf(w,f,g),y}emitContainer(h,f){let g=this.closeOpenString();g+=this.ensureRoot();let y=this.findCommonStackDepth(h);return g+=this.closeDownTo(y),g+=this.openDownTo(h,f?0:""),g}findCommonStackDepth(h){let f=Math.min(this.pathStack.length-1,h.length),g=0;for(let y=0;y<f;y++)if(this.pathStack[y+1].segment===h[y])g++;else break;return g+1}closeDownTo(h){let f="";while(this.pathStack.length>h){let g=this.pathStack.pop();f+=g.isArray?"]":"}"}return f}openDownTo(h,f){let g="",y=this.pathStack.length-1;for(let _=y;_<h.length;_++){let w=h[_],A=this.pathStack[this.pathStack.length-1];if(A.childCount>0)g+=",";if(A.childCount++,typeof w==="string")g+=`${JSON.stringify(w)}:`;let S=typeof(_+1<h.length?h[_+1]:f)==="number";g+=S?"[":"{",this.pathStack.push({segment:w,isArray:S,childCount:0})}return g}emitLeaf(h,f,g){let y="",_=this.pathStack[this.pathStack.length-1];if(_.childCount>0)y+=",";if(_.childCount++,typeof h==="string")y+=`${JSON.stringify(h)}:`;if(f.stringValue!=null&&f.willContinue)y+=g.slice(0,-1),this.stringOpen=!0;else y+=g;return y}};function fg(h){let f=[];for(let g of h.split(".")){let y=g.indexOf("[");if(y===-1)f.push(g);else{if(y>0)f.push(g.slice(0,y));for(let _ of g.matchAll(/\[(\d+)\]/g))f.push(parseInt(_[1],10))}}return f}var gg=Object.prototype.hasOwnProperty;function Sl(h,f){return gg.call(h,f)}function ul(h,f,g){Object.defineProperty(h,f,{value:g,enumerable:!0,configurable:!0,writable:!0})}function mg(h,f){let g=h;for(let y of f){if(g==null||typeof g!=="object")return;let _=g;if(!Sl(_,y))return;g=_[y]}return g}function Os(h,f,g){let y=h;for(let _=0;_<f.length-1;_++){let w=f[_],A=f[_+1];if(!Sl(y,w)||y[w]==null)ul(y,w,typeof A==="number"?[]:{});y=y[w]}ul(y,f[f.length-1],g)}function yg(h){let f=h.stringValue??h.numberValue??h.boolValue;if(f!=null)return{value:f,json:JSON.stringify(f)};if("nullValue"in h)return{value:null,json:"null"}}function dl({finishReason:h,hasToolCalls:f}){switch(h){case"STOP":return f?"tool-calls":"stop";case"MAX_TOKENS":case"CONTINUATION":return"length";case"IMAGE_SAFETY":case"RECITATION":case"SAFETY":case"BLOCKLIST":case"PROHIBITED_CONTENT":case"SPII":return"content-filter";case"MALFORMED_FUNCTION_CALL":return"error";default:return"other"}}var _g=["HARM_CATEGORY_HATE_SPEECH","HARM_CATEGORY_DANGEROUS_CONTENT","HARM_CATEGORY_HARASSMENT","HARM_CATEGORY_SEXUALLY_EXPLICIT"],Tg=/(^|[/.])gemini-2\.5(?:[.-]|$)/i,wg={"image/png":[/^gs:\/\/.*$/],"image/jpeg":[/^gs:\/\/.*$/],"image/webp":[/^gs:\/\/.*$/],"application/pdf":[/^gs:\/\/.*$/],"text/plain":[/^gs:\/\/.*$/]},js=class h{static[H](f){return te({modelId:f.modelId,config:f.config})}static[Q](f){return new h(f.modelId,f.config)}constructor(f,g){this.specificationVersion="v4",this.modelId=f,this.config=g,this.generateId=g.generateId??C}get provider(){return this.config.provider}get supportedUrls(){return this.config.supportedUrls?.()??{}}static async prepareRequest({modelId:f,config:g,options:{prompt:y,maxOutputTokens:_,temperature:w,topP:A,topK:S,frequencyPenalty:k,presencePenalty:V,stopSequences:P,responseFormat:ne,seed:Z,tools:K,toolChoice:X,reasoning:re,providerOptions:de,abortSignal:L},isStreaming:B=!1}){let he=[],q=g.provider.includes("vertex")?["googleVertex","vertex"]:["google"],U;for(let rt of q)if(U=await T({provider:rt,providerOptions:de,schema:cl}),U!=null)break;if(U==null&&!q.includes("google"))U=await T({provider:"google",providerOptions:de,schema:cl});let ue=g.provider.startsWith("google.vertex.");if(K?.some((rt)=>rt.type==="provider"&&rt.id==="google.vertex_rag_store")&&!ue)he.push({type:"other",message:`The 'vertex_rag_store' tool is only supported with the Google Vertex provider and might not be supported or could behave unexpectedly with the current Google provider (${g.provider}).`});if(U?.streamFunctionCallArguments&&!ue)he.push({type:"other",message:`'streamFunctionCallArguments' is only supported on the Vertex AI API and will be ignored with the current Google provider (${g.provider}). See https://docs.cloud.google.com/vertex-ai/generative-ai/docs/multimodal/function-calling#streaming-fc`});if(U?.serviceTier&&ue)he.push({type:"other",message:"'serviceTier' is a Gemini API option and is not supported on Vertex AI. Use 'sharedRequestType' (and optionally 'requestType') instead. See https://docs.cloud.google.com/vertex-ai/generative-ai/docs/priority-paygo"});if((U?.sharedRequestType||U?.requestType)&&!ue)he.push({type:"other",message:`'sharedRequestType' and 'requestType' are Vertex AI options and are ignored with the current Google provider (${g.provider}).`});let ye=ue&&(U?.sharedRequestType||U?.requestType)?{...U.sharedRequestType&&{"X-Vertex-AI-LLM-Shared-Request-Type":U.sharedRequestType},...U.requestType&&{"X-Vertex-AI-LLM-Request-Type":U.requestType}}:void 0,ve=ue?void 0:U?.serviceTier,_e=U?.imageConfig;if(_e!=null&&!ue){let{personGeneration:rt,prominentPeople:Me,imageOutputOptions:_t,...x}=_e,N=Object.entries({personGeneration:rt,prominentPeople:Me,imageOutputOptions:_t}).filter(([,R])=>R!=null).map(([R])=>`'imageConfig.${R}'`);if(N.length>0)he.push({type:"other",message:`${N.join(", ")} ${N.length===1?"is a Vertex AI option and is":"are Vertex AI options and are"} ignored with the current Google provider (${g.provider}).`}),_e=x}let Ne=f.toLowerCase().startsWith("gemma-"),Re=!ue&&Tg.test(f);if(Re&&k!=null)he.push({type:"unsupported",feature:"frequencyPenalty"});if(Re&&V!=null)he.push({type:"unsupported",feature:"presencePenalty"});let{usesGemini3Features:Ie}=tr(f),Be=Ie&&g.downloadToolResultFiles?.supportsGoogleCloudStorageUrls?wg:void 0,{contents:je,systemInstruction:Ve}=sg(g.downloadToolResultFiles?await ig(y,{abortSignal:L,maxBytes:g.downloadToolResultFiles.maxBytes,supportedUrls:Be}):y,{isGemmaModel:Ne,isGemini3Model:Ie,onWarning:(rt)=>he.push(rt),providerOptionsNames:q,supportsFunctionResponseParts:Ie,includeFunctionCallIds:!ue,supportedFunctionResponseUrls:Be}),{tools:Ue,toolConfig:Je,toolWarnings:Ze}=hg({tools:K,toolChoice:X,modelId:f,isVertexProvider:ue}),tt=Vt({tools:K,providerToolNames:{"google.code_execution":"code_execution"}}),ot=U?.thinkingConfig?.thinkingBudget!=null||U?.thinkingConfig?.thinkingLevel!=null?void 0:bg({reasoning:re,modelId:f,warnings:he}),et=U?.thinkingConfig||ot?{...ot,...U?.thinkingConfig}:void 0,mt=B&&ue?U?.streamFunctionCallArguments??!1:void 0,ge=U?.threshold,be=U?.safetySettings??(ge!=null?_g.map((rt)=>({category:rt,threshold:ge})):void 0),at=Je||mt||U?.retrievalConfig?{...Je,...mt&&{functionCallingConfig:{...Je?.functionCallingConfig,streamFunctionCallArguments:!0}},...U?.retrievalConfig&&{retrievalConfig:U.retrievalConfig}}:void 0;return{args:{generationConfig:{maxOutputTokens:_,temperature:w,topK:S,topP:A,frequencyPenalty:Re?void 0:k,presencePenalty:Re?void 0:V,stopSequences:P,seed:Z,responseMimeType:ne?.type==="json"?"application/json":void 0,responseJsonSchema:ne?.type==="json"&&ne.schema!=null&&(U?.structuredOutputs??!0)?Al(ne.schema):void 0,...U?.audioTimestamp&&{audioTimestamp:U.audioTimestamp},responseModalities:U?.responseModalities,thinkingConfig:et,...U?.mediaResolution&&{mediaResolution:U.mediaResolution},..._e&&{imageConfig:_e}},contents:je,systemInstruction:Ne?void 0:Ve,safetySettings:be,tools:Ue,toolConfig:at,cachedContent:U?.cachedContent,labels:U?.labels,serviceTier:ve,...U?.continuationToken!=null&&{continuationToken:U.continuationToken}},warnings:[...he,...Ze],providerOptionsNames:q,extraHeaders:ye,toolNameMapping:tt}}async getArgs(f,{isStreaming:g=!1}={}){let{responseFormat:y,tools:_,toolChoice:w}=f,A;if(y?.type==="json"&&y.schema!=null&&_?.some((S)=>S.type==="function")&&/(^|\/)gemini-/i.test(this.modelId)&&(!tr(this.modelId).usesGemini3Features||w?.type==="required"||w?.type==="tool")){let S="json";for(let k=1;_.some((V)=>V.name===S);k++)S=`json_${k}`;A={type:"function",name:S,description:y.description??"Respond with a JSON object.",inputSchema:y.schema}}return{...await h.prepareRequest({modelId:this.modelId,config:this.config,options:A==null?f:{...f,responseFormat:void 0,tools:[..._??[],A],toolChoice:w?.type==="tool"?w:w?.type==="none"?{type:"tool",toolName:A.name}:{type:"required"}},isStreaming:g}),jsonResponseToolName:A?.name}}static convertGenerateContentResponse({config:f,response:g,warnings:y,providerOptionsNames:_,toolNameMapping:w,jsonResponseToolName:A,initialPromptTokenCount:S,groundingMetadataPerRequest:k}){let V=(U)=>Object.fromEntries(_.map((ue)=>[ue,U])),P=g.candidates?.[0],ne=g.promptFeedback?.blockReason,Z=pl(ne)?ne:void 0,K=P?.finishReason==null&&Z!=null,X=P?.finishReason??Z,re=[],de=P?.content?.parts??[],L=g.usageMetadata,B,he;for(let U of de)if("executableCode"in U&&U.executableCode?.code){let ue=f.generateId();B=ue,re.push({type:"tool-call",toolCallId:ue,toolName:w?.toCustomToolName("code_execution")??"code_execution",input:JSON.stringify(U.executableCode),providerExecuted:!0})}else if("codeExecutionResult"in U&&U.codeExecutionResult)re.push({type:"tool-result",toolCallId:B,toolName:w?.toCustomToolName("code_execution")??"code_execution",result:{outcome:U.codeExecutionResult.outcome,output:U.codeExecutionResult.output??""}});else if("text"in U&&U.text!=null){if(A!=null&&U.thought!==!0)continue;let ue=U.thoughtSignature?V({thoughtSignature:U.thoughtSignature}):void 0;if(U.text.length===0){if(ue!=null&&re.length>0){let ye=re[re.length-1];ye.providerMetadata=ue}}else re.push({type:U.thought===!0?"reasoning":"text",text:U.text,providerMetadata:ue})}else if("functionCall"in U&&U.functionCall.name!=null){if(U.functionCall.name===A){re.push({type:"text",text:typeof U.functionCall.args==="string"?U.functionCall.args:JSON.stringify(U.functionCall.args??{}),...U.thoughtSignature?{providerMetadata:V({thoughtSignature:U.thoughtSignature})}:{}});continue}re.push({type:"tool-call",toolCallId:U.functionCall.id||f.generateId(),toolName:U.functionCall.name,input:JSON.stringify(U.functionCall.args??{}),providerMetadata:U.thoughtSignature?V({thoughtSignature:U.thoughtSignature}):void 0})}else if("inlineData"in U){let ue=U.thought===!0,ye=!!U.thoughtSignature;re.push({type:ue?"reasoning-file":"file",data:{type:"data",data:U.inlineData.data},mediaType:U.inlineData.mimeType,providerMetadata:ye?V({thoughtSignature:U.thoughtSignature}):void 0})}else if("toolCall"in U&&U.toolCall){let ue=U.toolCall.id||f.generateId();he=ue,re.push({type:"tool-call",toolCallId:ue,toolName:`server:${U.toolCall.toolType}`,input:JSON.stringify(U.toolCall.args??{}),providerExecuted:!0,dynamic:!0,providerMetadata:U.thoughtSignature?V({thoughtSignature:U.thoughtSignature,serverToolCallId:ue,serverToolType:U.toolCall.toolType}):V({serverToolCallId:ue,serverToolType:U.toolCall.toolType})})}else if("toolResponse"in U&&U.toolResponse){let ue=he||U.toolResponse.id||f.generateId();re.push({type:"tool-result",toolCallId:ue,toolName:`server:${U.toolResponse.toolType}`,result:U.toolResponse.response??{},providerMetadata:U.thoughtSignature?V({thoughtSignature:U.thoughtSignature,serverToolCallId:ue,serverToolType:U.toolResponse.toolType}):V({serverToolCallId:ue,serverToolType:U.toolResponse.toolType})}),he=void 0}let q=hl({groundingMetadata:P?.groundingMetadata,generateId:f.generateId})??[];for(let U of q)re.push(U);return{content:re,finishReason:{unified:K?"content-filter":dl({finishReason:X,hasToolCalls:re.some((U)=>U.type==="tool-call"&&!U.providerExecuted)}),raw:X},usage:rl(L),warnings:y,providerMetadata:V({promptFeedback:g.promptFeedback??null,groundingMetadata:P?.groundingMetadata??null,...k!=null?{groundingMetadataPerRequest:k}:{},urlContextMetadata:P?.urlContextMetadata??null,safetyRatings:P?.safetyRatings??null,usageMetadata:L??null,finishMessage:P?.finishMessage??null,serviceTier:L?.serviceTier??null,...P?.continuationToken!=null?{continuationToken:P.continuationToken}:{},...S!=null?{initialPromptTokenCount:S}:{}}),response:{id:g.responseId??void 0}}}async doGenerate(f){let{args:g,warnings:y,providerOptionsNames:_,extraHeaders:w,toolNameMapping:A,jsonResponseToolName:S}=await this.getArgs(f),k=I(this.config.headers?await M(this.config.headers):void 0,f.headers,w),V=(q)=>O({url:`${this.config.baseURL}/${ol(this.modelId)}:generateContent`,headers:k,body:q,failedResponseHandler:zt,successfulResponseHandler:E(Og),abortSignal:f.abortSignal,fetch:this.config.fetch}),{responseHeaders:P,value:ne,rawValue:Z}=await V(g),K=[],X=[],re,de=ne.usageMetadata?.promptTokenCount,L=!1;while(!0){let q=ne.candidates?.[0];X.push(q?.groundingMetadata??null);let U=q?.finishReason==="CONTINUATION"?q.continuationToken:void 0;if(re=xs(re,ne.usageMetadata??void 0),U==null)break;K.push(...h.convertGenerateContentResponse({config:this.config,response:ne,warnings:y,providerOptionsNames:_,toolNameMapping:A,jsonResponseToolName:S}).content),L=!0,{responseHeaders:P,value:ne,rawValue:Z}=await V({...g,continuationToken:U})}let B=h.convertGenerateContentResponse({config:this.config,response:{...ne,usageMetadata:re},warnings:y,providerOptionsNames:_,toolNameMapping:A,jsonResponseToolName:S,initialPromptTokenCount:L?de:void 0,groundingMetadataPerRequest:L?X:void 0}),he={...B,content:[...K,...B.content]};return{...he,request:{body:g},response:{...he.response,headers:P,body:Z}}}async doStream(f){let{args:g,warnings:y,providerOptionsNames:_,extraHeaders:w,toolNameMapping:A,jsonResponseToolName:S}=await this.getArgs(f,{isStreaming:!0}),k=(ge)=>Object.fromEntries(_.map((be)=>[be,ge])),V=I(this.config.headers?await M(this.config.headers):void 0,f.headers,w),P=(ge)=>O({url:`${this.config.baseURL}/${ol(this.modelId)}:streamGenerateContent?alt=sse`,headers:V,body:ge,failedResponseHandler:zt,successfulResponseHandler:ze(Rg),abortSignal:f.abortSignal,fetch:this.config.fetch}),{responseHeaders:ne,value:Z}=await P(g),K=[],X=null,re=Yf({stream:Z,getContinuationToken:(ge)=>{let be=ge.candidates?.[0];if(be?.groundingMetadata!=null)X=be.groundingMetadata;return be?.finishReason==="CONTINUATION"?be.continuationToken??void 0:void 0},continueStream:async(ge)=>{let{value:be}=await P({...g,continuationToken:ge});return K.push(X),X=null,be}}),de={unified:"interrupted",raw:void 0},L=void 0,B=void 0,he=void 0,q=null,U=null,ue=null,ye=null,ve=null,_e=null,Ne,Re=this.config.generateId,Ie=!1,Be=!1,je=null,Ve=null,Ue=0,Je=new Set,Ze,tt,ot=[],et=(ge)=>{let be=ot.pop();if(be==null)return;let{finalJSON:at,closingDelta:rt}=be.accumulator.finalize();if(rt.length>0)ge.enqueue({type:"tool-input-delta",id:be.toolCallId,delta:rt,providerMetadata:be.providerMetadata});ge.enqueue({type:"tool-input-end",id:be.toolCallId,providerMetadata:be.providerMetadata}),ge.enqueue({type:"tool-call",toolCallId:be.toolCallId,toolName:be.toolName,input:at,providerMetadata:be.providerMetadata}),Ie=!0},mt={stream:re.pipeThrough(new TransformStream({start(ge){ge.enqueue({type:"stream-start",warnings:y})},transform(ge,be){if("type"in ge){de={unified:"interrupted",raw:void 0};return}if(f.includeRawChunks)be.enqueue({type:"raw",rawValue:ge.rawValue});if(!ge.success){if(de.unified==="interrupted")de={unified:"error",raw:void 0};be.enqueue({type:"error",error:ge.error});return}let at=ge.value;if(at.error!=null){de={unified:"error",raw:void 0};let N=at.error;be.enqueue({type:"error",error:Kt({message:N.message,type:N.status,code:N.code??void 0,statusCode:N.code??void 0,isRetryable:N.code!=null&&(N.code===408||N.code===409||N.code===429||N.code>=500),data:N})});return}if(!Be&&at.responseId!=null)Be=!0,be.enqueue({type:"response-metadata",id:at.responseId});let rt=at.usageMetadata;if(rt!=null)L=rt;if(at.promptFeedback!=null&&Ne==null){if(q=at.promptFeedback,pl(at.promptFeedback.blockReason))Ne=at.promptFeedback.blockReason,de={unified:"content-filter",raw:Ne}}let Me=at.candidates?.[0];if(Me!=null){if(Me.groundingMetadata!=null)U=Me.groundingMetadata;if(Me.urlContextMetadata!=null)ue=Me.urlContextMetadata;if(Me.safetyRatings!=null)ye=Me.safetyRatings;if(Me.finishMessage!=null)ve=Me.finishMessage;if(Me.continuationToken!=null)_e=Me.continuationToken}if(Ne!=null||Me==null)return;let _t=Me.content,x=hl({groundingMetadata:Me.groundingMetadata,generateId:Re});if(x!=null){for(let N of x)if(N.sourceType==="url"&&!Je.has(N.url))Je.add(N.url),be.enqueue(N)}if(_t!=null){let N=_t.parts??[];for(let R of N)if("executableCode"in R&&R.executableCode?.code){let J=Re();Ze=J,be.enqueue({type:"tool-call",toolCallId:J,toolName:A.toCustomToolName("code_execution"),input:JSON.stringify(R.executableCode),providerExecuted:!0})}else if("codeExecutionResult"in R&&R.codeExecutionResult){let J=Ze;if(J)be.enqueue({type:"tool-result",toolCallId:J,toolName:A.toCustomToolName("code_execution"),result:{outcome:R.codeExecutionResult.outcome,output:R.codeExecutionResult.output??""}})}else if("text"in R&&R.text!=null){let J=R.thoughtSignature?k({thoughtSignature:R.thoughtSignature}):void 0;if(R.text.length===0){if(J!=null&&je!==null)be.enqueue({type:"text-delta",id:je,delta:"",providerMetadata:J})}else if(R.thought===!0){if(je!==null)be.enqueue({type:"text-end",id:je}),je=null;if(Ve===null)Ve=String(Ue++),be.enqueue({type:"reasoning-start",id:Ve,providerMetadata:J});be.enqueue({type:"reasoning-delta",id:Ve,delta:R.text,providerMetadata:J})}else{if(Ve!==null)be.enqueue({type:"reasoning-end",id:Ve}),Ve=null;if(je===null)je=String(Ue++),be.enqueue({type:"text-start",id:je,providerMetadata:J});be.enqueue({type:"text-delta",id:je,delta:R.text,providerMetadata:J})}}else if("inlineData"in R){if(je!==null)be.enqueue({type:"text-end",id:je}),je=null;if(Ve!==null)be.enqueue({type:"reasoning-end",id:Ve}),Ve=null;let J=R.thought===!0,Y=R.thoughtSignature?k({thoughtSignature:R.thoughtSignature}):void 0;be.enqueue({type:J?"reasoning-file":"file",mediaType:R.inlineData.mimeType,data:{type:"data",data:R.inlineData.data},providerMetadata:Y})}else if("toolCall"in R&&R.toolCall){let J=R.toolCall.id||Re();tt=J;let Y=k({...R.thoughtSignature?{thoughtSignature:R.thoughtSignature}:{},serverToolCallId:J,serverToolType:R.toolCall.toolType});be.enqueue({type:"tool-call",toolCallId:J,toolName:`server:${R.toolCall.toolType}`,input:JSON.stringify(R.toolCall.args??{}),providerExecuted:!0,dynamic:!0,providerMetadata:Y})}else if("toolResponse"in R&&R.toolResponse){let J=tt||R.toolResponse.id||Re(),Y=k({...R.thoughtSignature?{thoughtSignature:R.thoughtSignature}:{},serverToolCallId:J,serverToolType:R.toolResponse.toolType});be.enqueue({type:"tool-result",toolCallId:J,toolName:`server:${R.toolResponse.toolType}`,result:R.toolResponse.response??{},providerMetadata:Y}),tt=void 0}for(let R of N){if(!("functionCall"in R))continue;let J=R.thoughtSignature?k({thoughtSignature:R.thoughtSignature}):void 0,Y=R.functionCall.partialArgs!=null||R.functionCall.name!=null&&R.functionCall.willContinue===!0,se=R.functionCall.name==null&&R.functionCall.args==null&&R.functionCall.partialArgs==null&&R.functionCall.willContinue==null,pe=R.functionCall.name!=null&&R.functionCall.args!=null&&R.functionCall.partialArgs==null,W=R.functionCall.name!=null&&R.functionCall.args==null&&R.functionCall.partialArgs==null&&R.functionCall.willContinue!==!0;if(Y){if(R.functionCall.name!=null){let z=R.functionCall.id||Re(),ce=new pg;if(ot.push({toolCallId:z,toolName:R.functionCall.name,accumulator:ce,providerMetadata:J}),be.enqueue({type:"tool-input-start",id:z,toolName:R.functionCall.name,providerMetadata:J}),R.functionCall.partialArgs!=null){let ie=R.functionCall.partialArgs,{textDelta:me}=ce.processPartialArgs(ie);if(me.length>0)be.enqueue({type:"tool-input-delta",id:z,delta:me,providerMetadata:J});if(R.functionCall.willContinue!==!0&&ie.every((Se)=>Se.willContinue!==!0))et(be)}}else if(R.functionCall.partialArgs!=null&&ot.length>0){let z=ot[ot.length-1],ce=R.functionCall.partialArgs,{textDelta:ie}=z.accumulator.processPartialArgs(ce);if(ie.length>0)be.enqueue({type:"tool-input-delta",id:z.toolCallId,delta:ie,providerMetadata:J});if(R.functionCall.willContinue!==!0&&ce.every((me)=>me.willContinue!==!0))et(be)}}else if(se&&ot.length>0)et(be);else if(pe){let z=R.functionCall.id||Re(),ce=R.functionCall.name,ie=typeof R.functionCall.args==="string"?R.functionCall.args:JSON.stringify(R.functionCall.args??{});be.enqueue({type:"tool-input-start",id:z,toolName:ce,providerMetadata:J}),be.enqueue({type:"tool-input-delta",id:z,delta:ie,providerMetadata:J}),be.enqueue({type:"tool-input-end",id:z,providerMetadata:J}),be.enqueue({type:"tool-call",toolCallId:z,toolName:ce,input:ie,providerMetadata:J}),Ie=!0}else if(W){let z=R.functionCall.id||Re(),ce=R.functionCall.name;be.enqueue({type:"tool-input-start",id:z,toolName:ce,providerMetadata:J}),be.enqueue({type:"tool-input-end",id:z,providerMetadata:J}),be.enqueue({type:"tool-call",toolCallId:z,toolName:ce,input:"{}",providerMetadata:J}),Ie=!0}}}if(Me.finishReason==="CONTINUATION"){if(B==null)he=L?.promptTokenCount;B=xs(B,L),L=void 0}if(Me.finishReason!=null)de={unified:dl({finishReason:Me.finishReason,hasToolCalls:Ie}),raw:Me.finishReason}},flush(ge){if(L=xs(B,L),je!==null)ge.enqueue({type:"text-end",id:je});if(Ve!==null)ge.enqueue({type:"reasoning-end",id:Ve});ge.enqueue({type:"finish",finishReason:de,usage:rl(L),providerMetadata:k({promptFeedback:q,groundingMetadata:U,...K.length>0?{groundingMetadataPerRequest:[...K,X]}:{},urlContextMetadata:ue,safetyRatings:ye,usageMetadata:L??null,finishMessage:ve,serviceTier:L?.serviceTier??null,..._e!=null&&(de.raw==="MAX_TOKENS"||de.raw==="CONTINUATION")?{continuationToken:_e}:{},...he!=null?{initialPromptTokenCount:he}:{}})})}})),response:{headers:ne},request:{body:g}};return{...mt,stream:S==null?mt.stream:mt.stream.pipeThrough(gp(S))}}};function vg(){return 65536}function Eg(h){let f=h.toLowerCase();if(f.includes("2.5-pro")||f.includes("gemini-3-pro-image"))return 32768;return 24576}function Cg(h){return h.toLowerCase().includes("2.5-pro")?128:0}function bg({reasoning:h,modelId:f,warnings:g}){if(!Pe(h))return;if(tr(f).usesGemini3Features&&!f.includes("gemini-3-pro-image"))return Ag({reasoning:h,modelId:f,warnings:g});return kg({reasoning:h,modelId:f,warnings:g})}function Ag({reasoning:h,modelId:f,warnings:g}){let y=Sg(f),_=ut({reasoning:h,effortMap:{...y==="minimal"&&{minimal:"minimal"},low:"low",medium:"medium",high:"high"},warnings:g});if(_==null)return;return{thinkingLevel:_}}function Sg(h){let f=/(?:^|[/.])(gemini-[^/]*)$/i.exec(h)?.[1].toLowerCase();if(f==="gemini-flash-latest")return"low";let g=/^gemini-(\d+)(?:\.\d+)?-pro(?:$|-)/.exec(f??"");if(Number(g?.[1])>=3)return"low";let y=/^gemini-(\d+)\.(\d+)-flash(?:$|-(?!lite(?:-|$)))/.exec(f??"");if(y==null)return"minimal";let _=Number(y[1]),w=Number(y[2]);return _>3||_===3&&w>=7?"low":"minimal"}function kg({reasoning:h,modelId:f,warnings:g}){let y=Cg(f);if(h==="none"&&y===0)return{thinkingBudget:0};return{thinkingBudget:nn({reasoning:h,maxOutputTokens:vg(),maxReasoningBudget:Eg(f),minReasoningBudget:y,warnings:g})}}function hl({groundingMetadata:h,generateId:f}){if(!h?.groundingChunks)return;let g=[];for(let y of h.groundingChunks)if(y.web!=null)g.push({type:"source",sourceType:"url",id:f(),url:y.web.uri,title:y.web.title??void 0});else if(y.image!=null)g.push({type:"source",sourceType:"url",id:f(),url:y.image.sourceUri,title:y.image.title??void 0});else if(y.retrievedContext!=null){let _=y.retrievedContext.uri,w=y.retrievedContext.fileSearchStore;if(_&&(_.startsWith("http://")||_.startsWith("https://")))g.push({type:"source",sourceType:"url",id:f(),url:_,title:y.retrievedContext.title??void 0});else if(_){let A=y.retrievedContext.title??"Unknown Document",S="application/octet-stream",k=void 0;if(_.endsWith(".pdf"))S="application/pdf",k=_.split("/").pop();else if(_.endsWith(".txt"))S="text/plain",k=_.split("/").pop();else if(_.endsWith(".docx"))S="application/vnd.openxmlformats-officedocument.wordprocessingml.document",k=_.split("/").pop();else if(_.endsWith(".doc"))S="application/msword",k=_.split("/").pop();else if(_.match(/\.(md|markdown)$/))S="text/markdown",k=_.split("/").pop();else k=_.split("/").pop();g.push({type:"source",sourceType:"document",id:f(),mediaType:S,title:A,filename:k})}else if(w){let A=y.retrievedContext.title??"Unknown Document";g.push({type:"source",sourceType:"document",id:f(),mediaType:"application/octet-stream",title:A,filename:w.split("/").pop()})}}else if(y.maps!=null){if(y.maps.uri)g.push({type:"source",sourceType:"url",id:f(),url:y.maps.uri,title:y.maps.title??void 0})}return g.length>0?g:void 0}var kl=()=>t({webSearchQueries:o(e()).nullish(),imageSearchQueries:o(e()).nullish(),retrievalQueries:o(e()).nullish(),searchEntryPoint:t({renderedContent:e()}).nullish(),groundingChunks:o(t({web:t({uri:e(),title:e().nullish()}).nullish(),image:t({sourceUri:e(),imageUri:e(),title:e().nullish(),domain:e().nullish()}).nullish(),retrievedContext:t({uri:e().nullish(),title:e().nullish(),text:e().nullish(),fileSearchStore:e().nullish(),customMetadata:o(t({key:e(),stringValue:e().nullish(),numericValue:n().nullish(),stringListValue:t({values:o(e()).nullish()}).nullish()})).nullish()}).nullish(),maps:t({uri:e().nullish(),title:e().nullish(),text:e().nullish(),placeId:e().nullish()}).nullish()})).nullish(),groundingSupports:o(t({segment:t({startIndex:n().nullish(),endIndex:n().nullish(),text:e().nullish()}).nullish(),segment_text:e().nullish(),groundingChunkIndices:o(n()).nullish(),supportChunkIndices:o(n()).nullish(),confidenceScores:o(n()).nullish(),confidenceScore:o(n()).nullish()})).nullish(),retrievalMetadata:p([t({webDynamicRetrievalScore:n()}),t({})]).nullish()}),xg=()=>t({jsonPath:e(),stringValue:e().nullish(),numberValue:n().nullish(),boolValue:r().nullish(),nullValue:m().nullish(),willContinue:r().nullish()}),xl=()=>t({parts:o(p([t({functionCall:t({id:e().nullish(),name:e().nullish(),args:m().nullish(),partialArgs:o(xg()).nullish(),willContinue:r().nullish()}),thoughtSignature:e().nullish()}),t({inlineData:t({mimeType:e(),data:e()}),thought:r().nullish(),thoughtSignature:e().nullish()}),t({toolCall:t({toolType:e(),args:m().nullish(),id:e()}),thoughtSignature:e().nullish()}),t({toolResponse:t({toolType:e(),response:m().nullish(),id:e()}),thoughtSignature:e().nullish()}),t({executableCode:t({language:e(),code:e()}).nullish(),codeExecutionResult:t({outcome:e(),output:e().nullish()}).nullish(),text:e().nullish(),thought:r().nullish(),thoughtSignature:e().nullish()})])).nullish()}),nr=()=>t({category:e().nullish(),probability:e().nullish(),probabilityScore:n().nullish(),severity:e().nullish(),severityScore:n().nullish(),blocked:r().nullish()}),Qn=()=>o(t({modality:e(),tokenCount:n()}).loose()).nullish(),Ol=()=>t({cachedContentTokenCount:n().nullish(),thoughtsTokenCount:n().nullish(),promptTokenCount:n().nullish(),candidatesTokenCount:n().nullish(),toolUsePromptTokenCount:n().nullish(),totalTokenCount:n().nullish(),trafficType:e().nullish(),serviceTier:e().nullish(),promptTokensDetails:Qn(),cacheTokensDetails:Qn(),candidatesTokensDetails:Qn(),toolUsePromptTokensDetails:Qn()}).loose(),Rl=()=>t({urlMetadata:o(t({retrievedUrl:e(),urlRetrievalStatus:e()})).nullish()}),Og=u(()=>l(t({responseId:e().nullish(),candidates:o(t({content:xl().nullish().or(t({}).strict()),finishReason:e().nullish(),finishMessage:e().nullish(),continuationToken:e().nullish(),safetyRatings:o(nr()).nullish(),groundingMetadata:kl().nullish(),urlContextMetadata:Rl().nullish()})).nullish(),usageMetadata:Ol().nullish(),promptFeedback:t({blockReason:e().nullish(),safetyRatings:o(nr()).nullish()}).nullish()}))),Rg=u(()=>l(t({error:bl().nullish(),responseId:e().nullish(),candidates:o(t({content:xl().nullish(),finishReason:e().nullish(),finishMessage:e().nullish(),continuationToken:e().nullish(),safetyRatings:o(nr()).nullish(),groundingMetadata:kl().nullish(),urlContextMetadata:Rl().nullish()})).nullish(),usageMetadata:Ol().nullish(),promptFeedback:t({blockReason:e().nullish(),safetyRatings:o(nr()).nullish()}).nullish()})));function pl(h){return h!=null&&h!==""&&h!=="BLOCK_REASON_UNSPECIFIED"&&h!=="BLOCKED_REASON_UNSPECIFIED"}var Ig=u(()=>l(t({candidates:o(t({content:t({parts:o(t({inlineData:t({mimeType:e().nullish(),data:e().nullish()}).nullish()})).nullish()}).nullish()})).nullish(),usageMetadata:d(e(),Fe()).nullish()})));function Ng({text:h,voice:f,providerOptions:g}){let y=g?.google,_=y!=null&&typeof y==="object"?y:void 0,w=_&&"turns"in _?_.turns:void 0,A=[];if(Array.isArray(w)&&w.length>0){for(let V of w){if(V==null||typeof V!=="object"||!("text"in V)||typeof V.text!=="string")break;A.push(V.text)}if(A.length===w.length)h=A.join("")}let S=_&&"multiSpeakerVoiceConfig"in _?_.multiSpeakerVoiceConfig:void 0,k=S!=null&&typeof S==="object"&&"speakerVoiceConfigs"in S&&Array.isArray(S.speakerVoiceConfigs)?S.speakerVoiceConfigs:[];return{text:h,usesCustomVoice:f?.startsWith("voice_")===!0||f?.startsWith("voicekey_")===!0||k.some((V)=>V!=null&&typeof V==="object"&&("voiceConfig"in V)&&V.voiceConfig!=null&&typeof V.voiceConfig==="object"&&("voice"in V.voiceConfig))}}var Pg=()=>t({voiceName:e()}),jg=()=>t({prebuiltVoiceConfig:Pg(),voice:le().optional()}),fl=()=>t({speaker:e().min(1).optional(),style:e().optional()}),gl=u(()=>l(t({speechMetadata:fl().optional(),turns:o(t({text:e(),speechMetadata:fl().optional()})).min(1).optional(),multiSpeakerVoiceConfig:t({speakerVoiceConfigs:o(t({speaker:e(),voiceConfig:jg()}))}).optional()}))),Ug="Kore",Mg=24000,Il=class h{static[H](f){return te({modelId:f.modelId,config:f.config})}static[Q](f){return new h(f.modelId,f.config)}get provider(){return this.config.provider}constructor(f,g){this.modelId=f,this.config=g,this.specificationVersion="v4"}async getArgs({text:f,voice:g=Ug,outputFormat:y,instructions:_,speed:w,language:A,providerOptions:S}){let k=[],V=this.config.provider.includes("vertex")?["googleVertex","vertex"]:["google"],P;for(let he of V)if(P=await T({provider:he,providerOptions:S,schema:gl}),P!=null)break;if(P==null&&!V.includes("google"))P=await T({provider:"google",providerOptions:S,schema:gl});let ne=!this.modelId.startsWith("gemini-2.5-")&&!this.modelId.startsWith("gemini-3.1-"),Z=Ng({text:f,voice:g,providerOptions:{google:P}});if(Z.usesCustomVoice)throw new F({argument:"voice",message:"Custom voices are not supported. Use a prebuilt voice instead."});let K=P?.multiSpeakerVoiceConfig,X=K?{multiSpeakerVoiceConfig:K}:{voiceConfig:{prebuiltVoiceConfig:{voiceName:g}}},re=f;if(_!=null&&!ne)if(K)k.push({type:"unsupported",feature:"instructions",details:"Google Gemini TTS ignores `instructions` when `multiSpeakerVoiceConfig` is set, because prepending them would break multi-speaker transcript parsing."});else re=`${_}: ${f}`;let de=[{text:re}];if(ne){if(P?.turns&&P.speechMetadata)throw new F({argument:"providerOptions",message:"Set speechMetadata on each turn when using turns."});if(P?.turns&&f!=="")k.push({type:"unsupported",feature:"text",details:"Google TTS turns replace the top-level text."});de=(P?.turns??[{text:f,speechMetadata:P?.speechMetadata}]).map((he)=>{let q=he.speechMetadata?.style??_,U=he.speechMetadata?.speaker;if(K&&!K.speakerVoiceConfigs.some((ue)=>ue.speaker===U))throw new F({argument:"speechMetadata.speaker",message:"Every multi-speaker turn must specify a speechMetadata.speaker matching a configured speaker."});return{text:he.text,...q!=null||U!=null?{speechMetadata:{style:q,speaker:U}}:{}}})}else if(P?.turns||P?.speechMetadata)throw new F({argument:"providerOptions",message:"Structured speech metadata and turns require Gemini 3.8 TTS."});if(Z.text.length===0)throw new F({argument:"text",message:"Speech input must contain a non-empty transcript."});if(w!=null)k.push({type:"unsupported",feature:"speed",details:"Google Gemini TTS models do not support the `speed` option. It was ignored."});if(A!=null)k.push({type:"unsupported",feature:"language",details:"Google Gemini TTS models do not support the `language` option. Language is detected automatically from the input text."});let L=ne?{wav:"AUDIO_WAV","audio/wav":"AUDIO_WAV",pcm:"AUDIO_L16","audio/l16":"AUDIO_L16",mulaw:"AUDIO_MULAW","audio/mulaw":"AUDIO_MULAW",alaw:"AUDIO_ALAW","audio/alaw":"AUDIO_ALAW"}:{wav:"AUDIO_WAV",pcm:"AUDIO_L16"},B="wav";if(y!=null&&Object.prototype.hasOwnProperty.call(L,y))B=y;else if(y!=null)k.push({type:"unsupported",feature:"outputFormat",details:`Unsupported output format: ${y}. Using wav instead.`});return{requestBody:{contents:[{role:"user",parts:de}],generationConfig:{responseModalities:["AUDIO"],speechConfig:X,...ne&&y!=null?{responseFormat:{audio:{mimeType:L[B]}}}:{}}},warnings:k,outputFormat:L[B],usesStructuredSpeech:ne}}async doGenerate(f){let g=this.config._internal?.currentDate?.()??new Date,{requestBody:y,warnings:_,outputFormat:w,usesStructuredSpeech:A}=await this.getArgs(f),{value:S,responseHeaders:k,rawValue:V}=await O({url:`${this.config.baseURL}/models/${this.modelId}:generateContent`,headers:I(this.config.headers?await M(this.config.headers):void 0,f.headers),body:y,failedResponseHandler:zt,successfulResponseHandler:E(Ig),abortSignal:f.abortSignal,fetch:this.config.fetch}),P,ne;for(let de of S.candidates??[]){for(let L of de.content?.parts??[])if(L.inlineData?.data){P=L.inlineData.data,ne=L.inlineData.mimeType??void 0;break}if(P!=null)break}let Z=Dg(ne)??Mg,K=P!=null?ke(P):new Uint8Array(0),X=/^audio\/(?:l16|pcm)(?:;|$)/i.test(ne??"")||ne==null&&!A,re=w==="AUDIO_WAV"&&X&&K.length>0?Lg(K,Z):K;if(w==="AUDIO_L16"&&K.length>0&&!A)_.push({type:"unsupported",feature:"outputFormat",details:`Returning raw PCM audio (signed 16-bit little-endian, mono, ${Z} Hz). These bytes have no container header and are not directly playable; see providerMetadata.google for the sample rate and mime type.`});return{audio:re,warnings:_,...S.usageMetadata!=null&&{usage:S.usageMetadata},request:{body:JSON.stringify(y)},response:{timestamp:g,modelId:this.modelId,headers:k,body:V},providerMetadata:{google:{sampleRate:Z,mimeType:ne??null}}}}};function Dg(h){if(h==null)return;let f=/rate=(\d+)/.exec(h);return f?Number.parseInt(f[1],10):void 0}function Lg(h,f){let w=f*2,A=h.length,S=new ArrayBuffer(44+A),k=new DataView(S);Zn(k,0,"RIFF"),k.setUint32(4,36+A,!0),Zn(k,8,"WAVE"),Zn(k,12,"fmt "),k.setUint32(16,16,!0),k.setUint16(20,1,!0),k.setUint16(22,1,!0),k.setUint32(24,f,!0),k.setUint32(28,w,!0),k.setUint16(32,2,!0),k.setUint16(34,16,!0),Zn(k,36,"data"),k.setUint32(40,A,!0);let V=new Uint8Array(S);return V.set(h,44),V}function Zn(h,f,g){for(let y=0;y<g.length;y++)h.setUint8(f+y,g.charCodeAt(y))}var qg=G({id:"google.enterprise_web_search",inputSchema:u(()=>l(t({}))),outputSchema:u(()=>l(t({})))});u(()=>l(ae({fileSearchStoreNames:o(e()).describe("The names of the file_search_stores to retrieve from. Example: `fileSearchStores/my-file-search-store-123`"),topK:n().int().positive().describe("The number of file search retrieval chunks to retrieve.").optional(),metadataFilter:e().describe("Metadata filter to apply to the file search retrieval documents. See https://google.aip.dev/160 for the syntax of the filter expression.").optional()})));var Fg=G({id:"google.file_search",inputSchema:u(()=>l(t({}))),outputSchema:u(()=>l(t({})))}),Gg=G({id:"google.google_maps",inputSchema:u(()=>l(t({}))),outputSchema:u(()=>l(t({})))}),Xt={googleSearch:G({id:"google.google_search",inputSchema:u(()=>l(t({}))),outputSchema:u(()=>l(t({})))}),enterpriseWebSearch:qg,googleMaps:Gg,urlContext:G({id:"google.url_context",inputSchema:u(()=>l(t({}))),outputSchema:u(()=>l(t({})))}),fileSearch:Fg,codeExecution:Xf,vertexRagStore:G({id:"google.vertex_rag_store",inputSchema:u(()=>l(t({}))),outputSchema:u(()=>l(t({})))})};function Us(h){if(h==null)return At();let f=h.total_input_tokens??0,g=h.total_output_tokens??0,y=h.total_thought_tokens??0,_=h.total_cached_tokens??0;return{inputTokens:{total:h.total_input_tokens??void 0,noCache:h.total_input_tokens==null?void 0:f-_,cacheRead:h.total_cached_tokens??void 0,cacheWrite:void 0},outputTokens:{total:h.total_output_tokens==null&&h.total_thought_tokens==null?void 0:g+y,text:h.total_output_tokens??void 0,reasoning:h.total_thought_tokens??void 0},raw:h}}function Nl(h){let f=h?.output_tokens_by_modality;if(f==null)return;let g={};for(let y of f)if(y?.modality!=null&&y.tokens!=null)g[y.modality]=y.tokens;return Object.keys(g).length>0?g:void 0}var $g={pdf:"application/pdf",txt:"text/plain",md:"text/markdown",markdown:"text/markdown",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"};function Pl(h){let f=h.toLowerCase();for(let[g,y]of Object.entries($g))if(f.endsWith(`.${g}`))return y;return"application/octet-stream"}function jl(h){let f=h.split("/"),g=f[f.length-1];return g&&g.length>0?g:void 0}function Hg({annotation:h,generateId:f}){switch(h.type){case"url_citation":{let g=h;if(g.url==null||g.url.length===0)return;return{type:"source",sourceType:"url",id:f(),url:g.url,...g.title!=null?{title:g.title}:{}}}case"file_citation":{let g=h,y=g.url??g.document_uri??g.file_name;if(y==null||y.length===0)return;if(y.startsWith("http://")||y.startsWith("https://"))return{type:"source",sourceType:"url",id:f(),url:y,...g.file_name!=null?{title:g.file_name}:{}};let _=g.file_name??jl(y),w=Pl(y);return{type:"source",sourceType:"document",id:f(),mediaType:w,title:g.file_name??_??y,..._!=null?{filename:_}:{}}}case"place_citation":{let g=h;if(g.url==null||g.url.length===0)return;return{type:"source",sourceType:"url",id:f(),url:g.url,...g.name!=null?{title:g.name}:{}}}default:return}}function Ul({block:h,generateId:f}){let g=[];switch(h.type){case"url_context_result":{let y=h.result??[];for(let _ of y){if(_?.url==null||_.url.length===0)continue;if(_.status!=null&&_.status!=="success")continue;g.push({type:"source",sourceType:"url",id:f(),url:_.url})}break}case"google_search_result":{let y=h.result??[];for(let _ of y){let w=_?.url;if(w==null||w.length===0)continue;g.push({type:"source",sourceType:"url",id:f(),url:w,..._.title!=null?{title:_.title}:{}})}break}case"google_maps_result":{let y=h.result??[];for(let _ of y)for(let w of _.places??[]){if(w.url==null||w.url.length===0)continue;g.push({type:"source",sourceType:"url",id:f(),url:w.url,...w.name!=null?{title:w.name}:{}})}break}case"file_search_result":{let y=h.result??[];for(let _ of y){if(_==null||typeof _!=="object")continue;let w=_,A=w.url??w.document_uri??w.file_name;if(A==null||A.length===0)continue;if(A.startsWith("http://")||A.startsWith("https://")){g.push({type:"source",sourceType:"url",id:f(),url:A,...w.title!=null?{title:w.title}:{}});continue}let S=w.file_name??jl(A),k=Pl(A);g.push({type:"source",sourceType:"document",id:f(),mediaType:k,title:w.title??w.file_name??S??A,...S!=null?{filename:S}:{}})}break}}return g}function Is({annotations:h,generateId:f}){if(h==null)return[];let g=new Set,y=[];for(let _ of h){let w=Hg({annotation:_,generateId:f});if(w==null)continue;let A=w.sourceType==="url"?`url:${w.url}`:`doc:${w.filename??w.title}`;if(g.has(A))continue;g.add(A),y.push(w)}return y}function Ms({status:h,hasFunctionCall:f}){switch(h){case"completed":return f?"tool-calls":"stop";case"requires_action":return"tool-calls";case"failed":return"error";case"incomplete":return"length";case"cancelled":return"other";default:return"other"}}var Bg=new Set(["google_search_call","code_execution_call","url_context_call","file_search_call","google_maps_call","mcp_server_tool_call"]),Vg=new Set(["google_search_result","code_execution_result","url_context_result","file_search_result","google_maps_result","mcp_server_tool_result"]);function Wg(h){return h.replace(/_call$/,"")}function Jg(h){return h.replace(/_result$/,"")}function ml({warnings:h,generateId:f,includeRawChunks:g,serviceTier:y}){let _,w,A=y,S,k=!1,V=!1,P=new Map,ne=new Set;function Z(K){return K.sourceType==="url"?`url:${K.url}`:`doc:${K.filename??K.title}`}return new TransformStream({start(K){K.enqueue({type:"stream-start",warnings:h})},transform(K,X){if(g)X.enqueue({type:"raw",rawValue:K.rawValue});if(!K.success){S="failed",X.enqueue({type:"error",error:K.error});return}let re=K.value,de=re.event_type;switch(de){case"interaction.created":{let L=re.interaction;_=L?.id!=null&&L.id.length>0?L.id:void 0;let B=L?.created,he;if(typeof B==="string"){let q=new Date(B);if(!Number.isNaN(q.getTime()))he=q}X.enqueue({type:"response-metadata",..._!=null?{id:_}:{},modelId:L?.model,...he?{timestamp:he}:{}});break}case"step.start":{let L=re,{step:B,index:he}=L,q=`${_??"interaction"}:${he}`,U=B?.type;if(U==="model_output"){let ue=B?.content?.[0];if(ue?.type==="text"){P.set(he,{kind:"text",id:q,emittedSourceKeys:new Set}),X.enqueue({type:"text-start",id:q});let ye=Is({annotations:ue.annotations,generateId:f});for(let ve of ye){let _e=Z(ve);if(ne.has(_e))continue;ne.add(_e),X.enqueue(ve)}}else if(ue?.type==="image")P.set(he,{kind:"image",id:q,...ue.data!=null?{data:ue.data}:{},...ue.mime_type!=null?{mimeType:ue.mime_type}:{},...ue.uri!=null?{uri:ue.uri}:{}});else P.set(he,{kind:"pending_model_output",id:q})}else if(U==="thought"){let ue=B?.signature;if(P.set(he,{kind:"reasoning",id:q,...ue!=null?{signature:ue}:{}}),X.enqueue({type:"reasoning-start",id:q}),Array.isArray(B?.summary)){for(let ye of B.summary)if(ye?.type==="text"&&typeof ye.text==="string")X.enqueue({type:"reasoning-delta",id:q,delta:ye.text})}}else if(U==="processing_call"||U==="processing_result"){let ue={};if(B?.signature!=null)ue.signature=B.signature;if(_!=null)ue.interactionId=_;if(U==="processing_call")ue.processingId=B?.id||q;else ue.processingCallId=B?.call_id||q;P.set(he,{kind:"custom",id:q,customKind:`google.${U}`,google:ue})}else if(U==="function_call"){let ue=B?.id||q,ye=B?.name??"unknown";k=!0;let ve={kind:"function_call",id:q,toolCallId:ue,toolName:ye,argumentsAccum:"",...B?.signature!=null?{signature:B.signature}:{}};P.set(he,ve),X.enqueue({type:"tool-input-start",id:ue,toolName:ye})}else if(U!=null&&Bg.has(U)){let ue=U==="mcp_server_tool_call"?B?.name??"mcp_server_tool":Wg(U),ye={kind:"builtin_tool_call",id:q,blockType:U,toolCallId:B?.id||q,toolName:ue,arguments:B?.arguments??{},callEmitted:!1};P.set(he,ye)}else if(U!=null&&Vg.has(U)){let ue=U==="mcp_server_tool_result"?B?.name??"mcp_server_tool":Jg(U),ye={kind:"builtin_tool_result",id:q,blockType:U,callId:B?.call_id||q,toolName:ue,result:B?.result??null,...B?.is_error!=null?{isError:B.is_error}:{},resultEmitted:!1};P.set(he,ye)}else P.set(he,{kind:"unknown",id:q});break}case"step.delta":{let L=re,B=P.get(L.index);if(B==null)break;let he=L.delta?.type;if(B.kind==="pending_model_output"){if(he==="text"||he==="text_annotation"||he==="text_annotation_delta"){let U={kind:"text",id:B.id,emittedSourceKeys:new Set};P.set(L.index,U),B=U,X.enqueue({type:"text-start",id:U.id})}}if(he==="image"&&(B.kind==="pending_model_output"||B.kind==="text"||B.kind==="image")){let U=L.delta,ue={};if(_!=null)ue.interactionId=_;let ye=Object.keys(ue).length>0?{google:ue}:void 0;if(U?.data!=null&&U.data.length>0)X.enqueue({type:"file",mediaType:U.mime_type??"image/png",data:{type:"data",data:U.data},...ye?{providerMetadata:ye}:{}});else if(U?.uri!=null&&U.uri.length>0)X.enqueue({type:"file",mediaType:U.mime_type??"image/png",data:{type:"url",url:new URL(U.uri)},...ye?{providerMetadata:ye}:{}});if(B.kind==="image")B.data=void 0,B.uri=void 0;break}if(he==="video"&&(B.kind==="pending_model_output"||B.kind==="text")){let U=L.delta,ue={};if(_!=null)ue.interactionId=_;let ye=Object.keys(ue).length>0?{google:ue}:void 0;if(U?.data!=null&&U.data.length>0)X.enqueue({type:"file",mediaType:U.mime_type??"video/mp4",data:{type:"data",data:U.data},...ye?{providerMetadata:ye}:{}});else if(U?.uri!=null&&U.uri.length>0)X.enqueue({type:"file",mediaType:U.mime_type??"video/mp4",data:{type:"url",url:new URL(U.uri)},...ye?{providerMetadata:ye}:{}});break}let q=L.delta;if(B.kind==="custom"&&(q?.type==="processing_call"||q?.type==="processing_result")){if(q.signature!=null)B.google.signature=q.signature;if(q.type==="processing_call"&&q.id!=null&&q.id.length>0)B.google.processingId=q.id;if(q.type==="processing_result"&&q.call_id!=null&&q.call_id.length>0)B.google.processingCallId=q.call_id}else if(B.kind==="text"&&q?.type==="text"){let U=q.text??"";if(U.length>0)X.enqueue({type:"text-delta",id:B.id,delta:U})}else if(B.kind==="text"&&(q?.type==="text_annotation"||q?.type==="text_annotation_delta")){let U=Is({annotations:q.annotations,generateId:f});for(let ue of U){let ye=Z(ue);if(ne.has(ye))continue;ne.add(ye),B.emittedSourceKeys.add(ye),X.enqueue(ue)}}else if(B.kind==="image"&&q?.type==="image"){if(q.data!=null)B.data=q.data;if(q.mime_type!=null)B.mimeType=q.mime_type;if(q.uri!=null)B.uri=q.uri}else if(B.kind==="reasoning"){if(q?.type==="thought_summary"){let U=q.content;if(U?.type==="text"&&typeof U.text==="string")X.enqueue({type:"reasoning-delta",id:B.id,delta:U.text})}else if(q?.type==="thought_signature"){let U=q.signature;if(U!=null)B.signature=U}}else if(B.kind==="function_call"&&q?.type==="arguments_delta"){let U=typeof q.arguments==="string"?q.arguments:"";if(U.length>0)B.argumentsAccum+=U,X.enqueue({type:"tool-input-delta",id:B.toolCallId,delta:U});if(q.id!=null&&q.id.length>0)B.toolCallId=q.id;if(q.signature!=null)B.signature=q.signature;k=!0}else if(B.kind==="builtin_tool_call"&&q?.type===B.blockType){if(q.id!=null&&q.id.length>0)B.toolCallId=q.id;if(q.arguments!=null&&typeof q.arguments==="object")B.arguments=q.arguments;if(q.name!=null&&B.blockType==="mcp_server_tool_call")B.toolName=q.name}else if(B.kind==="builtin_tool_result"&&q?.type===B.blockType){if(q.call_id!=null&&q.call_id.length>0)B.callId=q.call_id;if(q.result!==void 0)B.result=q.result;if(q.is_error!=null)B.isError=q.is_error;if(q.name!=null&&B.blockType==="mcp_server_tool_result")B.toolName=q.name}break}case"step.stop":{let L=re,B=P.get(L.index);if(B==null)break;if(B.kind==="text"){let he=_!=null?{google:{interactionId:_}}:void 0;X.enqueue({type:"text-end",id:B.id,...he?{providerMetadata:he}:{}})}else if(B.kind==="reasoning"){let he={};if(B.signature!=null)he.signature=B.signature;if(_!=null)he.interactionId=_;let q=Object.keys(he).length>0?{google:he}:void 0;X.enqueue({type:"reasoning-end",id:B.id,...q?{providerMetadata:q}:{}})}else if(B.kind==="image"){let he={};if(_!=null)he.interactionId=_;let q=Object.keys(he).length>0?{google:he}:void 0;if(B.data!=null&&B.data.length>0)X.enqueue({type:"file",mediaType:B.mimeType??"image/png",data:{type:"data",data:B.data},...q?{providerMetadata:q}:{}});else if(B.uri!=null&&B.uri.length>0)X.enqueue({type:"file",mediaType:B.mimeType??"image/png",data:{type:"url",url:new URL(B.uri)},...q?{providerMetadata:q}:{}})}else if(B.kind==="function_call"){let he=B.argumentsAccum.length>0?B.argumentsAccum:"{}";X.enqueue({type:"tool-input-end",id:B.toolCallId});let q={};if(B.signature!=null)q.signature=B.signature;if(_!=null)q.interactionId=_;let U=Object.keys(q).length>0?{google:q}:void 0;X.enqueue({type:"tool-call",toolCallId:B.toolCallId,toolName:B.toolName,input:he,...U?{providerMetadata:U}:{}})}else if(B.kind==="custom")X.enqueue({type:"custom",kind:B.customKind,providerMetadata:{google:B.google}});else if(B.kind==="builtin_tool_call"&&!B.callEmitted)X.enqueue({type:"tool-call",toolCallId:B.toolCallId,toolName:B.toolName,input:JSON.stringify(B.arguments??{}),providerExecuted:!0}),B.callEmitted=!0;else if(B.kind==="builtin_tool_result"&&!B.resultEmitted){X.enqueue({type:"tool-result",toolCallId:B.callId,toolName:B.toolName,result:B.result??null}),B.resultEmitted=!0;let he=Ul({block:{type:B.blockType,call_id:B.callId,result:B.result},generateId:f});for(let q of he){let U=Z(q);if(ne.has(U))continue;ne.add(U),X.enqueue(q)}}P.delete(L.index);break}case"interaction.status_update":case"interaction.in_progress":case"interaction.requires_action":{let L=re;if(L.status!=null)S=L.status;else if(de==="interaction.requires_action")S="requires_action";else S="in_progress";break}case"interaction.completed":{V=!0;let L=re.interaction;if(L?.id!=null&&L.id.length>0)_=L.id;if(L?.status!=null)S=L.status;if(L?.usage!=null)w=L.usage;if(L?.service_tier!=null)A=L.service_tier;break}case"error":{let L=re;S="failed",X.enqueue({type:"error",error:Kt({message:L.error?.message??"Unknown interaction error",type:L.event_type,code:L.error?.code??void 0,data:L})});break}}},flush(K){let X=!V&&(S==null||S==="in_progress"),re={unified:X?"interrupted":Ms({status:S,hasFunctionCall:k}),raw:X?void 0:S},de=Nl(w),L={google:{..._!=null?{interactionId:_}:{},...A!=null?{serviceTier:A}:{},...de!=null?{outputTokensByModality:de}:{}}};K.enqueue({type:"finish",finishReason:re,usage:Us(w),providerMetadata:L})}})}function Kg({prompt:h,previousInteractionId:f,store:g,mediaResolution:y}){let _=[],w=f!=null&&g===!1,A=f!=null&&g!==!1;if(w)_.push({type:"other",message:"google.interactions: providerOptions.google.previousInteractionId was set together with store: false. These are incoherent (the prior interaction cannot be referenced when nothing was stored on the server); the full history will be sent and previous_interaction_id will still be emitted."});let S=A?zg({prompt:h,previousInteractionId:f}):h,k=[],V=[];for(let P of S)switch(P.role){case"system":k.push(P.content);break;case"user":{let ne=[];for(let K of P.content)if(K.type==="text")ne.push({type:"text",text:K.text});else if(K.type==="file"){let X=yl({part:K,warnings:_,mediaResolution:y});if(X!=null)ne.push(X)}let Z=em(ne);if(Z.length>0)V.push({type:"user_input",content:Z});break}case"assistant":{let ne=[],Z=()=>{if(ne.length>0)V.push({type:"model_output",content:ne}),ne=[]};for(let K of P.content)if(K.type==="text")ne.push({type:"text",text:K.text});else if(K.type==="reasoning"){Z();let X=K.providerOptions?.google?.signature;V.push({type:"thought",...X!=null?{signature:X}:{},summary:K.text.length>0?[{type:"text",text:K.text}]:void 0})}else if(K.type==="file"){let X=yl({part:K,warnings:_,mediaResolution:y});if(X!=null)ne.push(X)}else if(K.type==="custom"){Z();let X=K.providerOptions?.google,re=typeof X?.signature==="string"?X.signature:void 0;if(K.kind==="google.processing_call"&&typeof X?.processingId==="string")V.push({type:"processing_call",id:X.processingId,...re!=null?{signature:re}:{}});else if(K.kind==="google.processing_result"&&typeof X?.processingCallId==="string")V.push({type:"processing_result",call_id:X.processingCallId,...re!=null?{signature:re}:{}});else _.push({type:"other",message:`google.interactions: unsupported or invalid custom assistant content part "${K.kind}"; part dropped.`})}else if(K.type==="tool-call"){Z();let X=K.providerOptions?.google?.signature,re=typeof K.input==="string"?Xg(K.input):K.input??{};V.push({type:"function_call",id:K.toolCallId,name:K.toolName,arguments:re,...X!=null?{signature:X}:{}})}else _.push({type:"other",message:`google.interactions: unsupported assistant content part type "${K.type}"; part dropped.`});Z();break}case"tool":{let ne=[];for(let Z of P.content){if(Z.type!=="tool-result"){_.push({type:"other",message:`google.interactions: unsupported tool message part type "${Z.type}"; part dropped.`});continue}let K=Qg({toolCallId:Z.toolCallId,toolName:Z.toolName,output:Z.output,signature:Z.providerOptions?.google?.signature,warnings:_});ne.push(K)}if(ne.length>0)V.push({type:"user_input",content:ne});break}}return{input:V,systemInstruction:k.length>0?k.join(`
34
+
35
+ `):void 0,warnings:_}}function yl({part:h,warnings:f,mediaResolution:g}){if(h.data.type==="text")return{type:"text",text:h.data.text};let y=fe(h.mediaType),_;switch(y){case"image":_="image";break;case"audio":_="audio";break;case"video":_="video";break;case"application":case"text":_="document";break;default:_=void 0}if(_==null){f.push({type:"other",message:`google.interactions: unsupported file media type "${h.mediaType}"; part dropped.`});return}let w=g!=null&&(_==="image"||_==="video")?{resolution:g}:{},A=_==="video"?Yg({part:h,warnings:f}):{};switch(h.data.type){case"data":{let S=ee({part:h});return{type:_,data:j(h.data.data),mime_type:S,...w,...A}}case"url":return{type:_,uri:h.data.url.toString(),...Ae(h.mediaType)?{mime_type:h.mediaType}:{},...w,...A};case"reference":{let S=qe({reference:h.data.reference,provider:"google"});return{type:_,uri:S,...Ae(h.mediaType)?{mime_type:h.mediaType}:{},...w,...A}}}}function Yg({part:h,warnings:f}){let g=h.providerOptions?.google?.processing;if(g==null)return{};if(g==="agentic"||g==="static")return{processing:g};if(typeof g==="object"&&!Array.isArray(g)&&g.type==="static"){let y=g;return{processing:{type:"static",...typeof y.startOffset==="number"?{start_offset:`${y.startOffset}s`}:{},...typeof y.endOffset==="number"?{end_offset:`${y.endOffset}s`}:{},...typeof y.fps==="number"?{fps:y.fps}:{}}}}return f.push({type:"other",message:'google.interactions: invalid providerOptions.google.processing on video file part; expected "agentic", "static", or a static processing configuration. Option dropped.'}),{}}function zg({prompt:h,previousInteractionId:f}){let g=[],y=new Set;for(let _ of h){if(_.role==="assistant"){if(_.content.some((w)=>w.providerOptions?.google?.interactionId===f)){for(let w of _.content)if(w.type==="tool-call")y.add(w.toolCallId);continue}g.push(_);continue}if(_.role==="tool"){let w=_.content.filter((A)=>{if(A.type!=="tool-result")return!0;return!y.has(A.toolCallId)});if(w.length===0)continue;g.push({..._,content:w});continue}g.push(_)}return g}function Xg(h){try{let f=Qe(h);if(f!=null&&typeof f==="object"&&!Array.isArray(f))return f;return{value:f}}catch{return{value:h}}}function Qg({toolCallId:h,toolName:f,output:g,signature:y,warnings:_}){let w={type:"function_result",call_id:h,name:f,...y!=null?{signature:y}:{}};switch(g.type){case"text":return{...w,result:g.value};case"json":return{...w,result:JSON.stringify(g.value)};case"error-text":return{...w,is_error:!0,result:g.value};case"error-json":return{...w,is_error:!0,result:JSON.stringify(g.value)};case"execution-denied":return{...w,is_error:!0,result:g.reason??"Tool execution denied by user."};case"content":{let A=[];for(let S of g.value)if(S.type==="text")A.push({type:"text",text:S.text});else if(S.type==="file"){if(fe(S.mediaType)!=="image"){_.push({type:"other",message:`google.interactions: tool-result file with mediaType "${S.mediaType}" is not supported (Interactions \`function_result.result\` accepts only text and image content); part dropped.`});continue}let k=Zg({part:S,warnings:_});if(k!=null)A.push(k)}else _.push({type:"other",message:`google.interactions: tool-result content part type "${S.type}" is not supported; part dropped.`});return{...w,result:A}}}}function Zg({part:h,warnings:f}){switch(h.data.type){case"data":{let g=Ae(h.mediaType)?h.mediaType:ee({part:{type:"file",mediaType:h.mediaType,data:h.data}});return{type:"image",data:j(h.data.data),mime_type:g}}case"url":return{type:"image",uri:h.data.url.toString(),...Ae(h.mediaType)?{mime_type:h.mediaType}:{}};case"reference":return{type:"image",uri:qe({reference:h.data.reference,provider:"google"}),...Ae(h.mediaType)?{mime_type:h.mediaType}:{}};case"text":f.push({type:"other",message:'google.interactions: tool-result image part with `data.type === "text"` is not representable as an image; part dropped.'});return}}function em(h){if(h.length<2)return h;let f=[];for(let g of h){let y=f[f.length-1];if(g.type==="text"&&y!=null&&y.type==="text"&&y.annotations==null&&g.annotations==null){let _={type:"text",text:`${y.text}
36
+
37
+ ${g.text}`};f[f.length-1]=_;continue}f.push(g)}return f}var er=()=>t({modality:e().nullish(),tokens:n().nullish()}).loose(),Ml=()=>t({total_input_tokens:n().nullish(),total_output_tokens:n().nullish(),total_thought_tokens:n().nullish(),total_cached_tokens:n().nullish(),total_tool_use_tokens:n().nullish(),total_tokens:n().nullish(),input_tokens_by_modality:o(er()).nullish(),output_tokens_by_modality:o(er()).nullish(),cached_tokens_by_modality:o(er()).nullish(),tool_use_tokens_by_modality:o(er()).nullish(),grounding_tool_count:o(t({type:e().nullish(),count:n().nullish()}).loose()).nullish()}).loose(),Dl=()=>s(["in_progress","requires_action","completed","failed","cancelled","incomplete"]),Ll=()=>{let h=t({type:a("url_citation"),url:e().nullish(),title:e().nullish(),start_index:n().nullish(),end_index:n().nullish()}).loose(),f=t({type:a("file_citation"),file_name:e().nullish(),document_uri:e().nullish(),url:e().nullish(),page_number:n().nullish(),media_id:e().nullish(),start_index:n().nullish(),end_index:n().nullish(),custom_metadata:d(e(),m()).nullish()}).loose(),g=t({type:a("place_citation"),name:e().nullish(),url:e().nullish(),place_id:e().nullish(),start_index:n().nullish(),end_index:n().nullish()}).loose();return p([h,f,g,t({type:e()}).loose()])},ql=()=>t({type:e(),text:e().nullish(),data:e().nullish(),mime_type:e().nullish()}).loose(),_l=()=>{let h=t({type:a("text"),text:e(),annotations:o(Ll()).nullish()}).loose(),f=t({type:a("image"),data:e().nullish(),mime_type:e().nullish(),resolution:s(["low","medium","high","ultra_high"]).nullish(),uri:e().nullish()}).loose(),g=t({type:a("video"),data:e().nullish(),mime_type:e().nullish(),uri:e().nullish()}).loose();return p([h,f,g,t({type:e()}).loose()])},Fl=["google_search_call","code_execution_call","url_context_call","file_search_call","google_maps_call","mcp_server_tool_call"],Gl=["google_search_result","code_execution_result","url_context_result","file_search_result","google_maps_result","mcp_server_tool_result"],$l=()=>{let h=t({type:a("user_input"),content:o(_l()).nullish()}).loose(),f=t({type:a("model_output"),content:o(_l()).nullish()}).loose(),g=t({type:a("function_call"),id:e(),name:e(),arguments:d(e(),m()).nullish(),signature:e().nullish()}).loose(),y=t({type:a("thought"),signature:e().nullish(),summary:o(ql()).nullish()}).loose(),_=t({type:a("processing_call"),id:e(),signature:e().nullish()}).loose(),w=t({type:a("processing_result"),call_id:e(),signature:e().nullish()}).loose(),A=t({type:s(Fl),id:e(),arguments:d(e(),m()).nullish(),name:e().nullish(),server_name:e().nullish(),search_type:e().nullish(),signature:e().nullish()}).loose(),S=t({type:s(Gl),call_id:e(),result:m().nullish(),is_error:r().nullish(),name:e().nullish(),server_name:e().nullish(),signature:e().nullish()}).loose();return p([h,f,g,y,_,w,A,S,t({type:e()}).loose()])},Ns=u(()=>l(t({id:e().nullish(),created:e().nullish(),updated:e().nullish(),status:Dl(),model:e().nullish(),agent:e().nullish(),steps:o($l()).nullish(),usage:Ml().nullish(),service_tier:e().nullish(),previous_interaction_id:e().nullish(),response_modalities:o(e()).nullish()}).loose())),Hl=u(()=>l((()=>{let h=Dl(),f=Ll(),g=ql(),y=t({event_type:a("interaction.created"),event_id:e().nullish(),interaction:t({id:e().nullish(),created:e().nullish(),model:e().nullish(),agent:e().nullish(),status:h.nullish()}).loose()}).loose(),_=t({event_type:a("step.start"),event_id:e().nullish(),index:n(),step:$l()}).loose(),w=t({type:a("text"),text:e()}).loose(),A=t({type:a("thought_summary"),content:g.nullish()}).loose(),S=t({type:a("thought_signature"),signature:e().nullish()}).loose(),k=t({type:a("arguments_delta"),arguments:e().nullish(),id:e().nullish(),signature:e().nullish()}).loose(),V=t({type:s(["text_annotation_delta","text_annotation"]),annotations:o(f).nullish()}).loose(),P=t({type:a("image"),data:e().nullish(),mime_type:e().nullish(),resolution:s(["low","medium","high","ultra_high"]).nullish(),uri:e().nullish()}).loose(),ne=t({type:a("video"),data:e().nullish(),mime_type:e().nullish(),uri:e().nullish()}).loose(),Z=t({type:s(Fl),id:e().nullish(),arguments:d(e(),m()).nullish(),name:e().nullish(),server_name:e().nullish(),search_type:e().nullish(),signature:e().nullish()}).loose(),K=t({type:s(Gl),call_id:e().nullish(),result:m().nullish(),is_error:r().nullish(),name:e().nullish(),server_name:e().nullish(),signature:e().nullish()}).loose(),X=t({type:e()}).loose(),re=p([w,P,ne,A,S,k,V,Z,K,X]),de=t({event_type:a("step.delta"),event_id:e().nullish(),index:n(),delta:re}).loose(),L=t({event_type:a("step.stop"),event_id:e().nullish(),index:n()}).loose(),B=t({event_type:a("interaction.status_update"),event_id:e().nullish(),interaction_id:e().nullish(),status:h.nullish()}).loose(),he=t({event_type:a("interaction.in_progress"),event_id:e().nullish(),interaction_id:e().nullish(),status:h.nullish()}).loose(),q=t({event_type:a("interaction.requires_action"),event_id:e().nullish(),interaction_id:e().nullish(),status:h.nullish()}).loose(),U=t({event_type:a("interaction.completed"),event_id:e().nullish(),interaction:t({id:e().nullish(),status:h.nullish(),usage:Ml().nullish(),service_tier:e().nullish()}).loose()}).loose(),ue=t({event_type:a("error"),event_id:e().nullish(),error:t({code:e().nullish(),message:e().nullish()}).loose().nullish()}).loose(),ye=t({event_type:e()}).loose();return p([y,_,de,L,B,he,q,U,ue,ye])})())),tm=u(()=>l(t({previousInteractionId:e().nullish(),store:r().nullish(),agent:e().nullish(),agentConfig:p([t({type:a("dynamic")}).loose(),t({type:a("deep-research"),thinkingSummaries:s(["auto","none"]).nullish(),visualization:s(["off","auto"]).nullish(),collaborativePlanning:r().nullish()})]).nullish(),thinkingLevel:s(["minimal","low","medium","high"]).nullish(),thinkingSummaries:s(["auto","none"]).nullish(),responseFormat:o(p([t({type:a("text"),mimeType:e().nullish(),schema:m().nullish()}).loose(),t({type:a("image"),mimeType:e().nullish(),aspectRatio:s(["1:1","2:3","3:2","3:4","4:3","4:5","5:4","9:16","16:9","21:9","1:8","8:1","1:4","4:1"]).nullish(),imageSize:s(["1K","2K","4K","512"]).nullish()}).loose(),t({type:a("audio"),mimeType:e().nullish()}).loose(),t({type:a("video"),aspectRatio:s(["16:9","9:16"]).nullish(),resolution:s(["360p","720p","1080p","4k"]).nullish(),duration:e().nullish(),delivery:s(["inline","uri"]).nullish(),gcsUri:e().nullish()}).loose()])).nullish(),imageConfig:t({aspectRatio:s(["1:1","2:3","3:2","3:4","4:3","4:5","5:4","9:16","16:9","21:9","1:8","8:1","1:4","4:1"]).nullish(),imageSize:s(["1K","2K","4K","512"]).nullish()}).nullish(),mediaResolution:s(["low","medium","high","ultra_high"]).nullish(),responseModalities:o(s(["text","image","audio","video","document"])).nullish(),serviceTier:s(["flex","standard","priority"]).nullish(),systemInstruction:e().nullish(),signature:e().nullish(),interactionId:e().nullish(),pollingTimeoutMs:n().int().positive().nullish(),background:r().nullish(),environment:p([e(),t({type:a("remote"),sources:o(p([t({type:a("gcs"),source:e(),target:e().nullish()}),t({type:a("repository"),source:e(),target:e().nullish()}),t({type:a("inline"),content:e(),target:e()})])).nullish(),network:p([a("disabled"),t({allowlist:o(t({domain:e(),transform:o(d(e(),e())).nullish()}))})]).nullish()})]).nullish()})));function Ft({signature:h,interactionId:f,processingId:g,processingCallId:y}){let _={};if(h!=null)_.signature=h;if(f!=null)_.interactionId=f;if(g!=null)_.processingId=g;if(y!=null)_.processingCallId=y;return Object.keys(_).length>0?{providerMetadata:{google:_}}:{}}var nm=new Set(["google_search_call","code_execution_call","url_context_call","file_search_call","google_maps_call","mcp_server_tool_call"]),rm=new Set(["google_search_result","code_execution_result","url_context_result","file_search_result","google_maps_result","mcp_server_tool_result"]);function sm(h){return h.replace(/_call$/,"")}function im(h){return h.replace(/_result$/,"")}function Bl({steps:h,generateId:f,interactionId:g}){let y=[],_=!1;if(h==null)return{content:y,hasFunctionCall:_};for(let w of h){if(w==null||typeof w!=="object")continue;let A=w.type;if(typeof A!=="string")continue;switch(A){case"user_input":break;case"model_output":{let S=w.content??[];for(let k of S){if(k==null||typeof k!=="object")continue;let V=k.type;if(V==="text"){let P=k.text??"",ne=k.annotations;y.push({type:"text",text:P,...Ft({interactionId:g})});let Z=Is({annotations:ne,generateId:f});for(let K of Z)y.push(K)}else if(V==="image"){let P=k;if(P.data!=null&&P.data.length>0)y.push({type:"file",mediaType:P.mime_type??"image/png",data:{type:"data",data:P.data},...Ft({interactionId:g})});else if(P.uri!=null&&P.uri.length>0)y.push({type:"file",mediaType:P.mime_type??"image/png",data:{type:"url",url:new URL(P.uri)},...Ft({interactionId:g})})}else if(V==="video"){let P=k;if(P.data!=null&&P.data.length>0)y.push({type:"file",mediaType:P.mime_type??"video/mp4",data:{type:"data",data:P.data},...Ft({interactionId:g})});else if(P.uri!=null&&P.uri.length>0)y.push({type:"file",mediaType:P.mime_type??"video/mp4",data:{type:"url",url:new URL(P.uri)},...Ft({interactionId:g})})}}break}case"thought":{let S=w,k=(Array.isArray(S.summary)?S.summary:[]).filter((V)=>V?.type==="text"&&typeof V.text==="string").map((V)=>V.text).join(`
38
+ `);y.push({type:"reasoning",text:k,...Ft({signature:S.signature,interactionId:g})});break}case"processing_call":{let S=w,k=S.id||f();y.push({type:"custom",kind:"google.processing_call",...Ft({signature:S.signature,interactionId:g,processingId:k})});break}case"processing_result":{let S=w,k=S.call_id||f();y.push({type:"custom",kind:"google.processing_result",...Ft({signature:S.signature,interactionId:g,processingCallId:k})});break}case"function_call":{_=!0;let S=w;y.push({type:"tool-call",toolCallId:S.id,toolName:S.name,input:JSON.stringify(S.arguments??{}),...Ft({signature:S.signature,interactionId:g})});break}default:if(nm.has(A)){let S=w,k=A==="mcp_server_tool_call"?S.name??"mcp_server_tool":sm(A),V=JSON.stringify(S.arguments??{});y.push({type:"tool-call",toolCallId:S.id||f(),toolName:k,input:V,providerExecuted:!0})}else if(rm.has(A)){let S=w,k=A==="mcp_server_tool_result"?S.name??"mcp_server_tool":im(A);y.push({type:"tool-result",toolCallId:S.call_id||f(),toolName:k,result:S.result??null});let V=Ul({block:w,generateId:f});for(let P of V)y.push(P)}}}return{content:y,hasFunctionCall:_}}var om=()=>globalThis.fetch;async function Vl({baseURL:h,interactionId:f,headers:g,fetch:y=om()}){if(f==null||f.length===0)return;let _=`${h}/interactions/${encodeURIComponent(f)}/cancel`;try{let w=await y(_,{method:"POST",headers:Ee(I({"Content-Type":"application/json"},g),Pi()),body:"{}"});try{await w.text()}catch{}}catch{}}var am=new Set(["completed","failed","cancelled","incomplete"]);function Ps(h){return h!=null&&am.has(h)}var cm=1000,lm=1e4,um=1800000;async function dm({baseURL:h,interactionId:f,headers:g,fetch:y,abortSignal:_,initialDelayMs:w=cm,maxDelayMs:A=lm,timeoutMs:S=um}){if(f==null||f.length===0)throw Error("google.interactions: cannot poll a background interaction without an id. The POST response did not include an interaction id.");let k=Date.now(),V=w,P=`${h}/interactions/${encodeURIComponent(f)}`,ne=()=>Vl({baseURL:h,interactionId:f,headers:g,fetch:y});try{while(!0){if(_?.aborted)throw await ne(),new DOMException("Polling was aborted","AbortError");if(Date.now()-k>S)throw Error(`google.interactions: timed out polling interaction ${f} after ${S}ms.`);await Ci(V,{abortSignal:_});let{value:Z,rawValue:K,responseHeaders:X}=await Ce({url:P,validateUrl:!1,headers:g,failedResponseHandler:zt,successfulResponseHandler:E(Ns),abortSignal:_,fetch:y});if(Ps(Z.status))return{response:Z,rawResponse:K,responseHeaders:X};V=Math.min(V*2,A)}}catch(Z){if(We(Z))await ne();throw Z}}function hm({tools:h,toolChoice:f}){let g=[],y=h?.length?h:void 0;if(y==null)return{tools:void 0,toolChoice:void 0,toolWarnings:g};let _=[];for(let S of y){if(S.type==="function"){_.push({type:"function",name:S.name,description:S.description??"",parameters:S.inputSchema});continue}if(S.type==="provider"){let k=S.args??{};switch(S.id){case"google.google_search":{let V=k.searchTypes,P;if(V!=null&&typeof V==="object"){let ne=[];if(V.webSearch!=null)ne.push("web_search");if(V.imageSearch!=null)ne.push("image_search");if(ne.length>0)P=ne}_.push({type:"google_search",...P!=null?{search_types:P}:{}});break}case"google.code_execution":_.push({type:"code_execution"});break;case"google.url_context":_.push({type:"url_context"});break;case"google.file_search":_.push({type:"file_search",...k.fileSearchStoreNames!=null?{file_search_store_names:k.fileSearchStoreNames}:{},...k.topK!=null?{top_k:k.topK}:{},...k.metadataFilter!=null?{metadata_filter:k.metadataFilter}:{}});break;case"google.google_maps":_.push({type:"google_maps",...k.latitude!=null?{latitude:k.latitude}:{},...k.longitude!=null?{longitude:k.longitude}:{},...k.enableWidget!=null?{enable_widget:k.enableWidget}:{}});break;case"google.computer_use":_.push({type:"computer_use",environment:k.environment??"browser",...k.excludedPredefinedFunctions!=null?{excludedPredefinedFunctions:k.excludedPredefinedFunctions}:{}});break;case"google.mcp_server":_.push({type:"mcp_server",...k.name!=null?{name:k.name}:{},...k.url!=null?{url:k.url}:{},...k.headers!=null?{headers:k.headers}:{},...k.allowedTools!=null?{allowed_tools:k.allowedTools}:{}});break;case"google.retrieval":{let V=k.vertexAiSearchConfig??void 0;_.push({type:"retrieval",...k.retrievalTypes!=null?{retrieval_types:k.retrievalTypes}:{retrieval_types:["vertex_ai_search"]},...V!=null?{vertex_ai_search_config:V}:{}});break}default:g.push({type:"unsupported",feature:`provider-defined tool ${S.id}`,details:`provider-defined tool ${S.id} is not supported by google.interactions; tool dropped.`})}continue}g.push({type:"unsupported",feature:`tool of type ${S.type}`,details:"Only function tools and google.* provider-defined tools are supported by google.interactions; tool dropped."})}let w=_.some((S)=>S.type==="function"),A;if(f!=null&&w)switch(f.type){case"auto":A="auto";break;case"required":A="any";break;case"none":A="none";break;case"tool":A={allowed_tools:{mode:"validated",tools:[f.toolName]}}}return{tools:_.length>0?_:void 0,toolChoice:A,toolWarnings:g}}var pm=3,fm=500;function gm({baseURL:h,interactionId:f,headers:g,fetch:y,abortSignal:_,maxRetries:w=pm,retryDelayMs:A=fm}){if(f.length===0)throw Error("google.interactions: cannot stream a background interaction without an id.");let S={...g,accept:"text/event-stream"},k,V=!1,P=0,ne=!1,Z,K=new AbortController,X=()=>K.abort();if(_!=null)if(_.aborted)K.abort();else _.addEventListener("abort",X,{once:!0});let re=K.signal;function de(){let B=`${h}/interactions/${encodeURIComponent(f)}`,he=new URLSearchParams({stream:"true"});if(k!=null)he.set("last_event_id",k);return`${B}?${he.toString()}`}async function L(){let{value:B}=await Ce({url:de(),validateUrl:!1,headers:S,failedResponseHandler:zt,successfulResponseHandler:ze(Hl),abortSignal:re,fetch:y});return B.getReader()}return new ReadableStream({async start(B){try{while(!V&&!re.aborted){if(Z==null)try{Z=await L(),ne=!1}catch(he){if(We(he)||re.aborted){B.error(he);return}if(P++,P>=w){B.error(he);return}await Ci(A*P,{abortSignal:re});continue}try{let{done:he,value:q}=await Z.read();if(he){if(Z=void 0,V)break;if(!ne){if(P++,P>=w){B.error(Error("google.interactions: SSE stream closed without producing any events."));return}await Ci(A*P,{abortSignal:re})}else P=0;continue}if(ne=!0,q.success){let U=q.value;if(typeof U.event_id==="string"&&U.event_id.length>0)k=U.event_id;if(U.event_type==="interaction.completed"||U.event_type==="error")V=!0}B.enqueue(q)}catch(he){if(We(he)||re.aborted){B.error(he);return}if(Z=void 0,P++,P>=w){B.error(he);return}await Ci(A*P,{abortSignal:re})}}B.close()}catch(he){B.error(he)}finally{if(_!=null)_.removeEventListener("abort",X);if(Z?.cancel().catch(()=>{}),Z=void 0,re.aborted&&!V)await Vl({baseURL:h,interactionId:f,headers:g,fetch:y})}},cancel(){K.abort(),Z?.cancel().catch(()=>{}),Z=void 0}})}function mm({response:h,warnings:f,generateId:g,includeRawChunks:y,headerServiceTier:_}){return new ReadableStream({start(w){w.enqueue({type:"stream-start",warnings:f});let A=typeof h.id==="string"&&h.id.length>0?h.id:void 0,S,k=h.created;if(typeof k==="string"){let de=new Date(k);if(!Number.isNaN(de.getTime()))S=de}if(w.enqueue({type:"response-metadata",...A!=null?{id:A}:{},modelId:h.model??void 0,...S?{timestamp:S}:{}}),y)w.enqueue({type:"raw",rawValue:h});let{content:V,hasFunctionCall:P}=Bl({steps:h.steps??null,generateId:g,interactionId:A}),ne=0,Z=()=>`${A??"agent"}:${ne++}`;for(let de of V)switch(de.type){case"text":{let L=Z(),B=de.providerMetadata;if(w.enqueue({type:"text-start",id:L}),de.text.length>0)w.enqueue({type:"text-delta",id:L,delta:de.text});w.enqueue({type:"text-end",id:L,...B?{providerMetadata:B}:{}});break}case"reasoning":{let L=Z(),B=de.providerMetadata;if(w.enqueue({type:"reasoning-start",id:L}),de.text.length>0)w.enqueue({type:"reasoning-delta",id:L,delta:de.text});w.enqueue({type:"reasoning-end",id:L,...B?{providerMetadata:B}:{}});break}case"tool-call":{let L=de.providerMetadata;w.enqueue({type:"tool-input-start",id:de.toolCallId,toolName:de.toolName,...de.providerExecuted?{providerExecuted:de.providerExecuted}:{}}),w.enqueue({type:"tool-input-delta",id:de.toolCallId,delta:de.input}),w.enqueue({type:"tool-input-end",id:de.toolCallId}),w.enqueue({type:"tool-call",toolCallId:de.toolCallId,toolName:de.toolName,input:de.input,...de.providerExecuted?{providerExecuted:de.providerExecuted}:{},...L?{providerMetadata:L}:{}});break}case"tool-result":w.enqueue({type:"tool-result",toolCallId:de.toolCallId,toolName:de.toolName,result:de.result});break;case"source":case"file":w.enqueue(de)}let K=h.service_tier??_,X={unified:Ms({status:h.status,hasFunctionCall:P}),raw:h.status},re={google:{...A!=null?{interactionId:A}:{},...K!=null?{serviceTier:K}:{}}};w.enqueue({type:"finish",finishReason:X,usage:Us(h.usage),providerMetadata:re}),w.close()}})}var Wl=class h{static[H](f){return{...te({modelId:f.modelId,config:f.config}),agent:f.agent}}static[Q](f){return new h(f.agent!=null?{agent:f.agent}:f.modelId,f.config)}constructor(f,g){if(this.specificationVersion="v4",typeof f==="string")this.modelId=f,this.agent=void 0;else if("managedAgent"in f)this.modelId=f.managedAgent,this.agent=f.managedAgent;else this.modelId=f.agent,this.agent=f.agent;this.config=g}get provider(){return this.config.provider}get supportedUrls(){if(this.config.supportedUrls)return this.config.supportedUrls();return{"image/*":[/^https?:\/\/.+/],"application/pdf":[/^https?:\/\/.+/],"audio/*":[/^https?:\/\/.+/],"video/*":[/^https?:\/\/(www\.)?youtube\.com\/watch\?v=.+/,/^https?:\/\/youtu\.be\/.+/,/^gs:\/\/.+/]}}async getArgs(f){let g=[],y=await T({provider:"google",providerOptions:f.providerOptions,schema:tm}),_=this.agent!=null;if(!_){if(f.frequencyPenalty!=null)g.push({type:"unsupported",feature:"frequencyPenalty"});if(f.presencePenalty!=null)g.push({type:"unsupported",feature:"presencePenalty"})}let w=f.tools!=null&&f.tools.length>0,A,S;if(w){let L=hm({tools:f.tools,toolChoice:f.toolChoice});A=L.tools,S=L.toolChoice,g.push(...L.toolWarnings)}let k=[];if(f.responseFormat?.type==="json")if(_)g.push({type:"other",message:"google.interactions: structured output (responseFormat) is not supported when an agent is set; responseFormat will be ignored."});else{let L={type:"text",mime_type:"application/json",...f.responseFormat.schema!=null?{schema:f.responseFormat.schema}:{}};k.push(L)}if(y?.responseFormat!=null){for(let L of y.responseFormat)if(L.type==="text")k.push(Pt({type:"text",mime_type:L.mimeType??void 0,schema:L.schema??void 0}));else if(L.type==="image")k.push(Pt({type:"image",mime_type:L.mimeType??void 0,aspect_ratio:L.aspectRatio??void 0,image_size:L.imageSize??void 0}));else if(L.type==="audio")k.push(Pt({type:"audio",mime_type:L.mimeType??void 0}));else if(L.type==="video")k.push(Pt({type:"video",aspect_ratio:L.aspectRatio??void 0,resolution:L.resolution??void 0,duration:L.duration??void 0,delivery:L.delivery??void 0,gcs_uri:L.gcsUri??void 0}))}let{input:V,systemInstruction:P,warnings:ne}=Kg({prompt:f.prompt,previousInteractionId:y?.previousInteractionId??void 0,store:y?.store??void 0,mediaResolution:y?.mediaResolution??void 0});g.push(...ne);let Z=P,K=y?.systemInstruction??void 0;if(Z!=null&&K!=null)g.push({type:"other",message:"google.interactions: both AI SDK system message and providerOptions.google.systemInstruction were set; using the AI SDK system message."});else if(Z==null&&K!=null)Z=K;let X;if(_){let L=[];if(f.temperature!=null)L.push("temperature");if(f.topP!=null)L.push("topP");if(f.topK!=null)L.push("topK");if(f.frequencyPenalty!=null)L.push("frequencyPenalty");if(f.presencePenalty!=null)L.push("presencePenalty");if(f.seed!=null)L.push("seed");if(f.stopSequences!=null&&f.stopSequences.length>0)L.push("stopSequences");if(f.maxOutputTokens!=null)L.push("maxOutputTokens");if(y?.thinkingLevel!=null)L.push("thinkingLevel");if(y?.thinkingSummaries!=null)L.push("thinkingSummaries");if(y?.imageConfig!=null)L.push("imageConfig");if(L.length>0)g.push({type:"other",message:`google.interactions: ${L.join(", ")} ${L.length===1?"is":"are"} not supported when an agent is set; use providerOptions.google.agentConfig instead. Dropped from the request body.`});X=void 0}else if(X=Pt({temperature:f.temperature??void 0,top_p:f.topP??void 0,top_k:f.topK??void 0,seed:f.seed??void 0,stop_sequences:f.stopSequences!=null&&f.stopSequences.length>0?f.stopSequences:void 0,max_output_tokens:f.maxOutputTokens??void 0,thinking_level:y?.thinkingLevel??void 0,thinking_summaries:y?.thinkingSummaries??void 0,tool_choice:S}),y?.imageConfig!=null){let L=k.some((B)=>B.type==="image");if(g.push({type:"other",message:L?"google.interactions: providerOptions.google.imageConfig is deprecated and was ignored because providerOptions.google.responseFormat already supplies an image entry. Use responseFormat exclusively.":'google.interactions: providerOptions.google.imageConfig is deprecated. Use providerOptions.google.responseFormat with a { type: "image", ... } entry instead.'}),!L)k.push({type:"image",mime_type:"image/png",...y.imageConfig.aspectRatio!=null?{aspect_ratio:y.imageConfig.aspectRatio}:{},...y.imageConfig.imageSize!=null?{image_size:y.imageConfig.imageSize}:{}})}let re;if(_&&y?.agentConfig!=null){let L=y.agentConfig;if(L.type==="deep-research")re=Pt({type:"deep-research",thinking_summaries:L.thinkingSummaries??void 0,visualization:L.visualization??void 0,collaborative_planning:L.collaborativePlanning??void 0});else if(L.type==="dynamic")re={type:"dynamic"}}let de;if(y?.environment!=null)if(!_)g.push({type:"other",message:"google.interactions: environment is only supported when an agent is set; environment will be omitted from the request body."});else if(typeof y.environment==="string")de=y.environment;else{let L=y.environment,B=L.sources?.map((q)=>{if(q.type==="inline")return{type:"inline",content:q.content,target:q.target};return Pt({type:q.type,source:q.source,target:q.target??void 0})}),he;if(L.network==="disabled")he="disabled";else if(L.network!=null)he={allowlist:L.network.allowlist.map((q)=>Pt({domain:q.domain,transform:q.transform??void 0}))};de=Pt({type:"remote",sources:B!=null&&B.length>0?B:void 0,network:he})}return{args:Pt({..._?{agent:this.agent}:{model:this.modelId},input:V,system_instruction:Z,tools:A,response_format:k.length>0?k:void 0,response_modalities:y?.responseModalities!=null?y.responseModalities:void 0,previous_interaction_id:y?.previousInteractionId??void 0,service_tier:y?.serviceTier??void 0,store:y?.store??void 0,generation_config:X!=null&&Object.keys(X).length>0?X:void 0,agent_config:re,environment:de,background:y?.background??void 0}),warnings:g,isAgent:_,isBackground:y?.background===!0,pollingTimeoutMs:y?.pollingTimeoutMs??void 0}}async doGenerate(f){let{args:g,warnings:y,isAgent:_,isBackground:w,pollingTimeoutMs:A}=await this.getArgs(f),S=`${this.config.baseURL}/interactions`,k=I(this.config.headers?await M(this.config.headers):void 0,f.headers),{responseHeaders:V,value:P,rawValue:ne}=await O({url:S,headers:k,body:g,failedResponseHandler:zt,successfulResponseHandler:E(Ns),abortSignal:f.abortSignal,fetch:this.config.fetch});if((_||w)&&!Ps(P.status)){let q=await dm({baseURL:this.config.baseURL,interactionId:P.id,headers:k,fetch:this.config.fetch,abortSignal:f.abortSignal,timeoutMs:A});P=q.response,ne=q.rawResponse,V=q.responseHeaders??V}let Z=typeof P.id==="string"&&P.id.length>0?P.id:void 0,{content:K,hasFunctionCall:X}=Bl({steps:P.steps??null,generateId:this.config.generateId??C,interactionId:Z}),re={unified:Ms({status:P.status,hasFunctionCall:X}),raw:P.status},de=P.service_tier??V?.["x-gemini-service-tier"]??void 0,L=Nl(P.usage),B={google:{...Z!=null?{interactionId:Z}:{},...de!=null?{serviceTier:de}:{},...L!=null?{outputTokensByModality:L}:{}}},he;if(typeof P.created==="string"){let q=new Date(P.created);if(!Number.isNaN(q.getTime()))he=q}return{content:K,finishReason:re,usage:Us(P.usage),warnings:y,providerMetadata:B,request:{body:g},response:{headers:V,body:ne,...Z!=null?{id:Z}:{},...he?{timestamp:he}:{},modelId:P.model??void 0}}}async doStream(f){let{args:g,warnings:y,isBackground:_,pollingTimeoutMs:w}=await this.getArgs(f),A=`${this.config.baseURL}/interactions`,S=I(this.config.headers?await M(this.config.headers):void 0,f.headers);if(_)return this.doStreamBackground({args:g,warnings:y,url:A,mergedHeaders:S,options:f,pollingTimeoutMs:w});let k={...g,stream:!0},{responseHeaders:V,value:P}=await O({url:A,headers:S,body:k,failedResponseHandler:zt,successfulResponseHandler:ze(Hl),abortSignal:f.abortSignal,fetch:this.config.fetch}),ne=V?.["x-gemini-service-tier"],Z=ml({warnings:y,generateId:this.config.generateId??C,includeRawChunks:f.includeRawChunks,serviceTier:ne});return{stream:P.pipeThrough(Z),request:{body:k},response:{headers:V}}}async doStreamBackground({args:f,warnings:g,url:y,mergedHeaders:_,options:w,pollingTimeoutMs:A}){let{responseHeaders:S,value:k}=await O({url:y,headers:_,body:f,failedResponseHandler:zt,successfulResponseHandler:E(Ns),abortSignal:w.abortSignal,fetch:this.config.fetch}),V=k.id;if(V==null||V.length===0)throw Error("google.interactions: background POST response did not include an interaction id; cannot stream the result.");let P=S?.["x-gemini-service-tier"];if(Ps(k.status))return{stream:mm({response:k,warnings:g,generateId:this.config.generateId??C,includeRawChunks:w.includeRawChunks,headerServiceTier:P}),request:{body:f},response:{headers:S}};let ne=gm({baseURL:this.config.baseURL,interactionId:V,headers:_,fetch:this.config.fetch,abortSignal:w.abortSignal}),Z=ml({warnings:g,generateId:this.config.generateId??C,includeRawChunks:w.includeRawChunks,serviceTier:P});return{stream:ne.pipeThrough(Z),request:{body:f},response:{headers:S}}}};function Pt(h){let f={};for(let[g,y]of Object.entries(h)){if(y===void 0)continue;f[g]=y}return f}function ym(h){let f=new tu.GoogleAuth({scopes:["https://www.googleapis.com/auth/cloud-platform"],...h});return async function(){return(await(await f.getClient()).getAccessToken())?.token??null}}var _m="5.0.127",Tm=u(()=>l(t({error:t({code:n().nullable(),message:e(),status:e()})}))),Zt=oe({errorSchema:Tm,errorToMessage:(h)=>h.error.message}),Ds=u(()=>l(t({outputDimensionality:n().optional(),taskType:s(["SEMANTIC_SIMILARITY","CLASSIFICATION","CLUSTERING","RETRIEVAL_DOCUMENT","RETRIEVAL_QUERY","QUESTION_ANSWERING","FACT_VERIFICATION","CODE_RETRIEVAL_QUERY"]).optional(),title:e().optional(),autoTruncate:r().optional()}))),wm=class h{static[H](f){return te({modelId:f.modelId,config:f.config})}static[Q](f){return new h(f.modelId,f.config)}get provider(){return this.config.provider}get maxEmbeddingsPerCall(){return Jl(this.modelId)?1:250}constructor(f,g){this.specificationVersion="v4",this.supportsParallelCalls=!0,this.modelId=f,this.config=g}async doEmbed({values:f,dimensions:g,headers:y,abortSignal:_,providerOptions:w}){let A=await T({provider:"googleVertex",providerOptions:w,schema:Ds});if(A==null)A=await T({provider:"vertex",providerOptions:w,schema:Ds});if(A==null)A=await T({provider:"google",providerOptions:w,schema:Ds});if(A=A??{},f.length>this.maxEmbeddingsPerCall)throw new pt({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:f});let S=I(this.config.headers?await M(this.config.headers):void 0,y);if(Jl(this.modelId)){let{responseHeaders:Z,value:K,rawValue:X}=await O({url:`${this.config.baseURL}/models/${this.modelId}:embedContent`,headers:S,body:{content:{parts:[{text:f[0]}]},embedContentConfig:{outputDimensionality:A.outputDimensionality??g,taskType:A.taskType,title:A.title,autoTruncate:A.autoTruncate}},failedResponseHandler:Zt,successfulResponseHandler:E(Em),abortSignal:_,fetch:this.config.fetch});return{warnings:[],embeddings:[K.embedding.values],usage:K.usageMetadata?.promptTokenCount==null?void 0:{tokens:K.usageMetadata.promptTokenCount},response:{headers:Z,body:X}}}let k=`${this.config.baseURL}/models/${this.modelId}:predict`,{responseHeaders:V,value:P,rawValue:ne}=await O({url:k,headers:S,body:{instances:f.map((Z)=>({content:Z,task_type:A.taskType,title:A.title})),parameters:{outputDimensionality:A.outputDimensionality??g,autoTruncate:A.autoTruncate}},failedResponseHandler:Zt,successfulResponseHandler:E(vm),abortSignal:_,fetch:this.config.fetch});return{warnings:[],embeddings:P.predictions.map((Z)=>Z.embeddings.values),usage:{tokens:P.predictions.reduce((Z,K)=>Z+K.embeddings.statistics.token_count,0)},response:{headers:V,body:ne}}}},vm=u(()=>l(t({predictions:o(t({embeddings:t({values:o(n()),statistics:t({token_count:n()})})}))}))),Em=u(()=>l(t({embedding:t({values:o(n())}),usageMetadata:t({promptTokenCount:n().nullish()}).nullish()})));function Jl(h){return h==="gemini-embedding-2"||h==="gemini-embedding-2-preview"}var Cm=new Set(["gemini-2.5-flash-image","gemini-3-pro-image-preview","gemini-3.1-flash-image-preview","gemini-nano-banana-2.1"]),bm=class h{static[H](f){return te({modelId:f.modelId,config:f.config})}static[Q](f){return new h(f.modelId,f.config)}get supportsFileInputs(){return Cm.has(this.modelId)?!0:void 0}get supportsMaskInputs(){return this.supportsFileInputs===!0?!1:void 0}get provider(){return this.config.provider}constructor(f,g){this.modelId=f,this.config=g,this.specificationVersion="v4",this.maxImagesPerCall=1}async doGenerate(f){if(!this.modelId.startsWith("gemini-"))throw Error("Google image models other than Gemini are no longer supported. Use a model ID that starts with `gemini-`.");let{prompt:g,size:y,aspectRatio:_,seed:w,providerOptions:A,headers:S,abortSignal:k,files:V,mask:P}=f,ne=[];if(P!=null)throw Error("Gemini image models do not support mask-based image editing.");if(y!=null)ne.push({type:"unsupported",feature:"size",details:"This model does not support the `size` option. Use `aspectRatio` instead."});let Z=[];if(g!=null)Z.push({type:"text",text:g});if(V!=null&&V.length>0)for(let ye of V)if(ye.type==="url")Z.push({type:"file",data:{type:"url",url:new URL(ye.url)},mediaType:"image/*"});else Z.push({type:"file",data:{type:"data",data:typeof ye.data==="string"?ye.data:new Uint8Array(ye.data)},mediaType:ye.mediaType});let K=[{role:"user",content:Z}],X=new js(this.modelId,{provider:this.config.provider,baseURL:this.config.baseURL,headers:this.config.headers??{},fetch:this.config.fetch,generateId:this.config.generateId??C,supportedUrls:()=>({"*":[/^https?:\/\/.*$/,/^gs:\/\/.*$/]})}),{responseModalities:re,imageConfig:de,...L}=A?.googleVertex??A?.vertex??{},B={...L,responseModalities:["IMAGE"],imageConfig:_!=null||de!=null?{...de,..._!=null?{aspectRatio:_}:{}}:void 0},he=await X.doGenerate({prompt:K,seed:w,providerOptions:{googleVertex:B,vertex:B},headers:S,abortSignal:k}),q=this.config._internal?.currentDate?.()??new Date,U=[];for(let ye of he.content)if(ye.type==="file"&&ye.mediaType.startsWith("image/")&&ye.data.type==="data")U.push(j(ye.data.data));let ue={images:U.map(()=>({}))};return{images:U,...he.finishReason.unified==="content-filter"?{isRetryable:!1}:{},warnings:ne,providerMetadata:{googleVertex:ue,vertex:ue},response:{timestamp:q,modelId:this.modelId,headers:he.response?.headers},usage:he.usage?{inputTokens:he.usage.inputTokens.total,outputTokens:he.usage.outputTokens.total,totalTokens:(he.usage.inputTokens.total??0)+(he.usage.outputTokens.total??0)}:void 0}}},Am="Kore",Kl="en-US",qs="Chirp3-HD",Sm="https://texttospeech.googleapis.com/v1/text:synthesize",km=class h{static[H](f){return te({modelId:f.modelId,config:f.config})}static[Q](f){return new h(f.modelId,f.config)}get provider(){return this.config.provider}constructor(f,g){this.modelId=f,this.config=g,this.specificationVersion="v4"}async doGenerate(f){let g=this.config._internal?.currentDate?.()??new Date,y=[],{text:_,voice:w=Am,outputFormat:A,instructions:S,speed:k,language:V}=f,P,ne;if(w.includes(qs)){P=w;let de=w.split(qs)[0].replace(/-$/,"");ne=V??(de||Kl)}else ne=V??Kl,P=`${ne}-${qs}-${w}`;if(S!=null)y.push({type:"unsupported",feature:"instructions",details:"Google Cloud Text-to-Speech Chirp 3: HD voices do not support the `instructions` option. It was ignored."});if(A!=null&&A!=="wav")y.push({type:"unsupported",feature:"outputFormat",details:`Unsupported output format: ${A}. Using wav instead.`});let Z={input:{text:_},voice:{languageCode:ne,name:P},audioConfig:{audioEncoding:"LINEAR16",...k!=null?{speakingRate:k}:{}}},{value:K,responseHeaders:X,rawValue:re}=await O({url:Sm,headers:I(this.config.headers?await M(this.config.headers):void 0,f.headers),body:Z,failedResponseHandler:Zt,successfulResponseHandler:E(xm),abortSignal:f.abortSignal,fetch:this.config.fetch});return{audio:K.audioContent!=null?ke(K.audioContent):new Uint8Array(0),warnings:y,request:{body:JSON.stringify(Z)},response:{timestamp:g,modelId:this.modelId,headers:X,body:re},providerMetadata:{google:{mimeType:"audio/wav"}}}}},xm=u(()=>l(t({audioContent:e().nullish()}))),Om={googleSearch:Xt.googleSearch,enterpriseWebSearch:Xt.enterpriseWebSearch,googleMaps:Xt.googleMaps,urlContext:Xt.urlContext,fileSearch:Xt.fileSearch,codeExecution:Xt.codeExecution,vertexRagStore:Xt.vertexRagStore},Rm=u(()=>l(t({languageCodes:o(e()).optional(),enableAutomaticPunctuation:r().optional(),enableWordTimeOffsets:r().optional(),region:e().optional()})));function Fs(h){if(h==null)return;let f=Number.parseFloat(h);return Number.isFinite(f)?f:void 0}function Im(h){if(h==null)return;try{let f=new Intl.Locale(h).language;return f.length===2?f:void 0}catch{return}}var Nm=class h{static[H](f){return te({modelId:f.modelId,config:f.config})}static[Q](f){return new h(f.modelId,f.config)}get provider(){return this.config.provider}constructor(f,g){this.modelId=f,this.config=g,this.specificationVersion="v4"}async doGenerate(f){let g=this.config._internal?.currentDate?.()??new Date,y=[],_;for(let X of["googleVertex","vertex","google"])if(_=await T({provider:X,providerOptions:f.providerOptions,schema:Rm}),_!=null)break;let w=_?.region??this.config.location;if(!Ls(w))throw new F({argument:_?.region!=null?"region":"location",message:"Invalid Google Cloud Speech-to-Text region. Expected a single DNS label (letters, digits, and hyphens)."});let A=_?.languageCodes??["auto"],S=typeof f.audio==="string"?f.audio:it(f.audio),k={config:{model:this.modelId,languageCodes:A,autoDecodingConfig:{},features:{enableWordTimeOffsets:_?.enableWordTimeOffsets??!0,enableAutomaticPunctuation:_?.enableAutomaticPunctuation??!0}},content:S},V=`https://${w==="global"?"speech.googleapis.com":`${w}-speech.googleapis.com`}/v2/projects/${this.config.project}/locations/${w}/recognizers/_:recognize`,{value:P,responseHeaders:ne,rawValue:Z}=await O({url:V,headers:I(this.config.headers?await M(this.config.headers):void 0,f.headers),body:k,failedResponseHandler:Zt,successfulResponseHandler:E(Pm),abortSignal:f.abortSignal,fetch:this.config.fetch}),K=P.results??[];return{text:K.map((X)=>X.alternatives?.[0]?.transcript??"").join(" ").trim(),segments:K.flatMap((X)=>X.alternatives?.[0]?.words?.flatMap((re)=>{let de=Fs(re.startOffset),L=Fs(re.endOffset);return re.word==null||de==null||L==null?[]:[{text:re.word,startSecond:de,endSecond:L}]})??[]),language:Im(K[0]?.languageCode),durationInSeconds:Fs(P.metadata?.totalBilledDuration),warnings:y,response:{timestamp:g,modelId:this.modelId,headers:ne,body:Z}}}},Pm=u(()=>l(t({results:o(t({alternatives:o(t({transcript:e().nullish(),words:o(t({word:e().nullish(),startOffset:e().nullish(),endOffset:e().nullish()})).nullish()})).nullish(),languageCode:e().nullish()})).nullish(),metadata:t({totalBilledDuration:e().nullish()}).nullish()}))),jm=u(()=>l(t({languageCodes:o(e()).optional(),customVocabulary:o(e()).optional(),wordTimestamp:r().optional(),diarization:r().optional(),mode:s(["SMART","VERBATIM"]).optional()}))),Um="google.cloud.aiplatform.v1.LlmBidiService/BidiGenerateContent",Mm=3000;function Yl(h){return h.includes("-live")}function Dm(h){if(h==="global")return"aiplatform.googleapis.com";if(h==="eu"||h==="us")return`aiplatform.${h}.rep.googleapis.com`;return`${h}-aiplatform.googleapis.com`}var Lm=class h{static[H](f){return te({modelId:f.modelId,config:f.config})}static[Q](f){return new h(f.modelId,f.config)}get provider(){return this.config.provider}constructor(f,g){this.modelId=f,this.config=g,this.specificationVersion="v4"}async parseOptions(f){for(let g of["googleVertex","vertex","google"]){let y=await T({provider:g,providerOptions:f,schema:jm});if(y!=null)return y}}async doGenerate(f){if(Yl(this.modelId))throw new F({argument:"modelId",message:`Model '${this.modelId}' only supports streaming transcription. Use experimental_streamTranscribe, or a unary model such as 'gemini-3.5-transcribe'.`});let g=this.config._internal?.currentDate?.()??new Date,y=[],_=zl(await this.parseOptions(f.providerOptions)),w={contents:[{role:"user",parts:[{inlineData:{mimeType:f.mediaType,data:j(f.audio)}}]}],..._!=null?{generationConfig:{audioTranscriptionConfig:_}}:{}},{value:A,responseHeaders:S,rawValue:k}=await O({url:`${this.config.baseURL}/models/${this.modelId}:generateContent`,headers:I(this.config.headers?await M(this.config.headers):void 0,f.headers),body:w,failedResponseHandler:Zt,successfulResponseHandler:E($m),abortSignal:f.abortSignal,fetch:this.config.fetch}),V=A.candidates?.[0]?.content?.parts??[],P=V.map((re)=>re.text??"").join(""),ne=V.map((re)=>re.audioTranscription?.text??"").join(""),Z=P!==""?P:ne,K,X=[];for(let re of V){let de=re.audioTranscription;if(de==null)continue;K??=de.languageCode??void 0;for(let L of de.words??[]){let B=Xl(L.startOffset),he=Xl(L.endOffset);if(L.word==null||B==null||he==null)continue;X.push({text:L.word,startSecond:B,endSecond:he})}}return{text:Z,segments:X,language:K,durationInSeconds:void 0,warnings:y,response:{timestamp:g,modelId:this.modelId,headers:S,body:k},...A.usageMetadata!=null?{usage:A.usageMetadata,providerMetadata:{google:{usageMetadata:A.usageMetadata}}}:{}}}async doStream(f){if(!Yl(this.modelId))throw new F({argument:"modelId",message:`Model '${this.modelId}' does not support streaming transcription. Use a live model such as 'gemini-3.5-transcribe-live'.`});let g=this.config._internal?.currentDate?.()??new Date,y=[],_=await this.parseOptions(f.providerOptions);Fm(f.inputAudioFormat);let w=I(this.config.headers?await M(this.config.headers):void 0,f.headers),{project:A,location:S}=this.config,k=`projects/${A}/locations/${S}/publishers/google/models/${this.modelId}`,V=new URL(`wss://${Dm(S)}/ws/${Um}`),P={model:k,inputAudioTranscription:zl(_)??{}};return{request:{body:P},response:{timestamp:g,modelId:this.modelId},stream:qm({webSocket:this.config.webSocket,url:V,headers:w,setup:P,inputAudioRate:f.inputAudioFormat.rate??16000,finishGraceMs:this.config._internal?.finishGraceMs??Mm,warnings:y,audio:f.audio,abortSignal:f.abortSignal,includeRawChunks:f.includeRawChunks})}}};function qm({webSocket:h,url:f,headers:g,setup:y,inputAudioRate:_,finishGraceMs:w,warnings:A,audio:S,abortSignal:k,includeRawChunks:V}){let P=!1,ne=()=>{};return new ReadableStream({start:(Z)=>{let K,X,re,de=new Promise((Ue)=>{re=Ue}),L=0,B="",he="",q="",U,ue=!1,ye,ve,_e=()=>`google-segment-${L}`,Ne=()=>{if(ve!=null)clearTimeout(ve),ve=void 0},Re=()=>{if(P||!ue)return;Ne(),ve=setTimeout(()=>{ve=void 0,je()},w)};ne=(Ue)=>{if(Ne(),K!=null)K.cancel().catch(()=>{});else S.cancel().catch(()=>{});X?.close(Ue)};let Ie=(Ue)=>{if(P)return;P=!0,ne(),Z.error(Ue)},Be=()=>{if(B===""){if(q==="")return;B=q}q="",Z.enqueue({type:"transcript-final",id:_e(),text:B}),he+=he===""?B:` ${B}`,B="",L++},je=()=>{if(P)return;Be(),P=!0,Z.enqueue({type:"finish",text:he,segments:[],language:U,durationInSeconds:void 0,...ye!=null?{usage:ye,providerMetadata:{google:{usageMetadata:ye}}}:{}}),Z.close(),ne(1000)},Ve=async(Ue)=>{K=S.getReader();try{while(!0){let{done:Je,value:Ze}=await K.read();if(Je||P)break;Ue.send(JSON.stringify({realtimeInput:{audio:{data:j(Ze),mimeType:`audio/pcm;rate=${_}`}}})),await vn(Ue)}}finally{K.releaseLock(),K=void 0}if(!P)Ue.send(JSON.stringify({realtimeInput:{audioStreamEnd:!0}})),ue=!0,Re()};X=ia({url:f,headers:g,webSocket:h,abortSignal:k,onAbort:Ie,onProcessingError:Ie,onOpen:(Ue)=>{Z.enqueue({type:"stream-start",warnings:A}),Ue.send(JSON.stringify({setup:y})),de.then(()=>P?void 0:Ve(Ue)).catch(Ie)},onMessageText:async(Ue)=>{if(P)return;let Je=await yt({text:Ue});if(!Je.success)return;let Ze=Je.value;if(V)Z.enqueue({type:"raw",rawValue:Ze});if(Ze.setupComplete!=null)re();if(Ze.usageMetadata!=null)ye=Ze.usageMetadata;if(Ze.error!=null){Ie(Error(Ze.error.message??"Vertex Live API error"));return}let tt=Ze.serverContent,ot=tt?.interimInputTranscription;if(ot?.text)Re(),q=ot.text,Z.enqueue({type:"transcript-partial",id:_e(),text:ot.text});let et=tt?.inputTranscription??Ze.inputTranscription;if(et!=null){if(et.languageCode!=null)U=et.languageCode;if(et.text)Re(),q="",B+=et.text,Z.enqueue({type:"transcript-delta",id:_e(),delta:et.text});if(et.finished===!0)Be()}if(tt?.turnComplete)Be();let mt=tt?.interactionStatus;if(ue&&(mt==="IDLE"||mt==="REQUIRES_ACTION"||tt?.turnComplete===!0&&mt==null))je()},onSocketError:()=>{Ie(Error("Vertex Live transcription error."+(h==null?" Note: the native WebSocket implementation cannot send the Authorization header required by Vertex. Pass a header-capable WebSocket implementation (e.g. the 'ws' package) via createVertex({ webSocket }).":"")))},onClose:({code:Ue,reason:Je})=>{if(P)return;if(ue){je();return}Ie(Error(`Vertex Live transcription WebSocket closed unexpectedly before finishing (code ${Ue??"unknown"}${Je?`, reason: ${Je}`:""}).`))}})},cancel:()=>{if(P)return;P=!0,ne()}})}function zl(h){if(h==null)return;let f={};if(h.languageCodes!=null)f.languageCodes=h.languageCodes;if(h.customVocabulary!=null)f.customVocabulary=h.customVocabulary;if(h.wordTimestamp!=null)f.wordTimestamp=h.wordTimestamp;if(h.diarization!=null)f.diarization=h.diarization;if(h.mode!=null)f.mode=h.mode;return Object.keys(f).length>0?f:void 0}function Fm(h){if(h.type!=="audio/pcm"||h.rate!=null&&h.rate!==16000)throw new F({argument:"inputAudioFormat",message:"The Gemini Live transcription API only supports 16kHz 16-bit PCM input audio."})}function Xl(h){if(h==null)return;let f=Number.parseFloat(h);return Number.isFinite(f)?f:void 0}var Gm=()=>t({word:e().nullish(),startOffset:e().nullish(),endOffset:e().nullish()}),$m=u(()=>l(t({candidates:o(t({content:t({parts:o(t({text:e().nullish(),audioTranscription:t({text:e().nullish(),languageCode:e().nullish(),speakerLabel:e().nullish(),words:o(Gm()).nullish()}).nullish()})).nullish()}).nullish()})).nullish(),usageMetadata:d(e(),m()).nullish()}))),Ql=u(()=>l(ae({pollIntervalMs:n().positive().nullish(),pollTimeoutMs:n().positive().nullish(),personGeneration:s(["dont_allow","allow_adult","allow_all"]).nullish(),negativePrompt:e().nullish(),generateAudio:r().nullish(),gcsOutputDirectory:e().nullish(),referenceImages:o(t({bytesBase64Encoded:e().nullish(),gcsUri:e().nullish()})).nullish()})));function Hm(h){return h.frameImages?.find((f)=>f.frameType==="first_frame")?.image}function Bm(h){return Hm(h)??h.image}function Vm(h){return h.frameImages?.find((f)=>f.frameType==="last_frame")?.image}function Wm(h){if(h.frameImages!=null&&h.frameImages.length>0)return;return h.inputReferences!=null&&h.inputReferences.length>0?h.inputReferences:void 0}function Gs(h,f){if(h.type==="url"){if(h.url.startsWith("gs://"))return{gcsUri:h.url,mimeType:"image/png"};f.push({type:"unsupported",feature:"URL-based image input",details:"Vertex AI video models require base64-encoded images or GCS URIs. URL will be ignored."});return}return{bytesBase64Encoded:typeof h.data==="string"?h.data:it(h.data),mimeType:h.mediaType||"image/png"}}function Jm(h,f){let g=Gs(h,f);return g!=null?{image:g,referenceType:"asset"}:void 0}var Km=class{get provider(){return this.config.provider}get maxVideosPerCall(){return 4}constructor(h,f){this.modelId=h,this.config=f,this.specificationVersion="v4"}async buildRequest(h){let f=[],g=await T({provider:"googleVertex",providerOptions:h.providerOptions,schema:Ql})??await T({provider:"vertex",providerOptions:h.providerOptions,schema:Ql}),y=[{}],_=y[0];if(h.prompt!=null)_.prompt=h.prompt;let w=Bm(h);if(w!=null){let P=Gs(w,f);if(P!=null)_.image=P}let A=Vm(h);if(A!=null){let P=Gs(A,f);if(P!=null)_.lastFrame=P}let S=Wm(h);if(S!=null)_.referenceImages=S.flatMap((P)=>{let ne=Jm(P,f);return ne!=null?[ne]:[]});else if(g?.referenceImages!=null)_.referenceImages=g.referenceImages;let k={sampleCount:h.n};if(h.aspectRatio)k.aspectRatio=h.aspectRatio;if(h.resolution)k.resolution={"1280x720":"720p","1920x1080":"1080p","3840x2160":"4k"}[h.resolution]||h.resolution;if(h.duration)k.durationSeconds=h.duration;if(h.seed)k.seed=h.seed;let V=h.generateAudio??g?.generateAudio;if(V!=null)k.generateAudio=V;if(g!=null){let P=g;if(P.personGeneration!==void 0&&P.personGeneration!==null)k.personGeneration=P.personGeneration;if(P.negativePrompt!==void 0&&P.negativePrompt!==null)k.negativePrompt=P.negativePrompt;if(P.gcsOutputDirectory!==void 0&&P.gcsOutputDirectory!==null)k.gcsOutputDirectory=P.gcsOutputDirectory;for(let[ne,Z]of Object.entries(P))if(!["pollIntervalMs","pollTimeoutMs","personGeneration","negativePrompt","generateAudio","gcsOutputDirectory","referenceImages"].includes(ne))k[ne]=Z}return{instances:y,parameters:k,warnings:f,googleVertexOptions:g}}buildCompletedResult({finalOperation:h,responseHeaders:f,warnings:g,currentDate:y}){let _=h.response;if(!_?.videos||_.videos.length===0)throw new D({name:"VERTEX_VIDEO_GENERATION_ERROR",message:`No videos in response. Response: ${JSON.stringify(h)}`});let w=[],A=[];for(let S of _.videos)if(S.bytesBase64Encoded)w.push({type:"base64",data:S.bytesBase64Encoded,mediaType:S.mimeType||"video/mp4"}),A.push({mimeType:S.mimeType});else if(S.gcsUri)w.push({type:"url",url:S.gcsUri,mediaType:S.mimeType||"video/mp4"}),A.push({gcsUri:S.gcsUri,mimeType:S.mimeType});if(w.length===0)throw new D({name:"VERTEX_VIDEO_GENERATION_ERROR",message:"No valid videos in response"});return{status:"completed",videos:w,warnings:g,response:{timestamp:y,modelId:this.modelId,headers:f},providerMetadata:(()=>{let S={videos:A};return{googleVertex:S,"google-vertex":S,vertex:S}})()}}async doStart(h){let f=this.config._internal?.currentDate?.()??new Date,{instances:g,parameters:y,warnings:_}=await this.buildRequest(h),{value:w,responseHeaders:A}=await O({url:`${this.config.baseURL}/models/${this.modelId}:predictLongRunning`,headers:I(await M(this.config.headers),h.headers),body:{instances:g,parameters:y},successfulResponseHandler:E(Zl),failedResponseHandler:Zt,abortSignal:h.abortSignal,fetch:this.config.fetch}),S=w.name;if(!S)throw new D({name:"VERTEX_VIDEO_GENERATION_ERROR",message:"No operation name returned from API"});return{operation:{operationName:S},warnings:_,response:{timestamp:f,modelId:this.modelId,headers:A}}}async doStatus(h){let f=this.config._internal?.currentDate?.()??new Date,{operationName:g}=h.operation,{value:y,responseHeaders:_}=await O({url:`${this.config.baseURL}/models/${this.modelId}:fetchPredictOperation`,headers:I(await M(this.config.headers),h.headers),body:{operationName:g},successfulResponseHandler:E(Zl),failedResponseHandler:Zt,abortSignal:h.abortSignal,fetch:this.config.fetch});if(!y.done)return{status:"pending",response:{timestamp:f,modelId:this.modelId,headers:_}};if(y.error)return{status:"error",error:`Video generation failed: ${y.error.message}`,response:{timestamp:f,modelId:this.modelId,headers:_}};return this.buildCompletedResult({finalOperation:y,responseHeaders:_,warnings:[],currentDate:f})}},Zl=u(()=>l(t({name:e().nullish(),done:r().nullish(),error:t({code:n().nullish(),message:e(),status:e().nullish()}).nullish(),response:t({videos:o(t({bytesBase64Encoded:e().nullish(),gcsUri:e().nullish(),mimeType:e().nullish()})).nullish(),raiMediaFilteredCount:n().nullish()}).nullish()}))),Ym="https://aiplatform.googleapis.com/v1/publishers/google",zm="endpoints/";function Xm(h){return h.startsWith(zm)}function Qm(h,f){return async(g,y)=>{let _={...y,headers:{...y?.headers?Di(y.headers):{},"x-goog-api-key":h}};return(f??fetch)(g.toString(),_)}}function eu(h={}){let f=dt({settingValue:h.apiKey,environmentVariableName:"GOOGLE_VERTEX_API_KEY"}),g=()=>so({settingValue:h.project,settingName:"project",environmentVariableName:"GOOGLE_VERTEX_PROJECT",description:"Google Vertex project"}),y=()=>{let X=so({settingValue:h.location,settingName:"location",environmentVariableName:"GOOGLE_VERTEX_LOCATION",description:"Google Vertex location"});if(!Ls(X))throw new F({argument:"location",message:"Invalid Google Vertex location. Expected a single DNS label (letters, digits, and hyphens). Use `baseURL` for custom endpoints."});return X},_=({endpoint:X=!1}={})=>{if(f)return Ye(h.baseURL)??Ym;let re=Ye(h.baseURL);if(re!=null)return re;let de=y(),L=g();return`https://${(()=>{if(de==="global")return"aiplatform.googleapis.com";else if(de==="eu"||de==="us")return`aiplatform.${de}.rep.googleapis.com`;else return`${de}-aiplatform.googleapis.com`})()}/v1beta1/projects/${L}/locations/${de}${X?"":"/publishers/google"}`},w=(X,{endpoint:re=!1}={})=>{let de=async()=>{let L=await M(h.headers??{});return Ee(L,`ai-sdk-google-vertex/${_m}`)};return{provider:`google.vertex.${X}`,headers:de,fetch:f?Qm(f,h.fetch):h.fetch,baseURL:_({endpoint:re})}},A=(X)=>{let re=Xm(X);if(re&&f)throw Error("Google Vertex tuned models do not support Express Mode API keys. Use standard Google Cloud credentials instead.");return new js(X,{...w("chat",{endpoint:re}),generateId:h.generateId??C,supportedUrls:()=>({"*":[/^https?:\/\/.*$/,/^gs:\/\/.*$/]}),downloadToolResultFiles:{maxBytes:h.toolResultDownloads?.maxBytes??7340032,supportsGoogleCloudStorageUrls:!0}})},S=(X)=>{if(f)throw Error("Google Vertex Interactions models do not support Express Mode API keys. Use standard Google Cloud credentials instead.");return new Wl(X,{...w("interactions",{endpoint:!0}),generateId:h.generateId??C})},k=(X)=>new wm(X,w("embedding")),V=(X)=>new bm(X,{...w("image"),generateId:h.generateId??C}),P=(X)=>new Km(X,{...w("video"),generateId:h.generateId??C}),ne=(X)=>{if(X.startsWith("chirp")){if(f)throw Error("Google Vertex Chirp speech models do not support Express Mode API keys. Use standard Google Cloud credentials instead.");let re=w("speech");return new km(X,{provider:re.provider,headers:re.headers,fetch:re.fetch})}return new Il(X,w("speech"))},Z=(X)=>{if(f)throw Error("Google Vertex transcription models do not support Express Mode API keys. Use standard Google Cloud credentials instead.");let re=w("transcription");if(X.startsWith("gemini"))return new Lm(X,{provider:re.provider,baseURL:_(),headers:re.headers,fetch:re.fetch,webSocket:h.webSocket,project:g(),location:y()});return new Nm(X,{provider:re.provider,headers:re.headers,fetch:re.fetch,project:g(),location:y()})},K=function(X){if(new.target)throw Error("The Google Vertex AI model function cannot be called with the new keyword.");return A(X)};return K.specificationVersion="v4",K.languageModel=A,K.interactions=S,K.embeddingModel=k,K.textEmbeddingModel=k,K.image=V,K.imageModel=V,K.video=P,K.videoModel=P,K.speech=ne,K.speechModel=ne,K.transcription=Z,K.transcriptionModel=Z,K.tools=Om,K}function vl(h={}){if(dt({settingValue:h.apiKey,environmentVariableName:"GOOGLE_VERTEX_API_KEY"}))return eu(h);let f=ym(h.project==null?h.googleAuthOptions:{projectId:h.project,...h.googleAuthOptions});return eu({...h,headers:async()=>({Authorization:`Bearer ${await f()}`,...await M(h.headers)})})}var C_=vl();var nu=v(ks(),1);function Zm(h){let f=new nu.GoogleAuth({scopes:["https://www.googleapis.com/auth/cloud-platform"],...h});return async function(){return(await(await f.getClient()).getAccessToken())?.token??null}}var ey=u(()=>l(t({labels:d(e(),e()).optional()}))),ty={bash_20241022:Oi.bash_20241022,bash_20250124:Oi.bash_20250124,textEditor_20241022:Oi.textEditor_20241022,textEditor_20250124:Oi.textEditor_20250124,textEditor_20250429:Oi.textEditor_20250429,textEditor_20250728:Oi.textEditor_20250728,computer_20241022:Oi.computer_20241022,webSearch_20250305:Oi.webSearch_20250305,toolSearchRegex_20251119:Oi.toolSearchRegex_20251119,toolSearchBm25_20251119:Oi.toolSearchBm25_20251119};function ny(h={}){let f=()=>{let _=Ye(h.baseURL);if(_!=null)return _;let w=dt({settingValue:h.location,environmentVariableName:"GOOGLE_VERTEX_LOCATION"});if(w!=null&&!Ls(w))throw new F({argument:"location",message:"Invalid Google Vertex location. Expected a single DNS label (letters, digits, and hyphens). Use `baseURL` for custom endpoints."});let A=dt({settingValue:h.project,environmentVariableName:"GOOGLE_VERTEX_PROJECT"});return`https://${(()=>{if(w==="global")return"aiplatform.googleapis.com";else if(w==="eu"||w==="us")return`aiplatform.${w}.rep.googleapis.com`;else return`${w}-aiplatform.googleapis.com`})()}/v1/projects/${A}/locations/${w}/publishers/anthropic/models`},g=(_)=>new Bw(_,{provider:"googleVertex.anthropic.messages",baseURL:f(),headers:h.headers??{},fetch:h.fetch,buildRequestUrl:(w,A)=>`${w}/${_}:${A?"streamRawPredict":"rawPredict"}`,transformRequestBody:(w)=>{let{model:A,...S}=w;return{...S,anthropic_version:"vertex-2023-10-16"}},transformRequestHeaders:async(w,A)=>{let S=await T({provider:"vertex",providerOptions:A,schema:ey});if(S?.labels==null||Object.keys(w).some((k)=>k.toLowerCase()==="x-vertex-ai-labels"&&w[k]!=null))return w;return{...w,"x-vertex-ai-labels":it(new TextEncoder().encode(JSON.stringify(S.labels)))}},supportedUrls:()=>({}),supportsNativeStructuredOutput:!1,supportsStrictTools:!1}),y=function(_){if(new.target)throw Error("The Anthropic model function cannot be called with the new keyword.");return g(_)};return y.specificationVersion="v4",y.languageModel=g,y.chat=g,y.messages=g,y.embeddingModel=(_)=>{throw new we({modelId:_,modelType:"embeddingModel"})},y.textEmbeddingModel=y.embeddingModel,y.imageModel=(_)=>{throw new we({modelId:_,modelType:"imageModel"})},y.tools=ty,y}function wl(h={}){let f=h.generateAuthToken??Zm(h.googleAuthOptions);return ny({...h,headers:async()=>({Authorization:`Bearer ${await f()}`,...await M(h.headers)})})}var R_=wl();
39
+ export{vl,wl};