@vibe-lark/larkpal 0.1.85 → 0.1.87

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 (111) hide show
  1. package/dist/account-id-BM1T6029-BzQ_cMoi.mjs +1 -0
  2. package/dist/activation-context--5yu1dPF-XV0Y0pTy.mjs +1 -0
  3. package/dist/anthropic-CFZUCb1w.mjs +39 -0
  4. package/dist/assistant-visible-text-DuFWokAt-BOJV_zwc.mjs +9 -0
  5. package/dist/azure-openai-responses-BEuiMaF-.mjs +1 -0
  6. package/dist/boundary-file-read-BSd9MXPy-gnNVhPKT.mjs +1 -0
  7. package/dist/browser-lifecycle-cleanup-BdNsMhMD-BM97qA_M.mjs +1 -0
  8. package/dist/build-Bkj0hOS2.mjs +3 -0
  9. package/dist/bundled-compat-BpaDaAAu-DJtrIX6i.mjs +27 -0
  10. package/dist/bundled-dir-U738ay4K-BxbzrJOo.mjs +1 -0
  11. package/dist/call-DimWbpgJ-B4pv55RH.mjs +20 -0
  12. package/dist/channel-bootstrap.runtime-BVclcGv1-CEZ0-JP9.mjs +1 -0
  13. package/dist/channel-bootstrap.runtime-Cwcr38m2-Dt6QlQkX.mjs +1 -0
  14. package/dist/chunk-DHbaKqs-.mjs +1 -0
  15. package/dist/cli.mjs +7 -92
  16. package/dist/command-format-LSnUCVVF-Dn4h9IOh.mjs +16 -0
  17. package/dist/config-Bim2pi8a-03N-28sw.mjs +1 -0
  18. package/dist/delivery-context.shared-j5hC5qb1-BSLQG47q.mjs +1 -0
  19. package/dist/diagnostic-ClMwNnUA-BMKvPQJT.mjs +1 -0
  20. package/dist/dist-J5UB83Ws.mjs +601 -0
  21. package/dist/dist-coestTs9.mjs +5 -0
  22. package/dist/env-api-keys-Cuz5irWW.mjs +1 -0
  23. package/dist/event-stream-B7Ei41Bu.mjs +1 -0
  24. package/dist/facade-loader-DFzIYYt_-4bzFvy-b.mjs +1 -0
  25. package/dist/from-Ba69_5cR.mjs +14 -0
  26. package/dist/gateway-method-policy-C7rf0SeV-CTJcMQCE.mjs +1 -0
  27. package/dist/github-copilot-headers-BfhryVuU.mjs +1 -0
  28. package/dist/google-ABo-1guT.mjs +1 -0
  29. package/dist/google-gemini-cli-CGlN1zUA.mjs +2 -0
  30. package/dist/google-shared-C60sNhwd.mjs +301 -0
  31. package/dist/google-vertex-De0nAItu.mjs +1 -0
  32. package/dist/hash-Dw-N8Y9l.mjs +1 -0
  33. package/dist/headers-Bpsp70B9.mjs +1 -0
  34. package/dist/home-dir-C44RaPME-B5iLWwCq.mjs +1 -0
  35. package/dist/ids-BPsM98Uu-CJBJAeVC.mjs +1 -0
  36. package/dist/image-2w3cApg7-CrpUMCvm.mjs +3 -0
  37. package/dist/interactive-init-C5MFL5MW.mjs +8 -0
  38. package/dist/io-CH2g3vsv-JJtUIa_U.mjs +10 -0
  39. package/dist/jiti-loader-cache-Bat69wam-DNIteTtO.mjs +9 -0
  40. package/dist/json-file-BQRNuxmK-hRjIgOXI.mjs +1 -0
  41. package/dist/json-parse-BESd8UAM.mjs +3 -0
  42. package/dist/jws-YaZ38F_i.mjs +12 -0
  43. package/dist/lark-cli-provider-BLMxH6CN.mjs +4 -0
  44. package/dist/lark-logger-xpMKNNtY.mjs +1 -0
  45. package/dist/live-smoke-DpURW676.mjs +33 -0
  46. package/dist/load-context-mb7uvLSn-3xYwSnOZ.mjs +1 -0
  47. package/dist/loader-708jrx4Y-BbJRXNlQ.mjs +4 -0
  48. package/dist/main.mjs +480 -18553
  49. package/dist/manifest-registry-_hxKCS2K-OL8KK_o4.mjs +15 -0
  50. package/dist/mcp-server.mjs +4 -527
  51. package/dist/message-channel-Bk_YHfQg-n2Hw2Y0L.mjs +1 -0
  52. package/dist/message-channel-core-DTA--Gjh-CIh10vfo.mjs +1 -0
  53. package/dist/message.config.runtime-K-k4XOyq-F_h0Cgkl.mjs +1 -0
  54. package/dist/message.gateway.runtime-DqHOHRTQ-ge4c5p4s.mjs +1 -0
  55. package/dist/mistral-DyL3Zo1b.mjs +7 -0
  56. package/dist/model-auth-env-oyg2Hexc-DJbt9J3o.mjs +1 -0
  57. package/dist/models-config-BmpSQJQF-BL6S5qAo.mjs +1 -0
  58. package/dist/models-config.runtime-SOhLEw-f.mjs +1 -0
  59. package/dist/multipart-parser-B9dwXBqu.mjs +2 -0
  60. package/dist/oauth-25y2wc7K.mjs +75 -0
  61. package/dist/openai-C-rgGb7X.mjs +16 -0
  62. package/dist/openai-codex-responses-BbyAPsP1.mjs +7 -0
  63. package/dist/openai-completions-Bu5qvQzb.mjs +5 -0
  64. package/dist/openai-responses-pIdwQBc4.mjs +1 -0
  65. package/dist/openai-responses-shared-DqW1JSux.mjs +10 -0
  66. package/dist/paths-D6msg0S1-BO4XgM1u.mjs +1 -0
  67. package/dist/paths-D92DjaZ--DdtJ-zYp.mjs +1 -0
  68. package/dist/pi-model-discovery-Bd0TWzo8-DvSM0eWu.mjs +1 -0
  69. package/dist/pi-model-discovery-runtime-PrjWOmsV.mjs +1 -0
  70. package/dist/pi-tools.before-tool-call.runtime-Bn7uqKie-WPxU5oNX.mjs +2 -0
  71. package/dist/plugin-auto-enable-DdH3n9V8-Dr_bUXkG.mjs +1 -0
  72. package/dist/process-scoped-map-B2cWkYET-Co-i-MXA.mjs +1 -0
  73. package/dist/provider-discovery.runtime-DY0VWQ81.mjs +1 -0
  74. package/dist/provider-model-compat-CFqcq0it-BUwZENrz.mjs +1 -0
  75. package/dist/provider-runtime-C8rljsNs-BDvu6FW3.mjs +1 -0
  76. package/dist/provider-runtime-CT50mNIX-DImw7ZZu.mjs +79 -0
  77. package/dist/provider-stream-COLujAAo-Dpq1DSIk.mjs +248 -0
  78. package/dist/providers.runtime-Ba7tOlq7-B4t6ywCr.mjs +1 -0
  79. package/dist/public-surface-loader-BVl0NQAE-TfJ3izj1.mjs +1 -0
  80. package/dist/resolve-C33B7eeu-DZM_z6Wr.mjs +1 -0
  81. package/dist/runtime-Cym-fqI8-1GOIuRRQ.mjs +1 -0
  82. package/dist/runtime-channel-state-CohMybAh-BBzhl07Q.mjs +1 -0
  83. package/dist/runtime-snapshot-C54O1-gI-DxusscPf.mjs +1 -0
  84. package/dist/runtime-state-IBOIXKOx-Cw1GA1td.mjs +1 -0
  85. package/dist/runtime-web-tools-fallback.runtime-Ca-qn1mj-BsYE2gOd.mjs +1 -0
  86. package/dist/runtime-web-tools-manifest.runtime-BgxQTjmq-P6MKP9gQ.mjs +1 -0
  87. package/dist/runtime-web-tools-public-artifacts.runtime-D9qcoWIX-5VoyjouO.mjs +1 -0
  88. package/dist/session-archive.runtime-B52_5vs4-cU2tYbBz.mjs +1 -0
  89. package/dist/session-key-Cn2QoOyX-QZeYmbxd.mjs +1 -0
  90. package/dist/session-transcript-files.fs-DEeFXruQ-CXIAFSsr.mjs +1 -0
  91. package/dist/src-CCDx_C-U.mjs +3 -0
  92. package/dist/src-DACmA9V6.mjs +5 -0
  93. package/dist/subagent-announce-L5WsQatW--rMn240x.mjs +2 -0
  94. package/dist/subagent-announce.registry.runtime-DiqZyeTs-DNfNHsls.mjs +1 -0
  95. package/dist/subagent-registry-steer-runtime-DFgZFC0j-XYS1_qwl.mjs +1 -0
  96. package/dist/subagent-system-prompt-C1qnN--K-CsU4f97T.mjs +23 -0
  97. package/dist/target-parsing-loaded-DKkb6jJY-B830OA1a.mjs +12 -0
  98. package/dist/task-registry-delivery-runtime-Dd1CUkZF-B2Hj2k8C.mjs +16 -0
  99. package/dist/task-registry-delivery-runtime-ragbeVx5-Bdvo2Q5u.mjs +1 -0
  100. package/dist/thinking-Bh-7MqXz-uApNUe6g.mjs +1 -0
  101. package/dist/transcript-E_-ISOkD-VTwb782D.mjs +5 -0
  102. package/dist/transcript.runtime-BqhvZZdl-B4E0TiX5.mjs +1 -0
  103. package/dist/transform-messages-BTA3xbAI.mjs +1 -0
  104. package/dist/web-provider-public-artifacts-BlpRwIUS-DbVhDOrY.mjs +1 -0
  105. package/dist/web-search-providers.runtime--0aUtC3b-Bjh4Bmrz.mjs +1 -0
  106. package/package.json +1 -2
  107. package/dist/interactive-init-B6j8j_Ap.mjs +0 -450
  108. package/dist/lark-cli-provider-7LvtOIF_.mjs +0 -554
  109. package/dist/lark-logger-D7_pEVQc.mjs +0 -143
  110. package/dist/live-smoke-nvTUPtrv.mjs +0 -7135
  111. package/dist/rolldown-runtime-wcPFST8Q.mjs +0 -13
@@ -0,0 +1,301 @@
1
+ import{a as e,i as t,t as n}from"./chunk-DHbaKqs-.mjs";import{a as r,t as i}from"./transform-messages-BTA3xbAI.mjs";import{a,i as o,n as s,r as c,t as l}from"./jws-YaZ38F_i.mjs";import*as u from"fs/promises";import{writeFile as d}from"fs/promises";import{createWriteStream as f}from"fs";import{finished as p}from"node:stream/promises";import{Readable as m}from"node:stream";import*as h from"path";import*as g from"ws";var _=n(((e,t)=>{function n(e,t){typeof t==`boolean`&&(t={forever:t}),this._originalTimeouts=JSON.parse(JSON.stringify(e)),this._timeouts=e,this._options=t||{},this._maxRetryTime=t&&t.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._timer=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}t.exports=n,n.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)},n.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null},n.prototype.retry=function(e){if(this._timeout&&clearTimeout(this._timeout),!e)return!1;var t=new Date().getTime();if(e&&t-this._operationStart>=this._maxRetryTime)return this._errors.push(e),this._errors.unshift(Error(`RetryOperation timeout occurred`)),!1;this._errors.push(e);var n=this._timeouts.shift();if(n===void 0)if(this._cachedTimeouts)this._errors.splice(0,this._errors.length-1),n=this._cachedTimeouts.slice(-1);else return!1;var r=this;return this._timer=setTimeout(function(){r._attempts++,r._operationTimeoutCb&&(r._timeout=setTimeout(function(){r._operationTimeoutCb(r._attempts)},r._operationTimeout),r._options.unref&&r._timeout.unref()),r._fn(r._attempts)},n),this._options.unref&&this._timer.unref(),!0},n.prototype.attempt=function(e,t){this._fn=e,t&&(t.timeout&&(this._operationTimeout=t.timeout),t.cb&&(this._operationTimeoutCb=t.cb));var n=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){n._operationTimeoutCb()},n._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)},n.prototype.try=function(e){console.log(`Using RetryOperation.try() is deprecated`),this.attempt(e)},n.prototype.start=function(e){console.log(`Using RetryOperation.start() is deprecated`),this.attempt(e)},n.prototype.start=n.prototype.try,n.prototype.errors=function(){return this._errors},n.prototype.attempts=function(){return this._attempts},n.prototype.mainError=function(){if(this._errors.length===0)return null;for(var e={},t=null,n=0,r=0;r<this._errors.length;r++){var i=this._errors[r],a=i.message,o=(e[a]||0)+1;e[a]=o,o>=n&&(t=i,n=o)}return t}})),v=n((e=>{var t=_();e.operation=function(n){return new t(e.timeouts(n),{forever:n&&(n.forever||n.retries===1/0),unref:n&&n.unref,maxRetryTime:n&&n.maxRetryTime})},e.timeouts=function(e){if(e instanceof Array)return[].concat(e);var t={retries:10,factor:2,minTimeout:1*1e3,maxTimeout:1/0,randomize:!1};for(var n in e)t[n]=e[n];if(t.minTimeout>t.maxTimeout)throw Error(`minTimeout is greater than maxTimeout`);for(var r=[],i=0;i<t.retries;i++)r.push(this.createTimeout(i,t));return e&&e.forever&&!r.length&&r.push(this.createTimeout(i,t)),r.sort(function(e,t){return e-t}),r},e.createTimeout=function(e,t){var n=t.randomize?Math.random()+1:1,r=Math.round(n*Math.max(t.minTimeout,1)*t.factor**+e);return r=Math.min(r,t.maxTimeout),r},e.wrap=function(t,n,r){if(n instanceof Array&&(r=n,n=null),!r)for(var i in r=[],t)typeof t[i]==`function`&&r.push(i);for(var a=0;a<r.length;a++){var o=r[a],s=t[o];t[o]=function(r){var i=e.operation(n),a=Array.prototype.slice.call(arguments,1),o=a.pop();a.push(function(e){i.retry(e)||(e&&(arguments[0]=i.mainError()),o.apply(this,arguments))}),i.attempt(function(){r.apply(t,a)})}.bind(t,s),t[o].options=n}}})),y=n(((e,t)=>{t.exports=v()})),b=n(((e,t)=>{let n=y(),r=[`Failed to fetch`,`NetworkError when attempting to fetch resource.`,`The Internet connection appears to be offline.`,`Network request failed`];var i=class extends Error{constructor(e){super(),e instanceof Error?(this.originalError=e,{message:e}=e):(this.originalError=Error(e),this.originalError.stack=this.stack),this.name=`AbortError`,this.message=e}};let a=(e,t,n)=>{let r=n.retries-(t-1);return e.attemptNumber=t,e.retriesLeft=r,e},o=e=>r.includes(e),s=(e,t)=>new Promise((r,s)=>{t={onFailedAttempt:()=>{},retries:10,...t};let c=n.operation(t);c.attempt(async n=>{try{r(await e(n))}catch(e){if(!(e instanceof Error)){s(TypeError(`Non-error was thrown: "${e}". You should only throw errors.`));return}if(e instanceof i)c.stop(),s(e.originalError);else if(e instanceof TypeError&&!o(e.message))c.stop(),s(e);else{a(e,n,t);try{await t.onFailedAttempt(e)}catch(e){s(e);return}c.retry(e)||s(c.mainError())}}})});t.exports=s,t.exports.default=s,t.exports.AbortError=i})),x=n(((e,t)=>{t.exports={name:`gaxios`,version:`7.1.4`,description:`A simple common HTTP client specifically for Google APIs and services.`,main:`build/cjs/src/index.js`,types:`build/cjs/src/index.d.ts`,files:[`build/`],exports:{".":{import:{types:`./build/esm/src/index.d.ts`,default:`./build/esm/src/index.js`},require:{types:`./build/cjs/src/index.d.ts`,default:`./build/cjs/src/index.js`}}},scripts:{lint:`gts check --no-inline-config`,test:`c8 mocha build/esm/test`,"presystem-test":`npm run compile`,"system-test":`mocha build/esm/system-test --timeout 80000`,compile:`tsc -b ./tsconfig.json ./tsconfig.cjs.json && node utils/enable-esm.mjs`,fix:`gts fix`,prepare:`npm run compile`,pretest:`npm run compile`,webpack:`webpack`,"prebrowser-test":`npm run compile`,"browser-test":`node build/browser-test/browser-test-runner.js`,docs:`jsdoc -c .jsdoc.js`,"docs-test":`linkinator docs`,"predocs-test":`npm run docs`,"samples-test":`cd samples/ && npm link ../ && npm test && cd ../`,prelint:`cd samples; npm link ../; npm install`,clean:`gts clean`},repository:{type:`git`,directory:`packages/gaxios`,url:`https://github.com/googleapis/google-cloud-node-core.git`},keywords:[`google`],engines:{node:`>=18`},author:`Google, LLC`,license:`Apache-2.0`,devDependencies:{"@babel/plugin-proposal-private-methods":`^7.18.6`,"@types/cors":`^2.8.6`,"@types/express":`^5.0.0`,"@types/extend":`^3.0.1`,"@types/mocha":`^10.0.10`,"@types/multiparty":`4.2.1`,"@types/mv":`^2.1.0`,"@types/ncp":`^2.0.8`,"@types/node":`^22.13.1`,"@types/sinon":`^17.0.3`,"@types/tmp":`^0.2.6`,assert:`^2.0.0`,browserify:`^17.0.0`,c8:`^10.1.3`,cors:`^2.8.5`,express:`^5.0.0`,gts:`^6.0.2`,"is-docker":`^3.0.0`,jsdoc:`^4.0.4`,"jsdoc-fresh":`^5.0.0`,"jsdoc-region-tag":`^4.0.0`,karma:`^6.0.0`,"karma-chrome-launcher":`^3.0.0`,"karma-coverage":`^2.0.0`,"karma-firefox-launcher":`^2.0.0`,"karma-mocha":`^2.0.0`,"karma-remap-coverage":`^0.1.5`,"karma-sourcemap-loader":`^0.4.0`,"karma-webpack":`^5.0.1`,linkinator:`^6.1.2`,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.0`,"stream-browserify":`^3.0.0`,tmp:`0.2.5`,"ts-loader":`^9.5.2`,typescript:`5.8.3`,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-core/tree/main/packages/gaxios`}})),S=n(((e,t)=>{t.exports={pkg:x()}})),C=n((e=>{var t=e&&e.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(e,`__esModule`,{value:!0}),e.GaxiosError=e.GAXIOS_ERROR_SYMBOL=void 0,e.defaultErrorRedactor=o;let n=t(a()),r=t(S()).default.pkg;e.GAXIOS_ERROR_SYMBOL=Symbol.for(`${r.name}-gaxios-error`),e.GaxiosError=class t extends Error{config;response;code;status;error;[e.GAXIOS_ERROR_SYMBOL]=r.version;static[Symbol.hasInstance](n){return n&&typeof n==`object`&&e.GAXIOS_ERROR_SYMBOL in n&&n[e.GAXIOS_ERROR_SYMBOL]===r.version?!0:Function.prototype[Symbol.hasInstance].call(t,n)}constructor(e,t,r,a){if(super(e,{cause:a}),this.config=t,this.response=r,this.error=a instanceof Error?a:void 0,this.config=(0,n.default)(!0,{},t),this.response&&(this.response.config=(0,n.default)(!0,{},this.response.config)),this.response){try{this.response.data=i(this.config.responseType,this.response?.bodyUsed?this.response?.data:void 0)}catch{}this.status=this.response.status}a instanceof DOMException?this.code=a.name:a&&typeof a==`object`&&`code`in a&&(typeof a.code==`string`||typeof a.code==`number`)&&(this.code=a.code)}static extractAPIErrorFromResponse(e,t=`The request failed`){let n=t;if(typeof e.data==`string`&&(n=e.data),e.data&&typeof e.data==`object`&&`error`in e.data&&e.data.error&&!e.ok){if(typeof e.data.error==`string`)return{message:e.data.error,code:e.status,status:e.statusText};if(typeof e.data.error==`object`){n=`message`in e.data.error&&typeof e.data.error.message==`string`?e.data.error.message:n;let t=`status`in e.data.error&&typeof e.data.error.status==`string`?e.data.error.status:e.statusText,r=`code`in e.data.error&&typeof e.data.error.code==`number`?e.data.error.code:e.status;if(`errors`in e.data.error&&Array.isArray(e.data.error.errors)){let i=[];for(let t of e.data.error.errors)typeof t==`object`&&`message`in t&&typeof t.message==`string`&&i.push(t.message);return Object.assign({message:i.join(`
2
+ `)||n,code:r,status:t},e.data.error)}return Object.assign({message:n,code:r,status:t},e.data.error)}}return{message:n,code:e.status,status:e.statusText}}};function i(e,t){switch(e){case`stream`:return t;case`json`:return JSON.parse(JSON.stringify(t));case`arraybuffer`:return JSON.parse(Buffer.from(t).toString(`utf8`));case`blob`:return JSON.parse(t.text());default:return t}}function o(e){let t="<<REDACTED> - See `errorRedactor` option in `gaxios` for configuration>.";function n(e){e&&e.forEach((n,r)=>{(/^authentication$/i.test(r)||/^authorization$/i.test(r)||/secret/i.test(r))&&e.set(r,t)})}function r(e,n){if(typeof e==`object`&&e&&typeof e[n]==`string`){let r=e[n];(/grant_type=/i.test(r)||/assertion=/i.test(r)||/secret/i.test(r))&&(e[n]=t)}}function i(e){!e||typeof e!=`object`||(e instanceof FormData||e instanceof URLSearchParams||`forEach`in e&&`set`in e?e.forEach((n,r)=>{([`grant_type`,`assertion`].includes(r)||/secret/.test(r))&&e.set(r,t)}):(`grant_type`in e&&(e.grant_type=t),`assertion`in e&&(e.assertion=t),`client_secret`in e&&(e.client_secret=t)))}return e.config&&(n(e.config.headers),r(e.config,`data`),i(e.config.data),r(e.config,`body`),i(e.config.body),e.config.url.searchParams.has(`token`)&&e.config.url.searchParams.set(`token`,t),e.config.url.searchParams.has(`client_secret`)&&e.config.url.searchParams.set(`client_secret`,t)),e.response&&(o({config:e.response.config}),n(e.response.headers),e.response.bodyUsed&&(r(e.response,`data`),i(e.response.data))),e}})),w=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.getRetryConfig=t;async function t(e){let t=r(e);if(!e||!e.config||!t&&!e.config.retry)return{shouldRetry:!1};if(t||={},t.currentRetryAttempt=t.currentRetryAttempt||0,t.retry=t.retry===void 0||t.retry===null?3:t.retry,t.httpMethodsToRetry=t.httpMethodsToRetry||[`GET`,`HEAD`,`PUT`,`OPTIONS`,`DELETE`],t.noResponseRetries=t.noResponseRetries===void 0||t.noResponseRetries===null?2:t.noResponseRetries,t.retryDelayMultiplier=t.retryDelayMultiplier?t.retryDelayMultiplier:2,t.timeOfFirstRequest=t.timeOfFirstRequest?t.timeOfFirstRequest:Date.now(),t.totalTimeout=t.totalTimeout?t.totalTimeout:2**53-1,t.maxRetryDelay=t.maxRetryDelay?t.maxRetryDelay:2**53-1,t.statusCodesToRetry=t.statusCodesToRetry||[[100,199],[408,408],[429,429],[500,599]],e.config.retryConfig=t,!await(t.shouldRetry||n)(e))return{shouldRetry:!1,config:e.config};let a=i(t);e.config.retryConfig.currentRetryAttempt+=1;let o=t.retryBackoff?t.retryBackoff(e,a):new Promise(e=>{setTimeout(e,a)});return t.onRetryAttempt&&await t.onRetryAttempt(e),await o,{shouldRetry:!0,config:e.config}}function n(e){let t=r(e);if(e.config.signal?.aborted&&e.code!==`TimeoutError`||e.code===`AbortError`||!t||t.retry===0||!e.response&&(t.currentRetryAttempt||0)>=t.noResponseRetries||!t.httpMethodsToRetry||!t.httpMethodsToRetry.includes(e.config.method?.toUpperCase()||`GET`))return!1;if(e.response&&e.response.status){let n=!1;for(let[r,i]of t.statusCodesToRetry){let t=e.response.status;if(t>=r&&t<=i){n=!0;break}}if(!n)return!1}return t.currentRetryAttempt=t.currentRetryAttempt||0,!(t.currentRetryAttempt>=t.retry)}function r(e){if(e&&e.config&&e.config.retryConfig)return e.config.retryConfig}function i(e){let t=(e.currentRetryAttempt?0:e.retryDelay??100)+(e.retryDelayMultiplier**+e.currentRetryAttempt-1)/2*1e3,n=e.totalTimeout-(Date.now()-e.timeOfFirstRequest);return Math.min(t,n,e.maxRetryDelay)}})),T=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.GaxiosInterceptorManager=void 0,e.GaxiosInterceptorManager=class extends Set{}})),E=n((n=>{var r=n&&n.__importDefault||function(e){return e&&e.__esModule?e:{default:e}},i;Object.defineProperty(n,`__esModule`,{value:!0}),n.Gaxios=void 0;let o=r(a()),s=t(`https`),c=C(),l=w(),u=t(`stream`),d=T(),f=async()=>globalThis.crypto?.randomUUID()||(await import(`crypto`)).randomUUID();var p=class{agentCache=new Map;defaults;interceptors;constructor(e){this.defaults=e||{},this.interceptors={request:new d.GaxiosInterceptorManager,response:new d.GaxiosInterceptorManager}}fetch(...e){let t=e[0],n=e[1],r,a=new Headers;return typeof t==`string`?r=new URL(t):t instanceof URL?r=t:t&&t.url&&(r=new URL(t.url)),t&&typeof t==`object`&&`headers`in t&&i.mergeHeaders(a,t.headers),n&&i.mergeHeaders(a,new Headers(n.headers)),typeof t==`object`&&!(t instanceof URL)?this.request({...n,...t,headers:a,url:r}):this.request({...n,headers:a,url:r})}async request(e={}){let t=await this.#r(e);return t=await this.#t(t),this.#n(this._request(t))}async _defaultAdapter(e){let t=e.fetchImplementation||this.defaults.fetchImplementation||await i.#c(),n={...e};delete n.data;let r=await t(e.url,n),a=await this.getResponseData(e,r);return Object.getOwnPropertyDescriptor(r,`data`)?.configurable||Object.defineProperties(r,{data:{configurable:!0,writable:!0,enumerable:!0,value:a}}),Object.assign(r,{config:e,data:a})}async _request(e){try{let t;if(t=e.adapter?await e.adapter(e,this._defaultAdapter.bind(this)):await this._defaultAdapter(e),!e.validateStatus(t.status)){if(e.responseType===`stream`){let e=[];for await(let n of t.data)e.push(n);t.data=e.toString()}let n=c.GaxiosError.extractAPIErrorFromResponse(t,`Request failed with status code ${t.status}`);throw new c.GaxiosError(n?.message,e,t,n)}return t}catch(t){let n;n=t instanceof c.GaxiosError?t:t instanceof Error?new c.GaxiosError(t.message,e,void 0,t):new c.GaxiosError(`Unexpected Gaxios Error`,e,void 0,t);let{shouldRetry:r,config:i}=await(0,l.getRetryConfig)(n);if(r&&i)return n.config.retryConfig.currentRetryAttempt=i.retryConfig.currentRetryAttempt,e.retryConfig=n.config?.retryConfig,this.#i(e),this._request(e);throw e.errorRedactor&&e.errorRedactor(n),n}}async getResponseData(e,t){if(t.status===204)return``;if(e.maxContentLength&&t.headers.has(`content-length`)&&e.maxContentLength<Number.parseInt(t.headers?.get(`content-length`)||``))throw new c.GaxiosError("Response's `Content-Length` is over the limit.",e,Object.assign(t,{config:e}));switch(e.responseType){case`stream`:return t.body;case`json`:{let e=await t.text();try{return JSON.parse(e)}catch{return e}}case`arraybuffer`:return t.arrayBuffer();case`blob`:return t.blob();case`text`:return t.text();default:return this.getResponseDataFromContentType(t)}}#e(e,t=[]){let n=new URL(e),r=[...t],i=(process.env.NO_PROXY??process.env.no_proxy)?.split(`,`)||[];for(let e of i)r.push(e.trim());for(let e of r)if(e instanceof RegExp){if(e.test(n.toString()))return!1}else if(e instanceof URL){if(e.origin===n.origin)return!1}else if(e.startsWith(`*.`)||e.startsWith(`.`)){let t=e.replace(/^\*\./,`.`);if(n.hostname.endsWith(t))return!1}else if(e===n.origin||e===n.hostname||e===n.href)return!1;return!0}async#t(e){let t=Promise.resolve(e);for(let e of this.interceptors.request.values())e&&(t=t.then(e.resolved,e.rejected));return t}async#n(e){let t=Promise.resolve(e);for(let e of this.interceptors.response.values())e&&(t=t.then(e.resolved,e.rejected));return t}async#r(e){let t=new Headers(this.defaults.headers);i.mergeHeaders(t,e.headers);let n=(0,o.default)(!0,{},this.defaults,e);if(!n.url)throw Error(`URL is required.`);if(n.baseURL&&(n.url=new URL(n.url,n.baseURL)),n.url=new URL(n.url),n.params)if(n.paramsSerializer){let e=n.paramsSerializer(n.params);e.startsWith(`?`)&&(e=e.slice(1));let t=n.url.toString().includes(`?`)?`&`:`?`;n.url=n.url+t+e}else{let e=n.url instanceof URL?n.url:new URL(n.url);for(let[t,r]of new URLSearchParams(n.params))e.searchParams.append(t,r);n.url=e}typeof e.maxContentLength==`number`&&(n.size=e.maxContentLength),typeof e.maxRedirects==`number`&&(n.follow=e.maxRedirects);let r=typeof n.data==`string`||n.data instanceof ArrayBuffer||n.data instanceof Blob||globalThis.File&&n.data instanceof File||n.data instanceof FormData||n.data instanceof u.Readable||n.data instanceof ReadableStream||n.data instanceof String||n.data instanceof URLSearchParams||ArrayBuffer.isView(n.data)||[`Blob`,`File`,`FormData`].includes(n.data?.constructor?.name||``);if(n.multipart?.length){let e=await f();t.set(`content-type`,`multipart/related; boundary=${e}`),n.body=u.Readable.from(this.getMultipartRequest(n.multipart,e))}else r?n.body=n.data:typeof n.data==`object`?t.get(`Content-Type`)===`application/x-www-form-urlencoded`?n.body=n.paramsSerializer?n.paramsSerializer(n.data):new URLSearchParams(n.data):(t.has(`content-type`)||t.set(`content-type`,`application/json`),n.body=JSON.stringify(n.data)):n.data&&(n.body=n.data);n.validateStatus=n.validateStatus||this.validateStatus,n.responseType=n.responseType||`unknown`,!t.has(`accept`)&&n.responseType===`json`&&t.set(`accept`,`application/json`);let a=n.proxy||process?.env?.HTTPS_PROXY||process?.env?.https_proxy||process?.env?.HTTP_PROXY||process?.env?.http_proxy;if(!n.agent)if(a&&this.#e(n.url,n.noProxy)){let e=await i.#s();this.agentCache.has(a)?n.agent=this.agentCache.get(a):(n.agent=new e(a,{cert:n.cert,key:n.key}),this.agentCache.set(a,n.agent))}else n.cert&&n.key&&(this.agentCache.has(n.key)?n.agent=this.agentCache.get(n.key):(n.agent=new s.Agent({cert:n.cert,key:n.key}),this.agentCache.set(n.key,n.agent)));return typeof n.errorRedactor!=`function`&&n.errorRedactor!==!1&&(n.errorRedactor=c.defaultErrorRedactor),n.body&&!(`duplex`in n)&&(n.duplex=`half`),this.#i(n),Object.assign(n,{headers:t,url:n.url instanceof URL?n.url:new URL(n.url)})}#i(e){if(e.timeout){let t=AbortSignal.timeout(e.timeout);e.signal&&!e.signal.aborted?e.signal=AbortSignal.any([e.signal,t]):e.signal=t}}validateStatus(e){return e>=200&&e<300}async getResponseDataFromContentType(e){let t=e.headers.get(`Content-Type`);if(t===null)return e.text();if(t=t.toLowerCase(),t.includes(`application/json`)){let t=await e.text();try{t=JSON.parse(t)}catch{}return t}else if(t.match(/^text\//))return e.text();else return e.blob()}async*getMultipartRequest(e,t){let n=`--${t}--`;for(let n of e)yield`--${t}\r\nContent-Type: ${n.headers.get(`Content-Type`)||`application/octet-stream`}\r\n\r\n`,typeof n.content==`string`?yield n.content:yield*n.content,yield`\r
3
+ `;yield n}static#a;static#o;static async#s(){return this.#a||=(await import(`./dist-coestTs9.mjs`).then(t=>e(t.t()))).HttpsProxyAgent,this.#a}static async#c(){let e=typeof window<`u`&&!!window;return this.#o||=e?window.fetch:(await import(`./src-CCDx_C-U.mjs`)).default,this.#o}static mergeHeaders(e,...t){e=e instanceof Headers?e:new Headers(e);for(let n of t)(n instanceof Headers?n:new Headers(n)).forEach((t,n)=>{n===`set-cookie`?e.append(n,t):e.set(n,t)});return e}};n.Gaxios=p,i=p})),D=n((e=>{var t=e&&e.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);(!i||(`get`in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),n=e&&e.__exportStar||function(e,n){for(var r in e)r!==`default`&&!Object.prototype.hasOwnProperty.call(n,r)&&t(n,e,r)};Object.defineProperty(e,`__esModule`,{value:!0}),e.instance=e.Gaxios=e.GaxiosError=void 0,e.request=a;let r=E();Object.defineProperty(e,`Gaxios`,{enumerable:!0,get:function(){return r.Gaxios}});var i=C();Object.defineProperty(e,`GaxiosError`,{enumerable:!0,get:function(){return i.GaxiosError}}),n(T(),e),e.instance=new r.Gaxios;async function a(t){return e.instance.request(t)}})),O=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.GCE_LINUX_BIOS_PATHS=void 0,e.isGoogleCloudServerless=a,e.isGoogleComputeEngineLinux=o,e.isGoogleComputeEngineMACAddress=s,e.isGoogleComputeEngine=c,e.detectGCPResidency=l;let n=t(`fs`),r=t(`os`);e.GCE_LINUX_BIOS_PATHS={BIOS_DATE:`/sys/class/dmi/id/bios_date`,BIOS_VENDOR:`/sys/class/dmi/id/bios_vendor`};let i=/^42:01/;function a(){return!!(process.env.CLOUD_RUN_JOB||process.env.FUNCTION_NAME||process.env.K_SERVICE)}function o(){if((0,r.platform)()!==`linux`)return!1;try{(0,n.statSync)(e.GCE_LINUX_BIOS_PATHS.BIOS_DATE);let t=(0,n.readFileSync)(e.GCE_LINUX_BIOS_PATHS.BIOS_VENDOR,`utf8`);return/Google/.test(t)}catch{return!1}}function s(){let e=(0,r.networkInterfaces)();for(let t of Object.values(e))if(t){for(let{mac:e}of t)if(i.test(e))return!0}return!1}function c(){return o()||s()}function l(){return a()||c()}})),k=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.Colours=void 0;var t=class e{static isEnabled(e){return e&&e.isTTY&&(typeof e.getColorDepth==`function`?e.getColorDepth()>2:!0)}static refresh(){e.enabled=e.isEnabled(process==null?void 0:process.stderr),this.enabled?(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`):(e.reset=``,e.bright=``,e.dim=``,e.red=``,e.green=``,e.yellow=``,e.blue=``,e.magenta=``,e.cyan=``,e.white=``,e.grey=``)}};e.Colours=t,t.enabled=!1,t.reset=``,t.bright=``,t.dim=``,t.red=``,t.green=``,t.yellow=``,t.blue=``,t.magenta=``,t.cyan=``,t.white=``,t.grey=``,t.refresh()})),ee=n((e=>{var n=e&&e.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);(!i||(`get`in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),r=e&&e.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,`default`,{enumerable:!0,value:t})}):function(e,t){e.default=t}),i=e&&e.__importStar||(function(){var e=function(t){return e=Object.getOwnPropertyNames||function(e){var t=[];for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[t.length]=n);return t},e(t)};return function(t){if(t&&t.__esModule)return t;var i={};if(t!=null)for(var a=e(t),o=0;o<a.length;o++)a[o]!==`default`&&n(i,t,a[o]);return r(i,t),i}})();Object.defineProperty(e,`__esModule`,{value:!0}),e.env=e.DebugLogBackendBase=e.placeholder=e.AdhocDebugLogger=e.LogSeverity=void 0,e.getNodeBackend=p,e.getDebugBackend=h,e.getStructuredBackend=_,e.setBackend=b,e.log=x;let a=t(`events`),o=i(t(`process`)),s=i(t(`util`)),c=k();var l;(function(e){e.DEFAULT=`DEFAULT`,e.DEBUG=`DEBUG`,e.INFO=`INFO`,e.WARNING=`WARNING`,e.ERROR=`ERROR`})(l||(e.LogSeverity=l={}));var u=class extends a.EventEmitter{constructor(e,t){super(),this.namespace=e,this.upstream=t,this.func=Object.assign(this.invoke.bind(this),{instance:this,on:(e,t)=>this.on(e,t)}),this.func.debug=(...e)=>this.invokeSeverity(l.DEBUG,...e),this.func.info=(...e)=>this.invokeSeverity(l.INFO,...e),this.func.warn=(...e)=>this.invokeSeverity(l.WARNING,...e),this.func.error=(...e)=>this.invokeSeverity(l.ERROR,...e),this.func.sublog=e=>x(e,this.func)}invoke(e,...t){if(this.upstream)try{this.upstream(e,...t)}catch{}try{this.emit(`log`,e,t)}catch{}}invokeSeverity(e,...t){this.invoke({severity:e},...t)}};e.AdhocDebugLogger=u,e.placeholder=new u(``,()=>{}).func;var d=class{constructor(){this.cached=new Map,this.filters=[],this.filtersSet=!1;let t=o.env[e.env.nodeEnables]??`*`;t===`all`&&(t=`*`),this.filters=t.split(`,`)}log(e,t,...n){try{this.filtersSet||=(this.setFilters(),!0);let r=this.cached.get(e);r||(r=this.makeLogger(e),this.cached.set(e,r)),r(t,...n)}catch(e){console.error(e)}}};e.DebugLogBackendBase=d;var f=class extends d{constructor(){super(...arguments),this.enabledRegexp=/.*/g}isEnabled(e){return this.enabledRegexp.test(e)}makeLogger(e){return this.enabledRegexp.test(e)?(t,...n)=>{let r=`${c.Colours.green}${e}${c.Colours.reset}`,i=`${c.Colours.yellow}${o.pid}${c.Colours.reset}`,a;switch(t.severity){case l.ERROR:a=`${c.Colours.red}${t.severity}${c.Colours.reset}`;break;case l.INFO:a=`${c.Colours.magenta}${t.severity}${c.Colours.reset}`;break;case l.WARNING:a=`${c.Colours.yellow}${t.severity}${c.Colours.reset}`;break;default:a=t.severity??l.DEFAULT;break}let u=s.formatWithOptions({colors:c.Colours.enabled},...n),d=Object.assign({},t);delete d.severity;let f=Object.getOwnPropertyNames(d).length?JSON.stringify(d):``,p=f?`${c.Colours.grey}${f}${c.Colours.reset}`:``;console.error(`%s [%s|%s] %s%s`,i,r,a,u,f?` ${p}`:``)}:()=>{}}setFilters(){let e=this.filters.join(`,`).replace(/[|\\{}()[\]^$+?.]/g,`\\$&`).replace(/\*/g,`.*`).replace(/,/g,`$|^`);this.enabledRegexp=RegExp(`^${e}$`,`i`)}};function p(){return new f}var m=class extends d{constructor(e){super(),this.debugPkg=e}makeLogger(e){let t=this.debugPkg(e);return(e,...n)=>{t(n[0],...n.slice(1))}}setFilters(){let e=o.env.NODE_DEBUG??``;o.env.NODE_DEBUG=`${e}${e?`,`:``}${this.filters.join(`,`)}`}};function h(e){return new m(e)}var g=class extends d{constructor(e){super(),this.upstream=e??void 0}makeLogger(e){let t=this.upstream?.makeLogger(e);return(e,...n)=>{let r=e.severity??l.INFO,i=Object.assign({severity:r,message:s.format(...n)},e),a=JSON.stringify(i);t?t(e,a):console.log(`%s`,a)}}setFilters(){var e;(e=this.upstream)==null||e.setFilters()}};function _(e){return new g(e)}e.env={nodeEnables:`GOOGLE_SDK_NODE_LOGGING`};let v=new Map,y;function b(e){y=e,v.clear()}function x(t,n){if(!y&&!o.env[e.env.nodeEnables]||!t)return e.placeholder;n&&(t=`${n.instance.namespace}:${t}`);let r=v.get(t);if(r)return r.func;if(y===null)return e.placeholder;y===void 0&&(y=p());let i=(()=>{let e;return new u(t,(n,...r)=>{if(e!==y){if(y===null)return;y===void 0&&(y=p()),e=y}y?.log(t,n,...r)})})();return v.set(t,i),i.func}})),te=n((e=>{var t=e&&e.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);(!i||(`get`in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),n=e&&e.__exportStar||function(e,n){for(var r in e)r!==`default`&&!Object.prototype.hasOwnProperty.call(n,r)&&t(n,e,r)};Object.defineProperty(e,`__esModule`,{value:!0}),n(ee(),e)})),A=n((e=>{var t=e&&e.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);(!i||(`get`in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),n=e&&e.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,`default`,{enumerable:!0,value:t})}):function(e,t){e.default=t}),r=e&&e.__importStar||(function(){var e=function(t){return e=Object.getOwnPropertyNames||function(e){var t=[];for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[t.length]=n);return t},e(t)};return function(r){if(r&&r.__esModule)return r;var i={};if(r!=null)for(var a=e(r),o=0;o<a.length;o++)a[o]!==`default`&&t(i,r,a[o]);return n(i,r),i}})(),i=e&&e.__exportStar||function(e,n){for(var r in e)r!==`default`&&!Object.prototype.hasOwnProperty.call(n,r)&&t(n,e,r)};Object.defineProperty(e,`__esModule`,{value:!0}),e.gcpResidencyCache=e.METADATA_SERVER_DETECTION=e.HEADERS=e.HEADER_VALUE=e.HEADER_NAME=e.SECONDARY_HOST_ADDRESS=e.HOST_ADDRESS=e.BASE_PATH=void 0,e.instance=h,e.project=g,e.universe=_,e.bulk=v,e.isAvailable=x,e.resetIsAvailableCache=S,e.getGCPResidency=C,e.setGCPResidency=w,e.requestTimeout=T;let a=D(),s=o(),c=O(),l=r(te());e.BASE_PATH=`/computeMetadata/v1`,e.HOST_ADDRESS=`http://169.254.169.254`,e.SECONDARY_HOST_ADDRESS=`http://metadata.google.internal.`,e.HEADER_NAME=`Metadata-Flavor`,e.HEADER_VALUE=`Google`,e.HEADERS=Object.freeze({[e.HEADER_NAME]:e.HEADER_VALUE});let u=l.log(`gcp-metadata`);e.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 d(t){return t||=process.env.GCE_METADATA_IP||process.env.GCE_METADATA_HOST||e.HOST_ADDRESS,/^https?:\/\//.test(t)||(t=`http://${t}`),new URL(e.BASE_PATH,t).href}function f(e){Object.keys(e).forEach(e=>{switch(e){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(`'${e}' is not a valid configuration option.`)}})}async function p(t,n={},r=3,i=!1){let o=new Headers(e.HEADERS),c=``,l={};if(typeof t==`object`){let e=t;new Headers(e.headers).forEach((e,t)=>o.set(t,e)),c=e.metadataKey,l=e.params||l,r=e.noResponseRetries||r,i=e.fastFail||i}else c=t;typeof n==`string`?c+=`/${n}`:(f(n),n.property&&(c+=`/${n.property}`),new Headers(n.headers).forEach((e,t)=>o.set(t,e)),l=n.params||l);let p=i?m:a.request,h={url:`${d()}/${c}`,headers:o,retryConfig:{noResponseRetries:r},params:l,responseType:`text`,timeout:T()};u.info(`instance request %j`,h);let g=await p(h);u.info(`instance metadata is %s`,g.data);let _=g.headers.get(e.HEADER_NAME);if(_!==e.HEADER_VALUE)throw RangeError(`Invalid response from metadata service: incorrect ${e.HEADER_NAME} header. Expected '${e.HEADER_VALUE}', got ${_?`'${_}'`:`no header`}`);if(typeof g.data==`string`)try{return s.parse(g.data)}catch{}return g.data}async function m(t){let n={...t,url:t.url?.toString().replace(d(),d(e.SECONDARY_HOST_ADDRESS))},r=(0,a.request)(t),i=(0,a.request)(n);return Promise.any([r,i])}function h(e){return p(`instance`,e)}function g(e){return p(`project`,e)}function _(e){return p(`universe`,e)}async function v(e){let t={};return await Promise.all(e.map(e=>(async()=>{let n=await p(e),r=e.metadataKey;t[r]=n})())),t}function y(){return process.env.DETECT_GCP_RETRIES?Number(process.env.DETECT_GCP_RETRIES):0}let b;async function x(){if(process.env.METADATA_SERVER_DETECTION){let t=process.env.METADATA_SERVER_DETECTION.trim().toLocaleLowerCase();if(!(t in e.METADATA_SERVER_DETECTION))throw RangeError(`Unknown \`METADATA_SERVER_DETECTION\` env variable. Got \`${t}\`, but it should be \`${Object.keys(e.METADATA_SERVER_DETECTION).join("`, `")}\`, or unset`);switch(t){case`assume-present`:return!0;case`none`:return!1;case`bios-only`:return C();case`ping-only`:}}try{return b===void 0&&(b=p(`instance`,void 0,y(),!(process.env.GCE_METADATA_IP||process.env.GCE_METADATA_HOST))),await b,!0}catch(e){let t=e;if(process.env.DEBUG_AUTH&&console.info(t),t.type===`request-timeout`||t.response&&t.response.status===404)return!1;if(!(t.response&&t.response.status===404)&&(!t.code||![`EHOSTDOWN`,`EHOSTUNREACH`,`ENETUNREACH`,`ENOENT`,`ENOTFOUND`,`ECONNREFUSED`].includes(t.code.toString()))){let e=`UNKNOWN`;t.code&&(e=t.code.toString()),process.emitWarning(`received unexpected error = ${t.message} code = ${e}`,`MetadataLookupWarning`)}return!1}}function S(){b=void 0}e.gcpResidencyCache=null;function C(){return e.gcpResidencyCache===null&&w(),e.gcpResidencyCache}function w(t=null){e.gcpResidencyCache=t===null?(0,c.detectGCPResidency)():t}function T(){return C()?0:3e3}i(O(),e)})),ne=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.fromArrayBufferToHex=t;function t(e){return Array.from(new Uint8Array(e)).map(e=>e.toString(16).padStart(2,`0`)).join(``)}})),re=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.BrowserCrypto=void 0;let t=c(),n=ne();e.BrowserCrypto=class e{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(e){let n=new TextEncoder().encode(e),r=await window.crypto.subtle.digest(`SHA-256`,n);return t.fromByteArray(new Uint8Array(r))}randomBytesBase64(e){let n=new Uint8Array(e);return window.crypto.getRandomValues(n),t.fromByteArray(n)}static padBase64(e){for(;e.length%4!=0;)e+=`=`;return e}async verify(n,r,i){let a={name:`RSASSA-PKCS1-v1_5`,hash:{name:`SHA-256`}},o=new TextEncoder().encode(r),s=t.toByteArray(e.padBase64(i)),c=await window.crypto.subtle.importKey(`jwk`,n,a,!0,[`verify`]);return await window.crypto.subtle.verify(a,c,Buffer.from(s),o)}async sign(e,n){let r={name:`RSASSA-PKCS1-v1_5`,hash:{name:`SHA-256`}},i=new TextEncoder().encode(n),a=await window.crypto.subtle.importKey(`jwk`,e,r,!0,[`sign`]),o=await window.crypto.subtle.sign(r,a,i);return t.fromByteArray(new Uint8Array(o))}decodeBase64StringUtf8(n){let r=t.toByteArray(e.padBase64(n));return new TextDecoder().decode(r)}encodeBase64StringUtf8(e){let n=new TextEncoder().encode(e);return t.fromByteArray(n)}async sha256DigestHex(e){let t=new TextEncoder().encode(e),r=await window.crypto.subtle.digest(`SHA-256`,t);return(0,n.fromArrayBufferToHex)(r)}async signWithHmacSha256(e,t){let n=typeof e==`string`?e:String.fromCharCode(...new Uint16Array(e)),r=new TextEncoder,i=await window.crypto.subtle.importKey(`raw`,r.encode(n),{name:`HMAC`,hash:{name:`SHA-256`}},!1,[`sign`]);return window.crypto.subtle.sign(`HMAC`,i,r.encode(t))}}})),ie=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.NodeCrypto=void 0;let n=t(`crypto`);e.NodeCrypto=class{async sha256DigestBase64(e){return n.createHash(`sha256`).update(e).digest(`base64`)}randomBytesBase64(e){return n.randomBytes(e).toString(`base64`)}async verify(e,t,r){let i=n.createVerify(`RSA-SHA256`);return i.update(t),i.end(),i.verify(e,r,`base64`)}async sign(e,t){let r=n.createSign(`RSA-SHA256`);return r.update(t),r.end(),r.sign(e,`base64`)}decodeBase64StringUtf8(e){return Buffer.from(e,`base64`).toString(`utf-8`)}encodeBase64StringUtf8(e){return Buffer.from(e,`utf-8`).toString(`base64`)}async sha256DigestHex(e){return n.createHash(`sha256`).update(e).digest(`hex`)}async signWithHmacSha256(e,t){let a=typeof e==`string`?e:i(e);return r(n.createHmac(`sha256`,a).update(t).digest())}};function r(e){let t=new ArrayBuffer(e.length),n=new Uint8Array(t);for(let t=0;t<e.length;++t)n[t]=e[t];return t}function i(e){return Buffer.from(e)}})),ae=n((e=>{var t=e&&e.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);(!i||(`get`in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),n=e&&e.__exportStar||function(e,n){for(var r in e)r!==`default`&&!Object.prototype.hasOwnProperty.call(n,r)&&t(n,e,r)};Object.defineProperty(e,`__esModule`,{value:!0}),e.createCrypto=a,e.hasBrowserCrypto=o;let r=re(),i=ie();n(ne(),e);function a(){return o()?new r.BrowserCrypto:new i.NodeCrypto}function o(){return typeof window<`u`&&window.crypto!==void 0&&window.crypto.subtle!==void 0}})),j=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.LRUCache=void 0,e.snakeToCamel=o,e.originalOrCamelOptions=s,e.removeUndefinedValuesInObject=c,e.isValidFile=l,e.getWellKnownCertificateConfigFileLocation=u;let n=t(`fs`),r=t(`os`),i=t(`path`),a=`gcloud`;function o(e){return e.replace(/([_][^_])/g,e=>e.slice(1).toUpperCase())}function s(e){function t(t){let n=e||{};return n[t]??n[o(t)]}return{get:t}}e.LRUCache=class{capacity;#e=new Map;maxAge;constructor(e){this.capacity=e.capacity,this.maxAge=e.maxAge}#t(e,t){this.#e.delete(e),this.#e.set(e,{value:t,lastAccessed:Date.now()})}set(e,t){this.#t(e,t),this.#n()}get(e){let t=this.#e.get(e);if(t)return this.#t(e,t.value),this.#n(),t.value}#n(){let e=this.maxAge?Date.now()-this.maxAge:0,t=this.#e.entries().next();for(;!t.done&&(this.#e.size>this.capacity||t.value[1].lastAccessed<e);)this.#e.delete(t.value[0]),t=this.#e.entries().next()}};function c(e){return Object.entries(e).forEach(([t,n])=>{(n===void 0||n===`undefined`)&&delete e[t]}),e}async function l(e){try{return(await n.promises.lstat(e)).isFile()}catch{return!1}}function u(){let e=process.env.CLOUDSDK_CONFIG||(d()?i.join(process.env.APPDATA||``,a):i.join(process.env.HOME||``,`.config`,a));return i.join(e,`certificate_config.json`)}function d(){return r.platform().startsWith(`win`)}})),oe=n(((e,t)=>{t.exports={name:`google-auth-library`,version:`10.6.2`,author:`Google Inc.`,description:`Google APIs Authentication Client Library for Node.js`,engines:{node:`>=18`},main:`./build/src/index.js`,types:`./build/src/index.d.ts`,repository:{type:`git`,directory:`packages/google-auth-library-nodejs`,url:`https://github.com/googleapis/google-cloud-node-core.git`},keywords:[`google`,`api`,`google apis`,`client`,`client library`],dependencies:{"base64-js":`^1.3.0`,"ecdsa-sig-formatter":`^1.0.11`,gaxios:`^7.1.4`,"gcp-metadata":`8.1.2`,"google-logging-utils":`1.1.3`,jws:`^4.0.0`},devDependencies:{"@types/base64-js":`^1.2.5`,"@types/jws":`^3.1.0`,"@types/mocha":`^10.0.10`,"@types/mv":`^2.1.0`,"@types/ncp":`^2.0.8`,"@types/node":`^24.0.0`,"@types/sinon":`^21.0.0`,"assert-rejects":`^1.0.0`,c8:`^10.1.3`,codecov:`^3.8.3`,gts:`^6.0.2`,"is-docker":`^3.0.0`,jsdoc:`^4.0.4`,"jsdoc-fresh":`^5.0.0`,"jsdoc-region-tag":`^4.0.0`,karma:`^6.0.0`,"karma-chrome-launcher":`^3.0.0`,"karma-coverage":`^2.0.0`,"karma-firefox-launcher":`^2.0.0`,"karma-mocha":`^2.0.0`,"karma-sourcemap-loader":`^0.4.0`,"karma-webpack":`^5.0.1`,keypair:`^1.0.4`,mocha:`^11.1.0`,mv:`^2.1.1`,ncp:`^2.0.0`,nock:`^14.0.5`,"null-loader":`^4.0.1`,puppeteer:`^24.0.0`,sinon:`^21.0.0`,"ts-loader":`^9.5.2`,typescript:`5.8.3`,webpack:`^5.97.1`,"webpack-cli":`^6.0.1`},files:[`build/src`,`!build/src/**/*.map`],scripts:{test:`c8 mocha build/test`,clean:`gts clean`,prepare:`npm run compile`,lint:`gts check --no-inline-config`,compile:`tsc -p .`,fix:`gts fix`,pretest:`npm run compile -- --sourceMap`,docs:`jsdoc -c .jsdoc.js`,"samples-setup":`cd samples/ && npm link ../ && npm run setup && cd ../`,"samples-test":`cd samples/ && npm link ../ && npm test && cd ../`,"system-test":`mocha build/system-test --timeout 60000`,"presystem-test":`npm run compile -- --sourceMap`,webpack:`webpack`,"browser-test":`karma start`,"docs-test":`echo 'disabled until linkinator is fixed'`,"predocs-test":`npm run docs`,prelint:`cd samples; npm link ../; npm install`},license:`Apache-2.0`,homepage:`https://github.com/googleapis/google-cloud-node-core/tree/main/packages/google-auth-library-nodejs`}})),se=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.USER_AGENT=e.PRODUCT_NAME=e.pkg=void 0;let t=oe();e.pkg=t;let n=`google-api-nodejs-client`;e.PRODUCT_NAME=n,e.USER_AGENT=`${n}/${t.version}`})),M=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.AuthClient=e.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS=e.DEFAULT_UNIVERSE=void 0;let n=t(`events`),r=D(),i=j(),a=te(),o=se();e.DEFAULT_UNIVERSE=`googleapis.com`,e.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS=300*1e3,e.AuthClient=class t extends n.EventEmitter{apiKey;projectId;quotaProjectId;transporter;credentials={};eagerRefreshThresholdMillis=e.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS;forceRefreshOnFailure=!1;universeDomain=e.DEFAULT_UNIVERSE;static RequestMethodNameSymbol=Symbol(`request method name`);static RequestLogIdSymbol=Symbol(`request log id`);constructor(n={}){super();let a=(0,i.originalOrCamelOptions)(n);this.apiKey=n.apiKey,this.projectId=a.get(`project_id`)??null,this.quotaProjectId=a.get(`quota_project_id`),this.credentials=a.get(`credentials`)??{},this.universeDomain=a.get(`universe_domain`)??e.DEFAULT_UNIVERSE,this.transporter=n.transporter??new r.Gaxios(n.transporterOptions),a.get(`useAuthRequestParameters`)!==!1&&(this.transporter.interceptors.request.add(t.DEFAULT_REQUEST_INTERCEPTOR),this.transporter.interceptors.response.add(t.DEFAULT_RESPONSE_INTERCEPTOR)),n.eagerRefreshThresholdMillis&&(this.eagerRefreshThresholdMillis=n.eagerRefreshThresholdMillis),this.forceRefreshOnFailure=n.forceRefreshOnFailure??!1}fetch(...e){let t=e[0],n=e[1],i,a=new Headers;return typeof t==`string`?i=new URL(t):t instanceof URL?i=t:t&&t.url&&(i=new URL(t.url)),t&&typeof t==`object`&&`headers`in t&&r.Gaxios.mergeHeaders(a,t.headers),n&&r.Gaxios.mergeHeaders(a,new Headers(n.headers)),typeof t==`object`&&!(t instanceof URL)?this.request({...n,...t,headers:a,url:i}):this.request({...n,headers:a,url:i})}setCredentials(e){this.credentials=e}addSharedMetadataHeaders(e){return!e.has(`x-goog-user-project`)&&this.quotaProjectId&&e.set(`x-goog-user-project`,this.quotaProjectId),e}addUserProjectAndAuthHeaders(e,t){let n=t.get(`x-goog-user-project`),r=t.get(`authorization`);return n&&e.set(`x-goog-user-project`,n),r&&e.set(`authorization`,r),e}static log=(0,a.log)(`auth`);static DEFAULT_REQUEST_INTERCEPTOR={resolved:async e=>{if(!e.headers.has(`x-goog-api-client`)){let t=process.version.replace(/^v/,``);e.headers.set(`x-goog-api-client`,`gl-node/${t}`)}let n=e.headers.get(`User-Agent`);n?n.includes(`${o.PRODUCT_NAME}/`)||e.headers.set(`User-Agent`,`${n} ${o.USER_AGENT}`):e.headers.set(`User-Agent`,o.USER_AGENT);try{let n=e,r=n[t.RequestMethodNameSymbol],i=`${Math.floor(Math.random()*1e3)}`;n[t.RequestLogIdSymbol]=i;let a={url:e.url,headers:e.headers};r?t.log.info(`%s [%s] request %j`,r,i,a):t.log.info(`[%s] request %j`,i,a)}catch{}return e}};static DEFAULT_RESPONSE_INTERCEPTOR={resolved:async e=>{try{let n=e.config,r=n[t.RequestMethodNameSymbol],i=n[t.RequestLogIdSymbol];r?t.log.info(`%s [%s] response %j`,r,i,e.data):t.log.info(`[%s] response %j`,i,e.data)}catch{}return e},rejected:async e=>{try{let n=e.config,r=n[t.RequestMethodNameSymbol],i=n[t.RequestLogIdSymbol];r?t.log.info(`%s [%s] error %j`,r,i,e.response?.data):t.log.error(`[%s] error %j`,i,e.response?.data)}catch{}throw e}};static setMethodName(e,n){try{let r=e;r[t.RequestMethodNameSymbol]=n}catch{}}static get RETRY_CONFIG(){return{retry:!0,retryConfig:{httpMethodsToRetry:[`GET`,`PUT`,`POST`,`HEAD`,`OPTIONS`,`DELETE`]}}}}})),ce=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.LoginTicket=void 0,e.LoginTicket=class{envelope;payload;constructor(e,t){this.envelope=e,this.payload=t}getEnvelope(){return this.envelope}getPayload(){return this.payload}getUserId(){let e=this.getPayload();return e&&e.sub?e.sub:null}getAttributes(){return{envelope:this.getEnvelope(),payload:this.getPayload()}}}})),le=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.OAuth2Client=e.ClientAuthentication=e.CertificateFormat=e.CodeChallengeMethod=void 0;let n=D(),r=t(`querystring`),i=t(`stream`),a=s(),o=j(),c=ae(),l=M(),u=ce();var d;(function(e){e.Plain=`plain`,e.S256=`S256`})(d||(e.CodeChallengeMethod=d={}));var f;(function(e){e.PEM=`PEM`,e.JWK=`JWK`})(f||(e.CertificateFormat=f={}));var p;(function(e){e.ClientSecretPost=`ClientSecretPost`,e.ClientSecretBasic=`ClientSecretBasic`,e.None=`None`})(p||(e.ClientAuthentication=p={})),e.OAuth2Client=class e extends l.AuthClient{redirectUri;certificateCache={};certificateExpiry=null;certificateCacheFormat=f.PEM;refreshTokenPromises=new Map;endpoints;issuers;clientAuthentication;_clientId;_clientSecret;refreshHandler;constructor(e={},t,n){super(typeof e==`object`?e:{}),typeof e!=`object`&&(e={clientId:e,clientSecret:t,redirectUri:n}),this._clientId=e.clientId||e.client_id,this._clientSecret=e.clientSecret||e.client_secret,this.redirectUri=e.redirectUri||e.redirect_uris?.[0],this.endpoints={tokenInfoUrl:`https://oauth2.googleapis.com/tokeninfo`,oauth2AuthBaseUrl:`https://accounts.google.com/o/oauth2/v2/auth`,oauth2TokenUrl:`https://oauth2.googleapis.com/token`,oauth2RevokeUrl:`https://oauth2.googleapis.com/revoke`,oauth2FederatedSignonPemCertsUrl:`https://www.googleapis.com/oauth2/v1/certs`,oauth2FederatedSignonJwkCertsUrl:`https://www.googleapis.com/oauth2/v3/certs`,oauth2IapPublicKeyUrl:`https://www.gstatic.com/iap/verify/public_key`,...e.endpoints},this.clientAuthentication=e.clientAuthentication||p.ClientSecretPost,this.issuers=e.issuers||[`accounts.google.com`,`https://accounts.google.com`,this.universeDomain]}static GOOGLE_TOKEN_INFO_URL=`https://oauth2.googleapis.com/tokeninfo`;static CLOCK_SKEW_SECS_=300;static DEFAULT_MAX_TOKEN_LIFETIME_SECS_=86400;generateAuthUrl(e={}){if(e.code_challenge_method&&!e.code_challenge)throw Error(`If a code_challenge_method is provided, code_challenge must be included.`);return e.response_type=e.response_type||`code`,e.client_id=e.client_id||this._clientId,e.redirect_uri=e.redirect_uri||this.redirectUri,Array.isArray(e.scope)&&(e.scope=e.scope.join(` `)),this.endpoints.oauth2AuthBaseUrl.toString()+`?`+r.stringify(e)}generateCodeVerifier(){throw Error(`generateCodeVerifier is removed, please use generateCodeVerifierAsync instead.`)}async generateCodeVerifierAsync(){let e=(0,c.createCrypto)(),t=e.randomBytesBase64(96).replace(/\+/g,`~`).replace(/=/g,`_`).replace(/\//g,`-`);return{codeVerifier:t,codeChallenge:(await e.sha256DigestBase64(t)).split(`=`)[0].replace(/\+/g,`-`).replace(/\//g,`_`)}}getToken(e,t){let n=typeof e==`string`?{code:e}:e;if(t)this.getTokenAsync(n).then(e=>t(null,e.tokens,e.res),e=>t(e,null,e.response));else return this.getTokenAsync(n)}async getTokenAsync(t){let n=this.endpoints.oauth2TokenUrl.toString(),r=new Headers,i={client_id:t.client_id||this._clientId,code_verifier:t.codeVerifier,code:t.code,grant_type:`authorization_code`,redirect_uri:t.redirect_uri||this.redirectUri};if(this.clientAuthentication===p.ClientSecretBasic){let e=Buffer.from(`${this._clientId}:${this._clientSecret}`);r.set(`authorization`,`Basic ${e.toString(`base64`)}`)}this.clientAuthentication===p.ClientSecretPost&&(i.client_secret=this._clientSecret);let a={...e.RETRY_CONFIG,method:`POST`,url:n,data:new URLSearchParams((0,o.removeUndefinedValuesInObject)(i)),headers:r};l.AuthClient.setMethodName(a,`getTokenAsync`);let s=await this.transporter.request(a),c=s.data;return s.data&&s.data.expires_in&&(c.expiry_date=new Date().getTime()+s.data.expires_in*1e3,delete c.expires_in),this.emit(`tokens`,c),{tokens:c,res:s}}async refreshToken(e){if(!e)return this.refreshTokenNoCache(e);if(this.refreshTokenPromises.has(e))return this.refreshTokenPromises.get(e);let t=this.refreshTokenNoCache(e).then(t=>(this.refreshTokenPromises.delete(e),t),t=>{throw this.refreshTokenPromises.delete(e),t});return this.refreshTokenPromises.set(e,t),t}async refreshTokenNoCache(t){if(!t)throw Error(`No refresh token is set.`);let r=this.endpoints.oauth2TokenUrl.toString(),i={refresh_token:t,client_id:this._clientId,client_secret:this._clientSecret,grant_type:`refresh_token`},a;try{let t={...e.RETRY_CONFIG,method:`POST`,url:r,data:new URLSearchParams((0,o.removeUndefinedValuesInObject)(i))};l.AuthClient.setMethodName(t,`refreshTokenNoCache`),a=await this.transporter.request(t)}catch(e){throw e instanceof n.GaxiosError&&e.message===`invalid_grant`&&e.response?.data&&/ReAuth/i.test(e.response.data.error_description)&&(e.message=JSON.stringify(e.response.data)),e}let s=a.data;return a.data&&a.data.expires_in&&(s.expiry_date=new Date().getTime()+a.data.expires_in*1e3,delete s.expires_in),this.emit(`tokens`,s),{tokens:s,res:a}}refreshAccessToken(e){if(e)this.refreshAccessTokenAsync().then(t=>e(null,t.credentials,t.res),e);else return this.refreshAccessTokenAsync()}async refreshAccessTokenAsync(){let e=await this.refreshToken(this.credentials.refresh_token),t=e.tokens;return t.refresh_token=this.credentials.refresh_token,this.credentials=t,{credentials:this.credentials,res:e.res}}getAccessToken(e){if(e)this.getAccessTokenAsync().then(t=>e(null,t.token,t.res),e);else return this.getAccessTokenAsync()}async getAccessTokenAsync(){if(!this.credentials.access_token||this.isTokenExpiring()){if(!this.credentials.refresh_token)if(this.refreshHandler){let e=await this.processAndValidateRefreshHandler();if(e?.access_token)return this.setCredentials(e),{token:this.credentials.access_token}}else throw Error(`No refresh token or refresh handler callback is set.`);let e=await this.refreshAccessTokenAsync();if(!e.credentials||e.credentials&&!e.credentials.access_token)throw Error(`Could not refresh access token.`);return{token:e.credentials.access_token,res:e.res}}else return{token:this.credentials.access_token}}async getRequestHeaders(e){return(await this.getRequestMetadataAsync(e)).headers}async getRequestMetadataAsync(e){let t=this.credentials;if(!t.access_token&&!t.refresh_token&&!this.apiKey&&!this.refreshHandler)throw Error(`No access, refresh token, API key or refresh handler callback is set.`);if(t.access_token&&!this.isTokenExpiring()){t.token_type=t.token_type||`Bearer`;let e=new Headers({authorization:t.token_type+` `+t.access_token});return{headers:this.addSharedMetadataHeaders(e)}}if(this.refreshHandler){let e=await this.processAndValidateRefreshHandler();if(e?.access_token){this.setCredentials(e);let t=new Headers({authorization:`Bearer `+this.credentials.access_token});return{headers:this.addSharedMetadataHeaders(t)}}}if(this.apiKey)return{headers:new Headers({"X-Goog-Api-Key":this.apiKey})};let n=null,r=null;try{n=await this.refreshToken(t.refresh_token),r=n.tokens}catch(e){let t=e;throw t.response&&(t.response.status===403||t.response.status===404)&&(t.message=`Could not refresh access token: ${t.message}`),t}let i=this.credentials;i.token_type=i.token_type||`Bearer`,r.refresh_token=i.refresh_token,this.credentials=r;let a=new Headers({authorization:i.token_type+` `+r.access_token});return{headers:this.addSharedMetadataHeaders(a),res:n.res}}static getRevokeTokenUrl(t){return new e().getRevokeTokenURL(t).toString()}getRevokeTokenURL(e){let t=new URL(this.endpoints.oauth2RevokeUrl);return t.searchParams.append(`token`,e),t}revokeToken(t,n){let r={...e.RETRY_CONFIG,url:this.getRevokeTokenURL(t).toString(),method:`POST`};if(l.AuthClient.setMethodName(r,`revokeToken`),n)this.transporter.request(r).then(e=>n(null,e),n);else return this.transporter.request(r)}revokeCredentials(e){if(e)this.revokeCredentialsAsync().then(t=>e(null,t),e);else return this.revokeCredentialsAsync()}async revokeCredentialsAsync(){let e=this.credentials.access_token;if(this.credentials={},e)return this.revokeToken(e);throw Error(`No access token to revoke.`)}request(e,t){if(t)this.requestAsync(e).then(e=>t(null,e),e=>t(e,e.response));else return this.requestAsync(e)}async requestAsync(e,t=!1){try{let t=await this.getRequestMetadataAsync();return e.headers=n.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,t.headers),this.apiKey&&e.headers.set(`X-Goog-Api-Key`,this.apiKey),await this.transporter.request(e)}catch(n){let r=n.response;if(r){let n=r.status,a=this.credentials&&this.credentials.access_token&&this.credentials.refresh_token&&(!this.credentials.expiry_date||this.forceRefreshOnFailure),o=this.credentials&&this.credentials.access_token&&!this.credentials.refresh_token&&(!this.credentials.expiry_date||this.forceRefreshOnFailure)&&this.refreshHandler,s=r.config.data instanceof i.Readable,c=n===401||n===403;if(!t&&c&&!s&&a)return await this.refreshAccessTokenAsync(),this.requestAsync(e,!0);if(!t&&c&&!s&&o){let t=await this.processAndValidateRefreshHandler();return t?.access_token&&this.setCredentials(t),this.requestAsync(e,!0)}}throw n}}verifyIdToken(e,t){if(t&&typeof t!=`function`)throw Error(`This method accepts an options object as the first parameter, which includes the idToken, audience, and maxExpiry.`);if(t)this.verifyIdTokenAsync(e).then(e=>t(null,e),t);else return this.verifyIdTokenAsync(e)}async verifyIdTokenAsync(e){if(!e.idToken)throw Error(`The verifyIdToken method requires an ID Token`);let t=await this.getFederatedSignonCertsAsync();return await this.verifySignedJwtWithCertsAsync(e.idToken,t.certs,e.audience,this.issuers,e.maxExpiry)}async getTokenInfo(t){let{data:n}=await this.transporter.request({...e.RETRY_CONFIG,method:`POST`,headers:{"content-type":`application/x-www-form-urlencoded;charset=UTF-8`,authorization:`Bearer ${t}`},url:this.endpoints.tokenInfoUrl.toString()}),r=Object.assign({expiry_date:new Date().getTime()+n.expires_in*1e3,scopes:n.scope.split(` `)},n);return delete r.expires_in,delete r.scope,r}getFederatedSignonCerts(e){if(e)this.getFederatedSignonCertsAsync().then(t=>e(null,t.certs,t.res),e);else return this.getFederatedSignonCertsAsync()}async getFederatedSignonCertsAsync(){let t=new Date().getTime(),n=(0,c.hasBrowserCrypto)()?f.JWK:f.PEM;if(this.certificateExpiry&&t<this.certificateExpiry.getTime()&&this.certificateCacheFormat===n)return{certs:this.certificateCache,format:n};let r,i;switch(n){case f.PEM:i=this.endpoints.oauth2FederatedSignonPemCertsUrl.toString();break;case f.JWK:i=this.endpoints.oauth2FederatedSignonJwkCertsUrl.toString();break;default:throw Error(`Unsupported certificate format ${n}`)}try{let t={...e.RETRY_CONFIG,url:i};l.AuthClient.setMethodName(t,`getFederatedSignonCertsAsync`),r=await this.transporter.request(t)}catch(e){throw e instanceof Error&&(e.message=`Failed to retrieve verification certificates: ${e.message}`),e}let a=r?.headers.get(`cache-control`),o=-1;if(a){let e=/max-age=(?<maxAge>[0-9]+)/.exec(a)?.groups?.maxAge;e&&(o=Number(e)*1e3)}let s={};switch(n){case f.PEM:s=r.data;break;case f.JWK:for(let e of r.data.keys)s[e.kid]=e;break;default:throw Error(`Unsupported certificate format ${n}`)}let u=new Date;return this.certificateExpiry=o===-1?null:new Date(u.getTime()+o),this.certificateCache=s,this.certificateCacheFormat=n,{certs:s,format:n,res:r}}getIapPublicKeys(e){if(e)this.getIapPublicKeysAsync().then(t=>e(null,t.pubkeys,t.res),e);else return this.getIapPublicKeysAsync()}async getIapPublicKeysAsync(){let t,n=this.endpoints.oauth2IapPublicKeyUrl.toString();try{let r={...e.RETRY_CONFIG,url:n};l.AuthClient.setMethodName(r,`getIapPublicKeysAsync`),t=await this.transporter.request(r)}catch(e){throw e instanceof Error&&(e.message=`Failed to retrieve verification certificates: ${e.message}`),e}return{pubkeys:t.data,res:t}}verifySignedJwtWithCerts(){throw Error(`verifySignedJwtWithCerts is removed, please use verifySignedJwtWithCertsAsync instead.`)}async verifySignedJwtWithCertsAsync(t,n,r,i,o){let s=(0,c.createCrypto)();o||=e.DEFAULT_MAX_TOKEN_LIFETIME_SECS_;let l=t.split(`.`);if(l.length!==3)throw Error(`Wrong number of segments in token: `+t);let d=l[0]+`.`+l[1],f=l[2],p,m;try{p=JSON.parse(s.decodeBase64StringUtf8(l[0]))}catch(e){throw e instanceof Error&&(e.message=`Can't parse token envelope: ${l[0]}': ${e.message}`),e}if(!p)throw Error(`Can't parse token envelope: `+l[0]);try{m=JSON.parse(s.decodeBase64StringUtf8(l[1]))}catch(e){throw e instanceof Error&&(e.message=`Can't parse token payload '${l[0]}`),e}if(!m)throw Error(`Can't parse token payload: `+l[1]);if(!Object.prototype.hasOwnProperty.call(n,p.kid))throw Error(`No pem found for envelope: `+JSON.stringify(p));let h=n[p.kid];if(p.alg===`ES256`&&(f=a.joseToDer(f,`ES256`).toString(`base64`)),!await s.verify(h,d,f))throw Error(`Invalid token signature: `+t);if(!m.iat)throw Error(`No issue time in token: `+JSON.stringify(m));if(!m.exp)throw Error(`No expiration time in token: `+JSON.stringify(m));let g=Number(m.iat);if(isNaN(g))throw Error(`iat field using invalid format`);let _=Number(m.exp);if(isNaN(_))throw Error(`exp field using invalid format`);let v=new Date().getTime()/1e3;if(_>=v+o)throw Error(`Expiration time too far in future: `+JSON.stringify(m));let y=g-e.CLOCK_SKEW_SECS_,b=_+e.CLOCK_SKEW_SECS_;if(v<y)throw Error(`Token used too early, `+v+` < `+y+`: `+JSON.stringify(m));if(v>b)throw Error(`Token used too late, `+v+` > `+b+`: `+JSON.stringify(m));if(i&&i.indexOf(m.iss)<0)throw Error(`Invalid issuer, expected one of [`+i+`], but got `+m.iss);if(r!=null){let e=m.aud,t=!1;if(t=r.constructor===Array?r.indexOf(e)>-1:e===r,!t)throw Error(`Wrong recipient, payload audience != requiredAudience`)}return new u.LoginTicket(p,m)}async processAndValidateRefreshHandler(){if(this.refreshHandler){let e=await this.refreshHandler();if(!e.access_token)throw Error(`No access token is returned by the refreshHandler callback.`);return e}}isTokenExpiring(){let e=this.credentials.expiry_date;return e?e<=new Date().getTime()+this.eagerRefreshThresholdMillis:!1}}})),ue=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.Compute=void 0;let t=D(),n=A(),r=le();e.Compute=class extends r.OAuth2Client{serviceAccountEmail;scopes;constructor(e={}){super(e),this.credentials={expiry_date:1,refresh_token:`compute-placeholder`},this.serviceAccountEmail=e.serviceAccountEmail||`default`,this.scopes=Array.isArray(e.scopes)?e.scopes:e.scopes?[e.scopes]:[]}async refreshTokenNoCache(){let e=`service-accounts/${this.serviceAccountEmail}/token`,r;try{let t={property:e};this.scopes.length>0&&(t.params={scopes:this.scopes.join(`,`)}),r=await n.instance(t)}catch(e){throw e instanceof t.GaxiosError&&(e.message=`Could not refresh access token: ${e.message}`,this.wrapError(e)),e}let i=r;return r&&r.expires_in&&(i.expiry_date=new Date().getTime()+r.expires_in*1e3,delete i.expires_in),this.emit(`tokens`,i),{tokens:i,res:null}}async fetchIdToken(e){let t=`service-accounts/${this.serviceAccountEmail}/identity?format=full&audience=${e}`,r;try{let e={property:t};r=await n.instance(e)}catch(e){throw e instanceof Error&&(e.message=`Could not fetch ID token: ${e.message}`),e}return r}wrapError(e){let t=e.response;t&&t.status&&(e.status=t.status,t.status===403?e.message=`A Forbidden error was returned while attempting to retrieve an access token for the Compute Engine built-in service account. This may be because the Compute Engine instance does not have the correct permission scopes specified: `+e.message:t.status===404&&(e.message=`A Not Found error was returned while attempting to retrieve an accesstoken for the Compute Engine built-in service account. This may be because the Compute Engine instance does not have any permission scopes specified: `+e.message))}}})),de=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.IdTokenClient=void 0;let t=le();e.IdTokenClient=class extends t.OAuth2Client{targetAudience;idTokenProvider;constructor(e){super(e),this.targetAudience=e.targetAudience,this.idTokenProvider=e.idTokenProvider}async getRequestMetadataAsync(){if(!this.credentials.id_token||!this.credentials.expiry_date||this.isTokenExpiring()){let e=await this.idTokenProvider.fetchIdToken(this.targetAudience);this.credentials={id_token:e,expiry_date:this.getIdTokenExpiryDate(e)}}return{headers:new Headers({authorization:`Bearer `+this.credentials.id_token})}}getIdTokenExpiryDate(e){let t=e.split(`.`)[1];if(t)return JSON.parse(Buffer.from(t,`base64`).toString(`ascii`)).exp*1e3}}})),fe=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.GCPEnv=void 0,e.clear=i,e.getEnv=a;let t=A();var n;(function(e){e.APP_ENGINE=`APP_ENGINE`,e.KUBERNETES_ENGINE=`KUBERNETES_ENGINE`,e.CLOUD_FUNCTIONS=`CLOUD_FUNCTIONS`,e.COMPUTE_ENGINE=`COMPUTE_ENGINE`,e.CLOUD_RUN=`CLOUD_RUN`,e.CLOUD_RUN_JOBS=`CLOUD_RUN_JOBS`,e.NONE=`NONE`})(n||(e.GCPEnv=n={}));let r;function i(){r=void 0}async function a(){return r||(r=o(),r)}async function o(){let e=n.NONE;return e=s()?n.APP_ENGINE:c()?n.CLOUD_FUNCTIONS:await f()?await d()?n.KUBERNETES_ENGINE:l()?n.CLOUD_RUN:u()?n.CLOUD_RUN_JOBS:n.COMPUTE_ENGINE:n.NONE,e}function s(){return!!(process.env.GAE_SERVICE||process.env.GAE_MODULE_NAME)}function c(){return!!(process.env.FUNCTION_NAME||process.env.FUNCTION_TARGET)}function l(){return!!process.env.K_CONFIGURATION}function u(){return!!process.env.CLOUD_RUN_JOB}async function d(){try{return await t.instance(`attributes/cluster-name`),!0}catch{return!1}}async function f(){return t.isAvailable()}})),pe=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.buildPayloadForJwsSign=n,e.getJwsSign=r;let t=l();function n(e){let t=Math.floor(new Date().getTime()/1e3);return{iss:e.iss,scope:e.scope,aud:`https://oauth2.googleapis.com/token`,exp:t+3600,iat:t,sub:e.sub,...e.additionalClaims}}function r(e){let r=n(e);return(0,t.sign)({header:{alg:`RS256`},payload:r,secret:e.key})}})),me=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.getToken=r;let t=pe(),n=e=>({method:`POST`,url:`https://oauth2.googleapis.com/token`,data:new URLSearchParams({grant_type:`urn:ietf:params:oauth:grant-type:jwt-bearer`,assertion:(0,t.getJwsSign)(e)}),responseType:`json`,retryConfig:{httpMethodsToRetry:[`POST`]}});async function r(e){if(!e.transporter)throw Error(`No transporter set.`);try{let t=n(e);return(await e.transporter.request(t)).data}catch(e){let t=e,n=t.response?.data;throw n?.error&&(t.message=`${n.error}: ${n.error_description}`),t}}})),he=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.ErrorWithCode=void 0,e.ErrorWithCode=class extends Error{code;constructor(e,t){super(e),this.code=t}}})),ge=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.getCredentials=f;let n=t(`path`),r=t(`fs`),i=t(`util`),a=he(),o=r.readFile?(0,i.promisify)(r.readFile):async()=>{throw new a.ErrorWithCode(`use key rather than keyFile.`,`MISSING_CREDENTIALS`)};var s;(function(e){e.JSON=`.json`,e.DER=`.der`,e.CRT=`.crt`,e.PEM=`.pem`,e.P12=`.p12`,e.PFX=`.pfx`})(s||={});var c=class{keyFilePath;constructor(e){this.keyFilePath=e}async getCredentials(){let e=await o(this.keyFilePath,`utf8`),t;try{t=JSON.parse(e)}catch(e){throw Error(`Invalid JSON key file: ${e.message}`)}let n=t.private_key,r=t.client_email;if(!n||!r)throw new a.ErrorWithCode(`private_key and client_email are required.`,`MISSING_CREDENTIALS`);return{privateKey:n,clientEmail:r}}},l=class{keyFilePath;constructor(e){this.keyFilePath=e}async getCredentials(){return{privateKey:await o(this.keyFilePath,`utf8`)}}},u=class{async getCredentials(){throw new a.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`)}},d=class{static create(e){switch(n.extname(e)){case s.JSON:return new c(e);case s.DER:case s.CRT:case s.PEM:return new l(e);case s.P12:case s.PFX:return new u;default:throw new a.ErrorWithCode(`Unknown certificate type. Type is determined based on file extension. Current supported extensions are *.json, and *.pem.`,`UNKNOWN_CERTIFICATE_TYPE`)}}};async function f(e){return d.create(e).getCredentials()}})),_e=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.TokenHandler=void 0;let t=me(),n=ge();e.TokenHandler=class{token;tokenExpiresAt;inFlightRequest;tokenOptions;constructor(e){this.tokenOptions=e}async processCredentials(){if(!this.tokenOptions.key&&!this.tokenOptions.keyFile)throw Error(`No key or keyFile set.`);if(!this.tokenOptions.key&&this.tokenOptions.keyFile){let e=await(0,n.getCredentials)(this.tokenOptions.keyFile);this.tokenOptions.key=e.privateKey,this.tokenOptions.email=e.clientEmail}}isTokenExpiring(){if(!this.token||!this.tokenExpiresAt)return!0;let e=new Date().getTime(),t=this.tokenOptions.eagerRefreshThresholdMillis??0;return this.tokenExpiresAt<=e+t}hasExpired(){return new Date().getTime(),this.token&&this.tokenExpiresAt?new Date().getTime()>=this.tokenExpiresAt:!0}async getToken(e){if(await this.processCredentials(),this.inFlightRequest&&!e)return this.inFlightRequest;if(this.token&&!this.isTokenExpiring()&&!e)return this.token;try{this.inFlightRequest=(0,t.getToken)(this.tokenOptions);let e=await this.inFlightRequest;return this.token=e,this.tokenExpiresAt=new Date().getTime()+(e.expires_in??0)*1e3,e}finally{this.inFlightRequest=void 0}}}})),ve=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.revokeToken=t;async function t(e,t){let n=`https://oauth2.googleapis.com/revoke?token=`+e;return await t.request({url:n,retry:!0})}})),ye=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.GoogleToken=void 0;let t=D(),n=_e(),r=ve();e.GoogleToken=class{tokenOptions;tokenHandler;constructor(e){this.tokenOptions=e||{},this.tokenOptions.transporter=this.tokenOptions.transporter||{request:e=>(0,t.request)(e)},this.tokenOptions.iss||(this.tokenOptions.iss=this.tokenOptions.email),typeof this.tokenOptions.scope==`object`&&(this.tokenOptions.scope=this.tokenOptions.scope.join(` `)),this.tokenHandler=new n.TokenHandler(this.tokenOptions)}get expiresAt(){return this.tokenHandler.tokenExpiresAt}get accessToken(){return this.tokenHandler.token?.access_token}get idToken(){return this.tokenHandler.token?.id_token}get tokenType(){return this.tokenHandler.token?.token_type}get refreshToken(){return this.tokenHandler.token?.refresh_token}hasExpired(){return this.tokenHandler.hasExpired()}isTokenExpiring(){return this.tokenHandler.isTokenExpiring()}getToken(e,t={forceRefresh:!1}){let n;typeof e==`function`?n=e:typeof e==`object`&&(t=e);let r=this.tokenHandler.getToken(t.forceRefresh??!1);return n&&r.then(e=>n(null,e),n),r}revokeToken(e){if(!this.accessToken)return Promise.reject(Error(`No token to revoke.`));let t=(0,r.revokeToken)(this.accessToken,this.tokenOptions.transporter);e&&t.then(()=>e(),e),this.tokenHandler=new n.TokenHandler(this.tokenOptions)}get googleTokenOptions(){return this.tokenOptions}}})),be=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.JWTAccess=void 0;let t=l(),n=j(),r={alg:`RS256`,typ:`JWT`};e.JWTAccess=class e{email;key;keyId;projectId;eagerRefreshThresholdMillis;cache=new n.LRUCache({capacity:500,maxAge:3600*1e3});constructor(e,t,n,r){this.email=e,this.key=t,this.keyId=n,this.eagerRefreshThresholdMillis=r??300*1e3}getCachedKey(e,t){let n=e;if(t&&Array.isArray(t)&&t.length?n=e?`${e}_${t.join(`_`)}`:`${t.join(`_`)}`:typeof t==`string`&&(n=e?`${e}_${t}`:t),!n)throw Error(`Scopes or url must be provided`);return n}getRequestHeaders(n,i,a){let o=this.getCachedKey(n,a),s=this.cache.get(o),c=Date.now();if(s&&s.expiration-c>this.eagerRefreshThresholdMillis)return new Headers(s.headers);let l=Math.floor(Date.now()/1e3),u=e.getExpirationTime(l),d;if(Array.isArray(a)&&(a=a.join(` `)),d=a?{iss:this.email,sub:this.email,scope:a,exp:u,iat:l}:{iss:this.email,sub:this.email,aud:n,exp:u,iat:l},i){for(let e in d)if(i[e])throw Error(`The '${e}' property is not allowed when passing additionalClaims. This claim is included in the JWT by default.`)}let f=this.keyId?{...r,kid:this.keyId}:r,p=Object.assign(d,i),m=t.sign({header:f,payload:p,secret:this.key}),h=new Headers({authorization:`Bearer ${m}`});return this.cache.set(o,{expiration:u*1e3,headers:h}),h}static getExpirationTime(e){return e+3600}fromJSON(e){if(!e)throw Error(`Must pass in a JSON object containing the service account auth settings.`);if(!e.client_email)throw Error(`The incoming JSON object does not contain a client_email field`);if(!e.private_key)throw Error(`The incoming JSON object does not contain a private_key field`);this.email=e.client_email,this.key=e.private_key,this.keyId=e.private_key_id,this.projectId=e.project_id}fromStream(e,t){if(t)this.fromStreamAsync(e).then(()=>t(),t);else return this.fromStreamAsync(e)}fromStreamAsync(e){return new Promise((t,n)=>{e||n(Error(`Must pass in a stream containing the service account auth settings.`));let r=``;e.setEncoding(`utf8`).on(`data`,e=>r+=e).on(`error`,n).on(`end`,()=>{try{let e=JSON.parse(r);this.fromJSON(e),t()}catch(e){n(e)}})})}}})),xe=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.JWT=void 0;let t=ye(),n=ge(),r=be(),i=le(),a=M();e.JWT=class e extends i.OAuth2Client{email;keyFile;key;keyId;defaultScopes;scopes;scope;subject;gtoken;additionalClaims;useJWTAccessWithScope;defaultServicePath;access;constructor(e={}){super(e),this.email=e.email,this.keyFile=e.keyFile,this.key=e.key,this.keyId=e.keyId,this.scopes=e.scopes,this.subject=e.subject,this.additionalClaims=e.additionalClaims,this.credentials={refresh_token:`jwt-placeholder`,expiry_date:1}}createScoped(t){let n=new e(this);return n.scopes=t,n}async getRequestMetadataAsync(e){e=this.defaultServicePath?`https://${this.defaultServicePath}/`:e;let t=!this.hasUserScopes()&&e||this.useJWTAccessWithScope&&this.hasAnyScopes()||this.universeDomain!==a.DEFAULT_UNIVERSE;if(this.subject&&this.universeDomain!==a.DEFAULT_UNIVERSE)throw RangeError(`Service Account user is configured for the credential. Domain-wide delegation is not supported in universes other than ${a.DEFAULT_UNIVERSE}`);if(!this.apiKey&&t)if(this.additionalClaims&&this.additionalClaims.target_audience){let{tokens:e}=await this.refreshToken();return{headers:this.addSharedMetadataHeaders(new Headers({authorization:`Bearer ${e.id_token}`}))}}else{this.access||=new r.JWTAccess(this.email,this.key,this.keyId,this.eagerRefreshThresholdMillis);let t;this.hasUserScopes()?t=this.scopes:e||(t=this.defaultScopes);let n=this.useJWTAccessWithScope||this.universeDomain!==a.DEFAULT_UNIVERSE,i=await this.access.getRequestHeaders(e??void 0,this.additionalClaims,n?t:void 0);return{headers:this.addSharedMetadataHeaders(i)}}else if(this.hasAnyScopes()||this.apiKey)return super.getRequestMetadataAsync(e);else return{headers:new Headers}}async fetchIdToken(e){let n=new t.GoogleToken({iss:this.email,sub:this.subject,scope:this.scopes||this.defaultScopes,keyFile:this.keyFile,key:this.key,additionalClaims:{target_audience:e},transporter:this.transporter});if(await n.getToken({forceRefresh:!0}),!n.idToken)throw Error(`Unknown error: Failed to fetch ID token`);return n.idToken}hasUserScopes(){return this.scopes?this.scopes.length>0:!1}hasAnyScopes(){return!!(this.scopes&&this.scopes.length>0||this.defaultScopes&&this.defaultScopes.length>0)}authorize(e){if(e)this.authorizeAsync().then(t=>e(null,t),e);else return this.authorizeAsync()}async authorizeAsync(){let e=await this.refreshToken();if(!e)throw Error(`No result returned`);return this.credentials=e.tokens,this.credentials.refresh_token=`jwt-placeholder`,this.key=this.gtoken.googleTokenOptions?.key,this.email=this.gtoken.googleTokenOptions?.iss,e.tokens}async refreshTokenNoCache(){let e=this.createGToken(),t={access_token:(await e.getToken({forceRefresh:this.isTokenExpiring()})).access_token,token_type:`Bearer`,expiry_date:e.expiresAt,id_token:e.idToken};return this.emit(`tokens`,t),{res:null,tokens:t}}createGToken(){return this.gtoken||=new t.GoogleToken({iss:this.email,sub:this.subject,scope:this.scopes||this.defaultScopes,keyFile:this.keyFile,key:this.key,additionalClaims:this.additionalClaims,transporter:this.transporter}),this.gtoken}fromJSON(e){if(!e)throw Error(`Must pass in a JSON object containing the service account auth settings.`);if(!e.client_email)throw Error(`The incoming JSON object does not contain a client_email field`);if(!e.private_key)throw Error(`The incoming JSON object does not contain a private_key field`);this.email=e.client_email,this.key=e.private_key,this.keyId=e.private_key_id,this.projectId=e.project_id,this.quotaProjectId=e.quota_project_id,this.universeDomain=e.universe_domain||this.universeDomain}fromStream(e,t){if(t)this.fromStreamAsync(e).then(()=>t(),t);else return this.fromStreamAsync(e)}fromStreamAsync(e){return new Promise((t,n)=>{if(!e)throw Error(`Must pass in a stream containing the service account auth settings.`);let r=``;e.setEncoding(`utf8`).on(`error`,n).on(`data`,e=>r+=e).on(`end`,()=>{try{let e=JSON.parse(r);this.fromJSON(e),t()}catch(e){n(e)}})})}fromAPIKey(e){if(typeof e!=`string`)throw Error(`Must provide an API Key string.`);this.apiKey=e}async getCredentials(){if(this.key)return{private_key:this.key,client_email:this.email};if(this.keyFile){this.createGToken();let e=await(0,n.getCredentials)(this.keyFile);return{private_key:e.privateKey,client_email:e.clientEmail}}throw Error(`A key or a keyFile must be provided to getCredentials.`)}}})),Se=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.UserRefreshClient=e.USER_REFRESH_ACCOUNT_TYPE=void 0;let t=le(),n=M();e.USER_REFRESH_ACCOUNT_TYPE=`authorized_user`,e.UserRefreshClient=class e extends t.OAuth2Client{_refreshToken;constructor(e,t,n,r,i){let a=e&&typeof e==`object`?e:{clientId:e,clientSecret:t,refreshToken:n,eagerRefreshThresholdMillis:r,forceRefreshOnFailure:i};super(a),this._refreshToken=a.refreshToken,this.credentials.refresh_token=a.refreshToken}async refreshTokenNoCache(){return super.refreshTokenNoCache(this._refreshToken)}async fetchIdToken(t){let r={...e.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:t}),responseType:`json`};return n.AuthClient.setMethodName(r,`fetchIdToken`),(await this.transporter.request(r)).data.id_token}fromJSON(e){if(!e)throw Error(`Must pass in a JSON object containing the user refresh token`);if(e.type!==`authorized_user`)throw Error(`The incoming JSON object does not have the "authorized_user" type`);if(!e.client_id)throw Error(`The incoming JSON object does not contain a client_id field`);if(!e.client_secret)throw Error(`The incoming JSON object does not contain a client_secret field`);if(!e.refresh_token)throw Error(`The incoming JSON object does not contain a refresh_token field`);this._clientId=e.client_id,this._clientSecret=e.client_secret,this._refreshToken=e.refresh_token,this.credentials.refresh_token=e.refresh_token,this.quotaProjectId=e.quota_project_id,this.universeDomain=e.universe_domain||this.universeDomain}fromStream(e,t){if(t)this.fromStreamAsync(e).then(()=>t(),t);else return this.fromStreamAsync(e)}async fromStreamAsync(e){return new Promise((t,n)=>{if(!e)return n(Error(`Must pass in a stream containing the user refresh token.`));let r=``;e.setEncoding(`utf8`).on(`error`,n).on(`data`,e=>r+=e).on(`end`,()=>{try{let e=JSON.parse(r);return this.fromJSON(e),t()}catch(e){return n(e)}})})}static fromJSON(t){let n=new e;return n.fromJSON(t),n}}})),Ce=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.Impersonated=e.IMPERSONATED_ACCOUNT_TYPE=void 0;let t=le(),n=D(),r=j();e.IMPERSONATED_ACCOUNT_TYPE=`impersonated_service_account`,e.Impersonated=class e extends t.OAuth2Client{sourceClient;targetPrincipal;targetScopes;delegates;lifetime;endpoint;constructor(e={}){if(super(e),this.credentials={expiry_date:1,refresh_token:`impersonated-placeholder`},this.sourceClient=e.sourceClient??new t.OAuth2Client,this.targetPrincipal=e.targetPrincipal??``,this.delegates=e.delegates??[],this.targetScopes=e.targetScopes??[],this.lifetime=e.lifetime??3600,!(0,r.originalOrCamelOptions)(e).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=e.endpoint??`https://iamcredentials.${this.universeDomain}`}async sign(t){await this.sourceClient.getAccessToken();let n=`projects/-/serviceAccounts/${this.targetPrincipal}`,r=`${this.endpoint}/v1/${n}:signBlob`,i={delegates:this.delegates,payload:Buffer.from(t).toString(`base64`)};return(await this.sourceClient.request({...e.RETRY_CONFIG,url:r,data:i,method:`POST`})).data}getTargetPrincipal(){return this.targetPrincipal}async refreshToken(){try{await this.sourceClient.getAccessToken();let t=`projects/-/serviceAccounts/`+this.targetPrincipal,n=`${this.endpoint}/v1/${t}:generateAccessToken`,r={delegates:this.delegates,scope:this.targetScopes,lifetime:this.lifetime+`s`},i=await this.sourceClient.request({...e.RETRY_CONFIG,url:n,data:r,method:`POST`}),a=i.data;return this.credentials.access_token=a.accessToken,this.credentials.expiry_date=Date.parse(a.expireTime),{tokens:this.credentials,res:i}}catch(e){if(!(e instanceof Error))throw e;let t=0,r=``;throw e instanceof n.GaxiosError&&(t=e?.response?.data?.error?.status,r=e?.response?.data?.error?.message),t&&r?(e.message=`${t}: unable to impersonate: ${r}`,e):(e.message=`unable to impersonate: ${e}`,e)}}async fetchIdToken(t,n){await this.sourceClient.getAccessToken();let r=`projects/-/serviceAccounts/${this.targetPrincipal}`,i=`${this.endpoint}/v1/${r}:generateIdToken`,a={delegates:this.delegates,audience:t,includeEmail:n?.includeEmail??!0,useEmailAzp:n?.includeEmail??!0};return(await this.sourceClient.request({...e.RETRY_CONFIG,url:i,data:a,method:`POST`})).data.token}}})),we=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.OAuthClientAuthHandler=void 0,e.getErrorFromOAuthErrorResponse=i;let t=D(),n=ae(),r=[`PUT`,`POST`,`PATCH`];e.OAuthClientAuthHandler=class{#e=(0,n.createCrypto)();#t;transporter;constructor(e){e&&`clientId`in e?(this.#t=e,this.transporter=new t.Gaxios):(this.#t=e?.clientAuthentication,this.transporter=e?.transporter||new t.Gaxios)}applyClientAuthenticationOptions(e,n){e.headers=t.Gaxios.mergeHeaders(e.headers),this.injectAuthenticatedHeaders(e,n),n||this.injectAuthenticatedRequestBody(e)}injectAuthenticatedHeaders(e,n){if(n)e.headers=t.Gaxios.mergeHeaders(e.headers,{authorization:`Bearer ${n}`});else if(this.#t?.confidentialClientType===`basic`){e.headers=t.Gaxios.mergeHeaders(e.headers);let n=this.#t.clientId,r=this.#t.clientSecret||``,i=this.#e.encodeBase64StringUtf8(`${n}:${r}`);t.Gaxios.mergeHeaders(e.headers,{authorization:`Basic ${i}`})}}injectAuthenticatedRequestBody(e){if(this.#t?.confidentialClientType===`request-body`){let t=(e.method||`GET`).toUpperCase();if(!r.includes(t))throw Error(`${t} HTTP method does not support ${this.#t.confidentialClientType} client authentication`);let n=new Headers(e.headers).get(`content-type`);if(n?.startsWith(`application/x-www-form-urlencoded`)||e.data instanceof URLSearchParams){let t=new URLSearchParams(e.data??``);t.append(`client_id`,this.#t.clientId),t.append(`client_secret`,this.#t.clientSecret||``),e.data=t}else if(n?.startsWith(`application/json`))e.data=e.data||{},Object.assign(e.data,{client_id:this.#t.clientId,client_secret:this.#t.clientSecret||``});else throw Error(`${n} 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`]}}}};function i(e,t){let n=e.error,r=e.error_description,i=e.error_uri,a=`Error code ${n}`;r!==void 0&&(a+=`: ${r}`),i!==void 0&&(a+=` - ${i}`);let o=Error(a);if(t){let e=Object.keys(t);t.stack&&e.push(`stack`),e.forEach(e=>{e!==`message`&&Object.defineProperty(o,e,{value:t[e],writable:!1,enumerable:!0})})}return o}})),Te=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.StsCredentials=void 0;let t=D(),n=M(),r=we(),i=j();e.StsCredentials=class e extends r.OAuthClientAuthHandler{#e;constructor(e={tokenExchangeEndpoint:``},t){(typeof e!=`object`||e instanceof URL)&&(e={tokenExchangeEndpoint:e,clientAuthentication:t}),super(e),this.#e=e.tokenExchangeEndpoint}async exchangeToken(a,o,s){let c={grant_type:a.grantType,resource:a.resource,audience:a.audience,scope:a.scope?.join(` `),requested_token_type:a.requestedTokenType,subject_token:a.subjectToken,subject_token_type:a.subjectTokenType,actor_token:a.actingParty?.actorToken,actor_token_type:a.actingParty?.actorTokenType,options:s&&JSON.stringify(s)},l={...e.RETRY_CONFIG,url:this.#e.toString(),method:`POST`,headers:o,data:new URLSearchParams((0,i.removeUndefinedValuesInObject)(c)),responseType:`json`};n.AuthClient.setMethodName(l,`exchangeToken`),this.applyClientAuthenticationOptions(l);try{let e=await this.transporter.request(l),t=e.data;return t.res=e,t}catch(e){throw e instanceof t.GaxiosError&&e.response?(0,r.getErrorFromOAuthErrorResponse)(e.response.data,e):e}}}})),Ee=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.BaseExternalAccountClient=e.CLOUD_RESOURCE_MANAGER=e.EXTERNAL_ACCOUNT_TYPE=e.EXPIRATION_TIME_OFFSET=void 0;let n=D(),r=t(`stream`),i=M(),a=Te(),o=j(),s=se(),c=`https://www.googleapis.com/auth/cloud-platform`;e.EXPIRATION_TIME_OFFSET=300*1e3,e.EXTERNAL_ACCOUNT_TYPE=`external_account`,e.CLOUD_RESOURCE_MANAGER=`https://cloudresourcemanager.googleapis.com/v1/projects/`,e.BaseExternalAccountClient=class t extends i.AuthClient{scopes;projectNumber;audience;subjectTokenType;stsCredential;clientAuth;credentialSourceType;cachedAccessToken;serviceAccountImpersonationUrl;serviceAccountImpersonationLifetime;workforcePoolUserProject;configLifetimeRequested;tokenUrl;cloudResourceManagerURL;supplierContext;#e=null;constructor(t){super(t);let n=(0,o.originalOrCamelOptions)(t),r=n.get(`type`);if(r&&r!==e.EXTERNAL_ACCOUNT_TYPE)throw Error(`Expected "${e.EXTERNAL_ACCOUNT_TYPE}" type but received "${t.type}"`);let i=n.get(`client_id`),s=n.get(`client_secret`);this.tokenUrl=n.get(`token_url`)??`https://sts.{universeDomain}/v1/token`.replace(`{universeDomain}`,this.universeDomain);let l=n.get(`subject_token_type`),u=n.get(`workforce_pool_user_project`),d=n.get(`service_account_impersonation_url`),f=n.get(`service_account_impersonation`),p=(0,o.originalOrCamelOptions)(f).get(`token_lifetime_seconds`);this.cloudResourceManagerURL=new URL(n.get(`cloud_resource_manager_url`)||`https://cloudresourcemanager.${this.universeDomain}/v1/projects/`),i&&(this.clientAuth={confidentialClientType:`basic`,clientId:i,clientSecret:s}),this.stsCredential=new a.StsCredentials({tokenExchangeEndpoint:this.tokenUrl,clientAuthentication:this.clientAuth}),this.scopes=n.get(`scopes`)||[c],this.cachedAccessToken=null,this.audience=n.get(`audience`),this.subjectTokenType=l,this.workforcePoolUserProject=u;let m=RegExp(`//iam\\.googleapis\\.com/locations/[^/]+/workforcePools/[^/]+/providers/.+`);if(this.workforcePoolUserProject&&!this.audience.match(m))throw Error(`workforcePoolUserProject should not be set for non-workforce pool credentials.`);this.serviceAccountImpersonationUrl=d,this.serviceAccountImpersonationLifetime=p,this.serviceAccountImpersonationLifetime?this.configLifetimeRequested=!0:(this.configLifetimeRequested=!1,this.serviceAccountImpersonationLifetime=3600),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(e){super.setCredentials(e),this.cachedAccessToken=e}async getAccessToken(){return(!this.cachedAccessToken||this.isExpired(this.cachedAccessToken))&&await this.refreshAccessTokenAsync(),{token:this.cachedAccessToken.access_token,res:this.cachedAccessToken.res}}async getRequestHeaders(){let e=await this.getAccessToken(),t=new Headers({authorization:`Bearer ${e.token}`});return this.addSharedMetadataHeaders(t)}request(e,t){if(t)this.requestAsync(e).then(e=>t(null,e),e=>t(e,e.response));else return this.requestAsync(e)}async getProjectId(){let e=this.projectNumber||this.workforcePoolUserProject;if(this.projectId)return this.projectId;if(e){let n=await this.getRequestHeaders(),r={...t.RETRY_CONFIG,headers:n,url:`${this.cloudResourceManagerURL.toString()}${e}`,responseType:`json`};i.AuthClient.setMethodName(r,`getProjectId`);let a=await this.transporter.request(r);return this.projectId=a.data.projectId,this.projectId}return null}async requestAsync(e,t=!1){let i;try{let t=await this.getRequestHeaders();e.headers=n.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,t),i=await this.transporter.request(e)}catch(n){let i=n.response;if(i){let n=i.status,a=i.config.data instanceof r.Readable;if(!t&&(n===401||n===403)&&!a&&this.forceRefreshOnFailure)return await this.refreshAccessTokenAsync(),await this.requestAsync(e,!0)}throw n}return i}async refreshAccessTokenAsync(){this.#e=this.#e||this.#t();try{return await this.#e}finally{this.#e=null}}async#t(){let e=await this.retrieveSubjectToken(),t={grantType:`urn:ietf:params:oauth:grant-type:token-exchange`,audience:this.audience,requestedTokenType:`urn:ietf:params:oauth:token-type:access_token`,subjectToken:e,subjectTokenType:this.subjectTokenType,scope:this.serviceAccountImpersonationUrl?[c]:this.getScopesArray()},n=!this.clientAuth&&this.workforcePoolUserProject?{userProject:this.workforcePoolUserProject}:void 0,r=new Headers({"x-goog-api-client":this.getMetricsHeaderValue()}),i=await this.stsCredential.exchangeToken(t,r,n);return this.serviceAccountImpersonationUrl?this.cachedAccessToken=await this.getImpersonatedAccessToken(i.access_token):i.expires_in?this.cachedAccessToken={access_token:i.access_token,expiry_date:new Date().getTime()+i.expires_in*1e3,res:i.res}:this.cachedAccessToken={access_token:i.access_token,res:i.res},this.credentials={},Object.assign(this.credentials,this.cachedAccessToken),delete this.credentials.res,this.emit(`tokens`,{refresh_token:null,expiry_date:this.cachedAccessToken.expiry_date,access_token:this.cachedAccessToken.access_token,token_type:`Bearer`,id_token:null}),this.cachedAccessToken}getProjectNumber(e){let t=e.match(/\/projects\/([^/]+)/);return t?t[1]:null}async getImpersonatedAccessToken(e){let n={...t.RETRY_CONFIG,url:this.serviceAccountImpersonationUrl,method:`POST`,headers:{"content-type":`application/json`,authorization:`Bearer ${e}`},data:{scope:this.getScopesArray(),lifetime:this.serviceAccountImpersonationLifetime+`s`},responseType:`json`};i.AuthClient.setMethodName(n,`getImpersonatedAccessToken`);let r=await this.transporter.request(n),a=r.data;return{access_token:a.accessToken,expiry_date:new Date(a.expireTime).getTime(),res:r}}isExpired(e){let t=new Date().getTime();return e.expiry_date?t>=e.expiry_date-this.eagerRefreshThresholdMillis:!1}getScopesArray(){return typeof this.scopes==`string`?[this.scopes]:this.scopes||[c]}getMetricsHeaderValue(){let e=process.version.replace(/^v/,``),t=this.serviceAccountImpersonationUrl!==void 0,n=this.credentialSourceType?this.credentialSourceType:`unknown`;return`gl-node/${e} auth/${s.pkg.version} google-byoid-sdk source/${n} sa-impersonation/${t} config-lifetime/${this.configLifetimeRequested}`}getTokenUrl(){return this.tokenUrl}}})),De=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.FileSubjectTokenSupplier=void 0;let n=t(`util`),r=t(`fs`),i=(0,n.promisify)(r.readFile??(()=>{})),a=(0,n.promisify)(r.realpath??(()=>{})),o=(0,n.promisify)(r.lstat??(()=>{}));e.FileSubjectTokenSupplier=class{filePath;formatType;subjectTokenFieldName;constructor(e){this.filePath=e.filePath,this.formatType=e.formatType,this.subjectTokenFieldName=e.subjectTokenFieldName}async getSubjectToken(){let e=this.filePath;try{if(e=await a(e),!(await o(e)).isFile())throw Error()}catch(t){throw t instanceof Error&&(t.message=`The file at ${e} does not exist, or it is not a file. ${t.message}`),t}let t,n=await i(e,{encoding:`utf8`});if(this.formatType===`text`?t=n:this.formatType===`json`&&this.subjectTokenFieldName&&(t=JSON.parse(n)[this.subjectTokenFieldName]),!t)throw Error(`Unable to parse the subject_token from the credential_source file`);return t}}})),Oe=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.UrlSubjectTokenSupplier=void 0;let t=M();e.UrlSubjectTokenSupplier=class{url;headers;formatType;subjectTokenFieldName;additionalGaxiosOptions;constructor(e){this.url=e.url,this.formatType=e.formatType,this.subjectTokenFieldName=e.subjectTokenFieldName,this.headers=e.headers,this.additionalGaxiosOptions=e.additionalGaxiosOptions}async getSubjectToken(e){let n={...this.additionalGaxiosOptions,url:this.url,method:`GET`,headers:this.headers,responseType:this.formatType};t.AuthClient.setMethodName(n,`getSubjectToken`);let r;if(this.formatType===`text`?r=(await e.transporter.request(n)).data:this.formatType===`json`&&this.subjectTokenFieldName&&(r=(await e.transporter.request(n)).data[this.subjectTokenFieldName]),!r)throw Error(`Unable to parse the subject_token from the credential_source URL`);return r}}})),ke=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.CertificateSubjectTokenSupplier=e.InvalidConfigurationError=e.CertificateSourceUnavailableError=e.CERTIFICATE_CONFIGURATION_ENV_VARIABLE=void 0;let n=j(),r=t(`fs`),i=t(`crypto`),a=t(`https`);e.CERTIFICATE_CONFIGURATION_ENV_VARIABLE=`GOOGLE_API_CERTIFICATE_CONFIG`;var o=class extends Error{constructor(e){super(e),this.name=`CertificateSourceUnavailableError`}};e.CertificateSourceUnavailableError=o;var s=class extends Error{constructor(e){super(e),this.name=`InvalidConfigurationError`}};e.InvalidConfigurationError=s,e.CertificateSubjectTokenSupplier=class{certificateConfigPath;trustChainPath;cert;key;constructor(e){if(!e.useDefaultCertificateConfig&&!e.certificateConfigLocation)throw new s("Either `useDefaultCertificateConfig` must be true or a `certificateConfigLocation` must be provided.");if(e.useDefaultCertificateConfig&&e.certificateConfigLocation)throw new s("Both `useDefaultCertificateConfig` and `certificateConfigLocation` cannot be provided.");this.trustChainPath=e.trustChainPath,this.certificateConfigPath=e.certificateConfigLocation??``}async createMtlsHttpsAgent(){if(!this.key||!this.cert)throw new s(`Cannot create mTLS Agent with missing certificate or key`);return new a.Agent({key:this.key,cert:this.cert})}async getSubjectToken(){this.certificateConfigPath=await this.#e();let{certPath:e,keyPath:t}=await this.#t();return{cert:this.cert,key:this.key}=await this.#n(e,t),await this.#r(this.cert)}async#e(){let t=this.certificateConfigPath;if(t){if(await(0,n.isValidFile)(t))return t;throw new o(`Provided certificate config path is invalid: ${t}`)}let r=process.env[e.CERTIFICATE_CONFIGURATION_ENV_VARIABLE];if(r){if(await(0,n.isValidFile)(r))return r;throw new o(`Path from environment variable "${e.CERTIFICATE_CONFIGURATION_ENV_VARIABLE}" is invalid: ${r}`)}let i=(0,n.getWellKnownCertificateConfigFileLocation)();if(await(0,n.isValidFile)(i))return i;throw new o(`Could not find certificate configuration file. Searched override path, the "${e.CERTIFICATE_CONFIGURATION_ENV_VARIABLE}" env var, and the gcloud path (${i}).`)}async#t(){let e=this.certificateConfigPath,t;try{t=await r.promises.readFile(e,`utf8`)}catch{throw new o(`Failed to read certificate config file at: ${e}`)}try{let n=JSON.parse(t),r=n?.cert_configs?.workload?.cert_path,i=n?.cert_configs?.workload?.key_path;if(!r||!i)throw new s(`Certificate config file (${e}) is missing required "cert_path" or "key_path" in the workload config.`);return{certPath:r,keyPath:i}}catch(t){throw t instanceof s?t:new s(`Failed to parse certificate config from ${e}: ${t.message}`)}}async#n(e,t){let n,a;try{n=await r.promises.readFile(e),new i.X509Certificate(n)}catch(t){throw new o(`Failed to read certificate file at ${e}: ${t instanceof Error?t.message:String(t)}`)}try{a=await r.promises.readFile(t),(0,i.createPrivateKey)(a)}catch(e){throw new o(`Failed to read private key file at ${t}: ${e instanceof Error?e.message:String(e)}`)}return{cert:n,key:a}}async#r(e){let t=new i.X509Certificate(e);if(!this.trustChainPath)return JSON.stringify([t.raw.toString(`base64`)]);try{let e=((await r.promises.readFile(this.trustChainPath,`utf8`)).match(/-----BEGIN CERTIFICATE-----[^-]+-----END CERTIFICATE-----/g)??[]).map((e,t)=>{try{return new i.X509Certificate(e)}catch(e){let n=e instanceof Error?e.message:String(e);throw new s(`Failed to parse certificate at index ${t} in trust chain file ${this.trustChainPath}: ${n}`)}}),n=e.findIndex(e=>t.raw.equals(e.raw)),a;if(n===-1)a=[t,...e];else if(n===0)a=e;else throw new s(`Leaf certificate exists in the trust chain but is not the first entry (found at index ${n}).`);return JSON.stringify(a.map(e=>e.raw.toString(`base64`)))}catch(e){if(e instanceof s)throw e;let t=e instanceof Error?e.message:String(e);throw new o(`Failed to process certificate chain from ${this.trustChainPath}: ${t}`)}}}})),Ae=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.IdentityPoolClient=void 0;let t=Ee(),n=j(),r=De(),i=Oe(),a=ke(),o=Te(),s=D();e.IdentityPoolClient=class e extends t.BaseExternalAccountClient{subjectTokenSupplier;constructor(t){super(t);let o=(0,n.originalOrCamelOptions)(t),s=o.get(`credential_source`),c=o.get(`subject_token_supplier`);if(!s&&!c)throw Error(`A credential source or subject token supplier must be specified.`);if(s&&c)throw Error(`Only one of credential source or subject token supplier can be specified.`);if(c)this.subjectTokenSupplier=c,this.credentialSourceType=`programmatic`;else{let t=(0,n.originalOrCamelOptions)(s),o=(0,n.originalOrCamelOptions)(t.get(`format`)),c=o.get(`type`)||`text`,l=o.get(`subject_token_field_name`);if(c!==`json`&&c!==`text`)throw Error(`Invalid credential_source format "${c}"`);if(c===`json`&&!l)throw Error(`Missing subject_token_field_name for JSON credential_source format`);let u=t.get(`file`),d=t.get(`url`),f=t.get(`certificate`),p=t.get(`headers`);if(u&&d||d&&f||u&&f)throw Error(`No valid Identity Pool "credential_source" provided, must be either file, url, or certificate.`);if(u)this.credentialSourceType=`file`,this.subjectTokenSupplier=new r.FileSubjectTokenSupplier({filePath:u,formatType:c,subjectTokenFieldName:l});else if(d)this.credentialSourceType=`url`,this.subjectTokenSupplier=new i.UrlSubjectTokenSupplier({url:d,formatType:c,subjectTokenFieldName:l,headers:p,additionalGaxiosOptions:e.RETRY_CONFIG});else if(f){this.credentialSourceType=`certificate`;let e=new a.CertificateSubjectTokenSupplier({useDefaultCertificateConfig:f.use_default_certificate_config,certificateConfigLocation:f.certificate_config_location,trustChainPath:f.trust_chain_path});this.subjectTokenSupplier=e}else throw Error(`No valid Identity Pool "credential_source" provided, must be either file, url, or certificate.`)}}async retrieveSubjectToken(){let e=await this.subjectTokenSupplier.getSubjectToken(this.supplierContext);if(this.subjectTokenSupplier instanceof a.CertificateSubjectTokenSupplier){let e=await this.subjectTokenSupplier.createMtlsHttpsAgent();this.stsCredential=new o.StsCredentials({tokenExchangeEndpoint:this.getTokenUrl(),clientAuthentication:this.clientAuth,transporter:new s.Gaxios({agent:e})}),this.transporter=new s.Gaxios({...this.transporter.defaults||{},agent:e})}return e}}})),je=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.AwsRequestSigner=void 0;let t=D(),n=ae(),r=`AWS4-HMAC-SHA256`;e.AwsRequestSigner=class{getCredentials;region;crypto;constructor(e,t){this.getCredentials=e,this.region=t,this.crypto=(0,n.createCrypto)()}async getRequestOptions(e){if(!e.url)throw RangeError(`"url" is required in "amzOptions"`);let n=typeof e.data==`object`?JSON.stringify(e.data):e.data,r=e.url,i=e.method||`GET`,a=e.body||n,s=e.headers,c=await this.getCredentials(),l=new URL(r);if(typeof a!=`string`&&a!==void 0)throw TypeError(`'requestPayload' is expected to be a string if provided. Got: ${a}`);let u=await o({crypto:this.crypto,host:l.host,canonicalUri:l.pathname,canonicalQuerystring:l.search.slice(1),method:i,region:this.region,securityCredentials:c,requestPayload:a,additionalAmzHeaders:s}),d=t.Gaxios.mergeHeaders(u.amzDate?{"x-amz-date":u.amzDate}:{},{authorization:u.authorizationHeader,host:l.host},s||{});c.token&&t.Gaxios.mergeHeaders(d,{"x-amz-security-token":c.token});let f={url:r,method:i,headers:d};return a!==void 0&&(f.body=a),f}};async function i(e,t,n){return await e.signWithHmacSha256(t,n)}async function a(e,t,n,r,a){return await i(e,await i(e,await i(e,await i(e,`AWS4${t}`,n),r),a),`aws4_request`)}async function o(e){let o=t.Gaxios.mergeHeaders(e.additionalAmzHeaders),s=e.requestPayload||``,c=e.host.split(`.`)[0],l=new Date,u=l.toISOString().replace(/[-:]/g,``).replace(/\.[0-9]+/,``),d=l.toISOString().replace(/[-]/g,``).replace(/T.*/,``);e.securityCredentials.token&&o.set(`x-amz-security-token`,e.securityCredentials.token);let f=t.Gaxios.mergeHeaders({host:e.host},o.has(`date`)?{}:{"x-amz-date":u},o),p=``,m=[...f.keys()].sort();m.forEach(e=>{p+=`${e}:${f.get(e)}\n`});let h=m.join(`;`),g=await e.crypto.sha256DigestHex(s),_=`${e.method.toUpperCase()}\n${e.canonicalUri}\n${e.canonicalQuerystring}\n${p}\n${h}\n${g}`,v=`${d}/${e.region}/${c}/aws4_request`,y=`${r}\n${u}\n${v}\n`+await e.crypto.sha256DigestHex(_),b=await a(e.crypto,e.securityCredentials.secretAccessKey,d,e.region,c),x=await i(e.crypto,b,y),S=`${r} Credential=${e.securityCredentials.accessKeyId}/${v}, SignedHeaders=${h}, Signature=${(0,n.fromArrayBufferToHex)(x)}`;return{amzDate:o.has(`date`)?void 0:u,authorizationHeader:S,canonicalQuerystring:e.canonicalQuerystring}}})),Me=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.DefaultAwsSecurityCredentialsSupplier=void 0;let t=M();e.DefaultAwsSecurityCredentialsSupplier=class{regionUrl;securityCredentialsUrl;imdsV2SessionTokenUrl;additionalGaxiosOptions;constructor(e){this.regionUrl=e.regionUrl,this.securityCredentialsUrl=e.securityCredentialsUrl,this.imdsV2SessionTokenUrl=e.imdsV2SessionTokenUrl,this.additionalGaxiosOptions=e.additionalGaxiosOptions}async getAwsRegion(e){if(this.#r)return this.#r;let n=new Headers;if(!this.#r&&this.imdsV2SessionTokenUrl&&n.set(`x-aws-ec2-metadata-token`,await this.#e(e.transporter)),!this.regionUrl)throw RangeError(`Unable to determine AWS region due to missing "options.credential_source.region_url"`);let r={...this.additionalGaxiosOptions,url:this.regionUrl,method:`GET`,responseType:`text`,headers:n};t.AuthClient.setMethodName(r,`getAwsRegion`);let i=await e.transporter.request(r);return i.data.substr(0,i.data.length-1)}async getAwsSecurityCredentials(e){if(this.#i)return this.#i;let t=new Headers;this.imdsV2SessionTokenUrl&&t.set(`x-aws-ec2-metadata-token`,await this.#e(e.transporter));let n=await this.#t(t,e.transporter),r=await this.#n(n,t,e.transporter);return{accessKeyId:r.AccessKeyId,secretAccessKey:r.SecretAccessKey,token:r.Token}}async#e(e){let n={...this.additionalGaxiosOptions,url:this.imdsV2SessionTokenUrl,method:`PUT`,responseType:`text`,headers:{"x-aws-ec2-metadata-token-ttl-seconds":`300`}};return t.AuthClient.setMethodName(n,`#getImdsV2SessionToken`),(await e.request(n)).data}async#t(e,n){if(!this.securityCredentialsUrl)throw Error(`Unable to determine AWS role name due to missing "options.credential_source.url"`);let r={...this.additionalGaxiosOptions,url:this.securityCredentialsUrl,method:`GET`,responseType:`text`,headers:e};return t.AuthClient.setMethodName(r,`#getAwsRoleName`),(await n.request(r)).data}async#n(e,n,r){let i={...this.additionalGaxiosOptions,url:`${this.securityCredentialsUrl}/${e}`,headers:n,responseType:`json`};return t.AuthClient.setMethodName(i,`#retrieveAwsSecurityCredentials`),(await r.request(i)).data}get#r(){return process.env.AWS_REGION||process.env.AWS_DEFAULT_REGION||null}get#i(){return process.env.AWS_ACCESS_KEY_ID&&process.env.AWS_SECRET_ACCESS_KEY?{accessKeyId:process.env.AWS_ACCESS_KEY_ID,secretAccessKey:process.env.AWS_SECRET_ACCESS_KEY,token:process.env.AWS_SESSION_TOKEN}:null}}})),Ne=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.AwsClient=void 0;let t=je(),n=Ee(),r=Me(),i=j(),a=D();e.AwsClient=class e extends n.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(t){super(t);let n=(0,i.originalOrCamelOptions)(t),a=n.get(`credential_source`),o=n.get(`aws_security_credentials_supplier`);if(!a&&!o)throw Error(`A credential source or AWS security credentials supplier must be specified.`);if(a&&o)throw Error(`Only one of credential source or AWS security credentials supplier can be specified.`);if(o)this.awsSecurityCredentialsSupplier=o,this.regionalCredVerificationUrl=e.#e,this.credentialSourceType=`programmatic`;else{let e=(0,i.originalOrCamelOptions)(a);this.environmentId=e.get(`environment_id`);let t=e.get(`region_url`),n=e.get(`url`),o=e.get(`imdsv2_session_token_url`);this.awsSecurityCredentialsSupplier=new r.DefaultAwsSecurityCredentialsSupplier({regionUrl:t,securityCredentialsUrl:n,imdsV2SessionTokenUrl:o}),this.regionalCredVerificationUrl=e.get(`regional_cred_verification_url`),this.credentialSourceType=`aws`,this.validateEnvironmentId()}this.awsRequestSigner=null,this.region=``}validateEnvironmentId(){let e=this.environmentId?.match(/^(aws)(\d+)$/);if(!e||!this.regionalCredVerificationUrl)throw Error(`No valid AWS "credential_source" provided`);if(parseInt(e[2],10)!==1)throw Error(`aws version "${e[2]}" is not supported in the current build.`)}async retrieveSubjectToken(){this.awsRequestSigner||=(this.region=await this.awsSecurityCredentialsSupplier.getAwsRegion(this.supplierContext),new t.AwsRequestSigner(async()=>this.awsSecurityCredentialsSupplier.getAwsSecurityCredentials(this.supplierContext),this.region));let n=await this.awsRequestSigner.getRequestOptions({...e.RETRY_CONFIG,url:this.regionalCredVerificationUrl.replace(`{region}`,this.region),method:`POST`}),r=[];return a.Gaxios.mergeHeaders({"x-goog-cloud-target-resource":this.audience},n.headers).forEach((e,t)=>r.push({key:t,value:e})),encodeURIComponent(JSON.stringify({url:n.url,method:n.method,headers:r}))}}})),Pe=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.InvalidSubjectTokenError=e.InvalidMessageFieldError=e.InvalidCodeFieldError=e.InvalidTokenTypeFieldError=e.InvalidExpirationTimeFieldError=e.InvalidSuccessFieldError=e.InvalidVersionFieldError=e.ExecutableResponseError=e.ExecutableResponse=void 0;let t=`urn:ietf:params:oauth:token-type:saml2`,n=`urn:ietf:params:oauth:token-type:id_token`,r=`urn:ietf:params:oauth:token-type:jwt`;e.ExecutableResponse=class{version;success;expirationTime;tokenType;errorCode;errorMessage;subjectToken;constructor(e){if(!e.version)throw new a(`Executable response must contain a 'version' field.`);if(e.success===void 0)throw new o(`Executable response must contain a 'success' field.`);if(this.version=e.version,this.success=e.success,this.success){if(this.expirationTime=e.expiration_time,this.tokenType=e.token_type,this.tokenType!==t&&this.tokenType!==n&&this.tokenType!==r)throw new s(`Executable response must contain a 'token_type' field when successful and it must be one of ${n}, ${r}, or ${t}.`);if(this.tokenType===t){if(!e.saml_response)throw new u(`Executable response must contain a 'saml_response' field when token_type=${t}.`);this.subjectToken=e.saml_response}else{if(!e.id_token)throw new u(`Executable response must contain a 'id_token' field when token_type=${n} or ${r}.`);this.subjectToken=e.id_token}}else{if(!e.code)throw new c(`Executable response must contain a 'code' field when unsuccessful.`);if(!e.message)throw new l(`Executable response must contain a 'message' field when unsuccessful.`);this.errorCode=e.code,this.errorMessage=e.message}}isValid(){return!this.isExpired()&&this.success}isExpired(){return this.expirationTime!==void 0&&this.expirationTime<Math.round(Date.now()/1e3)}};var i=class extends Error{constructor(e){super(e),Object.setPrototypeOf(this,new.target.prototype)}};e.ExecutableResponseError=i;var a=class extends i{};e.InvalidVersionFieldError=a;var o=class extends i{};e.InvalidSuccessFieldError=o,e.InvalidExpirationTimeFieldError=class extends i{};var s=class extends i{};e.InvalidTokenTypeFieldError=s;var c=class extends i{};e.InvalidCodeFieldError=c;var l=class extends i{};e.InvalidMessageFieldError=l;var u=class extends i{};e.InvalidSubjectTokenError=u})),Fe=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.PluggableAuthHandler=e.ExecutableError=void 0;let n=Pe(),r=t(`child_process`),i=t(`fs`);var a=class extends Error{code;constructor(e,t){super(`The executable failed with exit code: ${t} and error message: ${e}.`),this.code=t,Object.setPrototypeOf(this,new.target.prototype)}};e.ExecutableError=a,e.PluggableAuthHandler=class e{commandComponents;timeoutMillis;outputFile;constructor(t){if(!t.command)throw Error(`No command provided.`);if(this.commandComponents=e.parseCommand(t.command),this.timeoutMillis=t.timeoutMillis,!this.timeoutMillis)throw Error(`No timeoutMillis provided.`);this.outputFile=t.outputFile}retrieveResponseFromExecutable(e){return new Promise((t,i)=>{let o=r.spawn(this.commandComponents[0],this.commandComponents.slice(1),{env:{...process.env,...Object.fromEntries(e)}}),s=``;o.stdout.on(`data`,e=>{s+=e}),o.stderr.on(`data`,e=>{s+=e});let c=setTimeout(()=>(o.removeAllListeners(),o.kill(),i(Error(`The executable failed to finish within the timeout specified.`))),this.timeoutMillis);o.on(`close`,e=>{if(clearTimeout(c),e===0)try{let e=JSON.parse(s);return t(new n.ExecutableResponse(e))}catch(e){return e instanceof n.ExecutableResponseError?i(e):i(new n.ExecutableResponseError(`The executable returned an invalid response: ${s}`))}else return i(new a(s,e.toString()))})})}async retrieveCachedResponse(){if(!this.outputFile||this.outputFile.length===0)return;let e;try{e=await i.promises.realpath(this.outputFile)}catch{return}if(!(await i.promises.lstat(e)).isFile())return;let t=await i.promises.readFile(e,{encoding:`utf8`});if(t!==``)try{let e=JSON.parse(t);return new n.ExecutableResponse(e).isValid()?new n.ExecutableResponse(e):void 0}catch(e){throw e instanceof n.ExecutableResponseError?e:new n.ExecutableResponseError(`The output file contained an invalid response: ${t}`)}}static parseCommand(e){let t=e.match(/(?:[^\s"]+|"[^"]*")+/g);if(!t)throw Error(`Provided command: "${e}" could not be parsed.`);for(let e=0;e<t.length;e++)t[e][0]===`"`&&t[e].slice(-1)===`"`&&(t[e]=t[e].slice(1,-1));return t}}})),Ie=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.PluggableAuthClient=e.ExecutableError=void 0;let t=Ee(),n=Pe(),r=Fe();var i=Fe();Object.defineProperty(e,`ExecutableError`,{enumerable:!0,get:function(){return i.ExecutableError}});let a=5*1e3,o=120*1e3;e.PluggableAuthClient=class extends t.BaseExternalAccountClient{command;timeoutMillis;outputFile;handler;constructor(e){if(super(e),!e.credential_source.executable||(this.command=e.credential_source.executable.command,!this.command))throw Error(`No valid Pluggable Auth "credential_source" provided.`);if(e.credential_source.executable.timeout_millis===void 0)this.timeoutMillis=3e4;else if(this.timeoutMillis=e.credential_source.executable.timeout_millis,this.timeoutMillis<a||this.timeoutMillis>o)throw Error(`Timeout must be between ${a} and ${o} milliseconds.`);this.outputFile=e.credential_source.executable.output_file,this.handler=new r.PluggableAuthHandler({command:this.command,timeoutMillis:this.timeoutMillis,outputFile:this.outputFile}),this.credentialSourceType=`executable`}async retrieveSubjectToken(){if(process.env.GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES!==`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 e;if(this.outputFile&&(e=await this.handler.retrieveCachedResponse()),!e){let t=new Map;t.set(`GOOGLE_EXTERNAL_ACCOUNT_AUDIENCE`,this.audience),t.set(`GOOGLE_EXTERNAL_ACCOUNT_TOKEN_TYPE`,this.subjectTokenType),t.set(`GOOGLE_EXTERNAL_ACCOUNT_INTERACTIVE`,`0`),this.outputFile&&t.set(`GOOGLE_EXTERNAL_ACCOUNT_OUTPUT_FILE`,this.outputFile);let n=this.getServiceAccountEmail();n&&t.set(`GOOGLE_EXTERNAL_ACCOUNT_IMPERSONATED_EMAIL`,n),e=await this.handler.retrieveResponseFromExecutable(t)}if(e.version>1)throw Error(`Version of executable is not currently supported, maximum supported version is 1.`);if(!e.success)throw new r.ExecutableError(e.errorMessage,e.errorCode);if(this.outputFile&&!e.expirationTime)throw new n.InvalidExpirationTimeFieldError("The executable response must contain the `expiration_time` field for successful responses when an output_file has been specified in the configuration.");if(e.isExpired())throw Error(`Executable response is expired.`);return e.subjectToken}}})),Le=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.ExternalAccountClient=void 0;let t=Ee(),n=Ae(),r=Ne(),i=Ie();e.ExternalAccountClient=class{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(e){return e&&e.type===t.EXTERNAL_ACCOUNT_TYPE?e.credential_source?.environment_id?new r.AwsClient(e):e.credential_source?.executable?new i.PluggableAuthClient(e):new n.IdentityPoolClient(e):null}}})),Re=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.ExternalAccountAuthorizedUserClient=e.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE=void 0;let n=M(),r=we(),i=D(),a=t(`stream`),o=Ee();e.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE=`external_account_authorized_user`;var s=class e extends r.OAuthClientAuthHandler{#e;constructor(e){super(e),this.#e=e.tokenRefreshEndpoint}async refreshToken(t,a){let o={...e.RETRY_CONFIG,url:this.#e,method:`POST`,headers:a,data:new URLSearchParams({grant_type:`refresh_token`,refresh_token:t}),responseType:`json`};n.AuthClient.setMethodName(o,`refreshToken`),this.applyClientAuthenticationOptions(o);try{let e=await this.transporter.request(o),t=e.data;return t.res=e,t}catch(e){throw e instanceof i.GaxiosError&&e.response?(0,r.getErrorFromOAuthErrorResponse)(e.response.data,e):e}}};e.ExternalAccountAuthorizedUserClient=class extends n.AuthClient{cachedAccessToken;externalAccountAuthorizedUserHandler;refreshToken;constructor(e){super(e),e.universe_domain&&(this.universeDomain=e.universe_domain),this.refreshToken=e.refresh_token;let t={confidentialClientType:`basic`,clientId:e.client_id,clientSecret:e.client_secret};this.externalAccountAuthorizedUserHandler=new s({tokenRefreshEndpoint:e.token_url??`https://sts.{universeDomain}/v1/oauthtoken`.replace(`{universeDomain}`,this.universeDomain),transporter:this.transporter,clientAuthentication:t}),this.cachedAccessToken=null,this.quotaProjectId=e.quota_project_id,typeof e?.eagerRefreshThresholdMillis==`number`?this.eagerRefreshThresholdMillis=e.eagerRefreshThresholdMillis:this.eagerRefreshThresholdMillis=o.EXPIRATION_TIME_OFFSET,this.forceRefreshOnFailure=!!e?.forceRefreshOnFailure}async getAccessToken(){return(!this.cachedAccessToken||this.isExpired(this.cachedAccessToken))&&await this.refreshAccessTokenAsync(),{token:this.cachedAccessToken.access_token,res:this.cachedAccessToken.res}}async getRequestHeaders(){let e=await this.getAccessToken(),t=new Headers({authorization:`Bearer ${e.token}`});return this.addSharedMetadataHeaders(t)}request(e,t){if(t)this.requestAsync(e).then(e=>t(null,e),e=>t(e,e.response));else return this.requestAsync(e)}async requestAsync(e,t=!1){let n;try{let t=await this.getRequestHeaders();e.headers=i.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,t),n=await this.transporter.request(e)}catch(n){let r=n.response;if(r){let n=r.status,i=r.config.data instanceof a.Readable;if(!t&&(n===401||n===403)&&!i&&this.forceRefreshOnFailure)return await this.refreshAccessTokenAsync(),await this.requestAsync(e,!0)}throw n}return n}async refreshAccessTokenAsync(){let e=await this.externalAccountAuthorizedUserHandler.refreshToken(this.refreshToken);return this.cachedAccessToken={access_token:e.access_token,expiry_date:new Date().getTime()+e.expires_in*1e3,res:e.res},e.refresh_token!==void 0&&(this.refreshToken=e.refresh_token),this.cachedAccessToken}isExpired(e){let t=new Date().getTime();return e.expiry_date?t>=e.expiry_date-this.eagerRefreshThresholdMillis:!1}}})),ze=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.GoogleAuth=e.GoogleAuthExceptionMessages=void 0;let n=t(`child_process`),r=t(`fs`),i=D(),a=A(),o=t(`os`),s=t(`path`),c=ae(),l=ue(),u=de(),d=fe(),f=xe(),p=Se(),m=Ce(),h=Le(),g=Ee(),_=M(),v=Re(),y=j();e.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.
4
+ To learn more about authentication and Google APIs, visit:
5
+ https://cloud.google.com/docs/authentication/getting-started`,NO_CREDENTIALS_FOUND:`Unable to find credentials in current environment.
6
+ To learn more about authentication and Google APIs, visit:
7
+ 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.
8
+ To learn more about Universe Domain retrieval, visit:
9
+ https://cloud.google.com/compute/docs/metadata/predefined-metadata-keys`},e.GoogleAuth=class{checkIsGCE=void 0;useJWTAccessWithScope;defaultServicePath;get isGCE(){return this.checkIsGCE}_findProjectIdPromise;_cachedProjectId;jsonContent=null;apiKey;cachedCredential=null;#e=null;defaultScopes;keyFilename;scopes;clientOptions={};constructor(t={}){if(this._cachedProjectId=t.projectId||null,this.cachedCredential=t.authClient||null,this.keyFilename=t.keyFilename||t.keyFile,this.scopes=t.scopes,this.clientOptions=t.clientOptions||{},this.jsonContent=t.credentials||null,this.apiKey=t.apiKey||this.clientOptions.apiKey||null,this.apiKey&&(this.jsonContent||this.clientOptions.credentials))throw RangeError(e.GoogleAuthExceptionMessages.API_KEY_WITH_CREDENTIALS);t.universeDomain&&(this.clientOptions.universeDomain=t.universeDomain)}setGapicJWTValues(e){e.defaultServicePath=this.defaultServicePath,e.useJWTAccessWithScope=this.useJWTAccessWithScope,e.defaultScopes=this.defaultScopes}getProjectId(e){if(e)this.getProjectIdAsync().then(t=>e(null,t),e);else return this.getProjectIdAsync()}async getProjectIdOptional(){try{return await this.getProjectId()}catch(t){if(t instanceof Error&&t.message===e.GoogleAuthExceptionMessages.NO_PROJECT_ID_FOUND)return null;throw t}}async findAndCacheProjectId(){let t=null;if(t||=await this.getProductionProjectId(),t||=await this.getFileProjectId(),t||=await this.getDefaultServiceProjectId(),t||=await this.getGCEProjectId(),t||=await this.getExternalAccountClientProjectId(),t)return this._cachedProjectId=t,t;throw Error(e.GoogleAuthExceptionMessages.NO_PROJECT_ID_FOUND)}async getProjectIdAsync(){return this._cachedProjectId?this._cachedProjectId:(this._findProjectIdPromise||=this.findAndCacheProjectId(),this._findProjectIdPromise)}async getUniverseDomainFromMetadataServer(){let e;try{e=await a.universe(`universe-domain`),e||=_.DEFAULT_UNIVERSE}catch(t){if(t&&t?.response?.status===404)e=_.DEFAULT_UNIVERSE;else throw t}return e}async getUniverseDomain(){let e=(0,y.originalOrCamelOptions)(this.clientOptions).get(`universe_domain`);try{e??=(await this.getClient()).universeDomain}catch{e??=_.DEFAULT_UNIVERSE}return e}getAnyScopes(){return this.scopes||this.defaultScopes}getApplicationDefault(e={},t){let n;if(typeof e==`function`?t=e:n=e,t)this.getApplicationDefaultAsync(n).then(e=>t(null,e.credential,e.projectId),t);else return this.getApplicationDefaultAsync(n)}async getApplicationDefaultAsync(t={}){if(this.cachedCredential)return await this.#t(this.cachedCredential,null);let n;if(n=await this._tryGetApplicationCredentialsFromEnvironmentVariable(t),n||(n=await this._tryGetApplicationCredentialsFromWellKnownFile(t),n))return n instanceof f.JWT?n.scopes=this.scopes:n instanceof g.BaseExternalAccountClient&&(n.scopes=this.getAnyScopes()),await this.#t(n);if(await this._checkIsGCE())return t.scopes=this.getAnyScopes(),await this.#t(new l.Compute(t));throw Error(e.GoogleAuthExceptionMessages.NO_ADC_FOUND)}async#t(e,t=process.env.GOOGLE_CLOUD_QUOTA_PROJECT||null){let n=await this.getProjectIdOptional();return t&&(e.quotaProjectId=t),this.cachedCredential=e,{credential:e,projectId:n}}async _checkIsGCE(){return this.checkIsGCE===void 0&&(this.checkIsGCE=a.getGCPResidency()||await a.isAvailable()),this.checkIsGCE}async _tryGetApplicationCredentialsFromEnvironmentVariable(e){let t=process.env.GOOGLE_APPLICATION_CREDENTIALS||process.env.google_application_credentials;if(!t||t.length===0)return null;try{return this._getApplicationCredentialsFromFilePath(t,e)}catch(e){throw e instanceof Error&&(e.message=`Unable to read the credential file specified by the GOOGLE_APPLICATION_CREDENTIALS environment variable: ${e.message}`),e}}async _tryGetApplicationCredentialsFromWellKnownFile(e){let t=null;if(this._isWindows())t=process.env.APPDATA;else{let e=process.env.HOME;e&&(t=s.join(e,`.config`))}return t&&(t=s.join(t,`gcloud`,`application_default_credentials.json`),r.existsSync(t)||(t=null)),t?await this._getApplicationCredentialsFromFilePath(t,e):null}async _getApplicationCredentialsFromFilePath(e,t={}){if(!e||e.length===0)throw Error(`The file path is invalid.`);try{if(e=r.realpathSync(e),!r.lstatSync(e).isFile())throw Error()}catch(t){throw t instanceof Error&&(t.message=`The file at ${e} does not exist, or it is not a file. ${t.message}`),t}let n=r.createReadStream(e);return this.fromStream(n,t)}fromImpersonatedJSON(e){if(!e)throw Error(`Must pass in a JSON object containing an impersonated refresh token`);if(e.type!==m.IMPERSONATED_ACCOUNT_TYPE)throw Error(`The incoming JSON object does not have the "${m.IMPERSONATED_ACCOUNT_TYPE}" type`);if(!e.source_credentials)throw Error(`The incoming JSON object does not contain a source_credentials field`);if(!e.service_account_impersonation_url)throw Error(`The incoming JSON object does not contain a service_account_impersonation_url field`);let t=this.fromJSON(e.source_credentials);if(e.service_account_impersonation_url?.length>256)throw RangeError(`Target principal is too long: ${e.service_account_impersonation_url}`);let n=/(?<target>[^/]+):(generateAccessToken|generateIdToken)$/.exec(e.service_account_impersonation_url)?.groups?.target;if(!n)throw RangeError(`Cannot extract target principal from ${e.service_account_impersonation_url}`);let r=(this.scopes||e.scopes||this.defaultScopes)??[];return new m.Impersonated({...e,sourceClient:t,targetPrincipal:n,targetScopes:Array.isArray(r)?r:[r]})}fromJSON(e,t={}){let n,r=(0,y.originalOrCamelOptions)(t).get(`universe_domain`);return e.type===p.USER_REFRESH_ACCOUNT_TYPE?(n=new p.UserRefreshClient(t),n.fromJSON(e)):e.type===m.IMPERSONATED_ACCOUNT_TYPE?n=this.fromImpersonatedJSON(e):e.type===g.EXTERNAL_ACCOUNT_TYPE?(n=h.ExternalAccountClient.fromJSON({...e,...t}),n.scopes=this.getAnyScopes()):e.type===v.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE?n=new v.ExternalAccountAuthorizedUserClient({...e,...t}):(t.scopes=this.scopes,n=new f.JWT(t),this.setGapicJWTValues(n),n.fromJSON(e)),r&&(n.universeDomain=r),n}_cacheClientFromJSON(e,t){let n=this.fromJSON(e,t);return this.jsonContent=e,this.cachedCredential=n,n}fromStream(e,t={},n){let r={};if(typeof t==`function`?n=t:r=t,n)this.fromStreamAsync(e,r).then(e=>n(null,e),n);else return this.fromStreamAsync(e,r)}fromStreamAsync(e,t){return new Promise((n,r)=>{if(!e)throw Error(`Must pass in a stream containing the Google auth settings.`);let i=[];e.setEncoding(`utf8`).on(`error`,r).on(`data`,e=>i.push(e)).on(`end`,()=>{try{try{let e=JSON.parse(i.join(``));return n(this._cacheClientFromJSON(e,t))}catch(e){if(!this.keyFilename)throw e;let t=new f.JWT({...this.clientOptions,keyFile:this.keyFilename});return this.cachedCredential=t,this.setGapicJWTValues(t),n(t)}}catch(e){return r(e)}})})}fromAPIKey(e,t={}){return new f.JWT({...t,apiKey:e})}_isWindows(){let e=o.platform();return!!(e&&e.length>=3&&e.substring(0,3).toLowerCase()===`win`)}async getDefaultServiceProjectId(){return new Promise(e=>{(0,n.exec)(`gcloud config config-helper --format json`,(t,n)=>{if(!t&&n)try{let t=JSON.parse(n).configuration.properties.core.project;e(t);return}catch{}e(null)})})}getProductionProjectId(){return process.env.GCLOUD_PROJECT||process.env.GOOGLE_CLOUD_PROJECT||process.env.gcloud_project||process.env.google_cloud_project}async getFileProjectId(){if(this.cachedCredential)return this.cachedCredential.projectId;if(this.keyFilename){let e=await this.getClient();if(e&&e.projectId)return e.projectId}let e=await this._tryGetApplicationCredentialsFromEnvironmentVariable();return e?e.projectId:null}async getExternalAccountClientProjectId(){return!this.jsonContent||this.jsonContent.type!==g.EXTERNAL_ACCOUNT_TYPE?null:await(await this.getClient()).getProjectId()}async getGCEProjectId(){try{return await a.project(`project-id`)}catch{return null}}getCredentials(e){if(e)this.getCredentialsAsync().then(t=>e(null,t),e);else return this.getCredentialsAsync()}async getCredentialsAsync(){let t=await this.getClient();if(t instanceof m.Impersonated)return{client_email:t.getTargetPrincipal()};if(t instanceof g.BaseExternalAccountClient){let e=t.getServiceAccountEmail();if(e)return{client_email:e,universe_domain:t.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[e,t]=await Promise.all([a.instance(`service-accounts/default/email`),this.getUniverseDomain()]);return{client_email:e,universe_domain:t}}throw Error(e.GoogleAuthExceptionMessages.NO_CREDENTIALS_FOUND)}async getClient(){if(this.cachedCredential)return this.cachedCredential;this.#e=this.#e||this.#n();try{return await this.#e}finally{this.#e=null}}async#n(){if(this.jsonContent)return this._cacheClientFromJSON(this.jsonContent,this.clientOptions);if(this.keyFilename){let e=s.resolve(this.keyFilename),t=r.createReadStream(e);return await this.fromStreamAsync(t,this.clientOptions)}else if(this.apiKey){let e=await this.fromAPIKey(this.apiKey,this.clientOptions);e.scopes=this.scopes;let{credential:t}=await this.#t(e);return t}else{let{credential:e}=await this.getApplicationDefaultAsync(this.clientOptions);return e}}async getIdTokenClient(e){let t=await this.getClient();if(!(`fetchIdToken`in t))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 u.IdTokenClient({targetAudience:e,idTokenProvider:t})}async getAccessToken(){return(await(await this.getClient()).getAccessToken()).token}async getRequestHeaders(e){return(await this.getClient()).getRequestHeaders(e)}async authorizeRequest(e={}){let t=e.url,n=await(await this.getClient()).getRequestHeaders(t);return e.headers=i.Gaxios.mergeHeaders(e.headers,n),e}async fetch(...e){return(await this.getClient()).fetch(...e)}async request(e){return(await this.getClient()).request(e)}getEnv(){return(0,d.getEnv)()}async sign(e,t){let n=await this.getClient(),r=await this.getUniverseDomain();if(t||=`https://iamcredentials.${r}/v1/projects/-/serviceAccounts/`,n instanceof m.Impersonated)return(await n.sign(e)).signedBlob;let i=(0,c.createCrypto)();if(n instanceof f.JWT&&n.key)return await i.sign(n.key,e);let a=await this.getCredentials();if(!a.client_email)throw Error("Cannot sign data without `client_email`.");return this.signBlob(i,a.client_email,e,t)}async signBlob(e,t,n,r){let i=new URL(r+`${t}:signBlob`);return(await this.request({method:`POST`,url:i.href,data:{payload:e.encodeBase64StringUtf8(n)},retry:!0,retryConfig:{httpMethodsToRetry:[`POST`]}})).data.signedBlob}}})),Be=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.IAMAuth=void 0,e.IAMAuth=class{selector;token;constructor(e,t){this.selector=e,this.token=t,this.selector=e,this.token=t}getRequestHeaders(){return{"x-goog-iam-authority-selector":this.selector,"x-goog-iam-authorization-token":this.token}}}})),Ve=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.DownscopedClient=e.EXPIRATION_TIME_OFFSET=e.MAX_ACCESS_BOUNDARY_RULES_COUNT=void 0;let n=D(),r=t(`stream`),i=M(),a=Te();e.MAX_ACCESS_BOUNDARY_RULES_COUNT=10,e.EXPIRATION_TIME_OFFSET=300*1e3,e.DownscopedClient=class extends i.AuthClient{authClient;credentialAccessBoundary;cachedDownscopedAccessToken;stsCredential;constructor(t,n={accessBoundary:{accessBoundaryRules:[]}}){if(super(t instanceof i.AuthClient?{}:t),t instanceof i.AuthClient?(this.authClient=t,this.credentialAccessBoundary=n):(this.authClient=t.authClient,this.credentialAccessBoundary=t.credentialAccessBoundary),this.credentialAccessBoundary.accessBoundary.accessBoundaryRules.length===0)throw Error(`At least one access boundary rule needs to be defined.`);if(this.credentialAccessBoundary.accessBoundary.accessBoundaryRules.length>e.MAX_ACCESS_BOUNDARY_RULES_COUNT)throw Error(`The provided access boundary has more than ${e.MAX_ACCESS_BOUNDARY_RULES_COUNT} access boundary rules.`);for(let e of this.credentialAccessBoundary.accessBoundary.accessBoundaryRules)if(e.availablePermissions.length===0)throw Error(`At least one permission should be defined in access boundary rules.`);this.stsCredential=new a.StsCredentials({tokenExchangeEndpoint:`https://sts.${this.universeDomain}/v1/token`}),this.cachedDownscopedAccessToken=null}setCredentials(e){if(!e.expiry_date)throw Error(`The access token expiry_date field is missing in the provided credentials.`);super.setCredentials(e),this.cachedDownscopedAccessToken=e}async getAccessToken(){return(!this.cachedDownscopedAccessToken||this.isExpired(this.cachedDownscopedAccessToken))&&await this.refreshAccessTokenAsync(),{token:this.cachedDownscopedAccessToken.access_token,expirationTime:this.cachedDownscopedAccessToken.expiry_date,res:this.cachedDownscopedAccessToken.res}}async getRequestHeaders(){let e=await this.getAccessToken(),t=new Headers({authorization:`Bearer ${e.token}`});return this.addSharedMetadataHeaders(t)}request(e,t){if(t)this.requestAsync(e).then(e=>t(null,e),e=>t(e,e.response));else return this.requestAsync(e)}async requestAsync(e,t=!1){let i;try{let t=await this.getRequestHeaders();e.headers=n.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,t),i=await this.transporter.request(e)}catch(n){let i=n.response;if(i){let n=i.status,a=i.config.data instanceof r.Readable;if(!t&&(n===401||n===403)&&!a&&this.forceRefreshOnFailure)return await this.refreshAccessTokenAsync(),await this.requestAsync(e,!0)}throw n}return i}async refreshAccessTokenAsync(){let e={grantType:`urn:ietf:params:oauth:grant-type:token-exchange`,requestedTokenType:`urn:ietf:params:oauth:token-type:access_token`,subjectToken:(await this.authClient.getAccessToken()).token,subjectTokenType:`urn:ietf:params:oauth:token-type:access_token`},t=await this.stsCredential.exchangeToken(e,void 0,this.credentialAccessBoundary),n=this.authClient.credentials?.expiry_date||null,r=t.expires_in?new Date().getTime()+t.expires_in*1e3:n;return this.cachedDownscopedAccessToken={access_token:t.access_token,expiry_date:r,res:t.res},this.credentials={},Object.assign(this.credentials,this.cachedDownscopedAccessToken),delete this.credentials.res,this.emit(`tokens`,{refresh_token:null,expiry_date:this.cachedDownscopedAccessToken.expiry_date,access_token:this.cachedDownscopedAccessToken.access_token,token_type:`Bearer`,id_token:null}),this.cachedDownscopedAccessToken}isExpired(e){let t=new Date().getTime();return e.expiry_date?t>=e.expiry_date-this.eagerRefreshThresholdMillis:!1}}})),He=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.PassThroughClient=void 0;let t=M();e.PassThroughClient=class extends t.AuthClient{async request(e){return this.transporter.request(e)}async getAccessToken(){return{}}async getRequestHeaders(){return new Headers}}})),Ue=n((e=>{var t=e&&e.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);(!i||(`get`in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),n=e&&e.__exportStar||function(e,n){for(var r in e)r!==`default`&&!Object.prototype.hasOwnProperty.call(n,r)&&t(n,e,r)};Object.defineProperty(e,`__esModule`,{value:!0}),e.GoogleAuth=e.auth=e.PassThroughClient=e.ExternalAccountAuthorizedUserClient=e.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE=e.ExecutableError=e.PluggableAuthClient=e.DownscopedClient=e.BaseExternalAccountClient=e.ExternalAccountClient=e.IdentityPoolClient=e.AwsRequestSigner=e.AwsClient=e.UserRefreshClient=e.LoginTicket=e.ClientAuthentication=e.OAuth2Client=e.CodeChallengeMethod=e.Impersonated=e.JWT=e.JWTAccess=e.IdTokenClient=e.IAMAuth=e.GCPEnv=e.Compute=e.DEFAULT_UNIVERSE=e.AuthClient=e.gaxios=e.gcpMetadata=void 0;let r=ze();Object.defineProperty(e,`GoogleAuth`,{enumerable:!0,get:function(){return r.GoogleAuth}}),e.gcpMetadata=A(),e.gaxios=D();var i=M();Object.defineProperty(e,`AuthClient`,{enumerable:!0,get:function(){return i.AuthClient}}),Object.defineProperty(e,`DEFAULT_UNIVERSE`,{enumerable:!0,get:function(){return i.DEFAULT_UNIVERSE}});var a=ue();Object.defineProperty(e,`Compute`,{enumerable:!0,get:function(){return a.Compute}});var o=fe();Object.defineProperty(e,`GCPEnv`,{enumerable:!0,get:function(){return o.GCPEnv}});var s=Be();Object.defineProperty(e,`IAMAuth`,{enumerable:!0,get:function(){return s.IAMAuth}});var c=de();Object.defineProperty(e,`IdTokenClient`,{enumerable:!0,get:function(){return c.IdTokenClient}});var l=be();Object.defineProperty(e,`JWTAccess`,{enumerable:!0,get:function(){return l.JWTAccess}});var u=xe();Object.defineProperty(e,`JWT`,{enumerable:!0,get:function(){return u.JWT}});var d=Ce();Object.defineProperty(e,`Impersonated`,{enumerable:!0,get:function(){return d.Impersonated}});var f=le();Object.defineProperty(e,`CodeChallengeMethod`,{enumerable:!0,get:function(){return f.CodeChallengeMethod}}),Object.defineProperty(e,`OAuth2Client`,{enumerable:!0,get:function(){return f.OAuth2Client}}),Object.defineProperty(e,`ClientAuthentication`,{enumerable:!0,get:function(){return f.ClientAuthentication}});var p=ce();Object.defineProperty(e,`LoginTicket`,{enumerable:!0,get:function(){return p.LoginTicket}});var m=Se();Object.defineProperty(e,`UserRefreshClient`,{enumerable:!0,get:function(){return m.UserRefreshClient}});var h=Ne();Object.defineProperty(e,`AwsClient`,{enumerable:!0,get:function(){return h.AwsClient}});var g=je();Object.defineProperty(e,`AwsRequestSigner`,{enumerable:!0,get:function(){return g.AwsRequestSigner}});var _=Ae();Object.defineProperty(e,`IdentityPoolClient`,{enumerable:!0,get:function(){return _.IdentityPoolClient}});var v=Le();Object.defineProperty(e,`ExternalAccountClient`,{enumerable:!0,get:function(){return v.ExternalAccountClient}});var y=Ee();Object.defineProperty(e,`BaseExternalAccountClient`,{enumerable:!0,get:function(){return y.BaseExternalAccountClient}});var b=Ve();Object.defineProperty(e,`DownscopedClient`,{enumerable:!0,get:function(){return b.DownscopedClient}});var x=Ie();Object.defineProperty(e,`PluggableAuthClient`,{enumerable:!0,get:function(){return x.PluggableAuthClient}}),Object.defineProperty(e,`ExecutableError`,{enumerable:!0,get:function(){return x.ExecutableError}});var S=Re();Object.defineProperty(e,`EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE`,{enumerable:!0,get:function(){return S.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE}}),Object.defineProperty(e,`ExternalAccountAuthorizedUserClient`,{enumerable:!0,get:function(){return S.ExternalAccountAuthorizedUserClient}});var C=He();Object.defineProperty(e,`PassThroughClient`,{enumerable:!0,get:function(){return C.PassThroughClient}}),n(ye(),e),e.auth=new r.GoogleAuth})),We=e(b(),1),Ge=Ue();function Ke(){return{geminiUrl:void 0,vertexUrl:void 0}}function qe(e,t,n,r){if(!e?.baseUrl){let e=Ke();return t?e.vertexUrl??n:e.geminiUrl??r}return e.baseUrl}
10
+ /**
11
+ * @license
12
+ * Copyright 2025 Google LLC
13
+ * SPDX-License-Identifier: Apache-2.0
14
+ */
15
+ var N=class{};function P(e,t){return e.replace(/\{([^}]+)\}/g,(e,n)=>{if(Object.prototype.hasOwnProperty.call(t,n)){let e=t[n];return e==null?``:String(e)}else throw Error(`Key '${n}' not found in valueMap.`)})}function F(e,t,n){for(let r=0;r<t.length-1;r++){let i=t[r];if(i.endsWith(`[]`)){let a=i.slice(0,-2);if(!(a in e))if(Array.isArray(n))e[a]=Array.from({length:n.length},()=>({}));else throw Error(`Value must be a list given an array path ${i}`);if(Array.isArray(e[a])){let i=e[a];if(Array.isArray(n))for(let e=0;e<i.length;e++){let a=i[e];F(a,t.slice(r+1),n[e])}else for(let e of i)F(e,t.slice(r+1),n)}return}else if(i.endsWith(`[0]`)){let a=i.slice(0,-3);a in e||(e[a]=[{}]);let o=e[a];F(o[0],t.slice(r+1),n);return}(!e[i]||typeof e[i]!=`object`)&&(e[i]={}),e=e[i]}let r=t[t.length-1],i=e[r];if(i!==void 0){if(!n||typeof n==`object`&&Object.keys(n).length===0||n===i)return;if(typeof i==`object`&&typeof n==`object`&&i!==null&&n!==null)Object.assign(i,n);else throw Error(`Cannot set value for an existing key. Key: ${r}`)}else r===`_self`&&typeof n==`object`&&n&&!Array.isArray(n)?Object.assign(e,n):e[r]=n}function I(e,t,n=void 0){try{if(t.length===1&&t[0]===`_self`)return e;for(let r=0;r<t.length;r++){if(typeof e!=`object`||!e)return n;let i=t[r];if(i.endsWith(`[]`)){let a=i.slice(0,-2);if(a in e){let i=e[a];return Array.isArray(i)?i.map(e=>I(e,t.slice(r+1),n)):n}else return n}else e=e[i]}return e}catch(e){if(e instanceof TypeError)return n;throw e}}function Je(e,t){for(let[n,r]of Object.entries(t)){let t=n.split(`.`),i=r.split(`.`),a=new Set,o=-1;for(let e=0;e<t.length;e++)if(t[e]===`*`){o=e;break}if(o!==-1&&i.length>o)for(let e=o;e<i.length;e++){let t=i[e];t!==`*`&&!t.endsWith(`[]`)&&!t.endsWith(`[0]`)&&a.add(t)}Ye(e,t,i,0,a)}}function Ye(e,t,n,r,i){if(r>=t.length||typeof e!=`object`||!e)return;let a=t[r];if(a.endsWith(`[]`)){let o=a.slice(0,-2),s=e;if(o in s&&Array.isArray(s[o]))for(let e of s[o])Ye(e,t,n,r+1,i)}else if(a===`*`){if(typeof e==`object`&&e&&!Array.isArray(e)){let t=e,a=Object.keys(t).filter(e=>!e.startsWith(`_`)&&!i.has(e)),o={};for(let e of a)o[e]=t[e];for(let[e,i]of Object.entries(o)){let a=[];for(let t of n.slice(r))t===`*`?a.push(e):a.push(t);F(t,a,i)}for(let e of a)delete t[e]}}else{let o=e;a in o&&Ye(o[a],t,n,r+1,i)}}
16
+ /**
17
+ * @license
18
+ * Copyright 2025 Google LLC
19
+ * SPDX-License-Identifier: Apache-2.0
20
+ */
21
+ function Xe(e){if(typeof e!=`string`)throw Error(`fromImageBytes must be a string`);return e}
22
+ /**
23
+ * @license
24
+ * Copyright 2025 Google LLC
25
+ * SPDX-License-Identifier: Apache-2.0
26
+ */
27
+ function Ze(e){let t={},n=I(e,[`operationName`]);n!=null&&F(t,[`operationName`],n);let r=I(e,[`resourceName`]);return r!=null&&F(t,[`_url`,`resourceName`],r),t}function Qe(e){let t={},n=I(e,[`name`]);n!=null&&F(t,[`name`],n);let r=I(e,[`metadata`]);r!=null&&F(t,[`metadata`],r);let i=I(e,[`done`]);i!=null&&F(t,[`done`],i);let a=I(e,[`error`]);a!=null&&F(t,[`error`],a);let o=I(e,[`response`,`generateVideoResponse`]);return o!=null&&F(t,[`response`],et(o)),t}function $e(e){let t={},n=I(e,[`name`]);n!=null&&F(t,[`name`],n);let r=I(e,[`metadata`]);r!=null&&F(t,[`metadata`],r);let i=I(e,[`done`]);i!=null&&F(t,[`done`],i);let a=I(e,[`error`]);a!=null&&F(t,[`error`],a);let o=I(e,[`response`]);return o!=null&&F(t,[`response`],tt(o)),t}function et(e){let t={},n=I(e,[`generatedSamples`]);if(n!=null){let e=n;Array.isArray(e)&&(e=e.map(e=>nt(e))),F(t,[`generatedVideos`],e)}let r=I(e,[`raiMediaFilteredCount`]);r!=null&&F(t,[`raiMediaFilteredCount`],r);let i=I(e,[`raiMediaFilteredReasons`]);return i!=null&&F(t,[`raiMediaFilteredReasons`],i),t}function tt(e){let t={},n=I(e,[`videos`]);if(n!=null){let e=n;Array.isArray(e)&&(e=e.map(e=>rt(e))),F(t,[`generatedVideos`],e)}let r=I(e,[`raiMediaFilteredCount`]);r!=null&&F(t,[`raiMediaFilteredCount`],r);let i=I(e,[`raiMediaFilteredReasons`]);return i!=null&&F(t,[`raiMediaFilteredReasons`],i),t}function nt(e){let t={},n=I(e,[`video`]);return n!=null&&F(t,[`video`],ut(n)),t}function rt(e){let t={},n=I(e,[`_self`]);return n!=null&&F(t,[`video`],dt(n)),t}function it(e){let t={},n=I(e,[`operationName`]);return n!=null&&F(t,[`_url`,`operationName`],n),t}function at(e){let t={},n=I(e,[`operationName`]);return n!=null&&F(t,[`_url`,`operationName`],n),t}function ot(e){let t={},n=I(e,[`name`]);n!=null&&F(t,[`name`],n);let r=I(e,[`metadata`]);r!=null&&F(t,[`metadata`],r);let i=I(e,[`done`]);i!=null&&F(t,[`done`],i);let a=I(e,[`error`]);a!=null&&F(t,[`error`],a);let o=I(e,[`response`]);return o!=null&&F(t,[`response`],st(o)),t}function st(e){let t={},n=I(e,[`sdkHttpResponse`]);n!=null&&F(t,[`sdkHttpResponse`],n);let r=I(e,[`parent`]);r!=null&&F(t,[`parent`],r);let i=I(e,[`documentName`]);return i!=null&&F(t,[`documentName`],i),t}function ct(e){let t={},n=I(e,[`name`]);n!=null&&F(t,[`name`],n);let r=I(e,[`metadata`]);r!=null&&F(t,[`metadata`],r);let i=I(e,[`done`]);i!=null&&F(t,[`done`],i);let a=I(e,[`error`]);a!=null&&F(t,[`error`],a);let o=I(e,[`response`]);return o!=null&&F(t,[`response`],lt(o)),t}function lt(e){let t={},n=I(e,[`sdkHttpResponse`]);n!=null&&F(t,[`sdkHttpResponse`],n);let r=I(e,[`parent`]);r!=null&&F(t,[`parent`],r);let i=I(e,[`documentName`]);return i!=null&&F(t,[`documentName`],i),t}function ut(e){let t={},n=I(e,[`uri`]);n!=null&&F(t,[`uri`],n);let r=I(e,[`encodedVideo`]);r!=null&&F(t,[`videoBytes`],Xe(r));let i=I(e,[`encoding`]);return i!=null&&F(t,[`mimeType`],i),t}function dt(e){let t={},n=I(e,[`gcsUri`]);n!=null&&F(t,[`uri`],n);let r=I(e,[`bytesBase64Encoded`]);r!=null&&F(t,[`videoBytes`],Xe(r));let i=I(e,[`mimeType`]);return i!=null&&F(t,[`mimeType`],i),t}
28
+ /**
29
+ * @license
30
+ * Copyright 2025 Google LLC
31
+ * SPDX-License-Identifier: Apache-2.0
32
+ */
33
+ var ft;(function(e){e.LANGUAGE_UNSPECIFIED=`LANGUAGE_UNSPECIFIED`,e.PYTHON=`PYTHON`})(ft||={});var pt;(function(e){e.OUTCOME_UNSPECIFIED=`OUTCOME_UNSPECIFIED`,e.OUTCOME_OK=`OUTCOME_OK`,e.OUTCOME_FAILED=`OUTCOME_FAILED`,e.OUTCOME_DEADLINE_EXCEEDED=`OUTCOME_DEADLINE_EXCEEDED`})(pt||={});var mt;(function(e){e.SCHEDULING_UNSPECIFIED=`SCHEDULING_UNSPECIFIED`,e.SILENT=`SILENT`,e.WHEN_IDLE=`WHEN_IDLE`,e.INTERRUPT=`INTERRUPT`})(mt||={});var ht;(function(e){e.TYPE_UNSPECIFIED=`TYPE_UNSPECIFIED`,e.STRING=`STRING`,e.NUMBER=`NUMBER`,e.INTEGER=`INTEGER`,e.BOOLEAN=`BOOLEAN`,e.ARRAY=`ARRAY`,e.OBJECT=`OBJECT`,e.NULL=`NULL`})(ht||={});var gt;(function(e){e.ENVIRONMENT_UNSPECIFIED=`ENVIRONMENT_UNSPECIFIED`,e.ENVIRONMENT_BROWSER=`ENVIRONMENT_BROWSER`})(gt||={});var _t;(function(e){e.AUTH_TYPE_UNSPECIFIED=`AUTH_TYPE_UNSPECIFIED`,e.NO_AUTH=`NO_AUTH`,e.API_KEY_AUTH=`API_KEY_AUTH`,e.HTTP_BASIC_AUTH=`HTTP_BASIC_AUTH`,e.GOOGLE_SERVICE_ACCOUNT_AUTH=`GOOGLE_SERVICE_ACCOUNT_AUTH`,e.OAUTH=`OAUTH`,e.OIDC_AUTH=`OIDC_AUTH`})(_t||={});var vt;(function(e){e.HTTP_IN_UNSPECIFIED=`HTTP_IN_UNSPECIFIED`,e.HTTP_IN_QUERY=`HTTP_IN_QUERY`,e.HTTP_IN_HEADER=`HTTP_IN_HEADER`,e.HTTP_IN_PATH=`HTTP_IN_PATH`,e.HTTP_IN_BODY=`HTTP_IN_BODY`,e.HTTP_IN_COOKIE=`HTTP_IN_COOKIE`})(vt||={});var yt;(function(e){e.API_SPEC_UNSPECIFIED=`API_SPEC_UNSPECIFIED`,e.SIMPLE_SEARCH=`SIMPLE_SEARCH`,e.ELASTIC_SEARCH=`ELASTIC_SEARCH`})(yt||={});var bt;(function(e){e.PHISH_BLOCK_THRESHOLD_UNSPECIFIED=`PHISH_BLOCK_THRESHOLD_UNSPECIFIED`,e.BLOCK_LOW_AND_ABOVE=`BLOCK_LOW_AND_ABOVE`,e.BLOCK_MEDIUM_AND_ABOVE=`BLOCK_MEDIUM_AND_ABOVE`,e.BLOCK_HIGH_AND_ABOVE=`BLOCK_HIGH_AND_ABOVE`,e.BLOCK_HIGHER_AND_ABOVE=`BLOCK_HIGHER_AND_ABOVE`,e.BLOCK_VERY_HIGH_AND_ABOVE=`BLOCK_VERY_HIGH_AND_ABOVE`,e.BLOCK_ONLY_EXTREMELY_HIGH=`BLOCK_ONLY_EXTREMELY_HIGH`})(bt||={});var xt;(function(e){e.UNSPECIFIED=`UNSPECIFIED`,e.BLOCKING=`BLOCKING`,e.NON_BLOCKING=`NON_BLOCKING`})(xt||={});var St;(function(e){e.MODE_UNSPECIFIED=`MODE_UNSPECIFIED`,e.MODE_DYNAMIC=`MODE_DYNAMIC`})(St||={});var Ct;(function(e){e.MODE_UNSPECIFIED=`MODE_UNSPECIFIED`,e.AUTO=`AUTO`,e.ANY=`ANY`,e.NONE=`NONE`,e.VALIDATED=`VALIDATED`})(Ct||={});var wt;(function(e){e.THINKING_LEVEL_UNSPECIFIED=`THINKING_LEVEL_UNSPECIFIED`,e.MINIMAL=`MINIMAL`,e.LOW=`LOW`,e.MEDIUM=`MEDIUM`,e.HIGH=`HIGH`})(wt||={});var Tt;(function(e){e.DONT_ALLOW=`DONT_ALLOW`,e.ALLOW_ADULT=`ALLOW_ADULT`,e.ALLOW_ALL=`ALLOW_ALL`})(Tt||={});var Et;(function(e){e.PROMINENT_PEOPLE_UNSPECIFIED=`PROMINENT_PEOPLE_UNSPECIFIED`,e.ALLOW_PROMINENT_PEOPLE=`ALLOW_PROMINENT_PEOPLE`,e.BLOCK_PROMINENT_PEOPLE=`BLOCK_PROMINENT_PEOPLE`})(Et||={});var Dt;(function(e){e.HARM_CATEGORY_UNSPECIFIED=`HARM_CATEGORY_UNSPECIFIED`,e.HARM_CATEGORY_HARASSMENT=`HARM_CATEGORY_HARASSMENT`,e.HARM_CATEGORY_HATE_SPEECH=`HARM_CATEGORY_HATE_SPEECH`,e.HARM_CATEGORY_SEXUALLY_EXPLICIT=`HARM_CATEGORY_SEXUALLY_EXPLICIT`,e.HARM_CATEGORY_DANGEROUS_CONTENT=`HARM_CATEGORY_DANGEROUS_CONTENT`,e.HARM_CATEGORY_CIVIC_INTEGRITY=`HARM_CATEGORY_CIVIC_INTEGRITY`,e.HARM_CATEGORY_IMAGE_HATE=`HARM_CATEGORY_IMAGE_HATE`,e.HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT=`HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT`,e.HARM_CATEGORY_IMAGE_HARASSMENT=`HARM_CATEGORY_IMAGE_HARASSMENT`,e.HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT=`HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT`,e.HARM_CATEGORY_JAILBREAK=`HARM_CATEGORY_JAILBREAK`})(Dt||={});var Ot;(function(e){e.HARM_BLOCK_METHOD_UNSPECIFIED=`HARM_BLOCK_METHOD_UNSPECIFIED`,e.SEVERITY=`SEVERITY`,e.PROBABILITY=`PROBABILITY`})(Ot||={});var kt;(function(e){e.HARM_BLOCK_THRESHOLD_UNSPECIFIED=`HARM_BLOCK_THRESHOLD_UNSPECIFIED`,e.BLOCK_LOW_AND_ABOVE=`BLOCK_LOW_AND_ABOVE`,e.BLOCK_MEDIUM_AND_ABOVE=`BLOCK_MEDIUM_AND_ABOVE`,e.BLOCK_ONLY_HIGH=`BLOCK_ONLY_HIGH`,e.BLOCK_NONE=`BLOCK_NONE`,e.OFF=`OFF`})(kt||={});var L;(function(e){e.FINISH_REASON_UNSPECIFIED=`FINISH_REASON_UNSPECIFIED`,e.STOP=`STOP`,e.MAX_TOKENS=`MAX_TOKENS`,e.SAFETY=`SAFETY`,e.RECITATION=`RECITATION`,e.LANGUAGE=`LANGUAGE`,e.OTHER=`OTHER`,e.BLOCKLIST=`BLOCKLIST`,e.PROHIBITED_CONTENT=`PROHIBITED_CONTENT`,e.SPII=`SPII`,e.MALFORMED_FUNCTION_CALL=`MALFORMED_FUNCTION_CALL`,e.IMAGE_SAFETY=`IMAGE_SAFETY`,e.UNEXPECTED_TOOL_CALL=`UNEXPECTED_TOOL_CALL`,e.IMAGE_PROHIBITED_CONTENT=`IMAGE_PROHIBITED_CONTENT`,e.NO_IMAGE=`NO_IMAGE`,e.IMAGE_RECITATION=`IMAGE_RECITATION`,e.IMAGE_OTHER=`IMAGE_OTHER`})(L||={});var At;(function(e){e.HARM_PROBABILITY_UNSPECIFIED=`HARM_PROBABILITY_UNSPECIFIED`,e.NEGLIGIBLE=`NEGLIGIBLE`,e.LOW=`LOW`,e.MEDIUM=`MEDIUM`,e.HIGH=`HIGH`})(At||={});var jt;(function(e){e.HARM_SEVERITY_UNSPECIFIED=`HARM_SEVERITY_UNSPECIFIED`,e.HARM_SEVERITY_NEGLIGIBLE=`HARM_SEVERITY_NEGLIGIBLE`,e.HARM_SEVERITY_LOW=`HARM_SEVERITY_LOW`,e.HARM_SEVERITY_MEDIUM=`HARM_SEVERITY_MEDIUM`,e.HARM_SEVERITY_HIGH=`HARM_SEVERITY_HIGH`})(jt||={});var Mt;(function(e){e.URL_RETRIEVAL_STATUS_UNSPECIFIED=`URL_RETRIEVAL_STATUS_UNSPECIFIED`,e.URL_RETRIEVAL_STATUS_SUCCESS=`URL_RETRIEVAL_STATUS_SUCCESS`,e.URL_RETRIEVAL_STATUS_ERROR=`URL_RETRIEVAL_STATUS_ERROR`,e.URL_RETRIEVAL_STATUS_PAYWALL=`URL_RETRIEVAL_STATUS_PAYWALL`,e.URL_RETRIEVAL_STATUS_UNSAFE=`URL_RETRIEVAL_STATUS_UNSAFE`})(Mt||={});var Nt;(function(e){e.BLOCKED_REASON_UNSPECIFIED=`BLOCKED_REASON_UNSPECIFIED`,e.SAFETY=`SAFETY`,e.OTHER=`OTHER`,e.BLOCKLIST=`BLOCKLIST`,e.PROHIBITED_CONTENT=`PROHIBITED_CONTENT`,e.IMAGE_SAFETY=`IMAGE_SAFETY`,e.MODEL_ARMOR=`MODEL_ARMOR`,e.JAILBREAK=`JAILBREAK`})(Nt||={});var Pt;(function(e){e.TRAFFIC_TYPE_UNSPECIFIED=`TRAFFIC_TYPE_UNSPECIFIED`,e.ON_DEMAND=`ON_DEMAND`,e.ON_DEMAND_PRIORITY=`ON_DEMAND_PRIORITY`,e.ON_DEMAND_FLEX=`ON_DEMAND_FLEX`,e.PROVISIONED_THROUGHPUT=`PROVISIONED_THROUGHPUT`})(Pt||={});var Ft;(function(e){e.MODALITY_UNSPECIFIED=`MODALITY_UNSPECIFIED`,e.TEXT=`TEXT`,e.IMAGE=`IMAGE`,e.AUDIO=`AUDIO`,e.VIDEO=`VIDEO`})(Ft||={});var It;(function(e){e.MODEL_STAGE_UNSPECIFIED=`MODEL_STAGE_UNSPECIFIED`,e.UNSTABLE_EXPERIMENTAL=`UNSTABLE_EXPERIMENTAL`,e.EXPERIMENTAL=`EXPERIMENTAL`,e.PREVIEW=`PREVIEW`,e.STABLE=`STABLE`,e.LEGACY=`LEGACY`,e.DEPRECATED=`DEPRECATED`,e.RETIRED=`RETIRED`})(It||={});var Lt;(function(e){e.MEDIA_RESOLUTION_UNSPECIFIED=`MEDIA_RESOLUTION_UNSPECIFIED`,e.MEDIA_RESOLUTION_LOW=`MEDIA_RESOLUTION_LOW`,e.MEDIA_RESOLUTION_MEDIUM=`MEDIA_RESOLUTION_MEDIUM`,e.MEDIA_RESOLUTION_HIGH=`MEDIA_RESOLUTION_HIGH`})(Lt||={});var Rt;(function(e){e.TUNING_MODE_UNSPECIFIED=`TUNING_MODE_UNSPECIFIED`,e.TUNING_MODE_FULL=`TUNING_MODE_FULL`,e.TUNING_MODE_PEFT_ADAPTER=`TUNING_MODE_PEFT_ADAPTER`})(Rt||={});var zt;(function(e){e.ADAPTER_SIZE_UNSPECIFIED=`ADAPTER_SIZE_UNSPECIFIED`,e.ADAPTER_SIZE_ONE=`ADAPTER_SIZE_ONE`,e.ADAPTER_SIZE_TWO=`ADAPTER_SIZE_TWO`,e.ADAPTER_SIZE_FOUR=`ADAPTER_SIZE_FOUR`,e.ADAPTER_SIZE_EIGHT=`ADAPTER_SIZE_EIGHT`,e.ADAPTER_SIZE_SIXTEEN=`ADAPTER_SIZE_SIXTEEN`,e.ADAPTER_SIZE_THIRTY_TWO=`ADAPTER_SIZE_THIRTY_TWO`})(zt||={});var Bt;(function(e){e.JOB_STATE_UNSPECIFIED=`JOB_STATE_UNSPECIFIED`,e.JOB_STATE_QUEUED=`JOB_STATE_QUEUED`,e.JOB_STATE_PENDING=`JOB_STATE_PENDING`,e.JOB_STATE_RUNNING=`JOB_STATE_RUNNING`,e.JOB_STATE_SUCCEEDED=`JOB_STATE_SUCCEEDED`,e.JOB_STATE_FAILED=`JOB_STATE_FAILED`,e.JOB_STATE_CANCELLING=`JOB_STATE_CANCELLING`,e.JOB_STATE_CANCELLED=`JOB_STATE_CANCELLED`,e.JOB_STATE_PAUSED=`JOB_STATE_PAUSED`,e.JOB_STATE_EXPIRED=`JOB_STATE_EXPIRED`,e.JOB_STATE_UPDATING=`JOB_STATE_UPDATING`,e.JOB_STATE_PARTIALLY_SUCCEEDED=`JOB_STATE_PARTIALLY_SUCCEEDED`})(Bt||={});var Vt;(function(e){e.TUNING_JOB_STATE_UNSPECIFIED=`TUNING_JOB_STATE_UNSPECIFIED`,e.TUNING_JOB_STATE_WAITING_FOR_QUOTA=`TUNING_JOB_STATE_WAITING_FOR_QUOTA`,e.TUNING_JOB_STATE_PROCESSING_DATASET=`TUNING_JOB_STATE_PROCESSING_DATASET`,e.TUNING_JOB_STATE_WAITING_FOR_CAPACITY=`TUNING_JOB_STATE_WAITING_FOR_CAPACITY`,e.TUNING_JOB_STATE_TUNING=`TUNING_JOB_STATE_TUNING`,e.TUNING_JOB_STATE_POST_PROCESSING=`TUNING_JOB_STATE_POST_PROCESSING`})(Vt||={});var Ht;(function(e){e.AGGREGATION_METRIC_UNSPECIFIED=`AGGREGATION_METRIC_UNSPECIFIED`,e.AVERAGE=`AVERAGE`,e.MODE=`MODE`,e.STANDARD_DEVIATION=`STANDARD_DEVIATION`,e.VARIANCE=`VARIANCE`,e.MINIMUM=`MINIMUM`,e.MAXIMUM=`MAXIMUM`,e.MEDIAN=`MEDIAN`,e.PERCENTILE_P90=`PERCENTILE_P90`,e.PERCENTILE_P95=`PERCENTILE_P95`,e.PERCENTILE_P99=`PERCENTILE_P99`})(Ht||={});var Ut;(function(e){e.PAIRWISE_CHOICE_UNSPECIFIED=`PAIRWISE_CHOICE_UNSPECIFIED`,e.BASELINE=`BASELINE`,e.CANDIDATE=`CANDIDATE`,e.TIE=`TIE`})(Ut||={});var Wt;(function(e){e.TUNING_TASK_UNSPECIFIED=`TUNING_TASK_UNSPECIFIED`,e.TUNING_TASK_I2V=`TUNING_TASK_I2V`,e.TUNING_TASK_T2V=`TUNING_TASK_T2V`,e.TUNING_TASK_R2V=`TUNING_TASK_R2V`})(Wt||={});var Gt;(function(e){e.STATE_UNSPECIFIED=`STATE_UNSPECIFIED`,e.STATE_PENDING=`STATE_PENDING`,e.STATE_ACTIVE=`STATE_ACTIVE`,e.STATE_FAILED=`STATE_FAILED`})(Gt||={});var Kt;(function(e){e.MEDIA_RESOLUTION_UNSPECIFIED=`MEDIA_RESOLUTION_UNSPECIFIED`,e.MEDIA_RESOLUTION_LOW=`MEDIA_RESOLUTION_LOW`,e.MEDIA_RESOLUTION_MEDIUM=`MEDIA_RESOLUTION_MEDIUM`,e.MEDIA_RESOLUTION_HIGH=`MEDIA_RESOLUTION_HIGH`,e.MEDIA_RESOLUTION_ULTRA_HIGH=`MEDIA_RESOLUTION_ULTRA_HIGH`})(Kt||={});var qt;(function(e){e.TOOL_TYPE_UNSPECIFIED=`TOOL_TYPE_UNSPECIFIED`,e.GOOGLE_SEARCH_WEB=`GOOGLE_SEARCH_WEB`,e.GOOGLE_SEARCH_IMAGE=`GOOGLE_SEARCH_IMAGE`,e.URL_CONTEXT=`URL_CONTEXT`,e.GOOGLE_MAPS=`GOOGLE_MAPS`,e.FILE_SEARCH=`FILE_SEARCH`})(qt||={});var Jt;(function(e){e.COLLECTION=`COLLECTION`})(Jt||={});var Yt;(function(e){e.UNSPECIFIED=`unspecified`,e.FLEX=`flex`,e.STANDARD=`standard`,e.PRIORITY=`priority`})(Yt||={});var Xt;(function(e){e.FEATURE_SELECTION_PREFERENCE_UNSPECIFIED=`FEATURE_SELECTION_PREFERENCE_UNSPECIFIED`,e.PRIORITIZE_QUALITY=`PRIORITIZE_QUALITY`,e.BALANCED=`BALANCED`,e.PRIORITIZE_COST=`PRIORITIZE_COST`})(Xt||={});var Zt;(function(e){e.PREDICT=`PREDICT`,e.EMBED_CONTENT=`EMBED_CONTENT`})(Zt||={});var Qt;(function(e){e.BLOCK_LOW_AND_ABOVE=`BLOCK_LOW_AND_ABOVE`,e.BLOCK_MEDIUM_AND_ABOVE=`BLOCK_MEDIUM_AND_ABOVE`,e.BLOCK_ONLY_HIGH=`BLOCK_ONLY_HIGH`,e.BLOCK_NONE=`BLOCK_NONE`})(Qt||={});var $t;(function(e){e.auto=`auto`,e.en=`en`,e.ja=`ja`,e.ko=`ko`,e.hi=`hi`,e.zh=`zh`,e.pt=`pt`,e.es=`es`})($t||={});var en;(function(e){e.MASK_MODE_DEFAULT=`MASK_MODE_DEFAULT`,e.MASK_MODE_USER_PROVIDED=`MASK_MODE_USER_PROVIDED`,e.MASK_MODE_BACKGROUND=`MASK_MODE_BACKGROUND`,e.MASK_MODE_FOREGROUND=`MASK_MODE_FOREGROUND`,e.MASK_MODE_SEMANTIC=`MASK_MODE_SEMANTIC`})(en||={});var tn;(function(e){e.CONTROL_TYPE_DEFAULT=`CONTROL_TYPE_DEFAULT`,e.CONTROL_TYPE_CANNY=`CONTROL_TYPE_CANNY`,e.CONTROL_TYPE_SCRIBBLE=`CONTROL_TYPE_SCRIBBLE`,e.CONTROL_TYPE_FACE_MESH=`CONTROL_TYPE_FACE_MESH`})(tn||={});var nn;(function(e){e.SUBJECT_TYPE_DEFAULT=`SUBJECT_TYPE_DEFAULT`,e.SUBJECT_TYPE_PERSON=`SUBJECT_TYPE_PERSON`,e.SUBJECT_TYPE_ANIMAL=`SUBJECT_TYPE_ANIMAL`,e.SUBJECT_TYPE_PRODUCT=`SUBJECT_TYPE_PRODUCT`})(nn||={});var rn;(function(e){e.EDIT_MODE_DEFAULT=`EDIT_MODE_DEFAULT`,e.EDIT_MODE_INPAINT_REMOVAL=`EDIT_MODE_INPAINT_REMOVAL`,e.EDIT_MODE_INPAINT_INSERTION=`EDIT_MODE_INPAINT_INSERTION`,e.EDIT_MODE_OUTPAINT=`EDIT_MODE_OUTPAINT`,e.EDIT_MODE_CONTROLLED_EDITING=`EDIT_MODE_CONTROLLED_EDITING`,e.EDIT_MODE_STYLE=`EDIT_MODE_STYLE`,e.EDIT_MODE_BGSWAP=`EDIT_MODE_BGSWAP`,e.EDIT_MODE_PRODUCT_IMAGE=`EDIT_MODE_PRODUCT_IMAGE`})(rn||={});var an;(function(e){e.FOREGROUND=`FOREGROUND`,e.BACKGROUND=`BACKGROUND`,e.PROMPT=`PROMPT`,e.SEMANTIC=`SEMANTIC`,e.INTERACTIVE=`INTERACTIVE`})(an||={});var on;(function(e){e.ASSET=`ASSET`,e.STYLE=`STYLE`})(on||={});var sn;(function(e){e.INSERT=`INSERT`,e.REMOVE=`REMOVE`,e.REMOVE_STATIC=`REMOVE_STATIC`,e.OUTPAINT=`OUTPAINT`})(sn||={});var cn;(function(e){e.OPTIMIZED=`OPTIMIZED`,e.LOSSLESS=`LOSSLESS`})(cn||={});var ln;(function(e){e.SUPERVISED_FINE_TUNING=`SUPERVISED_FINE_TUNING`,e.PREFERENCE_TUNING=`PREFERENCE_TUNING`,e.DISTILLATION=`DISTILLATION`})(ln||={});var un;(function(e){e.STATE_UNSPECIFIED=`STATE_UNSPECIFIED`,e.PROCESSING=`PROCESSING`,e.ACTIVE=`ACTIVE`,e.FAILED=`FAILED`})(un||={});var dn;(function(e){e.SOURCE_UNSPECIFIED=`SOURCE_UNSPECIFIED`,e.UPLOADED=`UPLOADED`,e.GENERATED=`GENERATED`,e.REGISTERED=`REGISTERED`})(dn||={});var fn;(function(e){e.TURN_COMPLETE_REASON_UNSPECIFIED=`TURN_COMPLETE_REASON_UNSPECIFIED`,e.MALFORMED_FUNCTION_CALL=`MALFORMED_FUNCTION_CALL`,e.RESPONSE_REJECTED=`RESPONSE_REJECTED`,e.NEED_MORE_INPUT=`NEED_MORE_INPUT`,e.PROHIBITED_INPUT_CONTENT=`PROHIBITED_INPUT_CONTENT`,e.IMAGE_PROHIBITED_INPUT_CONTENT=`IMAGE_PROHIBITED_INPUT_CONTENT`,e.INPUT_TEXT_CONTAIN_PROMINENT_PERSON_PROHIBITED=`INPUT_TEXT_CONTAIN_PROMINENT_PERSON_PROHIBITED`,e.INPUT_IMAGE_CELEBRITY=`INPUT_IMAGE_CELEBRITY`,e.INPUT_IMAGE_PHOTO_REALISTIC_CHILD_PROHIBITED=`INPUT_IMAGE_PHOTO_REALISTIC_CHILD_PROHIBITED`,e.INPUT_TEXT_NCII_PROHIBITED=`INPUT_TEXT_NCII_PROHIBITED`,e.INPUT_OTHER=`INPUT_OTHER`,e.INPUT_IP_PROHIBITED=`INPUT_IP_PROHIBITED`,e.BLOCKLIST=`BLOCKLIST`,e.UNSAFE_PROMPT_FOR_IMAGE_GENERATION=`UNSAFE_PROMPT_FOR_IMAGE_GENERATION`,e.GENERATED_IMAGE_SAFETY=`GENERATED_IMAGE_SAFETY`,e.GENERATED_CONTENT_SAFETY=`GENERATED_CONTENT_SAFETY`,e.GENERATED_AUDIO_SAFETY=`GENERATED_AUDIO_SAFETY`,e.GENERATED_VIDEO_SAFETY=`GENERATED_VIDEO_SAFETY`,e.GENERATED_CONTENT_PROHIBITED=`GENERATED_CONTENT_PROHIBITED`,e.GENERATED_CONTENT_BLOCKLIST=`GENERATED_CONTENT_BLOCKLIST`,e.GENERATED_IMAGE_PROHIBITED=`GENERATED_IMAGE_PROHIBITED`,e.GENERATED_IMAGE_CELEBRITY=`GENERATED_IMAGE_CELEBRITY`,e.GENERATED_IMAGE_PROMINENT_PEOPLE_DETECTED_BY_REWRITER=`GENERATED_IMAGE_PROMINENT_PEOPLE_DETECTED_BY_REWRITER`,e.GENERATED_IMAGE_IDENTIFIABLE_PEOPLE=`GENERATED_IMAGE_IDENTIFIABLE_PEOPLE`,e.GENERATED_IMAGE_MINORS=`GENERATED_IMAGE_MINORS`,e.OUTPUT_IMAGE_IP_PROHIBITED=`OUTPUT_IMAGE_IP_PROHIBITED`,e.GENERATED_OTHER=`GENERATED_OTHER`,e.MAX_REGENERATION_REACHED=`MAX_REGENERATION_REACHED`})(fn||={});var pn;(function(e){e.MODALITY_UNSPECIFIED=`MODALITY_UNSPECIFIED`,e.TEXT=`TEXT`,e.IMAGE=`IMAGE`,e.VIDEO=`VIDEO`,e.AUDIO=`AUDIO`,e.DOCUMENT=`DOCUMENT`})(pn||={});var mn;(function(e){e.VAD_SIGNAL_TYPE_UNSPECIFIED=`VAD_SIGNAL_TYPE_UNSPECIFIED`,e.VAD_SIGNAL_TYPE_SOS=`VAD_SIGNAL_TYPE_SOS`,e.VAD_SIGNAL_TYPE_EOS=`VAD_SIGNAL_TYPE_EOS`})(mn||={});var hn;(function(e){e.TYPE_UNSPECIFIED=`TYPE_UNSPECIFIED`,e.ACTIVITY_START=`ACTIVITY_START`,e.ACTIVITY_END=`ACTIVITY_END`})(hn||={});var gn;(function(e){e.START_SENSITIVITY_UNSPECIFIED=`START_SENSITIVITY_UNSPECIFIED`,e.START_SENSITIVITY_HIGH=`START_SENSITIVITY_HIGH`,e.START_SENSITIVITY_LOW=`START_SENSITIVITY_LOW`})(gn||={});var _n;(function(e){e.END_SENSITIVITY_UNSPECIFIED=`END_SENSITIVITY_UNSPECIFIED`,e.END_SENSITIVITY_HIGH=`END_SENSITIVITY_HIGH`,e.END_SENSITIVITY_LOW=`END_SENSITIVITY_LOW`})(_n||={});var vn;(function(e){e.ACTIVITY_HANDLING_UNSPECIFIED=`ACTIVITY_HANDLING_UNSPECIFIED`,e.START_OF_ACTIVITY_INTERRUPTS=`START_OF_ACTIVITY_INTERRUPTS`,e.NO_INTERRUPTION=`NO_INTERRUPTION`})(vn||={});var yn;(function(e){e.TURN_COVERAGE_UNSPECIFIED=`TURN_COVERAGE_UNSPECIFIED`,e.TURN_INCLUDES_ONLY_ACTIVITY=`TURN_INCLUDES_ONLY_ACTIVITY`,e.TURN_INCLUDES_ALL_INPUT=`TURN_INCLUDES_ALL_INPUT`,e.TURN_INCLUDES_AUDIO_ACTIVITY_AND_ALL_VIDEO=`TURN_INCLUDES_AUDIO_ACTIVITY_AND_ALL_VIDEO`})(yn||={});var bn;(function(e){e.SCALE_UNSPECIFIED=`SCALE_UNSPECIFIED`,e.C_MAJOR_A_MINOR=`C_MAJOR_A_MINOR`,e.D_FLAT_MAJOR_B_FLAT_MINOR=`D_FLAT_MAJOR_B_FLAT_MINOR`,e.D_MAJOR_B_MINOR=`D_MAJOR_B_MINOR`,e.E_FLAT_MAJOR_C_MINOR=`E_FLAT_MAJOR_C_MINOR`,e.E_MAJOR_D_FLAT_MINOR=`E_MAJOR_D_FLAT_MINOR`,e.F_MAJOR_D_MINOR=`F_MAJOR_D_MINOR`,e.G_FLAT_MAJOR_E_FLAT_MINOR=`G_FLAT_MAJOR_E_FLAT_MINOR`,e.G_MAJOR_E_MINOR=`G_MAJOR_E_MINOR`,e.A_FLAT_MAJOR_F_MINOR=`A_FLAT_MAJOR_F_MINOR`,e.A_MAJOR_G_FLAT_MINOR=`A_MAJOR_G_FLAT_MINOR`,e.B_FLAT_MAJOR_G_MINOR=`B_FLAT_MAJOR_G_MINOR`,e.B_MAJOR_A_FLAT_MINOR=`B_MAJOR_A_FLAT_MINOR`})(bn||={});var xn;(function(e){e.MUSIC_GENERATION_MODE_UNSPECIFIED=`MUSIC_GENERATION_MODE_UNSPECIFIED`,e.QUALITY=`QUALITY`,e.DIVERSITY=`DIVERSITY`,e.VOCALIZATION=`VOCALIZATION`})(xn||={});var Sn;(function(e){e.PLAYBACK_CONTROL_UNSPECIFIED=`PLAYBACK_CONTROL_UNSPECIFIED`,e.PLAY=`PLAY`,e.PAUSE=`PAUSE`,e.STOP=`STOP`,e.RESET_CONTEXT=`RESET_CONTEXT`})(Sn||={});var Cn=class{constructor(e){let t={};for(let n of e.headers.entries())t[n[0]]=n[1];this.headers=t,this.responseInternal=e}json(){return this.responseInternal.json()}},wn=class{get text(){if(this.candidates?.[0]?.content?.parts?.length===0)return;this.candidates&&this.candidates.length>1&&console.warn(`there are multiple candidates in the response, returning text from the first one.`);let e=``,t=!1,n=[];for(let r of this.candidates?.[0]?.content?.parts??[]){for(let[e,t]of Object.entries(r))e!==`text`&&e!==`thought`&&e!==`thoughtSignature`&&(t!==null||t!==void 0)&&n.push(e);if(typeof r.text==`string`){if(typeof r.thought==`boolean`&&r.thought)continue;t=!0,e+=r.text}}return n.length>0&&console.warn(`there are non-text parts ${n} in the response, returning concatenation of all text parts. Please refer to the non text parts for a full response from model.`),t?e:void 0}get data(){if(this.candidates?.[0]?.content?.parts?.length===0)return;this.candidates&&this.candidates.length>1&&console.warn(`there are multiple candidates in the response, returning data from the first one.`);let e=``,t=[];for(let n of this.candidates?.[0]?.content?.parts??[]){for(let[e,r]of Object.entries(n))e!==`inlineData`&&(r!==null||r!==void 0)&&t.push(e);n.inlineData&&typeof n.inlineData.data==`string`&&(e+=atob(n.inlineData.data))}return t.length>0&&console.warn(`there are non-data parts ${t} in the response, returning concatenation of all data parts. Please refer to the non data parts for a full response from model.`),e.length>0?btoa(e):void 0}get functionCalls(){if(this.candidates?.[0]?.content?.parts?.length===0)return;this.candidates&&this.candidates.length>1&&console.warn(`there are multiple candidates in the response, returning function calls from the first one.`);let e=(this.candidates?.[0]?.content?.parts)?.filter(e=>e.functionCall).map(e=>e.functionCall).filter(e=>e!==void 0);if(e?.length!==0)return e}get executableCode(){if(this.candidates?.[0]?.content?.parts?.length===0)return;this.candidates&&this.candidates.length>1&&console.warn(`there are multiple candidates in the response, returning executable code from the first one.`);let e=(this.candidates?.[0]?.content?.parts)?.filter(e=>e.executableCode).map(e=>e.executableCode).filter(e=>e!==void 0);if(e?.length!==0)return e?.[0]?.code}get codeExecutionResult(){if(this.candidates?.[0]?.content?.parts?.length===0)return;this.candidates&&this.candidates.length>1&&console.warn(`there are multiple candidates in the response, returning code execution result from the first one.`);let e=(this.candidates?.[0]?.content?.parts)?.filter(e=>e.codeExecutionResult).map(e=>e.codeExecutionResult).filter(e=>e!==void 0);if(e?.length!==0)return e?.[0]?.output}},Tn=class{},En=class{},Dn=class{},On=class{},kn=class{},An=class{},jn=class{},Mn=class{},Nn=class{},Pn=class{},Fn=class e{_fromAPIResponse({apiResponse:t,_isVertexAI:n}){let r=new e,i,a=t;return i=n?$e(a):Qe(a),Object.assign(r,i),r}},In=class{},Ln=class{},Rn=class{},zn=class{},Bn=class{},Vn=class{},Hn=class{},Un=class e{_fromAPIResponse({apiResponse:t,_isVertexAI:n}){let r=new e,i=ot(t);return Object.assign(r,i),r}},Wn=class{},Gn=class{},Kn=class{},qn=class{},Jn=class{},Yn=class{get text(){let e=``,t=!1,n=[];for(let r of this.serverContent?.modelTurn?.parts??[]){for(let[e,t]of Object.entries(r))e!==`text`&&e!==`thought`&&t!==null&&n.push(e);if(typeof r.text==`string`){if(typeof r.thought==`boolean`&&r.thought)continue;t=!0,e+=r.text}}return n.length>0&&console.warn(`there are non-text parts ${n} in the response, returning concatenation of all text parts. Please refer to the non text parts for a full response from model.`),t?e:void 0}get data(){let e=``,t=[];for(let n of this.serverContent?.modelTurn?.parts??[]){for(let[e,r]of Object.entries(n))e!==`inlineData`&&r!==null&&t.push(e);n.inlineData&&typeof n.inlineData.data==`string`&&(e+=atob(n.inlineData.data))}return t.length>0&&console.warn(`there are non-data parts ${t} in the response, returning concatenation of all data parts. Please refer to the non data parts for a full response from model.`),e.length>0?btoa(e):void 0}},Xn=class{get audioChunk(){if(this.serverContent&&this.serverContent.audioChunks&&this.serverContent.audioChunks.length>0)return this.serverContent.audioChunks[0]}},Zn=class e{_fromAPIResponse({apiResponse:t,_isVertexAI:n}){let r=new e,i=ct(t);return Object.assign(r,i),r}};
34
+ /**
35
+ * @license
36
+ * Copyright 2025 Google LLC
37
+ * SPDX-License-Identifier: Apache-2.0
38
+ */
39
+ function R(e,t){if(!t||typeof t!=`string`)throw Error(`model is required and must be a string`);if(t.includes(`..`)||t.includes(`?`)||t.includes(`&`))throw Error(`invalid model parameter`);if(e.isVertexAI()){if(t.startsWith(`publishers/`)||t.startsWith(`projects/`)||t.startsWith(`models/`))return t;if(t.indexOf(`/`)>=0){let e=t.split(`/`,2);return`publishers/${e[0]}/models/${e[1]}`}else return`publishers/google/models/${t}`}else if(t.startsWith(`models/`)||t.startsWith(`tunedModels/`))return t;else return`models/${t}`}function Qn(e,t){let n=R(e,t);return n?n.startsWith(`publishers/`)&&e.isVertexAI()?`projects/${e.getProject()}/locations/${e.getLocation()}/${n}`:n.startsWith(`models/`)&&e.isVertexAI()?`projects/${e.getProject()}/locations/${e.getLocation()}/publishers/google/${n}`:n:``}function $n(e){return Array.isArray(e)?e.map(e=>er(e)):[er(e)]}function er(e){if(typeof e==`object`&&e)return e;throw Error(`Could not parse input as Blob. Unsupported blob type: ${typeof e}`)}function tr(e){let t=er(e);if(t.mimeType&&t.mimeType.startsWith(`image/`))return t;throw Error(`Unsupported mime type: ${t.mimeType}`)}function nr(e){let t=er(e);if(t.mimeType&&t.mimeType.startsWith(`audio/`))return t;throw Error(`Unsupported mime type: ${t.mimeType}`)}function rr(e){if(e==null)throw Error(`PartUnion is required`);if(typeof e==`object`)return e;if(typeof e==`string`)return{text:e};throw Error(`Unsupported part type: ${typeof e}`)}function ir(e){if(e==null||Array.isArray(e)&&e.length===0)throw Error(`PartListUnion is required`);return Array.isArray(e)?e.map(e=>rr(e)):[rr(e)]}function ar(e){return typeof e==`object`&&!!e&&`parts`in e&&Array.isArray(e.parts)}function or(e){return typeof e==`object`&&!!e&&`functionCall`in e}function sr(e){return typeof e==`object`&&!!e&&`functionResponse`in e}function z(e){if(e==null)throw Error(`ContentUnion is required`);return ar(e)?e:{role:`user`,parts:ir(e)}}function cr(e,t){if(!t)return[];if(e.isVertexAI()&&Array.isArray(t))return t.flatMap(e=>{let t=z(e);return t.parts&&t.parts.length>0&&t.parts[0].text!==void 0?[t.parts[0].text]:[]});if(e.isVertexAI()){let e=z(t);return e.parts&&e.parts.length>0&&e.parts[0].text!==void 0?[e.parts[0].text]:[]}return Array.isArray(t)?t.map(e=>z(e)):[z(t)]}function B(e){if(e==null||Array.isArray(e)&&e.length===0)throw Error(`contents are required`);if(!Array.isArray(e)){if(or(e)||sr(e))throw Error(`To specify functionCall or functionResponse parts, please wrap them in a Content object, specifying the role for them`);return[z(e)]}let t=[],n=[],r=ar(e[0]);for(let i of e){let e=ar(i);if(e!=r)throw Error(`Mixing Content and Parts is not supported, please group the parts into a the appropriate Content objects and specify the roles for them`);if(e)t.push(i);else if(or(i)||sr(i))throw Error(`To specify functionCall or functionResponse parts, please wrap them, and any other parts, in Content objects as appropriate, specifying the role for them`);else n.push(i)}return r||t.push({role:`user`,parts:ir(n)}),t}function lr(e,t){e.includes(`null`)&&(t.nullable=!0);let n=e.filter(e=>e!==`null`);if(n.length===1)t.type=Object.values(ht).includes(n[0].toUpperCase())?n[0].toUpperCase():ht.TYPE_UNSPECIFIED;else{t.anyOf=[];for(let e of n)t.anyOf.push({type:Object.values(ht).includes(e.toUpperCase())?e.toUpperCase():ht.TYPE_UNSPECIFIED})}}function ur(e){let t={},n=[`items`],r=[`anyOf`],i=[`properties`];if(e.type&&e.anyOf)throw Error(`type and anyOf cannot be both populated.`);let a=e.anyOf;a!=null&&a.length==2&&(a[0].type===`null`?(t.nullable=!0,e=a[1]):a[1].type===`null`&&(t.nullable=!0,e=a[0])),e.type instanceof Array&&lr(e.type,t);for(let[a,o]of Object.entries(e))if(o!=null)if(a==`type`){if(o===`null`)throw Error(`type: null can not be the only possible type for the field.`);if(o instanceof Array)continue;t.type=Object.values(ht).includes(o.toUpperCase())?o.toUpperCase():ht.TYPE_UNSPECIFIED}else if(n.includes(a))t[a]=ur(o);else if(r.includes(a)){let e=[];for(let n of o){if(n.type==`null`){t.nullable=!0;continue}e.push(ur(n))}t[a]=e}else if(i.includes(a)){let e={};for(let[t,n]of Object.entries(o))e[t]=ur(n);t[a]=e}else{if(a===`additionalProperties`)continue;t[a]=o}return t}function dr(e){return ur(e)}function fr(e){if(typeof e==`object`)return e;if(typeof e==`string`)return{voiceConfig:{prebuiltVoiceConfig:{voiceName:e}}};throw Error(`Unsupported speechConfig type: ${typeof e}`)}function pr(e){if(`multiSpeakerVoiceConfig`in e)throw Error(`multiSpeakerVoiceConfig is not supported in the live API.`);return e}function mr(e){if(e.functionDeclarations)for(let t of e.functionDeclarations)t.parameters&&(Object.keys(t.parameters).includes(`$schema`)?t.parametersJsonSchema||(t.parametersJsonSchema=t.parameters,delete t.parameters):t.parameters=ur(t.parameters)),t.response&&(Object.keys(t.response).includes(`$schema`)?t.responseJsonSchema||(t.responseJsonSchema=t.response,delete t.response):t.response=ur(t.response));return e}function hr(e){if(e==null)throw Error(`tools is required`);if(!Array.isArray(e))throw Error(`tools is required and must be an array of Tools`);let t=[];for(let n of e)t.push(n);return t}function gr(e,t,n,r=1){let i=!t.startsWith(`${n}/`)&&t.split(`/`).length===r;return e.isVertexAI()?t.startsWith(`projects/`)?t:t.startsWith(`locations/`)?`projects/${e.getProject()}/${t}`:t.startsWith(`${n}/`)?`projects/${e.getProject()}/locations/${e.getLocation()}/${t}`:i?`projects/${e.getProject()}/locations/${e.getLocation()}/${n}/${t}`:t:i?`${n}/${t}`:t}function V(e,t){if(typeof t!=`string`)throw Error(`name must be a string`);return gr(e,t,`cachedContents`)}function _r(e){switch(e){case`STATE_UNSPECIFIED`:return`JOB_STATE_UNSPECIFIED`;case`CREATING`:return`JOB_STATE_RUNNING`;case`ACTIVE`:return`JOB_STATE_SUCCEEDED`;case`FAILED`:return`JOB_STATE_FAILED`;default:return e}}function H(e){return Xe(e)}function vr(e){return typeof e==`object`&&!!e&&`name`in e}function yr(e){return typeof e==`object`&&!!e&&`video`in e}function br(e){return typeof e==`object`&&!!e&&`uri`in e}function xr(e){let t;if(vr(e)&&(t=e.name),!(br(e)&&(t=e.uri,t===void 0))&&!(yr(e)&&(t=e.video?.uri,t===void 0))){if(typeof e==`string`&&(t=e),t===void 0)throw Error(`Could not extract file name from the provided input.`);if(t.startsWith(`https://`)){let e=t.split(`files/`)[1].match(/[a-z0-9]+/);if(e===null)throw Error(`Could not extract file name from URI ${t}`);t=e[0]}else t.startsWith(`files/`)&&(t=t.split(`files/`)[1]);return t}}function Sr(e,t){let n;return n=e.isVertexAI()?t?`publishers/google/models`:`models`:t?`models`:`tunedModels`,n}function Cr(e){for(let t of[`models`,`tunedModels`,`publisherModels`])if(wr(e,t))return e[t];return[]}function wr(e,t){return typeof e==`object`&&!!e&&t in e}function Tr(e,t={}){let n=e,r={name:n.name,description:n.description,parametersJsonSchema:n.inputSchema};return n.outputSchema&&(r.responseJsonSchema=n.outputSchema),t.behavior&&(r.behavior=t.behavior),{functionDeclarations:[r]}}function Er(e,t={}){let n=[],r=new Set;for(let i of e){let e=i.name;if(r.has(e))throw Error(`Duplicate function name ${e} found in MCP tools. Please ensure function names are unique.`);r.add(e);let a=Tr(i,t);a.functionDeclarations&&n.push(...a.functionDeclarations)}return{functionDeclarations:n}}function Dr(e,t){let n;if(typeof t==`string`)if(e.isVertexAI())if(t.startsWith(`gs://`))n={format:`jsonl`,gcsUri:[t]};else if(t.startsWith(`bq://`))n={format:`bigquery`,bigqueryUri:t};else throw Error(`Unsupported string source for Vertex AI: ${t}`);else if(t.startsWith(`files/`))n={fileName:t};else throw Error(`Unsupported string source for Gemini API: ${t}`);else if(Array.isArray(t)){if(e.isVertexAI())throw Error(`InlinedRequest[] is not supported in Vertex AI.`);n={inlinedRequests:t}}else n=t;let r=[n.gcsUri,n.bigqueryUri].filter(Boolean).length,i=[n.inlinedRequests,n.fileName].filter(Boolean).length;if(e.isVertexAI()){if(i>0||r!==1)throw Error("Exactly one of `gcsUri` or `bigqueryUri` must be set for Vertex AI.")}else if(r>0||i!==1)throw Error("Exactly one of `inlinedRequests`, `fileName`, must be set for Gemini API.");return n}function Or(e){if(typeof e!=`string`)return e;let t=e;if(t.startsWith(`gs://`))return{format:`jsonl`,gcsUri:t};if(t.startsWith(`bq://`))return{format:`bigquery`,bigqueryUri:t};throw Error(`Unsupported destination: ${t}`)}function kr(e){if(typeof e!=`object`||!e)return{};let t=e,n=t.inlinedResponses;if(typeof n!=`object`||!n)return e;let r=n.inlinedResponses;if(!Array.isArray(r)||r.length===0)return e;let i=!1;for(let e of r){if(typeof e!=`object`||!e)continue;let t=e.response;if(!(typeof t!=`object`||!t)&&t.embedding!==void 0){i=!0;break}}return i&&(t.inlinedEmbedContentResponses=t.inlinedResponses,delete t.inlinedResponses),e}function Ar(e,t){let n=t;if(!e.isVertexAI()){if(/batches\/[^/]+$/.test(n))return n.split(`/`).pop();throw Error(`Invalid batch job name: ${n}.`)}if(/^projects\/[^/]+\/locations\/[^/]+\/batchPredictionJobs\/[^/]+$/.test(n))return n.split(`/`).pop();if(/^\d+$/.test(n))return n;throw Error(`Invalid batch job name: ${n}.`)}function jr(e){let t=e;return t===`BATCH_STATE_UNSPECIFIED`?`JOB_STATE_UNSPECIFIED`:t===`BATCH_STATE_PENDING`?`JOB_STATE_PENDING`:t===`BATCH_STATE_RUNNING`?`JOB_STATE_RUNNING`:t===`BATCH_STATE_SUCCEEDED`?`JOB_STATE_SUCCEEDED`:t===`BATCH_STATE_FAILED`?`JOB_STATE_FAILED`:t===`BATCH_STATE_CANCELLED`?`JOB_STATE_CANCELLED`:t===`BATCH_STATE_EXPIRED`?`JOB_STATE_EXPIRED`:t}function Mr(e){return e.includes(`gemini`)&&e!==`gemini-embedding-001`||e.includes(`maas`)}
40
+ /**
41
+ * @license
42
+ * Copyright 2025 Google LLC
43
+ * SPDX-License-Identifier: Apache-2.0
44
+ */
45
+ function Nr(e){let t={},n=I(e,[`apiKey`]);if(n!=null&&F(t,[`apiKey`],n),I(e,[`apiKeyConfig`])!==void 0)throw Error(`apiKeyConfig parameter is not supported in Gemini API.`);if(I(e,[`authType`])!==void 0)throw Error(`authType parameter is not supported in Gemini API.`);if(I(e,[`googleServiceAccountConfig`])!==void 0)throw Error(`googleServiceAccountConfig parameter is not supported in Gemini API.`);if(I(e,[`httpBasicAuthConfig`])!==void 0)throw Error(`httpBasicAuthConfig parameter is not supported in Gemini API.`);if(I(e,[`oauthConfig`])!==void 0)throw Error(`oauthConfig parameter is not supported in Gemini API.`);if(I(e,[`oidcConfig`])!==void 0)throw Error(`oidcConfig parameter is not supported in Gemini API.`);return t}function Pr(e){let t={},n=I(e,[`responsesFile`]);n!=null&&F(t,[`fileName`],n);let r=I(e,[`inlinedResponses`,`inlinedResponses`]);if(r!=null){let e=r;Array.isArray(e)&&(e=e.map(e=>vi(e))),F(t,[`inlinedResponses`],e)}let i=I(e,[`inlinedEmbedContentResponses`,`inlinedResponses`]);if(i!=null){let e=i;Array.isArray(e)&&(e=e.map(e=>e)),F(t,[`inlinedEmbedContentResponses`],e)}return t}function Fr(e){let t={},n=I(e,[`predictionsFormat`]);n!=null&&F(t,[`format`],n);let r=I(e,[`gcsDestination`,`outputUriPrefix`]);r!=null&&F(t,[`gcsUri`],r);let i=I(e,[`bigqueryDestination`,`outputUri`]);return i!=null&&F(t,[`bigqueryUri`],i),t}function Ir(e){let t={},n=I(e,[`format`]);n!=null&&F(t,[`predictionsFormat`],n);let r=I(e,[`gcsUri`]);r!=null&&F(t,[`gcsDestination`,`outputUriPrefix`],r);let i=I(e,[`bigqueryUri`]);if(i!=null&&F(t,[`bigqueryDestination`,`outputUri`],i),I(e,[`fileName`])!==void 0)throw Error(`fileName parameter is not supported in Vertex AI.`);if(I(e,[`inlinedResponses`])!==void 0)throw Error(`inlinedResponses parameter is not supported in Vertex AI.`);if(I(e,[`inlinedEmbedContentResponses`])!==void 0)throw Error(`inlinedEmbedContentResponses parameter is not supported in Vertex AI.`);return t}function Lr(e){let t={},n=I(e,[`name`]);n!=null&&F(t,[`name`],n);let r=I(e,[`metadata`,`displayName`]);r!=null&&F(t,[`displayName`],r);let i=I(e,[`metadata`,`state`]);i!=null&&F(t,[`state`],jr(i));let a=I(e,[`metadata`,`createTime`]);a!=null&&F(t,[`createTime`],a);let o=I(e,[`metadata`,`endTime`]);o!=null&&F(t,[`endTime`],o);let s=I(e,[`metadata`,`updateTime`]);s!=null&&F(t,[`updateTime`],s);let c=I(e,[`metadata`,`model`]);c!=null&&F(t,[`model`],c);let l=I(e,[`metadata`,`output`]);return l!=null&&F(t,[`dest`],Pr(kr(l))),t}function Rr(e){let t={},n=I(e,[`name`]);n!=null&&F(t,[`name`],n);let r=I(e,[`displayName`]);r!=null&&F(t,[`displayName`],r);let i=I(e,[`state`]);i!=null&&F(t,[`state`],jr(i));let a=I(e,[`error`]);a!=null&&F(t,[`error`],a);let o=I(e,[`createTime`]);o!=null&&F(t,[`createTime`],o);let s=I(e,[`startTime`]);s!=null&&F(t,[`startTime`],s);let c=I(e,[`endTime`]);c!=null&&F(t,[`endTime`],c);let l=I(e,[`updateTime`]);l!=null&&F(t,[`updateTime`],l);let u=I(e,[`model`]);u!=null&&F(t,[`model`],u);let d=I(e,[`inputConfig`]);d!=null&&F(t,[`src`],zr(d));let f=I(e,[`outputConfig`]);f!=null&&F(t,[`dest`],Fr(kr(f)));let p=I(e,[`completionStats`]);return p!=null&&F(t,[`completionStats`],p),t}function zr(e){let t={},n=I(e,[`instancesFormat`]);n!=null&&F(t,[`format`],n);let r=I(e,[`gcsSource`,`uris`]);r!=null&&F(t,[`gcsUri`],r);let i=I(e,[`bigquerySource`,`inputUri`]);return i!=null&&F(t,[`bigqueryUri`],i),t}function Br(e,t){let n={};if(I(t,[`format`])!==void 0)throw Error(`format parameter is not supported in Gemini API.`);if(I(t,[`gcsUri`])!==void 0)throw Error(`gcsUri parameter is not supported in Gemini API.`);if(I(t,[`bigqueryUri`])!==void 0)throw Error(`bigqueryUri parameter is not supported in Gemini API.`);let r=I(t,[`fileName`]);r!=null&&F(n,[`fileName`],r);let i=I(t,[`inlinedRequests`]);if(i!=null){let t=i;Array.isArray(t)&&(t=t.map(t=>_i(e,t))),F(n,[`requests`,`requests`],t)}return n}function Vr(e){let t={},n=I(e,[`format`]);n!=null&&F(t,[`instancesFormat`],n);let r=I(e,[`gcsUri`]);r!=null&&F(t,[`gcsSource`,`uris`],r);let i=I(e,[`bigqueryUri`]);if(i!=null&&F(t,[`bigquerySource`,`inputUri`],i),I(e,[`fileName`])!==void 0)throw Error(`fileName parameter is not supported in Vertex AI.`);if(I(e,[`inlinedRequests`])!==void 0)throw Error(`inlinedRequests parameter is not supported in Vertex AI.`);return t}function Hr(e){let t={},n=I(e,[`data`]);if(n!=null&&F(t,[`data`],n),I(e,[`displayName`])!==void 0)throw Error(`displayName parameter is not supported in Gemini API.`);let r=I(e,[`mimeType`]);return r!=null&&F(t,[`mimeType`],r),t}function Ur(e,t){let n={},r=I(t,[`name`]);return r!=null&&F(n,[`_url`,`name`],Ar(e,r)),n}function Wr(e,t){let n={},r=I(t,[`name`]);return r!=null&&F(n,[`_url`,`name`],Ar(e,r)),n}function Gr(e){let t={},n=I(e,[`content`]);n!=null&&F(t,[`content`],n);let r=I(e,[`citationMetadata`]);r!=null&&F(t,[`citationMetadata`],Kr(r));let i=I(e,[`tokenCount`]);i!=null&&F(t,[`tokenCount`],i);let a=I(e,[`finishReason`]);a!=null&&F(t,[`finishReason`],a);let o=I(e,[`groundingMetadata`]);o!=null&&F(t,[`groundingMetadata`],o);let s=I(e,[`avgLogprobs`]);s!=null&&F(t,[`avgLogprobs`],s);let c=I(e,[`index`]);c!=null&&F(t,[`index`],c);let l=I(e,[`logprobsResult`]);l!=null&&F(t,[`logprobsResult`],l);let u=I(e,[`safetyRatings`]);if(u!=null){let e=u;Array.isArray(e)&&(e=e.map(e=>e)),F(t,[`safetyRatings`],e)}let d=I(e,[`urlContextMetadata`]);return d!=null&&F(t,[`urlContextMetadata`],d),t}function Kr(e){let t={},n=I(e,[`citationSources`]);if(n!=null){let e=n;Array.isArray(e)&&(e=e.map(e=>e)),F(t,[`citations`],e)}return t}function qr(e){let t={},n=I(e,[`parts`]);if(n!=null){let e=n;Array.isArray(e)&&(e=e.map(e=>Ti(e))),F(t,[`parts`],e)}let r=I(e,[`role`]);return r!=null&&F(t,[`role`],r),t}function Jr(e,t){let n={},r=I(e,[`displayName`]);if(t!==void 0&&r!=null&&F(t,[`batch`,`displayName`],r),I(e,[`dest`])!==void 0)throw Error(`dest parameter is not supported in Gemini API.`);let i=I(e,[`webhookConfig`]);return t!==void 0&&i!=null&&F(t,[`batch`,`webhookConfig`],i),n}function Yr(e,t){let n={},r=I(e,[`displayName`]);t!==void 0&&r!=null&&F(t,[`displayName`],r);let i=I(e,[`dest`]);if(t!==void 0&&i!=null&&F(t,[`outputConfig`],Ir(Or(i))),I(e,[`webhookConfig`])!==void 0)throw Error(`webhookConfig parameter is not supported in Vertex AI.`);return n}function Xr(e,t){let n={},r=I(t,[`model`]);r!=null&&F(n,[`_url`,`model`],R(e,r));let i=I(t,[`src`]);i!=null&&F(n,[`batch`,`inputConfig`],Br(e,Dr(e,i)));let a=I(t,[`config`]);return a!=null&&Jr(a,n),n}function Zr(e,t){let n={},r=I(t,[`model`]);r!=null&&F(n,[`model`],R(e,r));let i=I(t,[`src`]);i!=null&&F(n,[`inputConfig`],Vr(Dr(e,i)));let a=I(t,[`config`]);return a!=null&&Yr(a,n),n}function Qr(e,t){let n={},r=I(e,[`displayName`]);return t!==void 0&&r!=null&&F(t,[`batch`,`displayName`],r),n}function $r(e,t){let n={},r=I(t,[`model`]);r!=null&&F(n,[`_url`,`model`],R(e,r));let i=I(t,[`src`]);i!=null&&F(n,[`batch`,`inputConfig`],oi(e,i));let a=I(t,[`config`]);return a!=null&&Qr(a,n),n}function ei(e,t){let n={},r=I(t,[`name`]);return r!=null&&F(n,[`_url`,`name`],Ar(e,r)),n}function ti(e,t){let n={},r=I(t,[`name`]);return r!=null&&F(n,[`_url`,`name`],Ar(e,r)),n}function ni(e){let t={},n=I(e,[`sdkHttpResponse`]);n!=null&&F(t,[`sdkHttpResponse`],n);let r=I(e,[`name`]);r!=null&&F(t,[`name`],r);let i=I(e,[`done`]);i!=null&&F(t,[`done`],i);let a=I(e,[`error`]);return a!=null&&F(t,[`error`],a),t}function ri(e){let t={},n=I(e,[`sdkHttpResponse`]);n!=null&&F(t,[`sdkHttpResponse`],n);let r=I(e,[`name`]);r!=null&&F(t,[`name`],r);let i=I(e,[`done`]);i!=null&&F(t,[`done`],i);let a=I(e,[`error`]);return a!=null&&F(t,[`error`],a),t}function ii(e,t){let n={},r=I(t,[`contents`]);if(r!=null){let t=cr(e,r);Array.isArray(t)&&(t=t.map(e=>e)),F(n,[`requests[]`,`request`,`content`],t)}let i=I(t,[`config`]);return i!=null&&(F(n,[`_self`],ai(i,n)),Je(n,{"requests[].*":`requests[].request.*`})),n}function ai(e,t){let n={},r=I(e,[`taskType`]);t!==void 0&&r!=null&&F(t,[`requests[]`,`taskType`],r);let i=I(e,[`title`]);t!==void 0&&i!=null&&F(t,[`requests[]`,`title`],i);let a=I(e,[`outputDimensionality`]);if(t!==void 0&&a!=null&&F(t,[`requests[]`,`outputDimensionality`],a),I(e,[`mimeType`])!==void 0)throw Error(`mimeType parameter is not supported in Gemini API.`);if(I(e,[`autoTruncate`])!==void 0)throw Error(`autoTruncate parameter is not supported in Gemini API.`);if(I(e,[`documentOcr`])!==void 0)throw Error(`documentOcr parameter is not supported in Gemini API.`);if(I(e,[`audioTrackExtraction`])!==void 0)throw Error(`audioTrackExtraction parameter is not supported in Gemini API.`);return n}function oi(e,t){let n={},r=I(t,[`fileName`]);r!=null&&F(n,[`file_name`],r);let i=I(t,[`inlinedRequests`]);return i!=null&&F(n,[`requests`],ii(e,i)),n}function si(e){let t={};if(I(e,[`displayName`])!==void 0)throw Error(`displayName parameter is not supported in Gemini API.`);let n=I(e,[`fileUri`]);n!=null&&F(t,[`fileUri`],n);let r=I(e,[`mimeType`]);return r!=null&&F(t,[`mimeType`],r),t}function ci(e){let t={},n=I(e,[`id`]);n!=null&&F(t,[`id`],n);let r=I(e,[`args`]);r!=null&&F(t,[`args`],r);let i=I(e,[`name`]);if(i!=null&&F(t,[`name`],i),I(e,[`partialArgs`])!==void 0)throw Error(`partialArgs parameter is not supported in Gemini API.`);if(I(e,[`willContinue`])!==void 0)throw Error(`willContinue parameter is not supported in Gemini API.`);return t}function li(e){let t={},n=I(e,[`allowedFunctionNames`]);n!=null&&F(t,[`allowedFunctionNames`],n);let r=I(e,[`mode`]);if(r!=null&&F(t,[`mode`],r),I(e,[`streamFunctionCallArguments`])!==void 0)throw Error(`streamFunctionCallArguments parameter is not supported in Gemini API.`);return t}function ui(e,t,n){let r={},i=I(t,[`systemInstruction`]);n!==void 0&&i!=null&&F(n,[`systemInstruction`],qr(z(i)));let a=I(t,[`temperature`]);a!=null&&F(r,[`temperature`],a);let o=I(t,[`topP`]);o!=null&&F(r,[`topP`],o);let s=I(t,[`topK`]);s!=null&&F(r,[`topK`],s);let c=I(t,[`candidateCount`]);c!=null&&F(r,[`candidateCount`],c);let l=I(t,[`maxOutputTokens`]);l!=null&&F(r,[`maxOutputTokens`],l);let u=I(t,[`stopSequences`]);u!=null&&F(r,[`stopSequences`],u);let d=I(t,[`responseLogprobs`]);d!=null&&F(r,[`responseLogprobs`],d);let f=I(t,[`logprobs`]);f!=null&&F(r,[`logprobs`],f);let p=I(t,[`presencePenalty`]);p!=null&&F(r,[`presencePenalty`],p);let m=I(t,[`frequencyPenalty`]);m!=null&&F(r,[`frequencyPenalty`],m);let h=I(t,[`seed`]);h!=null&&F(r,[`seed`],h);let g=I(t,[`responseMimeType`]);g!=null&&F(r,[`responseMimeType`],g);let _=I(t,[`responseSchema`]);_!=null&&F(r,[`responseSchema`],dr(_));let v=I(t,[`responseJsonSchema`]);if(v!=null&&F(r,[`responseJsonSchema`],v),I(t,[`routingConfig`])!==void 0)throw Error(`routingConfig parameter is not supported in Gemini API.`);if(I(t,[`modelSelectionConfig`])!==void 0)throw Error(`modelSelectionConfig parameter is not supported in Gemini API.`);let y=I(t,[`safetySettings`]);if(n!==void 0&&y!=null){let e=y;Array.isArray(e)&&(e=e.map(e=>Ei(e))),F(n,[`safetySettings`],e)}let b=I(t,[`tools`]);if(n!==void 0&&b!=null){let e=hr(b);Array.isArray(e)&&(e=e.map(e=>Oi(mr(e)))),F(n,[`tools`],e)}let x=I(t,[`toolConfig`]);if(n!==void 0&&x!=null&&F(n,[`toolConfig`],Di(x)),I(t,[`labels`])!==void 0)throw Error(`labels parameter is not supported in Gemini API.`);let S=I(t,[`cachedContent`]);n!==void 0&&S!=null&&F(n,[`cachedContent`],V(e,S));let C=I(t,[`responseModalities`]);C!=null&&F(r,[`responseModalities`],C);let w=I(t,[`mediaResolution`]);w!=null&&F(r,[`mediaResolution`],w);let T=I(t,[`speechConfig`]);if(T!=null&&F(r,[`speechConfig`],fr(T)),I(t,[`audioTimestamp`])!==void 0)throw Error(`audioTimestamp parameter is not supported in Gemini API.`);let E=I(t,[`thinkingConfig`]);E!=null&&F(r,[`thinkingConfig`],E);let D=I(t,[`imageConfig`]);D!=null&&F(r,[`imageConfig`],gi(D));let O=I(t,[`enableEnhancedCivicAnswers`]);if(O!=null&&F(r,[`enableEnhancedCivicAnswers`],O),I(t,[`modelArmorConfig`])!==void 0)throw Error(`modelArmorConfig parameter is not supported in Gemini API.`);let k=I(t,[`serviceTier`]);return n!==void 0&&k!=null&&F(n,[`serviceTier`],k),r}function di(e){let t={},n=I(e,[`sdkHttpResponse`]);n!=null&&F(t,[`sdkHttpResponse`],n);let r=I(e,[`candidates`]);if(r!=null){let e=r;Array.isArray(e)&&(e=e.map(e=>Gr(e))),F(t,[`candidates`],e)}let i=I(e,[`modelVersion`]);i!=null&&F(t,[`modelVersion`],i);let a=I(e,[`promptFeedback`]);a!=null&&F(t,[`promptFeedback`],a);let o=I(e,[`responseId`]);o!=null&&F(t,[`responseId`],o);let s=I(e,[`usageMetadata`]);s!=null&&F(t,[`usageMetadata`],s);let c=I(e,[`modelStatus`]);return c!=null&&F(t,[`modelStatus`],c),t}function fi(e,t){let n={},r=I(t,[`name`]);return r!=null&&F(n,[`_url`,`name`],Ar(e,r)),n}function pi(e,t){let n={},r=I(t,[`name`]);return r!=null&&F(n,[`_url`,`name`],Ar(e,r)),n}function mi(e){let t={},n=I(e,[`authConfig`]);n!=null&&F(t,[`authConfig`],Nr(n));let r=I(e,[`enableWidget`]);return r!=null&&F(t,[`enableWidget`],r),t}function hi(e){let t={},n=I(e,[`searchTypes`]);if(n!=null&&F(t,[`searchTypes`],n),I(e,[`blockingConfidence`])!==void 0)throw Error(`blockingConfidence parameter is not supported in Gemini API.`);if(I(e,[`excludeDomains`])!==void 0)throw Error(`excludeDomains parameter is not supported in Gemini API.`);let r=I(e,[`timeRangeFilter`]);return r!=null&&F(t,[`timeRangeFilter`],r),t}function gi(e){let t={},n=I(e,[`aspectRatio`]);n!=null&&F(t,[`aspectRatio`],n);let r=I(e,[`imageSize`]);if(r!=null&&F(t,[`imageSize`],r),I(e,[`personGeneration`])!==void 0)throw Error(`personGeneration parameter is not supported in Gemini API.`);if(I(e,[`prominentPeople`])!==void 0)throw Error(`prominentPeople parameter is not supported in Gemini API.`);if(I(e,[`outputMimeType`])!==void 0)throw Error(`outputMimeType parameter is not supported in Gemini API.`);if(I(e,[`outputCompressionQuality`])!==void 0)throw Error(`outputCompressionQuality parameter is not supported in Gemini API.`);if(I(e,[`imageOutputOptions`])!==void 0)throw Error(`imageOutputOptions parameter is not supported in Gemini API.`);return t}function _i(e,t){let n={},r=I(t,[`model`]);r!=null&&F(n,[`request`,`model`],R(e,r));let i=I(t,[`contents`]);if(i!=null){let e=B(i);Array.isArray(e)&&(e=e.map(e=>qr(e))),F(n,[`request`,`contents`],e)}let a=I(t,[`metadata`]);a!=null&&F(n,[`metadata`],a);let o=I(t,[`config`]);return o!=null&&F(n,[`request`,`generationConfig`],ui(e,o,I(n,[`request`],{}))),n}function vi(e){let t={},n=I(e,[`response`]);n!=null&&F(t,[`response`],di(n));let r=I(e,[`metadata`]);r!=null&&F(t,[`metadata`],r);let i=I(e,[`error`]);return i!=null&&F(t,[`error`],i),t}function yi(e,t){let n={},r=I(e,[`pageSize`]);t!==void 0&&r!=null&&F(t,[`_query`,`pageSize`],r);let i=I(e,[`pageToken`]);if(t!==void 0&&i!=null&&F(t,[`_query`,`pageToken`],i),I(e,[`filter`])!==void 0)throw Error(`filter parameter is not supported in Gemini API.`);return n}function bi(e,t){let n={},r=I(e,[`pageSize`]);t!==void 0&&r!=null&&F(t,[`_query`,`pageSize`],r);let i=I(e,[`pageToken`]);t!==void 0&&i!=null&&F(t,[`_query`,`pageToken`],i);let a=I(e,[`filter`]);return t!==void 0&&a!=null&&F(t,[`_query`,`filter`],a),n}function xi(e){let t={},n=I(e,[`config`]);return n!=null&&yi(n,t),t}function Si(e){let t={},n=I(e,[`config`]);return n!=null&&bi(n,t),t}function Ci(e){let t={},n=I(e,[`sdkHttpResponse`]);n!=null&&F(t,[`sdkHttpResponse`],n);let r=I(e,[`nextPageToken`]);r!=null&&F(t,[`nextPageToken`],r);let i=I(e,[`operations`]);if(i!=null){let e=i;Array.isArray(e)&&(e=e.map(e=>Lr(e))),F(t,[`batchJobs`],e)}return t}function wi(e){let t={},n=I(e,[`sdkHttpResponse`]);n!=null&&F(t,[`sdkHttpResponse`],n);let r=I(e,[`nextPageToken`]);r!=null&&F(t,[`nextPageToken`],r);let i=I(e,[`batchPredictionJobs`]);if(i!=null){let e=i;Array.isArray(e)&&(e=e.map(e=>Rr(e))),F(t,[`batchJobs`],e)}return t}function Ti(e){let t={},n=I(e,[`mediaResolution`]);n!=null&&F(t,[`mediaResolution`],n);let r=I(e,[`codeExecutionResult`]);r!=null&&F(t,[`codeExecutionResult`],r);let i=I(e,[`executableCode`]);i!=null&&F(t,[`executableCode`],i);let a=I(e,[`fileData`]);a!=null&&F(t,[`fileData`],si(a));let o=I(e,[`functionCall`]);o!=null&&F(t,[`functionCall`],ci(o));let s=I(e,[`functionResponse`]);s!=null&&F(t,[`functionResponse`],s);let c=I(e,[`inlineData`]);c!=null&&F(t,[`inlineData`],Hr(c));let l=I(e,[`text`]);l!=null&&F(t,[`text`],l);let u=I(e,[`thought`]);u!=null&&F(t,[`thought`],u);let d=I(e,[`thoughtSignature`]);d!=null&&F(t,[`thoughtSignature`],d);let f=I(e,[`videoMetadata`]);f!=null&&F(t,[`videoMetadata`],f);let p=I(e,[`toolCall`]);p!=null&&F(t,[`toolCall`],p);let m=I(e,[`toolResponse`]);m!=null&&F(t,[`toolResponse`],m);let h=I(e,[`partMetadata`]);return h!=null&&F(t,[`partMetadata`],h),t}function Ei(e){let t={},n=I(e,[`category`]);if(n!=null&&F(t,[`category`],n),I(e,[`method`])!==void 0)throw Error(`method parameter is not supported in Gemini API.`);let r=I(e,[`threshold`]);return r!=null&&F(t,[`threshold`],r),t}function Di(e){let t={},n=I(e,[`retrievalConfig`]);n!=null&&F(t,[`retrievalConfig`],n);let r=I(e,[`functionCallingConfig`]);r!=null&&F(t,[`functionCallingConfig`],li(r));let i=I(e,[`includeServerSideToolInvocations`]);return i!=null&&F(t,[`includeServerSideToolInvocations`],i),t}function Oi(e){let t={};if(I(e,[`retrieval`])!==void 0)throw Error(`retrieval parameter is not supported in Gemini API.`);let n=I(e,[`computerUse`]);n!=null&&F(t,[`computerUse`],n);let r=I(e,[`fileSearch`]);r!=null&&F(t,[`fileSearch`],r);let i=I(e,[`googleSearch`]);i!=null&&F(t,[`googleSearch`],hi(i));let a=I(e,[`googleMaps`]);a!=null&&F(t,[`googleMaps`],mi(a));let o=I(e,[`codeExecution`]);if(o!=null&&F(t,[`codeExecution`],o),I(e,[`enterpriseWebSearch`])!==void 0)throw Error(`enterpriseWebSearch parameter is not supported in Gemini API.`);let s=I(e,[`functionDeclarations`]);if(s!=null){let e=s;Array.isArray(e)&&(e=e.map(e=>e)),F(t,[`functionDeclarations`],e)}let c=I(e,[`googleSearchRetrieval`]);if(c!=null&&F(t,[`googleSearchRetrieval`],c),I(e,[`parallelAiSearch`])!==void 0)throw Error(`parallelAiSearch parameter is not supported in Gemini API.`);let l=I(e,[`urlContext`]);l!=null&&F(t,[`urlContext`],l);let u=I(e,[`mcpServers`]);if(u!=null){let e=u;Array.isArray(e)&&(e=e.map(e=>e)),F(t,[`mcpServers`],e)}return t}
46
+ /**
47
+ * @license
48
+ * Copyright 2025 Google LLC
49
+ * SPDX-License-Identifier: Apache-2.0
50
+ */
51
+ var U;(function(e){e.PAGED_ITEM_BATCH_JOBS=`batchJobs`,e.PAGED_ITEM_MODELS=`models`,e.PAGED_ITEM_TUNING_JOBS=`tuningJobs`,e.PAGED_ITEM_FILES=`files`,e.PAGED_ITEM_CACHED_CONTENTS=`cachedContents`,e.PAGED_ITEM_FILE_SEARCH_STORES=`fileSearchStores`,e.PAGED_ITEM_DOCUMENTS=`documents`})(U||={});var ki=class{constructor(e,t,n,r){this.pageInternal=[],this.paramsInternal={},this.requestInternal=t,this.init(e,n,r)}init(e,t,n){this.nameInternal=e,this.pageInternal=t[this.nameInternal]||[],this.sdkHttpResponseInternal=t?.sdkHttpResponse,this.idxInternal=0;let r={config:{}};r=!n||Object.keys(n).length===0?{config:{}}:typeof n==`object`?Object.assign({},n):n,r.config&&(r.config.pageToken=t.nextPageToken),this.paramsInternal=r,this.pageInternalSize=r.config?.pageSize??this.pageInternal.length}initNextPage(e){this.init(this.nameInternal,e,this.paramsInternal)}get page(){return this.pageInternal}get name(){return this.nameInternal}get pageSize(){return this.pageInternalSize}get sdkHttpResponse(){return this.sdkHttpResponseInternal}get params(){return this.paramsInternal}get pageLength(){return this.pageInternal.length}getItem(e){return this.pageInternal[e]}[Symbol.asyncIterator](){return{next:async()=>{if(this.idxInternal>=this.pageLength)if(this.hasNextPage())await this.nextPage();else return{value:void 0,done:!0};let e=this.getItem(this.idxInternal);return this.idxInternal+=1,{value:e,done:!1}},return:async()=>({value:void 0,done:!0})}}async nextPage(){if(!this.hasNextPage())throw Error(`No more pages to fetch.`);let e=await this.requestInternal(this.params);return this.initNextPage(e),this.page}hasNextPage(){return this.params.config?.pageToken!==void 0}},Ai=class extends N{constructor(e){super(),this.apiClient=e,this.list=async(e={})=>new ki(U.PAGED_ITEM_BATCH_JOBS,e=>this.listInternal(e),await this.listInternal(e),e),this.create=async e=>(this.apiClient.isVertexAI()&&(e.config=this.formatDestination(e.src,e.config)),this.createInternal(e)),this.createEmbeddings=async e=>{if(console.warn(`batches.createEmbeddings() is experimental and may change without notice.`),this.apiClient.isVertexAI())throw Error(`Vertex AI does not support batches.createEmbeddings.`);return this.createEmbeddingsInternal(e)}}createInlinedGenerateContentRequest(e){let t=Xr(this.apiClient,e),n=t._url,r=P(`{model}:batchGenerateContent`,n),i=t.batch.inputConfig.requests,a=i.requests,o=[];for(let e of a){let t=Object.assign({},e);if(t.systemInstruction){let e=t.systemInstruction;delete t.systemInstruction;let n=t.request;n.systemInstruction=e,t.request=n}o.push(t)}return i.requests=o,delete t.config,delete t._url,delete t._query,{path:r,body:t}}getGcsUri(e){if(typeof e==`string`)return e.startsWith(`gs://`)?e:void 0;if(!Array.isArray(e)&&e.gcsUri&&e.gcsUri.length>0)return e.gcsUri[0]}getBigqueryUri(e){if(typeof e==`string`)return e.startsWith(`bq://`)?e:void 0;if(!Array.isArray(e))return e.bigqueryUri}formatDestination(e,t){let n=t?Object.assign({},t):{},r=Date.now().toString();if(n.displayName||=`genaiBatchJob_${r}`,n.dest===void 0){let t=this.getGcsUri(e),i=this.getBigqueryUri(e);if(t)t.endsWith(`.jsonl`)?n.dest=`${t.slice(0,-6)}/dest`:n.dest=`${t}_dest_${r}`;else if(i)n.dest=`${i}_dest_${r}`;else throw Error(`Unsupported source for Vertex AI: No GCS or BigQuery URI found.`)}return n}async createInternal(e){let t,n=``,r={};if(this.apiClient.isVertexAI()){let i=Zr(this.apiClient,e);return n=P(`batchPredictionJobs`,i._url),r=i._query,delete i._url,delete i._query,t=this.apiClient.request({path:n,queryParams:r,body:JSON.stringify(i),httpMethod:`POST`,httpOptions:e.config?.httpOptions,abortSignal:e.config?.abortSignal}).then(e=>e.json()),t.then(e=>Rr(e))}else{let i=Xr(this.apiClient,e);return n=P(`{model}:batchGenerateContent`,i._url),r=i._query,delete i._url,delete i._query,t=this.apiClient.request({path:n,queryParams:r,body:JSON.stringify(i),httpMethod:`POST`,httpOptions:e.config?.httpOptions,abortSignal:e.config?.abortSignal}).then(e=>e.json()),t.then(e=>Lr(e))}}async createEmbeddingsInternal(e){let t,n=``,r={};if(this.apiClient.isVertexAI())throw Error(`This method is only supported by the Gemini Developer API.`);{let i=$r(this.apiClient,e);return n=P(`{model}:asyncBatchEmbedContent`,i._url),r=i._query,delete i._url,delete i._query,t=this.apiClient.request({path:n,queryParams:r,body:JSON.stringify(i),httpMethod:`POST`,httpOptions:e.config?.httpOptions,abortSignal:e.config?.abortSignal}).then(e=>e.json()),t.then(e=>Lr(e))}}async get(e){let t,n=``,r={};if(this.apiClient.isVertexAI()){let i=pi(this.apiClient,e);return n=P(`batchPredictionJobs/{name}`,i._url),r=i._query,delete i._url,delete i._query,t=this.apiClient.request({path:n,queryParams:r,body:JSON.stringify(i),httpMethod:`GET`,httpOptions:e.config?.httpOptions,abortSignal:e.config?.abortSignal}).then(e=>e.json()),t.then(e=>Rr(e))}else{let i=fi(this.apiClient,e);return n=P(`batches/{name}`,i._url),r=i._query,delete i._url,delete i._query,t=this.apiClient.request({path:n,queryParams:r,body:JSON.stringify(i),httpMethod:`GET`,httpOptions:e.config?.httpOptions,abortSignal:e.config?.abortSignal}).then(e=>e.json()),t.then(e=>Lr(e))}}async cancel(e){let t=``,n={};if(this.apiClient.isVertexAI()){let r=Wr(this.apiClient,e);t=P(`batchPredictionJobs/{name}:cancel`,r._url),n=r._query,delete r._url,delete r._query,await this.apiClient.request({path:t,queryParams:n,body:JSON.stringify(r),httpMethod:`POST`,httpOptions:e.config?.httpOptions,abortSignal:e.config?.abortSignal})}else{let r=Ur(this.apiClient,e);t=P(`batches/{name}:cancel`,r._url),n=r._query,delete r._url,delete r._query,await this.apiClient.request({path:t,queryParams:n,body:JSON.stringify(r),httpMethod:`POST`,httpOptions:e.config?.httpOptions,abortSignal:e.config?.abortSignal})}}async listInternal(e){let t,n=``,r={};if(this.apiClient.isVertexAI()){let i=Si(e);return n=P(`batchPredictionJobs`,i._url),r=i._query,delete i._url,delete i._query,t=this.apiClient.request({path:n,queryParams:r,body:JSON.stringify(i),httpMethod:`GET`,httpOptions:e.config?.httpOptions,abortSignal:e.config?.abortSignal}).then(e=>e.json().then(t=>{let n=t;return n.sdkHttpResponse={headers:e.headers},n})),t.then(e=>{let t=wi(e),n=new Jn;return Object.assign(n,t),n})}else{let i=xi(e);return n=P(`batches`,i._url),r=i._query,delete i._url,delete i._query,t=this.apiClient.request({path:n,queryParams:r,body:JSON.stringify(i),httpMethod:`GET`,httpOptions:e.config?.httpOptions,abortSignal:e.config?.abortSignal}).then(e=>e.json().then(t=>{let n=t;return n.sdkHttpResponse={headers:e.headers},n})),t.then(e=>{let t=Ci(e),n=new Jn;return Object.assign(n,t),n})}}async delete(e){let t,n=``,r={};if(this.apiClient.isVertexAI()){let i=ti(this.apiClient,e);return n=P(`batchPredictionJobs/{name}`,i._url),r=i._query,delete i._url,delete i._query,t=this.apiClient.request({path:n,queryParams:r,body:JSON.stringify(i),httpMethod:`DELETE`,httpOptions:e.config?.httpOptions,abortSignal:e.config?.abortSignal}).then(e=>e.json().then(t=>{let n=t;return n.sdkHttpResponse={headers:e.headers},n})),t.then(e=>ri(e))}else{let i=ei(this.apiClient,e);return n=P(`batches/{name}`,i._url),r=i._query,delete i._url,delete i._query,t=this.apiClient.request({path:n,queryParams:r,body:JSON.stringify(i),httpMethod:`DELETE`,httpOptions:e.config?.httpOptions,abortSignal:e.config?.abortSignal}).then(e=>e.json().then(t=>{let n=t;return n.sdkHttpResponse={headers:e.headers},n})),t.then(e=>ni(e))}}};
52
+ /**
53
+ * @license
54
+ * Copyright 2025 Google LLC
55
+ * SPDX-License-Identifier: Apache-2.0
56
+ */
57
+ function ji(e){let t={},n=I(e,[`apiKey`]);if(n!=null&&F(t,[`apiKey`],n),I(e,[`apiKeyConfig`])!==void 0)throw Error(`apiKeyConfig parameter is not supported in Gemini API.`);if(I(e,[`authType`])!==void 0)throw Error(`authType parameter is not supported in Gemini API.`);if(I(e,[`googleServiceAccountConfig`])!==void 0)throw Error(`googleServiceAccountConfig parameter is not supported in Gemini API.`);if(I(e,[`httpBasicAuthConfig`])!==void 0)throw Error(`httpBasicAuthConfig parameter is not supported in Gemini API.`);if(I(e,[`oauthConfig`])!==void 0)throw Error(`oauthConfig parameter is not supported in Gemini API.`);if(I(e,[`oidcConfig`])!==void 0)throw Error(`oidcConfig parameter is not supported in Gemini API.`);return t}function Mi(e){let t={},n=I(e,[`data`]);if(n!=null&&F(t,[`data`],n),I(e,[`displayName`])!==void 0)throw Error(`displayName parameter is not supported in Gemini API.`);let r=I(e,[`mimeType`]);return r!=null&&F(t,[`mimeType`],r),t}function Ni(e){let t={},n=I(e,[`parts`]);if(n!=null){let e=n;Array.isArray(e)&&(e=e.map(e=>ra(e))),F(t,[`parts`],e)}let r=I(e,[`role`]);return r!=null&&F(t,[`role`],r),t}function Pi(e){let t={},n=I(e,[`parts`]);if(n!=null){let e=n;Array.isArray(e)&&(e=e.map(e=>ia(e))),F(t,[`parts`],e)}let r=I(e,[`role`]);return r!=null&&F(t,[`role`],r),t}function Fi(e,t){let n={},r=I(e,[`ttl`]);t!==void 0&&r!=null&&F(t,[`ttl`],r);let i=I(e,[`expireTime`]);t!==void 0&&i!=null&&F(t,[`expireTime`],i);let a=I(e,[`displayName`]);t!==void 0&&a!=null&&F(t,[`displayName`],a);let o=I(e,[`contents`]);if(t!==void 0&&o!=null){let e=B(o);Array.isArray(e)&&(e=e.map(e=>Ni(e))),F(t,[`contents`],e)}let s=I(e,[`systemInstruction`]);t!==void 0&&s!=null&&F(t,[`systemInstruction`],Ni(z(s)));let c=I(e,[`tools`]);if(t!==void 0&&c!=null){let e=c;Array.isArray(e)&&(e=e.map(e=>sa(e))),F(t,[`tools`],e)}let l=I(e,[`toolConfig`]);if(t!==void 0&&l!=null&&F(t,[`toolConfig`],aa(l)),I(e,[`kmsKeyName`])!==void 0)throw Error(`kmsKeyName parameter is not supported in Gemini API.`);return n}function Ii(e,t){let n={},r=I(e,[`ttl`]);t!==void 0&&r!=null&&F(t,[`ttl`],r);let i=I(e,[`expireTime`]);t!==void 0&&i!=null&&F(t,[`expireTime`],i);let a=I(e,[`displayName`]);t!==void 0&&a!=null&&F(t,[`displayName`],a);let o=I(e,[`contents`]);if(t!==void 0&&o!=null){let e=B(o);Array.isArray(e)&&(e=e.map(e=>Pi(e))),F(t,[`contents`],e)}let s=I(e,[`systemInstruction`]);t!==void 0&&s!=null&&F(t,[`systemInstruction`],Pi(z(s)));let c=I(e,[`tools`]);if(t!==void 0&&c!=null){let e=c;Array.isArray(e)&&(e=e.map(e=>ca(e))),F(t,[`tools`],e)}let l=I(e,[`toolConfig`]);t!==void 0&&l!=null&&F(t,[`toolConfig`],oa(l));let u=I(e,[`kmsKeyName`]);return t!==void 0&&u!=null&&F(t,[`encryption_spec`,`kmsKeyName`],u),n}function Li(e,t){let n={},r=I(t,[`model`]);r!=null&&F(n,[`model`],Qn(e,r));let i=I(t,[`config`]);return i!=null&&Fi(i,n),n}function Ri(e,t){let n={},r=I(t,[`model`]);r!=null&&F(n,[`model`],Qn(e,r));let i=I(t,[`config`]);return i!=null&&Ii(i,n),n}function zi(e,t){let n={},r=I(t,[`name`]);return r!=null&&F(n,[`_url`,`name`],V(e,r)),n}function Bi(e,t){let n={},r=I(t,[`name`]);return r!=null&&F(n,[`_url`,`name`],V(e,r)),n}function Vi(e){let t={},n=I(e,[`sdkHttpResponse`]);return n!=null&&F(t,[`sdkHttpResponse`],n),t}function Hi(e){let t={},n=I(e,[`sdkHttpResponse`]);return n!=null&&F(t,[`sdkHttpResponse`],n),t}function Ui(e){let t={};if(I(e,[`displayName`])!==void 0)throw Error(`displayName parameter is not supported in Gemini API.`);let n=I(e,[`fileUri`]);n!=null&&F(t,[`fileUri`],n);let r=I(e,[`mimeType`]);return r!=null&&F(t,[`mimeType`],r),t}function Wi(e){let t={},n=I(e,[`id`]);n!=null&&F(t,[`id`],n);let r=I(e,[`args`]);r!=null&&F(t,[`args`],r);let i=I(e,[`name`]);if(i!=null&&F(t,[`name`],i),I(e,[`partialArgs`])!==void 0)throw Error(`partialArgs parameter is not supported in Gemini API.`);if(I(e,[`willContinue`])!==void 0)throw Error(`willContinue parameter is not supported in Gemini API.`);return t}function Gi(e){let t={},n=I(e,[`allowedFunctionNames`]);n!=null&&F(t,[`allowedFunctionNames`],n);let r=I(e,[`mode`]);if(r!=null&&F(t,[`mode`],r),I(e,[`streamFunctionCallArguments`])!==void 0)throw Error(`streamFunctionCallArguments parameter is not supported in Gemini API.`);return t}function Ki(e){let t={},n=I(e,[`description`]);n!=null&&F(t,[`description`],n);let r=I(e,[`name`]);r!=null&&F(t,[`name`],r);let i=I(e,[`parameters`]);i!=null&&F(t,[`parameters`],i);let a=I(e,[`parametersJsonSchema`]);a!=null&&F(t,[`parametersJsonSchema`],a);let o=I(e,[`response`]);o!=null&&F(t,[`response`],o);let s=I(e,[`responseJsonSchema`]);if(s!=null&&F(t,[`responseJsonSchema`],s),I(e,[`behavior`])!==void 0)throw Error(`behavior parameter is not supported in Vertex AI.`);return t}function qi(e,t){let n={},r=I(t,[`name`]);return r!=null&&F(n,[`_url`,`name`],V(e,r)),n}function Ji(e,t){let n={},r=I(t,[`name`]);return r!=null&&F(n,[`_url`,`name`],V(e,r)),n}function Yi(e){let t={},n=I(e,[`authConfig`]);n!=null&&F(t,[`authConfig`],ji(n));let r=I(e,[`enableWidget`]);return r!=null&&F(t,[`enableWidget`],r),t}function Xi(e){let t={},n=I(e,[`searchTypes`]);if(n!=null&&F(t,[`searchTypes`],n),I(e,[`blockingConfidence`])!==void 0)throw Error(`blockingConfidence parameter is not supported in Gemini API.`);if(I(e,[`excludeDomains`])!==void 0)throw Error(`excludeDomains parameter is not supported in Gemini API.`);let r=I(e,[`timeRangeFilter`]);return r!=null&&F(t,[`timeRangeFilter`],r),t}function Zi(e,t){let n={},r=I(e,[`pageSize`]);t!==void 0&&r!=null&&F(t,[`_query`,`pageSize`],r);let i=I(e,[`pageToken`]);return t!==void 0&&i!=null&&F(t,[`_query`,`pageToken`],i),n}function Qi(e,t){let n={},r=I(e,[`pageSize`]);t!==void 0&&r!=null&&F(t,[`_query`,`pageSize`],r);let i=I(e,[`pageToken`]);return t!==void 0&&i!=null&&F(t,[`_query`,`pageToken`],i),n}function $i(e){let t={},n=I(e,[`config`]);return n!=null&&Zi(n,t),t}function ea(e){let t={},n=I(e,[`config`]);return n!=null&&Qi(n,t),t}function ta(e){let t={},n=I(e,[`sdkHttpResponse`]);n!=null&&F(t,[`sdkHttpResponse`],n);let r=I(e,[`nextPageToken`]);r!=null&&F(t,[`nextPageToken`],r);let i=I(e,[`cachedContents`]);if(i!=null){let e=i;Array.isArray(e)&&(e=e.map(e=>e)),F(t,[`cachedContents`],e)}return t}function na(e){let t={},n=I(e,[`sdkHttpResponse`]);n!=null&&F(t,[`sdkHttpResponse`],n);let r=I(e,[`nextPageToken`]);r!=null&&F(t,[`nextPageToken`],r);let i=I(e,[`cachedContents`]);if(i!=null){let e=i;Array.isArray(e)&&(e=e.map(e=>e)),F(t,[`cachedContents`],e)}return t}function ra(e){let t={},n=I(e,[`mediaResolution`]);n!=null&&F(t,[`mediaResolution`],n);let r=I(e,[`codeExecutionResult`]);r!=null&&F(t,[`codeExecutionResult`],r);let i=I(e,[`executableCode`]);i!=null&&F(t,[`executableCode`],i);let a=I(e,[`fileData`]);a!=null&&F(t,[`fileData`],Ui(a));let o=I(e,[`functionCall`]);o!=null&&F(t,[`functionCall`],Wi(o));let s=I(e,[`functionResponse`]);s!=null&&F(t,[`functionResponse`],s);let c=I(e,[`inlineData`]);c!=null&&F(t,[`inlineData`],Mi(c));let l=I(e,[`text`]);l!=null&&F(t,[`text`],l);let u=I(e,[`thought`]);u!=null&&F(t,[`thought`],u);let d=I(e,[`thoughtSignature`]);d!=null&&F(t,[`thoughtSignature`],d);let f=I(e,[`videoMetadata`]);f!=null&&F(t,[`videoMetadata`],f);let p=I(e,[`toolCall`]);p!=null&&F(t,[`toolCall`],p);let m=I(e,[`toolResponse`]);m!=null&&F(t,[`toolResponse`],m);let h=I(e,[`partMetadata`]);return h!=null&&F(t,[`partMetadata`],h),t}function ia(e){let t={},n=I(e,[`mediaResolution`]);n!=null&&F(t,[`mediaResolution`],n);let r=I(e,[`codeExecutionResult`]);r!=null&&F(t,[`codeExecutionResult`],r);let i=I(e,[`executableCode`]);i!=null&&F(t,[`executableCode`],i);let a=I(e,[`fileData`]);a!=null&&F(t,[`fileData`],a);let o=I(e,[`functionCall`]);o!=null&&F(t,[`functionCall`],o);let s=I(e,[`functionResponse`]);s!=null&&F(t,[`functionResponse`],s);let c=I(e,[`inlineData`]);c!=null&&F(t,[`inlineData`],c);let l=I(e,[`text`]);l!=null&&F(t,[`text`],l);let u=I(e,[`thought`]);u!=null&&F(t,[`thought`],u);let d=I(e,[`thoughtSignature`]);d!=null&&F(t,[`thoughtSignature`],d);let f=I(e,[`videoMetadata`]);if(f!=null&&F(t,[`videoMetadata`],f),I(e,[`toolCall`])!==void 0)throw Error(`toolCall parameter is not supported in Vertex AI.`);if(I(e,[`toolResponse`])!==void 0)throw Error(`toolResponse parameter is not supported in Vertex AI.`);if(I(e,[`partMetadata`])!==void 0)throw Error(`partMetadata parameter is not supported in Vertex AI.`);return t}function aa(e){let t={},n=I(e,[`retrievalConfig`]);n!=null&&F(t,[`retrievalConfig`],n);let r=I(e,[`functionCallingConfig`]);r!=null&&F(t,[`functionCallingConfig`],Gi(r));let i=I(e,[`includeServerSideToolInvocations`]);return i!=null&&F(t,[`includeServerSideToolInvocations`],i),t}function oa(e){let t={},n=I(e,[`retrievalConfig`]);n!=null&&F(t,[`retrievalConfig`],n);let r=I(e,[`functionCallingConfig`]);if(r!=null&&F(t,[`functionCallingConfig`],r),I(e,[`includeServerSideToolInvocations`])!==void 0)throw Error(`includeServerSideToolInvocations parameter is not supported in Vertex AI.`);return t}function sa(e){let t={};if(I(e,[`retrieval`])!==void 0)throw Error(`retrieval parameter is not supported in Gemini API.`);let n=I(e,[`computerUse`]);n!=null&&F(t,[`computerUse`],n);let r=I(e,[`fileSearch`]);r!=null&&F(t,[`fileSearch`],r);let i=I(e,[`googleSearch`]);i!=null&&F(t,[`googleSearch`],Xi(i));let a=I(e,[`googleMaps`]);a!=null&&F(t,[`googleMaps`],Yi(a));let o=I(e,[`codeExecution`]);if(o!=null&&F(t,[`codeExecution`],o),I(e,[`enterpriseWebSearch`])!==void 0)throw Error(`enterpriseWebSearch parameter is not supported in Gemini API.`);let s=I(e,[`functionDeclarations`]);if(s!=null){let e=s;Array.isArray(e)&&(e=e.map(e=>e)),F(t,[`functionDeclarations`],e)}let c=I(e,[`googleSearchRetrieval`]);if(c!=null&&F(t,[`googleSearchRetrieval`],c),I(e,[`parallelAiSearch`])!==void 0)throw Error(`parallelAiSearch parameter is not supported in Gemini API.`);let l=I(e,[`urlContext`]);l!=null&&F(t,[`urlContext`],l);let u=I(e,[`mcpServers`]);if(u!=null){let e=u;Array.isArray(e)&&(e=e.map(e=>e)),F(t,[`mcpServers`],e)}return t}function ca(e){let t={},n=I(e,[`retrieval`]);n!=null&&F(t,[`retrieval`],n);let r=I(e,[`computerUse`]);if(r!=null&&F(t,[`computerUse`],r),I(e,[`fileSearch`])!==void 0)throw Error(`fileSearch parameter is not supported in Vertex AI.`);let i=I(e,[`googleSearch`]);i!=null&&F(t,[`googleSearch`],i);let a=I(e,[`googleMaps`]);a!=null&&F(t,[`googleMaps`],a);let o=I(e,[`codeExecution`]);o!=null&&F(t,[`codeExecution`],o);let s=I(e,[`enterpriseWebSearch`]);s!=null&&F(t,[`enterpriseWebSearch`],s);let c=I(e,[`functionDeclarations`]);if(c!=null){let e=c;Array.isArray(e)&&(e=e.map(e=>Ki(e))),F(t,[`functionDeclarations`],e)}let l=I(e,[`googleSearchRetrieval`]);l!=null&&F(t,[`googleSearchRetrieval`],l);let u=I(e,[`parallelAiSearch`]);u!=null&&F(t,[`parallelAiSearch`],u);let d=I(e,[`urlContext`]);if(d!=null&&F(t,[`urlContext`],d),I(e,[`mcpServers`])!==void 0)throw Error(`mcpServers parameter is not supported in Vertex AI.`);return t}function la(e,t){let n={},r=I(e,[`ttl`]);t!==void 0&&r!=null&&F(t,[`ttl`],r);let i=I(e,[`expireTime`]);return t!==void 0&&i!=null&&F(t,[`expireTime`],i),n}function ua(e,t){let n={},r=I(e,[`ttl`]);t!==void 0&&r!=null&&F(t,[`ttl`],r);let i=I(e,[`expireTime`]);return t!==void 0&&i!=null&&F(t,[`expireTime`],i),n}function da(e,t){let n={},r=I(t,[`name`]);r!=null&&F(n,[`_url`,`name`],V(e,r));let i=I(t,[`config`]);return i!=null&&la(i,n),n}function fa(e,t){let n={},r=I(t,[`name`]);r!=null&&F(n,[`_url`,`name`],V(e,r));let i=I(t,[`config`]);return i!=null&&ua(i,n),n}
58
+ /**
59
+ * @license
60
+ * Copyright 2025 Google LLC
61
+ * SPDX-License-Identifier: Apache-2.0
62
+ */
63
+ var pa=class extends N{constructor(e){super(),this.apiClient=e,this.list=async(e={})=>new ki(U.PAGED_ITEM_CACHED_CONTENTS,e=>this.listInternal(e),await this.listInternal(e),e)}async create(e){let t,n=``,r={};if(this.apiClient.isVertexAI()){let i=Ri(this.apiClient,e);return n=P(`cachedContents`,i._url),r=i._query,delete i._url,delete i._query,t=this.apiClient.request({path:n,queryParams:r,body:JSON.stringify(i),httpMethod:`POST`,httpOptions:e.config?.httpOptions,abortSignal:e.config?.abortSignal}).then(e=>e.json()),t.then(e=>e)}else{let i=Li(this.apiClient,e);return n=P(`cachedContents`,i._url),r=i._query,delete i._url,delete i._query,t=this.apiClient.request({path:n,queryParams:r,body:JSON.stringify(i),httpMethod:`POST`,httpOptions:e.config?.httpOptions,abortSignal:e.config?.abortSignal}).then(e=>e.json()),t.then(e=>e)}}async get(e){let t,n=``,r={};if(this.apiClient.isVertexAI()){let i=Ji(this.apiClient,e);return n=P(`{name}`,i._url),r=i._query,delete i._url,delete i._query,t=this.apiClient.request({path:n,queryParams:r,body:JSON.stringify(i),httpMethod:`GET`,httpOptions:e.config?.httpOptions,abortSignal:e.config?.abortSignal}).then(e=>e.json()),t.then(e=>e)}else{let i=qi(this.apiClient,e);return n=P(`{name}`,i._url),r=i._query,delete i._url,delete i._query,t=this.apiClient.request({path:n,queryParams:r,body:JSON.stringify(i),httpMethod:`GET`,httpOptions:e.config?.httpOptions,abortSignal:e.config?.abortSignal}).then(e=>e.json()),t.then(e=>e)}}async delete(e){let t,n=``,r={};if(this.apiClient.isVertexAI()){let i=Bi(this.apiClient,e);return n=P(`{name}`,i._url),r=i._query,delete i._url,delete i._query,t=this.apiClient.request({path:n,queryParams:r,body:JSON.stringify(i),httpMethod:`DELETE`,httpOptions:e.config?.httpOptions,abortSignal:e.config?.abortSignal}).then(e=>e.json().then(t=>{let n=t;return n.sdkHttpResponse={headers:e.headers},n})),t.then(e=>{let t=Hi(e),n=new Rn;return Object.assign(n,t),n})}else{let i=zi(this.apiClient,e);return n=P(`{name}`,i._url),r=i._query,delete i._url,delete i._query,t=this.apiClient.request({path:n,queryParams:r,body:JSON.stringify(i),httpMethod:`DELETE`,httpOptions:e.config?.httpOptions,abortSignal:e.config?.abortSignal}).then(e=>e.json().then(t=>{let n=t;return n.sdkHttpResponse={headers:e.headers},n})),t.then(e=>{let t=Vi(e),n=new Rn;return Object.assign(n,t),n})}}async update(e){let t,n=``,r={};if(this.apiClient.isVertexAI()){let i=fa(this.apiClient,e);return n=P(`{name}`,i._url),r=i._query,delete i._url,delete i._query,t=this.apiClient.request({path:n,queryParams:r,body:JSON.stringify(i),httpMethod:`PATCH`,httpOptions:e.config?.httpOptions,abortSignal:e.config?.abortSignal}).then(e=>e.json()),t.then(e=>e)}else{let i=da(this.apiClient,e);return n=P(`{name}`,i._url),r=i._query,delete i._url,delete i._query,t=this.apiClient.request({path:n,queryParams:r,body:JSON.stringify(i),httpMethod:`PATCH`,httpOptions:e.config?.httpOptions,abortSignal:e.config?.abortSignal}).then(e=>e.json()),t.then(e=>e)}}async listInternal(e){let t,n=``,r={};if(this.apiClient.isVertexAI()){let i=ea(e);return n=P(`cachedContents`,i._url),r=i._query,delete i._url,delete i._query,t=this.apiClient.request({path:n,queryParams:r,body:JSON.stringify(i),httpMethod:`GET`,httpOptions:e.config?.httpOptions,abortSignal:e.config?.abortSignal}).then(e=>e.json().then(t=>{let n=t;return n.sdkHttpResponse={headers:e.headers},n})),t.then(e=>{let t=na(e),n=new zn;return Object.assign(n,t),n})}else{let i=$i(e);return n=P(`cachedContents`,i._url),r=i._query,delete i._url,delete i._query,t=this.apiClient.request({path:n,queryParams:r,body:JSON.stringify(i),httpMethod:`GET`,httpOptions:e.config?.httpOptions,abortSignal:e.config?.abortSignal}).then(e=>e.json().then(t=>{let n=t;return n.sdkHttpResponse={headers:e.headers},n})),t.then(e=>{let t=ta(e),n=new zn;return Object.assign(n,t),n})}}};function W(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&typeof Object.getOwnPropertySymbols==`function`)for(var i=0,r=Object.getOwnPropertySymbols(e);i<r.length;i++)t.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(e,r[i])&&(n[r[i]]=e[r[i]]);return n}function ma(e){var t=typeof Symbol==`function`&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&typeof e.length==`number`)return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw TypeError(t?`Object is not iterable.`:`Symbol.iterator is not defined.`)}function G(e){return this instanceof G?(this.v=e,this):new G(e)}function K(e,t,n){if(!Symbol.asyncIterator)throw TypeError(`Symbol.asyncIterator is not defined.`);var r=n.apply(e,t||[]),i,a=[];return i=Object.create((typeof AsyncIterator==`function`?AsyncIterator:Object).prototype),s(`next`),s(`throw`),s(`return`,o),i[Symbol.asyncIterator]=function(){return this},i;function o(e){return function(t){return Promise.resolve(t).then(e,d)}}function s(e,t){r[e]&&(i[e]=function(t){return new Promise(function(n,r){a.push([e,t,n,r])>1||c(e,t)})},t&&(i[e]=t(i[e])))}function c(e,t){try{l(r[e](t))}catch(e){f(a[0][3],e)}}function l(e){e.value instanceof G?Promise.resolve(e.value.v).then(u,d):f(a[0][2],e)}function u(e){c(`next`,e)}function d(e){c(`throw`,e)}function f(e,t){e(t),a.shift(),a.length&&c(a[0][0],a[0][1])}}function q(e){if(!Symbol.asyncIterator)throw TypeError(`Symbol.asyncIterator is not defined.`);var t=e[Symbol.asyncIterator],n;return t?t.call(e):(e=typeof ma==`function`?ma(e):e[Symbol.iterator](),n={},r(`next`),r(`throw`),r(`return`),n[Symbol.asyncIterator]=function(){return this},n);function r(t){n[t]=e[t]&&function(n){return new Promise(function(r,a){n=e[t](n),i(r,a,n.done,n.value)})}}function i(e,t,n,r){Promise.resolve(r).then(function(t){e({value:t,done:n})},t)}}
64
+ /**
65
+ * @license
66
+ * Copyright 2025 Google LLC
67
+ * SPDX-License-Identifier: Apache-2.0
68
+ */
69
+ function ha(e){if(e.candidates==null||e.candidates.length===0)return!1;let t=e.candidates[0]?.content;return t===void 0?!1:ga(t)}function ga(e){if(e.parts===void 0||e.parts.length===0)return!1;for(let t of e.parts)if(t===void 0||Object.keys(t).length===0)return!1;return!0}function _a(e){if(e.length!==0){for(let t of e)if(t.role!==`user`&&t.role!==`model`)throw Error(`Role must be user or model, but got ${t.role}.`)}}function va(e){if(e===void 0||e.length===0)return[];let t=[],n=e.length,r=0;for(;r<n;)if(e[r].role===`user`)t.push(e[r]),r++;else{let i=[],a=!0;for(;r<n&&e[r].role===`model`;)i.push(e[r]),a&&!ga(e[r])&&(a=!1),r++;a?t.push(...i):t.pop()}return t}var ya=class{constructor(e,t){this.modelsModule=e,this.apiClient=t}create(e){return new ba(this.apiClient,this.modelsModule,e.model,e.config,structuredClone(e.history))}},ba=class{constructor(e,t,n,r={},i=[]){this.apiClient=e,this.modelsModule=t,this.model=n,this.config=r,this.history=i,this.sendPromise=Promise.resolve(),_a(i)}async sendMessage(e){await this.sendPromise;let t=z(e.message),n=this.modelsModule.generateContent({model:this.model,contents:this.getHistory(!0).concat(t),config:e.config??this.config});return this.sendPromise=(async()=>{let e=await n,r=e.candidates?.[0]?.content,i=e.automaticFunctionCallingHistory,a=this.getHistory(!0).length,o=[];i!=null&&(o=i.slice(a)??[]);let s=r?[r]:[];this.recordHistory(t,s,o)})(),await this.sendPromise.catch(()=>{this.sendPromise=Promise.resolve()}),n}async sendMessageStream(e){await this.sendPromise;let t=z(e.message),n=this.modelsModule.generateContentStream({model:this.model,contents:this.getHistory(!0).concat(t),config:e.config??this.config});this.sendPromise=n.then(()=>void 0).catch(()=>void 0);let r=await n;return this.processStreamResponse(r,t)}getHistory(e=!1){let t=e?va(this.history):this.history;return structuredClone(t)}processStreamResponse(e,t){return K(this,arguments,function*(){var n,r,i,a;let o=[];try{for(var s=!0,c=q(e),l;l=yield G(c.next()),n=l.done,!n;s=!0){a=l.value,s=!1;let e=a;if(ha(e)){let t=e.candidates?.[0]?.content;t!==void 0&&o.push(t)}yield yield G(e)}}catch(e){r={error:e}}finally{try{!s&&!n&&(i=c.return)&&(yield G(i.call(c)))}finally{if(r)throw r.error}}this.recordHistory(t,o)})}recordHistory(e,t,n){let r=[];t.length>0&&t.every(e=>e.role!==void 0)?r=t:r.push({role:`model`,parts:[]}),n&&n.length>0?this.history.push(...va(n)):this.history.push(e),this.history.push(...r)}},xa=class e extends Error{constructor(t){super(t.message),this.name=`ApiError`,this.status=t.status,Object.setPrototypeOf(this,e.prototype)}};
70
+ /**
71
+ * @license
72
+ * Copyright 2025 Google LLC
73
+ * SPDX-License-Identifier: Apache-2.0
74
+ */
75
+ function Sa(e){let t={},n=I(e,[`file`]);return n!=null&&F(t,[`file`],n),t}function Ca(e){let t={},n=I(e,[`sdkHttpResponse`]);return n!=null&&F(t,[`sdkHttpResponse`],n),t}function wa(e){let t={},n=I(e,[`name`]);return n!=null&&F(t,[`_url`,`file`],xr(n)),t}function Ta(e){let t={},n=I(e,[`sdkHttpResponse`]);return n!=null&&F(t,[`sdkHttpResponse`],n),t}function Ea(e){let t={},n=I(e,[`name`]);return n!=null&&F(t,[`_url`,`file`],xr(n)),t}function Da(e){let t={},n=I(e,[`uris`]);return n!=null&&F(t,[`uris`],n),t}function Oa(e,t){let n={},r=I(e,[`pageSize`]);t!==void 0&&r!=null&&F(t,[`_query`,`pageSize`],r);let i=I(e,[`pageToken`]);return t!==void 0&&i!=null&&F(t,[`_query`,`pageToken`],i),n}function ka(e){let t={},n=I(e,[`config`]);return n!=null&&Oa(n,t),t}function Aa(e){let t={},n=I(e,[`sdkHttpResponse`]);n!=null&&F(t,[`sdkHttpResponse`],n);let r=I(e,[`nextPageToken`]);r!=null&&F(t,[`nextPageToken`],r);let i=I(e,[`files`]);if(i!=null){let e=i;Array.isArray(e)&&(e=e.map(e=>e)),F(t,[`files`],e)}return t}function ja(e){let t={},n=I(e,[`sdkHttpResponse`]);n!=null&&F(t,[`sdkHttpResponse`],n);let r=I(e,[`files`]);if(r!=null){let e=r;Array.isArray(e)&&(e=e.map(e=>e)),F(t,[`files`],e)}return t}
76
+ /**
77
+ * @license
78
+ * Copyright 2025 Google LLC
79
+ * SPDX-License-Identifier: Apache-2.0
80
+ */
81
+ var Ma=class extends N{constructor(e){super(),this.apiClient=e,this.list=async(e={})=>new ki(U.PAGED_ITEM_FILES,e=>this.listInternal(e),await this.listInternal(e),e)}async upload(e){if(this.apiClient.isVertexAI())throw Error(`Vertex AI does not support uploading files. You can share files through a GCS bucket.`);return this.apiClient.uploadFile(e.file,e.config).then(e=>e)}async download(e){await this.apiClient.downloadFile(e)}async registerFiles(e){throw Error(`registerFiles is only supported in Node.js environments.`)}async _registerFiles(e){return this.registerFilesInternal(e)}async listInternal(e){let t,n=``,r={};if(this.apiClient.isVertexAI())throw Error(`This method is only supported by the Gemini Developer API.`);{let i=ka(e);return n=P(`files`,i._url),r=i._query,delete i._url,delete i._query,t=this.apiClient.request({path:n,queryParams:r,body:JSON.stringify(i),httpMethod:`GET`,httpOptions:e.config?.httpOptions,abortSignal:e.config?.abortSignal}).then(e=>e.json().then(t=>{let n=t;return n.sdkHttpResponse={headers:e.headers},n})),t.then(e=>{let t=Aa(e),n=new Wn;return Object.assign(n,t),n})}}async createInternal(e){let t,n=``,r={};if(this.apiClient.isVertexAI())throw Error(`This method is only supported by the Gemini Developer API.`);{let i=Sa(e);return n=P(`upload/v1beta/files`,i._url),r=i._query,delete i._url,delete i._query,t=this.apiClient.request({path:n,queryParams:r,body:JSON.stringify(i),httpMethod:`POST`,httpOptions:e.config?.httpOptions,abortSignal:e.config?.abortSignal}).then(e=>e.json()),t.then(e=>{let t=Ca(e),n=new Gn;return Object.assign(n,t),n})}}async get(e){let t,n=``,r={};if(this.apiClient.isVertexAI())throw Error(`This method is only supported by the Gemini Developer API.`);{let i=Ea(e);return n=P(`files/{file}`,i._url),r=i._query,delete i._url,delete i._query,t=this.apiClient.request({path:n,queryParams:r,body:JSON.stringify(i),httpMethod:`GET`,httpOptions:e.config?.httpOptions,abortSignal:e.config?.abortSignal}).then(e=>e.json()),t.then(e=>e)}}async delete(e){let t,n=``,r={};if(this.apiClient.isVertexAI())throw Error(`This method is only supported by the Gemini Developer API.`);{let i=wa(e);return n=P(`files/{file}`,i._url),r=i._query,delete i._url,delete i._query,t=this.apiClient.request({path:n,queryParams:r,body:JSON.stringify(i),httpMethod:`DELETE`,httpOptions:e.config?.httpOptions,abortSignal:e.config?.abortSignal}).then(e=>e.json().then(t=>{let n=t;return n.sdkHttpResponse={headers:e.headers},n})),t.then(e=>{let t=Ta(e),n=new Kn;return Object.assign(n,t),n})}}async registerFilesInternal(e){let t,n=``,r={};if(this.apiClient.isVertexAI())throw Error(`This method is only supported by the Gemini Developer API.`);{let i=Da(e);return n=P(`files:register`,i._url),r=i._query,delete i._url,delete i._query,t=this.apiClient.request({path:n,queryParams:r,body:JSON.stringify(i),httpMethod:`POST`,httpOptions:e.config?.httpOptions,abortSignal:e.config?.abortSignal}).then(e=>e.json()),t.then(e=>{let t=ja(e),n=new qn;return Object.assign(n,t),n})}}};
82
+ /**
83
+ * @license
84
+ * Copyright 2025 Google LLC
85
+ * SPDX-License-Identifier: Apache-2.0
86
+ */
87
+ function Na(e){let t={};if(I(e,[`languageCodes`])!==void 0)throw Error(`languageCodes parameter is not supported in Gemini API.`);return t}function Pa(e){let t={},n=I(e,[`apiKey`]);if(n!=null&&F(t,[`apiKey`],n),I(e,[`apiKeyConfig`])!==void 0)throw Error(`apiKeyConfig parameter is not supported in Gemini API.`);if(I(e,[`authType`])!==void 0)throw Error(`authType parameter is not supported in Gemini API.`);if(I(e,[`googleServiceAccountConfig`])!==void 0)throw Error(`googleServiceAccountConfig parameter is not supported in Gemini API.`);if(I(e,[`httpBasicAuthConfig`])!==void 0)throw Error(`httpBasicAuthConfig parameter is not supported in Gemini API.`);if(I(e,[`oauthConfig`])!==void 0)throw Error(`oauthConfig parameter is not supported in Gemini API.`);if(I(e,[`oidcConfig`])!==void 0)throw Error(`oidcConfig parameter is not supported in Gemini API.`);return t}function Fa(e){let t={},n=I(e,[`data`]);if(n!=null&&F(t,[`data`],n),I(e,[`displayName`])!==void 0)throw Error(`displayName parameter is not supported in Gemini API.`);let r=I(e,[`mimeType`]);return r!=null&&F(t,[`mimeType`],r),t}function Ia(e){let t={},n=I(e,[`parts`]);if(n!=null){let e=n;Array.isArray(e)&&(e=e.map(e=>$a(e))),F(t,[`parts`],e)}let r=I(e,[`role`]);return r!=null&&F(t,[`role`],r),t}function La(e){let t={},n=I(e,[`parts`]);if(n!=null){let e=n;Array.isArray(e)&&(e=e.map(e=>eo(e))),F(t,[`parts`],e)}let r=I(e,[`role`]);return r!=null&&F(t,[`role`],r),t}function Ra(e){let t={};if(I(e,[`displayName`])!==void 0)throw Error(`displayName parameter is not supported in Gemini API.`);let n=I(e,[`fileUri`]);n!=null&&F(t,[`fileUri`],n);let r=I(e,[`mimeType`]);return r!=null&&F(t,[`mimeType`],r),t}function za(e){let t={},n=I(e,[`id`]);n!=null&&F(t,[`id`],n);let r=I(e,[`args`]);r!=null&&F(t,[`args`],r);let i=I(e,[`name`]);if(i!=null&&F(t,[`name`],i),I(e,[`partialArgs`])!==void 0)throw Error(`partialArgs parameter is not supported in Gemini API.`);if(I(e,[`willContinue`])!==void 0)throw Error(`willContinue parameter is not supported in Gemini API.`);return t}function Ba(e){let t={},n=I(e,[`description`]);n!=null&&F(t,[`description`],n);let r=I(e,[`name`]);r!=null&&F(t,[`name`],r);let i=I(e,[`parameters`]);i!=null&&F(t,[`parameters`],i);let a=I(e,[`parametersJsonSchema`]);a!=null&&F(t,[`parametersJsonSchema`],a);let o=I(e,[`response`]);o!=null&&F(t,[`response`],o);let s=I(e,[`responseJsonSchema`]);if(s!=null&&F(t,[`responseJsonSchema`],s),I(e,[`behavior`])!==void 0)throw Error(`behavior parameter is not supported in Vertex AI.`);return t}function Va(e){let t={},n=I(e,[`modelSelectionConfig`]);n!=null&&F(t,[`modelConfig`],n);let r=I(e,[`responseJsonSchema`]);r!=null&&F(t,[`responseJsonSchema`],r);let i=I(e,[`audioTimestamp`]);i!=null&&F(t,[`audioTimestamp`],i);let a=I(e,[`candidateCount`]);a!=null&&F(t,[`candidateCount`],a);let o=I(e,[`enableAffectiveDialog`]);o!=null&&F(t,[`enableAffectiveDialog`],o);let s=I(e,[`frequencyPenalty`]);s!=null&&F(t,[`frequencyPenalty`],s);let c=I(e,[`logprobs`]);c!=null&&F(t,[`logprobs`],c);let l=I(e,[`maxOutputTokens`]);l!=null&&F(t,[`maxOutputTokens`],l);let u=I(e,[`mediaResolution`]);u!=null&&F(t,[`mediaResolution`],u);let d=I(e,[`presencePenalty`]);d!=null&&F(t,[`presencePenalty`],d);let f=I(e,[`responseLogprobs`]);f!=null&&F(t,[`responseLogprobs`],f);let p=I(e,[`responseMimeType`]);p!=null&&F(t,[`responseMimeType`],p);let m=I(e,[`responseModalities`]);m!=null&&F(t,[`responseModalities`],m);let h=I(e,[`responseSchema`]);h!=null&&F(t,[`responseSchema`],h);let g=I(e,[`routingConfig`]);g!=null&&F(t,[`routingConfig`],g);let _=I(e,[`seed`]);_!=null&&F(t,[`seed`],_);let v=I(e,[`speechConfig`]);v!=null&&F(t,[`speechConfig`],v);let y=I(e,[`stopSequences`]);y!=null&&F(t,[`stopSequences`],y);let b=I(e,[`temperature`]);b!=null&&F(t,[`temperature`],b);let x=I(e,[`thinkingConfig`]);x!=null&&F(t,[`thinkingConfig`],x);let S=I(e,[`topK`]);S!=null&&F(t,[`topK`],S);let C=I(e,[`topP`]);if(C!=null&&F(t,[`topP`],C),I(e,[`enableEnhancedCivicAnswers`])!==void 0)throw Error(`enableEnhancedCivicAnswers parameter is not supported in Vertex AI.`);return t}function Ha(e){let t={},n=I(e,[`authConfig`]);n!=null&&F(t,[`authConfig`],Pa(n));let r=I(e,[`enableWidget`]);return r!=null&&F(t,[`enableWidget`],r),t}function Ua(e){let t={},n=I(e,[`searchTypes`]);if(n!=null&&F(t,[`searchTypes`],n),I(e,[`blockingConfidence`])!==void 0)throw Error(`blockingConfidence parameter is not supported in Gemini API.`);if(I(e,[`excludeDomains`])!==void 0)throw Error(`excludeDomains parameter is not supported in Gemini API.`);let r=I(e,[`timeRangeFilter`]);return r!=null&&F(t,[`timeRangeFilter`],r),t}function Wa(e,t){let n={},r=I(e,[`generationConfig`]);t!==void 0&&r!=null&&F(t,[`setup`,`generationConfig`],r);let i=I(e,[`responseModalities`]);t!==void 0&&i!=null&&F(t,[`setup`,`generationConfig`,`responseModalities`],i);let a=I(e,[`temperature`]);t!==void 0&&a!=null&&F(t,[`setup`,`generationConfig`,`temperature`],a);let o=I(e,[`topP`]);t!==void 0&&o!=null&&F(t,[`setup`,`generationConfig`,`topP`],o);let s=I(e,[`topK`]);t!==void 0&&s!=null&&F(t,[`setup`,`generationConfig`,`topK`],s);let c=I(e,[`maxOutputTokens`]);t!==void 0&&c!=null&&F(t,[`setup`,`generationConfig`,`maxOutputTokens`],c);let l=I(e,[`mediaResolution`]);t!==void 0&&l!=null&&F(t,[`setup`,`generationConfig`,`mediaResolution`],l);let u=I(e,[`seed`]);t!==void 0&&u!=null&&F(t,[`setup`,`generationConfig`,`seed`],u);let d=I(e,[`speechConfig`]);t!==void 0&&d!=null&&F(t,[`setup`,`generationConfig`,`speechConfig`],pr(d));let f=I(e,[`thinkingConfig`]);t!==void 0&&f!=null&&F(t,[`setup`,`generationConfig`,`thinkingConfig`],f);let p=I(e,[`enableAffectiveDialog`]);t!==void 0&&p!=null&&F(t,[`setup`,`generationConfig`,`enableAffectiveDialog`],p);let m=I(e,[`systemInstruction`]);t!==void 0&&m!=null&&F(t,[`setup`,`systemInstruction`],Ia(z(m)));let h=I(e,[`tools`]);if(t!==void 0&&h!=null){let e=hr(h);Array.isArray(e)&&(e=e.map(e=>ro(mr(e)))),F(t,[`setup`,`tools`],e)}let g=I(e,[`sessionResumption`]);t!==void 0&&g!=null&&F(t,[`setup`,`sessionResumption`],no(g));let _=I(e,[`inputAudioTranscription`]);t!==void 0&&_!=null&&F(t,[`setup`,`inputAudioTranscription`],Na(_));let v=I(e,[`outputAudioTranscription`]);t!==void 0&&v!=null&&F(t,[`setup`,`outputAudioTranscription`],Na(v));let y=I(e,[`realtimeInputConfig`]);t!==void 0&&y!=null&&F(t,[`setup`,`realtimeInputConfig`],y);let b=I(e,[`contextWindowCompression`]);t!==void 0&&b!=null&&F(t,[`setup`,`contextWindowCompression`],b);let x=I(e,[`proactivity`]);if(t!==void 0&&x!=null&&F(t,[`setup`,`proactivity`],x),I(e,[`explicitVadSignal`])!==void 0)throw Error(`explicitVadSignal parameter is not supported in Gemini API.`);let S=I(e,[`avatarConfig`]);t!==void 0&&S!=null&&F(t,[`setup`,`avatarConfig`],S);let C=I(e,[`safetySettings`]);if(t!==void 0&&C!=null){let e=C;Array.isArray(e)&&(e=e.map(e=>to(e))),F(t,[`setup`,`safetySettings`],e)}return n}function Ga(e,t){let n={},r=I(e,[`generationConfig`]);t!==void 0&&r!=null&&F(t,[`setup`,`generationConfig`],Va(r));let i=I(e,[`responseModalities`]);t!==void 0&&i!=null&&F(t,[`setup`,`generationConfig`,`responseModalities`],i);let a=I(e,[`temperature`]);t!==void 0&&a!=null&&F(t,[`setup`,`generationConfig`,`temperature`],a);let o=I(e,[`topP`]);t!==void 0&&o!=null&&F(t,[`setup`,`generationConfig`,`topP`],o);let s=I(e,[`topK`]);t!==void 0&&s!=null&&F(t,[`setup`,`generationConfig`,`topK`],s);let c=I(e,[`maxOutputTokens`]);t!==void 0&&c!=null&&F(t,[`setup`,`generationConfig`,`maxOutputTokens`],c);let l=I(e,[`mediaResolution`]);t!==void 0&&l!=null&&F(t,[`setup`,`generationConfig`,`mediaResolution`],l);let u=I(e,[`seed`]);t!==void 0&&u!=null&&F(t,[`setup`,`generationConfig`,`seed`],u);let d=I(e,[`speechConfig`]);t!==void 0&&d!=null&&F(t,[`setup`,`generationConfig`,`speechConfig`],pr(d));let f=I(e,[`thinkingConfig`]);t!==void 0&&f!=null&&F(t,[`setup`,`generationConfig`,`thinkingConfig`],f);let p=I(e,[`enableAffectiveDialog`]);t!==void 0&&p!=null&&F(t,[`setup`,`generationConfig`,`enableAffectiveDialog`],p);let m=I(e,[`systemInstruction`]);t!==void 0&&m!=null&&F(t,[`setup`,`systemInstruction`],La(z(m)));let h=I(e,[`tools`]);if(t!==void 0&&h!=null){let e=hr(h);Array.isArray(e)&&(e=e.map(e=>io(mr(e)))),F(t,[`setup`,`tools`],e)}let g=I(e,[`sessionResumption`]);t!==void 0&&g!=null&&F(t,[`setup`,`sessionResumption`],g);let _=I(e,[`inputAudioTranscription`]);t!==void 0&&_!=null&&F(t,[`setup`,`inputAudioTranscription`],_);let v=I(e,[`outputAudioTranscription`]);t!==void 0&&v!=null&&F(t,[`setup`,`outputAudioTranscription`],v);let y=I(e,[`realtimeInputConfig`]);t!==void 0&&y!=null&&F(t,[`setup`,`realtimeInputConfig`],y);let b=I(e,[`contextWindowCompression`]);t!==void 0&&b!=null&&F(t,[`setup`,`contextWindowCompression`],b);let x=I(e,[`proactivity`]);t!==void 0&&x!=null&&F(t,[`setup`,`proactivity`],x);let S=I(e,[`explicitVadSignal`]);t!==void 0&&S!=null&&F(t,[`setup`,`explicitVadSignal`],S);let C=I(e,[`avatarConfig`]);t!==void 0&&C!=null&&F(t,[`setup`,`avatarConfig`],C);let w=I(e,[`safetySettings`]);if(t!==void 0&&w!=null){let e=w;Array.isArray(e)&&(e=e.map(e=>e)),F(t,[`setup`,`safetySettings`],e)}return n}function Ka(e,t){let n={},r=I(t,[`model`]);r!=null&&F(n,[`setup`,`model`],R(e,r));let i=I(t,[`config`]);return i!=null&&F(n,[`config`],Wa(i,n)),n}function qa(e,t){let n={},r=I(t,[`model`]);r!=null&&F(n,[`setup`,`model`],R(e,r));let i=I(t,[`config`]);return i!=null&&F(n,[`config`],Ga(i,n)),n}function Ja(e){let t={},n=I(e,[`musicGenerationConfig`]);return n!=null&&F(t,[`musicGenerationConfig`],n),t}function Ya(e){let t={},n=I(e,[`weightedPrompts`]);if(n!=null){let e=n;Array.isArray(e)&&(e=e.map(e=>e)),F(t,[`weightedPrompts`],e)}return t}function Xa(e){let t={},n=I(e,[`media`]);if(n!=null){let e=$n(n);Array.isArray(e)&&(e=e.map(e=>Fa(e))),F(t,[`mediaChunks`],e)}let r=I(e,[`audio`]);r!=null&&F(t,[`audio`],Fa(nr(r)));let i=I(e,[`audioStreamEnd`]);i!=null&&F(t,[`audioStreamEnd`],i);let a=I(e,[`video`]);a!=null&&F(t,[`video`],Fa(tr(a)));let o=I(e,[`text`]);o!=null&&F(t,[`text`],o);let s=I(e,[`activityStart`]);s!=null&&F(t,[`activityStart`],s);let c=I(e,[`activityEnd`]);return c!=null&&F(t,[`activityEnd`],c),t}function Za(e){let t={},n=I(e,[`media`]);if(n!=null){let e=$n(n);Array.isArray(e)&&(e=e.map(e=>e)),F(t,[`mediaChunks`],e)}let r=I(e,[`audio`]);r!=null&&F(t,[`audio`],nr(r));let i=I(e,[`audioStreamEnd`]);i!=null&&F(t,[`audioStreamEnd`],i);let a=I(e,[`video`]);a!=null&&F(t,[`video`],tr(a));let o=I(e,[`text`]);o!=null&&F(t,[`text`],o);let s=I(e,[`activityStart`]);s!=null&&F(t,[`activityStart`],s);let c=I(e,[`activityEnd`]);return c!=null&&F(t,[`activityEnd`],c),t}function Qa(e){let t={},n=I(e,[`setupComplete`]);n!=null&&F(t,[`setupComplete`],n);let r=I(e,[`serverContent`]);r!=null&&F(t,[`serverContent`],r);let i=I(e,[`toolCall`]);i!=null&&F(t,[`toolCall`],i);let a=I(e,[`toolCallCancellation`]);a!=null&&F(t,[`toolCallCancellation`],a);let o=I(e,[`usageMetadata`]);o!=null&&F(t,[`usageMetadata`],ao(o));let s=I(e,[`goAway`]);s!=null&&F(t,[`goAway`],s);let c=I(e,[`sessionResumptionUpdate`]);c!=null&&F(t,[`sessionResumptionUpdate`],c);let l=I(e,[`voiceActivityDetectionSignal`]);l!=null&&F(t,[`voiceActivityDetectionSignal`],l);let u=I(e,[`voiceActivity`]);return u!=null&&F(t,[`voiceActivity`],oo(u)),t}function $a(e){let t={},n=I(e,[`mediaResolution`]);n!=null&&F(t,[`mediaResolution`],n);let r=I(e,[`codeExecutionResult`]);r!=null&&F(t,[`codeExecutionResult`],r);let i=I(e,[`executableCode`]);i!=null&&F(t,[`executableCode`],i);let a=I(e,[`fileData`]);a!=null&&F(t,[`fileData`],Ra(a));let o=I(e,[`functionCall`]);o!=null&&F(t,[`functionCall`],za(o));let s=I(e,[`functionResponse`]);s!=null&&F(t,[`functionResponse`],s);let c=I(e,[`inlineData`]);c!=null&&F(t,[`inlineData`],Fa(c));let l=I(e,[`text`]);l!=null&&F(t,[`text`],l);let u=I(e,[`thought`]);u!=null&&F(t,[`thought`],u);let d=I(e,[`thoughtSignature`]);d!=null&&F(t,[`thoughtSignature`],d);let f=I(e,[`videoMetadata`]);f!=null&&F(t,[`videoMetadata`],f);let p=I(e,[`toolCall`]);p!=null&&F(t,[`toolCall`],p);let m=I(e,[`toolResponse`]);m!=null&&F(t,[`toolResponse`],m);let h=I(e,[`partMetadata`]);return h!=null&&F(t,[`partMetadata`],h),t}function eo(e){let t={},n=I(e,[`mediaResolution`]);n!=null&&F(t,[`mediaResolution`],n);let r=I(e,[`codeExecutionResult`]);r!=null&&F(t,[`codeExecutionResult`],r);let i=I(e,[`executableCode`]);i!=null&&F(t,[`executableCode`],i);let a=I(e,[`fileData`]);a!=null&&F(t,[`fileData`],a);let o=I(e,[`functionCall`]);o!=null&&F(t,[`functionCall`],o);let s=I(e,[`functionResponse`]);s!=null&&F(t,[`functionResponse`],s);let c=I(e,[`inlineData`]);c!=null&&F(t,[`inlineData`],c);let l=I(e,[`text`]);l!=null&&F(t,[`text`],l);let u=I(e,[`thought`]);u!=null&&F(t,[`thought`],u);let d=I(e,[`thoughtSignature`]);d!=null&&F(t,[`thoughtSignature`],d);let f=I(e,[`videoMetadata`]);if(f!=null&&F(t,[`videoMetadata`],f),I(e,[`toolCall`])!==void 0)throw Error(`toolCall parameter is not supported in Vertex AI.`);if(I(e,[`toolResponse`])!==void 0)throw Error(`toolResponse parameter is not supported in Vertex AI.`);if(I(e,[`partMetadata`])!==void 0)throw Error(`partMetadata parameter is not supported in Vertex AI.`);return t}function to(e){let t={},n=I(e,[`category`]);if(n!=null&&F(t,[`category`],n),I(e,[`method`])!==void 0)throw Error(`method parameter is not supported in Gemini API.`);let r=I(e,[`threshold`]);return r!=null&&F(t,[`threshold`],r),t}function no(e){let t={},n=I(e,[`handle`]);if(n!=null&&F(t,[`handle`],n),I(e,[`transparent`])!==void 0)throw Error(`transparent parameter is not supported in Gemini API.`);return t}function ro(e){let t={};if(I(e,[`retrieval`])!==void 0)throw Error(`retrieval parameter is not supported in Gemini API.`);let n=I(e,[`computerUse`]);n!=null&&F(t,[`computerUse`],n);let r=I(e,[`fileSearch`]);r!=null&&F(t,[`fileSearch`],r);let i=I(e,[`googleSearch`]);i!=null&&F(t,[`googleSearch`],Ua(i));let a=I(e,[`googleMaps`]);a!=null&&F(t,[`googleMaps`],Ha(a));let o=I(e,[`codeExecution`]);if(o!=null&&F(t,[`codeExecution`],o),I(e,[`enterpriseWebSearch`])!==void 0)throw Error(`enterpriseWebSearch parameter is not supported in Gemini API.`);let s=I(e,[`functionDeclarations`]);if(s!=null){let e=s;Array.isArray(e)&&(e=e.map(e=>e)),F(t,[`functionDeclarations`],e)}let c=I(e,[`googleSearchRetrieval`]);if(c!=null&&F(t,[`googleSearchRetrieval`],c),I(e,[`parallelAiSearch`])!==void 0)throw Error(`parallelAiSearch parameter is not supported in Gemini API.`);let l=I(e,[`urlContext`]);l!=null&&F(t,[`urlContext`],l);let u=I(e,[`mcpServers`]);if(u!=null){let e=u;Array.isArray(e)&&(e=e.map(e=>e)),F(t,[`mcpServers`],e)}return t}function io(e){let t={},n=I(e,[`retrieval`]);n!=null&&F(t,[`retrieval`],n);let r=I(e,[`computerUse`]);if(r!=null&&F(t,[`computerUse`],r),I(e,[`fileSearch`])!==void 0)throw Error(`fileSearch parameter is not supported in Vertex AI.`);let i=I(e,[`googleSearch`]);i!=null&&F(t,[`googleSearch`],i);let a=I(e,[`googleMaps`]);a!=null&&F(t,[`googleMaps`],a);let o=I(e,[`codeExecution`]);o!=null&&F(t,[`codeExecution`],o);let s=I(e,[`enterpriseWebSearch`]);s!=null&&F(t,[`enterpriseWebSearch`],s);let c=I(e,[`functionDeclarations`]);if(c!=null){let e=c;Array.isArray(e)&&(e=e.map(e=>Ba(e))),F(t,[`functionDeclarations`],e)}let l=I(e,[`googleSearchRetrieval`]);l!=null&&F(t,[`googleSearchRetrieval`],l);let u=I(e,[`parallelAiSearch`]);u!=null&&F(t,[`parallelAiSearch`],u);let d=I(e,[`urlContext`]);if(d!=null&&F(t,[`urlContext`],d),I(e,[`mcpServers`])!==void 0)throw Error(`mcpServers parameter is not supported in Vertex AI.`);return t}function ao(e){let t={},n=I(e,[`promptTokenCount`]);n!=null&&F(t,[`promptTokenCount`],n);let r=I(e,[`cachedContentTokenCount`]);r!=null&&F(t,[`cachedContentTokenCount`],r);let i=I(e,[`candidatesTokenCount`]);i!=null&&F(t,[`responseTokenCount`],i);let a=I(e,[`toolUsePromptTokenCount`]);a!=null&&F(t,[`toolUsePromptTokenCount`],a);let o=I(e,[`thoughtsTokenCount`]);o!=null&&F(t,[`thoughtsTokenCount`],o);let s=I(e,[`totalTokenCount`]);s!=null&&F(t,[`totalTokenCount`],s);let c=I(e,[`promptTokensDetails`]);if(c!=null){let e=c;Array.isArray(e)&&(e=e.map(e=>e)),F(t,[`promptTokensDetails`],e)}let l=I(e,[`cacheTokensDetails`]);if(l!=null){let e=l;Array.isArray(e)&&(e=e.map(e=>e)),F(t,[`cacheTokensDetails`],e)}let u=I(e,[`candidatesTokensDetails`]);if(u!=null){let e=u;Array.isArray(e)&&(e=e.map(e=>e)),F(t,[`responseTokensDetails`],e)}let d=I(e,[`toolUsePromptTokensDetails`]);if(d!=null){let e=d;Array.isArray(e)&&(e=e.map(e=>e)),F(t,[`toolUsePromptTokensDetails`],e)}let f=I(e,[`trafficType`]);return f!=null&&F(t,[`trafficType`],f),t}function oo(e){let t={},n=I(e,[`type`]);return n!=null&&F(t,[`voiceActivityType`],n),t}
88
+ /**
89
+ * @license
90
+ * Copyright 2025 Google LLC
91
+ * SPDX-License-Identifier: Apache-2.0
92
+ */
93
+ function so(e,t){let n={},r=I(e,[`apiKey`]);if(r!=null&&F(n,[`apiKey`],r),I(e,[`apiKeyConfig`])!==void 0)throw Error(`apiKeyConfig parameter is not supported in Gemini API.`);if(I(e,[`authType`])!==void 0)throw Error(`authType parameter is not supported in Gemini API.`);if(I(e,[`googleServiceAccountConfig`])!==void 0)throw Error(`googleServiceAccountConfig parameter is not supported in Gemini API.`);if(I(e,[`httpBasicAuthConfig`])!==void 0)throw Error(`httpBasicAuthConfig parameter is not supported in Gemini API.`);if(I(e,[`oauthConfig`])!==void 0)throw Error(`oauthConfig parameter is not supported in Gemini API.`);if(I(e,[`oidcConfig`])!==void 0)throw Error(`oidcConfig parameter is not supported in Gemini API.`);return n}function co(e,t){let n={},r=I(e,[`data`]);if(r!=null&&F(n,[`data`],r),I(e,[`displayName`])!==void 0)throw Error(`displayName parameter is not supported in Gemini API.`);let i=I(e,[`mimeType`]);return i!=null&&F(n,[`mimeType`],i),n}function lo(e,t){let n={},r=I(e,[`content`]);r!=null&&F(n,[`content`],r);let i=I(e,[`citationMetadata`]);i!=null&&F(n,[`citationMetadata`],uo(i));let a=I(e,[`tokenCount`]);a!=null&&F(n,[`tokenCount`],a);let o=I(e,[`finishReason`]);o!=null&&F(n,[`finishReason`],o);let s=I(e,[`groundingMetadata`]);s!=null&&F(n,[`groundingMetadata`],s);let c=I(e,[`avgLogprobs`]);c!=null&&F(n,[`avgLogprobs`],c);let l=I(e,[`index`]);l!=null&&F(n,[`index`],l);let u=I(e,[`logprobsResult`]);u!=null&&F(n,[`logprobsResult`],u);let d=I(e,[`safetyRatings`]);if(d!=null){let e=d;Array.isArray(e)&&(e=e.map(e=>e)),F(n,[`safetyRatings`],e)}let f=I(e,[`urlContextMetadata`]);return f!=null&&F(n,[`urlContextMetadata`],f),n}function uo(e,t){let n={},r=I(e,[`citationSources`]);if(r!=null){let e=r;Array.isArray(e)&&(e=e.map(e=>e)),F(n,[`citations`],e)}return n}function fo(e,t,n){let r={},i=I(t,[`model`]);i!=null&&F(r,[`_url`,`model`],R(e,i));let a=I(t,[`contents`]);if(a!=null){let e=B(a);Array.isArray(e)&&(e=e.map(e=>_o(e))),F(r,[`contents`],e)}return r}function po(e,t){let n={},r=I(e,[`sdkHttpResponse`]);r!=null&&F(n,[`sdkHttpResponse`],r);let i=I(e,[`tokensInfo`]);if(i!=null){let e=i;Array.isArray(e)&&(e=e.map(e=>e)),F(n,[`tokensInfo`],e)}return n}function mo(e,t){let n={},r=I(e,[`values`]);r!=null&&F(n,[`values`],r);let i=I(e,[`statistics`]);return i!=null&&F(n,[`statistics`],ho(i)),n}function ho(e,t){let n={},r=I(e,[`truncated`]);r!=null&&F(n,[`truncated`],r);let i=I(e,[`token_count`]);return i!=null&&F(n,[`tokenCount`],i),n}function go(e,t){let n={},r=I(e,[`parts`]);if(r!=null){let e=r;Array.isArray(e)&&(e=e.map(e=>Fs(e))),F(n,[`parts`],e)}let i=I(e,[`role`]);return i!=null&&F(n,[`role`],i),n}function _o(e,t){let n={},r=I(e,[`parts`]);if(r!=null){let e=r;Array.isArray(e)&&(e=e.map(e=>Is(e))),F(n,[`parts`],e)}let i=I(e,[`role`]);return i!=null&&F(n,[`role`],i),n}function vo(e,t){let n={},r=I(e,[`controlType`]);r!=null&&F(n,[`controlType`],r);let i=I(e,[`enableControlImageComputation`]);return i!=null&&F(n,[`computeControl`],i),n}function yo(e,t){let n={};if(I(e,[`systemInstruction`])!==void 0)throw Error(`systemInstruction parameter is not supported in Gemini API.`);if(I(e,[`tools`])!==void 0)throw Error(`tools parameter is not supported in Gemini API.`);if(I(e,[`generationConfig`])!==void 0)throw Error(`generationConfig parameter is not supported in Gemini API.`);return n}function bo(e,t,n){let r={},i=I(e,[`systemInstruction`]);t!==void 0&&i!=null&&F(t,[`systemInstruction`],_o(z(i)));let a=I(e,[`tools`]);if(t!==void 0&&a!=null){let e=a;Array.isArray(e)&&(e=e.map(e=>ec(e))),F(t,[`tools`],e)}let o=I(e,[`generationConfig`]);return t!==void 0&&o!=null&&F(t,[`generationConfig`],gs(o)),r}function xo(e,t,n){let r={},i=I(t,[`model`]);i!=null&&F(r,[`_url`,`model`],R(e,i));let a=I(t,[`contents`]);if(a!=null){let e=B(a);Array.isArray(e)&&(e=e.map(e=>go(e))),F(r,[`contents`],e)}let o=I(t,[`config`]);return o!=null&&yo(o),r}function So(e,t,n){let r={},i=I(t,[`model`]);i!=null&&F(r,[`_url`,`model`],R(e,i));let a=I(t,[`contents`]);if(a!=null){let e=B(a);Array.isArray(e)&&(e=e.map(e=>_o(e))),F(r,[`contents`],e)}let o=I(t,[`config`]);return o!=null&&bo(o,r),r}function Co(e,t){let n={},r=I(e,[`sdkHttpResponse`]);r!=null&&F(n,[`sdkHttpResponse`],r);let i=I(e,[`totalTokens`]);i!=null&&F(n,[`totalTokens`],i);let a=I(e,[`cachedContentTokenCount`]);return a!=null&&F(n,[`cachedContentTokenCount`],a),n}function wo(e,t){let n={},r=I(e,[`sdkHttpResponse`]);r!=null&&F(n,[`sdkHttpResponse`],r);let i=I(e,[`totalTokens`]);return i!=null&&F(n,[`totalTokens`],i),n}function To(e,t,n){let r={},i=I(t,[`model`]);return i!=null&&F(r,[`_url`,`name`],R(e,i)),r}function Eo(e,t,n){let r={},i=I(t,[`model`]);return i!=null&&F(r,[`_url`,`name`],R(e,i)),r}function Do(e,t){let n={},r=I(e,[`sdkHttpResponse`]);return r!=null&&F(n,[`sdkHttpResponse`],r),n}function Oo(e,t){let n={},r=I(e,[`sdkHttpResponse`]);return r!=null&&F(n,[`sdkHttpResponse`],r),n}function ko(e,t,n){let r={},i=I(e,[`outputGcsUri`]);t!==void 0&&i!=null&&F(t,[`parameters`,`storageUri`],i);let a=I(e,[`negativePrompt`]);t!==void 0&&a!=null&&F(t,[`parameters`,`negativePrompt`],a);let o=I(e,[`numberOfImages`]);t!==void 0&&o!=null&&F(t,[`parameters`,`sampleCount`],o);let s=I(e,[`aspectRatio`]);t!==void 0&&s!=null&&F(t,[`parameters`,`aspectRatio`],s);let c=I(e,[`guidanceScale`]);t!==void 0&&c!=null&&F(t,[`parameters`,`guidanceScale`],c);let l=I(e,[`seed`]);t!==void 0&&l!=null&&F(t,[`parameters`,`seed`],l);let u=I(e,[`safetyFilterLevel`]);t!==void 0&&u!=null&&F(t,[`parameters`,`safetySetting`],u);let d=I(e,[`personGeneration`]);t!==void 0&&d!=null&&F(t,[`parameters`,`personGeneration`],d);let f=I(e,[`includeSafetyAttributes`]);t!==void 0&&f!=null&&F(t,[`parameters`,`includeSafetyAttributes`],f);let p=I(e,[`includeRaiReason`]);t!==void 0&&p!=null&&F(t,[`parameters`,`includeRaiReason`],p);let m=I(e,[`language`]);t!==void 0&&m!=null&&F(t,[`parameters`,`language`],m);let h=I(e,[`outputMimeType`]);t!==void 0&&h!=null&&F(t,[`parameters`,`outputOptions`,`mimeType`],h);let g=I(e,[`outputCompressionQuality`]);t!==void 0&&g!=null&&F(t,[`parameters`,`outputOptions`,`compressionQuality`],g);let _=I(e,[`addWatermark`]);t!==void 0&&_!=null&&F(t,[`parameters`,`addWatermark`],_);let v=I(e,[`labels`]);t!==void 0&&v!=null&&F(t,[`labels`],v);let y=I(e,[`editMode`]);t!==void 0&&y!=null&&F(t,[`parameters`,`editMode`],y);let b=I(e,[`baseSteps`]);return t!==void 0&&b!=null&&F(t,[`parameters`,`editConfig`,`baseSteps`],b),r}function Ao(e,t,n){let r={},i=I(t,[`model`]);i!=null&&F(r,[`_url`,`model`],R(e,i));let a=I(t,[`prompt`]);a!=null&&F(r,[`instances[0]`,`prompt`],a);let o=I(t,[`referenceImages`]);if(o!=null){let e=o;Array.isArray(e)&&(e=e.map(e=>Hs(e))),F(r,[`instances[0]`,`referenceImages`],e)}let s=I(t,[`config`]);return s!=null&&ko(s,r),r}function jo(e,t){let n={},r=I(e,[`sdkHttpResponse`]);r!=null&&F(n,[`sdkHttpResponse`],r);let i=I(e,[`predictions`]);if(i!=null){let e=i;Array.isArray(e)&&(e=e.map(e=>fs(e))),F(n,[`generatedImages`],e)}return n}function Mo(e,t,n){let r={},i=I(e,[`taskType`]);t!==void 0&&i!=null&&F(t,[`requests[]`,`taskType`],i);let a=I(e,[`title`]);t!==void 0&&a!=null&&F(t,[`requests[]`,`title`],a);let o=I(e,[`outputDimensionality`]);if(t!==void 0&&o!=null&&F(t,[`requests[]`,`outputDimensionality`],o),I(e,[`mimeType`])!==void 0)throw Error(`mimeType parameter is not supported in Gemini API.`);if(I(e,[`autoTruncate`])!==void 0)throw Error(`autoTruncate parameter is not supported in Gemini API.`);if(I(e,[`documentOcr`])!==void 0)throw Error(`documentOcr parameter is not supported in Gemini API.`);if(I(e,[`audioTrackExtraction`])!==void 0)throw Error(`audioTrackExtraction parameter is not supported in Gemini API.`);return r}function No(e,t,n){let r={},i=I(n,[`embeddingApiType`]);if(i===void 0&&(i=`PREDICT`),i===`PREDICT`){let n=I(e,[`taskType`]);t!==void 0&&n!=null&&F(t,[`instances[]`,`task_type`],n)}else if(i===`EMBED_CONTENT`){let n=I(e,[`taskType`]);t!==void 0&&n!=null&&F(t,[`embedContentConfig`,`taskType`],n)}let a=I(n,[`embeddingApiType`]);if(a===void 0&&(a=`PREDICT`),a===`PREDICT`){let n=I(e,[`title`]);t!==void 0&&n!=null&&F(t,[`instances[]`,`title`],n)}else if(a===`EMBED_CONTENT`){let n=I(e,[`title`]);t!==void 0&&n!=null&&F(t,[`embedContentConfig`,`title`],n)}let o=I(n,[`embeddingApiType`]);if(o===void 0&&(o=`PREDICT`),o===`PREDICT`){let n=I(e,[`outputDimensionality`]);t!==void 0&&n!=null&&F(t,[`parameters`,`outputDimensionality`],n)}else if(o===`EMBED_CONTENT`){let n=I(e,[`outputDimensionality`]);t!==void 0&&n!=null&&F(t,[`embedContentConfig`,`outputDimensionality`],n)}let s=I(n,[`embeddingApiType`]);if(s===void 0&&(s=`PREDICT`),s===`PREDICT`){let n=I(e,[`mimeType`]);t!==void 0&&n!=null&&F(t,[`instances[]`,`mimeType`],n)}let c=I(n,[`embeddingApiType`]);if(c===void 0&&(c=`PREDICT`),c===`PREDICT`){let n=I(e,[`autoTruncate`]);t!==void 0&&n!=null&&F(t,[`parameters`,`autoTruncate`],n)}else if(c===`EMBED_CONTENT`){let n=I(e,[`autoTruncate`]);t!==void 0&&n!=null&&F(t,[`embedContentConfig`,`autoTruncate`],n)}let l=I(n,[`embeddingApiType`]);if(l===void 0&&(l=`PREDICT`),l===`EMBED_CONTENT`){let n=I(e,[`documentOcr`]);t!==void 0&&n!=null&&F(t,[`embedContentConfig`,`documentOcr`],n)}let u=I(n,[`embeddingApiType`]);if(u===void 0&&(u=`PREDICT`),u===`EMBED_CONTENT`){let n=I(e,[`audioTrackExtraction`]);t!==void 0&&n!=null&&F(t,[`embedContentConfig`,`audioTrackExtraction`],n)}return r}function Po(e,t,n){let r={},i=I(t,[`model`]);i!=null&&F(r,[`_url`,`model`],R(e,i));let a=I(t,[`contents`]);if(a!=null){let t=cr(e,a);Array.isArray(t)&&(t=t.map(e=>e)),F(r,[`requests[]`,`content`],t)}let o=I(t,[`content`]);o!=null&&go(z(o));let s=I(t,[`config`]);s!=null&&Mo(s,r);let c=I(t,[`model`]);return c!==void 0&&F(r,[`requests[]`,`model`],R(e,c)),r}function Fo(e,t,n){let r={},i=I(t,[`model`]);i!=null&&F(r,[`_url`,`model`],R(e,i));let a=I(n,[`embeddingApiType`]);if(a===void 0&&(a=`PREDICT`),a===`PREDICT`){let n=I(t,[`contents`]);if(n!=null){let t=cr(e,n);Array.isArray(t)&&(t=t.map(e=>e)),F(r,[`instances[]`,`content`],t)}}let o=I(n,[`embeddingApiType`]);if(o===void 0&&(o=`PREDICT`),o===`EMBED_CONTENT`){let e=I(t,[`content`]);e!=null&&F(r,[`content`],_o(z(e)))}let s=I(t,[`config`]);return s!=null&&No(s,r,n),r}function Io(e,t){let n={},r=I(e,[`sdkHttpResponse`]);r!=null&&F(n,[`sdkHttpResponse`],r);let i=I(e,[`embeddings`]);if(i!=null){let e=i;Array.isArray(e)&&(e=e.map(e=>e)),F(n,[`embeddings`],e)}let a=I(e,[`metadata`]);return a!=null&&F(n,[`metadata`],a),n}function Lo(e,t){let n={},r=I(e,[`sdkHttpResponse`]);r!=null&&F(n,[`sdkHttpResponse`],r);let i=I(e,[`predictions[]`,`embeddings`]);if(i!=null){let e=i;Array.isArray(e)&&(e=e.map(e=>mo(e))),F(n,[`embeddings`],e)}let a=I(e,[`metadata`]);if(a!=null&&F(n,[`metadata`],a),t&&I(t,[`embeddingApiType`])===`EMBED_CONTENT`){let t=I(e,[`embedding`]),r=I(e,[`usageMetadata`]),i=I(e,[`truncated`]);if(t){let e={};r&&r.promptTokenCount&&(e.tokenCount=r.promptTokenCount),i&&(e.truncated=i),t.statistics=e,F(n,[`embeddings`],[t])}}return n}function Ro(e,t){let n={},r=I(e,[`endpoint`]);r!=null&&F(n,[`name`],r);let i=I(e,[`deployedModelId`]);return i!=null&&F(n,[`deployedModelId`],i),n}function zo(e,t){let n={};if(I(e,[`displayName`])!==void 0)throw Error(`displayName parameter is not supported in Gemini API.`);let r=I(e,[`fileUri`]);r!=null&&F(n,[`fileUri`],r);let i=I(e,[`mimeType`]);return i!=null&&F(n,[`mimeType`],i),n}function Bo(e,t){let n={},r=I(e,[`id`]);r!=null&&F(n,[`id`],r);let i=I(e,[`args`]);i!=null&&F(n,[`args`],i);let a=I(e,[`name`]);if(a!=null&&F(n,[`name`],a),I(e,[`partialArgs`])!==void 0)throw Error(`partialArgs parameter is not supported in Gemini API.`);if(I(e,[`willContinue`])!==void 0)throw Error(`willContinue parameter is not supported in Gemini API.`);return n}function Vo(e,t){let n={},r=I(e,[`allowedFunctionNames`]);r!=null&&F(n,[`allowedFunctionNames`],r);let i=I(e,[`mode`]);if(i!=null&&F(n,[`mode`],i),I(e,[`streamFunctionCallArguments`])!==void 0)throw Error(`streamFunctionCallArguments parameter is not supported in Gemini API.`);return n}function Ho(e,t){let n={},r=I(e,[`description`]);r!=null&&F(n,[`description`],r);let i=I(e,[`name`]);i!=null&&F(n,[`name`],i);let a=I(e,[`parameters`]);a!=null&&F(n,[`parameters`],a);let o=I(e,[`parametersJsonSchema`]);o!=null&&F(n,[`parametersJsonSchema`],o);let s=I(e,[`response`]);s!=null&&F(n,[`response`],s);let c=I(e,[`responseJsonSchema`]);if(c!=null&&F(n,[`responseJsonSchema`],c),I(e,[`behavior`])!==void 0)throw Error(`behavior parameter is not supported in Vertex AI.`);return n}function Uo(e,t,n,r){let i={},a=I(t,[`systemInstruction`]);n!==void 0&&a!=null&&F(n,[`systemInstruction`],go(z(a)));let o=I(t,[`temperature`]);o!=null&&F(i,[`temperature`],o);let s=I(t,[`topP`]);s!=null&&F(i,[`topP`],s);let c=I(t,[`topK`]);c!=null&&F(i,[`topK`],c);let l=I(t,[`candidateCount`]);l!=null&&F(i,[`candidateCount`],l);let u=I(t,[`maxOutputTokens`]);u!=null&&F(i,[`maxOutputTokens`],u);let d=I(t,[`stopSequences`]);d!=null&&F(i,[`stopSequences`],d);let f=I(t,[`responseLogprobs`]);f!=null&&F(i,[`responseLogprobs`],f);let p=I(t,[`logprobs`]);p!=null&&F(i,[`logprobs`],p);let m=I(t,[`presencePenalty`]);m!=null&&F(i,[`presencePenalty`],m);let h=I(t,[`frequencyPenalty`]);h!=null&&F(i,[`frequencyPenalty`],h);let g=I(t,[`seed`]);g!=null&&F(i,[`seed`],g);let _=I(t,[`responseMimeType`]);_!=null&&F(i,[`responseMimeType`],_);let v=I(t,[`responseSchema`]);v!=null&&F(i,[`responseSchema`],dr(v));let y=I(t,[`responseJsonSchema`]);if(y!=null&&F(i,[`responseJsonSchema`],y),I(t,[`routingConfig`])!==void 0)throw Error(`routingConfig parameter is not supported in Gemini API.`);if(I(t,[`modelSelectionConfig`])!==void 0)throw Error(`modelSelectionConfig parameter is not supported in Gemini API.`);let b=I(t,[`safetySettings`]);if(n!==void 0&&b!=null){let e=b;Array.isArray(e)&&(e=e.map(e=>Gs(e))),F(n,[`safetySettings`],e)}let x=I(t,[`tools`]);if(n!==void 0&&x!=null){let e=hr(x);Array.isArray(e)&&(e=e.map(e=>$s(mr(e)))),F(n,[`tools`],e)}let S=I(t,[`toolConfig`]);if(n!==void 0&&S!=null&&F(n,[`toolConfig`],Zs(S)),I(t,[`labels`])!==void 0)throw Error(`labels parameter is not supported in Gemini API.`);let C=I(t,[`cachedContent`]);n!==void 0&&C!=null&&F(n,[`cachedContent`],V(e,C));let w=I(t,[`responseModalities`]);w!=null&&F(i,[`responseModalities`],w);let T=I(t,[`mediaResolution`]);T!=null&&F(i,[`mediaResolution`],T);let E=I(t,[`speechConfig`]);if(E!=null&&F(i,[`speechConfig`],fr(E)),I(t,[`audioTimestamp`])!==void 0)throw Error(`audioTimestamp parameter is not supported in Gemini API.`);let D=I(t,[`thinkingConfig`]);D!=null&&F(i,[`thinkingConfig`],D);let O=I(t,[`imageConfig`]);O!=null&&F(i,[`imageConfig`],xs(O));let k=I(t,[`enableEnhancedCivicAnswers`]);if(k!=null&&F(i,[`enableEnhancedCivicAnswers`],k),I(t,[`modelArmorConfig`])!==void 0)throw Error(`modelArmorConfig parameter is not supported in Gemini API.`);let ee=I(t,[`serviceTier`]);return n!==void 0&&ee!=null&&F(n,[`serviceTier`],ee),i}function Wo(e,t,n,r){let i={},a=I(t,[`systemInstruction`]);n!==void 0&&a!=null&&F(n,[`systemInstruction`],_o(z(a)));let o=I(t,[`temperature`]);o!=null&&F(i,[`temperature`],o);let s=I(t,[`topP`]);s!=null&&F(i,[`topP`],s);let c=I(t,[`topK`]);c!=null&&F(i,[`topK`],c);let l=I(t,[`candidateCount`]);l!=null&&F(i,[`candidateCount`],l);let u=I(t,[`maxOutputTokens`]);u!=null&&F(i,[`maxOutputTokens`],u);let d=I(t,[`stopSequences`]);d!=null&&F(i,[`stopSequences`],d);let f=I(t,[`responseLogprobs`]);f!=null&&F(i,[`responseLogprobs`],f);let p=I(t,[`logprobs`]);p!=null&&F(i,[`logprobs`],p);let m=I(t,[`presencePenalty`]);m!=null&&F(i,[`presencePenalty`],m);let h=I(t,[`frequencyPenalty`]);h!=null&&F(i,[`frequencyPenalty`],h);let g=I(t,[`seed`]);g!=null&&F(i,[`seed`],g);let _=I(t,[`responseMimeType`]);_!=null&&F(i,[`responseMimeType`],_);let v=I(t,[`responseSchema`]);v!=null&&F(i,[`responseSchema`],dr(v));let y=I(t,[`responseJsonSchema`]);y!=null&&F(i,[`responseJsonSchema`],y);let b=I(t,[`routingConfig`]);b!=null&&F(i,[`routingConfig`],b);let x=I(t,[`modelSelectionConfig`]);x!=null&&F(i,[`modelConfig`],x);let S=I(t,[`safetySettings`]);if(n!==void 0&&S!=null){let e=S;Array.isArray(e)&&(e=e.map(e=>e)),F(n,[`safetySettings`],e)}let C=I(t,[`tools`]);if(n!==void 0&&C!=null){let e=hr(C);Array.isArray(e)&&(e=e.map(e=>ec(mr(e)))),F(n,[`tools`],e)}let w=I(t,[`toolConfig`]);n!==void 0&&w!=null&&F(n,[`toolConfig`],Qs(w));let T=I(t,[`labels`]);n!==void 0&&T!=null&&F(n,[`labels`],T);let E=I(t,[`cachedContent`]);n!==void 0&&E!=null&&F(n,[`cachedContent`],V(e,E));let D=I(t,[`responseModalities`]);D!=null&&F(i,[`responseModalities`],D);let O=I(t,[`mediaResolution`]);O!=null&&F(i,[`mediaResolution`],O);let k=I(t,[`speechConfig`]);k!=null&&F(i,[`speechConfig`],fr(k));let ee=I(t,[`audioTimestamp`]);ee!=null&&F(i,[`audioTimestamp`],ee);let te=I(t,[`thinkingConfig`]);te!=null&&F(i,[`thinkingConfig`],te);let A=I(t,[`imageConfig`]);if(A!=null&&F(i,[`imageConfig`],Ss(A)),I(t,[`enableEnhancedCivicAnswers`])!==void 0)throw Error(`enableEnhancedCivicAnswers parameter is not supported in Vertex AI.`);let ne=I(t,[`modelArmorConfig`]);n!==void 0&&ne!=null&&F(n,[`modelArmorConfig`],ne);let re=I(t,[`serviceTier`]);return n!==void 0&&re!=null&&F(n,[`serviceTier`],re),i}function Go(e,t,n){let r={},i=I(t,[`model`]);i!=null&&F(r,[`_url`,`model`],R(e,i));let a=I(t,[`contents`]);if(a!=null){let e=B(a);Array.isArray(e)&&(e=e.map(e=>go(e))),F(r,[`contents`],e)}let o=I(t,[`config`]);return o!=null&&F(r,[`generationConfig`],Uo(e,o,r)),r}function Ko(e,t,n){let r={},i=I(t,[`model`]);i!=null&&F(r,[`_url`,`model`],R(e,i));let a=I(t,[`contents`]);if(a!=null){let e=B(a);Array.isArray(e)&&(e=e.map(e=>_o(e))),F(r,[`contents`],e)}let o=I(t,[`config`]);return o!=null&&F(r,[`generationConfig`],Wo(e,o,r)),r}function qo(e,t){let n={},r=I(e,[`sdkHttpResponse`]);r!=null&&F(n,[`sdkHttpResponse`],r);let i=I(e,[`candidates`]);if(i!=null){let e=i;Array.isArray(e)&&(e=e.map(e=>lo(e))),F(n,[`candidates`],e)}let a=I(e,[`modelVersion`]);a!=null&&F(n,[`modelVersion`],a);let o=I(e,[`promptFeedback`]);o!=null&&F(n,[`promptFeedback`],o);let s=I(e,[`responseId`]);s!=null&&F(n,[`responseId`],s);let c=I(e,[`usageMetadata`]);c!=null&&F(n,[`usageMetadata`],c);let l=I(e,[`modelStatus`]);return l!=null&&F(n,[`modelStatus`],l),n}function Jo(e,t){let n={},r=I(e,[`sdkHttpResponse`]);r!=null&&F(n,[`sdkHttpResponse`],r);let i=I(e,[`candidates`]);if(i!=null){let e=i;Array.isArray(e)&&(e=e.map(e=>e)),F(n,[`candidates`],e)}let a=I(e,[`createTime`]);a!=null&&F(n,[`createTime`],a);let o=I(e,[`modelVersion`]);o!=null&&F(n,[`modelVersion`],o);let s=I(e,[`promptFeedback`]);s!=null&&F(n,[`promptFeedback`],s);let c=I(e,[`responseId`]);c!=null&&F(n,[`responseId`],c);let l=I(e,[`usageMetadata`]);return l!=null&&F(n,[`usageMetadata`],l),n}function Yo(e,t,n){let r={};if(I(e,[`outputGcsUri`])!==void 0)throw Error(`outputGcsUri parameter is not supported in Gemini API.`);if(I(e,[`negativePrompt`])!==void 0)throw Error(`negativePrompt parameter is not supported in Gemini API.`);let i=I(e,[`numberOfImages`]);t!==void 0&&i!=null&&F(t,[`parameters`,`sampleCount`],i);let a=I(e,[`aspectRatio`]);t!==void 0&&a!=null&&F(t,[`parameters`,`aspectRatio`],a);let o=I(e,[`guidanceScale`]);if(t!==void 0&&o!=null&&F(t,[`parameters`,`guidanceScale`],o),I(e,[`seed`])!==void 0)throw Error(`seed parameter is not supported in Gemini API.`);let s=I(e,[`safetyFilterLevel`]);t!==void 0&&s!=null&&F(t,[`parameters`,`safetySetting`],s);let c=I(e,[`personGeneration`]);t!==void 0&&c!=null&&F(t,[`parameters`,`personGeneration`],c);let l=I(e,[`includeSafetyAttributes`]);t!==void 0&&l!=null&&F(t,[`parameters`,`includeSafetyAttributes`],l);let u=I(e,[`includeRaiReason`]);t!==void 0&&u!=null&&F(t,[`parameters`,`includeRaiReason`],u);let d=I(e,[`language`]);t!==void 0&&d!=null&&F(t,[`parameters`,`language`],d);let f=I(e,[`outputMimeType`]);t!==void 0&&f!=null&&F(t,[`parameters`,`outputOptions`,`mimeType`],f);let p=I(e,[`outputCompressionQuality`]);if(t!==void 0&&p!=null&&F(t,[`parameters`,`outputOptions`,`compressionQuality`],p),I(e,[`addWatermark`])!==void 0)throw Error(`addWatermark parameter is not supported in Gemini API.`);if(I(e,[`labels`])!==void 0)throw Error(`labels parameter is not supported in Gemini API.`);let m=I(e,[`imageSize`]);if(t!==void 0&&m!=null&&F(t,[`parameters`,`sampleImageSize`],m),I(e,[`enhancePrompt`])!==void 0)throw Error(`enhancePrompt parameter is not supported in Gemini API.`);return r}function Xo(e,t,n){let r={},i=I(e,[`outputGcsUri`]);t!==void 0&&i!=null&&F(t,[`parameters`,`storageUri`],i);let a=I(e,[`negativePrompt`]);t!==void 0&&a!=null&&F(t,[`parameters`,`negativePrompt`],a);let o=I(e,[`numberOfImages`]);t!==void 0&&o!=null&&F(t,[`parameters`,`sampleCount`],o);let s=I(e,[`aspectRatio`]);t!==void 0&&s!=null&&F(t,[`parameters`,`aspectRatio`],s);let c=I(e,[`guidanceScale`]);t!==void 0&&c!=null&&F(t,[`parameters`,`guidanceScale`],c);let l=I(e,[`seed`]);t!==void 0&&l!=null&&F(t,[`parameters`,`seed`],l);let u=I(e,[`safetyFilterLevel`]);t!==void 0&&u!=null&&F(t,[`parameters`,`safetySetting`],u);let d=I(e,[`personGeneration`]);t!==void 0&&d!=null&&F(t,[`parameters`,`personGeneration`],d);let f=I(e,[`includeSafetyAttributes`]);t!==void 0&&f!=null&&F(t,[`parameters`,`includeSafetyAttributes`],f);let p=I(e,[`includeRaiReason`]);t!==void 0&&p!=null&&F(t,[`parameters`,`includeRaiReason`],p);let m=I(e,[`language`]);t!==void 0&&m!=null&&F(t,[`parameters`,`language`],m);let h=I(e,[`outputMimeType`]);t!==void 0&&h!=null&&F(t,[`parameters`,`outputOptions`,`mimeType`],h);let g=I(e,[`outputCompressionQuality`]);t!==void 0&&g!=null&&F(t,[`parameters`,`outputOptions`,`compressionQuality`],g);let _=I(e,[`addWatermark`]);t!==void 0&&_!=null&&F(t,[`parameters`,`addWatermark`],_);let v=I(e,[`labels`]);t!==void 0&&v!=null&&F(t,[`labels`],v);let y=I(e,[`imageSize`]);t!==void 0&&y!=null&&F(t,[`parameters`,`sampleImageSize`],y);let b=I(e,[`enhancePrompt`]);return t!==void 0&&b!=null&&F(t,[`parameters`,`enhancePrompt`],b),r}function Zo(e,t,n){let r={},i=I(t,[`model`]);i!=null&&F(r,[`_url`,`model`],R(e,i));let a=I(t,[`prompt`]);a!=null&&F(r,[`instances[0]`,`prompt`],a);let o=I(t,[`config`]);return o!=null&&Yo(o,r),r}function Qo(e,t,n){let r={},i=I(t,[`model`]);i!=null&&F(r,[`_url`,`model`],R(e,i));let a=I(t,[`prompt`]);a!=null&&F(r,[`instances[0]`,`prompt`],a);let o=I(t,[`config`]);return o!=null&&Xo(o,r),r}function $o(e,t){let n={},r=I(e,[`sdkHttpResponse`]);r!=null&&F(n,[`sdkHttpResponse`],r);let i=I(e,[`predictions`]);if(i!=null){let e=i;Array.isArray(e)&&(e=e.map(e=>ds(e))),F(n,[`generatedImages`],e)}let a=I(e,[`positivePromptSafetyAttributes`]);return a!=null&&F(n,[`positivePromptSafetyAttributes`],Us(a)),n}function es(e,t){let n={},r=I(e,[`sdkHttpResponse`]);r!=null&&F(n,[`sdkHttpResponse`],r);let i=I(e,[`predictions`]);if(i!=null){let e=i;Array.isArray(e)&&(e=e.map(e=>fs(e))),F(n,[`generatedImages`],e)}let a=I(e,[`positivePromptSafetyAttributes`]);return a!=null&&F(n,[`positivePromptSafetyAttributes`],Ws(a)),n}function ts(e,t,n){let r={},i=I(e,[`numberOfVideos`]);if(t!==void 0&&i!=null&&F(t,[`parameters`,`sampleCount`],i),I(e,[`outputGcsUri`])!==void 0)throw Error(`outputGcsUri parameter is not supported in Gemini API.`);if(I(e,[`fps`])!==void 0)throw Error(`fps parameter is not supported in Gemini API.`);let a=I(e,[`durationSeconds`]);if(t!==void 0&&a!=null&&F(t,[`parameters`,`durationSeconds`],a),I(e,[`seed`])!==void 0)throw Error(`seed parameter is not supported in Gemini API.`);let o=I(e,[`aspectRatio`]);t!==void 0&&o!=null&&F(t,[`parameters`,`aspectRatio`],o);let s=I(e,[`resolution`]);t!==void 0&&s!=null&&F(t,[`parameters`,`resolution`],s);let c=I(e,[`personGeneration`]);if(t!==void 0&&c!=null&&F(t,[`parameters`,`personGeneration`],c),I(e,[`pubsubTopic`])!==void 0)throw Error(`pubsubTopic parameter is not supported in Gemini API.`);let l=I(e,[`negativePrompt`]);t!==void 0&&l!=null&&F(t,[`parameters`,`negativePrompt`],l);let u=I(e,[`enhancePrompt`]);if(t!==void 0&&u!=null&&F(t,[`parameters`,`enhancePrompt`],u),I(e,[`generateAudio`])!==void 0)throw Error(`generateAudio parameter is not supported in Gemini API.`);let d=I(e,[`lastFrame`]);t!==void 0&&d!=null&&F(t,[`instances[0]`,`lastFrame`],Ts(d));let f=I(e,[`referenceImages`]);if(t!==void 0&&f!=null){let e=f;Array.isArray(e)&&(e=e.map(e=>pc(e))),F(t,[`instances[0]`,`referenceImages`],e)}if(I(e,[`mask`])!==void 0)throw Error(`mask parameter is not supported in Gemini API.`);if(I(e,[`compressionQuality`])!==void 0)throw Error(`compressionQuality parameter is not supported in Gemini API.`);if(I(e,[`labels`])!==void 0)throw Error(`labels parameter is not supported in Gemini API.`);let p=I(e,[`webhookConfig`]);return t!==void 0&&p!=null&&F(t,[`webhookConfig`],p),r}function ns(e,t,n){let r={},i=I(e,[`numberOfVideos`]);t!==void 0&&i!=null&&F(t,[`parameters`,`sampleCount`],i);let a=I(e,[`outputGcsUri`]);t!==void 0&&a!=null&&F(t,[`parameters`,`storageUri`],a);let o=I(e,[`fps`]);t!==void 0&&o!=null&&F(t,[`parameters`,`fps`],o);let s=I(e,[`durationSeconds`]);t!==void 0&&s!=null&&F(t,[`parameters`,`durationSeconds`],s);let c=I(e,[`seed`]);t!==void 0&&c!=null&&F(t,[`parameters`,`seed`],c);let l=I(e,[`aspectRatio`]);t!==void 0&&l!=null&&F(t,[`parameters`,`aspectRatio`],l);let u=I(e,[`resolution`]);t!==void 0&&u!=null&&F(t,[`parameters`,`resolution`],u);let d=I(e,[`personGeneration`]);t!==void 0&&d!=null&&F(t,[`parameters`,`personGeneration`],d);let f=I(e,[`pubsubTopic`]);t!==void 0&&f!=null&&F(t,[`parameters`,`pubsubTopic`],f);let p=I(e,[`negativePrompt`]);t!==void 0&&p!=null&&F(t,[`parameters`,`negativePrompt`],p);let m=I(e,[`enhancePrompt`]);t!==void 0&&m!=null&&F(t,[`parameters`,`enhancePrompt`],m);let h=I(e,[`generateAudio`]);t!==void 0&&h!=null&&F(t,[`parameters`,`generateAudio`],h);let g=I(e,[`lastFrame`]);t!==void 0&&g!=null&&F(t,[`instances[0]`,`lastFrame`],J(g));let _=I(e,[`referenceImages`]);if(t!==void 0&&_!=null){let e=_;Array.isArray(e)&&(e=e.map(e=>mc(e))),F(t,[`instances[0]`,`referenceImages`],e)}let v=I(e,[`mask`]);t!==void 0&&v!=null&&F(t,[`instances[0]`,`mask`],fc(v));let y=I(e,[`compressionQuality`]);t!==void 0&&y!=null&&F(t,[`parameters`,`compressionQuality`],y);let b=I(e,[`labels`]);if(t!==void 0&&b!=null&&F(t,[`labels`],b),I(e,[`webhookConfig`])!==void 0)throw Error(`webhookConfig parameter is not supported in Vertex AI.`);return r}function rs(e,t){let n={},r=I(e,[`name`]);r!=null&&F(n,[`name`],r);let i=I(e,[`metadata`]);i!=null&&F(n,[`metadata`],i);let a=I(e,[`done`]);a!=null&&F(n,[`done`],a);let o=I(e,[`error`]);o!=null&&F(n,[`error`],o);let s=I(e,[`response`,`generateVideoResponse`]);return s!=null&&F(n,[`response`],ss(s)),n}function is(e,t){let n={},r=I(e,[`name`]);r!=null&&F(n,[`name`],r);let i=I(e,[`metadata`]);i!=null&&F(n,[`metadata`],i);let a=I(e,[`done`]);a!=null&&F(n,[`done`],a);let o=I(e,[`error`]);o!=null&&F(n,[`error`],o);let s=I(e,[`response`]);return s!=null&&F(n,[`response`],cs(s)),n}function as(e,t,n){let r={},i=I(t,[`model`]);i!=null&&F(r,[`_url`,`model`],R(e,i));let a=I(t,[`prompt`]);a!=null&&F(r,[`instances[0]`,`prompt`],a);let o=I(t,[`image`]);o!=null&&F(r,[`instances[0]`,`image`],Ts(o));let s=I(t,[`video`]);s!=null&&F(r,[`instances[0]`,`video`],hc(s));let c=I(t,[`source`]);c!=null&&ls(c,r);let l=I(t,[`config`]);return l!=null&&ts(l,r),r}function os(e,t,n){let r={},i=I(t,[`model`]);i!=null&&F(r,[`_url`,`model`],R(e,i));let a=I(t,[`prompt`]);a!=null&&F(r,[`instances[0]`,`prompt`],a);let o=I(t,[`image`]);o!=null&&F(r,[`instances[0]`,`image`],J(o));let s=I(t,[`video`]);s!=null&&F(r,[`instances[0]`,`video`],gc(s));let c=I(t,[`source`]);c!=null&&us(c,r);let l=I(t,[`config`]);return l!=null&&ns(l,r),r}function ss(e,t){let n={},r=I(e,[`generatedSamples`]);if(r!=null){let e=r;Array.isArray(e)&&(e=e.map(e=>ms(e))),F(n,[`generatedVideos`],e)}let i=I(e,[`raiMediaFilteredCount`]);i!=null&&F(n,[`raiMediaFilteredCount`],i);let a=I(e,[`raiMediaFilteredReasons`]);return a!=null&&F(n,[`raiMediaFilteredReasons`],a),n}function cs(e,t){let n={},r=I(e,[`videos`]);if(r!=null){let e=r;Array.isArray(e)&&(e=e.map(e=>hs(e))),F(n,[`generatedVideos`],e)}let i=I(e,[`raiMediaFilteredCount`]);i!=null&&F(n,[`raiMediaFilteredCount`],i);let a=I(e,[`raiMediaFilteredReasons`]);return a!=null&&F(n,[`raiMediaFilteredReasons`],a),n}function ls(e,t,n){let r={},i=I(e,[`prompt`]);t!==void 0&&i!=null&&F(t,[`instances[0]`,`prompt`],i);let a=I(e,[`image`]);t!==void 0&&a!=null&&F(t,[`instances[0]`,`image`],Ts(a));let o=I(e,[`video`]);return t!==void 0&&o!=null&&F(t,[`instances[0]`,`video`],hc(o)),r}function us(e,t,n){let r={},i=I(e,[`prompt`]);t!==void 0&&i!=null&&F(t,[`instances[0]`,`prompt`],i);let a=I(e,[`image`]);t!==void 0&&a!=null&&F(t,[`instances[0]`,`image`],J(a));let o=I(e,[`video`]);return t!==void 0&&o!=null&&F(t,[`instances[0]`,`video`],gc(o)),r}function ds(e,t){let n={},r=I(e,[`_self`]);r!=null&&F(n,[`image`],Cs(r));let i=I(e,[`raiFilteredReason`]);i!=null&&F(n,[`raiFilteredReason`],i);let a=I(e,[`_self`]);return a!=null&&F(n,[`safetyAttributes`],Us(a)),n}function fs(e,t){let n={},r=I(e,[`_self`]);r!=null&&F(n,[`image`],ws(r));let i=I(e,[`raiFilteredReason`]);i!=null&&F(n,[`raiFilteredReason`],i);let a=I(e,[`_self`]);a!=null&&F(n,[`safetyAttributes`],Ws(a));let o=I(e,[`prompt`]);return o!=null&&F(n,[`enhancedPrompt`],o),n}function ps(e,t){let n={},r=I(e,[`_self`]);r!=null&&F(n,[`mask`],ws(r));let i=I(e,[`labels`]);if(i!=null){let e=i;Array.isArray(e)&&(e=e.map(e=>e)),F(n,[`labels`],e)}return n}function ms(e,t){let n={},r=I(e,[`video`]);return r!=null&&F(n,[`video`],uc(r)),n}function hs(e,t){let n={},r=I(e,[`_self`]);return r!=null&&F(n,[`video`],dc(r)),n}function gs(e,t){let n={},r=I(e,[`modelSelectionConfig`]);r!=null&&F(n,[`modelConfig`],r);let i=I(e,[`responseJsonSchema`]);i!=null&&F(n,[`responseJsonSchema`],i);let a=I(e,[`audioTimestamp`]);a!=null&&F(n,[`audioTimestamp`],a);let o=I(e,[`candidateCount`]);o!=null&&F(n,[`candidateCount`],o);let s=I(e,[`enableAffectiveDialog`]);s!=null&&F(n,[`enableAffectiveDialog`],s);let c=I(e,[`frequencyPenalty`]);c!=null&&F(n,[`frequencyPenalty`],c);let l=I(e,[`logprobs`]);l!=null&&F(n,[`logprobs`],l);let u=I(e,[`maxOutputTokens`]);u!=null&&F(n,[`maxOutputTokens`],u);let d=I(e,[`mediaResolution`]);d!=null&&F(n,[`mediaResolution`],d);let f=I(e,[`presencePenalty`]);f!=null&&F(n,[`presencePenalty`],f);let p=I(e,[`responseLogprobs`]);p!=null&&F(n,[`responseLogprobs`],p);let m=I(e,[`responseMimeType`]);m!=null&&F(n,[`responseMimeType`],m);let h=I(e,[`responseModalities`]);h!=null&&F(n,[`responseModalities`],h);let g=I(e,[`responseSchema`]);g!=null&&F(n,[`responseSchema`],g);let _=I(e,[`routingConfig`]);_!=null&&F(n,[`routingConfig`],_);let v=I(e,[`seed`]);v!=null&&F(n,[`seed`],v);let y=I(e,[`speechConfig`]);y!=null&&F(n,[`speechConfig`],y);let b=I(e,[`stopSequences`]);b!=null&&F(n,[`stopSequences`],b);let x=I(e,[`temperature`]);x!=null&&F(n,[`temperature`],x);let S=I(e,[`thinkingConfig`]);S!=null&&F(n,[`thinkingConfig`],S);let C=I(e,[`topK`]);C!=null&&F(n,[`topK`],C);let w=I(e,[`topP`]);if(w!=null&&F(n,[`topP`],w),I(e,[`enableEnhancedCivicAnswers`])!==void 0)throw Error(`enableEnhancedCivicAnswers parameter is not supported in Vertex AI.`);return n}function _s(e,t,n){let r={},i=I(t,[`model`]);return i!=null&&F(r,[`_url`,`name`],R(e,i)),r}function vs(e,t,n){let r={},i=I(t,[`model`]);return i!=null&&F(r,[`_url`,`name`],R(e,i)),r}function ys(e,t){let n={},r=I(e,[`authConfig`]);r!=null&&F(n,[`authConfig`],so(r));let i=I(e,[`enableWidget`]);return i!=null&&F(n,[`enableWidget`],i),n}function bs(e,t){let n={},r=I(e,[`searchTypes`]);if(r!=null&&F(n,[`searchTypes`],r),I(e,[`blockingConfidence`])!==void 0)throw Error(`blockingConfidence parameter is not supported in Gemini API.`);if(I(e,[`excludeDomains`])!==void 0)throw Error(`excludeDomains parameter is not supported in Gemini API.`);let i=I(e,[`timeRangeFilter`]);return i!=null&&F(n,[`timeRangeFilter`],i),n}function xs(e,t){let n={},r=I(e,[`aspectRatio`]);r!=null&&F(n,[`aspectRatio`],r);let i=I(e,[`imageSize`]);if(i!=null&&F(n,[`imageSize`],i),I(e,[`personGeneration`])!==void 0)throw Error(`personGeneration parameter is not supported in Gemini API.`);if(I(e,[`prominentPeople`])!==void 0)throw Error(`prominentPeople parameter is not supported in Gemini API.`);if(I(e,[`outputMimeType`])!==void 0)throw Error(`outputMimeType parameter is not supported in Gemini API.`);if(I(e,[`outputCompressionQuality`])!==void 0)throw Error(`outputCompressionQuality parameter is not supported in Gemini API.`);if(I(e,[`imageOutputOptions`])!==void 0)throw Error(`imageOutputOptions parameter is not supported in Gemini API.`);return n}function Ss(e,t){let n={},r=I(e,[`aspectRatio`]);r!=null&&F(n,[`aspectRatio`],r);let i=I(e,[`imageSize`]);i!=null&&F(n,[`imageSize`],i);let a=I(e,[`personGeneration`]);a!=null&&F(n,[`personGeneration`],a);let o=I(e,[`prominentPeople`]);o!=null&&F(n,[`prominentPeople`],o);let s=I(e,[`outputMimeType`]);s!=null&&F(n,[`imageOutputOptions`,`mimeType`],s);let c=I(e,[`outputCompressionQuality`]);c!=null&&F(n,[`imageOutputOptions`,`compressionQuality`],c);let l=I(e,[`imageOutputOptions`]);return l!=null&&F(n,[`imageOutputOptions`],l),n}function Cs(e,t){let n={},r=I(e,[`bytesBase64Encoded`]);r!=null&&F(n,[`imageBytes`],H(r));let i=I(e,[`mimeType`]);return i!=null&&F(n,[`mimeType`],i),n}function ws(e,t){let n={},r=I(e,[`gcsUri`]);r!=null&&F(n,[`gcsUri`],r);let i=I(e,[`bytesBase64Encoded`]);i!=null&&F(n,[`imageBytes`],H(i));let a=I(e,[`mimeType`]);return a!=null&&F(n,[`mimeType`],a),n}function Ts(e,t){let n={};if(I(e,[`gcsUri`])!==void 0)throw Error(`gcsUri parameter is not supported in Gemini API.`);let r=I(e,[`imageBytes`]);r!=null&&F(n,[`bytesBase64Encoded`],H(r));let i=I(e,[`mimeType`]);return i!=null&&F(n,[`mimeType`],i),n}function J(e,t){let n={},r=I(e,[`gcsUri`]);r!=null&&F(n,[`gcsUri`],r);let i=I(e,[`imageBytes`]);i!=null&&F(n,[`bytesBase64Encoded`],H(i));let a=I(e,[`mimeType`]);return a!=null&&F(n,[`mimeType`],a),n}function Es(e,t,n,r){let i={},a=I(t,[`pageSize`]);n!==void 0&&a!=null&&F(n,[`_query`,`pageSize`],a);let o=I(t,[`pageToken`]);n!==void 0&&o!=null&&F(n,[`_query`,`pageToken`],o);let s=I(t,[`filter`]);n!==void 0&&s!=null&&F(n,[`_query`,`filter`],s);let c=I(t,[`queryBase`]);return n!==void 0&&c!=null&&F(n,[`_url`,`models_url`],Sr(e,c)),i}function Ds(e,t,n,r){let i={},a=I(t,[`pageSize`]);n!==void 0&&a!=null&&F(n,[`_query`,`pageSize`],a);let o=I(t,[`pageToken`]);n!==void 0&&o!=null&&F(n,[`_query`,`pageToken`],o);let s=I(t,[`filter`]);n!==void 0&&s!=null&&F(n,[`_query`,`filter`],s);let c=I(t,[`queryBase`]);return n!==void 0&&c!=null&&F(n,[`_url`,`models_url`],Sr(e,c)),i}function Os(e,t,n){let r={},i=I(t,[`config`]);return i!=null&&Es(e,i,r),r}function ks(e,t,n){let r={},i=I(t,[`config`]);return i!=null&&Ds(e,i,r),r}function As(e,t){let n={},r=I(e,[`sdkHttpResponse`]);r!=null&&F(n,[`sdkHttpResponse`],r);let i=I(e,[`nextPageToken`]);i!=null&&F(n,[`nextPageToken`],i);let a=I(e,[`_self`]);if(a!=null){let e=Cr(a);Array.isArray(e)&&(e=e.map(e=>Ns(e))),F(n,[`models`],e)}return n}function js(e,t){let n={},r=I(e,[`sdkHttpResponse`]);r!=null&&F(n,[`sdkHttpResponse`],r);let i=I(e,[`nextPageToken`]);i!=null&&F(n,[`nextPageToken`],i);let a=I(e,[`_self`]);if(a!=null){let e=Cr(a);Array.isArray(e)&&(e=e.map(e=>Ps(e))),F(n,[`models`],e)}return n}function Ms(e,t){let n={},r=I(e,[`maskMode`]);r!=null&&F(n,[`maskMode`],r);let i=I(e,[`segmentationClasses`]);i!=null&&F(n,[`maskClasses`],i);let a=I(e,[`maskDilation`]);return a!=null&&F(n,[`dilation`],a),n}function Ns(e,t){let n={},r=I(e,[`name`]);r!=null&&F(n,[`name`],r);let i=I(e,[`displayName`]);i!=null&&F(n,[`displayName`],i);let a=I(e,[`description`]);a!=null&&F(n,[`description`],a);let o=I(e,[`version`]);o!=null&&F(n,[`version`],o);let s=I(e,[`_self`]);s!=null&&F(n,[`tunedModelInfo`],tc(s));let c=I(e,[`inputTokenLimit`]);c!=null&&F(n,[`inputTokenLimit`],c);let l=I(e,[`outputTokenLimit`]);l!=null&&F(n,[`outputTokenLimit`],l);let u=I(e,[`supportedGenerationMethods`]);u!=null&&F(n,[`supportedActions`],u);let d=I(e,[`temperature`]);d!=null&&F(n,[`temperature`],d);let f=I(e,[`maxTemperature`]);f!=null&&F(n,[`maxTemperature`],f);let p=I(e,[`topP`]);p!=null&&F(n,[`topP`],p);let m=I(e,[`topK`]);m!=null&&F(n,[`topK`],m);let h=I(e,[`thinking`]);return h!=null&&F(n,[`thinking`],h),n}function Ps(e,t){let n={},r=I(e,[`name`]);r!=null&&F(n,[`name`],r);let i=I(e,[`displayName`]);i!=null&&F(n,[`displayName`],i);let a=I(e,[`description`]);a!=null&&F(n,[`description`],a);let o=I(e,[`versionId`]);o!=null&&F(n,[`version`],o);let s=I(e,[`deployedModels`]);if(s!=null){let e=s;Array.isArray(e)&&(e=e.map(e=>Ro(e))),F(n,[`endpoints`],e)}let c=I(e,[`labels`]);c!=null&&F(n,[`labels`],c);let l=I(e,[`_self`]);l!=null&&F(n,[`tunedModelInfo`],nc(l));let u=I(e,[`defaultCheckpointId`]);u!=null&&F(n,[`defaultCheckpointId`],u);let d=I(e,[`checkpoints`]);if(d!=null){let e=d;Array.isArray(e)&&(e=e.map(e=>e)),F(n,[`checkpoints`],e)}return n}function Fs(e,t){let n={},r=I(e,[`mediaResolution`]);r!=null&&F(n,[`mediaResolution`],r);let i=I(e,[`codeExecutionResult`]);i!=null&&F(n,[`codeExecutionResult`],i);let a=I(e,[`executableCode`]);a!=null&&F(n,[`executableCode`],a);let o=I(e,[`fileData`]);o!=null&&F(n,[`fileData`],zo(o));let s=I(e,[`functionCall`]);s!=null&&F(n,[`functionCall`],Bo(s));let c=I(e,[`functionResponse`]);c!=null&&F(n,[`functionResponse`],c);let l=I(e,[`inlineData`]);l!=null&&F(n,[`inlineData`],co(l));let u=I(e,[`text`]);u!=null&&F(n,[`text`],u);let d=I(e,[`thought`]);d!=null&&F(n,[`thought`],d);let f=I(e,[`thoughtSignature`]);f!=null&&F(n,[`thoughtSignature`],f);let p=I(e,[`videoMetadata`]);p!=null&&F(n,[`videoMetadata`],p);let m=I(e,[`toolCall`]);m!=null&&F(n,[`toolCall`],m);let h=I(e,[`toolResponse`]);h!=null&&F(n,[`toolResponse`],h);let g=I(e,[`partMetadata`]);return g!=null&&F(n,[`partMetadata`],g),n}function Is(e,t){let n={},r=I(e,[`mediaResolution`]);r!=null&&F(n,[`mediaResolution`],r);let i=I(e,[`codeExecutionResult`]);i!=null&&F(n,[`codeExecutionResult`],i);let a=I(e,[`executableCode`]);a!=null&&F(n,[`executableCode`],a);let o=I(e,[`fileData`]);o!=null&&F(n,[`fileData`],o);let s=I(e,[`functionCall`]);s!=null&&F(n,[`functionCall`],s);let c=I(e,[`functionResponse`]);c!=null&&F(n,[`functionResponse`],c);let l=I(e,[`inlineData`]);l!=null&&F(n,[`inlineData`],l);let u=I(e,[`text`]);u!=null&&F(n,[`text`],u);let d=I(e,[`thought`]);d!=null&&F(n,[`thought`],d);let f=I(e,[`thoughtSignature`]);f!=null&&F(n,[`thoughtSignature`],f);let p=I(e,[`videoMetadata`]);if(p!=null&&F(n,[`videoMetadata`],p),I(e,[`toolCall`])!==void 0)throw Error(`toolCall parameter is not supported in Vertex AI.`);if(I(e,[`toolResponse`])!==void 0)throw Error(`toolResponse parameter is not supported in Vertex AI.`);if(I(e,[`partMetadata`])!==void 0)throw Error(`partMetadata parameter is not supported in Vertex AI.`);return n}function Ls(e,t){let n={},r=I(e,[`productImage`]);return r!=null&&F(n,[`image`],J(r)),n}function Rs(e,t,n){let r={},i=I(e,[`numberOfImages`]);t!==void 0&&i!=null&&F(t,[`parameters`,`sampleCount`],i);let a=I(e,[`baseSteps`]);t!==void 0&&a!=null&&F(t,[`parameters`,`baseSteps`],a);let o=I(e,[`outputGcsUri`]);t!==void 0&&o!=null&&F(t,[`parameters`,`storageUri`],o);let s=I(e,[`seed`]);t!==void 0&&s!=null&&F(t,[`parameters`,`seed`],s);let c=I(e,[`safetyFilterLevel`]);t!==void 0&&c!=null&&F(t,[`parameters`,`safetySetting`],c);let l=I(e,[`personGeneration`]);t!==void 0&&l!=null&&F(t,[`parameters`,`personGeneration`],l);let u=I(e,[`addWatermark`]);t!==void 0&&u!=null&&F(t,[`parameters`,`addWatermark`],u);let d=I(e,[`outputMimeType`]);t!==void 0&&d!=null&&F(t,[`parameters`,`outputOptions`,`mimeType`],d);let f=I(e,[`outputCompressionQuality`]);t!==void 0&&f!=null&&F(t,[`parameters`,`outputOptions`,`compressionQuality`],f);let p=I(e,[`enhancePrompt`]);t!==void 0&&p!=null&&F(t,[`parameters`,`enhancePrompt`],p);let m=I(e,[`labels`]);return t!==void 0&&m!=null&&F(t,[`labels`],m),r}function zs(e,t,n){let r={},i=I(t,[`model`]);i!=null&&F(r,[`_url`,`model`],R(e,i));let a=I(t,[`source`]);a!=null&&Vs(a,r);let o=I(t,[`config`]);return o!=null&&Rs(o,r),r}function Bs(e,t){let n={},r=I(e,[`predictions`]);if(r!=null){let e=r;Array.isArray(e)&&(e=e.map(e=>fs(e))),F(n,[`generatedImages`],e)}return n}function Vs(e,t,n){let r={},i=I(e,[`prompt`]);t!==void 0&&i!=null&&F(t,[`instances[0]`,`prompt`],i);let a=I(e,[`personImage`]);t!==void 0&&a!=null&&F(t,[`instances[0]`,`personImage`,`image`],J(a));let o=I(e,[`productImages`]);if(t!==void 0&&o!=null){let e=o;Array.isArray(e)&&(e=e.map(e=>Ls(e))),F(t,[`instances[0]`,`productImages`],e)}return r}function Hs(e,t){let n={},r=I(e,[`referenceImage`]);r!=null&&F(n,[`referenceImage`],J(r));let i=I(e,[`referenceId`]);i!=null&&F(n,[`referenceId`],i);let a=I(e,[`referenceType`]);a!=null&&F(n,[`referenceType`],a);let o=I(e,[`maskImageConfig`]);o!=null&&F(n,[`maskImageConfig`],Ms(o));let s=I(e,[`controlImageConfig`]);s!=null&&F(n,[`controlImageConfig`],vo(s));let c=I(e,[`styleImageConfig`]);c!=null&&F(n,[`styleImageConfig`],c);let l=I(e,[`subjectImageConfig`]);return l!=null&&F(n,[`subjectImageConfig`],l),n}function Us(e,t){let n={},r=I(e,[`safetyAttributes`,`categories`]);r!=null&&F(n,[`categories`],r);let i=I(e,[`safetyAttributes`,`scores`]);i!=null&&F(n,[`scores`],i);let a=I(e,[`contentType`]);return a!=null&&F(n,[`contentType`],a),n}function Ws(e,t){let n={},r=I(e,[`safetyAttributes`,`categories`]);r!=null&&F(n,[`categories`],r);let i=I(e,[`safetyAttributes`,`scores`]);i!=null&&F(n,[`scores`],i);let a=I(e,[`contentType`]);return a!=null&&F(n,[`contentType`],a),n}function Gs(e,t){let n={},r=I(e,[`category`]);if(r!=null&&F(n,[`category`],r),I(e,[`method`])!==void 0)throw Error(`method parameter is not supported in Gemini API.`);let i=I(e,[`threshold`]);return i!=null&&F(n,[`threshold`],i),n}function Ks(e,t){let n={},r=I(e,[`image`]);return r!=null&&F(n,[`image`],J(r)),n}function qs(e,t,n){let r={},i=I(e,[`mode`]);t!==void 0&&i!=null&&F(t,[`parameters`,`mode`],i);let a=I(e,[`maxPredictions`]);t!==void 0&&a!=null&&F(t,[`parameters`,`maxPredictions`],a);let o=I(e,[`confidenceThreshold`]);t!==void 0&&o!=null&&F(t,[`parameters`,`confidenceThreshold`],o);let s=I(e,[`maskDilation`]);t!==void 0&&s!=null&&F(t,[`parameters`,`maskDilation`],s);let c=I(e,[`binaryColorThreshold`]);t!==void 0&&c!=null&&F(t,[`parameters`,`binaryColorThreshold`],c);let l=I(e,[`labels`]);return t!==void 0&&l!=null&&F(t,[`labels`],l),r}function Js(e,t,n){let r={},i=I(t,[`model`]);i!=null&&F(r,[`_url`,`model`],R(e,i));let a=I(t,[`source`]);a!=null&&Xs(a,r);let o=I(t,[`config`]);return o!=null&&qs(o,r),r}function Ys(e,t){let n={},r=I(e,[`predictions`]);if(r!=null){let e=r;Array.isArray(e)&&(e=e.map(e=>ps(e))),F(n,[`generatedMasks`],e)}return n}function Xs(e,t,n){let r={},i=I(e,[`prompt`]);t!==void 0&&i!=null&&F(t,[`instances[0]`,`prompt`],i);let a=I(e,[`image`]);t!==void 0&&a!=null&&F(t,[`instances[0]`,`image`],J(a));let o=I(e,[`scribbleImage`]);return t!==void 0&&o!=null&&F(t,[`instances[0]`,`scribble`],Ks(o)),r}function Zs(e,t){let n={},r=I(e,[`retrievalConfig`]);r!=null&&F(n,[`retrievalConfig`],r);let i=I(e,[`functionCallingConfig`]);i!=null&&F(n,[`functionCallingConfig`],Vo(i));let a=I(e,[`includeServerSideToolInvocations`]);return a!=null&&F(n,[`includeServerSideToolInvocations`],a),n}function Qs(e,t){let n={},r=I(e,[`retrievalConfig`]);r!=null&&F(n,[`retrievalConfig`],r);let i=I(e,[`functionCallingConfig`]);if(i!=null&&F(n,[`functionCallingConfig`],i),I(e,[`includeServerSideToolInvocations`])!==void 0)throw Error(`includeServerSideToolInvocations parameter is not supported in Vertex AI.`);return n}function $s(e,t){let n={};if(I(e,[`retrieval`])!==void 0)throw Error(`retrieval parameter is not supported in Gemini API.`);let r=I(e,[`computerUse`]);r!=null&&F(n,[`computerUse`],r);let i=I(e,[`fileSearch`]);i!=null&&F(n,[`fileSearch`],i);let a=I(e,[`googleSearch`]);a!=null&&F(n,[`googleSearch`],bs(a));let o=I(e,[`googleMaps`]);o!=null&&F(n,[`googleMaps`],ys(o));let s=I(e,[`codeExecution`]);if(s!=null&&F(n,[`codeExecution`],s),I(e,[`enterpriseWebSearch`])!==void 0)throw Error(`enterpriseWebSearch parameter is not supported in Gemini API.`);let c=I(e,[`functionDeclarations`]);if(c!=null){let e=c;Array.isArray(e)&&(e=e.map(e=>e)),F(n,[`functionDeclarations`],e)}let l=I(e,[`googleSearchRetrieval`]);if(l!=null&&F(n,[`googleSearchRetrieval`],l),I(e,[`parallelAiSearch`])!==void 0)throw Error(`parallelAiSearch parameter is not supported in Gemini API.`);let u=I(e,[`urlContext`]);u!=null&&F(n,[`urlContext`],u);let d=I(e,[`mcpServers`]);if(d!=null){let e=d;Array.isArray(e)&&(e=e.map(e=>e)),F(n,[`mcpServers`],e)}return n}function ec(e,t){let n={},r=I(e,[`retrieval`]);r!=null&&F(n,[`retrieval`],r);let i=I(e,[`computerUse`]);if(i!=null&&F(n,[`computerUse`],i),I(e,[`fileSearch`])!==void 0)throw Error(`fileSearch parameter is not supported in Vertex AI.`);let a=I(e,[`googleSearch`]);a!=null&&F(n,[`googleSearch`],a);let o=I(e,[`googleMaps`]);o!=null&&F(n,[`googleMaps`],o);let s=I(e,[`codeExecution`]);s!=null&&F(n,[`codeExecution`],s);let c=I(e,[`enterpriseWebSearch`]);c!=null&&F(n,[`enterpriseWebSearch`],c);let l=I(e,[`functionDeclarations`]);if(l!=null){let e=l;Array.isArray(e)&&(e=e.map(e=>Ho(e))),F(n,[`functionDeclarations`],e)}let u=I(e,[`googleSearchRetrieval`]);u!=null&&F(n,[`googleSearchRetrieval`],u);let d=I(e,[`parallelAiSearch`]);d!=null&&F(n,[`parallelAiSearch`],d);let f=I(e,[`urlContext`]);if(f!=null&&F(n,[`urlContext`],f),I(e,[`mcpServers`])!==void 0)throw Error(`mcpServers parameter is not supported in Vertex AI.`);return n}function tc(e,t){let n={},r=I(e,[`baseModel`]);r!=null&&F(n,[`baseModel`],r);let i=I(e,[`createTime`]);i!=null&&F(n,[`createTime`],i);let a=I(e,[`updateTime`]);return a!=null&&F(n,[`updateTime`],a),n}function nc(e,t){let n={},r=I(e,[`labels`,`google-vertex-llm-tuning-base-model-id`]);r!=null&&F(n,[`baseModel`],r);let i=I(e,[`createTime`]);i!=null&&F(n,[`createTime`],i);let a=I(e,[`updateTime`]);return a!=null&&F(n,[`updateTime`],a),n}function rc(e,t,n){let r={},i=I(e,[`displayName`]);t!==void 0&&i!=null&&F(t,[`displayName`],i);let a=I(e,[`description`]);t!==void 0&&a!=null&&F(t,[`description`],a);let o=I(e,[`defaultCheckpointId`]);return t!==void 0&&o!=null&&F(t,[`defaultCheckpointId`],o),r}function ic(e,t,n){let r={},i=I(e,[`displayName`]);t!==void 0&&i!=null&&F(t,[`displayName`],i);let a=I(e,[`description`]);t!==void 0&&a!=null&&F(t,[`description`],a);let o=I(e,[`defaultCheckpointId`]);return t!==void 0&&o!=null&&F(t,[`defaultCheckpointId`],o),r}function ac(e,t,n){let r={},i=I(t,[`model`]);i!=null&&F(r,[`_url`,`name`],R(e,i));let a=I(t,[`config`]);return a!=null&&rc(a,r),r}function oc(e,t,n){let r={},i=I(t,[`model`]);i!=null&&F(r,[`_url`,`model`],R(e,i));let a=I(t,[`config`]);return a!=null&&ic(a,r),r}function sc(e,t,n){let r={},i=I(e,[`outputGcsUri`]);t!==void 0&&i!=null&&F(t,[`parameters`,`storageUri`],i);let a=I(e,[`safetyFilterLevel`]);t!==void 0&&a!=null&&F(t,[`parameters`,`safetySetting`],a);let o=I(e,[`personGeneration`]);t!==void 0&&o!=null&&F(t,[`parameters`,`personGeneration`],o);let s=I(e,[`includeRaiReason`]);t!==void 0&&s!=null&&F(t,[`parameters`,`includeRaiReason`],s);let c=I(e,[`outputMimeType`]);t!==void 0&&c!=null&&F(t,[`parameters`,`outputOptions`,`mimeType`],c);let l=I(e,[`outputCompressionQuality`]);t!==void 0&&l!=null&&F(t,[`parameters`,`outputOptions`,`compressionQuality`],l);let u=I(e,[`enhanceInputImage`]);t!==void 0&&u!=null&&F(t,[`parameters`,`upscaleConfig`,`enhanceInputImage`],u);let d=I(e,[`imagePreservationFactor`]);t!==void 0&&d!=null&&F(t,[`parameters`,`upscaleConfig`,`imagePreservationFactor`],d);let f=I(e,[`labels`]);t!==void 0&&f!=null&&F(t,[`labels`],f);let p=I(e,[`numberOfImages`]);t!==void 0&&p!=null&&F(t,[`parameters`,`sampleCount`],p);let m=I(e,[`mode`]);return t!==void 0&&m!=null&&F(t,[`parameters`,`mode`],m),r}function cc(e,t,n){let r={},i=I(t,[`model`]);i!=null&&F(r,[`_url`,`model`],R(e,i));let a=I(t,[`image`]);a!=null&&F(r,[`instances[0]`,`image`],J(a));let o=I(t,[`upscaleFactor`]);o!=null&&F(r,[`parameters`,`upscaleConfig`,`upscaleFactor`],o);let s=I(t,[`config`]);return s!=null&&sc(s,r),r}function lc(e,t){let n={},r=I(e,[`sdkHttpResponse`]);r!=null&&F(n,[`sdkHttpResponse`],r);let i=I(e,[`predictions`]);if(i!=null){let e=i;Array.isArray(e)&&(e=e.map(e=>fs(e))),F(n,[`generatedImages`],e)}return n}function uc(e,t){let n={},r=I(e,[`uri`]);r!=null&&F(n,[`uri`],r);let i=I(e,[`encodedVideo`]);i!=null&&F(n,[`videoBytes`],H(i));let a=I(e,[`encoding`]);return a!=null&&F(n,[`mimeType`],a),n}function dc(e,t){let n={},r=I(e,[`gcsUri`]);r!=null&&F(n,[`uri`],r);let i=I(e,[`bytesBase64Encoded`]);i!=null&&F(n,[`videoBytes`],H(i));let a=I(e,[`mimeType`]);return a!=null&&F(n,[`mimeType`],a),n}function fc(e,t){let n={},r=I(e,[`image`]);r!=null&&F(n,[`_self`],J(r));let i=I(e,[`maskMode`]);return i!=null&&F(n,[`maskMode`],i),n}function pc(e,t){let n={},r=I(e,[`image`]);r!=null&&F(n,[`image`],Ts(r));let i=I(e,[`referenceType`]);return i!=null&&F(n,[`referenceType`],i),n}function mc(e,t){let n={},r=I(e,[`image`]);r!=null&&F(n,[`image`],J(r));let i=I(e,[`referenceType`]);return i!=null&&F(n,[`referenceType`],i),n}function hc(e,t){let n={},r=I(e,[`uri`]);r!=null&&F(n,[`uri`],r);let i=I(e,[`videoBytes`]);i!=null&&F(n,[`encodedVideo`],H(i));let a=I(e,[`mimeType`]);return a!=null&&F(n,[`encoding`],a),n}function gc(e,t){let n={},r=I(e,[`uri`]);r!=null&&F(n,[`gcsUri`],r);let i=I(e,[`videoBytes`]);i!=null&&F(n,[`bytesBase64Encoded`],H(i));let a=I(e,[`mimeType`]);return a!=null&&F(n,[`mimeType`],a),n}
94
+ /**
95
+ * @license
96
+ * Copyright 2025 Google LLC
97
+ * SPDX-License-Identifier: Apache-2.0
98
+ */
99
+ function _c(e,t){let n={},r=I(e,[`displayName`]);return t!==void 0&&r!=null&&F(t,[`displayName`],r),n}function vc(e){let t={},n=I(e,[`config`]);return n!=null&&_c(n,t),t}function yc(e,t){let n={},r=I(e,[`force`]);return t!==void 0&&r!=null&&F(t,[`_query`,`force`],r),n}function bc(e){let t={},n=I(e,[`name`]);n!=null&&F(t,[`_url`,`name`],n);let r=I(e,[`config`]);return r!=null&&yc(r,t),t}function xc(e){let t={},n=I(e,[`name`]);return n!=null&&F(t,[`_url`,`name`],n),t}function Sc(e,t){let n={},r=I(e,[`customMetadata`]);if(t!==void 0&&r!=null){let e=r;Array.isArray(e)&&(e=e.map(e=>e)),F(t,[`customMetadata`],e)}let i=I(e,[`chunkingConfig`]);return t!==void 0&&i!=null&&F(t,[`chunkingConfig`],i),n}function Cc(e){let t={},n=I(e,[`name`]);n!=null&&F(t,[`name`],n);let r=I(e,[`metadata`]);r!=null&&F(t,[`metadata`],r);let i=I(e,[`done`]);i!=null&&F(t,[`done`],i);let a=I(e,[`error`]);a!=null&&F(t,[`error`],a);let o=I(e,[`response`]);return o!=null&&F(t,[`response`],Tc(o)),t}function wc(e){let t={},n=I(e,[`fileSearchStoreName`]);n!=null&&F(t,[`_url`,`file_search_store_name`],n);let r=I(e,[`fileName`]);r!=null&&F(t,[`fileName`],r);let i=I(e,[`config`]);return i!=null&&Sc(i,t),t}function Tc(e){let t={},n=I(e,[`sdkHttpResponse`]);n!=null&&F(t,[`sdkHttpResponse`],n);let r=I(e,[`parent`]);r!=null&&F(t,[`parent`],r);let i=I(e,[`documentName`]);return i!=null&&F(t,[`documentName`],i),t}function Ec(e,t){let n={},r=I(e,[`pageSize`]);t!==void 0&&r!=null&&F(t,[`_query`,`pageSize`],r);let i=I(e,[`pageToken`]);return t!==void 0&&i!=null&&F(t,[`_query`,`pageToken`],i),n}function Dc(e){let t={},n=I(e,[`config`]);return n!=null&&Ec(n,t),t}function Oc(e){let t={},n=I(e,[`sdkHttpResponse`]);n!=null&&F(t,[`sdkHttpResponse`],n);let r=I(e,[`nextPageToken`]);r!=null&&F(t,[`nextPageToken`],r);let i=I(e,[`fileSearchStores`]);if(i!=null){let e=i;Array.isArray(e)&&(e=e.map(e=>e)),F(t,[`fileSearchStores`],e)}return t}function kc(e,t){let n={},r=I(e,[`mimeType`]);t!==void 0&&r!=null&&F(t,[`mimeType`],r);let i=I(e,[`displayName`]);t!==void 0&&i!=null&&F(t,[`displayName`],i);let a=I(e,[`customMetadata`]);if(t!==void 0&&a!=null){let e=a;Array.isArray(e)&&(e=e.map(e=>e)),F(t,[`customMetadata`],e)}let o=I(e,[`chunkingConfig`]);return t!==void 0&&o!=null&&F(t,[`chunkingConfig`],o),n}function Ac(e){let t={},n=I(e,[`fileSearchStoreName`]);n!=null&&F(t,[`_url`,`file_search_store_name`],n);let r=I(e,[`config`]);return r!=null&&kc(r,t),t}function jc(e){let t={},n=I(e,[`sdkHttpResponse`]);return n!=null&&F(t,[`sdkHttpResponse`],n),t}
100
+ /**
101
+ * @license
102
+ * Copyright 2025 Google LLC
103
+ * SPDX-License-Identifier: Apache-2.0
104
+ */
105
+ const Mc=`x-goog-api-client`,Nc=new Set([`us`,`eu`]),Pc=[408,429,500,502,503,504];var Fc=class{constructor(e){this.clientOptions=Object.assign({},e),this.customBaseUrl=e.httpOptions?.baseUrl,this.clientOptions.vertexai&&(this.clientOptions.project&&this.clientOptions.location?this.clientOptions.apiKey=void 0:this.clientOptions.apiKey&&(this.clientOptions.project=void 0,this.clientOptions.location=void 0));let t={};if(this.clientOptions.vertexai){if(!this.clientOptions.location&&!this.clientOptions.apiKey&&!this.customBaseUrl&&(this.clientOptions.location=`global`),!(this.clientOptions.project&&this.clientOptions.location||this.clientOptions.apiKey)&&!this.customBaseUrl)throw Error(`Authentication is not set up. Please provide either a project and location, or an API key, or a custom base URL.`);let n=e.project&&e.location||!!e.apiKey;this.customBaseUrl&&!n?(t.baseUrl=this.customBaseUrl,this.clientOptions.project=void 0,this.clientOptions.location=void 0):this.clientOptions.apiKey||this.clientOptions.location===`global`?t.baseUrl=`https://aiplatform.googleapis.com/`:this.clientOptions.project&&this.clientOptions.location&&Nc.has(this.clientOptions.location)?t.baseUrl=`https://aiplatform.${this.clientOptions.location}.rep.googleapis.com/`:this.clientOptions.project&&this.clientOptions.location&&(t.baseUrl=`https://${this.clientOptions.location}-aiplatform.googleapis.com/`),t.apiVersion=this.clientOptions.apiVersion??`v1beta1`}else this.clientOptions.apiKey||console.warn(`API key should be set when using the Gemini API.`),t.apiVersion=this.clientOptions.apiVersion??`v1beta`,t.baseUrl=`https://generativelanguage.googleapis.com/`;t.headers=this.getDefaultHeaders(),this.clientOptions.httpOptions=t,e.httpOptions&&(this.clientOptions.httpOptions=this.patchHttpOptions(t,e.httpOptions))}isVertexAI(){return this.clientOptions.vertexai??!1}getProject(){return this.clientOptions.project}getLocation(){return this.clientOptions.location}getCustomBaseUrl(){return this.customBaseUrl}async getAuthHeaders(){let e=new Headers;return await this.clientOptions.auth.addAuthHeaders(e),e}getApiVersion(){if(this.clientOptions.httpOptions&&this.clientOptions.httpOptions.apiVersion!==void 0)return this.clientOptions.httpOptions.apiVersion;throw Error(`API version is not set.`)}getBaseUrl(){if(this.clientOptions.httpOptions&&this.clientOptions.httpOptions.baseUrl!==void 0)return this.clientOptions.httpOptions.baseUrl;throw Error(`Base URL is not set.`)}getRequestUrl(){return this.getRequestUrlInternal(this.clientOptions.httpOptions)}getHeaders(){if(this.clientOptions.httpOptions&&this.clientOptions.httpOptions.headers!==void 0)return this.clientOptions.httpOptions.headers;throw Error(`Headers are not set.`)}getRequestUrlInternal(e){if(!e||e.baseUrl===void 0||e.apiVersion===void 0)throw Error(`HTTP options are not correctly set.`);let t=[e.baseUrl.endsWith(`/`)?e.baseUrl.slice(0,-1):e.baseUrl];return e.apiVersion&&e.apiVersion!==``&&t.push(e.apiVersion),t.join(`/`)}getBaseResourcePath(){return`projects/${this.clientOptions.project}/locations/${this.clientOptions.location}`}getApiKey(){return this.clientOptions.apiKey}getWebsocketBaseUrl(){let e=this.getBaseUrl(),t=new URL(e);return t.protocol=t.protocol==`http:`?`ws`:`wss`,t.toString()}setBaseUrl(e){if(this.clientOptions.httpOptions)this.clientOptions.httpOptions.baseUrl=e;else throw Error(`HTTP options are not correctly set.`)}constructUrl(e,t,n){let r=[this.getRequestUrlInternal(t)];return n&&r.push(this.getBaseResourcePath()),e!==``&&r.push(e),new URL(`${r.join(`/`)}`)}shouldPrependVertexProjectPath(e,t){return!(t.baseUrl&&t.baseUrlResourceScope===Jt.COLLECTION||this.clientOptions.apiKey||!this.clientOptions.vertexai||e.path.startsWith(`projects/`)||e.httpMethod===`GET`&&e.path.startsWith(`publishers/google/models`))}async request(e){let t=this.clientOptions.httpOptions;e.httpOptions&&(t=this.patchHttpOptions(this.clientOptions.httpOptions,e.httpOptions));let n=this.shouldPrependVertexProjectPath(e,t),r=this.constructUrl(e.path,t,n);if(e.queryParams)for(let[t,n]of Object.entries(e.queryParams))r.searchParams.append(t,String(n));let i={};if(e.httpMethod===`GET`){if(e.body&&e.body!==`{}`)throw Error(`Request body should be empty for GET request, but got non empty request body`)}else i.body=e.body;return i=await this.includeExtraHttpOptionsToRequestInit(i,t,r.toString(),e.abortSignal),this.unaryApiCall(r,i,e.httpMethod)}patchHttpOptions(e,t){let n=JSON.parse(JSON.stringify(e));for(let[e,r]of Object.entries(t))typeof r==`object`?n[e]=Object.assign(Object.assign({},n[e]),r):r!==void 0&&(n[e]=r);return n}async requestStream(e){let t=this.clientOptions.httpOptions;e.httpOptions&&(t=this.patchHttpOptions(this.clientOptions.httpOptions,e.httpOptions));let n=this.shouldPrependVertexProjectPath(e,t),r=this.constructUrl(e.path,t,n);(!r.searchParams.has(`alt`)||r.searchParams.get(`alt`)!==`sse`)&&r.searchParams.set(`alt`,`sse`);let i={};return i.body=e.body,i=await this.includeExtraHttpOptionsToRequestInit(i,t,r.toString(),e.abortSignal),this.streamApiCall(r,i,e.httpMethod)}async includeExtraHttpOptionsToRequestInit(e,t,n,r){if(t&&t.timeout||r){let n=new AbortController,i=n.signal;if(t.timeout&&t?.timeout>0){let e=setTimeout(()=>n.abort(),t.timeout);e&&typeof e.unref==`function`&&e.unref()}r&&r.addEventListener(`abort`,()=>{n.abort()}),e.signal=i}return t&&t.extraBody!==null&&Lc(e,t.extraBody),e.headers=await this.getHeadersInternal(t,n),e}async unaryApiCall(e,t,n){return this.apiCall(e.toString(),Object.assign(Object.assign({},t),{method:n})).then(async e=>(await Ic(e),new Cn(e))).catch(e=>{throw e instanceof Error?e:Error(JSON.stringify(e))})}async streamApiCall(e,t,n){return this.apiCall(e.toString(),Object.assign(Object.assign({},t),{method:n})).then(async e=>(await Ic(e),this.processStreamResponse(e))).catch(e=>{throw e instanceof Error?e:Error(JSON.stringify(e))})}processStreamResponse(e){return K(this,arguments,function*(){let t=(e?.body)?.getReader(),n=new TextDecoder(`utf-8`);if(!t)throw Error(`Response body is empty`);try{let r=``,i=[`
106
+
107
+ `,`\r\r`,`\r
108
+ \r
109
+ `];for(;;){let{done:a,value:o}=yield G(t.read());if(a){if(r.trim().length>0)throw Error(`Incomplete JSON segment at the end`);break}let s=n.decode(o,{stream:!0});try{let e=JSON.parse(s);if(`error`in e){let t=JSON.parse(JSON.stringify(e.error)),n=t.status,r=t.code,i=`got status: ${n}. ${JSON.stringify(e)}`;if(r>=400&&r<600)throw new xa({message:i,status:r})}}catch(e){if(e.name===`ApiError`)throw e}r+=s;let c=-1,l=0;for(;;){c=-1,l=0;for(let e of i){let t=r.indexOf(e);t!==-1&&(c===-1||t<c)&&(c=t,l=e.length)}if(c===-1)break;let t=r.substring(0,c);r=r.substring(c+l);let n=t.trim();if(n.startsWith(`data:`)){let t=n.substring(5).trim();try{yield yield G(new Cn(new Response(t,{headers:e?.headers,status:e?.status,statusText:e?.statusText})))}catch(e){throw Error(`exception parsing stream chunk ${t}. ${e}`)}}}}}finally{t.releaseLock()}})}async apiCall(e,t){if(!this.clientOptions.httpOptions||!this.clientOptions.httpOptions.retryOptions)return fetch(e,t);let n=this.clientOptions.httpOptions.retryOptions;return(0,We.default)(async()=>{let n=await fetch(e,t);if(n.ok)return n;throw Pc.includes(n.status)?Error(`Retryable HTTP Error: ${n.statusText}`):new We.AbortError(`Non-retryable exception ${n.statusText} sending request`)},{retries:(n.attempts??5)-1})}getDefaultHeaders(){let e={},t=`google-genai-sdk/1.50.1 `+this.clientOptions.userAgentExtra;return e[`User-Agent`]=t,e[Mc]=t,e[`Content-Type`]=`application/json`,e}async getHeadersInternal(e,t){let n=new Headers;if(e&&e.headers){for(let[t,r]of Object.entries(e.headers))n.append(t,r);e.timeout&&e.timeout>0&&n.append(`X-Server-Timeout`,String(Math.ceil(e.timeout/1e3)))}return await this.clientOptions.auth.addAuthHeaders(n,t),n}getFileName(e){let t=``;return typeof e==`string`&&(t=e.replace(/[/\\]+$/,``),t=t.split(/[/\\]/).pop()??``),t}async uploadFile(e,t){let n={};t!=null&&(n.mimeType=t.mimeType,n.name=t.name,n.displayName=t.displayName),n.name&&!n.name.startsWith(`files/`)&&(n.name=`files/${n.name}`);let r=this.clientOptions.uploader,i=await r.stat(e);n.sizeBytes=String(i.size);let a=t?.mimeType??i.type;if(a===void 0||a===``)throw Error(`Can not determine mimeType. Please provide mimeType in the config.`);n.mimeType=a;let o={file:n},s=this.getFileName(e),c=P(`upload/v1beta/files`,o._url),l=await this.fetchUploadUrl(c,n.sizeBytes,n.mimeType,s,o,t?.httpOptions);return r.upload(e,l,this)}async uploadFileToFileSearchStore(e,t,n){let r=this.clientOptions.uploader,i=await r.stat(t),a=String(i.size),o=n?.mimeType??i.type;if(o===void 0||o===``)throw Error(`Can not determine mimeType. Please provide mimeType in the config.`);let s=`upload/v1beta/${e}:uploadToFileSearchStore`,c=this.getFileName(t),l={};n!=null&&kc(n,l);let u=await this.fetchUploadUrl(s,a,o,c,l,n?.httpOptions);return r.uploadToFileSearchStore(t,u,this)}async downloadFile(e){await this.clientOptions.downloader.download(e,this)}async fetchUploadUrl(e,t,n,r,i,a){let o={};o=a||{apiVersion:``,headers:Object.assign({"Content-Type":`application/json`,"X-Goog-Upload-Protocol":`resumable`,"X-Goog-Upload-Command":`start`,"X-Goog-Upload-Header-Content-Length":`${t}`,"X-Goog-Upload-Header-Content-Type":`${n}`},r?{"X-Goog-Upload-File-Name":r}:{})};let s=await this.request({path:e,body:JSON.stringify(i),httpMethod:`POST`,httpOptions:o});if(!s||!s?.headers)throw Error(`Server did not return an HttpResponse or the returned HttpResponse did not have headers.`);let c=s?.headers?.[`x-goog-upload-url`];if(c===void 0)throw Error(`Failed to get upload url. Server did not return the x-google-upload-url in the headers`);return c}};async function Ic(e){if(e===void 0)throw Error(`response is undefined`);if(!e.ok){let t=e.status,n;n=e.headers.get(`content-type`)?.includes(`application/json`)?await e.json():{error:{message:await e.text(),code:e.status,status:e.statusText}};let r=JSON.stringify(n);throw t>=400&&t<600?new xa({message:r,status:t}):Error(r)}}function Lc(e,t){if(!t||Object.keys(t).length===0)return;if(e.body instanceof Blob){console.warn(`includeExtraBodyToRequestInit: extraBody provided but current request body is a Blob. extraBody will be ignored as merging is not supported for Blob bodies.`);return}let n={};if(typeof e.body==`string`&&e.body.length>0)try{let t=JSON.parse(e.body);if(typeof t==`object`&&t&&!Array.isArray(t))n=t;else{console.warn(`includeExtraBodyToRequestInit: Original request body is valid JSON but not a non-array object. Skip applying extraBody to the request body.`);return}}catch{console.warn(`includeExtraBodyToRequestInit: Original request body is not valid JSON. Skip applying extraBody to the request body.`);return}function r(e,t){let n=Object.assign({},e);for(let e in t)if(Object.prototype.hasOwnProperty.call(t,e)){let i=t[e],a=n[e];i&&typeof i==`object`&&!Array.isArray(i)&&a&&typeof a==`object`&&!Array.isArray(a)?n[e]=r(a,i):(a&&i&&typeof a!=typeof i&&console.warn(`includeExtraBodyToRequestInit:deepMerge: Type mismatch for key "${e}". Original type: ${typeof a}, New type: ${typeof i}. Overwriting.`),n[e]=i)}return n}let i=r(n,t);e.body=JSON.stringify(i)}function Rc(e){for(let t of e)if(Bc(t)||typeof t==`object`&&`inputSchema`in t)return!0;return!1}function zc(e){e[Mc]=((e[Mc]??``)+` mcp_used/unknown`).trimStart()}function Bc(e){return typeof e==`object`&&!!e&&e instanceof Hc}function Vc(e){return K(this,arguments,function*(e,t=100){let n,r=0;for(;r<t;){let t=yield G(e.listTools({cursor:n}));for(let e of t.tools)yield yield G(e),r++;if(!t.nextCursor)break;n=t.nextCursor}})}var Hc=class e{constructor(e=[],t){this.mcpTools=[],this.functionNameToMcpClient={},this.mcpClients=e,this.config=t}static create(t,n){return new e(t,n)}async initialize(){var e,t,n,r;if(this.mcpTools.length>0)return;let i={},a=[];for(let l of this.mcpClients)try{for(var o=!0,s=(t=void 0,q(Vc(l))),c;c=await s.next(),e=c.done,!e;o=!0){r=c.value,o=!1;let e=r;a.push(e);let t=e.name;if(i[t])throw Error(`Duplicate function name ${t} found in MCP tools. Please ensure function names are unique.`);i[t]=l}}catch(e){t={error:e}}finally{try{!o&&!e&&(n=s.return)&&await n.call(s)}finally{if(t)throw t.error}}this.mcpTools=a,this.functionNameToMcpClient=i}async tool(){return await this.initialize(),Er(this.mcpTools,this.config)}async callTool(e){await this.initialize();let t=[];for(let n of e)if(n.name in this.functionNameToMcpClient){let e=this.functionNameToMcpClient[n.name],r;this.config.timeout&&(r={timeout:this.config.timeout});let i=await e.callTool({name:n.name,arguments:n.args},void 0,r);t.push({functionResponse:{name:n.name,response:i.isError?{error:i}:i}})}return t}};
110
+ /**
111
+ * @license
112
+ * Copyright 2025 Google LLC
113
+ * SPDX-License-Identifier: Apache-2.0
114
+ */
115
+ async function Uc(e,t,n){let r=new Xn,i;i=n.data instanceof Blob?JSON.parse(await n.data.text()):JSON.parse(n.data),Object.assign(r,i),t(r)}var Wc=class{constructor(e,t,n){this.apiClient=e,this.auth=t,this.webSocketFactory=n}async connect(e){if(this.apiClient.isVertexAI())throw Error(`Live music is not supported for Vertex AI.`);console.warn(`Live music generation is experimental and may change in future versions.`);let t=this.apiClient.getWebsocketBaseUrl(),n=this.apiClient.getApiVersion(),r=qc(this.apiClient.getDefaultHeaders()),i=`${t}/ws/google.ai.generativelanguage.${n}.GenerativeService.BidiGenerateMusic?key=${this.apiClient.getApiKey()}`,a=()=>{},o=new Promise(e=>{a=e}),s=e.callbacks,c=function(){a({})},l=this.apiClient,u={onopen:c,onmessage:e=>{Uc(l,s.onmessage,e)},onerror:s?.onerror??function(e){},onclose:s?.onclose??function(e){}},d=this.webSocketFactory.create(i,Kc(r),u);d.connect(),await o;let f={setup:{model:R(this.apiClient,e.model)}};return d.send(JSON.stringify(f)),new Gc(d,this.apiClient)}},Gc=class{constructor(e,t){this.conn=e,this.apiClient=t}async setWeightedPrompts(e){if(!e.weightedPrompts||Object.keys(e.weightedPrompts).length===0)throw Error(`Weighted prompts must be set and contain at least one entry.`);let t=Ya(e);this.conn.send(JSON.stringify({clientContent:t}))}async setMusicGenerationConfig(e){e.musicGenerationConfig||={};let t=Ja(e);this.conn.send(JSON.stringify(t))}sendPlaybackControl(e){let t={playbackControl:e};this.conn.send(JSON.stringify(t))}play(){this.sendPlaybackControl(Sn.PLAY)}pause(){this.sendPlaybackControl(Sn.PAUSE)}stop(){this.sendPlaybackControl(Sn.STOP)}resetContext(){this.sendPlaybackControl(Sn.RESET_CONTEXT)}close(){this.conn.close()}};function Kc(e){let t={};return e.forEach((e,n)=>{t[n]=e}),t}function qc(e){let t=new Headers;for(let[n,r]of Object.entries(e))t.append(n,r);return t}async function Jc(e,t,n){let r=new Yn,i;i=n.data instanceof Blob?await n.data.text():n.data instanceof ArrayBuffer?new TextDecoder().decode(n.data):n.data;let a=JSON.parse(i);if(e.isVertexAI()){let e=Qa(a);Object.assign(r,e)}else Object.assign(r,a);t(r)}var Yc=class{constructor(e,t,n){this.apiClient=e,this.auth=t,this.webSocketFactory=n,this.music=new Wc(this.apiClient,this.auth,this.webSocketFactory)}async connect(e){if(e.config&&e.config.httpOptions)throw Error(`The Live module does not support httpOptions at request-level in LiveConnectConfig yet. Please use the client-level httpOptions configuration instead.`);let t=this.apiClient.getWebsocketBaseUrl(),n=this.apiClient.getApiVersion(),r,i=this.apiClient.getHeaders();e.config&&e.config.tools&&Rc(e.config.tools)&&zc(i);let a=$c(i);if(this.apiClient.isVertexAI()){let e=this.apiClient.getProject(),i=this.apiClient.getLocation(),o=this.apiClient.getApiKey(),s=!!e&&!!i||!!o;this.apiClient.getCustomBaseUrl()&&!s?r=t:(r=`${t}/ws/google.cloud.aiplatform.${n}.LlmBidiService/BidiGenerateContent`,await this.auth.addAuthHeaders(a,r))}else{let e=this.apiClient.getApiKey(),i=`BidiGenerateContent`,a=`key`;e?.startsWith(`auth_tokens/`)&&(console.warn(`Warning: Ephemeral token support is experimental and may change in future versions.`),n!==`v1alpha`&&console.warn(`Warning: The SDK's ephemeral token support is in v1alpha only. Please use const ai = new GoogleGenAI({apiKey: token.name, httpOptions: { apiVersion: 'v1alpha' }}); before session connection.`),i=`BidiGenerateContentConstrained`,a=`access_token`),r=`${t}/ws/google.ai.generativelanguage.${n}.GenerativeService.${i}?${a}=${e}`}let o=()=>{},s=new Promise(e=>{o=e}),c=e.callbacks,l=function(){var e;(e=c?.onopen)==null||e.call(c),o({})},u=this.apiClient,d={onopen:l,onmessage:e=>{Jc(u,c.onmessage,e)},onerror:c?.onerror??function(e){},onclose:c?.onclose??function(e){}},f=this.webSocketFactory.create(r,Qc(a),d);f.connect(),await s;let p=R(this.apiClient,e.model);if(this.apiClient.isVertexAI()&&p.startsWith(`publishers/`)){let e=this.apiClient.getProject(),t=this.apiClient.getLocation();e&&t&&(p=`projects/${e}/locations/${t}/`+p)}let m={};this.apiClient.isVertexAI()&&e.config?.responseModalities===void 0&&(e.config===void 0?e.config={responseModalities:[Ft.AUDIO]}:e.config.responseModalities=[Ft.AUDIO]),e.config?.generationConfig&&console.warn("Setting `LiveConnectConfig.generation_config` is deprecated, please set the fields on `LiveConnectConfig` directly. This will become an error in a future version (not before Q3 2025).");let h=e.config?.tools??[],g=[];for(let e of h)if(this.isCallableTool(e)){let t=e;g.push(await t.tool())}else g.push(e);g.length>0&&(e.config.tools=g);let _={model:p,config:e.config,callbacks:e.callbacks};return m=this.apiClient.isVertexAI()?qa(this.apiClient,_):Ka(this.apiClient,_),delete m.config,f.send(JSON.stringify(m)),new Zc(f,this.apiClient)}isCallableTool(e){return`callTool`in e&&typeof e.callTool==`function`}};const Xc={turnComplete:!0};var Zc=class{constructor(e,t){this.conn=e,this.apiClient=t}tLiveClientContent(e,t){if(t.turns!==null&&t.turns!==void 0){let n=[];try{n=B(t.turns),e.isVertexAI()||(n=n.map(e=>go(e)))}catch{throw Error(`Failed to parse client content "turns", type: '${typeof t.turns}'`)}return{clientContent:{turns:n,turnComplete:t.turnComplete}}}return{clientContent:{turnComplete:t.turnComplete}}}tLiveClienttToolResponse(e,t){let n=[];if(t.functionResponses==null||(n=Array.isArray(t.functionResponses)?t.functionResponses:[t.functionResponses],n.length===0))throw Error(`functionResponses is required.`);for(let t of n){if(typeof t!=`object`||!t||!(`name`in t)||!(`response`in t))throw Error(`Could not parse function response, type '${typeof t}'.`);if(!e.isVertexAI()&&!(`id`in t))throw Error("FunctionResponse request must have an `id` field from the response of a ToolCall.FunctionalCalls in Google AI.")}return{toolResponse:{functionResponses:n}}}sendClientContent(e){e=Object.assign(Object.assign({},Xc),e);let t=this.tLiveClientContent(this.apiClient,e);this.conn.send(JSON.stringify(t))}sendRealtimeInput(e){let t={};t=this.apiClient.isVertexAI()?{realtimeInput:Za(e)}:{realtimeInput:Xa(e)},this.conn.send(JSON.stringify(t))}sendToolResponse(e){if(e.functionResponses==null)throw Error(`Tool response parameters are required.`);let t=this.tLiveClienttToolResponse(this.apiClient,e);this.conn.send(JSON.stringify(t))}close(){this.conn.close()}};function Qc(e){let t={};return e.forEach((e,n)=>{t[n]=e}),t}function $c(e){let t=new Headers;for(let[n,r]of Object.entries(e))t.append(n,r);return t}function el(e){if(e?.automaticFunctionCalling?.disable)return!0;let t=!1;for(let n of e?.tools??[])if(tl(n)){t=!0;break}if(!t)return!0;let n=e?.automaticFunctionCalling?.maximumRemoteCalls;return n&&(n<0||!Number.isInteger(n))||n==0?(console.warn(`Invalid maximumRemoteCalls value provided for automatic function calling. Disabled automatic function calling. Please provide a valid integer value greater than 0. maximumRemoteCalls provided:`,n),!0):!1}function tl(e){return`callTool`in e&&typeof e.callTool==`function`}function nl(e){return(e.config?.tools)?.some(e=>tl(e))??!1}function rl(e){let t=[];return e?.config?.tools&&e.config.tools.forEach((e,n)=>{if(tl(e))return;let r=e;r.functionDeclarations&&r.functionDeclarations.length>0&&t.push(n)}),t}function il(e){return!e?.automaticFunctionCalling?.ignoreCallHistory}
116
+ /**
117
+ * @license
118
+ * Copyright 2025 Google LLC
119
+ * SPDX-License-Identifier: Apache-2.0
120
+ */
121
+ var al=class extends N{constructor(e){super(),this.apiClient=e,this.embedContent=async e=>{if(!this.apiClient.isVertexAI())return e.model.includes(`gemini-embedding-2`)&&(e.contents=B(e.contents)),await this.embedContentInternal(e);if(e.model.includes(`gemini`)&&e.model!==`gemini-embedding-001`||e.model.includes(`maas`)){let t=B(e.contents);if(t.length>1)throw Error(`The embedContent API for this model only supports one content at a time.`);let n=Object.assign(Object.assign({},e),{content:t[0],embeddingApiType:Zt.EMBED_CONTENT});return await this.embedContentInternal(n)}else{let t=Object.assign(Object.assign({},e),{embeddingApiType:Zt.PREDICT});return await this.embedContentInternal(t)}},this.generateContent=async e=>{let t=await this.processParamsMaybeAddMcpUsage(e);if(this.maybeMoveToResponseJsonSchem(e),!nl(e)||el(e.config))return await this.generateContentInternal(t);let n=rl(e);if(n.length>0){let e=n.map(e=>`tools[${e}]`).join(`, `);throw Error(`Automatic function calling with CallableTools (or MCP objects) and basic FunctionDeclarations is not yet supported. Incompatible tools found at ${e}.`)}let r,i,a=B(t.contents),o=t.config?.automaticFunctionCalling?.maximumRemoteCalls??10,s=0;for(;s<o&&(r=await this.generateContentInternal(t),!(!r.functionCalls||r.functionCalls.length===0));){let n=r.candidates[0].content,o=[];for(let t of e.config?.tools??[])if(tl(t)){let e=await t.callTool(r.functionCalls);o.push(...e)}s++,i={role:`user`,parts:o},t.contents=B(t.contents),t.contents.push(n),t.contents.push(i),il(t.config)&&(a.push(n),a.push(i))}return il(t.config)&&(r.automaticFunctionCallingHistory=a),r},this.generateContentStream=async e=>{if(this.maybeMoveToResponseJsonSchem(e),el(e.config)){let t=await this.processParamsMaybeAddMcpUsage(e);return await this.generateContentStreamInternal(t)}let t=rl(e);if(t.length>0){let e=t.map(e=>`tools[${e}]`).join(`, `);throw Error(`Incompatible tools found at ${e}. Automatic function calling with CallableTools (or MCP objects) and basic FunctionDeclarations" is not yet supported.`)}let n=e?.config?.toolConfig?.functionCallingConfig?.streamFunctionCallArguments,r=e?.config?.automaticFunctionCalling?.disable;if(n&&!r)throw Error(`Running in streaming mode with 'streamFunctionCallArguments' enabled, this feature is not compatible with automatic function calling (AFC). Please set 'config.automaticFunctionCalling.disable' to true to disable AFC or leave 'config.toolConfig.functionCallingConfig.streamFunctionCallArguments' to be undefined or set to false to disable streaming function call arguments feature.`);return await this.processAfcStream(e)},this.generateImages=async e=>await this.generateImagesInternal(e).then(e=>{let t,n=[];if(e?.generatedImages)for(let r of e.generatedImages)r&&r?.safetyAttributes&&r?.safetyAttributes?.contentType===`Positive Prompt`?t=r?.safetyAttributes:n.push(r);let r;return r=t?{generatedImages:n,positivePromptSafetyAttributes:t,sdkHttpResponse:e.sdkHttpResponse}:{generatedImages:n,sdkHttpResponse:e.sdkHttpResponse},r}),this.list=async e=>{let t={config:Object.assign(Object.assign({},{queryBase:!0}),e?.config)};if(this.apiClient.isVertexAI()&&!t.config.queryBase){if(t.config?.filter)throw Error(`Filtering tuned models list for Vertex AI is not currently supported`);t.config.filter=`labels.tune-type:*`}return new ki(U.PAGED_ITEM_MODELS,e=>this.listInternal(e),await this.listInternal(t),t)},this.editImage=async e=>{let t={model:e.model,prompt:e.prompt,referenceImages:[],config:e.config};return e.referenceImages&&e.referenceImages&&(t.referenceImages=e.referenceImages.map(e=>e.toReferenceImageAPI())),await this.editImageInternal(t)},this.upscaleImage=async e=>{let t={numberOfImages:1,mode:`upscale`};e.config&&(t=Object.assign(Object.assign({},t),e.config));let n={model:e.model,image:e.image,upscaleFactor:e.upscaleFactor,config:t};return await this.upscaleImageInternal(n)},this.generateVideos=async e=>{if((e.prompt||e.image||e.video)&&e.source)throw Error(`Source and prompt/image/video are mutually exclusive. Please only use source.`);return this.apiClient.isVertexAI()||(e.video?.uri&&e.video?.videoBytes?e.video={uri:e.video.uri,mimeType:e.video.mimeType}:e.source?.video?.uri&&e.source?.video?.videoBytes&&(e.source.video={uri:e.source.video.uri,mimeType:e.source.video.mimeType})),await this.generateVideosInternal(e)}}maybeMoveToResponseJsonSchem(e){e.config&&e.config.responseSchema&&(e.config.responseJsonSchema||Object.keys(e.config.responseSchema).includes(`$schema`)&&(e.config.responseJsonSchema=e.config.responseSchema,delete e.config.responseSchema))}async processParamsMaybeAddMcpUsage(e){let t=e.config?.tools;if(!t)return e;let n=await Promise.all(t.map(async e=>tl(e)?await e.tool():e)),r={model:e.model,contents:e.contents,config:Object.assign(Object.assign({},e.config),{tools:n})};if(r.config.tools=n,e.config&&e.config.tools&&Rc(e.config.tools)){let t=e.config.httpOptions?.headers??{},n=Object.assign({},t);Object.keys(n).length===0&&(n=this.apiClient.getDefaultHeaders()),zc(n),r.config.httpOptions=Object.assign(Object.assign({},e.config.httpOptions),{headers:n})}return r}async initAfcToolsMap(e){let t=new Map;for(let n of e.config?.tools??[])if(tl(n)){let e=n,r=await e.tool();for(let n of r.functionDeclarations??[]){if(!n.name)throw Error(`Function declaration name is required.`);if(t.has(n.name))throw Error(`Duplicate tool declaration name: ${n.name}`);t.set(n.name,e)}}return t}async processAfcStream(e){let t=e.config?.automaticFunctionCalling?.maximumRemoteCalls??10,n=!1,r=0,i=await this.initAfcToolsMap(e);return(function(e,i,a){return K(this,arguments,function*(){for(var o,s,c,l;r<t;){n&&=(r++,!1);let p=yield G(e.processParamsMaybeAddMcpUsage(a)),m=yield G(e.generateContentStreamInternal(p)),h=[],g=[];try{for(var u=!0,d=(s=void 0,q(m)),f;f=yield G(d.next()),o=f.done,!o;u=!0){l=f.value,u=!1;let e=l;if(yield yield G(e),e.candidates&&e.candidates[0]?.content){g.push(e.candidates[0].content);for(let n of e.candidates[0].content.parts??[])if(r<t&&n.functionCall){if(!n.functionCall.name)throw Error(`Function call name was not returned by the model.`);if(i.has(n.functionCall.name)){let e=yield G(i.get(n.functionCall.name).callTool([n.functionCall]));h.push(...e)}else throw Error(`Automatic function calling was requested, but not all the tools the model used implement the CallableTool interface. Available tools: ${i.keys()}, mising tool: ${n.functionCall.name}`)}}}}catch(e){s={error:e}}finally{try{!u&&!o&&(c=d.return)&&(yield G(c.call(d)))}finally{if(s)throw s.error}}if(h.length>0){n=!0;let e=new wn;e.candidates=[{content:{role:`user`,parts:h}}],yield yield G(e);let t=[];t.push(...g),t.push({role:`user`,parts:h}),a.contents=B(a.contents).concat(t)}else break}})})(this,i,e)}async generateContentInternal(e){let t,n=``,r={};if(this.apiClient.isVertexAI()){let i=Ko(this.apiClient,e);return n=P(`{model}:generateContent`,i._url),r=i._query,delete i._url,delete i._query,t=this.apiClient.request({path:n,queryParams:r,body:JSON.stringify(i),httpMethod:`POST`,httpOptions:e.config?.httpOptions,abortSignal:e.config?.abortSignal}).then(e=>e.json().then(t=>{let n=t;return n.sdkHttpResponse={headers:e.headers},n})),t.then(e=>{let t=Jo(e),n=new wn;return Object.assign(n,t),n})}else{let i=Go(this.apiClient,e);return n=P(`{model}:generateContent`,i._url),r=i._query,delete i._url,delete i._query,t=this.apiClient.request({path:n,queryParams:r,body:JSON.stringify(i),httpMethod:`POST`,httpOptions:e.config?.httpOptions,abortSignal:e.config?.abortSignal}).then(e=>e.json().then(t=>{let n=t;return n.sdkHttpResponse={headers:e.headers},n})),t.then(e=>{let t=qo(e),n=new wn;return Object.assign(n,t),n})}}async generateContentStreamInternal(e){let t,n=``,r={};if(this.apiClient.isVertexAI()){let i=Ko(this.apiClient,e);return n=P(`{model}:streamGenerateContent?alt=sse`,i._url),r=i._query,delete i._url,delete i._query,t=this.apiClient.requestStream({path:n,queryParams:r,body:JSON.stringify(i),httpMethod:`POST`,httpOptions:e.config?.httpOptions,abortSignal:e.config?.abortSignal}),t.then(function(t){return K(this,arguments,function*(){var n,r,i,a;try{for(var o=!0,s=q(t),c;c=yield G(s.next()),n=c.done,!n;o=!0){a=c.value,o=!1;let t=a,n=Jo(yield G(t.json()),e);n.sdkHttpResponse={headers:t.headers};let r=new wn;Object.assign(r,n),yield yield G(r)}}catch(e){r={error:e}}finally{try{!o&&!n&&(i=s.return)&&(yield G(i.call(s)))}finally{if(r)throw r.error}}})})}else{let i=Go(this.apiClient,e);return n=P(`{model}:streamGenerateContent?alt=sse`,i._url),r=i._query,delete i._url,delete i._query,t=this.apiClient.requestStream({path:n,queryParams:r,body:JSON.stringify(i),httpMethod:`POST`,httpOptions:e.config?.httpOptions,abortSignal:e.config?.abortSignal}),t.then(function(t){return K(this,arguments,function*(){var n,r,i,a;try{for(var o=!0,s=q(t),c;c=yield G(s.next()),n=c.done,!n;o=!0){a=c.value,o=!1;let t=a,n=qo(yield G(t.json()),e);n.sdkHttpResponse={headers:t.headers};let r=new wn;Object.assign(r,n),yield yield G(r)}}catch(e){r={error:e}}finally{try{!o&&!n&&(i=s.return)&&(yield G(i.call(s)))}finally{if(r)throw r.error}}})})}}async embedContentInternal(e){let t,n=``,r={};if(this.apiClient.isVertexAI()){let i=Fo(this.apiClient,e,e);return n=P(Mr(e.model)?`{model}:embedContent`:`{model}:predict`,i._url),r=i._query,delete i._url,delete i._query,t=this.apiClient.request({path:n,queryParams:r,body:JSON.stringify(i),httpMethod:`POST`,httpOptions:e.config?.httpOptions,abortSignal:e.config?.abortSignal}).then(e=>e.json().then(t=>{let n=t;return n.sdkHttpResponse={headers:e.headers},n})),t.then(t=>{let n=Lo(t,e),r=new Tn;return Object.assign(r,n),r})}else{let i=Po(this.apiClient,e);return n=P(`{model}:batchEmbedContents`,i._url),r=i._query,delete i._url,delete i._query,t=this.apiClient.request({path:n,queryParams:r,body:JSON.stringify(i),httpMethod:`POST`,httpOptions:e.config?.httpOptions,abortSignal:e.config?.abortSignal}).then(e=>e.json().then(t=>{let n=t;return n.sdkHttpResponse={headers:e.headers},n})),t.then(e=>{let t=Io(e),n=new Tn;return Object.assign(n,t),n})}}async generateImagesInternal(e){let t,n=``,r={};if(this.apiClient.isVertexAI()){let i=Qo(this.apiClient,e);return n=P(`{model}:predict`,i._url),r=i._query,delete i._url,delete i._query,t=this.apiClient.request({path:n,queryParams:r,body:JSON.stringify(i),httpMethod:`POST`,httpOptions:e.config?.httpOptions,abortSignal:e.config?.abortSignal}).then(e=>e.json().then(t=>{let n=t;return n.sdkHttpResponse={headers:e.headers},n})),t.then(e=>{let t=es(e),n=new En;return Object.assign(n,t),n})}else{let i=Zo(this.apiClient,e);return n=P(`{model}:predict`,i._url),r=i._query,delete i._url,delete i._query,t=this.apiClient.request({path:n,queryParams:r,body:JSON.stringify(i),httpMethod:`POST`,httpOptions:e.config?.httpOptions,abortSignal:e.config?.abortSignal}).then(e=>e.json().then(t=>{let n=t;return n.sdkHttpResponse={headers:e.headers},n})),t.then(e=>{let t=$o(e),n=new En;return Object.assign(n,t),n})}}async editImageInternal(e){let t,n=``,r={};if(this.apiClient.isVertexAI()){let i=Ao(this.apiClient,e);return n=P(`{model}:predict`,i._url),r=i._query,delete i._url,delete i._query,t=this.apiClient.request({path:n,queryParams:r,body:JSON.stringify(i),httpMethod:`POST`,httpOptions:e.config?.httpOptions,abortSignal:e.config?.abortSignal}).then(e=>e.json().then(t=>{let n=t;return n.sdkHttpResponse={headers:e.headers},n})),t.then(e=>{let t=jo(e),n=new Dn;return Object.assign(n,t),n})}else throw Error(`This method is only supported by the Vertex AI.`)}async upscaleImageInternal(e){let t,n=``,r={};if(this.apiClient.isVertexAI()){let i=cc(this.apiClient,e);return n=P(`{model}:predict`,i._url),r=i._query,delete i._url,delete i._query,t=this.apiClient.request({path:n,queryParams:r,body:JSON.stringify(i),httpMethod:`POST`,httpOptions:e.config?.httpOptions,abortSignal:e.config?.abortSignal}).then(e=>e.json().then(t=>{let n=t;return n.sdkHttpResponse={headers:e.headers},n})),t.then(e=>{let t=lc(e),n=new On;return Object.assign(n,t),n})}else throw Error(`This method is only supported by the Vertex AI.`)}async recontextImage(e){let t,n=``,r={};if(this.apiClient.isVertexAI()){let i=zs(this.apiClient,e);return n=P(`{model}:predict`,i._url),r=i._query,delete i._url,delete i._query,t=this.apiClient.request({path:n,queryParams:r,body:JSON.stringify(i),httpMethod:`POST`,httpOptions:e.config?.httpOptions,abortSignal:e.config?.abortSignal}).then(e=>e.json()),t.then(e=>{let t=Bs(e),n=new kn;return Object.assign(n,t),n})}else throw Error(`This method is only supported by the Vertex AI.`)}async segmentImage(e){let t,n=``,r={};if(this.apiClient.isVertexAI()){let i=Js(this.apiClient,e);return n=P(`{model}:predict`,i._url),r=i._query,delete i._url,delete i._query,t=this.apiClient.request({path:n,queryParams:r,body:JSON.stringify(i),httpMethod:`POST`,httpOptions:e.config?.httpOptions,abortSignal:e.config?.abortSignal}).then(e=>e.json()),t.then(e=>{let t=Ys(e),n=new An;return Object.assign(n,t),n})}else throw Error(`This method is only supported by the Vertex AI.`)}async get(e){let t,n=``,r={};if(this.apiClient.isVertexAI()){let i=vs(this.apiClient,e);return n=P(`{name}`,i._url),r=i._query,delete i._url,delete i._query,t=this.apiClient.request({path:n,queryParams:r,body:JSON.stringify(i),httpMethod:`GET`,httpOptions:e.config?.httpOptions,abortSignal:e.config?.abortSignal}).then(e=>e.json()),t.then(e=>Ps(e))}else{let i=_s(this.apiClient,e);return n=P(`{name}`,i._url),r=i._query,delete i._url,delete i._query,t=this.apiClient.request({path:n,queryParams:r,body:JSON.stringify(i),httpMethod:`GET`,httpOptions:e.config?.httpOptions,abortSignal:e.config?.abortSignal}).then(e=>e.json()),t.then(e=>Ns(e))}}async listInternal(e){let t,n=``,r={};if(this.apiClient.isVertexAI()){let i=ks(this.apiClient,e);return n=P(`{models_url}`,i._url),r=i._query,delete i._url,delete i._query,t=this.apiClient.request({path:n,queryParams:r,body:JSON.stringify(i),httpMethod:`GET`,httpOptions:e.config?.httpOptions,abortSignal:e.config?.abortSignal}).then(e=>e.json().then(t=>{let n=t;return n.sdkHttpResponse={headers:e.headers},n})),t.then(e=>{let t=js(e),n=new jn;return Object.assign(n,t),n})}else{let i=Os(this.apiClient,e);return n=P(`{models_url}`,i._url),r=i._query,delete i._url,delete i._query,t=this.apiClient.request({path:n,queryParams:r,body:JSON.stringify(i),httpMethod:`GET`,httpOptions:e.config?.httpOptions,abortSignal:e.config?.abortSignal}).then(e=>e.json().then(t=>{let n=t;return n.sdkHttpResponse={headers:e.headers},n})),t.then(e=>{let t=As(e),n=new jn;return Object.assign(n,t),n})}}async update(e){let t,n=``,r={};if(this.apiClient.isVertexAI()){let i=oc(this.apiClient,e);return n=P(`{model}`,i._url),r=i._query,delete i._url,delete i._query,t=this.apiClient.request({path:n,queryParams:r,body:JSON.stringify(i),httpMethod:`PATCH`,httpOptions:e.config?.httpOptions,abortSignal:e.config?.abortSignal}).then(e=>e.json()),t.then(e=>Ps(e))}else{let i=ac(this.apiClient,e);return n=P(`{name}`,i._url),r=i._query,delete i._url,delete i._query,t=this.apiClient.request({path:n,queryParams:r,body:JSON.stringify(i),httpMethod:`PATCH`,httpOptions:e.config?.httpOptions,abortSignal:e.config?.abortSignal}).then(e=>e.json()),t.then(e=>Ns(e))}}async delete(e){let t,n=``,r={};if(this.apiClient.isVertexAI()){let i=Eo(this.apiClient,e);return n=P(`{name}`,i._url),r=i._query,delete i._url,delete i._query,t=this.apiClient.request({path:n,queryParams:r,body:JSON.stringify(i),httpMethod:`DELETE`,httpOptions:e.config?.httpOptions,abortSignal:e.config?.abortSignal}).then(e=>e.json().then(t=>{let n=t;return n.sdkHttpResponse={headers:e.headers},n})),t.then(e=>{let t=Oo(e),n=new Mn;return Object.assign(n,t),n})}else{let i=To(this.apiClient,e);return n=P(`{name}`,i._url),r=i._query,delete i._url,delete i._query,t=this.apiClient.request({path:n,queryParams:r,body:JSON.stringify(i),httpMethod:`DELETE`,httpOptions:e.config?.httpOptions,abortSignal:e.config?.abortSignal}).then(e=>e.json().then(t=>{let n=t;return n.sdkHttpResponse={headers:e.headers},n})),t.then(e=>{let t=Do(e),n=new Mn;return Object.assign(n,t),n})}}async countTokens(e){let t,n=``,r={};if(this.apiClient.isVertexAI()){let i=So(this.apiClient,e);return n=P(`{model}:countTokens`,i._url),r=i._query,delete i._url,delete i._query,t=this.apiClient.request({path:n,queryParams:r,body:JSON.stringify(i),httpMethod:`POST`,httpOptions:e.config?.httpOptions,abortSignal:e.config?.abortSignal}).then(e=>e.json().then(t=>{let n=t;return n.sdkHttpResponse={headers:e.headers},n})),t.then(e=>{let t=wo(e),n=new Nn;return Object.assign(n,t),n})}else{let i=xo(this.apiClient,e);return n=P(`{model}:countTokens`,i._url),r=i._query,delete i._url,delete i._query,t=this.apiClient.request({path:n,queryParams:r,body:JSON.stringify(i),httpMethod:`POST`,httpOptions:e.config?.httpOptions,abortSignal:e.config?.abortSignal}).then(e=>e.json().then(t=>{let n=t;return n.sdkHttpResponse={headers:e.headers},n})),t.then(e=>{let t=Co(e),n=new Nn;return Object.assign(n,t),n})}}async computeTokens(e){let t,n=``,r={};if(this.apiClient.isVertexAI()){let i=fo(this.apiClient,e);return n=P(`{model}:computeTokens`,i._url),r=i._query,delete i._url,delete i._query,t=this.apiClient.request({path:n,queryParams:r,body:JSON.stringify(i),httpMethod:`POST`,httpOptions:e.config?.httpOptions,abortSignal:e.config?.abortSignal}).then(e=>e.json().then(t=>{let n=t;return n.sdkHttpResponse={headers:e.headers},n})),t.then(e=>{let t=po(e),n=new Pn;return Object.assign(n,t),n})}else throw Error(`This method is only supported by the Vertex AI.`)}async generateVideosInternal(e){let t,n=``,r={};if(this.apiClient.isVertexAI()){let i=os(this.apiClient,e);return n=P(`{model}:predictLongRunning`,i._url),r=i._query,delete i._url,delete i._query,t=this.apiClient.request({path:n,queryParams:r,body:JSON.stringify(i),httpMethod:`POST`,httpOptions:e.config?.httpOptions,abortSignal:e.config?.abortSignal}).then(e=>e.json()),t.then(e=>{let t=is(e),n=new Fn;return Object.assign(n,t),n})}else{let i=as(this.apiClient,e);return n=P(`{model}:predictLongRunning`,i._url),r=i._query,delete i._url,delete i._query,t=this.apiClient.request({path:n,queryParams:r,body:JSON.stringify(i),httpMethod:`POST`,httpOptions:e.config?.httpOptions,abortSignal:e.config?.abortSignal}).then(e=>e.json()),t.then(e=>{let t=rs(e),n=new Fn;return Object.assign(n,t),n})}}},ol=class extends N{constructor(e){super(),this.apiClient=e}async getVideosOperation(e){let t=e.operation,n=e.config;if(t.name===void 0||t.name===``)throw Error(`Operation name is required.`);if(this.apiClient.isVertexAI()){let e=t.name.split(`/operations/`)[0],r;n&&`httpOptions`in n&&(r=n.httpOptions);let i=await this.fetchPredictVideosOperationInternal({operationName:t.name,resourceName:e,config:{httpOptions:r}});return t._fromAPIResponse({apiResponse:i,_isVertexAI:!0})}else{let e=await this.getVideosOperationInternal({operationName:t.name,config:n});return t._fromAPIResponse({apiResponse:e,_isVertexAI:!1})}}async get(e){let t=e.operation,n=e.config;if(t.name===void 0||t.name===``)throw Error(`Operation name is required.`);if(this.apiClient.isVertexAI()){let e=t.name.split(`/operations/`)[0],r;n&&`httpOptions`in n&&(r=n.httpOptions);let i=await this.fetchPredictVideosOperationInternal({operationName:t.name,resourceName:e,config:{httpOptions:r}});return t._fromAPIResponse({apiResponse:i,_isVertexAI:!0})}else{let e=await this.getVideosOperationInternal({operationName:t.name,config:n});return t._fromAPIResponse({apiResponse:e,_isVertexAI:!1})}}async getVideosOperationInternal(e){let t,n=``,r={};if(this.apiClient.isVertexAI()){let i=at(e);return n=P(`{operationName}`,i._url),r=i._query,delete i._url,delete i._query,t=this.apiClient.request({path:n,queryParams:r,body:JSON.stringify(i),httpMethod:`GET`,httpOptions:e.config?.httpOptions,abortSignal:e.config?.abortSignal}).then(e=>e.json()),t}else{let i=it(e);return n=P(`{operationName}`,i._url),r=i._query,delete i._url,delete i._query,t=this.apiClient.request({path:n,queryParams:r,body:JSON.stringify(i),httpMethod:`GET`,httpOptions:e.config?.httpOptions,abortSignal:e.config?.abortSignal}).then(e=>e.json()),t}}async fetchPredictVideosOperationInternal(e){let t,n=``,r={};if(this.apiClient.isVertexAI()){let i=Ze(e);return n=P(`{resourceName}:fetchPredictOperation`,i._url),r=i._query,delete i._url,delete i._query,t=this.apiClient.request({path:n,queryParams:r,body:JSON.stringify(i),httpMethod:`POST`,httpOptions:e.config?.httpOptions,abortSignal:e.config?.abortSignal}).then(e=>e.json()),t}else throw Error(`This method is only supported by the Vertex AI.`)}};
122
+ /**
123
+ * @license
124
+ * Copyright 2025 Google LLC
125
+ * SPDX-License-Identifier: Apache-2.0
126
+ */
127
+ function sl(e){let t={};if(I(e,[`languageCodes`])!==void 0)throw Error(`languageCodes parameter is not supported in Gemini API.`);return t}function cl(e){let t={},n=I(e,[`apiKey`]);if(n!=null&&F(t,[`apiKey`],n),I(e,[`apiKeyConfig`])!==void 0)throw Error(`apiKeyConfig parameter is not supported in Gemini API.`);if(I(e,[`authType`])!==void 0)throw Error(`authType parameter is not supported in Gemini API.`);if(I(e,[`googleServiceAccountConfig`])!==void 0)throw Error(`googleServiceAccountConfig parameter is not supported in Gemini API.`);if(I(e,[`httpBasicAuthConfig`])!==void 0)throw Error(`httpBasicAuthConfig parameter is not supported in Gemini API.`);if(I(e,[`oauthConfig`])!==void 0)throw Error(`oauthConfig parameter is not supported in Gemini API.`);if(I(e,[`oidcConfig`])!==void 0)throw Error(`oidcConfig parameter is not supported in Gemini API.`);return t}function ll(e){let t={},n=I(e,[`data`]);if(n!=null&&F(t,[`data`],n),I(e,[`displayName`])!==void 0)throw Error(`displayName parameter is not supported in Gemini API.`);let r=I(e,[`mimeType`]);return r!=null&&F(t,[`mimeType`],r),t}function ul(e){let t={},n=I(e,[`parts`]);if(n!=null){let e=n;Array.isArray(e)&&(e=e.map(e=>yl(e))),F(t,[`parts`],e)}let r=I(e,[`role`]);return r!=null&&F(t,[`role`],r),t}function dl(e,t,n){let r={},i=I(t,[`expireTime`]);n!==void 0&&i!=null&&F(n,[`expireTime`],i);let a=I(t,[`newSessionExpireTime`]);n!==void 0&&a!=null&&F(n,[`newSessionExpireTime`],a);let o=I(t,[`uses`]);n!==void 0&&o!=null&&F(n,[`uses`],o);let s=I(t,[`liveConnectConstraints`]);n!==void 0&&s!=null&&F(n,[`bidiGenerateContentSetup`],vl(e,s));let c=I(t,[`lockAdditionalFields`]);return n!==void 0&&c!=null&&F(n,[`fieldMask`],c),r}function fl(e,t){let n={},r=I(t,[`config`]);return r!=null&&F(n,[`config`],dl(e,r,n)),n}function pl(e){let t={};if(I(e,[`displayName`])!==void 0)throw Error(`displayName parameter is not supported in Gemini API.`);let n=I(e,[`fileUri`]);n!=null&&F(t,[`fileUri`],n);let r=I(e,[`mimeType`]);return r!=null&&F(t,[`mimeType`],r),t}function ml(e){let t={},n=I(e,[`id`]);n!=null&&F(t,[`id`],n);let r=I(e,[`args`]);r!=null&&F(t,[`args`],r);let i=I(e,[`name`]);if(i!=null&&F(t,[`name`],i),I(e,[`partialArgs`])!==void 0)throw Error(`partialArgs parameter is not supported in Gemini API.`);if(I(e,[`willContinue`])!==void 0)throw Error(`willContinue parameter is not supported in Gemini API.`);return t}function hl(e){let t={},n=I(e,[`authConfig`]);n!=null&&F(t,[`authConfig`],cl(n));let r=I(e,[`enableWidget`]);return r!=null&&F(t,[`enableWidget`],r),t}function gl(e){let t={},n=I(e,[`searchTypes`]);if(n!=null&&F(t,[`searchTypes`],n),I(e,[`blockingConfidence`])!==void 0)throw Error(`blockingConfidence parameter is not supported in Gemini API.`);if(I(e,[`excludeDomains`])!==void 0)throw Error(`excludeDomains parameter is not supported in Gemini API.`);let r=I(e,[`timeRangeFilter`]);return r!=null&&F(t,[`timeRangeFilter`],r),t}function _l(e,t){let n={},r=I(e,[`generationConfig`]);t!==void 0&&r!=null&&F(t,[`setup`,`generationConfig`],r);let i=I(e,[`responseModalities`]);t!==void 0&&i!=null&&F(t,[`setup`,`generationConfig`,`responseModalities`],i);let a=I(e,[`temperature`]);t!==void 0&&a!=null&&F(t,[`setup`,`generationConfig`,`temperature`],a);let o=I(e,[`topP`]);t!==void 0&&o!=null&&F(t,[`setup`,`generationConfig`,`topP`],o);let s=I(e,[`topK`]);t!==void 0&&s!=null&&F(t,[`setup`,`generationConfig`,`topK`],s);let c=I(e,[`maxOutputTokens`]);t!==void 0&&c!=null&&F(t,[`setup`,`generationConfig`,`maxOutputTokens`],c);let l=I(e,[`mediaResolution`]);t!==void 0&&l!=null&&F(t,[`setup`,`generationConfig`,`mediaResolution`],l);let u=I(e,[`seed`]);t!==void 0&&u!=null&&F(t,[`setup`,`generationConfig`,`seed`],u);let d=I(e,[`speechConfig`]);t!==void 0&&d!=null&&F(t,[`setup`,`generationConfig`,`speechConfig`],pr(d));let f=I(e,[`thinkingConfig`]);t!==void 0&&f!=null&&F(t,[`setup`,`generationConfig`,`thinkingConfig`],f);let p=I(e,[`enableAffectiveDialog`]);t!==void 0&&p!=null&&F(t,[`setup`,`generationConfig`,`enableAffectiveDialog`],p);let m=I(e,[`systemInstruction`]);t!==void 0&&m!=null&&F(t,[`setup`,`systemInstruction`],ul(z(m)));let h=I(e,[`tools`]);if(t!==void 0&&h!=null){let e=hr(h);Array.isArray(e)&&(e=e.map(e=>Sl(mr(e)))),F(t,[`setup`,`tools`],e)}let g=I(e,[`sessionResumption`]);t!==void 0&&g!=null&&F(t,[`setup`,`sessionResumption`],xl(g));let _=I(e,[`inputAudioTranscription`]);t!==void 0&&_!=null&&F(t,[`setup`,`inputAudioTranscription`],sl(_));let v=I(e,[`outputAudioTranscription`]);t!==void 0&&v!=null&&F(t,[`setup`,`outputAudioTranscription`],sl(v));let y=I(e,[`realtimeInputConfig`]);t!==void 0&&y!=null&&F(t,[`setup`,`realtimeInputConfig`],y);let b=I(e,[`contextWindowCompression`]);t!==void 0&&b!=null&&F(t,[`setup`,`contextWindowCompression`],b);let x=I(e,[`proactivity`]);if(t!==void 0&&x!=null&&F(t,[`setup`,`proactivity`],x),I(e,[`explicitVadSignal`])!==void 0)throw Error(`explicitVadSignal parameter is not supported in Gemini API.`);let S=I(e,[`avatarConfig`]);t!==void 0&&S!=null&&F(t,[`setup`,`avatarConfig`],S);let C=I(e,[`safetySettings`]);if(t!==void 0&&C!=null){let e=C;Array.isArray(e)&&(e=e.map(e=>bl(e))),F(t,[`setup`,`safetySettings`],e)}return n}function vl(e,t){let n={},r=I(t,[`model`]);r!=null&&F(n,[`setup`,`model`],R(e,r));let i=I(t,[`config`]);return i!=null&&F(n,[`config`],_l(i,n)),n}function yl(e){let t={},n=I(e,[`mediaResolution`]);n!=null&&F(t,[`mediaResolution`],n);let r=I(e,[`codeExecutionResult`]);r!=null&&F(t,[`codeExecutionResult`],r);let i=I(e,[`executableCode`]);i!=null&&F(t,[`executableCode`],i);let a=I(e,[`fileData`]);a!=null&&F(t,[`fileData`],pl(a));let o=I(e,[`functionCall`]);o!=null&&F(t,[`functionCall`],ml(o));let s=I(e,[`functionResponse`]);s!=null&&F(t,[`functionResponse`],s);let c=I(e,[`inlineData`]);c!=null&&F(t,[`inlineData`],ll(c));let l=I(e,[`text`]);l!=null&&F(t,[`text`],l);let u=I(e,[`thought`]);u!=null&&F(t,[`thought`],u);let d=I(e,[`thoughtSignature`]);d!=null&&F(t,[`thoughtSignature`],d);let f=I(e,[`videoMetadata`]);f!=null&&F(t,[`videoMetadata`],f);let p=I(e,[`toolCall`]);p!=null&&F(t,[`toolCall`],p);let m=I(e,[`toolResponse`]);m!=null&&F(t,[`toolResponse`],m);let h=I(e,[`partMetadata`]);return h!=null&&F(t,[`partMetadata`],h),t}function bl(e){let t={},n=I(e,[`category`]);if(n!=null&&F(t,[`category`],n),I(e,[`method`])!==void 0)throw Error(`method parameter is not supported in Gemini API.`);let r=I(e,[`threshold`]);return r!=null&&F(t,[`threshold`],r),t}function xl(e){let t={},n=I(e,[`handle`]);if(n!=null&&F(t,[`handle`],n),I(e,[`transparent`])!==void 0)throw Error(`transparent parameter is not supported in Gemini API.`);return t}function Sl(e){let t={};if(I(e,[`retrieval`])!==void 0)throw Error(`retrieval parameter is not supported in Gemini API.`);let n=I(e,[`computerUse`]);n!=null&&F(t,[`computerUse`],n);let r=I(e,[`fileSearch`]);r!=null&&F(t,[`fileSearch`],r);let i=I(e,[`googleSearch`]);i!=null&&F(t,[`googleSearch`],gl(i));let a=I(e,[`googleMaps`]);a!=null&&F(t,[`googleMaps`],hl(a));let o=I(e,[`codeExecution`]);if(o!=null&&F(t,[`codeExecution`],o),I(e,[`enterpriseWebSearch`])!==void 0)throw Error(`enterpriseWebSearch parameter is not supported in Gemini API.`);let s=I(e,[`functionDeclarations`]);if(s!=null){let e=s;Array.isArray(e)&&(e=e.map(e=>e)),F(t,[`functionDeclarations`],e)}let c=I(e,[`googleSearchRetrieval`]);if(c!=null&&F(t,[`googleSearchRetrieval`],c),I(e,[`parallelAiSearch`])!==void 0)throw Error(`parallelAiSearch parameter is not supported in Gemini API.`);let l=I(e,[`urlContext`]);l!=null&&F(t,[`urlContext`],l);let u=I(e,[`mcpServers`]);if(u!=null){let e=u;Array.isArray(e)&&(e=e.map(e=>e)),F(t,[`mcpServers`],e)}return t}
128
+ /**
129
+ * @license
130
+ * Copyright 2025 Google LLC
131
+ * SPDX-License-Identifier: Apache-2.0
132
+ */
133
+ function Cl(e){let t=[];for(let n in e)if(Object.prototype.hasOwnProperty.call(e,n)){let r=e[n];if(typeof r==`object`&&r&&Object.keys(r).length>0){let e=Object.keys(r).map(e=>`${n}.${e}`);t.push(...e)}else t.push(n)}return t.join(`,`)}function wl(e,t){let n=null,r=e.bidiGenerateContentSetup;if(typeof r==`object`&&r&&`setup`in r){let t=r.setup;typeof t==`object`&&t?(e.bidiGenerateContentSetup=t,n=t):delete e.bidiGenerateContentSetup}else r!==void 0&&delete e.bidiGenerateContentSetup;let i=e.fieldMask;if(n){let r=Cl(n);if(Array.isArray(t?.lockAdditionalFields)&&t?.lockAdditionalFields.length===0)r?e.fieldMask=r:delete e.fieldMask;else if(t?.lockAdditionalFields&&t.lockAdditionalFields.length>0&&i!==null&&Array.isArray(i)&&i.length>0){let t=[`temperature`,`topK`,`topP`,`maxOutputTokens`,`responseModalities`,`seed`,`speechConfig`],n=[];i.length>0&&(n=i.map(e=>t.includes(e)?`generationConfig.${e}`:e));let a=[];r&&a.push(r),n.length>0&&a.push(...n),a.length>0?e.fieldMask=a.join(`,`):delete e.fieldMask}else delete e.fieldMask}else i!==null&&Array.isArray(i)&&i.length>0?e.fieldMask=i.join(`,`):delete e.fieldMask;return e}var Tl=class extends N{constructor(e){super(),this.apiClient=e}async create(e){let t,n=``,r={};if(this.apiClient.isVertexAI())throw Error(`The client.tokens.create method is only supported by the Gemini Developer API.`);{let i=fl(this.apiClient,e);n=P(`auth_tokens`,i._url),r=i._query,delete i.config,delete i._url,delete i._query;let a=wl(i,e.config);return t=this.apiClient.request({path:n,queryParams:r,body:JSON.stringify(a),httpMethod:`POST`,httpOptions:e.config?.httpOptions,abortSignal:e.config?.abortSignal}).then(e=>e.json()),t.then(e=>e)}}};
134
+ /**
135
+ * @license
136
+ * Copyright 2025 Google LLC
137
+ * SPDX-License-Identifier: Apache-2.0
138
+ */
139
+ function El(e,t){let n={},r=I(e,[`force`]);return t!==void 0&&r!=null&&F(t,[`_query`,`force`],r),n}function Dl(e){let t={},n=I(e,[`name`]);n!=null&&F(t,[`_url`,`name`],n);let r=I(e,[`config`]);return r!=null&&El(r,t),t}function Ol(e){let t={},n=I(e,[`name`]);return n!=null&&F(t,[`_url`,`name`],n),t}function kl(e,t){let n={},r=I(e,[`pageSize`]);t!==void 0&&r!=null&&F(t,[`_query`,`pageSize`],r);let i=I(e,[`pageToken`]);return t!==void 0&&i!=null&&F(t,[`_query`,`pageToken`],i),n}function Al(e){let t={},n=I(e,[`parent`]);n!=null&&F(t,[`_url`,`parent`],n);let r=I(e,[`config`]);return r!=null&&kl(r,t),t}function jl(e){let t={},n=I(e,[`sdkHttpResponse`]);n!=null&&F(t,[`sdkHttpResponse`],n);let r=I(e,[`nextPageToken`]);r!=null&&F(t,[`nextPageToken`],r);let i=I(e,[`documents`]);if(i!=null){let e=i;Array.isArray(e)&&(e=e.map(e=>e)),F(t,[`documents`],e)}return t}
140
+ /**
141
+ * @license
142
+ * Copyright 2025 Google LLC
143
+ * SPDX-License-Identifier: Apache-2.0
144
+ */
145
+ var Ml=class extends N{constructor(e){super(),this.apiClient=e,this.list=async e=>new ki(U.PAGED_ITEM_DOCUMENTS,t=>this.listInternal({parent:e.parent,config:t.config}),await this.listInternal(e),e)}async get(e){let t,n=``,r={};if(this.apiClient.isVertexAI())throw Error(`This method is only supported by the Gemini Developer API.`);{let i=Ol(e);return n=P(`{name}`,i._url),r=i._query,delete i._url,delete i._query,t=this.apiClient.request({path:n,queryParams:r,body:JSON.stringify(i),httpMethod:`GET`,httpOptions:e.config?.httpOptions,abortSignal:e.config?.abortSignal}).then(e=>e.json()),t.then(e=>e)}}async delete(e){let t=``,n={};if(this.apiClient.isVertexAI())throw Error(`This method is only supported by the Gemini Developer API.`);{let r=Dl(e);t=P(`{name}`,r._url),n=r._query,delete r._url,delete r._query,await this.apiClient.request({path:t,queryParams:n,body:JSON.stringify(r),httpMethod:`DELETE`,httpOptions:e.config?.httpOptions,abortSignal:e.config?.abortSignal})}}async listInternal(e){let t,n=``,r={};if(this.apiClient.isVertexAI())throw Error(`This method is only supported by the Gemini Developer API.`);{let i=Al(e);return n=P(`{parent}/documents`,i._url),r=i._query,delete i._url,delete i._query,t=this.apiClient.request({path:n,queryParams:r,body:JSON.stringify(i),httpMethod:`GET`,httpOptions:e.config?.httpOptions,abortSignal:e.config?.abortSignal}).then(e=>e.json()),t.then(e=>{let t=jl(e),n=new Bn;return Object.assign(n,t),n})}}},Nl=class extends N{constructor(e,t=new Ml(e)){super(),this.apiClient=e,this.documents=t,this.list=async(e={})=>new ki(U.PAGED_ITEM_FILE_SEARCH_STORES,e=>this.listInternal(e),await this.listInternal(e),e)}async uploadToFileSearchStore(e){if(this.apiClient.isVertexAI())throw Error(`Vertex AI does not support uploading files to a file search store.`);return this.apiClient.uploadFileToFileSearchStore(e.fileSearchStoreName,e.file,e.config)}async create(e){let t,n=``,r={};if(this.apiClient.isVertexAI())throw Error(`This method is only supported by the Gemini Developer API.`);{let i=vc(e);return n=P(`fileSearchStores`,i._url),r=i._query,delete i._url,delete i._query,t=this.apiClient.request({path:n,queryParams:r,body:JSON.stringify(i),httpMethod:`POST`,httpOptions:e.config?.httpOptions,abortSignal:e.config?.abortSignal}).then(e=>e.json()),t.then(e=>e)}}async get(e){let t,n=``,r={};if(this.apiClient.isVertexAI())throw Error(`This method is only supported by the Gemini Developer API.`);{let i=xc(e);return n=P(`{name}`,i._url),r=i._query,delete i._url,delete i._query,t=this.apiClient.request({path:n,queryParams:r,body:JSON.stringify(i),httpMethod:`GET`,httpOptions:e.config?.httpOptions,abortSignal:e.config?.abortSignal}).then(e=>e.json()),t.then(e=>e)}}async delete(e){let t=``,n={};if(this.apiClient.isVertexAI())throw Error(`This method is only supported by the Gemini Developer API.`);{let r=bc(e);t=P(`{name}`,r._url),n=r._query,delete r._url,delete r._query,await this.apiClient.request({path:t,queryParams:n,body:JSON.stringify(r),httpMethod:`DELETE`,httpOptions:e.config?.httpOptions,abortSignal:e.config?.abortSignal})}}async listInternal(e){let t,n=``,r={};if(this.apiClient.isVertexAI())throw Error(`This method is only supported by the Gemini Developer API.`);{let i=Dc(e);return n=P(`fileSearchStores`,i._url),r=i._query,delete i._url,delete i._query,t=this.apiClient.request({path:n,queryParams:r,body:JSON.stringify(i),httpMethod:`GET`,httpOptions:e.config?.httpOptions,abortSignal:e.config?.abortSignal}).then(e=>e.json()),t.then(e=>{let t=Oc(e),n=new Vn;return Object.assign(n,t),n})}}async uploadToFileSearchStoreInternal(e){let t,n=``,r={};if(this.apiClient.isVertexAI())throw Error(`This method is only supported by the Gemini Developer API.`);{let i=Ac(e);return n=P(`upload/v1beta/{file_search_store_name}:uploadToFileSearchStore`,i._url),r=i._query,delete i._url,delete i._query,t=this.apiClient.request({path:n,queryParams:r,body:JSON.stringify(i),httpMethod:`POST`,httpOptions:e.config?.httpOptions,abortSignal:e.config?.abortSignal}).then(e=>e.json()),t.then(e=>{let t=jc(e),n=new Hn;return Object.assign(n,t),n})}}async importFile(e){let t,n=``,r={};if(this.apiClient.isVertexAI())throw Error(`This method is only supported by the Gemini Developer API.`);{let i=wc(e);return n=P(`{file_search_store_name}:importFile`,i._url),r=i._query,delete i._url,delete i._query,t=this.apiClient.request({path:n,queryParams:r,body:JSON.stringify(i),httpMethod:`POST`,httpOptions:e.config?.httpOptions,abortSignal:e.config?.abortSignal}).then(e=>e.json()),t.then(e=>{let t=Cc(e),n=new Un;return Object.assign(n,t),n})}}};
146
+ /**
147
+ * @license
148
+ * Copyright 2025 Google LLC
149
+ * SPDX-License-Identifier: Apache-2.0
150
+ */
151
+ let Pl=function(){let{crypto:e}=globalThis;if(e?.randomUUID)return Pl=e.randomUUID.bind(e),e.randomUUID();let t=new Uint8Array(1),n=e?()=>e.getRandomValues(t)[0]:()=>Math.random()*255&255;return`10000000-1000-4000-8000-100000000000`.replace(/[018]/g,e=>(e^n()&15>>e/4).toString(16))};const Fl=()=>Pl();
152
+ /**
153
+ * @license
154
+ * Copyright 2025 Google LLC
155
+ * SPDX-License-Identifier: Apache-2.0
156
+ */
157
+ function Il(e){return typeof e==`object`&&!!e&&(`name`in e&&e.name===`AbortError`||`message`in e&&String(e.message).includes(`FetchRequestCanceledException`))}const Ll=e=>{if(e instanceof Error)return e;if(typeof e==`object`&&e){try{if(Object.prototype.toString.call(e)===`[object Error]`){let t=Error(e.message,e.cause?{cause:e.cause}:{});return e.stack&&(t.stack=e.stack),e.cause&&!t.cause&&(t.cause=e.cause),e.name&&(t.name=e.name),t}}catch{}try{return Error(JSON.stringify(e))}catch{}}return Error(e)};
158
+ /**
159
+ * @license
160
+ * Copyright 2025 Google LLC
161
+ * SPDX-License-Identifier: Apache-2.0
162
+ */
163
+ var Y=class extends Error{},X=class e extends Y{constructor(t,n,r,i){super(`${e.makeMessage(t,n,r)}`),this.status=t,this.headers=i,this.error=n}static makeMessage(e,t,n){let r=t?.message?typeof t.message==`string`?t.message:JSON.stringify(t.message):t?JSON.stringify(t):n;return e&&r?`${e} ${r}`:e?`${e} status code (no body)`:r||`(no status code or body)`}static generate(t,n,r,i){if(!t||!i)return new zl({message:r,cause:Ll(n)});let a=n;return t===400?new Vl(t,a,r,i):t===401?new Hl(t,a,r,i):t===403?new Ul(t,a,r,i):t===404?new Wl(t,a,r,i):t===409?new Gl(t,a,r,i):t===422?new Kl(t,a,r,i):t===429?new ql(t,a,r,i):t>=500?new Jl(t,a,r,i):new e(t,a,r,i)}},Rl=class extends X{constructor({message:e}={}){super(void 0,void 0,e||`Request was aborted.`,void 0)}},zl=class extends X{constructor({message:e,cause:t}){super(void 0,void 0,e||`Connection error.`,void 0),t&&(this.cause=t)}},Bl=class extends zl{constructor({message:e}={}){super({message:e??`Request timed out.`})}},Vl=class extends X{},Hl=class extends X{},Ul=class extends X{},Wl=class extends X{},Gl=class extends X{},Kl=class extends X{},ql=class extends X{},Jl=class extends X{};
164
+ /**
165
+ * @license
166
+ * Copyright 2025 Google LLC
167
+ * SPDX-License-Identifier: Apache-2.0
168
+ */
169
+ const Yl=/^[a-z][a-z0-9+.-]*:/i,Xl=e=>Yl.test(e);let Zl=e=>(Zl=Array.isArray,Zl(e));const Ql=Zl;function $l(e){if(!e)return!0;for(let t in e)return!1;return!0}function eu(e,t){return Object.prototype.hasOwnProperty.call(e,t)}const tu=(e,t)=>{if(typeof t!=`number`||!Number.isInteger(t))throw new Y(`${e} must be an integer`);if(t<0)throw new Y(`${e} must be a positive integer`);return t},nu=e=>{try{return JSON.parse(e)}catch{return}},ru=e=>new Promise(t=>setTimeout(t,e));
170
+ /**
171
+ * @license
172
+ * Copyright 2025 Google LLC
173
+ * SPDX-License-Identifier: Apache-2.0
174
+ */
175
+ function iu(){if(typeof fetch<`u`)return fetch;throw Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new GeminiNextGenAPIClient({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function au(...e){let t=globalThis.ReadableStream;if(t===void 0)throw Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new t(...e)}function ou(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return au({start(){},async pull(e){let{done:n,value:r}=await t.next();n?e.close():e.enqueue(r)},async cancel(){await t.return?.call(t)}})}function su(e){if(e[Symbol.asyncIterator])return e;let t=e.getReader();return{async next(){try{let e=await t.read();return e?.done&&t.releaseLock(),e}catch(e){throw t.releaseLock(),e}},async return(){let e=t.cancel();return t.releaseLock(),await e,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function cu(e){var t;if(typeof e!=`object`||!e)return;if(e[Symbol.asyncIterator]){await(t=e[Symbol.asyncIterator]()).return?.call(t);return}let n=e.getReader(),r=n.cancel();n.releaseLock(),await r}
176
+ /**
177
+ * @license
178
+ * Copyright 2025 Google LLC
179
+ * SPDX-License-Identifier: Apache-2.0
180
+ */
181
+ const lu=({headers:e,body:t})=>({bodyHeaders:{"content-type":`application/json`},body:JSON.stringify(t)});
182
+ /**
183
+ * @license
184
+ * Copyright 2025 Google LLC
185
+ * SPDX-License-Identifier: Apache-2.0
186
+ */
187
+ function uu(e){return Object.entries(e).filter(([e,t])=>t!==void 0).map(([e,t])=>{if(typeof t==`string`||typeof t==`number`||typeof t==`boolean`)return`${encodeURIComponent(e)}=${encodeURIComponent(t)}`;if(t===null)return`${encodeURIComponent(e)}=`;throw new Y(`Cannot stringify type ${typeof t}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join(`&`)}
188
+ /**
189
+ * @license
190
+ * Copyright 2025 Google LLC
191
+ * SPDX-License-Identifier: Apache-2.0
192
+ */
193
+ const du=()=>{if(typeof File>`u`){let{process:e}=globalThis,t=typeof e?.versions?.node==`string`&&parseInt(e.versions.node.split(`.`))<20;throw Error("`File` is not defined as a global, which is required for file uploads."+(t?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":``))}};function fu(e,t,n){return du(),new File(e,t??`unknown_file`,n)}function pu(e){return(typeof e==`object`&&!!e&&(`name`in e&&e.name&&String(e.name)||`url`in e&&e.url&&String(e.url)||`filename`in e&&e.filename&&String(e.filename)||`path`in e&&e.path&&String(e.path))||``).split(/[\\/]/).pop()||void 0}const mu=e=>typeof e==`object`&&!!e&&typeof e[Symbol.asyncIterator]==`function`,hu=e=>typeof e==`object`&&!!e&&typeof e.size==`number`&&typeof e.type==`string`&&typeof e.text==`function`&&typeof e.slice==`function`&&typeof e.arrayBuffer==`function`,gu=e=>typeof e==`object`&&!!e&&typeof e.name==`string`&&typeof e.lastModified==`number`&&hu(e),_u=e=>typeof e==`object`&&!!e&&typeof e.url==`string`&&typeof e.blob==`function`;async function vu(e,t,n){if(du(),e=await e,gu(e))return e instanceof File?e:fu([await e.arrayBuffer()],e.name);if(_u(e)){let r=await e.blob();return t||=new URL(e.url).pathname.split(/[\\/]/).pop(),fu(await yu(r),t,n)}let r=await yu(e);if(t||=pu(e),!n?.type){let e=r.find(e=>typeof e==`object`&&`type`in e&&e.type);typeof e==`string`&&(n=Object.assign(Object.assign({},n),{type:e}))}return fu(r,t,n)}async function yu(e){var t,n,r,i;let a=[];if(typeof e==`string`||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)a.push(e);else if(hu(e))a.push(e instanceof Blob?e:await e.arrayBuffer());else if(mu(e))try{for(var o=!0,s=q(e),c;c=await s.next(),t=c.done,!t;o=!0){i=c.value,o=!1;let e=i;a.push(...await yu(e))}}catch(e){n={error:e}}finally{try{!o&&!t&&(r=s.return)&&await r.call(s)}finally{if(n)throw n.error}}else{let t=e?.constructor?.name;throw Error(`Unexpected data type: ${typeof e}${t?`; constructor: ${t}`:``}${bu(e)}`)}return a}function bu(e){return typeof e!=`object`||!e?``:`; props: [${Object.getOwnPropertyNames(e).map(e=>`"${e}"`).join(`, `)}]`}
194
+ /**
195
+ * @license
196
+ * Copyright 2025 Google LLC
197
+ * SPDX-License-Identifier: Apache-2.0
198
+ */
199
+ var xu=class{constructor(e){this._client=e}};xu._key=[];
200
+ /**
201
+ * @license
202
+ * Copyright 2025 Google LLC
203
+ * SPDX-License-Identifier: Apache-2.0
204
+ */
205
+ function Su(e){return e.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}const Cu=Object.freeze(Object.create(null)),Z=((e=Su)=>(function(t,...n){if(t.length===1)return t[0];let r=!1,i=[],a=t.reduce((t,a,o)=>{/[?#]/.test(a)&&(r=!0);let s=n[o],c=(r?encodeURIComponent:e)(``+s);return o!==n.length&&(s==null||typeof s==`object`&&s.toString===Object.getPrototypeOf(Object.getPrototypeOf(s.hasOwnProperty??Cu)??Cu)?.toString)&&(c=s+``,i.push({start:t.length+a.length,length:c.length,error:`Value of type ${Object.prototype.toString.call(s).slice(8,-1)} is not a valid path parameter`})),t+a+(o===n.length?``:c)},``),o=a.split(/[?#]/,1)[0],s=/(^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,c;for(;(c=s.exec(o))!==null;){let e=c[0].startsWith(`/`),t=+!!e,n=e?c[0].slice(1):c[0];i.push({start:c.index+t,length:n.length,error:`Value "${n}" can\'t be safely passed as a path parameter`})}if(i.sort((e,t)=>e.start-t.start),i.length>0){let e=0,t=i.reduce((t,n)=>{let r=` `.repeat(n.start-e),i=`^`.repeat(n.length);return e=n.start+n.length,t+r+i},``);throw new Y(`Path parameters result in path with invalid segments:\n${i.map(e=>e.error).join(`
206
+ `)}\n${a}\n${t}`)}return a}))(Su);
207
+ /**
208
+ * @license
209
+ * Copyright 2025 Google LLC
210
+ * SPDX-License-Identifier: Apache-2.0
211
+ */
212
+ var wu=class extends xu{create(e,t){let{api_version:n=this._client.apiVersion}=e,r=W(e,[`api_version`]);if(`model`in r&&`agent_config`in r)throw new Y("Invalid request: specified `model` and `agent_config`. If specifying `model`, use `generation_config`.");if(`agent`in r&&`generation_config`in r)throw new Y("Invalid request: specified `agent` and `generation_config`. If specifying `agent`, use `agent_config`.");return this._client.post(Z`/${n}/interactions`,Object.assign(Object.assign({body:r},t),{stream:e.stream??!1}))}delete(e,t={},n){let{api_version:r=this._client.apiVersion}=t??{};return this._client.delete(Z`/${r}/interactions/${e}`,n)}cancel(e,t={},n){let{api_version:r=this._client.apiVersion}=t??{};return this._client.post(Z`/${r}/interactions/${e}/cancel`,n)}get(e,t={},n){let r=t??{},{api_version:i=this._client.apiVersion}=r,a=W(r,[`api_version`]);return this._client.get(Z`/${i}/interactions/${e}`,Object.assign(Object.assign({query:a},n),{stream:t?.stream??!1}))}};wu._key=Object.freeze([`interactions`]);var Tu=class extends wu{},Eu=class extends xu{create(e,t){let{api_version:n=this._client.apiVersion,webhook_id:r}=e,i=W(e,[`api_version`,`webhook_id`]);return this._client.post(Z`/${n}/webhooks`,Object.assign({query:{webhook_id:r},body:i},t))}update(e,t,n){let{api_version:r=this._client.apiVersion,update_mask:i}=t,a=W(t,[`api_version`,`update_mask`]);return this._client.patch(Z`/${r}/webhooks/${e}`,Object.assign({query:{update_mask:i},body:a},n))}list(e={},t){let n=e??{},{api_version:r=this._client.apiVersion}=n,i=W(n,[`api_version`]);return this._client.get(Z`/${r}/webhooks`,Object.assign({query:i},t))}delete(e,t={},n){let{api_version:r=this._client.apiVersion}=t??{};return this._client.delete(Z`/${r}/webhooks/${e}`,n)}get(e,t={},n){let{api_version:r=this._client.apiVersion}=t??{};return this._client.get(Z`/${r}/webhooks/${e}`,n)}ping(e,t=void 0,n){let{api_version:r=this._client.apiVersion,body:i}=t??{};return this._client.post(Z`/${r}/webhooks/${e}:ping`,Object.assign({body:i},n))}rotateSigningSecret(e,t={},n){let r=t??{},{api_version:i=this._client.apiVersion}=r,a=W(r,[`api_version`]);return this._client.post(Z`/${i}/webhooks/${e}:rotateSigningSecret`,Object.assign({body:a},n))}};Eu._key=Object.freeze([`webhooks`]);var Du=class extends Eu{};
213
+ /**
214
+ * @license
215
+ * Copyright 2025 Google LLC
216
+ * SPDX-License-Identifier: Apache-2.0
217
+ */
218
+ function Ou(e){let t=0;for(let n of e)t+=n.length;let n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return n}let ku;function Au(e){let t;return(ku??=(t=new globalThis.TextEncoder,t.encode.bind(t)))(e)}let ju;function Mu(e){let t;return(ju??=(t=new globalThis.TextDecoder,t.decode.bind(t)))(e)}
219
+ /**
220
+ * @license
221
+ * Copyright 2025 Google LLC
222
+ * SPDX-License-Identifier: Apache-2.0
223
+ */
224
+ var Nu=class{constructor(){this.buffer=new Uint8Array,this.carriageReturnIndex=null,this.searchIndex=0}decode(e){if(e==null)return[];let t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e==`string`?Au(e):e;this.buffer=Ou([this.buffer,t]);let n=[],r;for(;(r=Pu(this.buffer,this.carriageReturnIndex??this.searchIndex))!=null;){if(r.carriage&&this.carriageReturnIndex==null){this.carriageReturnIndex=r.index;continue}if(this.carriageReturnIndex!=null&&(r.index!==this.carriageReturnIndex+1||r.carriage)){n.push(Mu(this.buffer.subarray(0,this.carriageReturnIndex-1))),this.buffer=this.buffer.subarray(this.carriageReturnIndex),this.carriageReturnIndex=null,this.searchIndex=0;continue}let e=this.carriageReturnIndex===null?r.preceding:r.preceding-1,t=Mu(this.buffer.subarray(0,e));n.push(t),this.buffer=this.buffer.subarray(r.index),this.carriageReturnIndex=null,this.searchIndex=0}return this.searchIndex=Math.max(0,this.buffer.length-1),n}flush(){return this.buffer.length?this.decode(`
225
+ `):[]}};Nu.NEWLINE_CHARS=new Set([`
226
+ `,`\r`]),Nu.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function Pu(e,t){let n=t??0,r=e.indexOf(10,n),i=e.indexOf(13,n);if(r===-1&&i===-1)return null;let a;return a=r!==-1&&i!==-1?Math.min(r,i):r===-1?i:r,e[a]===10?{preceding:a,index:a+1,carriage:!1}:{preceding:a,index:a+1,carriage:!0}}
227
+ /**
228
+ * @license
229
+ * Copyright 2025 Google LLC
230
+ * SPDX-License-Identifier: Apache-2.0
231
+ */
232
+ const Fu={off:0,error:200,warn:300,info:400,debug:500},Iu=(e,t,n)=>{if(e){if(eu(Fu,e))return e;Q(n).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(Fu))}`)}};function Lu(){}function Ru(e,t,n){return!t||Fu[e]>Fu[n]?Lu:t[e].bind(t)}const zu={error:Lu,warn:Lu,info:Lu,debug:Lu};let Bu=new WeakMap;function Q(e){let t=e.logger,n=e.logLevel??`off`;if(!t)return zu;let r=Bu.get(t);if(r&&r[0]===n)return r[1];let i={error:Ru(`error`,t,n),warn:Ru(`warn`,t,n),info:Ru(`info`,t,n),debug:Ru(`debug`,t,n)};return Bu.set(t,[n,i]),i}const Vu=e=>(e.options&&(e.options=Object.assign({},e.options),delete e.options.headers),e.headers&&=Object.fromEntries((e.headers instanceof Headers?[...e.headers]:Object.entries(e.headers)).map(([e,t])=>[e,e.toLowerCase()===`x-goog-api-key`||e.toLowerCase()===`authorization`||e.toLowerCase()===`cookie`||e.toLowerCase()===`set-cookie`?`***`:t])),`retryOfRequestLogID`in e&&(e.retryOfRequestLogID&&(e.retryOf=e.retryOfRequestLogID),delete e.retryOfRequestLogID),e);
233
+ /**
234
+ * @license
235
+ * Copyright 2025 Google LLC
236
+ * SPDX-License-Identifier: Apache-2.0
237
+ */
238
+ var Hu=class e{constructor(e,t,n){this.iterator=e,this.controller=t,this.client=n}static fromSSEResponse(t,n,r){let i=!1,a=r?Q(r):console;function o(){return K(this,arguments,function*(){var e,r,o,s;if(i)throw new Y("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");i=!0;let c=!1;try{try{for(var l=!0,u=q(Uu(t,n)),d;d=yield G(u.next()),e=d.done,!e;l=!0){s=d.value,l=!1;let e=s;if(!c)if(e.data.startsWith(`[DONE]`)){c=!0;continue}else try{yield yield G(JSON.parse(e.data))}catch(t){throw a.error(`Could not parse message into JSON:`,e.data),a.error(`From chunk:`,e.raw),t}}}catch(e){r={error:e}}finally{try{!l&&!e&&(o=u.return)&&(yield G(o.call(u)))}finally{if(r)throw r.error}}c=!0}catch(e){if(Il(e))return yield G(void 0);throw e}finally{c||n.abort()}})}return new e(o,n,r)}static fromReadableStream(t,n,r){let i=!1;function a(){return K(this,arguments,function*(){var e,n,r,i;let a=new Nu,o=su(t);try{for(var s=!0,c=q(o),l;l=yield G(c.next()),e=l.done,!e;s=!0){i=l.value,s=!1;let e=i;for(let t of a.decode(e))yield yield G(t)}}catch(e){n={error:e}}finally{try{!s&&!e&&(r=c.return)&&(yield G(r.call(c)))}finally{if(n)throw n.error}}for(let e of a.flush())yield yield G(e)})}function o(){return K(this,arguments,function*(){var e,t,r,o;if(i)throw new Y("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");i=!0;let s=!1;try{try{for(var c=!0,l=q(a()),u;u=yield G(l.next()),e=u.done,!e;c=!0){o=u.value,c=!1;let e=o;s||e&&(yield yield G(JSON.parse(e)))}}catch(e){t={error:e}}finally{try{!c&&!e&&(r=l.return)&&(yield G(r.call(l)))}finally{if(t)throw t.error}}s=!0}catch(e){if(Il(e))return yield G(void 0);throw e}finally{s||n.abort()}})}return new e(o,n,r)}[Symbol.asyncIterator](){return this.iterator()}tee(){let t=[],n=[],r=this.iterator(),i=e=>({next:()=>{if(e.length===0){let e=r.next();t.push(e),n.push(e)}return e.shift()}});return[new e(()=>i(t),this.controller,this.client),new e(()=>i(n),this.controller,this.client)]}toReadableStream(){let e=this,t;return au({async start(){t=e[Symbol.asyncIterator]()},async pull(e){try{let{value:n,done:r}=await t.next();if(r)return e.close();let i=Au(JSON.stringify(n)+`
239
+ `);e.enqueue(i)}catch(t){e.error(t)}},async cancel(){await t.return?.call(t)}})}};function Uu(e,t){return K(this,arguments,function*(){var n,r,i,a;if(!e.body)throw t.abort(),globalThis.navigator!==void 0&&globalThis.navigator.product===`ReactNative`?new Y(`The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api`):new Y(`Attempted to iterate over a response with no body`);let o=new Gu,s=new Nu,c=su(e.body);try{for(var l=!0,u=q(Wu(c)),d;d=yield G(u.next()),n=d.done,!n;l=!0){a=d.value,l=!1;let e=a;for(let t of s.decode(e)){let e=o.decode(t);e&&(yield yield G(e))}}}catch(e){r={error:e}}finally{try{!l&&!n&&(i=u.return)&&(yield G(i.call(u)))}finally{if(r)throw r.error}}for(let e of s.flush()){let t=o.decode(e);t&&(yield yield G(t))}})}function Wu(e){return K(this,arguments,function*(){var t,n,r,i;try{for(var a=!0,o=q(e),s;s=yield G(o.next()),t=s.done,!t;a=!0){i=s.value,a=!1;let e=i;e!=null&&(yield yield G(e instanceof ArrayBuffer?new Uint8Array(e):typeof e==`string`?Au(e):e))}}catch(e){n={error:e}}finally{try{!a&&!t&&(r=o.return)&&(yield G(r.call(o)))}finally{if(n)throw n.error}}})}var Gu=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith(`\r`)&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;let e={event:this.event,data:this.data.join(`
240
+ `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],e}if(this.chunks.push(e),e.startsWith(`:`))return null;let[t,n,r]=Ku(e,`:`);return r.startsWith(` `)&&(r=r.substring(1)),t===`event`?this.event=r:t===`data`&&this.data.push(r),null}};function Ku(e,t){let n=e.indexOf(t);return n===-1?[e,``,``]:[e.substring(0,n),t,e.substring(n+t.length)]}
241
+ /**
242
+ * @license
243
+ * Copyright 2025 Google LLC
244
+ * SPDX-License-Identifier: Apache-2.0
245
+ */
246
+ async function qu(e,t){let{response:n,requestLogID:r,retryOfRequestLogID:i,startTime:a}=t,o=await(async()=>{if(t.options.stream)return Q(e).debug(`response`,n.status,n.url,n.headers,n.body),t.options.__streamClass?t.options.__streamClass.fromSSEResponse(n,t.controller,e):Hu.fromSSEResponse(n,t.controller,e);if(n.status===204)return null;if(t.options.__binaryResponse)return n;let r=(n.headers.get(`content-type`)?.split(`;`)[0])?.trim();return r?.includes(`application/json`)||r?.endsWith(`+json`)?n.headers.get(`content-length`)===`0`?void 0:await n.json():await n.text()})();return Q(e).debug(`[${r}] response parsed`,Vu({retryOfRequestLogID:i,url:n.url,status:n.status,body:o,durationMs:Date.now()-a})),o}
247
+ /**
248
+ * @license
249
+ * Copyright 2025 Google LLC
250
+ * SPDX-License-Identifier: Apache-2.0
251
+ */
252
+ var Ju=class e extends Promise{constructor(e,t,n=qu){super(e=>{e(null)}),this.responsePromise=t,this.parseResponse=n,this.client=e}_thenUnwrap(t){return new e(this.client,this.responsePromise,async(e,n)=>t(await this.parseResponse(e,n),n))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t}}parse(){return this.parsedPromise||=this.responsePromise.then(e=>this.parseResponse(this.client,e)),this.parsedPromise}then(e,t){return this.parse().then(e,t)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}};
253
+ /**
254
+ * @license
255
+ * Copyright 2025 Google LLC
256
+ * SPDX-License-Identifier: Apache-2.0
257
+ */
258
+ const Yu=Symbol(`brand.privateNullableHeaders`);function*Xu(e){if(!e)return;if(Yu in e){let{values:t,nulls:n}=e;yield*t.entries();for(let e of n)yield[e,null];return}let t=!1,n;e instanceof Headers?n=e.entries():Ql(e)?n=e:(t=!0,n=Object.entries(e??{}));for(let e of n){let n=e[0];if(typeof n!=`string`)throw TypeError(`expected header name to be a string`);let r=Ql(e[1])?e[1]:[e[1]],i=!1;for(let e of r)e!==void 0&&(t&&!i&&(i=!0,yield[n,null]),yield[n,e])}}const Zu=e=>{let t=new Headers,n=new Set;for(let r of e){let e=new Set;for(let[i,a]of Xu(r)){let r=i.toLowerCase();e.has(r)||(t.delete(i),e.add(r)),a===null?(t.delete(i),n.add(r)):(t.append(i,a),n.delete(r))}}return{[Yu]:!0,values:t,nulls:n}},Qu=e=>{var t;if(globalThis.process!==void 0)return(globalThis.process.env?.[e])?.trim()||void 0;if(globalThis.Deno!==void 0)return(((t=globalThis.Deno.env)?.get)?.call(t,e))?.trim()||void 0};
259
+ /**
260
+ * @license
261
+ * Copyright 2025 Google LLC
262
+ * SPDX-License-Identifier: Apache-2.0
263
+ */
264
+ var $u,ed=class e{constructor(t){var{baseURL:n=Qu(`GEMINI_NEXT_GEN_API_BASE_URL`),apiKey:r=Qu(`GEMINI_API_KEY`)??null,apiVersion:i=`v1beta`}=t,a=W(t,[`baseURL`,`apiKey`,`apiVersion`]);let o=Object.assign(Object.assign({apiKey:r,apiVersion:i},a),{baseURL:n||`https://generativelanguage.googleapis.com`});this.baseURL=o.baseURL,this.timeout=o.timeout??e.DEFAULT_TIMEOUT,this.logger=o.logger??console;let s=`warn`;this.logLevel=s,this.logLevel=Iu(o.logLevel,`ClientOptions.logLevel`,this)??Iu(Qu(`GEMINI_NEXT_GEN_API_LOG`),`process.env['GEMINI_NEXT_GEN_API_LOG']`,this)??s,this.fetchOptions=o.fetchOptions,this.maxRetries=o.maxRetries??2,this.fetch=o.fetch??iu(),this.encoder=lu,this._options=o,this.apiKey=r,this.apiVersion=i,this.clientAdapter=o.clientAdapter}withOptions(e){return new this.constructor(Object.assign(Object.assign(Object.assign({},this._options),{baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,apiVersion:this.apiVersion}),e))}baseURLOverridden(){return this.baseURL!==`https://generativelanguage.googleapis.com`}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t}){if(!(e.has(`authorization`)||e.has(`x-goog-api-key`))&&!(this.apiKey&&e.get(`x-goog-api-key`))&&!t.has(`x-goog-api-key`))throw Error(`Could not resolve authentication method. Expected the apiKey to be set. Or for the "x-goog-api-key" headers to be explicitly omitted`)}async authHeaders(e){let t=Zu([e.headers]);if(!(t.values.has(`authorization`)||t.values.has(`x-goog-api-key`))){if(this.apiKey)return Zu([{"x-goog-api-key":this.apiKey}]);if(this.clientAdapter&&this.clientAdapter.isVertexAI())return Zu([await this.clientAdapter.getAuthHeaders()])}}stringifyQuery(e){return uu(e)}getUserAgent(){return`${this.constructor.name}/JS 0.0.1`}defaultIdempotencyKey(){return`stainless-node-retry-${Fl()}`}makeStatusError(e,t,n,r){return X.generate(e,t,n,r)}buildURL(e,t,n){let r=!this.baseURLOverridden()&&n||this.baseURL,i=Xl(e)?new URL(e):new URL(r+(r.endsWith(`/`)&&e.startsWith(`/`)?e.slice(1):e)),a=this.defaultQuery(),o=Object.fromEntries(i.searchParams);return(!$l(a)||!$l(o))&&(t=Object.assign(Object.assign(Object.assign({},o),a),t)),typeof t==`object`&&t&&!Array.isArray(t)&&(i.search=this.stringifyQuery(t)),i.toString()}async prepareOptions(e){if(this.clientAdapter&&this.clientAdapter.isVertexAI()&&!e.path.startsWith(`/${this.apiVersion}/projects/`)){let t=e.path.slice(this.apiVersion.length+1);e.path=`/${this.apiVersion}/projects/${this.clientAdapter.getProject()}/locations/${this.clientAdapter.getLocation()}${t}`}}async prepareRequest(e,{url:t,options:n}){}get(e,t){return this.methodRequest(`get`,e,t)}post(e,t){return this.methodRequest(`post`,e,t)}patch(e,t){return this.methodRequest(`patch`,e,t)}put(e,t){return this.methodRequest(`put`,e,t)}delete(e,t){return this.methodRequest(`delete`,e,t)}methodRequest(e,t,n){return this.request(Promise.resolve(n).then(n=>Object.assign({method:e,path:t},n)))}request(e,t=null){return new Ju(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,n){let r=await e,i=r.maxRetries??this.maxRetries;t??=i,await this.prepareOptions(r);let{req:a,url:o,timeout:s}=await this.buildRequest(r,{retryCount:i-t});await this.prepareRequest(a,{url:o,options:r});let c=`log_`+(Math.random()*(1<<24)|0).toString(16).padStart(6,`0`),l=n===void 0?``:`, retryOf: ${n}`,u=Date.now();if(Q(this).debug(`[${c}] sending request`,Vu({retryOfRequestLogID:n,method:r.method,url:o,options:r,headers:a.headers})),r.signal?.aborted)throw new Rl;let d=new AbortController,f=await this.fetchWithTimeout(o,a,s,d).catch(Ll),p=Date.now();if(f instanceof globalThis.Error){let e=`retrying, ${t} attempts remaining`;if(r.signal?.aborted)throw new Rl;let i=Il(f)||/timed? ?out/i.test(String(f)+(`cause`in f?String(f.cause):``));if(t)return Q(this).info(`[${c}] connection ${i?`timed out`:`failed`} - ${e}`),Q(this).debug(`[${c}] connection ${i?`timed out`:`failed`} (${e})`,Vu({retryOfRequestLogID:n,url:o,durationMs:p-u,message:f.message})),this.retryRequest(r,t,n??c);throw Q(this).info(`[${c}] connection ${i?`timed out`:`failed`} - error; no more retries left`),Q(this).debug(`[${c}] connection ${i?`timed out`:`failed`} (error; no more retries left)`,Vu({retryOfRequestLogID:n,url:o,durationMs:p-u,message:f.message})),i?new Bl:new zl({cause:f})}let m=`[${c}${l}] ${a.method} ${o} ${f.ok?`succeeded`:`failed`} with status ${f.status} in ${p-u}ms`;if(!f.ok){let e=await this.shouldRetry(f);if(t&&e){let e=`retrying, ${t} attempts remaining`;return await cu(f.body),Q(this).info(`${m} - ${e}`),Q(this).debug(`[${c}] response error (${e})`,Vu({retryOfRequestLogID:n,url:f.url,status:f.status,headers:f.headers,durationMs:p-u})),this.retryRequest(r,t,n??c,f.headers)}let i=e?`error; no more retries left`:`error; not retryable`;Q(this).info(`${m} - ${i}`);let a=await f.text().catch(e=>Ll(e).message),o=nu(a),s=o?void 0:a;throw Q(this).debug(`[${c}] response error (${i})`,Vu({retryOfRequestLogID:n,url:f.url,status:f.status,headers:f.headers,message:s,durationMs:Date.now()-u})),this.makeStatusError(f.status,o,s,f.headers)}return Q(this).info(m),Q(this).debug(`[${c}] response start`,Vu({retryOfRequestLogID:n,url:f.url,status:f.status,headers:f.headers,durationMs:p-u})),{response:f,options:r,controller:d,requestLogID:c,retryOfRequestLogID:n,startTime:u}}async fetchWithTimeout(e,t,n,r){let i=t||{},{signal:a,method:o}=i,s=W(i,[`signal`,`method`]),c=this._makeAbort(r);a&&a.addEventListener(`abort`,c,{once:!0});let l=setTimeout(c,n),u=globalThis.ReadableStream&&s.body instanceof globalThis.ReadableStream||typeof s.body==`object`&&s.body!==null&&Symbol.asyncIterator in s.body,d=Object.assign(Object.assign(Object.assign({signal:r.signal},u?{duplex:`half`}:{}),{method:`GET`}),s);o&&(d.method=o.toUpperCase());try{return await this.fetch.call(void 0,e,d)}finally{clearTimeout(l)}}async shouldRetry(e){let t=e.headers.get(`x-should-retry`);return t===`true`?!0:t===`false`?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,t,n,r){let i,a=r?.get(`retry-after-ms`);if(a){let e=parseFloat(a);Number.isNaN(e)||(i=e)}let o=r?.get(`retry-after`);if(o&&!i){let e=parseFloat(o);i=Number.isNaN(e)?Date.parse(o)-Date.now():e*1e3}if(i===void 0){let n=e.maxRetries??this.maxRetries;i=this.calculateDefaultRetryTimeoutMillis(t,n)}return await ru(i),this.makeRequest(e,t-1,n)}calculateDefaultRetryTimeoutMillis(e,t){let n=t-e;return Math.min(.5*2**n,8)*(1-Math.random()*.25)*1e3}async buildRequest(e,{retryCount:t=0}={}){let n=Object.assign({},e),{method:r,path:i,query:a,defaultBaseURL:o}=n,s=this.buildURL(i,a,o);`timeout`in n&&tu(`timeout`,n.timeout),n.timeout=n.timeout??this.timeout;let{bodyHeaders:c,body:l}=this.buildBody({options:n}),u=await this.buildHeaders({options:e,method:r,bodyHeaders:c,retryCount:t});return{req:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({method:r,headers:u},n.signal&&{signal:n.signal}),globalThis.ReadableStream&&l instanceof globalThis.ReadableStream&&{duplex:`half`}),l&&{body:l}),this.fetchOptions??{}),n.fetchOptions??{}),url:s,timeout:n.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:n,retryCount:r}){let i={};this.idempotencyHeader&&t!==`get`&&(e.idempotencyKey||=this.defaultIdempotencyKey(),i[this.idempotencyHeader]=e.idempotencyKey);let a=await this.authHeaders(e),o=Zu([i,{Accept:`application/json`,"User-Agent":this.getUserAgent()},this._options.defaultHeaders,n,e.headers,a]);return this.validateHeaders(o),o.values}_makeAbort(e){return()=>e.abort()}buildBody({options:{body:e,headers:t}}){if(!e)return{bodyHeaders:void 0,body:void 0};let n=Zu([t]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e==`string`&&n.values.has(`content-type`)||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:e}:typeof e==`object`&&(Symbol.asyncIterator in e||Symbol.iterator in e&&`next`in e&&typeof e.next==`function`)?{bodyHeaders:void 0,body:ou(e)}:typeof e==`object`&&n.values.get(`content-type`)===`application/x-www-form-urlencoded`?{bodyHeaders:{"content-type":`application/x-www-form-urlencoded`},body:this.stringifyQuery(e)}:this.encoder({body:e,headers:n})}};ed.DEFAULT_TIMEOUT=6e4;var $=class extends ed{constructor(){super(...arguments),this.interactions=new Tu(this),this.webhooks=new Du(this)}};$u=$,$.GeminiNextGenAPIClient=$u,$.GeminiNextGenAPIClientError=Y,$.APIError=X,$.APIConnectionError=zl,$.APIConnectionTimeoutError=Bl,$.APIUserAbortError=Rl,$.NotFoundError=Wl,$.ConflictError=Gl,$.RateLimitError=ql,$.BadRequestError=Vl,$.AuthenticationError=Hl,$.InternalServerError=Jl,$.PermissionDeniedError=Ul,$.UnprocessableEntityError=Kl,$.toFile=vu,$.Interactions=Tu,$.Webhooks=Du;
265
+ /**
266
+ * @license
267
+ * Copyright 2025 Google LLC
268
+ * SPDX-License-Identifier: Apache-2.0
269
+ */
270
+ const td=`x-goog-api-key`,nd=`https://www.googleapis.com/auth/cloud-platform`;var rd=class{constructor(e){if(e.apiKey!==void 0){this.apiKey=e.apiKey;return}let t=id(e.googleAuthOptions);this.googleAuth=new Ge.GoogleAuth(t)}async addAuthHeaders(e,t){if(this.apiKey!==void 0){if(this.apiKey.startsWith(`auth_tokens/`))throw Error(`Ephemeral tokens are only supported by the live API.`);this.addKeyHeader(e);return}return this.addGoogleAuthHeaders(e,t)}addKeyHeader(e){if(e.get(td)===null){if(this.apiKey===void 0)throw Error(`Trying to set API key header but apiKey is not set`);e.append(td,this.apiKey)}}async addGoogleAuthHeaders(e,t){if(this.googleAuth===void 0)throw Error(`Trying to set google-auth headers but googleAuth is unset`);let n=await this.googleAuth.getRequestHeaders(t);for(let[t,r]of n)e.get(t)===null&&e.append(t,r)}};function id(e){let t;if(e){if(t=e,!t.scopes)return t.scopes=[nd],t;if(typeof t.scopes==`string`&&t.scopes!==nd||Array.isArray(t.scopes)&&t.scopes.indexOf(nd)<0)throw Error(`Invalid auth scopes. Scopes must include: ${nd}`);return t}else return t={scopes:[nd]},t}
271
+ /**
272
+ * @license
273
+ * Copyright 2025 Google LLC
274
+ * SPDX-License-Identifier: Apache-2.0
275
+ */
276
+ var ad=class{async download(e,t){if(e.downloadPath){let n=await od(e,t);if(n instanceof Cn){let t=f(e.downloadPath);m.fromWeb(n.responseInternal.body).pipe(t),await p(t)}else try{await d(e.downloadPath,n,{encoding:`base64`})}catch(t){throw Error(`Failed to write file to ${e.downloadPath}: ${t}`)}}}};async function od(e,t){let n=xr(e.file);if(n!==void 0)return await t.request({path:`files/${n}:download`,httpMethod:`GET`,queryParams:{alt:`media`},httpOptions:e.config?.httpOptions,abortSignal:e.config?.abortSignal});if(yr(e.file)){let t=e.file.video?.videoBytes;if(typeof t==`string`)return t;throw Error(`Failed to download generated video, Uri or videoBytes not found.`)}else if(br(e.file)){let t=e.file.videoBytes;if(typeof t==`string`)return t;throw Error(`Failed to download video, Uri or videoBytes not found.`)}else throw Error(`Unsupported file type`)}
277
+ /**
278
+ * @license
279
+ * Copyright 2025 Google LLC
280
+ * SPDX-License-Identifier: Apache-2.0
281
+ */
282
+ var sd=class{create(e,t,n){return new cd(e,t,n)}},cd=class{constructor(e,t,n){this.url=e,this.headers=t,this.callbacks=n}connect(){this.ws=new g.WebSocket(this.url,{headers:this.headers}),this.ws.onopen=this.callbacks.onopen,this.ws.onerror=this.callbacks.onerror,this.ws.onclose=this.callbacks.onclose,this.ws.onmessage=this.callbacks.onmessage}send(e){if(this.ws===void 0)throw Error(`WebSocket is not connected`);this.ws.send(e)}close(){if(this.ws===void 0)throw Error(`WebSocket is not connected`);this.ws.close()}};
283
+ /**
284
+ * @license
285
+ * Copyright 2025 Google LLC
286
+ * SPDX-License-Identifier: Apache-2.0
287
+ */
288
+ function ld(e,t){let n={},r=I(e,[`name`]);return r!=null&&F(n,[`_url`,`name`],r),n}function ud(e,t){let n={},r=I(e,[`name`]);return r!=null&&F(n,[`_url`,`name`],r),n}function dd(e,t){let n={},r=I(e,[`sdkHttpResponse`]);return r!=null&&F(n,[`sdkHttpResponse`],r),n}function fd(e,t){let n={},r=I(e,[`sdkHttpResponse`]);return r!=null&&F(n,[`sdkHttpResponse`],r),n}function pd(e,t,n){let r={};if(I(e,[`validationDataset`])!==void 0)throw Error(`validationDataset parameter is not supported in Gemini API.`);let i=I(e,[`tunedModelDisplayName`]);if(t!==void 0&&i!=null&&F(t,[`displayName`],i),I(e,[`description`])!==void 0)throw Error(`description parameter is not supported in Gemini API.`);let a=I(e,[`epochCount`]);t!==void 0&&a!=null&&F(t,[`tuningTask`,`hyperparameters`,`epochCount`],a);let o=I(e,[`learningRateMultiplier`]);if(o!=null&&F(r,[`tuningTask`,`hyperparameters`,`learningRateMultiplier`],o),I(e,[`exportLastCheckpointOnly`])!==void 0)throw Error(`exportLastCheckpointOnly parameter is not supported in Gemini API.`);if(I(e,[`preTunedModelCheckpointId`])!==void 0)throw Error(`preTunedModelCheckpointId parameter is not supported in Gemini API.`);if(I(e,[`adapterSize`])!==void 0)throw Error(`adapterSize parameter is not supported in Gemini API.`);if(I(e,[`tuningMode`])!==void 0)throw Error(`tuningMode parameter is not supported in Gemini API.`);if(I(e,[`customBaseModel`])!==void 0)throw Error(`customBaseModel parameter is not supported in Gemini API.`);let s=I(e,[`batchSize`]);t!==void 0&&s!=null&&F(t,[`tuningTask`,`hyperparameters`,`batchSize`],s);let c=I(e,[`learningRate`]);if(t!==void 0&&c!=null&&F(t,[`tuningTask`,`hyperparameters`,`learningRate`],c),I(e,[`labels`])!==void 0)throw Error(`labels parameter is not supported in Gemini API.`);if(I(e,[`beta`])!==void 0)throw Error(`beta parameter is not supported in Gemini API.`);if(I(e,[`baseTeacherModel`])!==void 0)throw Error(`baseTeacherModel parameter is not supported in Gemini API.`);if(I(e,[`tunedTeacherModelSource`])!==void 0)throw Error(`tunedTeacherModelSource parameter is not supported in Gemini API.`);if(I(e,[`sftLossWeightMultiplier`])!==void 0)throw Error(`sftLossWeightMultiplier parameter is not supported in Gemini API.`);if(I(e,[`outputUri`])!==void 0)throw Error(`outputUri parameter is not supported in Gemini API.`);if(I(e,[`encryptionSpec`])!==void 0)throw Error(`encryptionSpec parameter is not supported in Gemini API.`);return r}function md(e,t,n){let r={},i=I(n,[`config`,`method`]);if(i===void 0&&(i=`SUPERVISED_FINE_TUNING`),i===`SUPERVISED_FINE_TUNING`){let n=I(e,[`validationDataset`]);t!==void 0&&n!=null&&F(t,[`supervisedTuningSpec`],jd(n))}else if(i===`PREFERENCE_TUNING`){let n=I(e,[`validationDataset`]);t!==void 0&&n!=null&&F(t,[`preferenceOptimizationSpec`],jd(n))}else if(i===`DISTILLATION`){let n=I(e,[`validationDataset`]);t!==void 0&&n!=null&&F(t,[`distillationSpec`],jd(n))}let a=I(e,[`tunedModelDisplayName`]);t!==void 0&&a!=null&&F(t,[`tunedModelDisplayName`],a);let o=I(e,[`description`]);t!==void 0&&o!=null&&F(t,[`description`],o);let s=I(n,[`config`,`method`]);if(s===void 0&&(s=`SUPERVISED_FINE_TUNING`),s===`SUPERVISED_FINE_TUNING`){let n=I(e,[`epochCount`]);t!==void 0&&n!=null&&F(t,[`supervisedTuningSpec`,`hyperParameters`,`epochCount`],n)}else if(s===`PREFERENCE_TUNING`){let n=I(e,[`epochCount`]);t!==void 0&&n!=null&&F(t,[`preferenceOptimizationSpec`,`hyperParameters`,`epochCount`],n)}else if(s===`DISTILLATION`){let n=I(e,[`epochCount`]);t!==void 0&&n!=null&&F(t,[`distillationSpec`,`hyperParameters`,`epochCount`],n)}let c=I(n,[`config`,`method`]);if(c===void 0&&(c=`SUPERVISED_FINE_TUNING`),c===`SUPERVISED_FINE_TUNING`){let n=I(e,[`learningRateMultiplier`]);t!==void 0&&n!=null&&F(t,[`supervisedTuningSpec`,`hyperParameters`,`learningRateMultiplier`],n)}else if(c===`PREFERENCE_TUNING`){let n=I(e,[`learningRateMultiplier`]);t!==void 0&&n!=null&&F(t,[`preferenceOptimizationSpec`,`hyperParameters`,`learningRateMultiplier`],n)}else if(c===`DISTILLATION`){let n=I(e,[`learningRateMultiplier`]);t!==void 0&&n!=null&&F(t,[`distillationSpec`,`hyperParameters`,`learningRateMultiplier`],n)}let l=I(n,[`config`,`method`]);if(l===void 0&&(l=`SUPERVISED_FINE_TUNING`),l===`SUPERVISED_FINE_TUNING`){let n=I(e,[`exportLastCheckpointOnly`]);t!==void 0&&n!=null&&F(t,[`supervisedTuningSpec`,`exportLastCheckpointOnly`],n)}else if(l===`PREFERENCE_TUNING`){let n=I(e,[`exportLastCheckpointOnly`]);t!==void 0&&n!=null&&F(t,[`preferenceOptimizationSpec`,`exportLastCheckpointOnly`],n)}else if(l===`DISTILLATION`){let n=I(e,[`exportLastCheckpointOnly`]);t!==void 0&&n!=null&&F(t,[`distillationSpec`,`exportLastCheckpointOnly`],n)}let u=I(n,[`config`,`method`]);if(u===void 0&&(u=`SUPERVISED_FINE_TUNING`),u===`SUPERVISED_FINE_TUNING`){let n=I(e,[`adapterSize`]);t!==void 0&&n!=null&&F(t,[`supervisedTuningSpec`,`hyperParameters`,`adapterSize`],n)}else if(u===`PREFERENCE_TUNING`){let n=I(e,[`adapterSize`]);t!==void 0&&n!=null&&F(t,[`preferenceOptimizationSpec`,`hyperParameters`,`adapterSize`],n)}else if(u===`DISTILLATION`){let n=I(e,[`adapterSize`]);t!==void 0&&n!=null&&F(t,[`distillationSpec`,`hyperParameters`,`adapterSize`],n)}let d=I(n,[`config`,`method`]);if(d===void 0&&(d=`SUPERVISED_FINE_TUNING`),d===`SUPERVISED_FINE_TUNING`){let n=I(e,[`tuningMode`]);t!==void 0&&n!=null&&F(t,[`supervisedTuningSpec`,`tuningMode`],n)}else if(d===`DISTILLATION`){let n=I(e,[`tuningMode`]);t!==void 0&&n!=null&&F(t,[`distillationSpec`,`tuningMode`],n)}let f=I(e,[`customBaseModel`]);t!==void 0&&f!=null&&F(t,[`customBaseModel`],f);let p=I(n,[`config`,`method`]);if(p===void 0&&(p=`SUPERVISED_FINE_TUNING`),p===`SUPERVISED_FINE_TUNING`){let n=I(e,[`batchSize`]);t!==void 0&&n!=null&&F(t,[`supervisedTuningSpec`,`hyperParameters`,`batchSize`],n)}else if(p===`DISTILLATION`){let n=I(e,[`batchSize`]);t!==void 0&&n!=null&&F(t,[`distillationSpec`,`hyperParameters`,`batchSize`],n)}let m=I(n,[`config`,`method`]);if(m===void 0&&(m=`SUPERVISED_FINE_TUNING`),m===`SUPERVISED_FINE_TUNING`){let n=I(e,[`learningRate`]);t!==void 0&&n!=null&&F(t,[`supervisedTuningSpec`,`hyperParameters`,`learningRate`],n)}else if(m===`DISTILLATION`){let n=I(e,[`learningRate`]);t!==void 0&&n!=null&&F(t,[`distillationSpec`,`hyperParameters`,`learningRate`],n)}let h=I(e,[`labels`]);t!==void 0&&h!=null&&F(t,[`labels`],h);let g=I(e,[`beta`]);t!==void 0&&g!=null&&F(t,[`preferenceOptimizationSpec`,`hyperParameters`,`beta`],g);let _=I(e,[`baseTeacherModel`]);t!==void 0&&_!=null&&F(t,[`distillationSpec`,`baseTeacherModel`],_);let v=I(e,[`tunedTeacherModelSource`]);t!==void 0&&v!=null&&F(t,[`distillationSpec`,`tunedTeacherModelSource`],v);let y=I(e,[`sftLossWeightMultiplier`]);t!==void 0&&y!=null&&F(t,[`distillationSpec`,`hyperParameters`,`sftLossWeightMultiplier`],y);let b=I(e,[`outputUri`]);t!==void 0&&b!=null&&F(t,[`outputUri`],b);let x=I(e,[`encryptionSpec`]);return t!==void 0&&x!=null&&F(t,[`encryptionSpec`],x),r}function hd(e,t){let n={},r=I(e,[`baseModel`]);r!=null&&F(n,[`baseModel`],r);let i=I(e,[`preTunedModel`]);i!=null&&F(n,[`preTunedModel`],i);let a=I(e,[`trainingDataset`]);a!=null&&Ed(a);let o=I(e,[`config`]);return o!=null&&pd(o,n),n}function gd(e,t){let n={},r=I(e,[`baseModel`]);r!=null&&F(n,[`baseModel`],r);let i=I(e,[`preTunedModel`]);i!=null&&F(n,[`preTunedModel`],i);let a=I(e,[`trainingDataset`]);a!=null&&Dd(a,n,t);let o=I(e,[`config`]);return o!=null&&md(o,n,t),n}function _d(e,t){let n={},r=I(e,[`name`]);return r!=null&&F(n,[`_url`,`name`],r),n}function vd(e,t){let n={},r=I(e,[`name`]);return r!=null&&F(n,[`_url`,`name`],r),n}function yd(e,t,n){let r={},i=I(e,[`pageSize`]);t!==void 0&&i!=null&&F(t,[`_query`,`pageSize`],i);let a=I(e,[`pageToken`]);t!==void 0&&a!=null&&F(t,[`_query`,`pageToken`],a);let o=I(e,[`filter`]);return t!==void 0&&o!=null&&F(t,[`_query`,`filter`],o),r}function bd(e,t,n){let r={},i=I(e,[`pageSize`]);t!==void 0&&i!=null&&F(t,[`_query`,`pageSize`],i);let a=I(e,[`pageToken`]);t!==void 0&&a!=null&&F(t,[`_query`,`pageToken`],a);let o=I(e,[`filter`]);return t!==void 0&&o!=null&&F(t,[`_query`,`filter`],o),r}function xd(e,t){let n={},r=I(e,[`config`]);return r!=null&&yd(r,n),n}function Sd(e,t){let n={},r=I(e,[`config`]);return r!=null&&bd(r,n),n}function Cd(e,t){let n={},r=I(e,[`sdkHttpResponse`]);r!=null&&F(n,[`sdkHttpResponse`],r);let i=I(e,[`nextPageToken`]);i!=null&&F(n,[`nextPageToken`],i);let a=I(e,[`tunedModels`]);if(a!=null){let e=a;Array.isArray(e)&&(e=e.map(e=>Od(e))),F(n,[`tuningJobs`],e)}return n}function wd(e,t){let n={},r=I(e,[`sdkHttpResponse`]);r!=null&&F(n,[`sdkHttpResponse`],r);let i=I(e,[`nextPageToken`]);i!=null&&F(n,[`nextPageToken`],i);let a=I(e,[`tuningJobs`]);if(a!=null){let e=a;Array.isArray(e)&&(e=e.map(e=>kd(e))),F(n,[`tuningJobs`],e)}return n}function Td(e,t){let n={},r=I(e,[`name`]);r!=null&&F(n,[`model`],r);let i=I(e,[`name`]);return i!=null&&F(n,[`endpoint`],i),n}function Ed(e,t){let n={};if(I(e,[`gcsUri`])!==void 0)throw Error(`gcsUri parameter is not supported in Gemini API.`);if(I(e,[`vertexDatasetResource`])!==void 0)throw Error(`vertexDatasetResource parameter is not supported in Gemini API.`);let r=I(e,[`examples`]);if(r!=null){let e=r;Array.isArray(e)&&(e=e.map(e=>e)),F(n,[`examples`,`examples`],e)}return n}function Dd(e,t,n){let r={},i=I(n,[`config`,`method`]);if(i===void 0&&(i=`SUPERVISED_FINE_TUNING`),i===`SUPERVISED_FINE_TUNING`){let n=I(e,[`gcsUri`]);t!==void 0&&n!=null&&F(t,[`supervisedTuningSpec`,`trainingDatasetUri`],n)}else if(i===`PREFERENCE_TUNING`){let n=I(e,[`gcsUri`]);t!==void 0&&n!=null&&F(t,[`preferenceOptimizationSpec`,`trainingDatasetUri`],n)}else if(i===`DISTILLATION`){let n=I(e,[`gcsUri`]);t!==void 0&&n!=null&&F(t,[`distillationSpec`,`promptDatasetUri`],n)}let a=I(n,[`config`,`method`]);if(a===void 0&&(a=`SUPERVISED_FINE_TUNING`),a===`SUPERVISED_FINE_TUNING`){let n=I(e,[`vertexDatasetResource`]);t!==void 0&&n!=null&&F(t,[`supervisedTuningSpec`,`trainingDatasetUri`],n)}else if(a===`PREFERENCE_TUNING`){let n=I(e,[`vertexDatasetResource`]);t!==void 0&&n!=null&&F(t,[`preferenceOptimizationSpec`,`trainingDatasetUri`],n)}else if(a===`DISTILLATION`){let n=I(e,[`vertexDatasetResource`]);t!==void 0&&n!=null&&F(t,[`distillationSpec`,`promptDatasetUri`],n)}if(I(e,[`examples`])!==void 0)throw Error(`examples parameter is not supported in Vertex AI.`);return r}function Od(e,t){let n={},r=I(e,[`sdkHttpResponse`]);r!=null&&F(n,[`sdkHttpResponse`],r);let i=I(e,[`name`]);i!=null&&F(n,[`name`],i);let a=I(e,[`state`]);a!=null&&F(n,[`state`],_r(a));let o=I(e,[`createTime`]);o!=null&&F(n,[`createTime`],o);let s=I(e,[`tuningTask`,`startTime`]);s!=null&&F(n,[`startTime`],s);let c=I(e,[`tuningTask`,`completeTime`]);c!=null&&F(n,[`endTime`],c);let l=I(e,[`updateTime`]);l!=null&&F(n,[`updateTime`],l);let u=I(e,[`description`]);u!=null&&F(n,[`description`],u);let d=I(e,[`baseModel`]);d!=null&&F(n,[`baseModel`],d);let f=I(e,[`_self`]);return f!=null&&F(n,[`tunedModel`],Td(f)),n}function kd(e,t){let n={},r=I(e,[`sdkHttpResponse`]);r!=null&&F(n,[`sdkHttpResponse`],r);let i=I(e,[`name`]);i!=null&&F(n,[`name`],i);let a=I(e,[`state`]);a!=null&&F(n,[`state`],_r(a));let o=I(e,[`createTime`]);o!=null&&F(n,[`createTime`],o);let s=I(e,[`startTime`]);s!=null&&F(n,[`startTime`],s);let c=I(e,[`endTime`]);c!=null&&F(n,[`endTime`],c);let l=I(e,[`updateTime`]);l!=null&&F(n,[`updateTime`],l);let u=I(e,[`error`]);u!=null&&F(n,[`error`],u);let d=I(e,[`description`]);d!=null&&F(n,[`description`],d);let f=I(e,[`baseModel`]);f!=null&&F(n,[`baseModel`],f);let p=I(e,[`tunedModel`]);p!=null&&F(n,[`tunedModel`],p);let m=I(e,[`preTunedModel`]);m!=null&&F(n,[`preTunedModel`],m);let h=I(e,[`supervisedTuningSpec`]);h!=null&&F(n,[`supervisedTuningSpec`],h);let g=I(e,[`preferenceOptimizationSpec`]);g!=null&&F(n,[`preferenceOptimizationSpec`],g);let _=I(e,[`distillationSpec`]);_!=null&&F(n,[`distillationSpec`],_);let v=I(e,[`tuningDataStats`]);v!=null&&F(n,[`tuningDataStats`],v);let y=I(e,[`encryptionSpec`]);y!=null&&F(n,[`encryptionSpec`],y);let b=I(e,[`partnerModelTuningSpec`]);b!=null&&F(n,[`partnerModelTuningSpec`],b);let x=I(e,[`customBaseModel`]);x!=null&&F(n,[`customBaseModel`],x);let S=I(e,[`evaluateDatasetRuns`]);if(S!=null){let e=S;Array.isArray(e)&&(e=e.map(e=>e)),F(n,[`evaluateDatasetRuns`],e)}let C=I(e,[`experiment`]);C!=null&&F(n,[`experiment`],C);let w=I(e,[`fullFineTuningSpec`]);w!=null&&F(n,[`fullFineTuningSpec`],w);let T=I(e,[`labels`]);T!=null&&F(n,[`labels`],T);let E=I(e,[`outputUri`]);E!=null&&F(n,[`outputUri`],E);let D=I(e,[`pipelineJob`]);D!=null&&F(n,[`pipelineJob`],D);let O=I(e,[`serviceAccount`]);O!=null&&F(n,[`serviceAccount`],O);let k=I(e,[`tunedModelDisplayName`]);k!=null&&F(n,[`tunedModelDisplayName`],k);let ee=I(e,[`tuningJobState`]);ee!=null&&F(n,[`tuningJobState`],ee);let te=I(e,[`veoTuningSpec`]);te!=null&&F(n,[`veoTuningSpec`],te);let A=I(e,[`distillationSamplingSpec`]);A!=null&&F(n,[`distillationSamplingSpec`],A);let ne=I(e,[`tuningJobMetadata`]);return ne!=null&&F(n,[`tuningJobMetadata`],ne),n}function Ad(e,t){let n={},r=I(e,[`sdkHttpResponse`]);r!=null&&F(n,[`sdkHttpResponse`],r);let i=I(e,[`name`]);i!=null&&F(n,[`name`],i);let a=I(e,[`metadata`]);a!=null&&F(n,[`metadata`],a);let o=I(e,[`done`]);o!=null&&F(n,[`done`],o);let s=I(e,[`error`]);return s!=null&&F(n,[`error`],s),n}function jd(e,t){let n={},r=I(e,[`gcsUri`]);r!=null&&F(n,[`validationDatasetUri`],r);let i=I(e,[`vertexDatasetResource`]);return i!=null&&F(n,[`validationDatasetUri`],i),n}
289
+ /**
290
+ * @license
291
+ * Copyright 2025 Google LLC
292
+ * SPDX-License-Identifier: Apache-2.0
293
+ */
294
+ var Md=class extends N{constructor(e){super(),this.apiClient=e,this.list=async(e={})=>new ki(U.PAGED_ITEM_TUNING_JOBS,e=>this.listInternal(e),await this.listInternal(e),e),this.get=async e=>await this.getInternal(e),this.tune=async e=>{if(this.apiClient.isVertexAI())if(e.baseModel.startsWith(`projects/`)){let t={tunedModelName:e.baseModel};e.config?.preTunedModelCheckpointId&&(t.checkpointId=e.config.preTunedModelCheckpointId);let n=Object.assign(Object.assign({},e),{preTunedModel:t});return n.baseModel=void 0,await this.tuneInternal(n)}else{let t=Object.assign({},e);return await this.tuneInternal(t)}else{let t=Object.assign({},e),n=await this.tuneMldevInternal(t),r=``;return n.metadata!==void 0&&n.metadata.tunedModel!==void 0?r=n.metadata.tunedModel:n.name!==void 0&&n.name.includes(`/operations/`)&&(r=n.name.split(`/operations/`)[0]),{name:r,state:Bt.JOB_STATE_QUEUED}}}}async getInternal(e){let t,n=``,r={};if(this.apiClient.isVertexAI()){let i=vd(e);return n=P(`{name}`,i._url),r=i._query,delete i._url,delete i._query,t=this.apiClient.request({path:n,queryParams:r,body:JSON.stringify(i),httpMethod:`GET`,httpOptions:e.config?.httpOptions,abortSignal:e.config?.abortSignal}).then(e=>e.json().then(t=>{let n=t;return n.sdkHttpResponse={headers:e.headers},n})),t.then(e=>kd(e))}else{let i=_d(e);return n=P(`{name}`,i._url),r=i._query,delete i._url,delete i._query,t=this.apiClient.request({path:n,queryParams:r,body:JSON.stringify(i),httpMethod:`GET`,httpOptions:e.config?.httpOptions,abortSignal:e.config?.abortSignal}).then(e=>e.json().then(t=>{let n=t;return n.sdkHttpResponse={headers:e.headers},n})),t.then(e=>Od(e))}}async listInternal(e){let t,n=``,r={};if(this.apiClient.isVertexAI()){let i=Sd(e);return n=P(`tuningJobs`,i._url),r=i._query,delete i._url,delete i._query,t=this.apiClient.request({path:n,queryParams:r,body:JSON.stringify(i),httpMethod:`GET`,httpOptions:e.config?.httpOptions,abortSignal:e.config?.abortSignal}).then(e=>e.json().then(t=>{let n=t;return n.sdkHttpResponse={headers:e.headers},n})),t.then(e=>{let t=wd(e),n=new In;return Object.assign(n,t),n})}else{let i=xd(e);return n=P(`tunedModels`,i._url),r=i._query,delete i._url,delete i._query,t=this.apiClient.request({path:n,queryParams:r,body:JSON.stringify(i),httpMethod:`GET`,httpOptions:e.config?.httpOptions,abortSignal:e.config?.abortSignal}).then(e=>e.json().then(t=>{let n=t;return n.sdkHttpResponse={headers:e.headers},n})),t.then(e=>{let t=Cd(e),n=new In;return Object.assign(n,t),n})}}async cancel(e){let t,n=``,r={};if(this.apiClient.isVertexAI()){let i=ud(e);return n=P(`{name}:cancel`,i._url),r=i._query,delete i._url,delete i._query,t=this.apiClient.request({path:n,queryParams:r,body:JSON.stringify(i),httpMethod:`POST`,httpOptions:e.config?.httpOptions,abortSignal:e.config?.abortSignal}).then(e=>e.json().then(t=>{let n=t;return n.sdkHttpResponse={headers:e.headers},n})),t.then(e=>{let t=fd(e),n=new Ln;return Object.assign(n,t),n})}else{let i=ld(e);return n=P(`{name}:cancel`,i._url),r=i._query,delete i._url,delete i._query,t=this.apiClient.request({path:n,queryParams:r,body:JSON.stringify(i),httpMethod:`POST`,httpOptions:e.config?.httpOptions,abortSignal:e.config?.abortSignal}).then(e=>e.json().then(t=>{let n=t;return n.sdkHttpResponse={headers:e.headers},n})),t.then(e=>{let t=dd(e),n=new Ln;return Object.assign(n,t),n})}}async tuneInternal(e){let t,n=``,r={};if(this.apiClient.isVertexAI()){let i=gd(e,e);return n=P(`tuningJobs`,i._url),r=i._query,delete i._url,delete i._query,t=this.apiClient.request({path:n,queryParams:r,body:JSON.stringify(i),httpMethod:`POST`,httpOptions:e.config?.httpOptions,abortSignal:e.config?.abortSignal}).then(e=>e.json().then(t=>{let n=t;return n.sdkHttpResponse={headers:e.headers},n})),t.then(e=>kd(e))}else throw Error(`This method is only supported by the Vertex AI.`)}async tuneMldevInternal(e){let t,n=``,r={};if(this.apiClient.isVertexAI())throw Error(`This method is only supported by the Gemini Developer API.`);{let i=hd(e);return n=P(`tunedModels`,i._url),r=i._query,delete i._url,delete i._query,t=this.apiClient.request({path:n,queryParams:r,body:JSON.stringify(i),httpMethod:`POST`,httpOptions:e.config?.httpOptions,abortSignal:e.config?.abortSignal}).then(e=>e.json().then(t=>{let n=t;return n.sdkHttpResponse={headers:e.headers},n})),t.then(e=>Ad(e))}}};const Nd=1024*1024*8,Pd=1e3,Fd=`x-goog-upload-status`;async function Id(e,t,n,r){let i=await Rd(e,t,n,r),a=await i?.json();if(i?.headers?.[Fd]!==`final`)throw Error(`Failed to upload file: Upload status is not finalized.`);return a.file}async function Ld(e,t,n,r){let i=await Rd(e,t,n,r),a=await i?.json();if(i?.headers?.[Fd]!==`final`)throw Error(`Failed to upload file: Upload status is not finalized.`);let o=ct(a),s=new Zn;return Object.assign(s,o),s}async function Rd(e,t,n,r){let i=t,a=r?.baseUrl||n.clientOptions.httpOptions?.baseUrl;if(a){let e=new URL(a),n=new URL(t);n.protocol=e.protocol,n.host=e.host,n.port=e.port,i=n.toString()}let o=0,s=0,c=new Cn(new Response),l=`upload`;for(o=e.size;s<o;){let t=Math.min(Nd,o-s),a=e.slice(s,s+t);s+t>=o&&(l+=`, finalize`);let u=0,d=Pd;for(;u<3;){let e=Object.assign(Object.assign({},r?.headers||{}),{"X-Goog-Upload-Command":l,"X-Goog-Upload-Offset":String(s),"Content-Length":String(t)});if(c=await n.request({path:``,body:a,httpMethod:`POST`,httpOptions:Object.assign(Object.assign({},r),{apiVersion:``,baseUrl:i,headers:e})}),c?.headers?.[Fd])break;u++,await Bd(d),d*=2}if(s+=t,c?.headers?.[Fd]!==`active`)break;if(o<=s)throw Error(`All content has been uploaded, but the upload status is not finalized.`)}return c}async function zd(e){return{size:e.size,type:e.type}}function Bd(e){return new Promise(t=>setTimeout(t,e))}
295
+ /**
296
+ * @license
297
+ * Copyright 2025 Google LLC
298
+ * SPDX-License-Identifier: Apache-2.0
299
+ */
300
+ var Vd=class{async stat(e){let t={size:0,type:void 0};return typeof e==`string`?(t.size=(await u.stat(e)).size,t.type=this.inferMimeType(e),t):await zd(e)}async upload(e,t,n,r){return typeof e==`string`?await this.uploadFileFromPath(e,t,n,r):Id(e,t,n,r)}async uploadToFileSearchStore(e,t,n,r){return typeof e==`string`?await this.uploadFileToFileSearchStoreFromPath(e,t,n,r):Ld(e,t,n,r)}inferMimeType(e){return{aac:`audio/aac`,abw:`application/x-abiword`,arc:`application/x-freearc`,avi:`video/x-msvideo`,azw:`application/vnd.amazon.ebook`,bin:`application/octet-stream`,bmp:`image/bmp`,bz:`application/x-bzip`,bz2:`application/x-bzip2`,csh:`application/x-csh`,css:`text/css`,csv:`text/csv`,doc:`application/msword`,docx:`application/vnd.openxmlformats-officedocument.wordprocessingml.document`,eot:`application/vnd.ms-fontobject`,epub:`application/epub+zip`,gz:`application/gzip`,gif:`image/gif`,htm:`text/html`,html:`text/html`,ico:`image/vnd.microsoft.icon`,ics:`text/calendar`,jar:`application/java-archive`,jpeg:`image/jpeg`,jpg:`image/jpeg`,js:`text/javascript`,json:`application/json`,jsonld:`application/ld+json`,kml:`application/vnd.google-earth.kml+xml`,kmz:`application/vnd.google-earth.kmz+xml`,mjs:`text/javascript`,mp3:`audio/mpeg`,mp4:`video/mp4`,mpeg:`video/mpeg`,mpkg:`application/vnd.apple.installer+xml`,odt:`application/vnd.oasis.opendocument.text`,oga:`audio/ogg`,ogv:`video/ogg`,ogx:`application/ogg`,opus:`audio/opus`,otf:`font/otf`,png:`image/png`,pdf:`application/pdf`,php:`application/x-httpd-php`,ppt:`application/vnd.ms-powerpoint`,pptx:`application/vnd.openxmlformats-officedocument.presentationml.presentation`,rar:`application/vnd.rar`,rtf:`application/rtf`,sh:`application/x-sh`,svg:`image/svg+xml`,swf:`application/x-shockwave-flash`,tar:`application/x-tar`,tif:`image/tiff`,tiff:`image/tiff`,ts:`video/mp2t`,ttf:`font/ttf`,txt:`text/plain`,vsd:`application/vnd.visio`,wav:`audio/wav`,weba:`audio/webm`,webm:`video/webm`,webp:`image/webp`,woff:`font/woff`,woff2:`font/woff2`,xhtml:`application/xhtml+xml`,xls:`application/vnd.ms-excel`,xlsx:`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`,xml:`application/xml`,xul:`application/vnd.mozilla.xul+xml`,zip:`application/zip`,"3gp":`video/3gpp`,"3g2":`video/3gpp2`,"7z":`application/x-7z-compressed`}[e.slice(e.lastIndexOf(`.`)+1).toLowerCase()]}async uploadFileFromPath(e,t,n,r){let i=await this.uploadFileFromPathInternal(e,t,n,r),a=await i?.json();if(i?.headers?.[Fd]!==`final`)throw Error(`Failed to upload file: Upload status is not finalized.`);return a.file}async uploadFileToFileSearchStoreFromPath(e,t,n,r){let i=await this.uploadFileFromPathInternal(e,t,n,r),a=await i?.json();if(i?.headers?.[Fd]!==`final`)throw Error(`Failed to upload file: Upload status is not finalized.`);let o=ct(a),s=new Zn;return Object.assign(s,o),s}async uploadFileFromPathInternal(e,t,n,r){let i=t,a=r?.baseUrl||n.clientOptions.httpOptions?.baseUrl;if(a){let e=new URL(a),n=new URL(t);n.protocol=e.protocol,n.host=e.host,n.port=e.port,i=n.toString()}let o=0,s=0,c=new Cn(new Response),l=`upload`,d,f=h.basename(e);try{if(d=await u.open(e,`r`),!d)throw Error(`Failed to open file`);for(o=(await d.stat()).size;s<o;){let e=Math.min(Nd,o-s);s+e>=o&&(l+=`, finalize`);let t=new Uint8Array(e),{bytesRead:a}=await d.read(t,0,e,s);if(a!==e)throw Error(`Failed to read ${e} bytes from file at offset ${s}. bytes actually read: ${a}`);let u=new Blob([t]),p=0,m=Pd;for(;p<3;){let e=Object.assign(Object.assign({},r?.headers||{}),{"X-Goog-Upload-Command":l,"X-Goog-Upload-Offset":String(s),"Content-Length":String(a),"X-Goog-Upload-File-Name":f});if(c=await n.request({path:``,body:u,httpMethod:`POST`,httpOptions:Object.assign(Object.assign({},r),{apiVersion:``,baseUrl:i,headers:e})}),c?.headers?.[Fd])break;p++,await Bd(m),m*=2}if(s+=a,c?.headers?.[Fd]!==`active`)break;if(o<=s)throw Error(`All content has been uploaded, but the upload status is not finalized.`)}return c}finally{d&&await d.close()}}},Hd=class extends Ma{async registerFiles(e){if(typeof process>`u`||!process.versions||!process.versions.node)throw Error(`registerFiles is only supported in Node.js environments.`);let t=await e.auth.getRequestHeaders(),n=e.config||{},r=n.httpOptions||{},i=Object.assign({},r.headers||{});if(t)if(typeof t[Symbol.iterator]==`function`)for(let[e,n]of t)i[e]=n;else for(let[e,n]of Object.entries(t))i[e]=n;return this._registerFiles({uris:e.uris,config:Object.assign(Object.assign({},n),{httpOptions:Object.assign(Object.assign({},r),{headers:i})})})}},Ud=class{getNextGenClient(){let e=this.httpOptions;return this._nextGenClient===void 0&&(this._nextGenClient=new $({baseURL:this.apiClient.getBaseUrl(),apiKey:this.apiKey,apiVersion:this.apiClient.getApiVersion(),clientAdapter:this.apiClient,defaultHeaders:this.apiClient.getDefaultHeaders(),timeout:e?.timeout,maxRetries:e?.retryOptions?.attempts})),e?.extraBody&&console.warn(`GoogleGenAI.interactions: Client level httpOptions.extraBody is not supported by the interactions client and will be ignored.`),this._nextGenClient}get interactions(){return this._interactions===void 0?(console.warn(`GoogleGenAI.interactions: Interactions usage is experimental and may change in future versions.`),this._interactions=this.getNextGenClient().interactions,this._interactions):this._interactions}get webhooks(){return this._webhooks===void 0&&(this._webhooks=this.getNextGenClient().webhooks),this._webhooks}constructor(e){if((e.project||e.location)&&e.apiKey)throw Error(`Project/location and API key are mutually exclusive in the client initializer.`);this.vertexai=e.vertexai??Gd(`GOOGLE_GENAI_USE_VERTEXAI`)??!1;let t=qd(),n=Wd(`GOOGLE_CLOUD_PROJECT`),r=Wd(`GOOGLE_CLOUD_LOCATION`);this.apiKey=e.apiKey??t,this.project=e.project??n,this.location=e.location??r,!this.vertexai&&!this.apiKey&&console.warn(`API key should be set when using the Gemini API.`),e.vertexai&&(e.googleAuthOptions?.credentials&&(console.debug(`The user provided Google Cloud credentials will take precedence over the API key from the environment variable.`),this.apiKey=void 0),(n||r)&&e.apiKey?(console.debug(`The user provided Vertex AI API key will take precedence over the project/location from the environment variables.`),this.project=void 0,this.location=void 0):(e.project||e.location)&&t?(console.debug(`The user provided project/location will take precedence over the API key from the environment variables.`),this.apiKey=void 0):(n||r)&&t&&(console.debug(`The project/location from the environment variables will take precedence over the API key from the environment variables.`),this.apiKey=void 0),!this.location&&!this.apiKey&&(this.location=`global`));let i=qe(e.httpOptions,e.vertexai,Wd(`GOOGLE_VERTEX_BASE_URL`),Wd(`GOOGLE_GEMINI_BASE_URL`));i&&(e.httpOptions?e.httpOptions.baseUrl=i:e.httpOptions={baseUrl:i}),this.apiVersion=e.apiVersion,this.httpOptions=e.httpOptions;let a=new rd({apiKey:this.apiKey,googleAuthOptions:e.googleAuthOptions});this.apiClient=new Fc({auth:a,project:this.project,location:this.location,apiVersion:this.apiVersion,apiKey:this.apiKey,vertexai:this.vertexai,httpOptions:this.httpOptions,userAgentExtra:`gl-node/`+process.version,uploader:new Vd,downloader:new ad}),this.models=new al(this.apiClient),this.live=new Yc(this.apiClient,a,new sd),this.batches=new Ai(this.apiClient),this.chats=new ya(this.models,this.apiClient),this.caches=new pa(this.apiClient),this.files=new Hd(this.apiClient),this.operations=new ol(this.apiClient),this.authTokens=new Tl(this.apiClient),this.tunings=new Md(this.apiClient),this.fileSearchStores=new Nl(this.apiClient)}};function Wd(e){return((process==null?void 0:process.env)?.[e])?.trim()??void 0}function Gd(e){return Kd(Wd(e))}function Kd(e){return e===void 0?!1:e.toLowerCase()===`true`}function qd(){let e=Wd(`GOOGLE_API_KEY`),t=Wd(`GEMINI_API_KEY`);return e&&t&&console.warn(`Both GOOGLE_API_KEY and GEMINI_API_KEY are set. Using GOOGLE_API_KEY.`),e||t||void 0}function Jd(e){return e.thought===!0}function Yd(e,t){return typeof t==`string`&&t.length>0?t:e}const Xd=/^[A-Za-z0-9+/]+={0,2}$/;function Zd(e){return!e||e.length%4!=0?!1:Xd.test(e)}function Qd(e,t){return e&&Zd(t)?t:void 0}function $d(e){return e.startsWith(`claude-`)||e.startsWith(`gpt-oss-`)}function ef(e){let t=e.toLowerCase().match(/^gemini(?:-live)?-(\d+)/);if(t)return Number.parseInt(t[1],10)}function tf(e){let t=ef(e);return t===void 0?!0:t>=3}function nf(e,t){let n=[],a=i(t.messages,e,t=>$d(e.id)?t.replace(/[^a-zA-Z0-9_-]/g,`_`).slice(0,64):t);for(let t of a)if(t.role===`user`)if(typeof t.content==`string`)n.push({role:`user`,parts:[{text:r(t.content)}]});else{let e=t.content.map(e=>e.type===`text`?{text:r(e.text)}:{inlineData:{mimeType:e.mimeType,data:e.data}});if(e.length===0)continue;n.push({role:`user`,parts:e})}else if(t.role===`assistant`){let i=[],a=t.provider===e.provider&&t.model===e.id;for(let n of t.content)if(n.type===`text`){if(!n.text||n.text.trim()===``)continue;let e=Qd(a,n.textSignature);i.push({text:r(n.text),...e&&{thoughtSignature:e}})}else if(n.type===`thinking`){if(!n.thinking||n.thinking.trim()===``)continue;if(a){let e=Qd(a,n.thinkingSignature);i.push({thought:!0,text:r(n.thinking),...e&&{thoughtSignature:e}})}else i.push({text:r(n.thinking)})}else if(n.type===`toolCall`){let t=Qd(a,n.thoughtSignature),r=e.id.toLowerCase().includes(`gemini-3`),o=t||(r?`skip_thought_signature_validator`:void 0),s={functionCall:{name:n.name,args:n.arguments??{},...$d(e.id)?{id:n.id}:{}},...o&&{thoughtSignature:o}};i.push(s)}if(i.length===0)continue;n.push({role:`model`,parts:i})}else if(t.role===`toolResult`){let i=t.content.filter(e=>e.type===`text`).map(e=>e.text).join(`
301
+ `),a=e.input.includes(`image`)?t.content.filter(e=>e.type===`image`):[],o=i.length>0,s=a.length>0,c=tf(e.id),l=o?r(i):s?`(see attached image)`:``,u=a.map(e=>({inlineData:{mimeType:e.mimeType,data:e.data}})),d=$d(e.id),f={functionResponse:{name:t.toolName,response:t.isError?{error:l}:{output:l},...s&&c&&{parts:u},...d?{id:t.toolCallId}:{}}},p=n[n.length-1];p?.role===`user`&&p.parts?.some(e=>e.functionResponse)?p.parts.push(f):n.push({role:`user`,parts:[f]}),s&&!c&&n.push({role:`user`,parts:[{text:`Tool result image:`},...u]})}return n}const rf=new Set([`$schema`,`$id`,`$anchor`,`$dynamicAnchor`,`$vocabulary`,`$comment`,`$defs`,`definitions`]);function af(e){if(typeof e!=`object`||!e||Array.isArray(e))return e;let t={};for(let[n,r]of Object.entries(e))rf.has(n)||(t[n]=af(r));return t}function of(e,t=!1){if(e.length!==0)return[{functionDeclarations:e.map(e=>({name:e.name,description:e.description,...t?{parameters:af(e.parameters)}:{parametersJsonSchema:e.parameters}}))}]}function sf(e){switch(e){case`auto`:return Ct.AUTO;case`none`:return Ct.NONE;case`any`:return Ct.ANY;default:return Ct.AUTO}}function cf(e){switch(e){case L.STOP:return`stop`;case L.MAX_TOKENS:return`length`;case L.BLOCKLIST:case L.PROHIBITED_CONTENT:case L.SPII:case L.SAFETY:case L.IMAGE_SAFETY:case L.IMAGE_PROHIBITED_CONTENT:case L.IMAGE_RECITATION:case L.IMAGE_OTHER:case L.RECITATION:case L.FINISH_REASON_UNSPECIFIED:case L.OTHER:case L.LANGUAGE:case L.MALFORMED_FUNCTION_CALL:case L.UNEXPECTED_TOOL_CALL:case L.NO_IMAGE:return`error`;default:throw Error(`Unhandled stop reason: ${e}`)}}function lf(e){switch(e){case`STOP`:return`stop`;case`MAX_TOKENS`:return`length`;default:return`error`}}export{lf as a,Ud as c,cf as i,wt as l,of as n,sf as o,Jd as r,Yd as s,nf as t};