@pen.dev/cli 0.2.8

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 (94) hide show
  1. package/LICENSE +66 -0
  2. package/README.md +369 -0
  3. package/SKILL.md +175 -0
  4. package/dist/all-Bd-ariyL.mjs +2 -0
  5. package/dist/anthropic-messages-D9L1s6pn.mjs +40 -0
  6. package/dist/anthropic-messages-OUY8OJj7.mjs +40 -0
  7. package/dist/azure-openai-responses-DJKVhgL-.mjs +2 -0
  8. package/dist/azure-openai-responses-DSoXDHyP.mjs +2 -0
  9. package/dist/browserAll-CGZu5S9C.mjs +2 -0
  10. package/dist/completionchunk-BaC49qbM.mjs +28 -0
  11. package/dist/completionchunk-c1fsGiUK.mjs +2 -0
  12. package/dist/diagnostics-hlO-DFfk.mjs +2 -0
  13. package/dist/dist-BMO4tFTj.mjs +1576 -0
  14. package/dist/dist-BupqiQep.mjs +10 -0
  15. package/dist/dist-CCiXmKIu.mjs +10 -0
  16. package/dist/dist-Dq7S86ex.mjs +4 -0
  17. package/dist/emscripten-module.browser-F76W5DM6-3XbeCXXF.mjs +5147 -0
  18. package/dist/emscripten-module.browser-XIKQQPVU-JPkxo8p_.mjs +2160 -0
  19. package/dist/error-body-D-jnPxbB.mjs +2 -0
  20. package/dist/esm-D7vjDQPJ.mjs +2 -0
  21. package/dist/esm-DZA7B0U9.mjs +25 -0
  22. package/dist/ffi-D6Fxg1d3.mjs +2 -0
  23. package/dist/ffi-u92ceo2s.mjs +2 -0
  24. package/dist/from-BRY6g9CG.mjs +15 -0
  25. package/dist/from-Bra_AO5N.mjs +15 -0
  26. package/dist/github-copilot-headers-ByQsj8SR.mjs +2 -0
  27. package/dist/github-copilot-headers-C4gA1Pjv.mjs +2 -0
  28. package/dist/google-generative-ai-BqfOLKon.mjs +2 -0
  29. package/dist/google-generative-ai-CZCmY9Gg.mjs +2 -0
  30. package/dist/google-shared-TkwodIGJ.mjs +318 -0
  31. package/dist/google-shared-YCDndJGN.mjs +318 -0
  32. package/dist/google-vertex-COsje8-Z.mjs +2 -0
  33. package/dist/google-vertex-Cz5Ddo09.mjs +2 -0
  34. package/dist/hash-BFdQp5Bn.mjs +2 -0
  35. package/dist/hash-DFXd8wf4.mjs +2 -0
  36. package/dist/headers-BkXFKypW.mjs +2 -0
  37. package/dist/headers-DtjIrAKV.mjs +2 -0
  38. package/dist/html-DwPxy9Y2.mjs +26 -0
  39. package/dist/index.mjs +8 -0
  40. package/dist/init-BaeOBiNV.mjs +2 -0
  41. package/dist/json-parse-BEWPMC87.mjs +4 -0
  42. package/dist/json-parse-qcO5FIDw.mjs +4 -0
  43. package/dist/mistral-conversations-DIR6EyvH.mjs +8 -0
  44. package/dist/mistral-conversations-JED5QLUZ.mjs +10 -0
  45. package/dist/models-CtsqYGxn.mjs +2 -0
  46. package/dist/models-DVeZ-5Ql.mjs +2 -0
  47. package/dist/module-ES6BEMUI-DGywGVC7.mjs +2 -0
  48. package/dist/module-asyncify-2EFITU5U-BU2CORSO.mjs +2 -0
  49. package/dist/multipart-parser-4wzMiNnD.mjs +3 -0
  50. package/dist/multipart-parser-CYJPmLQW.mjs +3 -0
  51. package/dist/node_modules/@highagency/pencil-wasm/enums.gen.d.ts +247 -0
  52. package/dist/node_modules/@highagency/pencil-wasm/package.json +26 -0
  53. package/dist/node_modules/@highagency/pencil-wasm/pencil.d.ts +769 -0
  54. package/dist/node_modules/@highagency/pencil-wasm/pencil.js +1 -0
  55. package/dist/node_modules/@highagency/pencil-wasm/pencil.wasm +0 -0
  56. package/dist/openai-CJ1JzbCY.mjs +17 -0
  57. package/dist/openai-Cv91uXJB.mjs +17 -0
  58. package/dist/openai-codex-responses-Cq8yFwfN.mjs +8 -0
  59. package/dist/openai-codex-responses-CzFfnGCe.mjs +8 -0
  60. package/dist/openai-completions-DT4sdoVc.mjs +6 -0
  61. package/dist/openai-completions-iO6yRDuR.mjs +6 -0
  62. package/dist/openai-prompt-cache-CjAED4AP.mjs +2 -0
  63. package/dist/openai-prompt-cache-tVxLccHG.mjs +2 -0
  64. package/dist/openai-responses-Cr3SvtkS.mjs +2 -0
  65. package/dist/openai-responses-Dtr2Vk2j.mjs +2 -0
  66. package/dist/openai-responses-shared-BLDoTd9K.mjs +13 -0
  67. package/dist/openai-responses-shared-C4PQs_0V.mjs +11 -0
  68. package/dist/openrouter-images-Dk-x2ke6.mjs +2 -0
  69. package/dist/openrouter-images-NEnwWNeg.mjs +2 -0
  70. package/dist/otel-BIqiVgiM.mjs +4 -0
  71. package/dist/otel-BbTSxAZp.mjs +4 -0
  72. package/dist/out/data/halo.lib.pen +4728 -0
  73. package/dist/out/data/lunaris.lib.pen +5980 -0
  74. package/dist/out/data/nitro.lib.pen +4923 -0
  75. package/dist/out/data/shadcn.lib.pen +5596 -0
  76. package/dist/out/mcp-server-darwin-arm64 +0 -0
  77. package/dist/out/mcp-server-darwin-x64 +0 -0
  78. package/dist/out/mcp-server-linux-arm64 +0 -0
  79. package/dist/out/mcp-server-linux-x64 +0 -0
  80. package/dist/out/mcp-server-windows-arm64.exe +0 -0
  81. package/dist/out/mcp-server-windows-x64.exe +0 -0
  82. package/dist/photon_rs-D_fXqzJa.mjs +2 -0
  83. package/dist/provider-env-D0o9FEJi.mjs +2 -0
  84. package/dist/provider-env-DTh1Xe-B.mjs +2 -0
  85. package/dist/sanitize-unicode-B5GgPEiu.mjs +2 -0
  86. package/dist/sanitize-unicode-DVHYNBlY.mjs +2 -0
  87. package/dist/src-Bk9f60_P.mjs +4 -0
  88. package/dist/src-CbkJodKR.mjs +4 -0
  89. package/dist/standalone-BGhJUGyg.mjs +30 -0
  90. package/dist/transform-messages-DSEUXL48.mjs +2 -0
  91. package/dist/transform-messages-j96k5V_T.mjs +2 -0
  92. package/dist/validate-response-CezyBuEO.mjs +3 -0
  93. package/dist/webworkerAll-Dy6-Qx-T.mjs +2 -0
  94. package/package.json +69 -0
@@ -0,0 +1,318 @@
1
+ #!/usr/bin/env node
2
+ import{Ft as e,It as t,Mt as n}from"./index.mjs";import{t as r}from"./sanitize-unicode-B5GgPEiu.mjs";import{t as i}from"./transform-messages-j96k5V_T.mjs";import{createWriteStream as a}from"fs";import*as o from"path";import{Readable as s}from"node:stream";import{finished as c}from"node:stream/promises";import*as l from"fs/promises";import{writeFile as u}from"fs/promises";var d=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}})),f=n((e=>{var t=d();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}}})),p=n(((e,t)=>{t.exports=f()})),m=n(((e,t)=>{let n=p(),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})),h=n(((e,t)=>{var n=Object.prototype.hasOwnProperty,r=Object.prototype.toString,i=Object.defineProperty,a=Object.getOwnPropertyDescriptor,o=function(e){return typeof Array.isArray==`function`?Array.isArray(e):r.call(e)===`[object Array]`},s=function(e){if(!e||r.call(e)!==`[object Object]`)return!1;var t=n.call(e,`constructor`),i=e.constructor&&e.constructor.prototype&&n.call(e.constructor.prototype,`isPrototypeOf`);if(e.constructor&&!t&&!i)return!1;for(var a in e);return a===void 0||n.call(e,a)},c=function(e,t){i&&t.name===`__proto__`?i(e,t.name,{enumerable:!0,configurable:!0,value:t.newValue,writable:!0}):e[t.name]=t.newValue},l=function(e,t){if(t===`__proto__`){if(!n.call(e,t))return;if(a)return a(e,t).value}return e[t]};t.exports=function e(){var t,n,r,i,a,u,d=arguments[0],f=1,p=arguments.length,m=!1;for(typeof d==`boolean`&&(m=d,d=arguments[1]||{},f=2),(d==null||typeof d!=`object`&&typeof d!=`function`)&&(d={});f<p;++f)if(t=arguments[f],t!=null)for(n in t)r=l(d,n),i=l(t,n),d!==i&&(m&&i&&(s(i)||(a=o(i)))?(a?(a=!1,u=r&&o(r)?r:[]):u=r&&s(r)?r:{},c(d,{name:n,newValue:e(m,u,i)})):i!==void 0&&c(d,{name:n,newValue:i}));return d}})),g=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`}})),_=n(((e,t)=>{t.exports={pkg:g()}})),v=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=a;let n=t(h()),r=t(_()).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(`
3
+ `)||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 a(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&&(a({config:e.response.config}),n(e.response.headers),e.response.bodyUsed&&(r(e.response,`data`),i(e.response.data))),e}})),y=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)}})),b=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.GaxiosInterceptorManager=void 0,e.GaxiosInterceptorManager=class extends Set{}})),x=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 a=r(h()),o=e(`https`),s=v(),c=y(),l=e(`stream`),u=b(),d=async()=>globalThis.crypto?.randomUUID()||(await import(`crypto`)).randomUUID();var f=class{agentCache=new Map;defaults;interceptors;constructor(e){this.defaults=e||{},this.interceptors={request:new u.GaxiosInterceptorManager,response:new u.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=s.GaxiosError.extractAPIErrorFromResponse(t,`Request failed with status code ${t.status}`);throw new s.GaxiosError(n?.message,e,t,n)}return t}catch(t){let n;n=t instanceof s.GaxiosError?t:t instanceof Error?new s.GaxiosError(t.message,e,void 0,t):new s.GaxiosError(`Unexpected Gaxios Error`,e,void 0,t);let{shouldRetry:r,config:i}=await(0,c.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 s.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,a.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 l.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 d();t.set(`content-type`,`multipart/related; boundary=${e}`),n.body=l.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 c=n.proxy||process?.env?.HTTPS_PROXY||process?.env?.https_proxy||process?.env?.HTTP_PROXY||process?.env?.http_proxy;if(!n.agent)if(c&&this.#e(n.url,n.noProxy)){let e=await i.#s();this.agentCache.has(c)?n.agent=this.agentCache.get(c):(n.agent=new e(c,{cert:n.cert,key:n.key}),this.agentCache.set(c,n.agent))}else n.cert&&n.key&&(this.agentCache.has(n.key)?n.agent=this.agentCache.get(n.key):(n.agent=new o.Agent({cert:n.cert,key:n.key}),this.agentCache.set(n.key,n.agent)));return typeof n.errorRedactor!=`function`&&n.errorRedactor!==!1&&(n.errorRedactor=s.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
4
+ `;yield n}static#a;static#o;static async#s(){return this.#a||=(await import(`./dist-BupqiQep.mjs`).then(e=>t(e.default))).HttpsProxyAgent,this.#a}static async#c(){let e=typeof window<`u`&&!!window;return this.#o||=e?window.fetch:(await import(`./src-Bk9f60_P.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=f,i=f})),S=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=x();Object.defineProperty(e,`Gaxios`,{enumerable:!0,get:function(){return r.Gaxios}});var i=v();Object.defineProperty(e,`GaxiosError`,{enumerable:!0,get:function(){return i.GaxiosError}}),n(b(),e),e.instance=new r.Gaxios;async function a(t){return e.instance.request(t)}})),C=n(((e,t)=>{(function(e){var n,r=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,i=Math.ceil,a=Math.floor,o=`[BigNumber Error] `,s=o+`Number primitive has more than 15 significant digits: `,c=0x5af3107a4000,l=14,u=9007199254740991,d=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,0xe8d4a51000,0x9184e72a000],f=1e7,p=1e9;function m(e){var t,n,S,C=F.prototype={constructor:F,toString:null,valueOf:null},w=new F(1),T=20,E=4,D=-7,O=21,k=-1e7,A=1e7,j=!1,M=1,N=0,ee={prefix:``,groupSize:3,secondaryGroupSize:0,groupSeparator:`,`,decimalSeparator:`.`,fractionGroupSize:0,fractionGroupSeparator:`\xA0`,suffix:``},P=`0123456789abcdefghijklmnopqrstuvwxyz`,te=!0;function F(e,t){var i,o,c,d,f,p,m,h,g=this;if(!(g instanceof F))return new F(e,t);if(t==null){if(e&&e._isBigNumber===!0){g.s=e.s,!e.c||e.e>A?g.c=g.e=null:e.e<k?g.c=[g.e=0]:(g.e=e.e,g.c=e.c.slice());return}if((p=typeof e==`number`)&&e*0==0){if(g.s=1/e<0?(e=-e,-1):1,e===~~e){for(d=0,f=e;f>=10;f/=10,d++);d>A?g.c=g.e=null:(g.e=d,g.c=[e]);return}h=String(e)}else{if(!r.test(h=String(e)))return S(g,h,p);g.s=h.charCodeAt(0)==45?(h=h.slice(1),-1):1}(d=h.indexOf(`.`))>-1&&(h=h.replace(`.`,``)),(f=h.search(/e/i))>0?(d<0&&(d=f),d+=+h.slice(f+1),h=h.substring(0,f)):d<0&&(d=h.length)}else{if(v(t,2,P.length,`Base`),t==10&&te)return g=new F(e),L(g,T+g.e+1,E);if(h=String(e),p=typeof e==`number`){if(e*0!=0)return S(g,h,p,t);if(g.s=1/e<0?(h=h.slice(1),-1):1,F.DEBUG&&h.replace(/^0\.0*|\./,``).length>15)throw Error(s+e)}else g.s=h.charCodeAt(0)===45?(h=h.slice(1),-1):1;for(i=P.slice(0,t),d=f=0,m=h.length;f<m;f++)if(i.indexOf(o=h.charAt(f))<0){if(o==`.`){if(f>d){d=m;continue}}else if(!c&&(h==h.toUpperCase()&&(h=h.toLowerCase())||h==h.toLowerCase()&&(h=h.toUpperCase()))){c=!0,f=-1,d=0;continue}return S(g,String(e),p,t)}p=!1,h=n(h,t,10,g.s),(d=h.indexOf(`.`))>-1?h=h.replace(`.`,``):d=h.length}for(f=0;h.charCodeAt(f)===48;f++);for(m=h.length;h.charCodeAt(--m)===48;);if(h=h.slice(f,++m)){if(m-=f,p&&F.DEBUG&&m>15&&(e>u||e!==a(e)))throw Error(s+g.s*e);if((d=d-f-1)>A)g.c=g.e=null;else if(d<k)g.c=[g.e=0];else{if(g.e=d,g.c=[],f=(d+1)%l,d<0&&(f+=l),f<m){for(f&&g.c.push(+h.slice(0,f)),m-=l;f<m;)g.c.push(+h.slice(f,f+=l));f=l-(h=h.slice(f)).length}else f-=m;for(;f--;h+=`0`);g.c.push(+h)}}else g.c=[g.e=0]}F.clone=m,F.ROUND_UP=0,F.ROUND_DOWN=1,F.ROUND_CEIL=2,F.ROUND_FLOOR=3,F.ROUND_HALF_UP=4,F.ROUND_HALF_DOWN=5,F.ROUND_HALF_EVEN=6,F.ROUND_HALF_CEIL=7,F.ROUND_HALF_FLOOR=8,F.EUCLID=9,F.config=F.set=function(e){var t,n;if(e!=null)if(typeof e==`object`){if(e.hasOwnProperty(t=`DECIMAL_PLACES`)&&(n=e[t],v(n,0,p,t),T=n),e.hasOwnProperty(t=`ROUNDING_MODE`)&&(n=e[t],v(n,0,8,t),E=n),e.hasOwnProperty(t=`EXPONENTIAL_AT`)&&(n=e[t],n&&n.pop?(v(n[0],-p,0,t),v(n[1],0,p,t),D=n[0],O=n[1]):(v(n,-p,p,t),D=-(O=n<0?-n:n))),e.hasOwnProperty(t=`RANGE`))if(n=e[t],n&&n.pop)v(n[0],-p,-1,t),v(n[1],1,p,t),k=n[0],A=n[1];else if(v(n,-p,p,t),n)k=-(A=n<0?-n:n);else throw Error(o+t+` cannot be zero: `+n);if(e.hasOwnProperty(t=`CRYPTO`))if(n=e[t],n===!!n)if(n)if(typeof crypto<`u`&&crypto&&(crypto.getRandomValues||crypto.randomBytes))j=n;else throw j=!n,Error(o+`crypto unavailable`);else j=n;else throw Error(o+t+` not true or false: `+n);if(e.hasOwnProperty(t=`MODULO_MODE`)&&(n=e[t],v(n,0,9,t),M=n),e.hasOwnProperty(t=`POW_PRECISION`)&&(n=e[t],v(n,0,p,t),N=n),e.hasOwnProperty(t=`FORMAT`))if(n=e[t],typeof n==`object`)ee=n;else throw Error(o+t+` not an object: `+n);if(e.hasOwnProperty(t=`ALPHABET`))if(n=e[t],typeof n==`string`&&!/^.?$|[+\-.\s]|(.).*\1/.test(n))te=n.slice(0,10)==`0123456789`,P=n;else throw Error(o+t+` invalid: `+n)}else throw Error(o+`Object expected: `+e);return{DECIMAL_PLACES:T,ROUNDING_MODE:E,EXPONENTIAL_AT:[D,O],RANGE:[k,A],CRYPTO:j,MODULO_MODE:M,POW_PRECISION:N,FORMAT:ee,ALPHABET:P}},F.isBigNumber=function(e){if(!e||e._isBigNumber!==!0)return!1;if(!F.DEBUG)return!0;var t,n,r=e.c,i=e.e,s=e.s;out:if({}.toString.call(r)==`[object Array]`){if((s===1||s===-1)&&i>=-p&&i<=p&&i===a(i)){if(r[0]===0){if(i===0&&r.length===1)return!0;break out}if(t=(i+1)%l,t<1&&(t+=l),String(r[0]).length==t){for(t=0;t<r.length;t++)if(n=r[t],n<0||n>=c||n!==a(n))break out;if(n!==0)return!0}}}else if(r===null&&i===null&&(s===null||s===1||s===-1))return!0;throw Error(o+`Invalid BigNumber: `+e)},F.maximum=F.max=function(){return re(arguments,-1)},F.minimum=F.min=function(){return re(arguments,1)},F.random=(function(){var e=9007199254740992,t=Math.random()*e&2097151?function(){return a(Math.random()*e)}:function(){return(Math.random()*1073741824|0)*8388608+(Math.random()*8388608|0)};return function(e){var n,r,s,c,u,f=0,m=[],h=new F(w);if(e==null?e=T:v(e,0,p),c=i(e/l),j)if(crypto.getRandomValues){for(n=crypto.getRandomValues(new Uint32Array(c*=2));f<c;)u=n[f]*131072+(n[f+1]>>>11),u>=9e15?(r=crypto.getRandomValues(new Uint32Array(2)),n[f]=r[0],n[f+1]=r[1]):(m.push(u%0x5af3107a4000),f+=2);f=c/2}else if(crypto.randomBytes){for(n=crypto.randomBytes(c*=7);f<c;)u=(n[f]&31)*281474976710656+n[f+1]*1099511627776+n[f+2]*4294967296+n[f+3]*16777216+(n[f+4]<<16)+(n[f+5]<<8)+n[f+6],u>=9e15?crypto.randomBytes(7).copy(n,f):(m.push(u%0x5af3107a4000),f+=7);f=c/7}else throw j=!1,Error(o+`crypto unavailable`);if(!j)for(;f<c;)u=t(),u<9e15&&(m[f++]=u%0x5af3107a4000);for(c=m[--f],e%=l,c&&e&&(u=d[l-e],m[f]=a(c/u)*u);m[f]===0;m.pop(),f--);if(f<0)m=[s=0];else{for(s=-1;m[0]===0;m.splice(0,1),s-=l);for(f=1,u=m[0];u>=10;u/=10,f++);f<l&&(s-=l-f)}return h.e=s,h.c=m,h}})(),F.sum=function(){for(var e=1,t=arguments,n=new F(t[0]);e<t.length;)n=n.plus(t[e++]);return n},n=(function(){var e=`0123456789`;function n(e,t,n,r){for(var i,a=[0],o,s=0,c=e.length;s<c;){for(o=a.length;o--;a[o]*=t);for(a[0]+=r.indexOf(e.charAt(s++)),i=0;i<a.length;i++)a[i]>n-1&&(a[i+1]??(a[i+1]=0),a[i+1]+=a[i]/n|0,a[i]%=n)}return a.reverse()}return function(r,i,a,o,s){var c,l,u,d,f,p,m,h,_=r.indexOf(`.`),v=T,y=E;for(_>=0&&(d=N,N=0,r=r.replace(`.`,``),h=new F(i),p=h.pow(r.length-_),N=d,h.c=n(x(g(p.c),p.e,`0`),10,a,e),h.e=h.c.length),m=n(r,i,a,s?(c=P,e):(c=e,P)),u=d=m.length;m[--d]==0;m.pop());if(!m[0])return c.charAt(0);if(_<0?--u:(p.c=m,p.e=u,p.s=o,p=t(p,h,v,y,a),m=p.c,f=p.r,u=p.e),l=u+v+1,_=m[l],d=a/2,f=f||l<0||m[l+1]!=null,f=y<4?(_!=null||f)&&(y==0||y==(p.s<0?3:2)):_>d||_==d&&(y==4||f||y==6&&m[l-1]&1||y==(p.s<0?8:7)),l<1||!m[0])r=f?x(c.charAt(1),-v,c.charAt(0)):c.charAt(0);else{if(m.length=l,f)for(--a;++m[--l]>a;)m[l]=0,l||(++u,m=[1].concat(m));for(d=m.length;!m[--d];);for(_=0,r=``;_<=d;r+=c.charAt(m[_++]));r=x(r,u,c.charAt(0))}return r}})(),t=(function(){function e(e,t,n){var r,i,a,o,s=0,c=e.length,l=t%f,u=t/f|0;for(e=e.slice();c--;)a=e[c]%f,o=e[c]/f|0,r=u*a+o*l,i=l*a+r%f*f+s,s=(i/n|0)+(r/f|0)+u*o,e[c]=i%n;return s&&(e=[s].concat(e)),e}function t(e,t,n,r){var i,a;if(n!=r)a=n>r?1:-1;else for(i=a=0;i<n;i++)if(e[i]!=t[i]){a=e[i]>t[i]?1:-1;break}return a}function n(e,t,n,r){for(var i=0;n--;)e[n]-=i,i=e[n]<t[n]?1:0,e[n]=i*r+e[n]-t[n];for(;!e[0]&&e.length>1;e.splice(0,1));}return function(r,i,o,s,u){var d,f,p,m,g,_,v,y,b,x,S,C,w,T,E,D,O,k=r.s==i.s?1:-1,A=r.c,j=i.c;if(!A||!A[0]||!j||!j[0])return new F(!r.s||!i.s||(A?j&&A[0]==j[0]:!j)?NaN:A&&A[0]==0||!j?k*0:k/0);for(y=new F(k),b=y.c=[],f=r.e-i.e,k=o+f+1,u||(u=c,f=h(r.e/l)-h(i.e/l),k=k/l|0),p=0;j[p]==(A[p]||0);p++);if(j[p]>(A[p]||0)&&f--,k<0)b.push(1),m=!0;else{for(T=A.length,D=j.length,p=0,k+=2,g=a(u/(j[0]+1)),g>1&&(j=e(j,g,u),A=e(A,g,u),D=j.length,T=A.length),w=D,x=A.slice(0,D),S=x.length;S<D;x[S++]=0);O=j.slice(),O=[0].concat(O),E=j[0],j[1]>=u/2&&E++;do{if(g=0,d=t(j,x,D,S),d<0){if(C=x[0],D!=S&&(C=C*u+(x[1]||0)),g=a(C/E),g>1)for(g>=u&&(g=u-1),_=e(j,g,u),v=_.length,S=x.length;t(_,x,v,S)==1;)g--,n(_,D<v?O:j,v,u),v=_.length,d=1;else g==0&&(d=g=1),_=j.slice(),v=_.length;if(v<S&&(_=[0].concat(_)),n(x,_,S,u),S=x.length,d==-1)for(;t(j,x,D,S)<1;)g++,n(x,D<S?O:j,S,u),S=x.length}else d===0&&(g++,x=[0]);b[p++]=g,x[0]?x[S++]=A[w]||0:(x=[A[w]],S=1)}while((w++<T||x[0]!=null)&&k--);m=x[0]!=null,b[0]||b.splice(0,1)}if(u==c){for(p=1,k=b[0];k>=10;k/=10,p++);L(y,o+(y.e=p+f*l-1)+1,s,m)}else y.e=f,y.r=+m;return y}})();function ne(e,t,n,r){var i,a,o,s,c;if(n==null?n=E:v(n,0,8),!e.c)return e.toString();if(i=e.c[0],o=e.e,t==null)c=g(e.c),c=r==1||r==2&&(o<=D||o>=O)?b(c,o):x(c,o,`0`);else if(e=L(new F(e),t,n),a=e.e,c=g(e.c),s=c.length,r==1||r==2&&(t<=a||a<=D)){for(;s<t;c+=`0`,s++);c=b(c,a)}else if(t-=o+(r===2&&a>o),c=x(c,a,`0`),a+1>s){if(--t>0)for(c+=`.`;t--;c+=`0`);}else if(t+=a-s,t>0)for(a+1==s&&(c+=`.`);t--;c+=`0`);return e.s<0&&i?`-`+c:c}function re(e,t){for(var n,r,i=1,a=new F(e[0]);i<e.length;i++)r=new F(e[i]),(!r.s||(n=_(a,r))===t||n===0&&a.s===t)&&(a=r);return a}function I(e,t,n){for(var r=1,i=t.length;!t[--i];t.pop());for(i=t[0];i>=10;i/=10,r++);return(n=r+n*l-1)>A?e.c=e.e=null:n<k?e.c=[e.e=0]:(e.e=n,e.c=t),e}S=(function(){var e=/^(-?)0([xbo])(?=\w[\w.]*$)/i,t=/^([^.]+)\.$/,n=/^\.([^.]+)$/,r=/^-?(Infinity|NaN)$/,i=/^\s*\+(?=[\w.])|^\s+|\s+$/g;return function(a,s,c,l){var u,d=c?s:s.replace(i,``);if(r.test(d))a.s=isNaN(d)?null:d<0?-1:1;else{if(!c&&(d=d.replace(e,function(e,t,n){return u=(n=n.toLowerCase())==`x`?16:n==`b`?2:8,!l||l==u?t:e}),l&&(u=l,d=d.replace(t,`$1`).replace(n,`0.$1`)),s!=d))return new F(d,u);if(F.DEBUG)throw Error(o+`Not a`+(l?` base `+l:``)+` number: `+s);a.s=null}a.c=a.e=null}})();function L(e,t,n,r){var o,s,u,f,p,m,h,g=e.c,_=d;if(g){out:{for(o=1,f=g[0];f>=10;f/=10,o++);if(s=t-o,s<0)s+=l,u=t,p=g[m=0],h=a(p/_[o-u-1]%10);else if(m=i((s+1)/l),m>=g.length)if(r){for(;g.length<=m;g.push(0));p=h=0,o=1,s%=l,u=s-l+1}else break out;else{for(p=f=g[m],o=1;f>=10;f/=10,o++);s%=l,u=s-l+o,h=u<0?0:a(p/_[o-u-1]%10)}if(r=r||t<0||g[m+1]!=null||(u<0?p:p%_[o-u-1]),r=n<4?(h||r)&&(n==0||n==(e.s<0?3:2)):h>5||h==5&&(n==4||r||n==6&&(s>0?u>0?p/_[o-u]:0:g[m-1])%10&1||n==(e.s<0?8:7)),t<1||!g[0])return g.length=0,r?(t-=e.e+1,g[0]=_[(l-t%l)%l],e.e=-t||0):g[0]=e.e=0,e;if(s==0?(g.length=m,f=1,m--):(g.length=m+1,f=_[l-s],g[m]=u>0?a(p/_[o-u]%_[u])*f:0),r)for(;;)if(m==0){for(s=1,u=g[0];u>=10;u/=10,s++);for(u=g[0]+=f,f=1;u>=10;u/=10,f++);s!=f&&(e.e++,g[0]==c&&(g[0]=1));break}else{if(g[m]+=f,g[m]!=c)break;g[m--]=0,f=1}for(s=g.length;g[--s]===0;g.pop());}e.e>A?e.c=e.e=null:e.e<k&&(e.c=[e.e=0])}return e}function R(e){var t,n=e.e;return n===null?e.toString():(t=g(e.c),t=n<=D||n>=O?b(t,n):x(t,n,`0`),e.s<0?`-`+t:t)}return C.absoluteValue=C.abs=function(){var e=new F(this);return e.s<0&&(e.s=1),e},C.comparedTo=function(e,t){return _(this,new F(e,t))},C.decimalPlaces=C.dp=function(e,t){var n,r,i,a=this;if(e!=null)return v(e,0,p),t==null?t=E:v(t,0,8),L(new F(a),e+a.e+1,t);if(!(n=a.c))return null;if(r=((i=n.length-1)-h(this.e/l))*l,i=n[i])for(;i%10==0;i/=10,r--);return r<0&&(r=0),r},C.dividedBy=C.div=function(e,n){return t(this,new F(e,n),T,E)},C.dividedToIntegerBy=C.idiv=function(e,n){return t(this,new F(e,n),0,1)},C.exponentiatedBy=C.pow=function(e,t){var n,r,s,c,u,d,f,p,m,h=this;if(e=new F(e),e.c&&!e.isInteger())throw Error(o+`Exponent not an integer: `+R(e));if(t!=null&&(t=new F(t)),d=e.e>14,!h.c||!h.c[0]||h.c[0]==1&&!h.e&&h.c.length==1||!e.c||!e.c[0])return m=new F(R(h)**(d?e.s*(2-y(e)):+R(e))),t?m.mod(t):m;if(f=e.s<0,t){if(t.c?!t.c[0]:!t.s)return new F(NaN);r=!f&&h.isInteger()&&t.isInteger(),r&&(h=h.mod(t))}else if(e.e>9&&(h.e>0||h.e<-1||(h.e==0?h.c[0]>1||d&&h.c[1]>=24e7:h.c[0]<8e13||d&&h.c[0]<=9999975e7)))return c=h.s<0&&y(e)?-0:0,h.e>-1&&(c=1/c),new F(f?1/c:c);else N&&(c=i(N/l+2));for(d?(n=new F(.5),f&&(e.s=1),p=y(e)):(s=Math.abs(+R(e)),p=s%2),m=new F(w);;){if(p){if(m=m.times(h),!m.c)break;c?m.c.length>c&&(m.c.length=c):r&&(m=m.mod(t))}if(s){if(s=a(s/2),s===0)break;p=s%2}else if(e=e.times(n),L(e,e.e+1,1),e.e>14)p=y(e);else{if(s=+R(e),s===0)break;p=s%2}h=h.times(h),c?h.c&&h.c.length>c&&(h.c.length=c):r&&(h=h.mod(t))}return r?m:(f&&(m=w.div(m)),t?m.mod(t):c?L(m,N,E,u):m)},C.integerValue=function(e){var t=new F(this);return e==null?e=E:v(e,0,8),L(t,t.e+1,e)},C.isEqualTo=C.eq=function(e,t){return _(this,new F(e,t))===0},C.isFinite=function(){return!!this.c},C.isGreaterThan=C.gt=function(e,t){return _(this,new F(e,t))>0},C.isGreaterThanOrEqualTo=C.gte=function(e,t){return(t=_(this,new F(e,t)))===1||t===0},C.isInteger=function(){return!!this.c&&h(this.e/l)>this.c.length-2},C.isLessThan=C.lt=function(e,t){return _(this,new F(e,t))<0},C.isLessThanOrEqualTo=C.lte=function(e,t){return(t=_(this,new F(e,t)))===-1||t===0},C.isNaN=function(){return!this.s},C.isNegative=function(){return this.s<0},C.isPositive=function(){return this.s>0},C.isZero=function(){return!!this.c&&this.c[0]==0},C.minus=function(e,t){var n,r,i,a,o=this,s=o.s;if(e=new F(e,t),t=e.s,!s||!t)return new F(NaN);if(s!=t)return e.s=-t,o.plus(e);var u=o.e/l,d=e.e/l,f=o.c,p=e.c;if(!u||!d){if(!f||!p)return f?(e.s=-t,e):new F(p?o:NaN);if(!f[0]||!p[0])return p[0]?(e.s=-t,e):new F(f[0]?o:E==3?-0:0)}if(u=h(u),d=h(d),f=f.slice(),s=u-d){for((a=s<0)?(s=-s,i=f):(d=u,i=p),i.reverse(),t=s;t--;i.push(0));i.reverse()}else for(r=(a=(s=f.length)<(t=p.length))?s:t,s=t=0;t<r;t++)if(f[t]!=p[t]){a=f[t]<p[t];break}if(a&&(i=f,f=p,p=i,e.s=-e.s),t=(r=p.length)-(n=f.length),t>0)for(;t--;f[n++]=0);for(t=c-1;r>s;){if(f[--r]<p[r]){for(n=r;n&&!f[--n];f[n]=t);--f[n],f[r]+=c}f[r]-=p[r]}for(;f[0]==0;f.splice(0,1),--d);return f[0]?I(e,f,d):(e.s=E==3?-1:1,e.c=[e.e=0],e)},C.modulo=C.mod=function(e,n){var r,i,a=this;return e=new F(e,n),!a.c||!e.s||e.c&&!e.c[0]?new F(NaN):!e.c||a.c&&!a.c[0]?new F(a):(M==9?(i=e.s,e.s=1,r=t(a,e,0,3),e.s=i,r.s*=i):r=t(a,e,0,M),e=a.minus(r.times(e)),!e.c[0]&&M==1&&(e.s=a.s),e)},C.multipliedBy=C.times=function(e,t){var n,r,i,a,o,s,u,d,p,m,g,_,v,y,b,x=this,S=x.c,C=(e=new F(e,t)).c;if(!S||!C||!S[0]||!C[0])return!x.s||!e.s||S&&!S[0]&&!C||C&&!C[0]&&!S?e.c=e.e=e.s=null:(e.s*=x.s,!S||!C?e.c=e.e=null:(e.c=[0],e.e=0)),e;for(r=h(x.e/l)+h(e.e/l),e.s*=x.s,u=S.length,m=C.length,u<m&&(v=S,S=C,C=v,i=u,u=m,m=i),i=u+m,v=[];i--;v.push(0));for(y=c,b=f,i=m;--i>=0;){for(n=0,g=C[i]%b,_=C[i]/b|0,o=u,a=i+o;a>i;)d=S[--o]%b,p=S[o]/b|0,s=_*d+p*g,d=g*d+s%b*b+v[a]+n,n=(d/y|0)+(s/b|0)+_*p,v[a--]=d%y;v[a]=n}return n?++r:v.splice(0,1),I(e,v,r)},C.negated=function(){var e=new F(this);return e.s=-e.s||null,e},C.plus=function(e,t){var n,r=this,i=r.s;if(e=new F(e,t),t=e.s,!i||!t)return new F(NaN);if(i!=t)return e.s=-t,r.minus(e);var a=r.e/l,o=e.e/l,s=r.c,u=e.c;if(!a||!o){if(!s||!u)return new F(i/0);if(!s[0]||!u[0])return u[0]?e:new F(s[0]?r:i*0)}if(a=h(a),o=h(o),s=s.slice(),i=a-o){for(i>0?(o=a,n=u):(i=-i,n=s),n.reverse();i--;n.push(0));n.reverse()}for(i=s.length,t=u.length,i-t<0&&(n=u,u=s,s=n,t=i),i=0;t;)i=(s[--t]=s[t]+u[t]+i)/c|0,s[t]=c===s[t]?0:s[t]%c;return i&&(s=[i].concat(s),++o),I(e,s,o)},C.precision=C.sd=function(e,t){var n,r,i,a=this;if(e!=null&&e!==!!e)return v(e,1,p),t==null?t=E:v(t,0,8),L(new F(a),e,t);if(!(n=a.c))return null;if(i=n.length-1,r=i*l+1,i=n[i]){for(;i%10==0;i/=10,r--);for(i=n[0];i>=10;i/=10,r++);}return e&&a.e+1>r&&(r=a.e+1),r},C.shiftedBy=function(e){return v(e,-u,u),this.times(`1e`+e)},C.squareRoot=C.sqrt=function(){var e,n,r,i,a,o=this,s=o.c,c=o.s,l=o.e,u=T+4,d=new F(`0.5`);if(c!==1||!s||!s[0])return new F(!c||c<0&&(!s||s[0])?NaN:s?o:1/0);if(c=Math.sqrt(+R(o)),c==0||c==1/0?(n=g(s),(n.length+l)%2==0&&(n+=`0`),c=Math.sqrt(+n),l=h((l+1)/2)-(l<0||l%2),c==1/0?n=`5e`+l:(n=c.toExponential(),n=n.slice(0,n.indexOf(`e`)+1)+l),r=new F(n)):r=new F(c+``),r.c[0]){for(l=r.e,c=l+u,c<3&&(c=0);;)if(a=r,r=d.times(a.plus(t(o,a,u,1))),g(a.c).slice(0,c)===(n=g(r.c)).slice(0,c))if(r.e<l&&--c,n=n.slice(c-3,c+1),n==`9999`||!i&&n==`4999`){if(!i&&(L(a,a.e+T+2,0),a.times(a).eq(o))){r=a;break}u+=4,c+=4,i=1}else{(!+n||!+n.slice(1)&&n.charAt(0)==`5`)&&(L(r,r.e+T+2,1),e=!r.times(r).eq(o));break}}return L(r,r.e+T+1,E,e)},C.toExponential=function(e,t){return e!=null&&(v(e,0,p),e++),ne(this,e,t,1)},C.toFixed=function(e,t){return e!=null&&(v(e,0,p),e=e+this.e+1),ne(this,e,t)},C.toFormat=function(e,t,n){var r,i=this;if(n==null)e!=null&&t&&typeof t==`object`?(n=t,t=null):e&&typeof e==`object`?(n=e,e=t=null):n=ee;else if(typeof n!=`object`)throw Error(o+`Argument not an object: `+n);if(r=i.toFixed(e,t),i.c){var a,s=r.split(`.`),c=+n.groupSize,l=+n.secondaryGroupSize,u=n.groupSeparator||``,d=s[0],f=s[1],p=i.s<0,m=p?d.slice(1):d,h=m.length;if(l&&(a=c,c=l,l=a,h-=a),c>0&&h>0){for(a=h%c||c,d=m.substr(0,a);a<h;a+=c)d+=u+m.substr(a,c);l>0&&(d+=u+m.slice(a)),p&&(d=`-`+d)}r=f?d+(n.decimalSeparator||``)+((l=+n.fractionGroupSize)?f.replace(RegExp(`\\d{`+l+`}\\B`,`g`),`$&`+(n.fractionGroupSeparator||``)):f):d}return(n.prefix||``)+r+(n.suffix||``)},C.toFraction=function(e){var n,r,i,a,s,c,u,f,p,m,h,_,v=this,y=v.c;if(e!=null&&(u=new F(e),!u.isInteger()&&(u.c||u.s!==1)||u.lt(w)))throw Error(o+`Argument `+(u.isInteger()?`out of range: `:`not an integer: `)+R(u));if(!y)return new F(v);for(n=new F(w),p=r=new F(w),i=f=new F(w),_=g(y),s=n.e=_.length-v.e-1,n.c[0]=d[(c=s%l)<0?l+c:c],e=!e||u.comparedTo(n)>0?s>0?n:p:u,c=A,A=1/0,u=new F(_),f.c[0]=0;m=t(u,n,0,1),a=r.plus(m.times(i)),a.comparedTo(e)!=1;)r=i,i=a,p=f.plus(m.times(a=p)),f=a,n=u.minus(m.times(a=n)),u=a;return a=t(e.minus(r),i,0,1),f=f.plus(a.times(p)),r=r.plus(a.times(i)),f.s=p.s=v.s,s*=2,h=t(p,i,s,E).minus(v).abs().comparedTo(t(f,r,s,E).minus(v).abs())<1?[p,i]:[f,r],A=c,h},C.toNumber=function(){return+R(this)},C.toPrecision=function(e,t){return e!=null&&v(e,1,p),ne(this,e,t,2)},C.toString=function(e){var t,r=this,i=r.s,a=r.e;return a===null?i?(t=`Infinity`,i<0&&(t=`-`+t)):t=`NaN`:(e==null?t=a<=D||a>=O?b(g(r.c),a):x(g(r.c),a,`0`):e===10&&te?(r=L(new F(r),T+a+1,E),t=x(g(r.c),r.e,`0`)):(v(e,2,P.length,`Base`),t=n(x(g(r.c),a,`0`),10,e,i,!0)),i<0&&r.c[0]&&(t=`-`+t)),t},C.valueOf=C.toJSON=function(){return R(this)},C._isBigNumber=!0,e!=null&&F.set(e),F}function h(e){var t=e|0;return e>0||e===t?t:t-1}function g(e){for(var t,n,r=1,i=e.length,a=e[0]+``;r<i;){for(t=e[r++]+``,n=l-t.length;n--;t=`0`+t);a+=t}for(i=a.length;a.charCodeAt(--i)===48;);return a.slice(0,i+1||1)}function _(e,t){var n,r,i=e.c,a=t.c,o=e.s,s=t.s,c=e.e,l=t.e;if(!o||!s)return null;if(n=i&&!i[0],r=a&&!a[0],n||r)return n?r?0:-s:o;if(o!=s)return o;if(n=o<0,r=c==l,!i||!a)return r?0:!i^n?1:-1;if(!r)return c>l^n?1:-1;for(s=(c=i.length)<(l=a.length)?c:l,o=0;o<s;o++)if(i[o]!=a[o])return i[o]>a[o]^n?1:-1;return c==l?0:c>l^n?1:-1}function v(e,t,n,r){if(e<t||e>n||e!==a(e))throw Error(o+(r||`Argument`)+(typeof e==`number`?e<t||e>n?` out of range: `:` not an integer: `:` not a primitive number: `)+String(e))}function y(e){var t=e.c.length-1;return h(e.e/l)==t&&e.c[t]%2!=0}function b(e,t){return(e.length>1?e.charAt(0)+`.`+e.slice(1):e)+(t<0?`e`:`e+`)+t}function x(e,t,n){var r,i;if(t<0){for(i=n+`.`;++t;i+=n);e=i+e}else if(r=e.length,++t>r){for(i=n,t-=r;--t;i+=n);e+=i}else t<r&&(e=e.slice(0,t)+`.`+e.slice(t));return e}n=m(),n.default=n.BigNumber=n,typeof define==`function`&&define.amd?define(function(){return n}):t!==void 0&&t.exports?t.exports=n:(e||=typeof self<`u`&&self?self:window,e.BigNumber=n)})(e)})),w=n(((e,t)=>{var n=C(),r=t.exports;(function(){var e=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,t,i,a={"\b":`\\b`," ":`\\t`,"\n":`\\n`,"\f":`\\f`,"\r":`\\r`,'"':`\\"`,"\\":`\\\\`},o;function s(t){return e.lastIndex=0,e.test(t)?`"`+t.replace(e,function(e){var t=a[e];return typeof t==`string`?t:`\\u`+(`0000`+e.charCodeAt(0).toString(16)).slice(-4)})+`"`:`"`+t+`"`}function c(e,r){var a,l,u,d,f=t,p,m=r[e],h=m!=null&&(m instanceof n||n.isBigNumber(m));switch(m&&typeof m==`object`&&typeof m.toJSON==`function`&&(m=m.toJSON(e)),typeof o==`function`&&(m=o.call(r,e,m)),typeof m){case`string`:return h?m:s(m);case`number`:return isFinite(m)?String(m):`null`;case`boolean`:case`null`:case`bigint`:return String(m);case`object`:if(!m)return`null`;if(t+=i,p=[],Object.prototype.toString.apply(m)===`[object Array]`){for(d=m.length,a=0;a<d;a+=1)p[a]=c(a,m)||`null`;return u=p.length===0?`[]`:t?`[
5
+ `+t+p.join(`,
6
+ `+t)+`
7
+ `+f+`]`:`[`+p.join(`,`)+`]`,t=f,u}if(o&&typeof o==`object`)for(d=o.length,a=0;a<d;a+=1)typeof o[a]==`string`&&(l=o[a],u=c(l,m),u&&p.push(s(l)+(t?`: `:`:`)+u));else Object.keys(m).forEach(function(e){var n=c(e,m);n&&p.push(s(e)+(t?`: `:`:`)+n)});return u=p.length===0?`{}`:t?`{
8
+ `+t+p.join(`,
9
+ `+t)+`
10
+ `+f+`}`:`{`+p.join(`,`)+`}`,t=f,u}}typeof r.stringify!=`function`&&(r.stringify=function(e,n,r){var a;if(t=``,i=``,typeof r==`number`)for(a=0;a<r;a+=1)i+=` `;else typeof r==`string`&&(i=r);if(o=n,n&&typeof n!=`function`&&(typeof n!=`object`||typeof n.length!=`number`))throw Error(`JSON.stringify`);return c(``,{"":e})})})()})),T=n(((e,t)=>{var n=null;let r=/(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])/,i=/(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)/;t.exports=function(e){var t={strict:!1,storeAsString:!1,alwaysParseAsBig:!1,useNativeBigInt:!1,protoAction:`error`,constructorAction:`error`};if(e!=null){if(e.strict===!0&&(t.strict=!0),e.storeAsString===!0&&(t.storeAsString=!0),t.alwaysParseAsBig=e.alwaysParseAsBig===!0?e.alwaysParseAsBig:!1,t.useNativeBigInt=e.useNativeBigInt===!0?e.useNativeBigInt:!1,e.constructorAction!==void 0)if(e.constructorAction===`error`||e.constructorAction===`ignore`||e.constructorAction===`preserve`)t.constructorAction=e.constructorAction;else throw Error(`Incorrect value for constructorAction option, must be "error", "ignore" or undefined but passed ${e.constructorAction}`);if(e.protoAction!==void 0)if(e.protoAction===`error`||e.protoAction===`ignore`||e.protoAction===`preserve`)t.protoAction=e.protoAction;else throw Error(`Incorrect value for protoAction option, must be "error", "ignore" or undefined but passed ${e.protoAction}`)}var a,o,s={'"':`"`,"\\":`\\`,"/":`/`,b:`\b`,f:`\f`,n:`
11
+ `,r:`\r`,t:` `},c,l=function(e){throw{name:`SyntaxError`,message:e,at:a,text:c}},u=function(e){return e&&e!==o&&l(`Expected '`+e+`' instead of '`+o+`'`),o=c.charAt(a),a+=1,o},d=function(){var e,r=``;for(o===`-`&&(r=`-`,u(`-`));o>=`0`&&o<=`9`;)r+=o,u();if(o===`.`)for(r+=`.`;u()&&o>=`0`&&o<=`9`;)r+=o;if(o===`e`||o===`E`)for(r+=o,u(),(o===`-`||o===`+`)&&(r+=o,u());o>=`0`&&o<=`9`;)r+=o,u();if(e=+r,!isFinite(e))l(`Bad number`);else return n??=C(),r.length>15?t.storeAsString?r:t.useNativeBigInt?BigInt(r):new n(r):t.alwaysParseAsBig?t.useNativeBigInt?BigInt(e):new n(e):e},f=function(){var e,t,n=``,r;if(o===`"`)for(var i=a;u();){if(o===`"`)return a-1>i&&(n+=c.substring(i,a-1)),u(),n;if(o===`\\`){if(a-1>i&&(n+=c.substring(i,a-1)),u(),o===`u`){for(r=0,t=0;t<4&&(e=parseInt(u(),16),isFinite(e));t+=1)r=r*16+e;n+=String.fromCharCode(r)}else if(typeof s[o]==`string`)n+=s[o];else break;i=a}}l(`Bad string`)},p=function(){for(;o&&o<=` `;)u()},m=function(){switch(o){case`t`:return u(`t`),u(`r`),u(`u`),u(`e`),!0;case`f`:return u(`f`),u(`a`),u(`l`),u(`s`),u(`e`),!1;case`n`:return u(`n`),u(`u`),u(`l`),u(`l`),null}l(`Unexpected '`+o+`'`)},h,g=function(){var e=[];if(o===`[`){if(u(`[`),p(),o===`]`)return u(`]`),e;for(;o;){if(e.push(h()),p(),o===`]`)return u(`]`),e;u(`,`),p()}}l(`Bad array`)},_=function(){var e,n=Object.create(null);if(o===`{`){if(u(`{`),p(),o===`}`)return u(`}`),n;for(;o;){if(e=f(),p(),u(`:`),t.strict===!0&&Object.hasOwnProperty.call(n,e)&&l(`Duplicate key "`+e+`"`),r.test(e)===!0?t.protoAction===`error`?l(`Object contains forbidden prototype property`):t.protoAction===`ignore`?h():n[e]=h():i.test(e)===!0?t.constructorAction===`error`?l(`Object contains forbidden constructor property`):t.constructorAction===`ignore`?h():n[e]=h():n[e]=h(),p(),o===`}`)return u(`}`),n;u(`,`),p()}}l(`Bad object`)};return h=function(){switch(p(),o){case`{`:return _();case`[`:return g();case`"`:return f();case`-`:return d();default:return o>=`0`&&o<=`9`?d():m()}},function(e,t){var n;return c=e+``,a=0,o=` `,n=h(),p(),o&&l(`Syntax error`),typeof t==`function`?(function e(n,r){var i,a=n[r];return a&&typeof a==`object`&&Object.keys(a).forEach(function(t){i=e(a,t),i===void 0?delete a[t]:a[t]=i}),t.call(n,r,a)})({"":n},``):n}}})),E=n(((e,t)=>{var n=w().stringify,r=T();t.exports=function(e){return{parse:r(e),stringify:n}},t.exports.parse=r(),t.exports.stringify=n})),D=n((t=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.GCE_LINUX_BIOS_PATHS=void 0,t.isGoogleCloudServerless=a,t.isGoogleComputeEngineLinux=o,t.isGoogleComputeEngineMACAddress=s,t.isGoogleComputeEngine=c,t.detectGCPResidency=l;let n=e(`fs`),r=e(`os`);t.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)(t.GCE_LINUX_BIOS_PATHS.BIOS_DATE);let e=(0,n.readFileSync)(t.GCE_LINUX_BIOS_PATHS.BIOS_VENDOR,`utf8`);return/Google/.test(e)}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()}})),O=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()})),k=n((t=>{var n=t&&t.__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=t&&t.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,`default`,{enumerable:!0,value:t})}):function(e,t){e.default=t}),i=t&&t.__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(t,`__esModule`,{value:!0}),t.env=t.DebugLogBackendBase=t.placeholder=t.AdhocDebugLogger=t.LogSeverity=void 0,t.getNodeBackend=p,t.getDebugBackend=h,t.getStructuredBackend=_,t.setBackend=b,t.log=x;let a=e(`events`),o=i(e(`process`)),s=i(e(`util`)),c=O();var l;(function(e){e.DEFAULT=`DEFAULT`,e.DEBUG=`DEBUG`,e.INFO=`INFO`,e.WARNING=`WARNING`,e.ERROR=`ERROR`})(l||(t.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)}};t.AdhocDebugLogger=u,t.placeholder=new u(``,()=>{}).func;var d=class{constructor(){this.cached=new Map,this.filters=[],this.filtersSet=!1;let e=o.env[t.env.nodeEnables]??`*`;e===`all`&&(e=`*`),this.filters=e.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)}}};t.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)}t.env={nodeEnables:`GOOGLE_SDK_NODE_LOGGING`};let v=new Map,y;function b(e){y=e,v.clear()}function x(e,n){if(!y&&!o.env[t.env.nodeEnables]||!e)return t.placeholder;n&&(e=`${n.instance.namespace}:${e}`);let r=v.get(e);if(r)return r.func;if(y===null)return t.placeholder;y===void 0&&(y=p());let i=(()=>{let t;return new u(e,(n,...r)=>{if(t!==y){if(y===null)return;y===void 0&&(y=p()),t=y}y?.log(e,n,...r)})})();return v.set(e,i),i.func}})),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.__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(k(),e)})),j=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=m,e.project=h,e.universe=g,e.bulk=_,e.isAvailable=b,e.resetIsAvailableCache=x,e.getGCPResidency=C,e.setGCPResidency=w,e.requestTimeout=T;let a=S(),o=E(),s=D(),c=r(A());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 l=c.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 u(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 d(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 f(t,n={},r=3,i=!1){let s=new Headers(e.HEADERS),c=``,f={};if(typeof t==`object`){let e=t;new Headers(e.headers).forEach((e,t)=>s.set(t,e)),c=e.metadataKey,f=e.params||f,r=e.noResponseRetries||r,i=e.fastFail||i}else c=t;typeof n==`string`?c+=`/${n}`:(d(n),n.property&&(c+=`/${n.property}`),new Headers(n.headers).forEach((e,t)=>s.set(t,e)),f=n.params||f);let m=i?p:a.request,h={url:`${u()}/${c}`,headers:s,retryConfig:{noResponseRetries:r},params:f,responseType:`text`,timeout:T()};l.info(`instance request %j`,h);let g=await m(h);l.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 o.parse(g.data)}catch{}return g.data}async function p(t){let n={...t,url:t.url?.toString().replace(u(),u(e.SECONDARY_HOST_ADDRESS))},r=(0,a.request)(t),i=(0,a.request)(n);return Promise.any([r,i])}function m(e){return f(`instance`,e)}function h(e){return f(`project`,e)}function g(e){return f(`universe`,e)}async function _(e){let t={};return await Promise.all(e.map(e=>(async()=>{let n=await f(e),r=e.metadataKey;t[r]=n})())),t}function v(){return process.env.DETECT_GCP_RETRIES?Number(process.env.DETECT_GCP_RETRIES):0}let y;async function b(){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 y===void 0&&(y=f(`instance`,void 0,v(),!(process.env.GCE_METADATA_IP||process.env.GCE_METADATA_HOST))),await y,!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 x(){y=void 0}e.gcpResidencyCache=null;function C(){return e.gcpResidencyCache===null&&w(),e.gcpResidencyCache}function w(t=null){e.gcpResidencyCache=t===null?(0,s.detectGCPResidency)():t}function T(){return C()?0:3e3}i(D(),e)})),M=n((e=>{e.byteLength=c,e.toByteArray=u,e.fromByteArray=p;for(var t=[],n=[],r=typeof Uint8Array<`u`?Uint8Array:Array,i=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`,a=0,o=i.length;a<o;++a)t[a]=i[a],n[i.charCodeAt(a)]=a;n[45]=62,n[95]=63;function s(e){var t=e.length;if(t%4>0)throw Error(`Invalid string. Length must be a multiple of 4`);var n=e.indexOf(`=`);n===-1&&(n=t);var r=n===t?0:4-n%4;return[n,r]}function c(e){var t=s(e),n=t[0],r=t[1];return(n+r)*3/4-r}function l(e,t,n){return(t+n)*3/4-n}function u(e){var t,i=s(e),a=i[0],o=i[1],c=new r(l(e,a,o)),u=0,d=o>0?a-4:a,f;for(f=0;f<d;f+=4)t=n[e.charCodeAt(f)]<<18|n[e.charCodeAt(f+1)]<<12|n[e.charCodeAt(f+2)]<<6|n[e.charCodeAt(f+3)],c[u++]=t>>16&255,c[u++]=t>>8&255,c[u++]=t&255;return o===2&&(t=n[e.charCodeAt(f)]<<2|n[e.charCodeAt(f+1)]>>4,c[u++]=t&255),o===1&&(t=n[e.charCodeAt(f)]<<10|n[e.charCodeAt(f+1)]<<4|n[e.charCodeAt(f+2)]>>2,c[u++]=t>>8&255,c[u++]=t&255),c}function d(e){return t[e>>18&63]+t[e>>12&63]+t[e>>6&63]+t[e&63]}function f(e,t,n){for(var r,i=[],a=t;a<n;a+=3)r=(e[a]<<16&16711680)+(e[a+1]<<8&65280)+(e[a+2]&255),i.push(d(r));return i.join(``)}function p(e){for(var n,r=e.length,i=r%3,a=[],o=16383,s=0,c=r-i;s<c;s+=o)a.push(f(e,s,s+o>c?c:s+o));return i===1?(n=e[r-1],a.push(t[n>>2]+t[n<<4&63]+`==`)):i===2&&(n=(e[r-2]<<8)+e[r-1],a.push(t[n>>10]+t[n>>4&63]+t[n<<2&63]+`=`)),a.join(``)}})),N=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(``)}})),ee=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.BrowserCrypto=void 0;let t=M(),n=N();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))}}})),P=n((t=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.NodeCrypto=void 0;let n=e(`crypto`);t.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)}})),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}),e.createCrypto=a,e.hasBrowserCrypto=o;let r=ee(),i=P();n(N(),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}})),F=n(((t,n)=>{
12
+ /*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */
13
+ var r=e(`buffer`),i=r.Buffer;function a(e,t){for(var n in e)t[n]=e[n]}i.from&&i.alloc&&i.allocUnsafe&&i.allocUnsafeSlow?n.exports=r:(a(r,t),t.Buffer=o);function o(e,t,n){return i(e,t,n)}o.prototype=Object.create(i.prototype),a(i,o),o.from=function(e,t,n){if(typeof e==`number`)throw TypeError(`Argument must not be a number`);return i(e,t,n)},o.alloc=function(e,t,n){if(typeof e!=`number`)throw TypeError(`Argument must be a number`);var r=i(e);return t===void 0?r.fill(0):typeof n==`string`?r.fill(t,n):r.fill(t),r},o.allocUnsafe=function(e){if(typeof e!=`number`)throw TypeError(`Argument must be a number`);return i(e)},o.allocUnsafeSlow=function(e){if(typeof e!=`number`)throw TypeError(`Argument must be a number`);return r.SlowBuffer(e)}})),ne=n(((e,t)=>{function n(e){return(e/8|0)+(e%8==0?0:1)}var r={ES256:n(256),ES384:n(384),ES512:n(521)};function i(e){var t=r[e];if(t)return t;throw Error(`Unknown algorithm "`+e+`"`)}t.exports=i})),re=n(((e,t)=>{var n=F().Buffer,r=ne(),i=128,a=0,o=32,s=16,c=2,l=s|o|a<<6,u=c|a<<6;function d(e){return e.replace(/=/g,``).replace(/\+/g,`-`).replace(/\//g,`_`)}function f(e){if(n.isBuffer(e))return e;if(typeof e==`string`)return n.from(e,`base64`);throw TypeError(`ECDSA signature must be a Base64 string or a Buffer`)}function p(e,t){e=f(e);var a=r(t),o=a+1,s=e.length,c=0;if(e[c++]!==l)throw Error(`Could not find expected "seq"`);var p=e[c++];if(p===(i|1)&&(p=e[c++]),s-c<p)throw Error(`"seq" specified length of "`+p+`", only "`+(s-c)+`" remaining`);if(e[c++]!==u)throw Error(`Could not find expected "int" for "r"`);var m=e[c++];if(s-c-2<m)throw Error(`"r" specified length of "`+m+`", only "`+(s-c-2)+`" available`);if(o<m)throw Error(`"r" specified length of "`+m+`", max of "`+o+`" is acceptable`);var h=c;if(c+=m,e[c++]!==u)throw Error(`Could not find expected "int" for "s"`);var g=e[c++];if(s-c!==g)throw Error(`"s" specified length of "`+g+`", expected "`+(s-c)+`"`);if(o<g)throw Error(`"s" specified length of "`+g+`", max of "`+o+`" is acceptable`);var _=c;if(c+=g,c!==s)throw Error(`Expected to consume entire buffer, but "`+(s-c)+`" bytes remain`);var v=a-m,y=a-g,b=n.allocUnsafe(v+m+y+g);for(c=0;c<v;++c)b[c]=0;e.copy(b,c,h+Math.max(-v,0),h+m),c=a;for(var x=c;c<x+y;++c)b[c]=0;return e.copy(b,c,_+Math.max(-y,0),_+g),b=b.toString(`base64`),b=d(b),b}function m(e,t,n){for(var r=0;t+r<n&&e[t+r]===0;)++r;return e[t+r]>=i&&--r,r}function h(e,t){e=f(e);var a=r(t),o=e.length;if(o!==a*2)throw TypeError(`"`+t+`" signatures must be "`+a*2+`" bytes, saw "`+o+`"`);var s=m(e,0,a),c=m(e,a,e.length),d=a-s,p=a-c,h=2+d+1+1+p,g=h<i,_=n.allocUnsafe((g?2:3)+h),v=0;return _[v++]=l,g?_[v++]=h:(_[v++]=i|1,_[v++]=h&255),_[v++]=u,_[v++]=d,s<0?(_[v++]=0,v+=e.copy(_,v,0,a)):v+=e.copy(_,v,s,a),_[v++]=u,_[v++]=p,c<0?(_[v++]=0,e.copy(_,v,a)):e.copy(_,v,a+c),_}t.exports={derToJose:p,joseToDer:h}})),I=n((t=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.LRUCache=void 0,t.snakeToCamel=o,t.originalOrCamelOptions=s,t.removeUndefinedValuesInObject=c,t.isValidFile=l,t.getWellKnownCertificateConfigFileLocation=u;let n=e(`fs`),r=e(`os`),i=e(`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}}t.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`)}})),L=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`}})),R=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.USER_AGENT=e.PRODUCT_NAME=e.pkg=void 0;let t=L();e.pkg=t;let n=`google-api-nodejs-client`;e.PRODUCT_NAME=n,e.USER_AGENT=`${n}/${t.version}`})),z=n((t=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.AuthClient=t.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS=t.DEFAULT_UNIVERSE=void 0;let n=e(`events`),r=S(),i=I(),a=A(),o=R();t.DEFAULT_UNIVERSE=`googleapis.com`,t.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS=300*1e3,t.AuthClient=class e extends n.EventEmitter{apiKey;projectId;quotaProjectId;transporter;credentials={};eagerRefreshThresholdMillis=t.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS;forceRefreshOnFailure=!1;universeDomain=t.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`)??t.DEFAULT_UNIVERSE,this.transporter=n.transporter??new r.Gaxios(n.transporterOptions),a.get(`useAuthRequestParameters`)!==!1&&(this.transporter.interceptors.request.add(e.DEFAULT_REQUEST_INTERCEPTOR),this.transporter.interceptors.response.add(e.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 t=>{if(!t.headers.has(`x-goog-api-client`)){let e=process.version.replace(/^v/,``);t.headers.set(`x-goog-api-client`,`gl-node/${e}`)}let n=t.headers.get(`User-Agent`);n?n.includes(`${o.PRODUCT_NAME}/`)||t.headers.set(`User-Agent`,`${n} ${o.USER_AGENT}`):t.headers.set(`User-Agent`,o.USER_AGENT);try{let n=t,r=n[e.RequestMethodNameSymbol],i=`${Math.floor(Math.random()*1e3)}`;n[e.RequestLogIdSymbol]=i;let a={url:t.url,headers:t.headers};r?e.log.info(`%s [%s] request %j`,r,i,a):e.log.info(`[%s] request %j`,i,a)}catch{}return t}};static DEFAULT_RESPONSE_INTERCEPTOR={resolved:async t=>{try{let n=t.config,r=n[e.RequestMethodNameSymbol],i=n[e.RequestLogIdSymbol];r?e.log.info(`%s [%s] response %j`,r,i,t.data):e.log.info(`[%s] response %j`,i,t.data)}catch{}return t},rejected:async t=>{try{let n=t.config,r=n[e.RequestMethodNameSymbol],i=n[e.RequestLogIdSymbol];r?e.log.info(`%s [%s] error %j`,r,i,t.response?.data):e.log.error(`[%s] error %j`,i,t.response?.data)}catch{}throw t}};static setMethodName(t,n){try{let r=t;r[e.RequestMethodNameSymbol]=n}catch{}}static get RETRY_CONFIG(){return{retry:!0,retryConfig:{httpMethodsToRetry:[`GET`,`PUT`,`POST`,`HEAD`,`OPTIONS`,`DELETE`]}}}}})),ie=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()}}}})),ae=n((t=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.OAuth2Client=t.ClientAuthentication=t.CertificateFormat=t.CodeChallengeMethod=void 0;let n=S(),r=e(`querystring`),i=e(`stream`),a=re(),o=I(),s=te(),c=z(),l=ie();var u;(function(e){e.Plain=`plain`,e.S256=`S256`})(u||(t.CodeChallengeMethod=u={}));var d;(function(e){e.PEM=`PEM`,e.JWK=`JWK`})(d||(t.CertificateFormat=d={}));var f;(function(e){e.ClientSecretPost=`ClientSecretPost`,e.ClientSecretBasic=`ClientSecretBasic`,e.None=`None`})(f||(t.ClientAuthentication=f={})),t.OAuth2Client=class e extends c.AuthClient{redirectUri;certificateCache={};certificateExpiry=null;certificateCacheFormat=d.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||f.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,s.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===f.ClientSecretBasic){let e=Buffer.from(`${this._clientId}:${this._clientSecret}`);r.set(`authorization`,`Basic ${e.toString(`base64`)}`)}this.clientAuthentication===f.ClientSecretPost&&(i.client_secret=this._clientSecret);let a={...e.RETRY_CONFIG,method:`POST`,url:n,data:new URLSearchParams((0,o.removeUndefinedValuesInObject)(i)),headers:r};c.AuthClient.setMethodName(a,`getTokenAsync`);let s=await this.transporter.request(a),l=s.data;return s.data&&s.data.expires_in&&(l.expiry_date=new Date().getTime()+s.data.expires_in*1e3,delete l.expires_in),this.emit(`tokens`,l),{tokens:l,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))};c.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(c.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,s.hasBrowserCrypto)()?d.JWK:d.PEM;if(this.certificateExpiry&&t<this.certificateExpiry.getTime()&&this.certificateCacheFormat===n)return{certs:this.certificateCache,format:n};let r,i;switch(n){case d.PEM:i=this.endpoints.oauth2FederatedSignonPemCertsUrl.toString();break;case d.JWK:i=this.endpoints.oauth2FederatedSignonJwkCertsUrl.toString();break;default:throw Error(`Unsupported certificate format ${n}`)}try{let t={...e.RETRY_CONFIG,url:i};c.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 l={};switch(n){case d.PEM:l=r.data;break;case d.JWK:for(let e of r.data.keys)l[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=l,this.certificateCacheFormat=n,{certs:l,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};c.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 c=(0,s.createCrypto)();o||=e.DEFAULT_MAX_TOKEN_LIFETIME_SECS_;let u=t.split(`.`);if(u.length!==3)throw Error(`Wrong number of segments in token: `+t);let d=u[0]+`.`+u[1],f=u[2],p,m;try{p=JSON.parse(c.decodeBase64StringUtf8(u[0]))}catch(e){throw e instanceof Error&&(e.message=`Can't parse token envelope: ${u[0]}': ${e.message}`),e}if(!p)throw Error(`Can't parse token envelope: `+u[0]);try{m=JSON.parse(c.decodeBase64StringUtf8(u[1]))}catch(e){throw e instanceof Error&&(e.message=`Can't parse token payload '${u[0]}`),e}if(!m)throw Error(`Can't parse token payload: `+u[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 c.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 l.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}}})),oe=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.Compute=void 0;let t=S(),n=j(),r=ae();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))}}})),se=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.IdTokenClient=void 0;let t=ae();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}}})),ce=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.GCPEnv=void 0,e.clear=i,e.getEnv=a;let t=j();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()}})),le=n(((t,n)=>{var r=F().Buffer,i=e(`stream`),a=e(`util`);function o(e){if(this.buffer=null,this.writable=!0,this.readable=!0,!e)return this.buffer=r.alloc(0),this;if(typeof e.pipe==`function`)return this.buffer=r.alloc(0),e.pipe(this),this;if(e.length||typeof e==`object`)return this.buffer=e,this.writable=!1,process.nextTick(function(){this.emit(`end`,e),this.readable=!1,this.emit(`close`)}.bind(this)),this;throw TypeError(`Unexpected data type (`+typeof e+`)`)}a.inherits(o,i),o.prototype.write=function(e){this.buffer=r.concat([this.buffer,r.from(e)]),this.emit(`data`,e)},o.prototype.end=function(e){e&&this.write(e),this.emit(`end`,e),this.emit(`close`),this.writable=!1,this.readable=!1},n.exports=o})),ue=n(((t,n)=>{var r=e(`buffer`).Buffer,i=e(`buffer`).SlowBuffer;n.exports=a;function a(e,t){if(!r.isBuffer(e)||!r.isBuffer(t)||e.length!==t.length)return!1;for(var n=0,i=0;i<e.length;i++)n|=e[i]^t[i];return n===0}a.install=function(){r.prototype.equal=i.prototype.equal=function(e){return a(this,e)}};var o=r.prototype.equal,s=i.prototype.equal;a.restore=function(){r.prototype.equal=o,i.prototype.equal=s}})),de=n(((t,n)=>{var r=F().Buffer,i=e(`crypto`),a=re(),o=e(`util`),s=`"%s" is not a valid algorithm.
14
+ Supported algorithms are:
15
+ "HS256", "HS384", "HS512", "RS256", "RS384", "RS512", "PS256", "PS384", "PS512", "ES256", "ES384", "ES512" and "none".`,c=`secret must be a string or buffer`,l=`key must be a string or a buffer`,u=`key must be a string, a buffer or an object`,d=typeof i.createPublicKey==`function`;d&&(l+=` or a KeyObject`,c+=`or a KeyObject`);function f(e){if(!r.isBuffer(e)&&typeof e!=`string`&&(!d||typeof e!=`object`||typeof e.type!=`string`||typeof e.asymmetricKeyType!=`string`||typeof e.export!=`function`))throw _(l)}function p(e){if(!r.isBuffer(e)&&typeof e!=`string`&&typeof e!=`object`)throw _(u)}function m(e){if(!r.isBuffer(e)){if(typeof e==`string`)return e;if(!d||typeof e!=`object`||e.type!==`secret`||typeof e.export!=`function`)throw _(c)}}function h(e){return e.replace(/=/g,``).replace(/\+/g,`-`).replace(/\//g,`_`)}function g(e){e=e.toString();var t=4-e.length%4;if(t!==4)for(var n=0;n<t;++n)e+=`=`;return e.replace(/\-/g,`+`).replace(/_/g,`/`)}function _(e){var t=[].slice.call(arguments,1),n=o.format.bind(o,e).apply(null,t);return TypeError(n)}function v(e){return r.isBuffer(e)||typeof e==`string`}function y(e){return v(e)||(e=JSON.stringify(e)),e}function b(e){return function(t,n){m(n),t=y(t);var r=i.createHmac(`sha`+e,n);return h((r.update(t),r.digest(`base64`)))}}var x,S=`timingSafeEqual`in i?function(e,t){return e.byteLength===t.byteLength?i.timingSafeEqual(e,t):!1}:function(e,t){return x||=ue(),x(e,t)};function C(e){return function(t,n,i){var a=b(e)(t,i);return S(r.from(n),r.from(a))}}function w(e){return function(t,n){p(n),t=y(t);var r=i.createSign(`RSA-SHA`+e);return h((r.update(t),r.sign(n,`base64`)))}}function T(e){return function(t,n,r){f(r),t=y(t),n=g(n);var a=i.createVerify(`RSA-SHA`+e);return a.update(t),a.verify(r,n,`base64`)}}function E(e){return function(t,n){p(n),t=y(t);var r=i.createSign(`RSA-SHA`+e);return h((r.update(t),r.sign({key:n,padding:i.constants.RSA_PKCS1_PSS_PADDING,saltLength:i.constants.RSA_PSS_SALTLEN_DIGEST},`base64`)))}}function D(e){return function(t,n,r){f(r),t=y(t),n=g(n);var a=i.createVerify(`RSA-SHA`+e);return a.update(t),a.verify({key:r,padding:i.constants.RSA_PKCS1_PSS_PADDING,saltLength:i.constants.RSA_PSS_SALTLEN_DIGEST},n,`base64`)}}function O(e){var t=w(e);return function(){var n=t.apply(null,arguments);return n=a.derToJose(n,`ES`+e),n}}function k(e){var t=T(e);return function(n,r,i){return r=a.joseToDer(r,`ES`+e).toString(`base64`),t(n,r,i)}}function A(){return function(){return``}}function j(){return function(e,t){return t===``}}n.exports=function(e){var t={hs:b,rs:w,ps:E,es:O,none:A},n={hs:C,rs:T,ps:D,es:k,none:j},r=e.match(/^(RS|PS|ES|HS)(256|384|512)$|^(none)$/);if(!r)throw _(s,e);var i=(r[1]||r[3]).toLowerCase(),a=r[2];return{sign:t[i](a),verify:n[i](a)}}})),fe=n(((t,n)=>{var r=e(`buffer`).Buffer;n.exports=function(e){return typeof e==`string`?e:typeof e==`number`||r.isBuffer(e)?e.toString():JSON.stringify(e)}})),pe=n(((t,n)=>{var r=F().Buffer,i=le(),a=de(),o=e(`stream`),s=fe(),c=e(`util`);function l(e,t){return r.from(e,t).toString(`base64`).replace(/=/g,``).replace(/\+/g,`-`).replace(/\//g,`_`)}function u(e,t,n){n||=`utf8`;var r=l(s(e),`binary`),i=l(s(t),n);return c.format(`%s.%s`,r,i)}function d(e){var t=e.header,n=e.payload,r=e.secret||e.privateKey,i=e.encoding,o=a(t.alg),s=u(t,n,i),l=o.sign(s,r);return c.format(`%s.%s`,s,l)}function f(e){var t=e.secret;if(t??=e.privateKey,t??=e.key,/^hs/i.test(e.header.alg)===!0&&t==null)throw TypeError(`secret must be a string or buffer or a KeyObject`);var n=new i(t);this.readable=!0,this.header=e.header,this.encoding=e.encoding,this.secret=this.privateKey=this.key=n,this.payload=new i(e.payload),this.secret.once(`close`,function(){!this.payload.writable&&this.readable&&this.sign()}.bind(this)),this.payload.once(`close`,function(){!this.secret.writable&&this.readable&&this.sign()}.bind(this))}c.inherits(f,o),f.prototype.sign=function(){try{var e=d({header:this.header,payload:this.payload.buffer,secret:this.secret.buffer,encoding:this.encoding});return this.emit(`done`,e),this.emit(`data`,e),this.emit(`end`),this.readable=!1,e}catch(e){this.readable=!1,this.emit(`error`,e),this.emit(`close`)}},f.sign=d,n.exports=f})),me=n(((t,n)=>{var r=F().Buffer,i=le(),a=de(),o=e(`stream`),s=fe(),c=e(`util`),l=/^[a-zA-Z0-9\-_]+?\.[a-zA-Z0-9\-_]+?\.([a-zA-Z0-9\-_]+)?$/;function u(e){return Object.prototype.toString.call(e)===`[object Object]`}function d(e){if(u(e))return e;try{return JSON.parse(e)}catch{return}}function f(e){var t=e.split(`.`,1)[0];return d(r.from(t,`base64`).toString(`binary`))}function p(e){return e.split(`.`,2).join(`.`)}function m(e){return e.split(`.`)[2]}function h(e,t){t||=`utf8`;var n=e.split(`.`)[1];return r.from(n,`base64`).toString(t)}function g(e){return l.test(e)&&!!f(e)}function _(e,t,n){if(!t){var r=Error(`Missing algorithm parameter for jws.verify`);throw r.code=`MISSING_ALGORITHM`,r}e=s(e);var i=m(e),o=p(e);return a(t).verify(o,i,n)}function v(e,t){if(t||={},e=s(e),!g(e))return null;var n=f(e);if(!n)return null;var r=h(e);return(n.typ===`JWT`||t.json)&&(r=JSON.parse(r,t.encoding)),{header:n,payload:r,signature:m(e)}}function y(e){e||={};var t=e.secret;if(t??=e.publicKey,t??=e.key,/^hs/i.test(e.algorithm)===!0&&t==null)throw TypeError(`secret must be a string or buffer or a KeyObject`);var n=new i(t);this.readable=!0,this.algorithm=e.algorithm,this.encoding=e.encoding,this.secret=this.publicKey=this.key=n,this.signature=new i(e.signature),this.secret.once(`close`,function(){!this.signature.writable&&this.readable&&this.verify()}.bind(this)),this.signature.once(`close`,function(){!this.secret.writable&&this.readable&&this.verify()}.bind(this))}c.inherits(y,o),y.prototype.verify=function(){try{var e=_(this.signature.buffer,this.algorithm,this.key.buffer),t=v(this.signature.buffer,this.encoding);return this.emit(`done`,e,t),this.emit(`data`,e),this.emit(`end`),this.readable=!1,e}catch(e){this.readable=!1,this.emit(`error`,e),this.emit(`close`)}},y.decode=v,y.isValid=g,y.verify=_,n.exports=y})),he=n((e=>{var t=pe(),n=me();e.ALGORITHMS=[`HS256`,`HS384`,`HS512`,`RS256`,`RS384`,`RS512`,`PS256`,`PS384`,`PS512`,`ES256`,`ES384`,`ES512`],e.sign=t.sign,e.verify=n.verify,e.decode=n.decode,e.isValid=n.isValid,e.createSign=function(e){return new t(e)},e.createVerify=function(e){return new n(e)}})),ge=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.buildPayloadForJwsSign=n,e.getJwsSign=r;let t=he();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})}})),_e=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.getToken=r;let t=ge(),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}}})),ve=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}}})),ye=n((t=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.getCredentials=f;let n=e(`path`),r=e(`fs`),i=e(`util`),a=ve(),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){let t=e;throw Error(`Invalid JSON key file: ${t.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()}})),be=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.TokenHandler=void 0;let t=_e(),n=ye();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}}}})),xe=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})}})),Se=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.GoogleToken=void 0;let t=S(),n=be(),r=xe();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}}})),Ce=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.JWTAccess=void 0;let t=he(),n=I(),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)}})})}}})),we=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.JWT=void 0;let t=Se(),n=ye(),r=Ce(),i=ae(),a=z();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.`)}}})),Te=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.UserRefreshClient=e.USER_REFRESH_ACCOUNT_TYPE=void 0;let t=ae(),n=z();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}}})),Ee=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.Impersonated=e.IMPERSONATED_ACCOUNT_TYPE=void 0;let t=ae(),n=S(),r=I();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}}})),De=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.OAuthClientAuthHandler=void 0,e.getErrorFromOAuthErrorResponse=i;let t=S(),n=te(),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}})),Oe=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.StsCredentials=void 0;let t=S(),n=z(),r=De(),i=I();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}}}})),ke=n((t=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.BaseExternalAccountClient=t.CLOUD_RESOURCE_MANAGER=t.EXTERNAL_ACCOUNT_TYPE=t.EXPIRATION_TIME_OFFSET=void 0;let n=S(),r=e(`stream`),i=z(),a=Oe(),o=I(),s=R(),c=`https://www.googleapis.com/auth/cloud-platform`;t.EXPIRATION_TIME_OFFSET=300*1e3,t.EXTERNAL_ACCOUNT_TYPE=`external_account`,t.CLOUD_RESOURCE_MANAGER=`https://cloudresourcemanager.googleapis.com/v1/projects/`,t.BaseExternalAccountClient=class e extends i.AuthClient{scopes;projectNumber;audience;subjectTokenType;stsCredential;clientAuth;credentialSourceType;cachedAccessToken;serviceAccountImpersonationUrl;serviceAccountImpersonationLifetime;workforcePoolUserProject;configLifetimeRequested;tokenUrl;cloudResourceManagerURL;supplierContext;#e=null;constructor(e){super(e);let n=(0,o.originalOrCamelOptions)(e),r=n.get(`type`);if(r&&r!==t.EXTERNAL_ACCOUNT_TYPE)throw Error(`Expected "${t.EXTERNAL_ACCOUNT_TYPE}" type but received "${e.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 t=this.projectNumber||this.workforcePoolUserProject;if(this.projectId)return this.projectId;if(t){let n=await this.getRequestHeaders(),r={...e.RETRY_CONFIG,headers:n,url:`${this.cloudResourceManagerURL.toString()}${t}`,responseType:`json`};return i.AuthClient.setMethodName(r,`getProjectId`),this.projectId=(await this.transporter.request(r)).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(t){let n={...e.RETRY_CONFIG,url:this.serviceAccountImpersonationUrl,method:`POST`,headers:{"content-type":`application/json`,authorization:`Bearer ${t}`},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}}})),Ae=n((t=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.FileSubjectTokenSupplier=void 0;let n=e(`util`),r=e(`fs`),i=(0,n.promisify)(r.readFile??(()=>{})),a=(0,n.promisify)(r.realpath??(()=>{})),o=(0,n.promisify)(r.lstat??(()=>{}));t.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}}})),je=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.UrlSubjectTokenSupplier=void 0;let t=z();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}}})),Me=n((t=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.CertificateSubjectTokenSupplier=t.InvalidConfigurationError=t.CertificateSourceUnavailableError=t.CERTIFICATE_CONFIGURATION_ENV_VARIABLE=void 0;let n=I(),r=e(`fs`),i=e(`crypto`),a=e(`https`);t.CERTIFICATE_CONFIGURATION_ENV_VARIABLE=`GOOGLE_API_CERTIFICATE_CONFIG`;var o=class extends Error{constructor(e){super(e),this.name=`CertificateSourceUnavailableError`}};t.CertificateSourceUnavailableError=o;var s=class extends Error{constructor(e){super(e),this.name=`InvalidConfigurationError`}};t.InvalidConfigurationError=s,t.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 e=this.certificateConfigPath;if(e){if(await(0,n.isValidFile)(e))return e;throw new o(`Provided certificate config path is invalid: ${e}`)}let r=process.env[t.CERTIFICATE_CONFIGURATION_ENV_VARIABLE];if(r){if(await(0,n.isValidFile)(r))return r;throw new o(`Path from environment variable "${t.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 "${t.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}`)}}}})),Ne=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.IdentityPoolClient=void 0;let t=ke(),n=I(),r=Ae(),i=je(),a=Me(),o=Oe(),s=S();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`,this.subjectTokenSupplier=new a.CertificateSubjectTokenSupplier({useDefaultCertificateConfig:f.use_default_certificate_config,certificateConfigLocation:f.certificate_config_location,trustChainPath:f.trust_chain_path});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}}})),Pe=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.AwsRequestSigner=void 0;let t=S(),n=te(),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}}})),Fe=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.DefaultAwsSecurityCredentialsSupplier=void 0;let t=z();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}}})),Ie=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.AwsClient=void 0;let t=Pe(),n=ke(),r=Fe(),i=I(),a=S();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}))}}})),Le=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})),Re=n((t=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.PluggableAuthHandler=t.ExecutableError=void 0;let n=Le(),r=e(`child_process`),i=e(`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)}};t.ExecutableError=a,t.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}}})),ze=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.PluggableAuthClient=e.ExecutableError=void 0;let t=ke(),n=Le(),r=Re();var i=Re();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}}})),Be=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.ExternalAccountClient=void 0;let t=ke(),n=Ne(),r=Ie(),i=ze();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}}})),Ve=n((t=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.ExternalAccountAuthorizedUserClient=t.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE=void 0;let n=z(),r=De(),i=S(),a=e(`stream`),o=ke();t.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}}};t.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}}})),He=n((t=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.GoogleAuth=t.GoogleAuthExceptionMessages=void 0;let n=e(`child_process`),r=e(`fs`),i=S(),a=j(),o=e(`os`),s=e(`path`),c=te(),l=oe(),u=se(),d=ce(),f=we(),p=Te(),m=Ee(),h=Be(),g=ke(),_=z(),v=Ve(),y=I();t.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.
16
+ To learn more about authentication and Google APIs, visit:
17
+ https://cloud.google.com/docs/authentication/getting-started`,NO_CREDENTIALS_FOUND:`Unable to find credentials in current environment.
18
+ To learn more about authentication and Google APIs, visit:
19
+ 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.
20
+ To learn more about Universe Domain retrieval, visit:
21
+ https://cloud.google.com/compute/docs/metadata/predefined-metadata-keys`},t.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(e={}){if(this._cachedProjectId=e.projectId||null,this.cachedCredential=e.authClient||null,this.keyFilename=e.keyFilename||e.keyFile,this.scopes=e.scopes,this.clientOptions=e.clientOptions||{},this.jsonContent=e.credentials||null,this.apiKey=e.apiKey||this.clientOptions.apiKey||null,this.apiKey&&(this.jsonContent||this.clientOptions.credentials))throw RangeError(t.GoogleAuthExceptionMessages.API_KEY_WITH_CREDENTIALS);e.universeDomain&&(this.clientOptions.universeDomain=e.universeDomain)}setGapicJWTValues(e){e.defaultServicePath=this.defaultServicePath,e.useJWTAccessWithScope=this.useJWTAccessWithScope,e.defaultScopes=this.defaultScopes}getProjectId(e){if(e)this.getProjectIdAsync().then(t=>e(null,t),e);else return this.getProjectIdAsync()}async getProjectIdOptional(){try{return await this.getProjectId()}catch(e){if(e instanceof Error&&e.message===t.GoogleAuthExceptionMessages.NO_PROJECT_ID_FOUND)return null;throw e}}async findAndCacheProjectId(){let e=null;if(e||=await this.getProductionProjectId(),e||=await this.getFileProjectId(),e||=await this.getDefaultServiceProjectId(),e||=await this.getGCEProjectId(),e||=await this.getExternalAccountClientProjectId(),e)return this._cachedProjectId=e,e;throw Error(t.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(e={}){if(this.cachedCredential)return await this.#t(this.cachedCredential,null);let n;if(n=await this._tryGetApplicationCredentialsFromEnvironmentVariable(e),n||(n=await this._tryGetApplicationCredentialsFromWellKnownFile(e),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 e.scopes=this.getAnyScopes(),await this.#t(new l.Compute(e));throw Error(t.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 e=await this.getClient();if(e instanceof m.Impersonated)return{client_email:e.getTargetPrincipal()};if(e instanceof g.BaseExternalAccountClient){let t=e.getServiceAccountEmail();if(t)return{client_email:t,universe_domain:e.universeDomain}}if(this.jsonContent)return{client_email:this.jsonContent.client_email,private_key:this.jsonContent.private_key,universe_domain:this.jsonContent.universe_domain};if(await this._checkIsGCE()){let[e,t]=await Promise.all([a.instance(`service-accounts/default/email`),this.getUniverseDomain()]);return{client_email:e,universe_domain:t}}throw Error(t.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}}})),Ue=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}}}})),We=n((t=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.DownscopedClient=t.EXPIRATION_TIME_OFFSET=t.MAX_ACCESS_BOUNDARY_RULES_COUNT=void 0;let n=S(),r=e(`stream`),i=z(),a=Oe();t.MAX_ACCESS_BOUNDARY_RULES_COUNT=10,t.EXPIRATION_TIME_OFFSET=300*1e3,t.DownscopedClient=class extends i.AuthClient{authClient;credentialAccessBoundary;cachedDownscopedAccessToken;stsCredential;constructor(e,n={accessBoundary:{accessBoundaryRules:[]}}){if(super(e instanceof i.AuthClient?{}:e),e instanceof i.AuthClient?(this.authClient=e,this.credentialAccessBoundary=n):(this.authClient=e.authClient,this.credentialAccessBoundary=e.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>t.MAX_ACCESS_BOUNDARY_RULES_COUNT)throw Error(`The provided access boundary has more than ${t.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}}})),Ge=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.PassThroughClient=void 0;let t=z();e.PassThroughClient=class extends t.AuthClient{async request(e){return this.transporter.request(e)}async getAccessToken(){return{}}async getRequestHeaders(){return new Headers}}})),Ke=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=He();Object.defineProperty(e,`GoogleAuth`,{enumerable:!0,get:function(){return r.GoogleAuth}}),e.gcpMetadata=j(),e.gaxios=S();var i=z();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=oe();Object.defineProperty(e,`Compute`,{enumerable:!0,get:function(){return a.Compute}});var o=ce();Object.defineProperty(e,`GCPEnv`,{enumerable:!0,get:function(){return o.GCPEnv}});var s=Ue();Object.defineProperty(e,`IAMAuth`,{enumerable:!0,get:function(){return s.IAMAuth}});var c=se();Object.defineProperty(e,`IdTokenClient`,{enumerable:!0,get:function(){return c.IdTokenClient}});var l=Ce();Object.defineProperty(e,`JWTAccess`,{enumerable:!0,get:function(){return l.JWTAccess}});var u=we();Object.defineProperty(e,`JWT`,{enumerable:!0,get:function(){return u.JWT}});var d=Ee();Object.defineProperty(e,`Impersonated`,{enumerable:!0,get:function(){return d.Impersonated}});var f=ae();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=ie();Object.defineProperty(e,`LoginTicket`,{enumerable:!0,get:function(){return p.LoginTicket}});var m=Te();Object.defineProperty(e,`UserRefreshClient`,{enumerable:!0,get:function(){return m.UserRefreshClient}});var h=Ie();Object.defineProperty(e,`AwsClient`,{enumerable:!0,get:function(){return h.AwsClient}});var g=Pe();Object.defineProperty(e,`AwsRequestSigner`,{enumerable:!0,get:function(){return g.AwsRequestSigner}});var _=Ne();Object.defineProperty(e,`IdentityPoolClient`,{enumerable:!0,get:function(){return _.IdentityPoolClient}});var v=Be();Object.defineProperty(e,`ExternalAccountClient`,{enumerable:!0,get:function(){return v.ExternalAccountClient}});var y=ke();Object.defineProperty(e,`BaseExternalAccountClient`,{enumerable:!0,get:function(){return y.BaseExternalAccountClient}});var b=We();Object.defineProperty(e,`DownscopedClient`,{enumerable:!0,get:function(){return b.DownscopedClient}});var x=ze();Object.defineProperty(e,`PluggableAuthClient`,{enumerable:!0,get:function(){return x.PluggableAuthClient}}),Object.defineProperty(e,`ExecutableError`,{enumerable:!0,get:function(){return x.ExecutableError}});var C=Ve();Object.defineProperty(e,`EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE`,{enumerable:!0,get:function(){return C.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE}}),Object.defineProperty(e,`ExternalAccountAuthorizedUserClient`,{enumerable:!0,get:function(){return C.ExternalAccountAuthorizedUserClient}});var w=Ge();Object.defineProperty(e,`PassThroughClient`,{enumerable:!0,get:function(){return w.PassThroughClient}}),n(Se(),e),e.auth=new r.GoogleAuth})),qe=n(((e,t)=>{let n=[`nodebuffer`,`arraybuffer`,`fragments`],r=typeof Blob<`u`;r&&n.push(`blob`),t.exports={BINARY_TYPES:n,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:`258EAFA5-E914-47DA-95CA-C5AB0DC85B11`,hasBlob:r,kForOnEventAttribute:Symbol(`kIsForOnEventAttribute`),kListener:Symbol(`kListener`),kStatusCode:Symbol(`status-code`),kWebSocket:Symbol(`websocket`),NOOP:()=>{}}})),Je=n(((t,n)=>{let{EMPTY_BUFFER:r}=qe(),i=Buffer[Symbol.species];function a(e,t){if(e.length===0)return r;if(e.length===1)return e[0];let n=Buffer.allocUnsafe(t),a=0;for(let t=0;t<e.length;t++){let r=e[t];n.set(r,a),a+=r.length}return a<t?new i(n.buffer,n.byteOffset,a):n}function o(e,t,n,r,i){for(let a=0;a<i;a++)n[r+a]=e[a]^t[a&3]}function s(e,t){for(let n=0;n<e.length;n++)e[n]^=t[n&3]}function c(e){return e.length===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.length)}function l(e){if(l.readOnly=!0,Buffer.isBuffer(e))return e;let t;return e instanceof ArrayBuffer?t=new i(e):ArrayBuffer.isView(e)?t=new i(e.buffer,e.byteOffset,e.byteLength):(t=Buffer.from(e),l.readOnly=!1),t}if(n.exports={concat:a,mask:o,toArrayBuffer:c,toBuffer:l,unmask:s},!process.env.WS_NO_BUFFER_UTIL)try{let t=e(`bufferutil`);n.exports.mask=function(e,n,r,i,a){a<48?o(e,n,r,i,a):t.mask(e,n,r,i,a)},n.exports.unmask=function(e,n){e.length<32?s(e,n):t.unmask(e,n)}}catch{}})),Ye=n(((e,t)=>{let n=Symbol(`kDone`),r=Symbol(`kRun`);t.exports=class{constructor(e){this[n]=()=>{this.pending--,this[r]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[r]()}[r](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[n])}}}})),Xe=n(((t,n)=>{let r=e(`zlib`),i=Je(),a=Ye(),{kStatusCode:o}=qe(),s=Buffer[Symbol.species],c=Buffer.from([0,0,255,255]),l=Symbol(`permessage-deflate`),u=Symbol(`total-length`),d=Symbol(`callback`),f=Symbol(`buffers`),p=Symbol(`error`),m;n.exports=class{constructor(e){this._options=e||{},this._threshold=this._options.threshold===void 0?1024:this._options.threshold,this._maxPayload=this._options.maxPayload|0,this._isServer=!!this._options.isServer,this._deflate=null,this._inflate=null,this.params=null,m||=new a(this._options.concurrencyLimit===void 0?10:this._options.concurrencyLimit)}static get extensionName(){return`permessage-deflate`}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits??(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&=(this._inflate.close(),null),this._deflate){let e=this._deflate[d];this._deflate.close(),this._deflate=null,e&&e(Error(`The deflate stream was closed while data was being processed`))}}acceptAsServer(e){let t=this._options,n=e.find(e=>!(t.serverNoContextTakeover===!1&&e.server_no_context_takeover||e.server_max_window_bits&&(t.serverMaxWindowBits===!1||typeof t.serverMaxWindowBits==`number`&&t.serverMaxWindowBits>e.server_max_window_bits)||typeof t.clientMaxWindowBits==`number`&&!e.client_max_window_bits));if(!n)throw Error(`None of the extension offers can be accepted`);return t.serverNoContextTakeover&&(n.server_no_context_takeover=!0),t.clientNoContextTakeover&&(n.client_no_context_takeover=!0),typeof t.serverMaxWindowBits==`number`&&(n.server_max_window_bits=t.serverMaxWindowBits),typeof t.clientMaxWindowBits==`number`?n.client_max_window_bits=t.clientMaxWindowBits:(n.client_max_window_bits===!0||t.clientMaxWindowBits===!1)&&delete n.client_max_window_bits,n}acceptAsClient(e){let t=e[0];if(this._options.clientNoContextTakeover===!1&&t.client_no_context_takeover)throw Error(`Unexpected parameter "client_no_context_takeover"`);if(!t.client_max_window_bits)typeof this._options.clientMaxWindowBits==`number`&&(t.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits==`number`&&t.client_max_window_bits>this._options.clientMaxWindowBits)throw Error(`Unexpected or invalid parameter "client_max_window_bits"`);return t}normalizeParams(e){return e.forEach(e=>{Object.keys(e).forEach(t=>{let n=e[t];if(n.length>1)throw Error(`Parameter "${t}" must have only a single value`);if(n=n[0],t===`client_max_window_bits`){if(n!==!0){let e=+n;if(!Number.isInteger(e)||e<8||e>15)throw TypeError(`Invalid value for parameter "${t}": ${n}`);n=e}else if(!this._isServer)throw TypeError(`Invalid value for parameter "${t}": ${n}`)}else if(t===`server_max_window_bits`){let e=+n;if(!Number.isInteger(e)||e<8||e>15)throw TypeError(`Invalid value for parameter "${t}": ${n}`);n=e}else if(t===`client_no_context_takeover`||t===`server_no_context_takeover`){if(n!==!0)throw TypeError(`Invalid value for parameter "${t}": ${n}`)}else throw Error(`Unknown parameter "${t}"`);e[t]=n})}),e}decompress(e,t,n){m.add(r=>{this._decompress(e,t,(e,t)=>{r(),n(e,t)})})}compress(e,t,n){m.add(r=>{this._compress(e,t,(e,t)=>{r(),n(e,t)})})}_decompress(e,t,n){let a=this._isServer?`client`:`server`;if(!this._inflate){let e=`${a}_max_window_bits`,t=typeof this.params[e]==`number`?this.params[e]:r.Z_DEFAULT_WINDOWBITS;this._inflate=r.createInflateRaw({...this._options.zlibInflateOptions,windowBits:t}),this._inflate[l]=this,this._inflate[u]=0,this._inflate[f]=[],this._inflate.on(`error`,_),this._inflate.on(`data`,g)}this._inflate[d]=n,this._inflate.write(e),t&&this._inflate.write(c),this._inflate.flush(()=>{let e=this._inflate[p];if(e){this._inflate.close(),this._inflate=null,n(e);return}let r=i.concat(this._inflate[f],this._inflate[u]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[u]=0,this._inflate[f]=[],t&&this.params[`${a}_no_context_takeover`]&&this._inflate.reset()),n(null,r)})}_compress(e,t,n){let a=this._isServer?`server`:`client`;if(!this._deflate){let e=`${a}_max_window_bits`,t=typeof this.params[e]==`number`?this.params[e]:r.Z_DEFAULT_WINDOWBITS;this._deflate=r.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:t}),this._deflate[u]=0,this._deflate[f]=[],this._deflate.on(`data`,h)}this._deflate[d]=n,this._deflate.write(e),this._deflate.flush(r.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let e=i.concat(this._deflate[f],this._deflate[u]);t&&(e=new s(e.buffer,e.byteOffset,e.length-4)),this._deflate[d]=null,this._deflate[u]=0,this._deflate[f]=[],t&&this.params[`${a}_no_context_takeover`]&&this._deflate.reset(),n(null,e)})}};function h(e){this[f].push(e),this[u]+=e.length}function g(e){if(this[u]+=e.length,this[l]._maxPayload<1||this[u]<=this[l]._maxPayload){this[f].push(e);return}this[p]=RangeError(`Max payload size exceeded`),this[p].code=`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`,this[p][o]=1009,this.removeListener(`data`,g),this.reset()}function _(e){if(this[l]._inflate=null,this[p]){this[d](this[p]);return}e[o]=1007,this[d](e)}})),Ze=n(((t,n)=>{let{isUtf8:r}=e(`buffer`),{hasBlob:i}=qe(),a=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function o(e){return e>=1e3&&e<=1014&&e!==1004&&e!==1005&&e!==1006||e>=3e3&&e<=4999}function s(e){let t=e.length,n=0;for(;n<t;)if(!(e[n]&128))n++;else if((e[n]&224)==192){if(n+1===t||(e[n+1]&192)!=128||(e[n]&254)==192)return!1;n+=2}else if((e[n]&240)==224){if(n+2>=t||(e[n+1]&192)!=128||(e[n+2]&192)!=128||e[n]===224&&(e[n+1]&224)==128||e[n]===237&&(e[n+1]&224)==160)return!1;n+=3}else if((e[n]&248)==240){if(n+3>=t||(e[n+1]&192)!=128||(e[n+2]&192)!=128||(e[n+3]&192)!=128||e[n]===240&&(e[n+1]&240)==128||e[n]===244&&e[n+1]>143||e[n]>244)return!1;n+=4}else return!1;return!0}function c(e){return i&&typeof e==`object`&&typeof e.arrayBuffer==`function`&&typeof e.type==`string`&&typeof e.stream==`function`&&(e[Symbol.toStringTag]===`Blob`||e[Symbol.toStringTag]===`File`)}if(n.exports={isBlob:c,isValidStatusCode:o,isValidUTF8:s,tokenChars:a},r)n.exports.isValidUTF8=function(e){return e.length<24?s(e):r(e)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=e(`utf-8-validate`);n.exports.isValidUTF8=function(e){return e.length<32?s(e):t(e)}}catch{}})),Qe=n(((t,n)=>{let{Writable:r}=e(`stream`),i=Xe(),{BINARY_TYPES:a,EMPTY_BUFFER:o,kStatusCode:s,kWebSocket:c}=qe(),{concat:l,toArrayBuffer:u,unmask:d}=Je(),{isValidStatusCode:f,isValidUTF8:p}=Ze(),m=Buffer[Symbol.species];n.exports=class extends r{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents===void 0?!0:e.allowSynchronousEvents,this._binaryType=e.binaryType||a[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[c]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=0}_write(e,t,n){if(this._opcode===8&&this._state==0)return n();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(n)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let t=this._buffers[0];return this._buffers[0]=new m(t.buffer,t.byteOffset+e,t.length-e),new m(t.buffer,t.byteOffset,e)}let t=Buffer.allocUnsafe(e);do{let n=this._buffers[0],r=t.length-e;e>=n.length?t.set(this._buffers.shift(),r):(t.set(new Uint8Array(n.buffer,n.byteOffset,e),r),this._buffers[0]=new m(n.buffer,n.byteOffset+e,n.length-e)),e-=n.length}while(e>0);return t}startLoop(e){this._loop=!0;do switch(this._state){case 0:this.getInfo(e);break;case 1:this.getPayloadLength16(e);break;case 2:this.getPayloadLength64(e);break;case 3:this.getMask();break;case 4:this.getData(e);break;case 5:case 6:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let t=this.consume(2);if(t[0]&48){e(this.createError(RangeError,`RSV2 and RSV3 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_2_3`));return}let n=(t[0]&64)==64;if(n&&!this._extensions[i.extensionName]){e(this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`));return}if(this._fin=(t[0]&128)==128,this._opcode=t[0]&15,this._payloadLength=t[1]&127,this._opcode===0){if(n){e(this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`));return}if(!this._fragmented){e(this.createError(RangeError,`invalid opcode 0`,!0,1002,`WS_ERR_INVALID_OPCODE`));return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){e(this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,`WS_ERR_INVALID_OPCODE`));return}this._compressed=n}else if(this._opcode>7&&this._opcode<11){if(!this._fin){e(this.createError(RangeError,`FIN must be set`,!0,1002,`WS_ERR_EXPECTED_FIN`));return}if(n){e(this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`));return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){e(this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,`WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH`));return}}else{e(this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,`WS_ERR_INVALID_OPCODE`));return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(t[1]&128)==128,this._isServer){if(!this._masked){e(this.createError(RangeError,`MASK must be set`,!0,1002,`WS_ERR_EXPECTED_MASK`));return}}else if(this._masked){e(this.createError(RangeError,`MASK must be clear`,!0,1002,`WS_ERR_UNEXPECTED_MASK`));return}this._payloadLength===126?this._state=1:this._payloadLength===127?this._state=2:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let t=this.consume(8),n=t.readUInt32BE(0);if(n>2**21-1){e(this.createError(RangeError,`Unsupported WebSocket frame: payload length > 2^53 - 1`,!1,1009,`WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH`));return}this._payloadLength=n*2**32+t.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){e(this.createError(RangeError,`Max payload size exceeded`,!1,1009,`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`));return}this._masked?this._state=3:this._state=4}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=4}getData(e){let t=o;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}t=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&d(t,this._mask)}if(this._opcode>7){this.controlMessage(t,e);return}if(this._compressed){this._state=5,this.decompress(t,e);return}t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}decompress(e,t){this._extensions[i.extensionName].decompress(e,this._fin,(e,n)=>{if(e)return t(e);if(n.length){if(this._messageLength+=n.length,this._messageLength>this._maxPayload&&this._maxPayload>0){t(this.createError(RangeError,`Max payload size exceeded`,!1,1009,`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`));return}this._fragments.push(n)}this.dataMessage(t),this._state===0&&this.startLoop(t)})}dataMessage(e){if(!this._fin){this._state=0;return}let t=this._messageLength,n=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let r;r=this._binaryType===`nodebuffer`?l(n,t):this._binaryType===`arraybuffer`?u(l(n,t)):this._binaryType===`blob`?new Blob(n):n,this._allowSynchronousEvents?(this.emit(`message`,r,!0),this._state=0):(this._state=6,setImmediate(()=>{this.emit(`message`,r,!0),this._state=0,this.startLoop(e)}))}else{let r=l(n,t);if(!this._skipUTF8Validation&&!p(r)){e(this.createError(Error,`invalid UTF-8 sequence`,!0,1007,`WS_ERR_INVALID_UTF8`));return}this._state===5||this._allowSynchronousEvents?(this.emit(`message`,r,!1),this._state=0):(this._state=6,setImmediate(()=>{this.emit(`message`,r,!1),this._state=0,this.startLoop(e)}))}}controlMessage(e,t){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit(`conclude`,1005,o),this.end();else{let n=e.readUInt16BE(0);if(!f(n)){t(this.createError(RangeError,`invalid status code ${n}`,!0,1002,`WS_ERR_INVALID_CLOSE_CODE`));return}let r=new m(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!p(r)){t(this.createError(Error,`invalid UTF-8 sequence`,!0,1007,`WS_ERR_INVALID_UTF8`));return}this._loop=!1,this.emit(`conclude`,n,r),this.end()}this._state=0;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?`ping`:`pong`,e),this._state=0):(this._state=6,setImmediate(()=>{this.emit(this._opcode===9?`ping`:`pong`,e),this._state=0,this.startLoop(t)}))}createError(e,t,n,r,i){this._loop=!1,this._errored=!0;let a=new e(n?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(a,this.createError),a.code=i,a[s]=r,a}}})),$e=n(((t,n)=>{let{Duplex:r}=e(`stream`),{randomFillSync:i}=e(`crypto`),{types:{isUint8Array:a}}=e(`util`),o=Xe(),{EMPTY_BUFFER:s,kWebSocket:c,NOOP:l}=qe(),{isBlob:u,isValidStatusCode:d}=Ze(),{mask:f,toBuffer:p}=Je(),m=Symbol(`kByteLength`),h=Buffer.alloc(4),g=8*1024,_,v=g;n.exports=class e{constructor(e,t,n){this._extensions=t||{},n&&(this._generateMask=n,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=0,this.onerror=l,this[c]=void 0}static frame(e,t){let n,r=!1,a=2,o=!1;t.mask&&(n=t.maskBuffer||h,t.generateMask?t.generateMask(n):(v===g&&(_===void 0&&(_=Buffer.alloc(g)),i(_,0,g),v=0),n[0]=_[v++],n[1]=_[v++],n[2]=_[v++],n[3]=_[v++]),o=(n[0]|n[1]|n[2]|n[3])===0,a=6);let s;typeof e==`string`?(!t.mask||o)&&t[m]!==void 0?s=t[m]:(e=Buffer.from(e),s=e.length):(s=e.length,r=t.mask&&t.readOnly&&!o);let c=s;s>=65536?(a+=8,c=127):s>125&&(a+=2,c=126);let l=Buffer.allocUnsafe(r?s+a:a);return l[0]=t.fin?t.opcode|128:t.opcode,t.rsv1&&(l[0]|=64),l[1]=c,c===126?l.writeUInt16BE(s,2):c===127&&(l[2]=l[3]=0,l.writeUIntBE(s,4,6)),!t.mask||(l[1]|=128,l[a-4]=n[0],l[a-3]=n[1],l[a-2]=n[2],l[a-1]=n[3],o)?[l,e]:r?(f(e,n,l,a,s),[l]):(f(e,n,e,0,s),[l,e])}close(t,n,r,i){let o;if(t===void 0)o=s;else if(typeof t!=`number`||!d(t))throw TypeError(`First argument must be a valid error code number`);else if(n===void 0||!n.length)o=Buffer.allocUnsafe(2),o.writeUInt16BE(t,0);else{let e=Buffer.byteLength(n);if(e>123)throw RangeError(`The message must not be greater than 123 bytes`);if(o=Buffer.allocUnsafe(2+e),o.writeUInt16BE(t,0),typeof n==`string`)o.write(n,2);else if(a(n))o.set(n,2);else throw TypeError(`Second argument must be a string or a Uint8Array`)}let c={[m]:o.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state===0?this.sendFrame(e.frame(o,c),i):this.enqueue([this.dispatch,o,!1,c,i])}ping(t,n,r){let i,a;if(typeof t==`string`?(i=Buffer.byteLength(t),a=!1):u(t)?(i=t.size,a=!1):(t=p(t),i=t.length,a=p.readOnly),i>125)throw RangeError(`The data size must not be greater than 125 bytes`);let o={[m]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:a,rsv1:!1};u(t)?this._state===0?this.getBlobData(t,!1,o,r):this.enqueue([this.getBlobData,t,!1,o,r]):this._state===0?this.sendFrame(e.frame(t,o),r):this.enqueue([this.dispatch,t,!1,o,r])}pong(t,n,r){let i,a;if(typeof t==`string`?(i=Buffer.byteLength(t),a=!1):u(t)?(i=t.size,a=!1):(t=p(t),i=t.length,a=p.readOnly),i>125)throw RangeError(`The data size must not be greater than 125 bytes`);let o={[m]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:a,rsv1:!1};u(t)?this._state===0?this.getBlobData(t,!1,o,r):this.enqueue([this.getBlobData,t,!1,o,r]):this._state===0?this.sendFrame(e.frame(t,o),r):this.enqueue([this.dispatch,t,!1,o,r])}send(e,t,n){let r=this._extensions[o.extensionName],i=t.binary?2:1,a=t.compress,s,c;typeof e==`string`?(s=Buffer.byteLength(e),c=!1):u(e)?(s=e.size,c=!1):(e=p(e),s=e.length,c=p.readOnly),this._firstFragment?(this._firstFragment=!1,a&&r&&r.params[r._isServer?`server_no_context_takeover`:`client_no_context_takeover`]&&(a=s>=r._threshold),this._compress=a):(a=!1,i=0),t.fin&&(this._firstFragment=!0);let l={[m]:s,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:i,readOnly:c,rsv1:a};u(e)?this._state===0?this.getBlobData(e,this._compress,l,n):this.enqueue([this.getBlobData,e,this._compress,l,n]):this._state===0?this.dispatch(e,this._compress,l,n):this.enqueue([this.dispatch,e,this._compress,l,n])}getBlobData(t,n,r,i){this._bufferedBytes+=r[m],this._state=2,t.arrayBuffer().then(t=>{if(this._socket.destroyed){let e=Error(`The socket was closed while the blob was being read`);process.nextTick(y,this,e,i);return}this._bufferedBytes-=r[m];let a=p(t);n?this.dispatch(a,n,r,i):(this._state=0,this.sendFrame(e.frame(a,r),i),this.dequeue())}).catch(e=>{process.nextTick(b,this,e,i)})}dispatch(t,n,r,i){if(!n){this.sendFrame(e.frame(t,r),i);return}let a=this._extensions[o.extensionName];this._bufferedBytes+=r[m],this._state=1,a.compress(t,r.fin,(t,n)=>{if(this._socket.destroyed){y(this,Error(`The socket was closed while data was being compressed`),i);return}this._bufferedBytes-=r[m],this._state=0,r.readOnly=!1,this.sendFrame(e.frame(n,r),i),this.dequeue()})}dequeue(){for(;this._state===0&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][m],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][m],this._queue.push(e)}sendFrame(e,t){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],t),this._socket.uncork()):this._socket.write(e[0],t)}};function y(e,t,n){typeof n==`function`&&n(t);for(let n=0;n<e._queue.length;n++){let r=e._queue[n],i=r[r.length-1];typeof i==`function`&&i(t)}}function b(e,t,n){y(e,t,n),e.onerror(t)}})),et=n(((e,t)=>{let{kForOnEventAttribute:n,kListener:r}=qe(),i=Symbol(`kCode`),a=Symbol(`kData`),o=Symbol(`kError`),s=Symbol(`kMessage`),c=Symbol(`kReason`),l=Symbol(`kTarget`),u=Symbol(`kType`),d=Symbol(`kWasClean`);var f=class{constructor(e){this[l]=null,this[u]=e}get target(){return this[l]}get type(){return this[u]}};Object.defineProperty(f.prototype,`target`,{enumerable:!0}),Object.defineProperty(f.prototype,`type`,{enumerable:!0});var p=class extends f{constructor(e,t={}){super(e),this[i]=t.code===void 0?0:t.code,this[c]=t.reason===void 0?``:t.reason,this[d]=t.wasClean===void 0?!1:t.wasClean}get code(){return this[i]}get reason(){return this[c]}get wasClean(){return this[d]}};Object.defineProperty(p.prototype,`code`,{enumerable:!0}),Object.defineProperty(p.prototype,`reason`,{enumerable:!0}),Object.defineProperty(p.prototype,`wasClean`,{enumerable:!0});var m=class extends f{constructor(e,t={}){super(e),this[o]=t.error===void 0?null:t.error,this[s]=t.message===void 0?``:t.message}get error(){return this[o]}get message(){return this[s]}};Object.defineProperty(m.prototype,`error`,{enumerable:!0}),Object.defineProperty(m.prototype,`message`,{enumerable:!0});var h=class extends f{constructor(e,t={}){super(e),this[a]=t.data===void 0?null:t.data}get data(){return this[a]}};Object.defineProperty(h.prototype,`data`,{enumerable:!0}),t.exports={CloseEvent:p,ErrorEvent:m,Event:f,EventTarget:{addEventListener(e,t,i={}){for(let a of this.listeners(e))if(!i[n]&&a[r]===t&&!a[n])return;let a;if(e===`message`)a=function(e,n){let r=new h(`message`,{data:n?e:e.toString()});r[l]=this,g(t,this,r)};else if(e===`close`)a=function(e,n){let r=new p(`close`,{code:e,reason:n.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});r[l]=this,g(t,this,r)};else if(e===`error`)a=function(e){let n=new m(`error`,{error:e,message:e.message});n[l]=this,g(t,this,n)};else if(e===`open`)a=function(){let e=new f(`open`);e[l]=this,g(t,this,e)};else return;a[n]=!!i[n],a[r]=t,i.once?this.once(e,a):this.on(e,a)},removeEventListener(e,t){for(let i of this.listeners(e))if(i[r]===t&&!i[n]){this.removeListener(e,i);break}}},MessageEvent:h};function g(e,t,n){typeof e==`object`&&e.handleEvent?e.handleEvent.call(e,n):e.call(t,n)}})),tt=n(((e,t)=>{let{tokenChars:n}=Ze();function r(e,t,n){e[t]===void 0?e[t]=[n]:e[t].push(n)}function i(e){let t=Object.create(null),i=Object.create(null),a=!1,o=!1,s=!1,c,l,u=-1,d=-1,f=-1,p=0;for(;p<e.length;p++)if(d=e.charCodeAt(p),c===void 0)if(f===-1&&n[d]===1)u===-1&&(u=p);else if(p!==0&&(d===32||d===9))f===-1&&u!==-1&&(f=p);else if(d===59||d===44){if(u===-1)throw SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p);let n=e.slice(u,f);d===44?(r(t,n,i),i=Object.create(null)):c=n,u=f=-1}else throw SyntaxError(`Unexpected character at index ${p}`);else if(l===void 0)if(f===-1&&n[d]===1)u===-1&&(u=p);else if(d===32||d===9)f===-1&&u!==-1&&(f=p);else if(d===59||d===44){if(u===-1)throw SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p),r(i,e.slice(u,f),!0),d===44&&(r(t,c,i),i=Object.create(null),c=void 0),u=f=-1}else if(d===61&&u!==-1&&f===-1)l=e.slice(u,p),u=f=-1;else throw SyntaxError(`Unexpected character at index ${p}`);else if(o){if(n[d]!==1)throw SyntaxError(`Unexpected character at index ${p}`);u===-1?u=p:a||=!0,o=!1}else if(s)if(n[d]===1)u===-1&&(u=p);else if(d===34&&u!==-1)s=!1,f=p;else if(d===92)o=!0;else throw SyntaxError(`Unexpected character at index ${p}`);else if(d===34&&e.charCodeAt(p-1)===61)s=!0;else if(f===-1&&n[d]===1)u===-1&&(u=p);else if(u!==-1&&(d===32||d===9))f===-1&&(f=p);else if(d===59||d===44){if(u===-1)throw SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p);let n=e.slice(u,f);a&&=(n=n.replace(/\\/g,``),!1),r(i,l,n),d===44&&(r(t,c,i),i=Object.create(null),c=void 0),l=void 0,u=f=-1}else throw SyntaxError(`Unexpected character at index ${p}`);if(u===-1||s||d===32||d===9)throw SyntaxError(`Unexpected end of input`);f===-1&&(f=p);let m=e.slice(u,f);return c===void 0?r(t,m,i):(l===void 0?r(i,m,!0):a?r(i,l,m.replace(/\\/g,``)):r(i,l,m),r(t,c,i)),t}function a(e){return Object.keys(e).map(t=>{let n=e[t];return Array.isArray(n)||(n=[n]),n.map(e=>[t].concat(Object.keys(e).map(t=>{let n=e[t];return Array.isArray(n)||(n=[n]),n.map(e=>e===!0?t:`${t}=${e}`).join(`; `)})).join(`; `)).join(`, `)}).join(`, `)}t.exports={format:a,parse:i}})),nt=n(((t,n)=>{let r=e(`events`),i=e(`https`),a=e(`http`),o=e(`net`),s=e(`tls`),{randomBytes:c,createHash:l}=e(`crypto`),{Duplex:u,Readable:d}=e(`stream`),{URL:f}=e(`url`),p=Xe(),m=Qe(),h=$e(),{isBlob:g}=Ze(),{BINARY_TYPES:_,CLOSE_TIMEOUT:v,EMPTY_BUFFER:y,GUID:b,kForOnEventAttribute:x,kListener:S,kStatusCode:C,kWebSocket:w,NOOP:T}=qe(),{EventTarget:{addEventListener:E,removeEventListener:D}}=et(),{format:O,parse:k}=tt(),{toBuffer:A}=Je(),j=Symbol(`kAborted`),M=[8,13],N=[`CONNECTING`,`OPEN`,`CLOSING`,`CLOSED`],ee=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;var P=class e extends r{constructor(t,n,r){super(),this._binaryType=_[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=y,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol=``,this._readyState=e.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,t===null?(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0):(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,n===void 0?n=[]:Array.isArray(n)||(typeof n==`object`&&n?(r=n,n=[]):n=[n]),te(this,t,n,r))}get binaryType(){return this._binaryType}set binaryType(e){_.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(t,n,r){let i=new m({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),a=new h(t,this._extensions,r.generateMask);this._receiver=i,this._sender=a,this._socket=t,i[w]=this,a[w]=this,t[w]=this,i.on(`conclude`,R),i.on(`drain`,z),i.on(`error`,ie),i.on(`message`,oe),i.on(`ping`,se),i.on(`pong`,ce),a.onerror=ue,t.setTimeout&&t.setTimeout(0),t.setNoDelay&&t.setNoDelay(),n.length>0&&t.unshift(n),t.on(`close`,fe),t.on(`data`,pe),t.on(`end`,me),t.on(`error`,he),this._readyState=e.OPEN,this.emit(`open`)}emitClose(){if(!this._socket){this._readyState=e.CLOSED,this.emit(`close`,this._closeCode,this._closeMessage);return}this._extensions[p.extensionName]&&this._extensions[p.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=e.CLOSED,this.emit(`close`,this._closeCode,this._closeMessage)}close(t,n){if(this.readyState!==e.CLOSED){if(this.readyState===e.CONNECTING){I(this,this._req,`WebSocket was closed before the connection was established`);return}if(this.readyState===e.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=e.CLOSING,this._sender.close(t,n,!this._isServer,e=>{e||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),de(this)}}pause(){this.readyState===e.CONNECTING||this.readyState===e.CLOSED||(this._paused=!0,this._socket.pause())}ping(t,n,r){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof t==`function`?(r=t,t=n=void 0):typeof n==`function`&&(r=n,n=void 0),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){L(this,t,r);return}n===void 0&&(n=!this._isServer),this._sender.ping(t||y,n,r)}pong(t,n,r){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof t==`function`?(r=t,t=n=void 0):typeof n==`function`&&(r=n,n=void 0),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){L(this,t,r);return}n===void 0&&(n=!this._isServer),this._sender.pong(t||y,n,r)}resume(){this.readyState===e.CONNECTING||this.readyState===e.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(t,n,r){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof n==`function`&&(r=n,n={}),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){L(this,t,r);return}let i={binary:typeof t!=`string`,mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[p.extensionName]||(i.compress=!1),this._sender.send(t||y,i,r)}terminate(){if(this.readyState!==e.CLOSED){if(this.readyState===e.CONNECTING){I(this,this._req,`WebSocket was closed before the connection was established`);return}this._socket&&(this._readyState=e.CLOSING,this._socket.destroy())}}};Object.defineProperty(P,`CONNECTING`,{enumerable:!0,value:N.indexOf(`CONNECTING`)}),Object.defineProperty(P.prototype,`CONNECTING`,{enumerable:!0,value:N.indexOf(`CONNECTING`)}),Object.defineProperty(P,`OPEN`,{enumerable:!0,value:N.indexOf(`OPEN`)}),Object.defineProperty(P.prototype,`OPEN`,{enumerable:!0,value:N.indexOf(`OPEN`)}),Object.defineProperty(P,`CLOSING`,{enumerable:!0,value:N.indexOf(`CLOSING`)}),Object.defineProperty(P.prototype,`CLOSING`,{enumerable:!0,value:N.indexOf(`CLOSING`)}),Object.defineProperty(P,`CLOSED`,{enumerable:!0,value:N.indexOf(`CLOSED`)}),Object.defineProperty(P.prototype,`CLOSED`,{enumerable:!0,value:N.indexOf(`CLOSED`)}),[`binaryType`,`bufferedAmount`,`extensions`,`isPaused`,`protocol`,`readyState`,`url`].forEach(e=>{Object.defineProperty(P.prototype,e,{enumerable:!0})}),[`open`,`error`,`close`,`message`].forEach(e=>{Object.defineProperty(P.prototype,`on${e}`,{enumerable:!0,get(){for(let t of this.listeners(e))if(t[x])return t[S];return null},set(t){for(let t of this.listeners(e))if(t[x]){this.removeListener(e,t);break}typeof t==`function`&&this.addEventListener(e,t,{[x]:!0})}})}),P.prototype.addEventListener=E,P.prototype.removeEventListener=D,n.exports=P;function te(e,t,n,r){let o={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:v,protocolVersion:M[1],maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...r,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:`GET`,host:void 0,path:void 0,port:void 0};if(e._autoPong=o.autoPong,e._closeTimeout=o.closeTimeout,!M.includes(o.protocolVersion))throw RangeError(`Unsupported protocol version: ${o.protocolVersion} (supported versions: ${M.join(`, `)})`);let s;if(t instanceof f)s=t;else try{s=new f(t)}catch{throw SyntaxError(`Invalid URL: ${t}`)}s.protocol===`http:`?s.protocol=`ws:`:s.protocol===`https:`&&(s.protocol=`wss:`),e._url=s.href;let u=s.protocol===`wss:`,d=s.protocol===`ws+unix:`,m;if(s.protocol!==`ws:`&&!u&&!d?m=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:d&&!s.pathname?m=`The URL's pathname is empty`:s.hash&&(m=`The URL contains a fragment identifier`),m){let t=SyntaxError(m);if(e._redirects===0)throw t;F(e,t);return}let h=u?443:80,g=c(16).toString(`base64`),_=u?i.request:a.request,y=new Set,x;if(o.createConnection=o.createConnection||(u?re:ne),o.defaultPort=o.defaultPort||h,o.port=s.port||h,o.host=s.hostname.startsWith(`[`)?s.hostname.slice(1,-1):s.hostname,o.headers={...o.headers,"Sec-WebSocket-Version":o.protocolVersion,"Sec-WebSocket-Key":g,Connection:`Upgrade`,Upgrade:`websocket`},o.path=s.pathname+s.search,o.timeout=o.handshakeTimeout,o.perMessageDeflate&&(x=new p({...o.perMessageDeflate,isServer:!1,maxPayload:o.maxPayload}),o.headers[`Sec-WebSocket-Extensions`]=O({[p.extensionName]:x.offer()})),n.length){for(let e of n){if(typeof e!=`string`||!ee.test(e)||y.has(e))throw SyntaxError(`An invalid or duplicated subprotocol was specified`);y.add(e)}o.headers[`Sec-WebSocket-Protocol`]=n.join(`,`)}if(o.origin&&(o.protocolVersion<13?o.headers[`Sec-WebSocket-Origin`]=o.origin:o.headers.Origin=o.origin),(s.username||s.password)&&(o.auth=`${s.username}:${s.password}`),d){let e=o.path.split(`:`);o.socketPath=e[0],o.path=e[1]}let S;if(o.followRedirects){if(e._redirects===0){e._originalIpc=d,e._originalSecure=u,e._originalHostOrSocketPath=d?o.socketPath:s.host;let t=r&&r.headers;if(r={...r,headers:{}},t)for(let[e,n]of Object.entries(t))r.headers[e.toLowerCase()]=n}else if(e.listenerCount(`redirect`)===0){let t=d?e._originalIpc?o.socketPath===e._originalHostOrSocketPath:!1:e._originalIpc?!1:s.host===e._originalHostOrSocketPath;(!t||e._originalSecure&&!u)&&(delete o.headers.authorization,delete o.headers.cookie,t||delete o.headers.host,o.auth=void 0)}o.auth&&!r.headers.authorization&&(r.headers.authorization=`Basic `+Buffer.from(o.auth).toString(`base64`)),S=e._req=_(o),e._redirects&&e.emit(`redirect`,e.url,S)}else S=e._req=_(o);o.timeout&&S.on(`timeout`,()=>{I(e,S,`Opening handshake has timed out`)}),S.on(`error`,t=>{S===null||S[j]||(S=e._req=null,F(e,t))}),S.on(`response`,i=>{let a=i.headers.location,s=i.statusCode;if(a&&o.followRedirects&&s>=300&&s<400){if(++e._redirects>o.maxRedirects){I(e,S,`Maximum redirects exceeded`);return}S.abort();let i;try{i=new f(a,t)}catch{F(e,SyntaxError(`Invalid URL: ${a}`));return}te(e,i,n,r)}else e.emit(`unexpected-response`,S,i)||I(e,S,`Unexpected server response: ${i.statusCode}`)}),S.on(`upgrade`,(t,n,r)=>{if(e.emit(`upgrade`,t),e.readyState!==P.CONNECTING)return;S=e._req=null;let i=t.headers.upgrade;if(i===void 0||i.toLowerCase()!==`websocket`){I(e,n,`Invalid Upgrade header`);return}let a=l(`sha1`).update(g+b).digest(`base64`);if(t.headers[`sec-websocket-accept`]!==a){I(e,n,`Invalid Sec-WebSocket-Accept header`);return}let s=t.headers[`sec-websocket-protocol`],c;if(s===void 0?y.size&&(c=`Server sent no subprotocol`):y.size?y.has(s)||(c=`Server sent an invalid subprotocol`):c=`Server sent a subprotocol but none was requested`,c){I(e,n,c);return}s&&(e._protocol=s);let u=t.headers[`sec-websocket-extensions`];if(u!==void 0){if(!x){I(e,n,`Server sent a Sec-WebSocket-Extensions header but no extension was requested`);return}let t;try{t=k(u)}catch{I(e,n,`Invalid Sec-WebSocket-Extensions header`);return}let r=Object.keys(t);if(r.length!==1||r[0]!==p.extensionName){I(e,n,`Server indicated an extension that was not requested`);return}try{x.accept(t[p.extensionName])}catch{I(e,n,`Invalid Sec-WebSocket-Extensions header`);return}e._extensions[p.extensionName]=x}e.setSocket(n,r,{allowSynchronousEvents:o.allowSynchronousEvents,generateMask:o.generateMask,maxPayload:o.maxPayload,skipUTF8Validation:o.skipUTF8Validation})}),o.finishRequest?o.finishRequest(S,e):S.end()}function F(e,t){e._readyState=P.CLOSING,e._errorEmitted=!0,e.emit(`error`,t),e.emitClose()}function ne(e){return e.path=e.socketPath,o.connect(e)}function re(e){return e.path=void 0,!e.servername&&e.servername!==``&&(e.servername=o.isIP(e.host)?``:e.host),s.connect(e)}function I(e,t,n){e._readyState=P.CLOSING;let r=Error(n);Error.captureStackTrace(r,I),t.setHeader?(t[j]=!0,t.abort(),t.socket&&!t.socket.destroyed&&t.socket.destroy(),process.nextTick(F,e,r)):(t.destroy(r),t.once(`error`,e.emit.bind(e,`error`)),t.once(`close`,e.emitClose.bind(e)))}function L(e,t,n){if(t){let n=g(t)?t.size:A(t).length;e._socket?e._sender._bufferedBytes+=n:e._bufferedAmount+=n}if(n){let t=Error(`WebSocket is not open: readyState ${e.readyState} (${N[e.readyState]})`);process.nextTick(n,t)}}function R(e,t){let n=this[w];n._closeFrameReceived=!0,n._closeMessage=t,n._closeCode=e,n._socket[w]!==void 0&&(n._socket.removeListener(`data`,pe),process.nextTick(le,n._socket),e===1005?n.close():n.close(e,t))}function z(){let e=this[w];e.isPaused||e._socket.resume()}function ie(e){let t=this[w];t._socket[w]!==void 0&&(t._socket.removeListener(`data`,pe),process.nextTick(le,t._socket),t.close(e[C])),t._errorEmitted||(t._errorEmitted=!0,t.emit(`error`,e))}function ae(){this[w].emitClose()}function oe(e,t){this[w].emit(`message`,e,t)}function se(e){let t=this[w];t._autoPong&&t.pong(e,!this._isServer,T),t.emit(`ping`,e)}function ce(e){this[w].emit(`pong`,e)}function le(e){e.resume()}function ue(e){let t=this[w];t.readyState!==P.CLOSED&&(t.readyState===P.OPEN&&(t._readyState=P.CLOSING,de(t)),this._socket.end(),t._errorEmitted||(t._errorEmitted=!0,t.emit(`error`,e)))}function de(e){e._closeTimer=setTimeout(e._socket.destroy.bind(e._socket),e._closeTimeout)}function fe(){let e=this[w];if(this.removeListener(`close`,fe),this.removeListener(`data`,pe),this.removeListener(`end`,me),e._readyState=P.CLOSING,!this._readableState.endEmitted&&!e._closeFrameReceived&&!e._receiver._writableState.errorEmitted&&this._readableState.length!==0){let t=this.read(this._readableState.length);e._receiver.write(t)}e._receiver.end(),this[w]=void 0,clearTimeout(e._closeTimer),e._receiver._writableState.finished||e._receiver._writableState.errorEmitted?e.emitClose():(e._receiver.on(`error`,ae),e._receiver.on(`finish`,ae))}function pe(e){this[w]._receiver.write(e)||this.pause()}function me(){let e=this[w];e._readyState=P.CLOSING,e._receiver.end(),this.end()}function he(){let e=this[w];this.removeListener(`error`,he),this.on(`error`,T),e&&(e._readyState=P.CLOSING,this.destroy())}})),rt=n(((t,n)=>{nt();let{Duplex:r}=e(`stream`);function i(e){e.emit(`close`)}function a(){!this.destroyed&&this._writableState.finished&&this.destroy()}function o(e){this.removeListener(`error`,o),this.destroy(),this.listenerCount(`error`)===0&&this.emit(`error`,e)}function s(e,t){let n=!0,s=new r({...t,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return e.on(`message`,function(t,n){let r=!n&&s._readableState.objectMode?t.toString():t;s.push(r)||e.pause()}),e.once(`error`,function(e){s.destroyed||(n=!1,s.destroy(e))}),e.once(`close`,function(){s.destroyed||s.push(null)}),s._destroy=function(t,r){if(e.readyState===e.CLOSED){r(t),process.nextTick(i,s);return}let a=!1;e.once(`error`,function(e){a=!0,r(e)}),e.once(`close`,function(){a||r(t),process.nextTick(i,s)}),n&&e.terminate()},s._final=function(t){if(e.readyState===e.CONNECTING){e.once(`open`,function(){s._final(t)});return}e._socket!==null&&(e._socket._writableState.finished?(t(),s._readableState.endEmitted&&s.destroy()):(e._socket.once(`finish`,function(){t()}),e.close()))},s._read=function(){e.isPaused&&e.resume()},s._write=function(t,n,r){if(e.readyState===e.CONNECTING){e.once(`open`,function(){s._write(t,n,r)});return}e.send(t,r)},s.on(`end`,a),s.on(`error`,o),s}n.exports=s})),it=n(((e,t)=>{let{tokenChars:n}=Ze();function r(e){let t=new Set,r=-1,i=-1,a=0;for(;a<e.length;a++){let o=e.charCodeAt(a);if(i===-1&&n[o]===1)r===-1&&(r=a);else if(a!==0&&(o===32||o===9))i===-1&&r!==-1&&(i=a);else if(o===44){if(r===-1)throw SyntaxError(`Unexpected character at index ${a}`);i===-1&&(i=a);let n=e.slice(r,i);if(t.has(n))throw SyntaxError(`The "${n}" subprotocol is duplicated`);t.add(n),r=i=-1}else throw SyntaxError(`Unexpected character at index ${a}`)}if(r===-1||i!==-1)throw SyntaxError(`Unexpected end of input`);let o=e.slice(r,a);if(t.has(o))throw SyntaxError(`The "${o}" subprotocol is duplicated`);return t.add(o),t}t.exports={parse:r}})),at=n(((t,n)=>{let r=e(`events`),i=e(`http`),{Duplex:a}=e(`stream`),{createHash:o}=e(`crypto`),s=tt(),c=Xe(),l=it(),u=nt(),{CLOSE_TIMEOUT:d,GUID:f,kWebSocket:p}=qe(),m=/^[+/0-9A-Za-z]{22}==$/;n.exports=class extends r{constructor(e,t){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:d,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:u,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw TypeError(`One and only one of the "port", "server", or "noServer" options must be specified`);if(e.port==null?e.server&&(this._server=e.server):(this._server=i.createServer((e,t)=>{let n=i.STATUS_CODES[426];t.writeHead(426,{"Content-Length":n.length,"Content-Type":`text/plain`}),t.end(n)}),this._server.listen(e.port,e.host,e.backlog,t)),this._server){let e=this.emit.bind(this,`connection`);this._removeListeners=h(this._server,{listening:this.emit.bind(this,`listening`),error:this.emit.bind(this,`error`),upgrade:(t,n,r)=>{this.handleUpgrade(t,n,r,e)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=0}address(){if(this.options.noServer)throw Error(`The server is operating in "noServer" mode`);return this._server?this._server.address():null}close(e){if(this._state===2){e&&this.once(`close`,()=>{e(Error(`The server is not running`))}),process.nextTick(g,this);return}if(e&&this.once(`close`,e),this._state!==1)if(this._state=1,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients&&this.clients.size?this._shouldEmitClose=!0:process.nextTick(g,this);else{let e=this._server;this._removeListeners(),this._removeListeners=this._server=null,e.close(()=>{g(this)})}}shouldHandle(e){if(this.options.path){let t=e.url.indexOf(`?`);if((t===-1?e.url:e.url.slice(0,t))!==this.options.path)return!1}return!0}handleUpgrade(e,t,n,r){t.on(`error`,_);let i=e.headers[`sec-websocket-key`],a=e.headers.upgrade,o=+e.headers[`sec-websocket-version`];if(e.method!==`GET`){y(this,e,t,405,`Invalid HTTP method`);return}if(a===void 0||a.toLowerCase()!==`websocket`){y(this,e,t,400,`Invalid Upgrade header`);return}if(i===void 0||!m.test(i)){y(this,e,t,400,`Missing or invalid Sec-WebSocket-Key header`);return}if(o!==13&&o!==8){y(this,e,t,400,`Missing or invalid Sec-WebSocket-Version header`,{"Sec-WebSocket-Version":`13, 8`});return}if(!this.shouldHandle(e)){v(t,400);return}let u=e.headers[`sec-websocket-protocol`],d=new Set;if(u!==void 0)try{d=l.parse(u)}catch{y(this,e,t,400,`Invalid Sec-WebSocket-Protocol header`);return}let f=e.headers[`sec-websocket-extensions`],p={};if(this.options.perMessageDeflate&&f!==void 0){let n=new c({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let e=s.parse(f);e[c.extensionName]&&(n.accept(e[c.extensionName]),p[c.extensionName]=n)}catch{y(this,e,t,400,`Invalid or unacceptable Sec-WebSocket-Extensions header`);return}}if(this.options.verifyClient){let a={origin:e.headers[`${o===8?`sec-websocket-origin`:`origin`}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(a,(a,o,s,c)=>{if(!a)return v(t,o||401,s,c);this.completeUpgrade(p,i,d,e,t,n,r)});return}if(!this.options.verifyClient(a))return v(t,401)}this.completeUpgrade(p,i,d,e,t,n,r)}completeUpgrade(e,t,n,r,i,a,l){if(!i.readable||!i.writable)return i.destroy();if(i[p])throw Error(`server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration`);if(this._state>0)return v(i,503);let u=[`HTTP/1.1 101 Switching Protocols`,`Upgrade: websocket`,`Connection: Upgrade`,`Sec-WebSocket-Accept: ${o(`sha1`).update(t+f).digest(`base64`)}`],d=new this.options.WebSocket(null,void 0,this.options);if(n.size){let e=this.options.handleProtocols?this.options.handleProtocols(n,r):n.values().next().value;e&&(u.push(`Sec-WebSocket-Protocol: ${e}`),d._protocol=e)}if(e[c.extensionName]){let t=e[c.extensionName].params,n=s.format({[c.extensionName]:[t]});u.push(`Sec-WebSocket-Extensions: ${n}`),d._extensions=e}this.emit(`headers`,u,r),i.write(u.concat(`\r
22
+ `).join(`\r
23
+ `)),i.removeListener(`error`,_),d.setSocket(i,a,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(d),d.on(`close`,()=>{this.clients.delete(d),this._shouldEmitClose&&!this.clients.size&&process.nextTick(g,this)})),l(d,r)}};function h(e,t){for(let n of Object.keys(t))e.on(n,t[n]);return function(){for(let n of Object.keys(t))e.removeListener(n,t[n])}}function g(e){e._state=2,e.emit(`close`)}function _(){this.destroy()}function v(e,t,n,r){n||=i.STATUS_CODES[t],r={Connection:`close`,"Content-Type":`text/html`,"Content-Length":Buffer.byteLength(n),...r},e.once(`finish`,e.destroy),e.end(`HTTP/1.1 ${t} ${i.STATUS_CODES[t]}\r\n`+Object.keys(r).map(e=>`${e}: ${r[e]}`).join(`\r
24
+ `)+`\r
25
+ \r
26
+ `+n)}function y(e,t,n,r,i,a){if(e.listenerCount(`wsClientError`)){let r=Error(i);Error.captureStackTrace(r,y),e.emit(`wsClientError`,r,n,t)}else v(n,r,i,a)}}));rt(),tt(),Xe(),Qe(),$e(),it();var ot=t(nt(),1);at();var st=t(m(),1),ct=Ke();function lt(){return{geminiUrl:void 0,vertexUrl:void 0}}function ut(e,t,n,r){if(!e?.baseUrl){let e=lt();return t?e.vertexUrl??n:e.geminiUrl??r}return e.baseUrl}
27
+ /**
28
+ * @license
29
+ * Copyright 2025 Google LLC
30
+ * SPDX-License-Identifier: Apache-2.0
31
+ */
32
+ var dt=class{};function B(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 V(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];V(a,t.slice(r+1),n[e])}else for(let e of i)V(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];V(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 if(r===`_self`&&typeof n==`object`&&n&&!Array.isArray(n)){let t=n;Object.assign(e,t)}else e[r]=n}function H(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=>H(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 ft(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)}pt(e,t,i,0,a)}}function pt(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])pt(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);V(t,a,i)}for(let e of a)delete t[e]}}else{let o=e;a in o&&pt(o[a],t,n,r+1,i)}}
33
+ /**
34
+ * @license
35
+ * Copyright 2025 Google LLC
36
+ * SPDX-License-Identifier: Apache-2.0
37
+ */
38
+ function mt(e){if(typeof e!=`string`)throw Error(`fromImageBytes must be a string`);return e}
39
+ /**
40
+ * @license
41
+ * Copyright 2025 Google LLC
42
+ * SPDX-License-Identifier: Apache-2.0
43
+ */
44
+ function ht(e){let t={},n=H(e,[`operationName`]);n!=null&&V(t,[`operationName`],n);let r=H(e,[`resourceName`]);return r!=null&&V(t,[`_url`,`resourceName`],r),t}function gt(e){let t={},n=H(e,[`name`]);n!=null&&V(t,[`name`],n);let r=H(e,[`metadata`]);r!=null&&V(t,[`metadata`],r);let i=H(e,[`done`]);i!=null&&V(t,[`done`],i);let a=H(e,[`error`]);a!=null&&V(t,[`error`],a);let o=H(e,[`response`,`generateVideoResponse`]);return o!=null&&V(t,[`response`],vt(o)),t}function _t(e){let t={},n=H(e,[`name`]);n!=null&&V(t,[`name`],n);let r=H(e,[`metadata`]);r!=null&&V(t,[`metadata`],r);let i=H(e,[`done`]);i!=null&&V(t,[`done`],i);let a=H(e,[`error`]);a!=null&&V(t,[`error`],a);let o=H(e,[`response`]);return o!=null&&V(t,[`response`],yt(o)),t}function vt(e){let t={},n=H(e,[`generatedSamples`]);if(n!=null){let e=n;Array.isArray(e)&&(e=e.map(e=>bt(e))),V(t,[`generatedVideos`],e)}let r=H(e,[`raiMediaFilteredCount`]);r!=null&&V(t,[`raiMediaFilteredCount`],r);let i=H(e,[`raiMediaFilteredReasons`]);return i!=null&&V(t,[`raiMediaFilteredReasons`],i),t}function yt(e){let t={},n=H(e,[`videos`]);if(n!=null){let e=n;Array.isArray(e)&&(e=e.map(e=>xt(e))),V(t,[`generatedVideos`],e)}let r=H(e,[`raiMediaFilteredCount`]);r!=null&&V(t,[`raiMediaFilteredCount`],r);let i=H(e,[`raiMediaFilteredReasons`]);return i!=null&&V(t,[`raiMediaFilteredReasons`],i),t}function bt(e){let t={},n=H(e,[`video`]);return n!=null&&V(t,[`video`],Ot(n)),t}function xt(e){let t={},n=H(e,[`_self`]);return n!=null&&V(t,[`video`],kt(n)),t}function St(e){let t={},n=H(e,[`operationName`]);return n!=null&&V(t,[`_url`,`operationName`],n),t}function Ct(e){let t={},n=H(e,[`operationName`]);return n!=null&&V(t,[`_url`,`operationName`],n),t}function wt(e){let t={},n=H(e,[`name`]);n!=null&&V(t,[`name`],n);let r=H(e,[`metadata`]);r!=null&&V(t,[`metadata`],r);let i=H(e,[`done`]);i!=null&&V(t,[`done`],i);let a=H(e,[`error`]);a!=null&&V(t,[`error`],a);let o=H(e,[`response`]);return o!=null&&V(t,[`response`],Tt(o)),t}function Tt(e){let t={},n=H(e,[`sdkHttpResponse`]);n!=null&&V(t,[`sdkHttpResponse`],n);let r=H(e,[`parent`]);r!=null&&V(t,[`parent`],r);let i=H(e,[`documentName`]);return i!=null&&V(t,[`documentName`],i),t}function Et(e){let t={},n=H(e,[`name`]);n!=null&&V(t,[`name`],n);let r=H(e,[`metadata`]);r!=null&&V(t,[`metadata`],r);let i=H(e,[`done`]);i!=null&&V(t,[`done`],i);let a=H(e,[`error`]);a!=null&&V(t,[`error`],a);let o=H(e,[`response`]);return o!=null&&V(t,[`response`],Dt(o)),t}function Dt(e){let t={},n=H(e,[`sdkHttpResponse`]);n!=null&&V(t,[`sdkHttpResponse`],n);let r=H(e,[`parent`]);r!=null&&V(t,[`parent`],r);let i=H(e,[`documentName`]);return i!=null&&V(t,[`documentName`],i),t}function Ot(e){let t={},n=H(e,[`uri`]);n!=null&&V(t,[`uri`],n);let r=H(e,[`encodedVideo`]);r!=null&&V(t,[`videoBytes`],mt(r));let i=H(e,[`encoding`]);return i!=null&&V(t,[`mimeType`],i),t}function kt(e){let t={},n=H(e,[`gcsUri`]);n!=null&&V(t,[`uri`],n);let r=H(e,[`bytesBase64Encoded`]);r!=null&&V(t,[`videoBytes`],mt(r));let i=H(e,[`mimeType`]);return i!=null&&V(t,[`mimeType`],i),t}
45
+ /**
46
+ * @license
47
+ * Copyright 2025 Google LLC
48
+ * SPDX-License-Identifier: Apache-2.0
49
+ */
50
+ var At;(function(e){e.LANGUAGE_UNSPECIFIED=`LANGUAGE_UNSPECIFIED`,e.PYTHON=`PYTHON`})(At||={});var jt;(function(e){e.OUTCOME_UNSPECIFIED=`OUTCOME_UNSPECIFIED`,e.OUTCOME_OK=`OUTCOME_OK`,e.OUTCOME_FAILED=`OUTCOME_FAILED`,e.OUTCOME_DEADLINE_EXCEEDED=`OUTCOME_DEADLINE_EXCEEDED`})(jt||={});var Mt;(function(e){e.SCHEDULING_UNSPECIFIED=`SCHEDULING_UNSPECIFIED`,e.SILENT=`SILENT`,e.WHEN_IDLE=`WHEN_IDLE`,e.INTERRUPT=`INTERRUPT`})(Mt||={});var Nt;(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`})(Nt||={});var Pt;(function(e){e.ENVIRONMENT_UNSPECIFIED=`ENVIRONMENT_UNSPECIFIED`,e.ENVIRONMENT_BROWSER=`ENVIRONMENT_BROWSER`})(Pt||={});var Ft;(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`})(Ft||={});var It;(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`})(It||={});var Lt;(function(e){e.API_SPEC_UNSPECIFIED=`API_SPEC_UNSPECIFIED`,e.SIMPLE_SEARCH=`SIMPLE_SEARCH`,e.ELASTIC_SEARCH=`ELASTIC_SEARCH`})(Lt||={});var Rt;(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`})(Rt||={});var zt;(function(e){e.UNSPECIFIED=`UNSPECIFIED`,e.BLOCKING=`BLOCKING`,e.NON_BLOCKING=`NON_BLOCKING`})(zt||={});var Bt;(function(e){e.MODE_UNSPECIFIED=`MODE_UNSPECIFIED`,e.MODE_DYNAMIC=`MODE_DYNAMIC`})(Bt||={});var Vt;(function(e){e.MODE_UNSPECIFIED=`MODE_UNSPECIFIED`,e.AUTO=`AUTO`,e.ANY=`ANY`,e.NONE=`NONE`,e.VALIDATED=`VALIDATED`})(Vt||={});var Ht;(function(e){e.THINKING_LEVEL_UNSPECIFIED=`THINKING_LEVEL_UNSPECIFIED`,e.MINIMAL=`MINIMAL`,e.LOW=`LOW`,e.MEDIUM=`MEDIUM`,e.HIGH=`HIGH`})(Ht||={});var Ut;(function(e){e.DONT_ALLOW=`DONT_ALLOW`,e.ALLOW_ADULT=`ALLOW_ADULT`,e.ALLOW_ALL=`ALLOW_ALL`})(Ut||={});var Wt;(function(e){e.PROMINENT_PEOPLE_UNSPECIFIED=`PROMINENT_PEOPLE_UNSPECIFIED`,e.ALLOW_PROMINENT_PEOPLE=`ALLOW_PROMINENT_PEOPLE`,e.BLOCK_PROMINENT_PEOPLE=`BLOCK_PROMINENT_PEOPLE`})(Wt||={});var Gt;(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`})(Gt||={});var Kt;(function(e){e.HARM_BLOCK_METHOD_UNSPECIFIED=`HARM_BLOCK_METHOD_UNSPECIFIED`,e.SEVERITY=`SEVERITY`,e.PROBABILITY=`PROBABILITY`})(Kt||={});var qt;(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`})(qt||={});var U;(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`})(U||={});var Jt;(function(e){e.HARM_PROBABILITY_UNSPECIFIED=`HARM_PROBABILITY_UNSPECIFIED`,e.NEGLIGIBLE=`NEGLIGIBLE`,e.LOW=`LOW`,e.MEDIUM=`MEDIUM`,e.HIGH=`HIGH`})(Jt||={});var Yt;(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`})(Yt||={});var Xt;(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`})(Xt||={});var Zt;(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`})(Zt||={});var Qt;(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`})(Qt||={});var $t;(function(e){e.MODALITY_UNSPECIFIED=`MODALITY_UNSPECIFIED`,e.TEXT=`TEXT`,e.IMAGE=`IMAGE`,e.AUDIO=`AUDIO`,e.VIDEO=`VIDEO`})($t||={});var en;(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`})(en||={});var tn;(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`})(tn||={});var nn;(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`})(nn||={});var rn;(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`})(rn||={});var an;(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`})(an||={});var on;(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`})(on||={});var sn;(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`})(sn||={});var cn;(function(e){e.PAIRWISE_CHOICE_UNSPECIFIED=`PAIRWISE_CHOICE_UNSPECIFIED`,e.BASELINE=`BASELINE`,e.CANDIDATE=`CANDIDATE`,e.TIE=`TIE`})(cn||={});var ln;(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`})(ln||={});var un;(function(e){e.STATE_UNSPECIFIED=`STATE_UNSPECIFIED`,e.STATE_PENDING=`STATE_PENDING`,e.STATE_ACTIVE=`STATE_ACTIVE`,e.STATE_FAILED=`STATE_FAILED`})(un||={});var dn;(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`})(dn||={});var fn;(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`})(fn||={});var pn;(function(e){e.COLLECTION=`COLLECTION`})(pn||={});var mn;(function(e){e.UNSPECIFIED=`unspecified`,e.FLEX=`flex`,e.STANDARD=`standard`,e.PRIORITY=`priority`})(mn||={});var hn;(function(e){e.FEATURE_SELECTION_PREFERENCE_UNSPECIFIED=`FEATURE_SELECTION_PREFERENCE_UNSPECIFIED`,e.PRIORITIZE_QUALITY=`PRIORITIZE_QUALITY`,e.BALANCED=`BALANCED`,e.PRIORITIZE_COST=`PRIORITIZE_COST`})(hn||={});var gn;(function(e){e.PREDICT=`PREDICT`,e.EMBED_CONTENT=`EMBED_CONTENT`})(gn||={});var _n;(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`})(_n||={});var vn;(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`})(vn||={});var yn;(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`})(yn||={});var bn;(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`})(bn||={});var xn;(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`})(xn||={});var Sn;(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`})(Sn||={});var Cn;(function(e){e.FOREGROUND=`FOREGROUND`,e.BACKGROUND=`BACKGROUND`,e.PROMPT=`PROMPT`,e.SEMANTIC=`SEMANTIC`,e.INTERACTIVE=`INTERACTIVE`})(Cn||={});var wn;(function(e){e.ASSET=`ASSET`,e.STYLE=`STYLE`})(wn||={});var Tn;(function(e){e.INSERT=`INSERT`,e.REMOVE=`REMOVE`,e.REMOVE_STATIC=`REMOVE_STATIC`,e.OUTPAINT=`OUTPAINT`})(Tn||={});var En;(function(e){e.OPTIMIZED=`OPTIMIZED`,e.LOSSLESS=`LOSSLESS`})(En||={});var Dn;(function(e){e.CROP=`CROP`,e.PAD=`PAD`})(Dn||={});var On;(function(e){e.SUPERVISED_FINE_TUNING=`SUPERVISED_FINE_TUNING`,e.PREFERENCE_TUNING=`PREFERENCE_TUNING`,e.DISTILLATION=`DISTILLATION`})(On||={});var kn;(function(e){e.STATE_UNSPECIFIED=`STATE_UNSPECIFIED`,e.PROCESSING=`PROCESSING`,e.ACTIVE=`ACTIVE`,e.FAILED=`FAILED`})(kn||={});var An;(function(e){e.SOURCE_UNSPECIFIED=`SOURCE_UNSPECIFIED`,e.UPLOADED=`UPLOADED`,e.GENERATED=`GENERATED`,e.REGISTERED=`REGISTERED`})(An||={});var jn;(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`})(jn||={});var Mn;(function(e){e.MODALITY_UNSPECIFIED=`MODALITY_UNSPECIFIED`,e.TEXT=`TEXT`,e.IMAGE=`IMAGE`,e.VIDEO=`VIDEO`,e.AUDIO=`AUDIO`,e.DOCUMENT=`DOCUMENT`})(Mn||={});var Nn;(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`})(Nn||={});var Pn;(function(e){e.TYPE_UNSPECIFIED=`TYPE_UNSPECIFIED`,e.ACTIVITY_START=`ACTIVITY_START`,e.ACTIVITY_END=`ACTIVITY_END`})(Pn||={});var Fn;(function(e){e.START_SENSITIVITY_UNSPECIFIED=`START_SENSITIVITY_UNSPECIFIED`,e.START_SENSITIVITY_HIGH=`START_SENSITIVITY_HIGH`,e.START_SENSITIVITY_LOW=`START_SENSITIVITY_LOW`})(Fn||={});var In;(function(e){e.END_SENSITIVITY_UNSPECIFIED=`END_SENSITIVITY_UNSPECIFIED`,e.END_SENSITIVITY_HIGH=`END_SENSITIVITY_HIGH`,e.END_SENSITIVITY_LOW=`END_SENSITIVITY_LOW`})(In||={});var Ln;(function(e){e.ACTIVITY_HANDLING_UNSPECIFIED=`ACTIVITY_HANDLING_UNSPECIFIED`,e.START_OF_ACTIVITY_INTERRUPTS=`START_OF_ACTIVITY_INTERRUPTS`,e.NO_INTERRUPTION=`NO_INTERRUPTION`})(Ln||={});var Rn;(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`})(Rn||={});var zn;(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`})(zn||={});var Bn;(function(e){e.MUSIC_GENERATION_MODE_UNSPECIFIED=`MUSIC_GENERATION_MODE_UNSPECIFIED`,e.QUALITY=`QUALITY`,e.DIVERSITY=`DIVERSITY`,e.VOCALIZATION=`VOCALIZATION`})(Bn||={});var Vn;(function(e){e.PLAYBACK_CONTROL_UNSPECIFIED=`PLAYBACK_CONTROL_UNSPECIFIED`,e.PLAY=`PLAY`,e.PAUSE=`PAUSE`,e.STOP=`STOP`,e.RESET_CONTEXT=`RESET_CONTEXT`})(Vn||={});var Hn=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()}},Un=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}},Wn=class{},Gn=class{},Kn=class{},qn=class{},Jn=class{},Yn=class{},Xn=class{},Zn=class{},Qn=class{},$n=class{},er=class e{_fromAPIResponse({apiResponse:t,_isVertexAI:n}){let r=new e,i,a=t;return i=n?_t(a):gt(a),Object.assign(r,i),r}},tr=class{},nr=class{},rr=class{},ir=class{},ar=class{},or=class{},sr=class{},cr=class e{_fromAPIResponse({apiResponse:t,_isVertexAI:n}){let r=new e,i=wt(t);return Object.assign(r,i),r}},lr=class{},ur=class{},dr=class{},fr=class{},pr=class{},mr=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}},hr=class{get audioChunk(){if(this.serverContent&&this.serverContent.audioChunks&&this.serverContent.audioChunks.length>0)return this.serverContent.audioChunks[0]}},gr=class e{_fromAPIResponse({apiResponse:t,_isVertexAI:n}){let r=new e,i=Et(t);return Object.assign(r,i),r}};
51
+ /**
52
+ * @license
53
+ * Copyright 2025 Google LLC
54
+ * SPDX-License-Identifier: Apache-2.0
55
+ */
56
+ function W(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 _r(e,t){let n=W(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 vr(e){return Array.isArray(e)?e.map(e=>yr(e)):[yr(e)]}function yr(e){if(typeof e==`object`&&e)return e;throw Error(`Could not parse input as Blob. Unsupported blob type: ${typeof e}`)}function br(e){let t=yr(e);if(t.mimeType&&t.mimeType.startsWith(`image/`))return t;throw Error(`Unsupported mime type: ${t.mimeType}`)}function xr(e){let t=yr(e);if(t.mimeType&&t.mimeType.startsWith(`audio/`))return t;throw Error(`Unsupported mime type: ${t.mimeType}`)}function Sr(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 Cr(e){if(e==null||Array.isArray(e)&&e.length===0)throw Error(`PartListUnion is required`);return Array.isArray(e)?e.map(e=>Sr(e)):[Sr(e)]}function wr(e){return typeof e==`object`&&!!e&&`parts`in e&&Array.isArray(e.parts)}function Tr(e){return typeof e==`object`&&!!e&&`functionCall`in e}function Er(e){return typeof e==`object`&&!!e&&`functionResponse`in e}function G(e){if(e==null)throw Error(`ContentUnion is required`);return wr(e)?e:{role:`user`,parts:Cr(e)}}function Dr(e,t){if(!t)return[];if(e.isVertexAI()&&Array.isArray(t))return t.flatMap(e=>{let t=G(e);return t.parts&&t.parts.length>0&&t.parts[0].text!==void 0?[t.parts[0].text]:[]});if(e.isVertexAI()){let e=G(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=>G(e)):[G(t)]}function K(e){if(e==null||Array.isArray(e)&&e.length===0)throw Error(`contents are required`);if(!Array.isArray(e)){if(Tr(e)||Er(e))throw Error(`To specify functionCall or functionResponse parts, please wrap them in a Content object, specifying the role for them`);return[G(e)]}let t=[],n=[],r=wr(e[0]);for(let i of e){let e=wr(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(Tr(i)||Er(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:Cr(n)}),t}function Or(e,t){e.includes(`null`)&&(t.nullable=!0);let n=e.filter(e=>e!==`null`);if(n.length===1)t.type=Object.values(Nt).includes(n[0].toUpperCase())?n[0].toUpperCase():Nt.TYPE_UNSPECIFIED;else{t.anyOf=[];for(let e of n)t.anyOf.push({type:Object.values(Nt).includes(e.toUpperCase())?e.toUpperCase():Nt.TYPE_UNSPECIFIED})}}function kr(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&&Or(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(Nt).includes(o.toUpperCase())?o.toUpperCase():Nt.TYPE_UNSPECIFIED}else if(n.includes(a))t[a]=kr(o);else if(r.includes(a)){let e=[];for(let n of o){if(n.type==`null`){t.nullable=!0;continue}e.push(kr(n))}t[a]=e}else if(i.includes(a)){let e={};for(let[t,n]of Object.entries(o))e[t]=kr(n);t[a]=e}else{if(a===`additionalProperties`)continue;t[a]=o}return t}function Ar(e){return kr(e)}function jr(e){if(typeof e==`object`)return e;if(typeof e==`string`)return{voiceConfig:{prebuiltVoiceConfig:{voiceName:e}}};throw Error(`Unsupported speechConfig type: ${typeof e}`)}function Mr(e){if(`multiSpeakerVoiceConfig`in e)throw Error(`multiSpeakerVoiceConfig is not supported in the live API.`);return e}function Nr(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=kr(t.parameters)),t.response&&(Object.keys(t.response).includes(`$schema`)?t.responseJsonSchema||(t.responseJsonSchema=t.response,delete t.response):t.response=kr(t.response));return e}function Pr(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 Fr(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 Ir(e,t){if(typeof t!=`string`)throw Error(`name must be a string`);return Fr(e,t,`cachedContents`)}function Lr(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 Rr(e){return mt(e)}function zr(e){return typeof e==`object`&&!!e&&`name`in e}function Br(e){return typeof e==`object`&&!!e&&`video`in e}function Vr(e){return typeof e==`object`&&!!e&&`uri`in e}function Hr(e){let t;if(zr(e)&&(t=e.name),!(Vr(e)&&(t=e.uri,t===void 0))&&!(Br(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 Ur(e,t){let n;return n=e.isVertexAI()?t?`publishers/google/models`:`models`:t?`models`:`tunedModels`,n}function Wr(e){for(let t of[`models`,`tunedModels`,`publisherModels`])if(Gr(e,t))return e[t];return[]}function Gr(e,t){return typeof e==`object`&&!!e&&t in e}function Kr(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 qr(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=Kr(i,t);a.functionDeclarations&&n.push(...a.functionDeclarations)}return{functionDeclarations:n}}function Jr(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 if(/^projects\/[^/]+\/locations\/[^/]+\/datasets\/[^/]+$/.test(t))n={format:`vertex-dataset`,vertexDatasetName: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,n.vertexDatasetName].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`, `bigqueryUri`, or `vertexDatasetName` 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 Yr(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 Xr(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 Zr(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 Qr(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 $r(e){return e.includes(`gemini`)&&e!==`gemini-embedding-001`||e.includes(`maas`)}
57
+ /**
58
+ * @license
59
+ * Copyright 2025 Google LLC
60
+ * SPDX-License-Identifier: Apache-2.0
61
+ */
62
+ function ei(e){let t={},n=H(e,[`apiKey`]);if(n!=null&&V(t,[`apiKey`],n),H(e,[`apiKeyConfig`])!==void 0)throw Error(`apiKeyConfig parameter is not supported in Gemini API.`);if(H(e,[`authType`])!==void 0)throw Error(`authType parameter is not supported in Gemini API.`);if(H(e,[`googleServiceAccountConfig`])!==void 0)throw Error(`googleServiceAccountConfig parameter is not supported in Gemini API.`);if(H(e,[`httpBasicAuthConfig`])!==void 0)throw Error(`httpBasicAuthConfig parameter is not supported in Gemini API.`);if(H(e,[`oauthConfig`])!==void 0)throw Error(`oauthConfig parameter is not supported in Gemini API.`);if(H(e,[`oidcConfig`])!==void 0)throw Error(`oidcConfig parameter is not supported in Gemini API.`);return t}function ti(e){let t={},n=H(e,[`responsesFile`]);n!=null&&V(t,[`fileName`],n);let r=H(e,[`inlinedResponses`,`inlinedResponses`]);if(r!=null){let e=r;Array.isArray(e)&&(e=e.map(e=>zi(e))),V(t,[`inlinedResponses`],e)}let i=H(e,[`inlinedEmbedContentResponses`,`inlinedResponses`]);if(i!=null){let e=i;Array.isArray(e)&&(e=e.map(e=>e)),V(t,[`inlinedEmbedContentResponses`],e)}return t}function ni(e){let t={},n=H(e,[`predictionsFormat`]);n!=null&&V(t,[`format`],n);let r=H(e,[`gcsDestination`,`outputUriPrefix`]);r!=null&&V(t,[`gcsUri`],r);let i=H(e,[`bigqueryDestination`,`outputUri`]);i!=null&&V(t,[`bigqueryUri`],i);let a=H(e,[`vertexMultimodalDatasetDestination`]);return a!=null&&V(t,[`vertexDataset`],Xi(a)),t}function ri(e){let t={},n=H(e,[`format`]);n!=null&&V(t,[`predictionsFormat`],n);let r=H(e,[`gcsUri`]);r!=null&&V(t,[`gcsDestination`,`outputUriPrefix`],r);let i=H(e,[`bigqueryUri`]);if(i!=null&&V(t,[`bigqueryDestination`,`outputUri`],i),H(e,[`fileName`])!==void 0)throw Error(`fileName parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).`);if(H(e,[`inlinedResponses`])!==void 0)throw Error(`inlinedResponses parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).`);if(H(e,[`inlinedEmbedContentResponses`])!==void 0)throw Error(`inlinedEmbedContentResponses parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).`);let a=H(e,[`vertexDataset`]);return a!=null&&V(t,[`vertexMultimodalDatasetDestination`],Zi(a)),t}function ii(e){let t={},n=H(e,[`name`]);n!=null&&V(t,[`name`],n);let r=H(e,[`metadata`,`displayName`]);r!=null&&V(t,[`displayName`],r);let i=H(e,[`metadata`,`state`]);i!=null&&V(t,[`state`],Qr(i));let a=H(e,[`metadata`,`createTime`]);a!=null&&V(t,[`createTime`],a);let o=H(e,[`metadata`,`endTime`]);o!=null&&V(t,[`endTime`],o);let s=H(e,[`metadata`,`updateTime`]);s!=null&&V(t,[`updateTime`],s);let c=H(e,[`metadata`,`model`]);c!=null&&V(t,[`model`],c);let l=H(e,[`metadata`,`output`]);return l!=null&&V(t,[`dest`],ti(Xr(l))),t}function ai(e){let t={},n=H(e,[`name`]);n!=null&&V(t,[`name`],n);let r=H(e,[`displayName`]);r!=null&&V(t,[`displayName`],r);let i=H(e,[`state`]);i!=null&&V(t,[`state`],Qr(i));let a=H(e,[`error`]);a!=null&&V(t,[`error`],a);let o=H(e,[`createTime`]);o!=null&&V(t,[`createTime`],o);let s=H(e,[`startTime`]);s!=null&&V(t,[`startTime`],s);let c=H(e,[`endTime`]);c!=null&&V(t,[`endTime`],c);let l=H(e,[`updateTime`]);l!=null&&V(t,[`updateTime`],l);let u=H(e,[`model`]);u!=null&&V(t,[`model`],u);let d=H(e,[`inputConfig`]);d!=null&&V(t,[`src`],oi(d));let f=H(e,[`outputConfig`]);f!=null&&V(t,[`dest`],ni(Xr(f)));let p=H(e,[`completionStats`]);p!=null&&V(t,[`completionStats`],p);let m=H(e,[`outputInfo`]);return m!=null&&V(t,[`outputInfo`],m),t}function oi(e){let t={},n=H(e,[`instancesFormat`]);n!=null&&V(t,[`format`],n);let r=H(e,[`gcsSource`,`uris`]);r!=null&&V(t,[`gcsUri`],r);let i=H(e,[`bigquerySource`,`inputUri`]);i!=null&&V(t,[`bigqueryUri`],i);let a=H(e,[`vertexMultimodalDatasetSource`,`datasetName`]);return a!=null&&V(t,[`vertexDatasetName`],a),t}function si(e,t){let n={};if(H(t,[`format`])!==void 0)throw Error(`format parameter is not supported in Gemini API.`);if(H(t,[`gcsUri`])!==void 0)throw Error(`gcsUri parameter is not supported in Gemini API.`);if(H(t,[`bigqueryUri`])!==void 0)throw Error(`bigqueryUri parameter is not supported in Gemini API.`);let r=H(t,[`fileName`]);r!=null&&V(n,[`fileName`],r);let i=H(t,[`inlinedRequests`]);if(i!=null){let t=i;Array.isArray(t)&&(t=t.map(t=>Ri(e,t))),V(n,[`requests`,`requests`],t)}if(H(t,[`vertexDatasetName`])!==void 0)throw Error(`vertexDatasetName parameter is not supported in Gemini API.`);return n}function ci(e){let t={},n=H(e,[`format`]);n!=null&&V(t,[`instancesFormat`],n);let r=H(e,[`gcsUri`]);r!=null&&V(t,[`gcsSource`,`uris`],r);let i=H(e,[`bigqueryUri`]);if(i!=null&&V(t,[`bigquerySource`,`inputUri`],i),H(e,[`fileName`])!==void 0)throw Error(`fileName parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).`);if(H(e,[`inlinedRequests`])!==void 0)throw Error(`inlinedRequests parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).`);let a=H(e,[`vertexDatasetName`]);return a!=null&&V(t,[`vertexMultimodalDatasetSource`,`datasetName`],a),t}function li(e){let t={},n=H(e,[`data`]);if(n!=null&&V(t,[`data`],n),H(e,[`displayName`])!==void 0)throw Error(`displayName parameter is not supported in Gemini API.`);let r=H(e,[`mimeType`]);return r!=null&&V(t,[`mimeType`],r),t}function ui(e,t){let n={},r=H(t,[`name`]);return r!=null&&V(n,[`_url`,`name`],Zr(e,r)),n}function di(e,t){let n={},r=H(t,[`name`]);return r!=null&&V(n,[`_url`,`name`],Zr(e,r)),n}function fi(e){let t={},n=H(e,[`content`]);n!=null&&V(t,[`content`],n);let r=H(e,[`citationMetadata`]);r!=null&&V(t,[`citationMetadata`],pi(r));let i=H(e,[`tokenCount`]);i!=null&&V(t,[`tokenCount`],i);let a=H(e,[`finishReason`]);a!=null&&V(t,[`finishReason`],a);let o=H(e,[`groundingMetadata`]);o!=null&&V(t,[`groundingMetadata`],o);let s=H(e,[`avgLogprobs`]);s!=null&&V(t,[`avgLogprobs`],s);let c=H(e,[`index`]);c!=null&&V(t,[`index`],c);let l=H(e,[`logprobsResult`]);l!=null&&V(t,[`logprobsResult`],l);let u=H(e,[`safetyRatings`]);if(u!=null){let e=u;Array.isArray(e)&&(e=e.map(e=>e)),V(t,[`safetyRatings`],e)}let d=H(e,[`urlContextMetadata`]);return d!=null&&V(t,[`urlContextMetadata`],d),t}function pi(e){let t={},n=H(e,[`citationSources`]);if(n!=null){let e=n;Array.isArray(e)&&(e=e.map(e=>e)),V(t,[`citations`],e)}return t}function mi(e){let t={},n=H(e,[`parts`]);if(n!=null){let e=n;Array.isArray(e)&&(e=e.map(e=>Ki(e))),V(t,[`parts`],e)}let r=H(e,[`role`]);return r!=null&&V(t,[`role`],r),t}function hi(e,t){let n={},r=H(e,[`displayName`]);if(t!==void 0&&r!=null&&V(t,[`batch`,`displayName`],r),H(e,[`dest`])!==void 0)throw Error(`dest parameter is not supported in Gemini API.`);let i=H(e,[`webhookConfig`]);return t!==void 0&&i!=null&&V(t,[`batch`,`webhookConfig`],i),n}function gi(e,t){let n={},r=H(e,[`displayName`]);t!==void 0&&r!=null&&V(t,[`displayName`],r);let i=H(e,[`dest`]);if(t!==void 0&&i!=null&&V(t,[`outputConfig`],ri(Yr(i))),H(e,[`webhookConfig`])!==void 0)throw Error(`webhookConfig parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).`);return n}function _i(e,t){let n={},r=H(t,[`model`]);r!=null&&V(n,[`_url`,`model`],W(e,r));let i=H(t,[`src`]);i!=null&&V(n,[`batch`,`inputConfig`],si(e,Jr(e,i)));let a=H(t,[`config`]);return a!=null&&hi(a,n),n}function vi(e,t){let n={},r=H(t,[`model`]);r!=null&&V(n,[`model`],W(e,r));let i=H(t,[`src`]);i!=null&&V(n,[`inputConfig`],ci(Jr(e,i)));let a=H(t,[`config`]);return a!=null&&gi(a,n),n}function yi(e,t){let n={},r=H(e,[`displayName`]);return t!==void 0&&r!=null&&V(t,[`batch`,`displayName`],r),n}function bi(e,t){let n={},r=H(t,[`model`]);r!=null&&V(n,[`_url`,`model`],W(e,r));let i=H(t,[`src`]);i!=null&&V(n,[`batch`,`inputConfig`],Di(e,i));let a=H(t,[`config`]);return a!=null&&yi(a,n),n}function xi(e,t){let n={},r=H(t,[`name`]);return r!=null&&V(n,[`_url`,`name`],Zr(e,r)),n}function Si(e,t){let n={},r=H(t,[`name`]);return r!=null&&V(n,[`_url`,`name`],Zr(e,r)),n}function Ci(e){let t={},n=H(e,[`sdkHttpResponse`]);n!=null&&V(t,[`sdkHttpResponse`],n);let r=H(e,[`name`]);r!=null&&V(t,[`name`],r);let i=H(e,[`done`]);i!=null&&V(t,[`done`],i);let a=H(e,[`error`]);return a!=null&&V(t,[`error`],a),t}function wi(e){let t={},n=H(e,[`sdkHttpResponse`]);n!=null&&V(t,[`sdkHttpResponse`],n);let r=H(e,[`name`]);r!=null&&V(t,[`name`],r);let i=H(e,[`done`]);i!=null&&V(t,[`done`],i);let a=H(e,[`error`]);return a!=null&&V(t,[`error`],a),t}function Ti(e,t){let n={},r=H(t,[`contents`]);if(r!=null){let t=Dr(e,r);Array.isArray(t)&&(t=t.map(e=>e)),V(n,[`requests[]`,`request`,`content`],t)}let i=H(t,[`config`]);return i!=null&&(V(n,[`_self`],Ei(i,n)),ft(n,{"requests[].*":`requests[].request.*`})),n}function Ei(e,t){let n={},r=H(e,[`taskType`]);t!==void 0&&r!=null&&V(t,[`requests[]`,`taskType`],r);let i=H(e,[`title`]);t!==void 0&&i!=null&&V(t,[`requests[]`,`title`],i);let a=H(e,[`outputDimensionality`]);if(t!==void 0&&a!=null&&V(t,[`requests[]`,`outputDimensionality`],a),H(e,[`mimeType`])!==void 0)throw Error(`mimeType parameter is not supported in Gemini API.`);if(H(e,[`autoTruncate`])!==void 0)throw Error(`autoTruncate parameter is not supported in Gemini API.`);if(H(e,[`documentOcr`])!==void 0)throw Error(`documentOcr parameter is not supported in Gemini API.`);if(H(e,[`audioTrackExtraction`])!==void 0)throw Error(`audioTrackExtraction parameter is not supported in Gemini API.`);return n}function Di(e,t){let n={},r=H(t,[`fileName`]);r!=null&&V(n,[`file_name`],r);let i=H(t,[`inlinedRequests`]);return i!=null&&V(n,[`requests`],Ti(e,i)),n}function Oi(e){let t={};if(H(e,[`displayName`])!==void 0)throw Error(`displayName parameter is not supported in Gemini API.`);let n=H(e,[`fileUri`]);n!=null&&V(t,[`fileUri`],n);let r=H(e,[`mimeType`]);return r!=null&&V(t,[`mimeType`],r),t}function ki(e){let t={},n=H(e,[`id`]);n!=null&&V(t,[`id`],n);let r=H(e,[`args`]);r!=null&&V(t,[`args`],r);let i=H(e,[`name`]);if(i!=null&&V(t,[`name`],i),H(e,[`partialArgs`])!==void 0)throw Error(`partialArgs parameter is not supported in Gemini API.`);if(H(e,[`willContinue`])!==void 0)throw Error(`willContinue parameter is not supported in Gemini API.`);return t}function Ai(e){let t={},n=H(e,[`allowedFunctionNames`]);n!=null&&V(t,[`allowedFunctionNames`],n);let r=H(e,[`mode`]);if(r!=null&&V(t,[`mode`],r),H(e,[`streamFunctionCallArguments`])!==void 0)throw Error(`streamFunctionCallArguments parameter is not supported in Gemini API.`);return t}function ji(e,t,n){let r={},i=H(t,[`systemInstruction`]);n!==void 0&&i!=null&&V(n,[`systemInstruction`],mi(G(i)));let a=H(t,[`temperature`]);a!=null&&V(r,[`temperature`],a);let o=H(t,[`topP`]);o!=null&&V(r,[`topP`],o);let s=H(t,[`topK`]);s!=null&&V(r,[`topK`],s);let c=H(t,[`candidateCount`]);c!=null&&V(r,[`candidateCount`],c);let l=H(t,[`maxOutputTokens`]);l!=null&&V(r,[`maxOutputTokens`],l);let u=H(t,[`stopSequences`]);u!=null&&V(r,[`stopSequences`],u);let d=H(t,[`responseLogprobs`]);d!=null&&V(r,[`responseLogprobs`],d);let f=H(t,[`logprobs`]);f!=null&&V(r,[`logprobs`],f);let p=H(t,[`presencePenalty`]);p!=null&&V(r,[`presencePenalty`],p);let m=H(t,[`frequencyPenalty`]);m!=null&&V(r,[`frequencyPenalty`],m);let h=H(t,[`seed`]);h!=null&&V(r,[`seed`],h);let g=H(t,[`responseMimeType`]);g!=null&&V(r,[`responseMimeType`],g);let _=H(t,[`responseSchema`]);_!=null&&V(r,[`responseSchema`],Ar(_));let v=H(t,[`responseJsonSchema`]);if(v!=null&&V(r,[`responseJsonSchema`],v),H(t,[`routingConfig`])!==void 0)throw Error(`routingConfig parameter is not supported in Gemini API.`);if(H(t,[`modelSelectionConfig`])!==void 0)throw Error(`modelSelectionConfig parameter is not supported in Gemini API.`);let y=H(t,[`safetySettings`]);if(n!==void 0&&y!=null){let e=y;Array.isArray(e)&&(e=e.map(e=>qi(e))),V(n,[`safetySettings`],e)}let b=H(t,[`tools`]);if(n!==void 0&&b!=null){let e=Pr(b);Array.isArray(e)&&(e=e.map(e=>Yi(Nr(e)))),V(n,[`tools`],e)}let x=H(t,[`toolConfig`]);if(n!==void 0&&x!=null&&V(n,[`toolConfig`],Ji(x)),H(t,[`labels`])!==void 0)throw Error(`labels parameter is not supported in Gemini API.`);let S=H(t,[`cachedContent`]);n!==void 0&&S!=null&&V(n,[`cachedContent`],Ir(e,S));let C=H(t,[`responseModalities`]);C!=null&&V(r,[`responseModalities`],C);let w=H(t,[`mediaResolution`]);w!=null&&V(r,[`mediaResolution`],w);let T=H(t,[`speechConfig`]);if(T!=null&&V(r,[`speechConfig`],jr(T)),H(t,[`audioTimestamp`])!==void 0)throw Error(`audioTimestamp parameter is not supported in Gemini API.`);let E=H(t,[`thinkingConfig`]);E!=null&&V(r,[`thinkingConfig`],E);let D=H(t,[`imageConfig`]);D!=null&&V(r,[`imageConfig`],Li(D));let O=H(t,[`enableEnhancedCivicAnswers`]);if(O!=null&&V(r,[`enableEnhancedCivicAnswers`],O),H(t,[`modelArmorConfig`])!==void 0)throw Error(`modelArmorConfig parameter is not supported in Gemini API.`);let k=H(t,[`serviceTier`]);return n!==void 0&&k!=null&&V(n,[`serviceTier`],k),r}function Mi(e){let t={},n=H(e,[`sdkHttpResponse`]);n!=null&&V(t,[`sdkHttpResponse`],n);let r=H(e,[`candidates`]);if(r!=null){let e=r;Array.isArray(e)&&(e=e.map(e=>fi(e))),V(t,[`candidates`],e)}let i=H(e,[`modelVersion`]);i!=null&&V(t,[`modelVersion`],i);let a=H(e,[`promptFeedback`]);a!=null&&V(t,[`promptFeedback`],a);let o=H(e,[`responseId`]);o!=null&&V(t,[`responseId`],o);let s=H(e,[`usageMetadata`]);s!=null&&V(t,[`usageMetadata`],s);let c=H(e,[`modelStatus`]);return c!=null&&V(t,[`modelStatus`],c),t}function Ni(e,t){let n={},r=H(t,[`name`]);return r!=null&&V(n,[`_url`,`name`],Zr(e,r)),n}function Pi(e,t){let n={},r=H(t,[`name`]);return r!=null&&V(n,[`_url`,`name`],Zr(e,r)),n}function Fi(e){let t={},n=H(e,[`authConfig`]);n!=null&&V(t,[`authConfig`],ei(n));let r=H(e,[`enableWidget`]);return r!=null&&V(t,[`enableWidget`],r),t}function Ii(e){let t={},n=H(e,[`searchTypes`]);if(n!=null&&V(t,[`searchTypes`],n),H(e,[`blockingConfidence`])!==void 0)throw Error(`blockingConfidence parameter is not supported in Gemini API.`);if(H(e,[`excludeDomains`])!==void 0)throw Error(`excludeDomains parameter is not supported in Gemini API.`);let r=H(e,[`timeRangeFilter`]);return r!=null&&V(t,[`timeRangeFilter`],r),t}function Li(e){let t={},n=H(e,[`aspectRatio`]);n!=null&&V(t,[`aspectRatio`],n);let r=H(e,[`imageSize`]);if(r!=null&&V(t,[`imageSize`],r),H(e,[`personGeneration`])!==void 0)throw Error(`personGeneration parameter is not supported in Gemini API.`);if(H(e,[`prominentPeople`])!==void 0)throw Error(`prominentPeople parameter is not supported in Gemini API.`);if(H(e,[`outputMimeType`])!==void 0)throw Error(`outputMimeType parameter is not supported in Gemini API.`);if(H(e,[`outputCompressionQuality`])!==void 0)throw Error(`outputCompressionQuality parameter is not supported in Gemini API.`);if(H(e,[`imageOutputOptions`])!==void 0)throw Error(`imageOutputOptions parameter is not supported in Gemini API.`);return t}function Ri(e,t){let n={},r=H(t,[`model`]);r!=null&&V(n,[`request`,`model`],W(e,r));let i=H(t,[`contents`]);if(i!=null){let e=K(i);Array.isArray(e)&&(e=e.map(e=>mi(e))),V(n,[`request`,`contents`],e)}let a=H(t,[`metadata`]);a!=null&&V(n,[`metadata`],a);let o=H(t,[`config`]);return o!=null&&V(n,[`request`,`generationConfig`],ji(e,o,H(n,[`request`],{}))),n}function zi(e){let t={},n=H(e,[`response`]);n!=null&&V(t,[`response`],Mi(n));let r=H(e,[`metadata`]);r!=null&&V(t,[`metadata`],r);let i=H(e,[`error`]);return i!=null&&V(t,[`error`],i),t}function Bi(e,t){let n={},r=H(e,[`pageSize`]);t!==void 0&&r!=null&&V(t,[`_query`,`pageSize`],r);let i=H(e,[`pageToken`]);if(t!==void 0&&i!=null&&V(t,[`_query`,`pageToken`],i),H(e,[`filter`])!==void 0)throw Error(`filter parameter is not supported in Gemini API.`);return n}function Vi(e,t){let n={},r=H(e,[`pageSize`]);t!==void 0&&r!=null&&V(t,[`_query`,`pageSize`],r);let i=H(e,[`pageToken`]);t!==void 0&&i!=null&&V(t,[`_query`,`pageToken`],i);let a=H(e,[`filter`]);return t!==void 0&&a!=null&&V(t,[`_query`,`filter`],a),n}function Hi(e){let t={},n=H(e,[`config`]);return n!=null&&Bi(n,t),t}function Ui(e){let t={},n=H(e,[`config`]);return n!=null&&Vi(n,t),t}function Wi(e){let t={},n=H(e,[`sdkHttpResponse`]);n!=null&&V(t,[`sdkHttpResponse`],n);let r=H(e,[`nextPageToken`]);r!=null&&V(t,[`nextPageToken`],r);let i=H(e,[`operations`]);if(i!=null){let e=i;Array.isArray(e)&&(e=e.map(e=>ii(e))),V(t,[`batchJobs`],e)}return t}function Gi(e){let t={},n=H(e,[`sdkHttpResponse`]);n!=null&&V(t,[`sdkHttpResponse`],n);let r=H(e,[`nextPageToken`]);r!=null&&V(t,[`nextPageToken`],r);let i=H(e,[`batchPredictionJobs`]);if(i!=null){let e=i;Array.isArray(e)&&(e=e.map(e=>ai(e))),V(t,[`batchJobs`],e)}return t}function Ki(e){let t={},n=H(e,[`mediaResolution`]);n!=null&&V(t,[`mediaResolution`],n);let r=H(e,[`codeExecutionResult`]);r!=null&&V(t,[`codeExecutionResult`],r);let i=H(e,[`executableCode`]);i!=null&&V(t,[`executableCode`],i);let a=H(e,[`fileData`]);a!=null&&V(t,[`fileData`],Oi(a));let o=H(e,[`functionCall`]);o!=null&&V(t,[`functionCall`],ki(o));let s=H(e,[`functionResponse`]);s!=null&&V(t,[`functionResponse`],s);let c=H(e,[`inlineData`]);c!=null&&V(t,[`inlineData`],li(c));let l=H(e,[`text`]);l!=null&&V(t,[`text`],l);let u=H(e,[`thought`]);u!=null&&V(t,[`thought`],u);let d=H(e,[`thoughtSignature`]);d!=null&&V(t,[`thoughtSignature`],d);let f=H(e,[`videoMetadata`]);f!=null&&V(t,[`videoMetadata`],f);let p=H(e,[`toolCall`]);p!=null&&V(t,[`toolCall`],p);let m=H(e,[`toolResponse`]);m!=null&&V(t,[`toolResponse`],m);let h=H(e,[`partMetadata`]);return h!=null&&V(t,[`partMetadata`],h),t}function qi(e){let t={},n=H(e,[`category`]);if(n!=null&&V(t,[`category`],n),H(e,[`method`])!==void 0)throw Error(`method parameter is not supported in Gemini API.`);let r=H(e,[`threshold`]);return r!=null&&V(t,[`threshold`],r),t}function Ji(e){let t={},n=H(e,[`retrievalConfig`]);n!=null&&V(t,[`retrievalConfig`],n);let r=H(e,[`functionCallingConfig`]);r!=null&&V(t,[`functionCallingConfig`],Ai(r));let i=H(e,[`includeServerSideToolInvocations`]);return i!=null&&V(t,[`includeServerSideToolInvocations`],i),t}function Yi(e){let t={};if(H(e,[`retrieval`])!==void 0)throw Error(`retrieval parameter is not supported in Gemini API.`);let n=H(e,[`computerUse`]);n!=null&&V(t,[`computerUse`],n);let r=H(e,[`fileSearch`]);r!=null&&V(t,[`fileSearch`],r);let i=H(e,[`googleSearch`]);i!=null&&V(t,[`googleSearch`],Ii(i));let a=H(e,[`googleMaps`]);a!=null&&V(t,[`googleMaps`],Fi(a));let o=H(e,[`codeExecution`]);if(o!=null&&V(t,[`codeExecution`],o),H(e,[`enterpriseWebSearch`])!==void 0)throw Error(`enterpriseWebSearch parameter is not supported in Gemini API.`);let s=H(e,[`functionDeclarations`]);if(s!=null){let e=s;Array.isArray(e)&&(e=e.map(e=>e)),V(t,[`functionDeclarations`],e)}let c=H(e,[`googleSearchRetrieval`]);if(c!=null&&V(t,[`googleSearchRetrieval`],c),H(e,[`parallelAiSearch`])!==void 0)throw Error(`parallelAiSearch parameter is not supported in Gemini API.`);let l=H(e,[`urlContext`]);l!=null&&V(t,[`urlContext`],l);let u=H(e,[`mcpServers`]);if(u!=null){let e=u;Array.isArray(e)&&(e=e.map(e=>e)),V(t,[`mcpServers`],e)}return t}function Xi(e){let t={},n=H(e,[`bigqueryDestination`,`outputUri`]);n!=null&&V(t,[`bigqueryDestination`],n);let r=H(e,[`displayName`]);return r!=null&&V(t,[`displayName`],r),t}function Zi(e){let t={},n=H(e,[`bigqueryDestination`]);n!=null&&V(t,[`bigqueryDestination`,`outputUri`],n);let r=H(e,[`displayName`]);return r!=null&&V(t,[`displayName`],r),t}
63
+ /**
64
+ * @license
65
+ * Copyright 2025 Google LLC
66
+ * SPDX-License-Identifier: Apache-2.0
67
+ */
68
+ var Qi;(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`})(Qi||={});var $i=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}},ea=class extends dt{constructor(e){super(),this.apiClient=e,this.list=async(e={})=>new $i(Qi.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(`Gemini Enterprise Agent Platform (previously known as Vertex AI) does not support batches.createEmbeddings.`);return this.createEmbeddingsInternal(e)}}createInlinedGenerateContentRequest(e){let t=_i(this.apiClient,e),n=t._url,r=B(`{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 Gemini Enterprise Agent Platform (previously known as Vertex AI): No GCS or BigQuery URI found.`)}return n}async createInternal(e){let t,n=``,r={};if(this.apiClient.isVertexAI()){let i=vi(this.apiClient,e);return n=B(`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=>ai(e))}else{let i=_i(this.apiClient,e);return n=B(`{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=>ii(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=bi(this.apiClient,e);return n=B(`{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=>ii(e))}}async get(e){let t,n=``,r={};if(this.apiClient.isVertexAI()){let i=Pi(this.apiClient,e);return n=B(`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=>ai(e))}else{let i=Ni(this.apiClient,e);return n=B(`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=>ii(e))}}async cancel(e){let t=``,n={};if(this.apiClient.isVertexAI()){let r=di(this.apiClient,e);t=B(`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=ui(this.apiClient,e);t=B(`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=Ui(e);return n=B(`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=Gi(e),n=new pr;return Object.assign(n,t),n})}else{let i=Hi(e);return n=B(`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=Wi(e),n=new pr;return Object.assign(n,t),n})}}async delete(e){let t,n=``,r={};if(this.apiClient.isVertexAI()){let i=Si(this.apiClient,e);return n=B(`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=>wi(e))}else{let i=xi(this.apiClient,e);return n=B(`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=>Ci(e))}}};
69
+ /**
70
+ * @license
71
+ * Copyright 2025 Google LLC
72
+ * SPDX-License-Identifier: Apache-2.0
73
+ */
74
+ function ta(e){let t={},n=H(e,[`apiKey`]);if(n!=null&&V(t,[`apiKey`],n),H(e,[`apiKeyConfig`])!==void 0)throw Error(`apiKeyConfig parameter is not supported in Gemini API.`);if(H(e,[`authType`])!==void 0)throw Error(`authType parameter is not supported in Gemini API.`);if(H(e,[`googleServiceAccountConfig`])!==void 0)throw Error(`googleServiceAccountConfig parameter is not supported in Gemini API.`);if(H(e,[`httpBasicAuthConfig`])!==void 0)throw Error(`httpBasicAuthConfig parameter is not supported in Gemini API.`);if(H(e,[`oauthConfig`])!==void 0)throw Error(`oauthConfig parameter is not supported in Gemini API.`);if(H(e,[`oidcConfig`])!==void 0)throw Error(`oidcConfig parameter is not supported in Gemini API.`);return t}function na(e){let t={},n=H(e,[`data`]);if(n!=null&&V(t,[`data`],n),H(e,[`displayName`])!==void 0)throw Error(`displayName parameter is not supported in Gemini API.`);let r=H(e,[`mimeType`]);return r!=null&&V(t,[`mimeType`],r),t}function ra(e){let t={},n=H(e,[`parts`]);if(n!=null){let e=n;Array.isArray(e)&&(e=e.map(e=>Da(e))),V(t,[`parts`],e)}let r=H(e,[`role`]);return r!=null&&V(t,[`role`],r),t}function ia(e){let t={},n=H(e,[`parts`]);if(n!=null){let e=n;Array.isArray(e)&&(e=e.map(e=>Oa(e))),V(t,[`parts`],e)}let r=H(e,[`role`]);return r!=null&&V(t,[`role`],r),t}function aa(e,t){let n={},r=H(e,[`ttl`]);t!==void 0&&r!=null&&V(t,[`ttl`],r);let i=H(e,[`expireTime`]);t!==void 0&&i!=null&&V(t,[`expireTime`],i);let a=H(e,[`displayName`]);t!==void 0&&a!=null&&V(t,[`displayName`],a);let o=H(e,[`contents`]);if(t!==void 0&&o!=null){let e=K(o);Array.isArray(e)&&(e=e.map(e=>ra(e))),V(t,[`contents`],e)}let s=H(e,[`systemInstruction`]);t!==void 0&&s!=null&&V(t,[`systemInstruction`],ra(G(s)));let c=H(e,[`tools`]);if(t!==void 0&&c!=null){let e=c;Array.isArray(e)&&(e=e.map(e=>ja(e))),V(t,[`tools`],e)}let l=H(e,[`toolConfig`]);if(t!==void 0&&l!=null&&V(t,[`toolConfig`],ka(l)),H(e,[`kmsKeyName`])!==void 0)throw Error(`kmsKeyName parameter is not supported in Gemini API.`);return n}function oa(e,t){let n={},r=H(e,[`ttl`]);t!==void 0&&r!=null&&V(t,[`ttl`],r);let i=H(e,[`expireTime`]);t!==void 0&&i!=null&&V(t,[`expireTime`],i);let a=H(e,[`displayName`]);t!==void 0&&a!=null&&V(t,[`displayName`],a);let o=H(e,[`contents`]);if(t!==void 0&&o!=null){let e=K(o);Array.isArray(e)&&(e=e.map(e=>ia(e))),V(t,[`contents`],e)}let s=H(e,[`systemInstruction`]);t!==void 0&&s!=null&&V(t,[`systemInstruction`],ia(G(s)));let c=H(e,[`tools`]);if(t!==void 0&&c!=null){let e=c;Array.isArray(e)&&(e=e.map(e=>Ma(e))),V(t,[`tools`],e)}let l=H(e,[`toolConfig`]);t!==void 0&&l!=null&&V(t,[`toolConfig`],Aa(l));let u=H(e,[`kmsKeyName`]);return t!==void 0&&u!=null&&V(t,[`encryption_spec`,`kmsKeyName`],u),n}function sa(e,t){let n={},r=H(t,[`model`]);r!=null&&V(n,[`model`],_r(e,r));let i=H(t,[`config`]);return i!=null&&aa(i,n),n}function ca(e,t){let n={},r=H(t,[`model`]);r!=null&&V(n,[`model`],_r(e,r));let i=H(t,[`config`]);return i!=null&&oa(i,n),n}function la(e,t){let n={},r=H(t,[`name`]);return r!=null&&V(n,[`_url`,`name`],Ir(e,r)),n}function ua(e,t){let n={},r=H(t,[`name`]);return r!=null&&V(n,[`_url`,`name`],Ir(e,r)),n}function da(e){let t={},n=H(e,[`sdkHttpResponse`]);return n!=null&&V(t,[`sdkHttpResponse`],n),t}function fa(e){let t={},n=H(e,[`sdkHttpResponse`]);return n!=null&&V(t,[`sdkHttpResponse`],n),t}function pa(e){let t={};if(H(e,[`displayName`])!==void 0)throw Error(`displayName parameter is not supported in Gemini API.`);let n=H(e,[`fileUri`]);n!=null&&V(t,[`fileUri`],n);let r=H(e,[`mimeType`]);return r!=null&&V(t,[`mimeType`],r),t}function ma(e){let t={},n=H(e,[`id`]);n!=null&&V(t,[`id`],n);let r=H(e,[`args`]);r!=null&&V(t,[`args`],r);let i=H(e,[`name`]);if(i!=null&&V(t,[`name`],i),H(e,[`partialArgs`])!==void 0)throw Error(`partialArgs parameter is not supported in Gemini API.`);if(H(e,[`willContinue`])!==void 0)throw Error(`willContinue parameter is not supported in Gemini API.`);return t}function ha(e){let t={},n=H(e,[`allowedFunctionNames`]);n!=null&&V(t,[`allowedFunctionNames`],n);let r=H(e,[`mode`]);if(r!=null&&V(t,[`mode`],r),H(e,[`streamFunctionCallArguments`])!==void 0)throw Error(`streamFunctionCallArguments parameter is not supported in Gemini API.`);return t}function ga(e){let t={},n=H(e,[`description`]);n!=null&&V(t,[`description`],n);let r=H(e,[`name`]);r!=null&&V(t,[`name`],r);let i=H(e,[`parameters`]);i!=null&&V(t,[`parameters`],i);let a=H(e,[`parametersJsonSchema`]);a!=null&&V(t,[`parametersJsonSchema`],a);let o=H(e,[`response`]);o!=null&&V(t,[`response`],o);let s=H(e,[`responseJsonSchema`]);if(s!=null&&V(t,[`responseJsonSchema`],s),H(e,[`behavior`])!==void 0)throw Error(`behavior parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).`);return t}function _a(e,t){let n={},r=H(t,[`name`]);return r!=null&&V(n,[`_url`,`name`],Ir(e,r)),n}function va(e,t){let n={},r=H(t,[`name`]);return r!=null&&V(n,[`_url`,`name`],Ir(e,r)),n}function ya(e){let t={},n=H(e,[`authConfig`]);n!=null&&V(t,[`authConfig`],ta(n));let r=H(e,[`enableWidget`]);return r!=null&&V(t,[`enableWidget`],r),t}function ba(e){let t={},n=H(e,[`searchTypes`]);if(n!=null&&V(t,[`searchTypes`],n),H(e,[`blockingConfidence`])!==void 0)throw Error(`blockingConfidence parameter is not supported in Gemini API.`);if(H(e,[`excludeDomains`])!==void 0)throw Error(`excludeDomains parameter is not supported in Gemini API.`);let r=H(e,[`timeRangeFilter`]);return r!=null&&V(t,[`timeRangeFilter`],r),t}function xa(e,t){let n={},r=H(e,[`pageSize`]);t!==void 0&&r!=null&&V(t,[`_query`,`pageSize`],r);let i=H(e,[`pageToken`]);return t!==void 0&&i!=null&&V(t,[`_query`,`pageToken`],i),n}function Sa(e,t){let n={},r=H(e,[`pageSize`]);t!==void 0&&r!=null&&V(t,[`_query`,`pageSize`],r);let i=H(e,[`pageToken`]);return t!==void 0&&i!=null&&V(t,[`_query`,`pageToken`],i),n}function Ca(e){let t={},n=H(e,[`config`]);return n!=null&&xa(n,t),t}function wa(e){let t={},n=H(e,[`config`]);return n!=null&&Sa(n,t),t}function Ta(e){let t={},n=H(e,[`sdkHttpResponse`]);n!=null&&V(t,[`sdkHttpResponse`],n);let r=H(e,[`nextPageToken`]);r!=null&&V(t,[`nextPageToken`],r);let i=H(e,[`cachedContents`]);if(i!=null){let e=i;Array.isArray(e)&&(e=e.map(e=>e)),V(t,[`cachedContents`],e)}return t}function Ea(e){let t={},n=H(e,[`sdkHttpResponse`]);n!=null&&V(t,[`sdkHttpResponse`],n);let r=H(e,[`nextPageToken`]);r!=null&&V(t,[`nextPageToken`],r);let i=H(e,[`cachedContents`]);if(i!=null){let e=i;Array.isArray(e)&&(e=e.map(e=>e)),V(t,[`cachedContents`],e)}return t}function Da(e){let t={},n=H(e,[`mediaResolution`]);n!=null&&V(t,[`mediaResolution`],n);let r=H(e,[`codeExecutionResult`]);r!=null&&V(t,[`codeExecutionResult`],r);let i=H(e,[`executableCode`]);i!=null&&V(t,[`executableCode`],i);let a=H(e,[`fileData`]);a!=null&&V(t,[`fileData`],pa(a));let o=H(e,[`functionCall`]);o!=null&&V(t,[`functionCall`],ma(o));let s=H(e,[`functionResponse`]);s!=null&&V(t,[`functionResponse`],s);let c=H(e,[`inlineData`]);c!=null&&V(t,[`inlineData`],na(c));let l=H(e,[`text`]);l!=null&&V(t,[`text`],l);let u=H(e,[`thought`]);u!=null&&V(t,[`thought`],u);let d=H(e,[`thoughtSignature`]);d!=null&&V(t,[`thoughtSignature`],d);let f=H(e,[`videoMetadata`]);f!=null&&V(t,[`videoMetadata`],f);let p=H(e,[`toolCall`]);p!=null&&V(t,[`toolCall`],p);let m=H(e,[`toolResponse`]);m!=null&&V(t,[`toolResponse`],m);let h=H(e,[`partMetadata`]);return h!=null&&V(t,[`partMetadata`],h),t}function Oa(e){let t={},n=H(e,[`mediaResolution`]);n!=null&&V(t,[`mediaResolution`],n);let r=H(e,[`codeExecutionResult`]);r!=null&&V(t,[`codeExecutionResult`],r);let i=H(e,[`executableCode`]);i!=null&&V(t,[`executableCode`],i);let a=H(e,[`fileData`]);a!=null&&V(t,[`fileData`],a);let o=H(e,[`functionCall`]);o!=null&&V(t,[`functionCall`],o);let s=H(e,[`functionResponse`]);s!=null&&V(t,[`functionResponse`],s);let c=H(e,[`inlineData`]);c!=null&&V(t,[`inlineData`],c);let l=H(e,[`text`]);l!=null&&V(t,[`text`],l);let u=H(e,[`thought`]);u!=null&&V(t,[`thought`],u);let d=H(e,[`thoughtSignature`]);d!=null&&V(t,[`thoughtSignature`],d);let f=H(e,[`videoMetadata`]);if(f!=null&&V(t,[`videoMetadata`],f),H(e,[`toolCall`])!==void 0)throw Error(`toolCall parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).`);if(H(e,[`toolResponse`])!==void 0)throw Error(`toolResponse parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).`);if(H(e,[`partMetadata`])!==void 0)throw Error(`partMetadata parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).`);return t}function ka(e){let t={},n=H(e,[`retrievalConfig`]);n!=null&&V(t,[`retrievalConfig`],n);let r=H(e,[`functionCallingConfig`]);r!=null&&V(t,[`functionCallingConfig`],ha(r));let i=H(e,[`includeServerSideToolInvocations`]);return i!=null&&V(t,[`includeServerSideToolInvocations`],i),t}function Aa(e){let t={},n=H(e,[`retrievalConfig`]);n!=null&&V(t,[`retrievalConfig`],n);let r=H(e,[`functionCallingConfig`]);if(r!=null&&V(t,[`functionCallingConfig`],r),H(e,[`includeServerSideToolInvocations`])!==void 0)throw Error(`includeServerSideToolInvocations parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).`);return t}function ja(e){let t={};if(H(e,[`retrieval`])!==void 0)throw Error(`retrieval parameter is not supported in Gemini API.`);let n=H(e,[`computerUse`]);n!=null&&V(t,[`computerUse`],n);let r=H(e,[`fileSearch`]);r!=null&&V(t,[`fileSearch`],r);let i=H(e,[`googleSearch`]);i!=null&&V(t,[`googleSearch`],ba(i));let a=H(e,[`googleMaps`]);a!=null&&V(t,[`googleMaps`],ya(a));let o=H(e,[`codeExecution`]);if(o!=null&&V(t,[`codeExecution`],o),H(e,[`enterpriseWebSearch`])!==void 0)throw Error(`enterpriseWebSearch parameter is not supported in Gemini API.`);let s=H(e,[`functionDeclarations`]);if(s!=null){let e=s;Array.isArray(e)&&(e=e.map(e=>e)),V(t,[`functionDeclarations`],e)}let c=H(e,[`googleSearchRetrieval`]);if(c!=null&&V(t,[`googleSearchRetrieval`],c),H(e,[`parallelAiSearch`])!==void 0)throw Error(`parallelAiSearch parameter is not supported in Gemini API.`);let l=H(e,[`urlContext`]);l!=null&&V(t,[`urlContext`],l);let u=H(e,[`mcpServers`]);if(u!=null){let e=u;Array.isArray(e)&&(e=e.map(e=>e)),V(t,[`mcpServers`],e)}return t}function Ma(e){let t={},n=H(e,[`retrieval`]);n!=null&&V(t,[`retrieval`],n);let r=H(e,[`computerUse`]);if(r!=null&&V(t,[`computerUse`],r),H(e,[`fileSearch`])!==void 0)throw Error(`fileSearch parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).`);let i=H(e,[`googleSearch`]);i!=null&&V(t,[`googleSearch`],i);let a=H(e,[`googleMaps`]);a!=null&&V(t,[`googleMaps`],a);let o=H(e,[`codeExecution`]);o!=null&&V(t,[`codeExecution`],o);let s=H(e,[`enterpriseWebSearch`]);s!=null&&V(t,[`enterpriseWebSearch`],s);let c=H(e,[`functionDeclarations`]);if(c!=null){let e=c;Array.isArray(e)&&(e=e.map(e=>ga(e))),V(t,[`functionDeclarations`],e)}let l=H(e,[`googleSearchRetrieval`]);l!=null&&V(t,[`googleSearchRetrieval`],l);let u=H(e,[`parallelAiSearch`]);u!=null&&V(t,[`parallelAiSearch`],u);let d=H(e,[`urlContext`]);if(d!=null&&V(t,[`urlContext`],d),H(e,[`mcpServers`])!==void 0)throw Error(`mcpServers parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).`);return t}function Na(e,t){let n={},r=H(e,[`ttl`]);t!==void 0&&r!=null&&V(t,[`ttl`],r);let i=H(e,[`expireTime`]);return t!==void 0&&i!=null&&V(t,[`expireTime`],i),n}function Pa(e,t){let n={},r=H(e,[`ttl`]);t!==void 0&&r!=null&&V(t,[`ttl`],r);let i=H(e,[`expireTime`]);return t!==void 0&&i!=null&&V(t,[`expireTime`],i),n}function Fa(e,t){let n={},r=H(t,[`name`]);r!=null&&V(n,[`_url`,`name`],Ir(e,r));let i=H(t,[`config`]);return i!=null&&Na(i,n),n}function Ia(e,t){let n={},r=H(t,[`name`]);r!=null&&V(n,[`_url`,`name`],Ir(e,r));let i=H(t,[`config`]);return i!=null&&Pa(i,n),n}
75
+ /**
76
+ * @license
77
+ * Copyright 2025 Google LLC
78
+ * SPDX-License-Identifier: Apache-2.0
79
+ */
80
+ var La=class extends dt{constructor(e){super(),this.apiClient=e,this.list=async(e={})=>new $i(Qi.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=ca(this.apiClient,e);return n=B(`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=sa(this.apiClient,e);return n=B(`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=va(this.apiClient,e);return n=B(`{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=_a(this.apiClient,e);return n=B(`{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=ua(this.apiClient,e);return n=B(`{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=fa(e),n=new rr;return Object.assign(n,t),n})}else{let i=la(this.apiClient,e);return n=B(`{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=da(e),n=new rr;return Object.assign(n,t),n})}}async update(e){let t,n=``,r={};if(this.apiClient.isVertexAI()){let i=Ia(this.apiClient,e);return n=B(`{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=Fa(this.apiClient,e);return n=B(`{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=wa(e);return n=B(`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=Ea(e),n=new ir;return Object.assign(n,t),n})}else{let i=Ca(e);return n=B(`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 ir;return Object.assign(n,t),n})}}};function Ra(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 za(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 q(e){return this instanceof q?(this.v=e,this):new q(e)}function J(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 q?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 Y(e){if(!Symbol.asyncIterator)throw TypeError(`Symbol.asyncIterator is not defined.`);var t=e[Symbol.asyncIterator],n;return t?t.call(e):(e=typeof za==`function`?za(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)}}
81
+ /**
82
+ * @license
83
+ * Copyright 2025 Google LLC
84
+ * SPDX-License-Identifier: Apache-2.0
85
+ */
86
+ function Ba(e){if(e.candidates==null||e.candidates.length===0)return!1;let t=e.candidates[0]?.content;return t===void 0?!1:Va(t)}function Va(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 Ha(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 Ua(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&&!Va(e[r])&&(a=!1),r++;a?t.push(...i):t.pop()}return t}var Wa=class{constructor(e,t){this.modelsModule=e,this.apiClient=t}create(e){return new Ga(this.apiClient,this.modelsModule,e.model,e.config,structuredClone(e.history))}},Ga=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(),Ha(i)}async sendMessage(e){await this.sendPromise;let t=G(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=G(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?Ua(this.history):this.history;return structuredClone(t)}processStreamResponse(e,t){return J(this,arguments,function*(){var n,r,i,a;let o=[];try{for(var s=!0,c=Y(e),l;l=yield q(c.next()),n=l.done,!n;s=!0){a=l.value,s=!1;let e=a;if(Ba(e)){let t=e.candidates?.[0]?.content;t!==void 0&&o.push(t)}yield yield q(e)}}catch(e){r={error:e}}finally{try{!s&&!n&&(i=c.return)&&(yield q(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(...Ua(n)):this.history.push(e),this.history.push(...r)}},Ka=class e extends Error{constructor(t){super(t.message),this.name=`ApiError`,this.status=t.status,Object.setPrototypeOf(this,e.prototype)}};
87
+ /**
88
+ * @license
89
+ * Copyright 2025 Google LLC
90
+ * SPDX-License-Identifier: Apache-2.0
91
+ */
92
+ function qa(e){let t={},n=H(e,[`file`]);return n!=null&&V(t,[`file`],n),t}function Ja(e){let t={},n=H(e,[`sdkHttpResponse`]);return n!=null&&V(t,[`sdkHttpResponse`],n),t}function Ya(e){let t={},n=H(e,[`name`]);return n!=null&&V(t,[`_url`,`file`],Hr(n)),t}function Xa(e){let t={},n=H(e,[`sdkHttpResponse`]);return n!=null&&V(t,[`sdkHttpResponse`],n),t}function Za(e){let t={},n=H(e,[`name`]);return n!=null&&V(t,[`_url`,`file`],Hr(n)),t}function Qa(e){let t={},n=H(e,[`uris`]);return n!=null&&V(t,[`uris`],n),t}function $a(e,t){let n={},r=H(e,[`pageSize`]);t!==void 0&&r!=null&&V(t,[`_query`,`pageSize`],r);let i=H(e,[`pageToken`]);return t!==void 0&&i!=null&&V(t,[`_query`,`pageToken`],i),n}function eo(e){let t={},n=H(e,[`config`]);return n!=null&&$a(n,t),t}function to(e){let t={},n=H(e,[`sdkHttpResponse`]);n!=null&&V(t,[`sdkHttpResponse`],n);let r=H(e,[`nextPageToken`]);r!=null&&V(t,[`nextPageToken`],r);let i=H(e,[`files`]);if(i!=null){let e=i;Array.isArray(e)&&(e=e.map(e=>e)),V(t,[`files`],e)}return t}function no(e){let t={},n=H(e,[`sdkHttpResponse`]);n!=null&&V(t,[`sdkHttpResponse`],n);let r=H(e,[`files`]);if(r!=null){let e=r;Array.isArray(e)&&(e=e.map(e=>e)),V(t,[`files`],e)}return t}
93
+ /**
94
+ * @license
95
+ * Copyright 2025 Google LLC
96
+ * SPDX-License-Identifier: Apache-2.0
97
+ */
98
+ var ro=class extends dt{constructor(e){super(),this.apiClient=e,this.list=async(e={})=>new $i(Qi.PAGED_ITEM_FILES,e=>this.listInternal(e),await this.listInternal(e),e)}async upload(e){if(this.apiClient.isVertexAI())throw Error(`Gemini Enterprise Agent Platform (previously known as Vertex AI) does not support uploading files. You can share files through a GCS bucket.`);return this.apiClient.uploadFile(e.file,e.config).then(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=eo(e);return n=B(`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=to(e),n=new lr;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=qa(e);return n=B(`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=Ja(e),n=new ur;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=Za(e);return n=B(`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=Ya(e);return n=B(`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=Xa(e),n=new dr;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=Qa(e);return n=B(`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=no(e),n=new fr;return Object.assign(n,t),n})}}};
99
+ /**
100
+ * @license
101
+ * Copyright 2025 Google LLC
102
+ * SPDX-License-Identifier: Apache-2.0
103
+ */
104
+ function io(e){let t={};if(H(e,[`languageCodes`])!==void 0)throw Error(`languageCodes parameter is not supported in Gemini API.`);return t}function ao(e){let t={},n=H(e,[`apiKey`]);if(n!=null&&V(t,[`apiKey`],n),H(e,[`apiKeyConfig`])!==void 0)throw Error(`apiKeyConfig parameter is not supported in Gemini API.`);if(H(e,[`authType`])!==void 0)throw Error(`authType parameter is not supported in Gemini API.`);if(H(e,[`googleServiceAccountConfig`])!==void 0)throw Error(`googleServiceAccountConfig parameter is not supported in Gemini API.`);if(H(e,[`httpBasicAuthConfig`])!==void 0)throw Error(`httpBasicAuthConfig parameter is not supported in Gemini API.`);if(H(e,[`oauthConfig`])!==void 0)throw Error(`oauthConfig parameter is not supported in Gemini API.`);if(H(e,[`oidcConfig`])!==void 0)throw Error(`oidcConfig parameter is not supported in Gemini API.`);return t}function oo(e){let t={},n=H(e,[`data`]);if(n!=null&&V(t,[`data`],n),H(e,[`displayName`])!==void 0)throw Error(`displayName parameter is not supported in Gemini API.`);let r=H(e,[`mimeType`]);return r!=null&&V(t,[`mimeType`],r),t}function so(e){let t={},n=H(e,[`parts`]);if(n!=null){let e=n;Array.isArray(e)&&(e=e.map(e=>To(e))),V(t,[`parts`],e)}let r=H(e,[`role`]);return r!=null&&V(t,[`role`],r),t}function co(e){let t={},n=H(e,[`parts`]);if(n!=null){let e=n;Array.isArray(e)&&(e=e.map(e=>Eo(e))),V(t,[`parts`],e)}let r=H(e,[`role`]);return r!=null&&V(t,[`role`],r),t}function lo(e){let t={};if(H(e,[`displayName`])!==void 0)throw Error(`displayName parameter is not supported in Gemini API.`);let n=H(e,[`fileUri`]);n!=null&&V(t,[`fileUri`],n);let r=H(e,[`mimeType`]);return r!=null&&V(t,[`mimeType`],r),t}function uo(e){let t={},n=H(e,[`id`]);n!=null&&V(t,[`id`],n);let r=H(e,[`args`]);r!=null&&V(t,[`args`],r);let i=H(e,[`name`]);if(i!=null&&V(t,[`name`],i),H(e,[`partialArgs`])!==void 0)throw Error(`partialArgs parameter is not supported in Gemini API.`);if(H(e,[`willContinue`])!==void 0)throw Error(`willContinue parameter is not supported in Gemini API.`);return t}function fo(e){let t={},n=H(e,[`description`]);n!=null&&V(t,[`description`],n);let r=H(e,[`name`]);r!=null&&V(t,[`name`],r);let i=H(e,[`parameters`]);i!=null&&V(t,[`parameters`],i);let a=H(e,[`parametersJsonSchema`]);a!=null&&V(t,[`parametersJsonSchema`],a);let o=H(e,[`response`]);o!=null&&V(t,[`response`],o);let s=H(e,[`responseJsonSchema`]);if(s!=null&&V(t,[`responseJsonSchema`],s),H(e,[`behavior`])!==void 0)throw Error(`behavior parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).`);return t}function po(e){let t={},n=H(e,[`modelSelectionConfig`]);n!=null&&V(t,[`modelConfig`],n);let r=H(e,[`responseJsonSchema`]);r!=null&&V(t,[`responseJsonSchema`],r);let i=H(e,[`audioTimestamp`]);i!=null&&V(t,[`audioTimestamp`],i);let a=H(e,[`candidateCount`]);a!=null&&V(t,[`candidateCount`],a);let o=H(e,[`enableAffectiveDialog`]);o!=null&&V(t,[`enableAffectiveDialog`],o);let s=H(e,[`frequencyPenalty`]);s!=null&&V(t,[`frequencyPenalty`],s);let c=H(e,[`logprobs`]);c!=null&&V(t,[`logprobs`],c);let l=H(e,[`maxOutputTokens`]);l!=null&&V(t,[`maxOutputTokens`],l);let u=H(e,[`mediaResolution`]);u!=null&&V(t,[`mediaResolution`],u);let d=H(e,[`presencePenalty`]);d!=null&&V(t,[`presencePenalty`],d);let f=H(e,[`responseLogprobs`]);f!=null&&V(t,[`responseLogprobs`],f);let p=H(e,[`responseMimeType`]);p!=null&&V(t,[`responseMimeType`],p);let m=H(e,[`responseModalities`]);m!=null&&V(t,[`responseModalities`],m);let h=H(e,[`responseSchema`]);h!=null&&V(t,[`responseSchema`],h);let g=H(e,[`routingConfig`]);g!=null&&V(t,[`routingConfig`],g);let _=H(e,[`seed`]);_!=null&&V(t,[`seed`],_);let v=H(e,[`speechConfig`]);v!=null&&V(t,[`speechConfig`],v);let y=H(e,[`stopSequences`]);y!=null&&V(t,[`stopSequences`],y);let b=H(e,[`temperature`]);b!=null&&V(t,[`temperature`],b);let x=H(e,[`thinkingConfig`]);x!=null&&V(t,[`thinkingConfig`],x);let S=H(e,[`topK`]);S!=null&&V(t,[`topK`],S);let C=H(e,[`topP`]);if(C!=null&&V(t,[`topP`],C),H(e,[`enableEnhancedCivicAnswers`])!==void 0)throw Error(`enableEnhancedCivicAnswers parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).`);return t}function mo(e){let t={},n=H(e,[`authConfig`]);n!=null&&V(t,[`authConfig`],ao(n));let r=H(e,[`enableWidget`]);return r!=null&&V(t,[`enableWidget`],r),t}function ho(e){let t={},n=H(e,[`searchTypes`]);if(n!=null&&V(t,[`searchTypes`],n),H(e,[`blockingConfidence`])!==void 0)throw Error(`blockingConfidence parameter is not supported in Gemini API.`);if(H(e,[`excludeDomains`])!==void 0)throw Error(`excludeDomains parameter is not supported in Gemini API.`);let r=H(e,[`timeRangeFilter`]);return r!=null&&V(t,[`timeRangeFilter`],r),t}function go(e,t){let n={},r=H(e,[`generationConfig`]);t!==void 0&&r!=null&&V(t,[`setup`,`generationConfig`],r);let i=H(e,[`responseModalities`]);t!==void 0&&i!=null&&V(t,[`setup`,`generationConfig`,`responseModalities`],i);let a=H(e,[`temperature`]);t!==void 0&&a!=null&&V(t,[`setup`,`generationConfig`,`temperature`],a);let o=H(e,[`topP`]);t!==void 0&&o!=null&&V(t,[`setup`,`generationConfig`,`topP`],o);let s=H(e,[`topK`]);t!==void 0&&s!=null&&V(t,[`setup`,`generationConfig`,`topK`],s);let c=H(e,[`maxOutputTokens`]);t!==void 0&&c!=null&&V(t,[`setup`,`generationConfig`,`maxOutputTokens`],c);let l=H(e,[`mediaResolution`]);t!==void 0&&l!=null&&V(t,[`setup`,`generationConfig`,`mediaResolution`],l);let u=H(e,[`seed`]);t!==void 0&&u!=null&&V(t,[`setup`,`generationConfig`,`seed`],u);let d=H(e,[`speechConfig`]);t!==void 0&&d!=null&&V(t,[`setup`,`generationConfig`,`speechConfig`],Mr(d));let f=H(e,[`thinkingConfig`]);t!==void 0&&f!=null&&V(t,[`setup`,`generationConfig`,`thinkingConfig`],f);let p=H(e,[`enableAffectiveDialog`]);t!==void 0&&p!=null&&V(t,[`setup`,`generationConfig`,`enableAffectiveDialog`],p);let m=H(e,[`systemInstruction`]);t!==void 0&&m!=null&&V(t,[`setup`,`systemInstruction`],so(G(m)));let h=H(e,[`tools`]);if(t!==void 0&&h!=null){let e=Pr(h);Array.isArray(e)&&(e=e.map(e=>ko(Nr(e)))),V(t,[`setup`,`tools`],e)}let g=H(e,[`sessionResumption`]);t!==void 0&&g!=null&&V(t,[`setup`,`sessionResumption`],Oo(g));let _=H(e,[`inputAudioTranscription`]);t!==void 0&&_!=null&&V(t,[`setup`,`inputAudioTranscription`],io(_));let v=H(e,[`outputAudioTranscription`]);t!==void 0&&v!=null&&V(t,[`setup`,`outputAudioTranscription`],io(v));let y=H(e,[`realtimeInputConfig`]);t!==void 0&&y!=null&&V(t,[`setup`,`realtimeInputConfig`],y);let b=H(e,[`contextWindowCompression`]);t!==void 0&&b!=null&&V(t,[`setup`,`contextWindowCompression`],b);let x=H(e,[`proactivity`]);if(t!==void 0&&x!=null&&V(t,[`setup`,`proactivity`],x),H(e,[`explicitVadSignal`])!==void 0)throw Error(`explicitVadSignal parameter is not supported in Gemini API.`);let S=H(e,[`avatarConfig`]);t!==void 0&&S!=null&&V(t,[`setup`,`avatarConfig`],S);let C=H(e,[`safetySettings`]);if(t!==void 0&&C!=null){let e=C;Array.isArray(e)&&(e=e.map(e=>Do(e))),V(t,[`setup`,`safetySettings`],e)}return n}function _o(e,t){let n={},r=H(e,[`generationConfig`]);t!==void 0&&r!=null&&V(t,[`setup`,`generationConfig`],po(r));let i=H(e,[`responseModalities`]);t!==void 0&&i!=null&&V(t,[`setup`,`generationConfig`,`responseModalities`],i);let a=H(e,[`temperature`]);t!==void 0&&a!=null&&V(t,[`setup`,`generationConfig`,`temperature`],a);let o=H(e,[`topP`]);t!==void 0&&o!=null&&V(t,[`setup`,`generationConfig`,`topP`],o);let s=H(e,[`topK`]);t!==void 0&&s!=null&&V(t,[`setup`,`generationConfig`,`topK`],s);let c=H(e,[`maxOutputTokens`]);t!==void 0&&c!=null&&V(t,[`setup`,`generationConfig`,`maxOutputTokens`],c);let l=H(e,[`mediaResolution`]);t!==void 0&&l!=null&&V(t,[`setup`,`generationConfig`,`mediaResolution`],l);let u=H(e,[`seed`]);t!==void 0&&u!=null&&V(t,[`setup`,`generationConfig`,`seed`],u);let d=H(e,[`speechConfig`]);t!==void 0&&d!=null&&V(t,[`setup`,`generationConfig`,`speechConfig`],Mr(d));let f=H(e,[`thinkingConfig`]);t!==void 0&&f!=null&&V(t,[`setup`,`generationConfig`,`thinkingConfig`],f);let p=H(e,[`enableAffectiveDialog`]);t!==void 0&&p!=null&&V(t,[`setup`,`generationConfig`,`enableAffectiveDialog`],p);let m=H(e,[`systemInstruction`]);t!==void 0&&m!=null&&V(t,[`setup`,`systemInstruction`],co(G(m)));let h=H(e,[`tools`]);if(t!==void 0&&h!=null){let e=Pr(h);Array.isArray(e)&&(e=e.map(e=>Ao(Nr(e)))),V(t,[`setup`,`tools`],e)}let g=H(e,[`sessionResumption`]);t!==void 0&&g!=null&&V(t,[`setup`,`sessionResumption`],g);let _=H(e,[`inputAudioTranscription`]);t!==void 0&&_!=null&&V(t,[`setup`,`inputAudioTranscription`],_);let v=H(e,[`outputAudioTranscription`]);t!==void 0&&v!=null&&V(t,[`setup`,`outputAudioTranscription`],v);let y=H(e,[`realtimeInputConfig`]);t!==void 0&&y!=null&&V(t,[`setup`,`realtimeInputConfig`],y);let b=H(e,[`contextWindowCompression`]);t!==void 0&&b!=null&&V(t,[`setup`,`contextWindowCompression`],b);let x=H(e,[`proactivity`]);t!==void 0&&x!=null&&V(t,[`setup`,`proactivity`],x);let S=H(e,[`explicitVadSignal`]);t!==void 0&&S!=null&&V(t,[`setup`,`explicitVadSignal`],S);let C=H(e,[`avatarConfig`]);t!==void 0&&C!=null&&V(t,[`setup`,`avatarConfig`],C);let w=H(e,[`safetySettings`]);if(t!==void 0&&w!=null){let e=w;Array.isArray(e)&&(e=e.map(e=>e)),V(t,[`setup`,`safetySettings`],e)}return n}function vo(e,t){let n={},r=H(t,[`model`]);r!=null&&V(n,[`setup`,`model`],W(e,r));let i=H(t,[`config`]);return i!=null&&V(n,[`config`],go(i,n)),n}function yo(e,t){let n={},r=H(t,[`model`]);r!=null&&V(n,[`setup`,`model`],W(e,r));let i=H(t,[`config`]);return i!=null&&V(n,[`config`],_o(i,n)),n}function bo(e){let t={},n=H(e,[`musicGenerationConfig`]);return n!=null&&V(t,[`musicGenerationConfig`],n),t}function xo(e){let t={},n=H(e,[`weightedPrompts`]);if(n!=null){let e=n;Array.isArray(e)&&(e=e.map(e=>e)),V(t,[`weightedPrompts`],e)}return t}function So(e){let t={},n=H(e,[`media`]);if(n!=null){let e=vr(n);Array.isArray(e)&&(e=e.map(e=>oo(e))),V(t,[`mediaChunks`],e)}let r=H(e,[`audio`]);r!=null&&V(t,[`audio`],oo(xr(r)));let i=H(e,[`audioStreamEnd`]);i!=null&&V(t,[`audioStreamEnd`],i);let a=H(e,[`video`]);a!=null&&V(t,[`video`],oo(br(a)));let o=H(e,[`text`]);o!=null&&V(t,[`text`],o);let s=H(e,[`activityStart`]);s!=null&&V(t,[`activityStart`],s);let c=H(e,[`activityEnd`]);return c!=null&&V(t,[`activityEnd`],c),t}function Co(e){let t={},n=H(e,[`media`]);if(n!=null){let e=vr(n);Array.isArray(e)&&(e=e.map(e=>e)),V(t,[`mediaChunks`],e)}let r=H(e,[`audio`]);r!=null&&V(t,[`audio`],xr(r));let i=H(e,[`audioStreamEnd`]);i!=null&&V(t,[`audioStreamEnd`],i);let a=H(e,[`video`]);a!=null&&V(t,[`video`],br(a));let o=H(e,[`text`]);o!=null&&V(t,[`text`],o);let s=H(e,[`activityStart`]);s!=null&&V(t,[`activityStart`],s);let c=H(e,[`activityEnd`]);return c!=null&&V(t,[`activityEnd`],c),t}function wo(e){let t={},n=H(e,[`setupComplete`]);n!=null&&V(t,[`setupComplete`],n);let r=H(e,[`serverContent`]);r!=null&&V(t,[`serverContent`],r);let i=H(e,[`toolCall`]);i!=null&&V(t,[`toolCall`],i);let a=H(e,[`toolCallCancellation`]);a!=null&&V(t,[`toolCallCancellation`],a);let o=H(e,[`usageMetadata`]);o!=null&&V(t,[`usageMetadata`],jo(o));let s=H(e,[`goAway`]);s!=null&&V(t,[`goAway`],s);let c=H(e,[`sessionResumptionUpdate`]);c!=null&&V(t,[`sessionResumptionUpdate`],c);let l=H(e,[`voiceActivityDetectionSignal`]);l!=null&&V(t,[`voiceActivityDetectionSignal`],l);let u=H(e,[`voiceActivity`]);return u!=null&&V(t,[`voiceActivity`],Mo(u)),t}function To(e){let t={},n=H(e,[`mediaResolution`]);n!=null&&V(t,[`mediaResolution`],n);let r=H(e,[`codeExecutionResult`]);r!=null&&V(t,[`codeExecutionResult`],r);let i=H(e,[`executableCode`]);i!=null&&V(t,[`executableCode`],i);let a=H(e,[`fileData`]);a!=null&&V(t,[`fileData`],lo(a));let o=H(e,[`functionCall`]);o!=null&&V(t,[`functionCall`],uo(o));let s=H(e,[`functionResponse`]);s!=null&&V(t,[`functionResponse`],s);let c=H(e,[`inlineData`]);c!=null&&V(t,[`inlineData`],oo(c));let l=H(e,[`text`]);l!=null&&V(t,[`text`],l);let u=H(e,[`thought`]);u!=null&&V(t,[`thought`],u);let d=H(e,[`thoughtSignature`]);d!=null&&V(t,[`thoughtSignature`],d);let f=H(e,[`videoMetadata`]);f!=null&&V(t,[`videoMetadata`],f);let p=H(e,[`toolCall`]);p!=null&&V(t,[`toolCall`],p);let m=H(e,[`toolResponse`]);m!=null&&V(t,[`toolResponse`],m);let h=H(e,[`partMetadata`]);return h!=null&&V(t,[`partMetadata`],h),t}function Eo(e){let t={},n=H(e,[`mediaResolution`]);n!=null&&V(t,[`mediaResolution`],n);let r=H(e,[`codeExecutionResult`]);r!=null&&V(t,[`codeExecutionResult`],r);let i=H(e,[`executableCode`]);i!=null&&V(t,[`executableCode`],i);let a=H(e,[`fileData`]);a!=null&&V(t,[`fileData`],a);let o=H(e,[`functionCall`]);o!=null&&V(t,[`functionCall`],o);let s=H(e,[`functionResponse`]);s!=null&&V(t,[`functionResponse`],s);let c=H(e,[`inlineData`]);c!=null&&V(t,[`inlineData`],c);let l=H(e,[`text`]);l!=null&&V(t,[`text`],l);let u=H(e,[`thought`]);u!=null&&V(t,[`thought`],u);let d=H(e,[`thoughtSignature`]);d!=null&&V(t,[`thoughtSignature`],d);let f=H(e,[`videoMetadata`]);if(f!=null&&V(t,[`videoMetadata`],f),H(e,[`toolCall`])!==void 0)throw Error(`toolCall parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).`);if(H(e,[`toolResponse`])!==void 0)throw Error(`toolResponse parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).`);if(H(e,[`partMetadata`])!==void 0)throw Error(`partMetadata parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).`);return t}function Do(e){let t={},n=H(e,[`category`]);if(n!=null&&V(t,[`category`],n),H(e,[`method`])!==void 0)throw Error(`method parameter is not supported in Gemini API.`);let r=H(e,[`threshold`]);return r!=null&&V(t,[`threshold`],r),t}function Oo(e){let t={},n=H(e,[`handle`]);if(n!=null&&V(t,[`handle`],n),H(e,[`transparent`])!==void 0)throw Error(`transparent parameter is not supported in Gemini API.`);return t}function ko(e){let t={};if(H(e,[`retrieval`])!==void 0)throw Error(`retrieval parameter is not supported in Gemini API.`);let n=H(e,[`computerUse`]);n!=null&&V(t,[`computerUse`],n);let r=H(e,[`fileSearch`]);r!=null&&V(t,[`fileSearch`],r);let i=H(e,[`googleSearch`]);i!=null&&V(t,[`googleSearch`],ho(i));let a=H(e,[`googleMaps`]);a!=null&&V(t,[`googleMaps`],mo(a));let o=H(e,[`codeExecution`]);if(o!=null&&V(t,[`codeExecution`],o),H(e,[`enterpriseWebSearch`])!==void 0)throw Error(`enterpriseWebSearch parameter is not supported in Gemini API.`);let s=H(e,[`functionDeclarations`]);if(s!=null){let e=s;Array.isArray(e)&&(e=e.map(e=>e)),V(t,[`functionDeclarations`],e)}let c=H(e,[`googleSearchRetrieval`]);if(c!=null&&V(t,[`googleSearchRetrieval`],c),H(e,[`parallelAiSearch`])!==void 0)throw Error(`parallelAiSearch parameter is not supported in Gemini API.`);let l=H(e,[`urlContext`]);l!=null&&V(t,[`urlContext`],l);let u=H(e,[`mcpServers`]);if(u!=null){let e=u;Array.isArray(e)&&(e=e.map(e=>e)),V(t,[`mcpServers`],e)}return t}function Ao(e){let t={},n=H(e,[`retrieval`]);n!=null&&V(t,[`retrieval`],n);let r=H(e,[`computerUse`]);if(r!=null&&V(t,[`computerUse`],r),H(e,[`fileSearch`])!==void 0)throw Error(`fileSearch parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).`);let i=H(e,[`googleSearch`]);i!=null&&V(t,[`googleSearch`],i);let a=H(e,[`googleMaps`]);a!=null&&V(t,[`googleMaps`],a);let o=H(e,[`codeExecution`]);o!=null&&V(t,[`codeExecution`],o);let s=H(e,[`enterpriseWebSearch`]);s!=null&&V(t,[`enterpriseWebSearch`],s);let c=H(e,[`functionDeclarations`]);if(c!=null){let e=c;Array.isArray(e)&&(e=e.map(e=>fo(e))),V(t,[`functionDeclarations`],e)}let l=H(e,[`googleSearchRetrieval`]);l!=null&&V(t,[`googleSearchRetrieval`],l);let u=H(e,[`parallelAiSearch`]);u!=null&&V(t,[`parallelAiSearch`],u);let d=H(e,[`urlContext`]);if(d!=null&&V(t,[`urlContext`],d),H(e,[`mcpServers`])!==void 0)throw Error(`mcpServers parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).`);return t}function jo(e){let t={},n=H(e,[`promptTokenCount`]);n!=null&&V(t,[`promptTokenCount`],n);let r=H(e,[`cachedContentTokenCount`]);r!=null&&V(t,[`cachedContentTokenCount`],r);let i=H(e,[`candidatesTokenCount`]);i!=null&&V(t,[`responseTokenCount`],i);let a=H(e,[`toolUsePromptTokenCount`]);a!=null&&V(t,[`toolUsePromptTokenCount`],a);let o=H(e,[`thoughtsTokenCount`]);o!=null&&V(t,[`thoughtsTokenCount`],o);let s=H(e,[`totalTokenCount`]);s!=null&&V(t,[`totalTokenCount`],s);let c=H(e,[`promptTokensDetails`]);if(c!=null){let e=c;Array.isArray(e)&&(e=e.map(e=>e)),V(t,[`promptTokensDetails`],e)}let l=H(e,[`cacheTokensDetails`]);if(l!=null){let e=l;Array.isArray(e)&&(e=e.map(e=>e)),V(t,[`cacheTokensDetails`],e)}let u=H(e,[`candidatesTokensDetails`]);if(u!=null){let e=u;Array.isArray(e)&&(e=e.map(e=>e)),V(t,[`responseTokensDetails`],e)}let d=H(e,[`toolUsePromptTokensDetails`]);if(d!=null){let e=d;Array.isArray(e)&&(e=e.map(e=>e)),V(t,[`toolUsePromptTokensDetails`],e)}let f=H(e,[`trafficType`]);return f!=null&&V(t,[`trafficType`],f),t}function Mo(e){let t={},n=H(e,[`type`]);return n!=null&&V(t,[`voiceActivityType`],n),t}
105
+ /**
106
+ * @license
107
+ * Copyright 2025 Google LLC
108
+ * SPDX-License-Identifier: Apache-2.0
109
+ */
110
+ function No(e,t){let n={},r=H(e,[`apiKey`]);if(r!=null&&V(n,[`apiKey`],r),H(e,[`apiKeyConfig`])!==void 0)throw Error(`apiKeyConfig parameter is not supported in Gemini API.`);if(H(e,[`authType`])!==void 0)throw Error(`authType parameter is not supported in Gemini API.`);if(H(e,[`googleServiceAccountConfig`])!==void 0)throw Error(`googleServiceAccountConfig parameter is not supported in Gemini API.`);if(H(e,[`httpBasicAuthConfig`])!==void 0)throw Error(`httpBasicAuthConfig parameter is not supported in Gemini API.`);if(H(e,[`oauthConfig`])!==void 0)throw Error(`oauthConfig parameter is not supported in Gemini API.`);if(H(e,[`oidcConfig`])!==void 0)throw Error(`oidcConfig parameter is not supported in Gemini API.`);return n}function Po(e,t){let n={},r=H(e,[`data`]);if(r!=null&&V(n,[`data`],r),H(e,[`displayName`])!==void 0)throw Error(`displayName parameter is not supported in Gemini API.`);let i=H(e,[`mimeType`]);return i!=null&&V(n,[`mimeType`],i),n}function Fo(e,t){let n={},r=H(e,[`content`]);r!=null&&V(n,[`content`],r);let i=H(e,[`citationMetadata`]);i!=null&&V(n,[`citationMetadata`],Io(i));let a=H(e,[`tokenCount`]);a!=null&&V(n,[`tokenCount`],a);let o=H(e,[`finishReason`]);o!=null&&V(n,[`finishReason`],o);let s=H(e,[`groundingMetadata`]);s!=null&&V(n,[`groundingMetadata`],s);let c=H(e,[`avgLogprobs`]);c!=null&&V(n,[`avgLogprobs`],c);let l=H(e,[`index`]);l!=null&&V(n,[`index`],l);let u=H(e,[`logprobsResult`]);u!=null&&V(n,[`logprobsResult`],u);let d=H(e,[`safetyRatings`]);if(d!=null){let e=d;Array.isArray(e)&&(e=e.map(e=>e)),V(n,[`safetyRatings`],e)}let f=H(e,[`urlContextMetadata`]);return f!=null&&V(n,[`urlContextMetadata`],f),n}function Io(e,t){let n={},r=H(e,[`citationSources`]);if(r!=null){let e=r;Array.isArray(e)&&(e=e.map(e=>e)),V(n,[`citations`],e)}return n}function Lo(e,t,n){let r={},i=H(t,[`model`]);i!=null&&V(r,[`_url`,`model`],W(e,i));let a=H(t,[`contents`]);if(a!=null){let e=K(a);Array.isArray(e)&&(e=e.map(e=>Ho(e))),V(r,[`contents`],e)}return r}function Ro(e,t){let n={},r=H(e,[`sdkHttpResponse`]);r!=null&&V(n,[`sdkHttpResponse`],r);let i=H(e,[`tokensInfo`]);if(i!=null){let e=i;Array.isArray(e)&&(e=e.map(e=>e)),V(n,[`tokensInfo`],e)}return n}function zo(e,t){let n={},r=H(e,[`values`]);r!=null&&V(n,[`values`],r);let i=H(e,[`statistics`]);return i!=null&&V(n,[`statistics`],Bo(i)),n}function Bo(e,t){let n={},r=H(e,[`truncated`]);r!=null&&V(n,[`truncated`],r);let i=H(e,[`token_count`]);return i!=null&&V(n,[`tokenCount`],i),n}function Vo(e,t){let n={},r=H(e,[`parts`]);if(r!=null){let e=r;Array.isArray(e)&&(e=e.map(e=>sc(e))),V(n,[`parts`],e)}let i=H(e,[`role`]);return i!=null&&V(n,[`role`],i),n}function Ho(e,t){let n={},r=H(e,[`parts`]);if(r!=null){let e=r;Array.isArray(e)&&(e=e.map(e=>cc(e))),V(n,[`parts`],e)}let i=H(e,[`role`]);return i!=null&&V(n,[`role`],i),n}function Uo(e,t){let n={},r=H(e,[`controlType`]);r!=null&&V(n,[`controlType`],r);let i=H(e,[`enableControlImageComputation`]);return i!=null&&V(n,[`computeControl`],i),n}function Wo(e,t){let n={};if(H(e,[`systemInstruction`])!==void 0)throw Error(`systemInstruction parameter is not supported in Gemini API.`);if(H(e,[`tools`])!==void 0)throw Error(`tools parameter is not supported in Gemini API.`);if(H(e,[`generationConfig`])!==void 0)throw Error(`generationConfig parameter is not supported in Gemini API.`);return n}function Go(e,t,n){let r={},i=H(e,[`systemInstruction`]);t!==void 0&&i!=null&&V(t,[`systemInstruction`],Ho(G(i)));let a=H(e,[`tools`]);if(t!==void 0&&a!=null){let e=a;Array.isArray(e)&&(e=e.map(e=>Ec(e))),V(t,[`tools`],e)}let o=H(e,[`generationConfig`]);return t!==void 0&&o!=null&&V(t,[`generationConfig`],Vs(o)),r}function Ko(e,t,n){let r={},i=H(t,[`model`]);i!=null&&V(r,[`_url`,`model`],W(e,i));let a=H(t,[`contents`]);if(a!=null){let e=K(a);Array.isArray(e)&&(e=e.map(e=>Vo(e))),V(r,[`contents`],e)}let o=H(t,[`config`]);return o!=null&&Wo(o),r}function qo(e,t,n){let r={},i=H(t,[`model`]);i!=null&&V(r,[`_url`,`model`],W(e,i));let a=H(t,[`contents`]);if(a!=null){let e=K(a);Array.isArray(e)&&(e=e.map(e=>Ho(e))),V(r,[`contents`],e)}let o=H(t,[`config`]);return o!=null&&Go(o,r),r}function Jo(e,t){let n={},r=H(e,[`sdkHttpResponse`]);r!=null&&V(n,[`sdkHttpResponse`],r);let i=H(e,[`totalTokens`]);i!=null&&V(n,[`totalTokens`],i);let a=H(e,[`cachedContentTokenCount`]);return a!=null&&V(n,[`cachedContentTokenCount`],a),n}function Yo(e,t){let n={},r=H(e,[`sdkHttpResponse`]);r!=null&&V(n,[`sdkHttpResponse`],r);let i=H(e,[`totalTokens`]);return i!=null&&V(n,[`totalTokens`],i),n}function Xo(e,t,n){let r={},i=H(t,[`model`]);return i!=null&&V(r,[`_url`,`name`],W(e,i)),r}function Zo(e,t,n){let r={},i=H(t,[`model`]);return i!=null&&V(r,[`_url`,`name`],W(e,i)),r}function Qo(e,t){let n={},r=H(e,[`sdkHttpResponse`]);return r!=null&&V(n,[`sdkHttpResponse`],r),n}function $o(e,t){let n={},r=H(e,[`sdkHttpResponse`]);return r!=null&&V(n,[`sdkHttpResponse`],r),n}function es(e,t,n){let r={},i=H(e,[`outputGcsUri`]);t!==void 0&&i!=null&&V(t,[`parameters`,`storageUri`],i);let a=H(e,[`negativePrompt`]);t!==void 0&&a!=null&&V(t,[`parameters`,`negativePrompt`],a);let o=H(e,[`numberOfImages`]);t!==void 0&&o!=null&&V(t,[`parameters`,`sampleCount`],o);let s=H(e,[`aspectRatio`]);t!==void 0&&s!=null&&V(t,[`parameters`,`aspectRatio`],s);let c=H(e,[`guidanceScale`]);t!==void 0&&c!=null&&V(t,[`parameters`,`guidanceScale`],c);let l=H(e,[`seed`]);t!==void 0&&l!=null&&V(t,[`parameters`,`seed`],l);let u=H(e,[`safetyFilterLevel`]);t!==void 0&&u!=null&&V(t,[`parameters`,`safetySetting`],u);let d=H(e,[`personGeneration`]);t!==void 0&&d!=null&&V(t,[`parameters`,`personGeneration`],d);let f=H(e,[`includeSafetyAttributes`]);t!==void 0&&f!=null&&V(t,[`parameters`,`includeSafetyAttributes`],f);let p=H(e,[`includeRaiReason`]);t!==void 0&&p!=null&&V(t,[`parameters`,`includeRaiReason`],p);let m=H(e,[`language`]);t!==void 0&&m!=null&&V(t,[`parameters`,`language`],m);let h=H(e,[`outputMimeType`]);t!==void 0&&h!=null&&V(t,[`parameters`,`outputOptions`,`mimeType`],h);let g=H(e,[`outputCompressionQuality`]);t!==void 0&&g!=null&&V(t,[`parameters`,`outputOptions`,`compressionQuality`],g);let _=H(e,[`addWatermark`]);t!==void 0&&_!=null&&V(t,[`parameters`,`addWatermark`],_);let v=H(e,[`labels`]);t!==void 0&&v!=null&&V(t,[`labels`],v);let y=H(e,[`editMode`]);t!==void 0&&y!=null&&V(t,[`parameters`,`editMode`],y);let b=H(e,[`baseSteps`]);return t!==void 0&&b!=null&&V(t,[`parameters`,`editConfig`,`baseSteps`],b),r}function ts(e,t,n){let r={},i=H(t,[`model`]);i!=null&&V(r,[`_url`,`model`],W(e,i));let a=H(t,[`prompt`]);a!=null&&V(r,[`instances[0]`,`prompt`],a);let o=H(t,[`referenceImages`]);if(o!=null){let e=o;Array.isArray(e)&&(e=e.map(e=>mc(e))),V(r,[`instances[0]`,`referenceImages`],e)}let s=H(t,[`config`]);return s!=null&&es(s,r),r}function ns(e,t){let n={},r=H(e,[`sdkHttpResponse`]);r!=null&&V(n,[`sdkHttpResponse`],r);let i=H(e,[`predictions`]);if(i!=null){let e=i;Array.isArray(e)&&(e=e.map(e=>Ls(e))),V(n,[`generatedImages`],e)}return n}function rs(e,t,n){let r={},i=H(e,[`taskType`]);t!==void 0&&i!=null&&V(t,[`requests[]`,`taskType`],i);let a=H(e,[`title`]);t!==void 0&&a!=null&&V(t,[`requests[]`,`title`],a);let o=H(e,[`outputDimensionality`]);if(t!==void 0&&o!=null&&V(t,[`requests[]`,`outputDimensionality`],o),H(e,[`mimeType`])!==void 0)throw Error(`mimeType parameter is not supported in Gemini API.`);if(H(e,[`autoTruncate`])!==void 0)throw Error(`autoTruncate parameter is not supported in Gemini API.`);if(H(e,[`documentOcr`])!==void 0)throw Error(`documentOcr parameter is not supported in Gemini API.`);if(H(e,[`audioTrackExtraction`])!==void 0)throw Error(`audioTrackExtraction parameter is not supported in Gemini API.`);return r}function is(e,t,n){let r={},i=H(n,[`embeddingApiType`]);if(i===void 0&&(i=`PREDICT`),i===`PREDICT`){let n=H(e,[`taskType`]);t!==void 0&&n!=null&&V(t,[`instances[]`,`task_type`],n)}else if(i===`EMBED_CONTENT`){let n=H(e,[`taskType`]);t!==void 0&&n!=null&&V(t,[`embedContentConfig`,`taskType`],n)}let a=H(n,[`embeddingApiType`]);if(a===void 0&&(a=`PREDICT`),a===`PREDICT`){let n=H(e,[`title`]);t!==void 0&&n!=null&&V(t,[`instances[]`,`title`],n)}else if(a===`EMBED_CONTENT`){let n=H(e,[`title`]);t!==void 0&&n!=null&&V(t,[`embedContentConfig`,`title`],n)}let o=H(n,[`embeddingApiType`]);if(o===void 0&&(o=`PREDICT`),o===`PREDICT`){let n=H(e,[`outputDimensionality`]);t!==void 0&&n!=null&&V(t,[`parameters`,`outputDimensionality`],n)}else if(o===`EMBED_CONTENT`){let n=H(e,[`outputDimensionality`]);t!==void 0&&n!=null&&V(t,[`embedContentConfig`,`outputDimensionality`],n)}let s=H(n,[`embeddingApiType`]);if(s===void 0&&(s=`PREDICT`),s===`PREDICT`){let n=H(e,[`mimeType`]);t!==void 0&&n!=null&&V(t,[`instances[]`,`mimeType`],n)}let c=H(n,[`embeddingApiType`]);if(c===void 0&&(c=`PREDICT`),c===`PREDICT`){let n=H(e,[`autoTruncate`]);t!==void 0&&n!=null&&V(t,[`parameters`,`autoTruncate`],n)}else if(c===`EMBED_CONTENT`){let n=H(e,[`autoTruncate`]);t!==void 0&&n!=null&&V(t,[`embedContentConfig`,`autoTruncate`],n)}let l=H(n,[`embeddingApiType`]);if(l===void 0&&(l=`PREDICT`),l===`EMBED_CONTENT`){let n=H(e,[`documentOcr`]);t!==void 0&&n!=null&&V(t,[`embedContentConfig`,`documentOcr`],n)}let u=H(n,[`embeddingApiType`]);if(u===void 0&&(u=`PREDICT`),u===`EMBED_CONTENT`){let n=H(e,[`audioTrackExtraction`]);t!==void 0&&n!=null&&V(t,[`embedContentConfig`,`audioTrackExtraction`],n)}return r}function as(e,t,n){let r={},i=H(t,[`model`]);i!=null&&V(r,[`_url`,`model`],W(e,i));let a=H(t,[`contents`]);if(a!=null){let t=Dr(e,a);Array.isArray(t)&&(t=t.map(e=>e)),V(r,[`requests[]`,`content`],t)}let o=H(t,[`content`]);o!=null&&Vo(G(o));let s=H(t,[`config`]);s!=null&&rs(s,r);let c=H(t,[`model`]);return c!==void 0&&V(r,[`requests[]`,`model`],W(e,c)),r}function os(e,t,n){let r={},i=H(t,[`model`]);i!=null&&V(r,[`_url`,`model`],W(e,i));let a=H(n,[`embeddingApiType`]);if(a===void 0&&(a=`PREDICT`),a===`PREDICT`){let n=H(t,[`contents`]);if(n!=null){let t=Dr(e,n);Array.isArray(t)&&(t=t.map(e=>e)),V(r,[`instances[]`,`content`],t)}}let o=H(n,[`embeddingApiType`]);if(o===void 0&&(o=`PREDICT`),o===`EMBED_CONTENT`){let e=H(t,[`content`]);e!=null&&V(r,[`content`],Ho(G(e)))}let s=H(t,[`config`]);return s!=null&&is(s,r,n),r}function ss(e,t){let n={},r=H(e,[`sdkHttpResponse`]);r!=null&&V(n,[`sdkHttpResponse`],r);let i=H(e,[`embeddings`]);if(i!=null){let e=i;Array.isArray(e)&&(e=e.map(e=>e)),V(n,[`embeddings`],e)}let a=H(e,[`metadata`]);return a!=null&&V(n,[`metadata`],a),n}function cs(e,t){let n={},r=H(e,[`sdkHttpResponse`]);r!=null&&V(n,[`sdkHttpResponse`],r);let i=H(e,[`predictions[]`,`embeddings`]);if(i!=null){let e=i;Array.isArray(e)&&(e=e.map(e=>zo(e))),V(n,[`embeddings`],e)}let a=H(e,[`metadata`]);if(a!=null&&V(n,[`metadata`],a),t&&H(t,[`embeddingApiType`])===`EMBED_CONTENT`){let t=H(e,[`embedding`]),r=H(e,[`usageMetadata`]),i=H(e,[`truncated`]);if(t){let e={};r&&r.promptTokenCount&&(e.tokenCount=r.promptTokenCount),i&&(e.truncated=i),t.statistics=e,V(n,[`embeddings`],[t])}}return n}function ls(e,t){let n={},r=H(e,[`endpoint`]);r!=null&&V(n,[`name`],r);let i=H(e,[`deployedModelId`]);return i!=null&&V(n,[`deployedModelId`],i),n}function us(e,t){let n={};if(H(e,[`displayName`])!==void 0)throw Error(`displayName parameter is not supported in Gemini API.`);let r=H(e,[`fileUri`]);r!=null&&V(n,[`fileUri`],r);let i=H(e,[`mimeType`]);return i!=null&&V(n,[`mimeType`],i),n}function ds(e,t){let n={},r=H(e,[`id`]);r!=null&&V(n,[`id`],r);let i=H(e,[`args`]);i!=null&&V(n,[`args`],i);let a=H(e,[`name`]);if(a!=null&&V(n,[`name`],a),H(e,[`partialArgs`])!==void 0)throw Error(`partialArgs parameter is not supported in Gemini API.`);if(H(e,[`willContinue`])!==void 0)throw Error(`willContinue parameter is not supported in Gemini API.`);return n}function fs(e,t){let n={},r=H(e,[`allowedFunctionNames`]);r!=null&&V(n,[`allowedFunctionNames`],r);let i=H(e,[`mode`]);if(i!=null&&V(n,[`mode`],i),H(e,[`streamFunctionCallArguments`])!==void 0)throw Error(`streamFunctionCallArguments parameter is not supported in Gemini API.`);return n}function ps(e,t){let n={},r=H(e,[`description`]);r!=null&&V(n,[`description`],r);let i=H(e,[`name`]);i!=null&&V(n,[`name`],i);let a=H(e,[`parameters`]);a!=null&&V(n,[`parameters`],a);let o=H(e,[`parametersJsonSchema`]);o!=null&&V(n,[`parametersJsonSchema`],o);let s=H(e,[`response`]);s!=null&&V(n,[`response`],s);let c=H(e,[`responseJsonSchema`]);if(c!=null&&V(n,[`responseJsonSchema`],c),H(e,[`behavior`])!==void 0)throw Error(`behavior parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).`);return n}function ms(e,t,n,r){let i={},a=H(t,[`systemInstruction`]);n!==void 0&&a!=null&&V(n,[`systemInstruction`],Vo(G(a)));let o=H(t,[`temperature`]);o!=null&&V(i,[`temperature`],o);let s=H(t,[`topP`]);s!=null&&V(i,[`topP`],s);let c=H(t,[`topK`]);c!=null&&V(i,[`topK`],c);let l=H(t,[`candidateCount`]);l!=null&&V(i,[`candidateCount`],l);let u=H(t,[`maxOutputTokens`]);u!=null&&V(i,[`maxOutputTokens`],u);let d=H(t,[`stopSequences`]);d!=null&&V(i,[`stopSequences`],d);let f=H(t,[`responseLogprobs`]);f!=null&&V(i,[`responseLogprobs`],f);let p=H(t,[`logprobs`]);p!=null&&V(i,[`logprobs`],p);let m=H(t,[`presencePenalty`]);m!=null&&V(i,[`presencePenalty`],m);let h=H(t,[`frequencyPenalty`]);h!=null&&V(i,[`frequencyPenalty`],h);let g=H(t,[`seed`]);g!=null&&V(i,[`seed`],g);let _=H(t,[`responseMimeType`]);_!=null&&V(i,[`responseMimeType`],_);let v=H(t,[`responseSchema`]);v!=null&&V(i,[`responseSchema`],Ar(v));let y=H(t,[`responseJsonSchema`]);if(y!=null&&V(i,[`responseJsonSchema`],y),H(t,[`routingConfig`])!==void 0)throw Error(`routingConfig parameter is not supported in Gemini API.`);if(H(t,[`modelSelectionConfig`])!==void 0)throw Error(`modelSelectionConfig parameter is not supported in Gemini API.`);let b=H(t,[`safetySettings`]);if(n!==void 0&&b!=null){let e=b;Array.isArray(e)&&(e=e.map(e=>_c(e))),V(n,[`safetySettings`],e)}let x=H(t,[`tools`]);if(n!==void 0&&x!=null){let e=Pr(x);Array.isArray(e)&&(e=e.map(e=>Tc(Nr(e)))),V(n,[`tools`],e)}let S=H(t,[`toolConfig`]);if(n!==void 0&&S!=null&&V(n,[`toolConfig`],Cc(S)),H(t,[`labels`])!==void 0)throw Error(`labels parameter is not supported in Gemini API.`);let C=H(t,[`cachedContent`]);n!==void 0&&C!=null&&V(n,[`cachedContent`],Ir(e,C));let w=H(t,[`responseModalities`]);w!=null&&V(i,[`responseModalities`],w);let T=H(t,[`mediaResolution`]);T!=null&&V(i,[`mediaResolution`],T);let E=H(t,[`speechConfig`]);if(E!=null&&V(i,[`speechConfig`],jr(E)),H(t,[`audioTimestamp`])!==void 0)throw Error(`audioTimestamp parameter is not supported in Gemini API.`);let D=H(t,[`thinkingConfig`]);D!=null&&V(i,[`thinkingConfig`],D);let O=H(t,[`imageConfig`]);O!=null&&V(i,[`imageConfig`],Ks(O));let k=H(t,[`enableEnhancedCivicAnswers`]);if(k!=null&&V(i,[`enableEnhancedCivicAnswers`],k),H(t,[`modelArmorConfig`])!==void 0)throw Error(`modelArmorConfig parameter is not supported in Gemini API.`);let A=H(t,[`serviceTier`]);return n!==void 0&&A!=null&&V(n,[`serviceTier`],A),i}function hs(e,t,n,r){let i={},a=H(t,[`systemInstruction`]);n!==void 0&&a!=null&&V(n,[`systemInstruction`],Ho(G(a)));let o=H(t,[`temperature`]);o!=null&&V(i,[`temperature`],o);let s=H(t,[`topP`]);s!=null&&V(i,[`topP`],s);let c=H(t,[`topK`]);c!=null&&V(i,[`topK`],c);let l=H(t,[`candidateCount`]);l!=null&&V(i,[`candidateCount`],l);let u=H(t,[`maxOutputTokens`]);u!=null&&V(i,[`maxOutputTokens`],u);let d=H(t,[`stopSequences`]);d!=null&&V(i,[`stopSequences`],d);let f=H(t,[`responseLogprobs`]);f!=null&&V(i,[`responseLogprobs`],f);let p=H(t,[`logprobs`]);p!=null&&V(i,[`logprobs`],p);let m=H(t,[`presencePenalty`]);m!=null&&V(i,[`presencePenalty`],m);let h=H(t,[`frequencyPenalty`]);h!=null&&V(i,[`frequencyPenalty`],h);let g=H(t,[`seed`]);g!=null&&V(i,[`seed`],g);let _=H(t,[`responseMimeType`]);_!=null&&V(i,[`responseMimeType`],_);let v=H(t,[`responseSchema`]);v!=null&&V(i,[`responseSchema`],Ar(v));let y=H(t,[`responseJsonSchema`]);y!=null&&V(i,[`responseJsonSchema`],y);let b=H(t,[`routingConfig`]);b!=null&&V(i,[`routingConfig`],b);let x=H(t,[`modelSelectionConfig`]);x!=null&&V(i,[`modelConfig`],x);let S=H(t,[`safetySettings`]);if(n!==void 0&&S!=null){let e=S;Array.isArray(e)&&(e=e.map(e=>e)),V(n,[`safetySettings`],e)}let C=H(t,[`tools`]);if(n!==void 0&&C!=null){let e=Pr(C);Array.isArray(e)&&(e=e.map(e=>Ec(Nr(e)))),V(n,[`tools`],e)}let w=H(t,[`toolConfig`]);n!==void 0&&w!=null&&V(n,[`toolConfig`],wc(w));let T=H(t,[`labels`]);n!==void 0&&T!=null&&V(n,[`labels`],T);let E=H(t,[`cachedContent`]);n!==void 0&&E!=null&&V(n,[`cachedContent`],Ir(e,E));let D=H(t,[`responseModalities`]);D!=null&&V(i,[`responseModalities`],D);let O=H(t,[`mediaResolution`]);O!=null&&V(i,[`mediaResolution`],O);let k=H(t,[`speechConfig`]);k!=null&&V(i,[`speechConfig`],jr(k));let A=H(t,[`audioTimestamp`]);A!=null&&V(i,[`audioTimestamp`],A);let j=H(t,[`thinkingConfig`]);j!=null&&V(i,[`thinkingConfig`],j);let M=H(t,[`imageConfig`]);if(M!=null&&V(i,[`imageConfig`],qs(M)),H(t,[`enableEnhancedCivicAnswers`])!==void 0)throw Error(`enableEnhancedCivicAnswers parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).`);let N=H(t,[`modelArmorConfig`]);n!==void 0&&N!=null&&V(n,[`modelArmorConfig`],N);let ee=H(t,[`serviceTier`]);return n!==void 0&&ee!=null&&V(n,[`serviceTier`],ee),i}function gs(e,t,n){let r={},i=H(t,[`model`]);i!=null&&V(r,[`_url`,`model`],W(e,i));let a=H(t,[`contents`]);if(a!=null){let e=K(a);Array.isArray(e)&&(e=e.map(e=>Vo(e))),V(r,[`contents`],e)}let o=H(t,[`config`]);return o!=null&&V(r,[`generationConfig`],ms(e,o,r)),r}function _s(e,t,n){let r={},i=H(t,[`model`]);i!=null&&V(r,[`_url`,`model`],W(e,i));let a=H(t,[`contents`]);if(a!=null){let e=K(a);Array.isArray(e)&&(e=e.map(e=>Ho(e))),V(r,[`contents`],e)}let o=H(t,[`config`]);return o!=null&&V(r,[`generationConfig`],hs(e,o,r)),r}function vs(e,t){let n={},r=H(e,[`sdkHttpResponse`]);r!=null&&V(n,[`sdkHttpResponse`],r);let i=H(e,[`candidates`]);if(i!=null){let e=i;Array.isArray(e)&&(e=e.map(e=>Fo(e))),V(n,[`candidates`],e)}let a=H(e,[`modelVersion`]);a!=null&&V(n,[`modelVersion`],a);let o=H(e,[`promptFeedback`]);o!=null&&V(n,[`promptFeedback`],o);let s=H(e,[`responseId`]);s!=null&&V(n,[`responseId`],s);let c=H(e,[`usageMetadata`]);c!=null&&V(n,[`usageMetadata`],c);let l=H(e,[`modelStatus`]);return l!=null&&V(n,[`modelStatus`],l),n}function ys(e,t){let n={},r=H(e,[`sdkHttpResponse`]);r!=null&&V(n,[`sdkHttpResponse`],r);let i=H(e,[`candidates`]);if(i!=null){let e=i;Array.isArray(e)&&(e=e.map(e=>e)),V(n,[`candidates`],e)}let a=H(e,[`createTime`]);a!=null&&V(n,[`createTime`],a);let o=H(e,[`modelVersion`]);o!=null&&V(n,[`modelVersion`],o);let s=H(e,[`promptFeedback`]);s!=null&&V(n,[`promptFeedback`],s);let c=H(e,[`responseId`]);c!=null&&V(n,[`responseId`],c);let l=H(e,[`usageMetadata`]);return l!=null&&V(n,[`usageMetadata`],l),n}function bs(e,t,n){let r={};if(H(e,[`outputGcsUri`])!==void 0)throw Error(`outputGcsUri parameter is not supported in Gemini API.`);if(H(e,[`negativePrompt`])!==void 0)throw Error(`negativePrompt parameter is not supported in Gemini API.`);let i=H(e,[`numberOfImages`]);t!==void 0&&i!=null&&V(t,[`parameters`,`sampleCount`],i);let a=H(e,[`aspectRatio`]);t!==void 0&&a!=null&&V(t,[`parameters`,`aspectRatio`],a);let o=H(e,[`guidanceScale`]);if(t!==void 0&&o!=null&&V(t,[`parameters`,`guidanceScale`],o),H(e,[`seed`])!==void 0)throw Error(`seed parameter is not supported in Gemini API.`);let s=H(e,[`safetyFilterLevel`]);t!==void 0&&s!=null&&V(t,[`parameters`,`safetySetting`],s);let c=H(e,[`personGeneration`]);t!==void 0&&c!=null&&V(t,[`parameters`,`personGeneration`],c);let l=H(e,[`includeSafetyAttributes`]);t!==void 0&&l!=null&&V(t,[`parameters`,`includeSafetyAttributes`],l);let u=H(e,[`includeRaiReason`]);t!==void 0&&u!=null&&V(t,[`parameters`,`includeRaiReason`],u);let d=H(e,[`language`]);t!==void 0&&d!=null&&V(t,[`parameters`,`language`],d);let f=H(e,[`outputMimeType`]);t!==void 0&&f!=null&&V(t,[`parameters`,`outputOptions`,`mimeType`],f);let p=H(e,[`outputCompressionQuality`]);if(t!==void 0&&p!=null&&V(t,[`parameters`,`outputOptions`,`compressionQuality`],p),H(e,[`addWatermark`])!==void 0)throw Error(`addWatermark parameter is not supported in Gemini API.`);if(H(e,[`labels`])!==void 0)throw Error(`labels parameter is not supported in Gemini API.`);let m=H(e,[`imageSize`]);if(t!==void 0&&m!=null&&V(t,[`parameters`,`sampleImageSize`],m),H(e,[`enhancePrompt`])!==void 0)throw Error(`enhancePrompt parameter is not supported in Gemini API.`);return r}function xs(e,t,n){let r={},i=H(e,[`outputGcsUri`]);t!==void 0&&i!=null&&V(t,[`parameters`,`storageUri`],i);let a=H(e,[`negativePrompt`]);t!==void 0&&a!=null&&V(t,[`parameters`,`negativePrompt`],a);let o=H(e,[`numberOfImages`]);t!==void 0&&o!=null&&V(t,[`parameters`,`sampleCount`],o);let s=H(e,[`aspectRatio`]);t!==void 0&&s!=null&&V(t,[`parameters`,`aspectRatio`],s);let c=H(e,[`guidanceScale`]);t!==void 0&&c!=null&&V(t,[`parameters`,`guidanceScale`],c);let l=H(e,[`seed`]);t!==void 0&&l!=null&&V(t,[`parameters`,`seed`],l);let u=H(e,[`safetyFilterLevel`]);t!==void 0&&u!=null&&V(t,[`parameters`,`safetySetting`],u);let d=H(e,[`personGeneration`]);t!==void 0&&d!=null&&V(t,[`parameters`,`personGeneration`],d);let f=H(e,[`includeSafetyAttributes`]);t!==void 0&&f!=null&&V(t,[`parameters`,`includeSafetyAttributes`],f);let p=H(e,[`includeRaiReason`]);t!==void 0&&p!=null&&V(t,[`parameters`,`includeRaiReason`],p);let m=H(e,[`language`]);t!==void 0&&m!=null&&V(t,[`parameters`,`language`],m);let h=H(e,[`outputMimeType`]);t!==void 0&&h!=null&&V(t,[`parameters`,`outputOptions`,`mimeType`],h);let g=H(e,[`outputCompressionQuality`]);t!==void 0&&g!=null&&V(t,[`parameters`,`outputOptions`,`compressionQuality`],g);let _=H(e,[`addWatermark`]);t!==void 0&&_!=null&&V(t,[`parameters`,`addWatermark`],_);let v=H(e,[`labels`]);t!==void 0&&v!=null&&V(t,[`labels`],v);let y=H(e,[`imageSize`]);t!==void 0&&y!=null&&V(t,[`parameters`,`sampleImageSize`],y);let b=H(e,[`enhancePrompt`]);return t!==void 0&&b!=null&&V(t,[`parameters`,`enhancePrompt`],b),r}function Ss(e,t,n){let r={},i=H(t,[`model`]);i!=null&&V(r,[`_url`,`model`],W(e,i));let a=H(t,[`prompt`]);a!=null&&V(r,[`instances[0]`,`prompt`],a);let o=H(t,[`config`]);return o!=null&&bs(o,r),r}function Cs(e,t,n){let r={},i=H(t,[`model`]);i!=null&&V(r,[`_url`,`model`],W(e,i));let a=H(t,[`prompt`]);a!=null&&V(r,[`instances[0]`,`prompt`],a);let o=H(t,[`config`]);return o!=null&&xs(o,r),r}function ws(e,t){let n={},r=H(e,[`sdkHttpResponse`]);r!=null&&V(n,[`sdkHttpResponse`],r);let i=H(e,[`predictions`]);if(i!=null){let e=i;Array.isArray(e)&&(e=e.map(e=>Is(e))),V(n,[`generatedImages`],e)}let a=H(e,[`positivePromptSafetyAttributes`]);return a!=null&&V(n,[`positivePromptSafetyAttributes`],hc(a)),n}function Ts(e,t){let n={},r=H(e,[`sdkHttpResponse`]);r!=null&&V(n,[`sdkHttpResponse`],r);let i=H(e,[`predictions`]);if(i!=null){let e=i;Array.isArray(e)&&(e=e.map(e=>Ls(e))),V(n,[`generatedImages`],e)}let a=H(e,[`positivePromptSafetyAttributes`]);return a!=null&&V(n,[`positivePromptSafetyAttributes`],gc(a)),n}function Es(e,t,n){let r={},i=H(e,[`numberOfVideos`]);if(t!==void 0&&i!=null&&V(t,[`parameters`,`sampleCount`],i),H(e,[`outputGcsUri`])!==void 0)throw Error(`outputGcsUri parameter is not supported in Gemini API.`);if(H(e,[`fps`])!==void 0)throw Error(`fps parameter is not supported in Gemini API.`);let a=H(e,[`durationSeconds`]);if(t!==void 0&&a!=null&&V(t,[`parameters`,`durationSeconds`],a),H(e,[`seed`])!==void 0)throw Error(`seed parameter is not supported in Gemini API.`);let o=H(e,[`aspectRatio`]);t!==void 0&&o!=null&&V(t,[`parameters`,`aspectRatio`],o);let s=H(e,[`resolution`]);t!==void 0&&s!=null&&V(t,[`parameters`,`resolution`],s);let c=H(e,[`personGeneration`]);if(t!==void 0&&c!=null&&V(t,[`parameters`,`personGeneration`],c),H(e,[`pubsubTopic`])!==void 0)throw Error(`pubsubTopic parameter is not supported in Gemini API.`);let l=H(e,[`negativePrompt`]);t!==void 0&&l!=null&&V(t,[`parameters`,`negativePrompt`],l);let u=H(e,[`enhancePrompt`]);if(t!==void 0&&u!=null&&V(t,[`parameters`,`enhancePrompt`],u),H(e,[`generateAudio`])!==void 0)throw Error(`generateAudio parameter is not supported in Gemini API.`);let d=H(e,[`lastFrame`]);t!==void 0&&d!=null&&V(t,[`instances[0]`,`lastFrame`],Xs(d));let f=H(e,[`referenceImages`]);if(t!==void 0&&f!=null){let e=f;Array.isArray(e)&&(e=e.map(e=>zc(e))),V(t,[`instances[0]`,`referenceImages`],e)}if(H(e,[`mask`])!==void 0)throw Error(`mask parameter is not supported in Gemini API.`);if(H(e,[`compressionQuality`])!==void 0)throw Error(`compressionQuality parameter is not supported in Gemini API.`);if(H(e,[`labels`])!==void 0)throw Error(`labels parameter is not supported in Gemini API.`);let p=H(e,[`webhookConfig`]);if(t!==void 0&&p!=null&&V(t,[`webhookConfig`],p),H(e,[`resizeMode`])!==void 0)throw Error(`resizeMode parameter is not supported in Gemini API.`);return r}function Ds(e,t,n){let r={},i=H(e,[`numberOfVideos`]);t!==void 0&&i!=null&&V(t,[`parameters`,`sampleCount`],i);let a=H(e,[`outputGcsUri`]);t!==void 0&&a!=null&&V(t,[`parameters`,`storageUri`],a);let o=H(e,[`fps`]);t!==void 0&&o!=null&&V(t,[`parameters`,`fps`],o);let s=H(e,[`durationSeconds`]);t!==void 0&&s!=null&&V(t,[`parameters`,`durationSeconds`],s);let c=H(e,[`seed`]);t!==void 0&&c!=null&&V(t,[`parameters`,`seed`],c);let l=H(e,[`aspectRatio`]);t!==void 0&&l!=null&&V(t,[`parameters`,`aspectRatio`],l);let u=H(e,[`resolution`]);t!==void 0&&u!=null&&V(t,[`parameters`,`resolution`],u);let d=H(e,[`personGeneration`]);t!==void 0&&d!=null&&V(t,[`parameters`,`personGeneration`],d);let f=H(e,[`pubsubTopic`]);t!==void 0&&f!=null&&V(t,[`parameters`,`pubsubTopic`],f);let p=H(e,[`negativePrompt`]);t!==void 0&&p!=null&&V(t,[`parameters`,`negativePrompt`],p);let m=H(e,[`enhancePrompt`]);t!==void 0&&m!=null&&V(t,[`parameters`,`enhancePrompt`],m);let h=H(e,[`generateAudio`]);t!==void 0&&h!=null&&V(t,[`parameters`,`generateAudio`],h);let g=H(e,[`lastFrame`]);t!==void 0&&g!=null&&V(t,[`instances[0]`,`lastFrame`],Zs(g));let _=H(e,[`referenceImages`]);if(t!==void 0&&_!=null){let e=_;Array.isArray(e)&&(e=e.map(e=>Bc(e))),V(t,[`instances[0]`,`referenceImages`],e)}let v=H(e,[`mask`]);t!==void 0&&v!=null&&V(t,[`instances[0]`,`mask`],Rc(v));let y=H(e,[`compressionQuality`]);t!==void 0&&y!=null&&V(t,[`parameters`,`compressionQuality`],y);let b=H(e,[`labels`]);if(t!==void 0&&b!=null&&V(t,[`labels`],b),H(e,[`webhookConfig`])!==void 0)throw Error(`webhookConfig parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).`);let x=H(e,[`resizeMode`]);return t!==void 0&&x!=null&&V(t,[`parameters`,`resizeMode`],x),r}function Os(e,t){let n={},r=H(e,[`name`]);r!=null&&V(n,[`name`],r);let i=H(e,[`metadata`]);i!=null&&V(n,[`metadata`],i);let a=H(e,[`done`]);a!=null&&V(n,[`done`],a);let o=H(e,[`error`]);o!=null&&V(n,[`error`],o);let s=H(e,[`response`,`generateVideoResponse`]);return s!=null&&V(n,[`response`],Ms(s)),n}function ks(e,t){let n={},r=H(e,[`name`]);r!=null&&V(n,[`name`],r);let i=H(e,[`metadata`]);i!=null&&V(n,[`metadata`],i);let a=H(e,[`done`]);a!=null&&V(n,[`done`],a);let o=H(e,[`error`]);o!=null&&V(n,[`error`],o);let s=H(e,[`response`]);return s!=null&&V(n,[`response`],Ns(s)),n}function As(e,t,n){let r={},i=H(t,[`model`]);i!=null&&V(r,[`_url`,`model`],W(e,i));let a=H(t,[`prompt`]);a!=null&&V(r,[`instances[0]`,`prompt`],a);let o=H(t,[`image`]);o!=null&&V(r,[`instances[0]`,`image`],Xs(o));let s=H(t,[`video`]);s!=null&&V(r,[`instances[0]`,`video`],Vc(s));let c=H(t,[`source`]);c!=null&&Ps(c,r);let l=H(t,[`config`]);return l!=null&&Es(l,r),r}function js(e,t,n){let r={},i=H(t,[`model`]);i!=null&&V(r,[`_url`,`model`],W(e,i));let a=H(t,[`prompt`]);a!=null&&V(r,[`instances[0]`,`prompt`],a);let o=H(t,[`image`]);o!=null&&V(r,[`instances[0]`,`image`],Zs(o));let s=H(t,[`video`]);s!=null&&V(r,[`instances[0]`,`video`],Hc(s));let c=H(t,[`source`]);c!=null&&Fs(c,r);let l=H(t,[`config`]);return l!=null&&Ds(l,r),r}function Ms(e,t){let n={},r=H(e,[`generatedSamples`]);if(r!=null){let e=r;Array.isArray(e)&&(e=e.map(e=>zs(e))),V(n,[`generatedVideos`],e)}let i=H(e,[`raiMediaFilteredCount`]);i!=null&&V(n,[`raiMediaFilteredCount`],i);let a=H(e,[`raiMediaFilteredReasons`]);return a!=null&&V(n,[`raiMediaFilteredReasons`],a),n}function Ns(e,t){let n={},r=H(e,[`videos`]);if(r!=null){let e=r;Array.isArray(e)&&(e=e.map(e=>Bs(e))),V(n,[`generatedVideos`],e)}let i=H(e,[`raiMediaFilteredCount`]);i!=null&&V(n,[`raiMediaFilteredCount`],i);let a=H(e,[`raiMediaFilteredReasons`]);return a!=null&&V(n,[`raiMediaFilteredReasons`],a),n}function Ps(e,t,n){let r={},i=H(e,[`prompt`]);t!==void 0&&i!=null&&V(t,[`instances[0]`,`prompt`],i);let a=H(e,[`image`]);t!==void 0&&a!=null&&V(t,[`instances[0]`,`image`],Xs(a));let o=H(e,[`video`]);return t!==void 0&&o!=null&&V(t,[`instances[0]`,`video`],Vc(o)),r}function Fs(e,t,n){let r={},i=H(e,[`prompt`]);t!==void 0&&i!=null&&V(t,[`instances[0]`,`prompt`],i);let a=H(e,[`image`]);t!==void 0&&a!=null&&V(t,[`instances[0]`,`image`],Zs(a));let o=H(e,[`video`]);return t!==void 0&&o!=null&&V(t,[`instances[0]`,`video`],Hc(o)),r}function Is(e,t){let n={},r=H(e,[`_self`]);r!=null&&V(n,[`image`],Js(r));let i=H(e,[`raiFilteredReason`]);i!=null&&V(n,[`raiFilteredReason`],i);let a=H(e,[`_self`]);return a!=null&&V(n,[`safetyAttributes`],hc(a)),n}function Ls(e,t){let n={},r=H(e,[`_self`]);r!=null&&V(n,[`image`],Ys(r));let i=H(e,[`raiFilteredReason`]);i!=null&&V(n,[`raiFilteredReason`],i);let a=H(e,[`_self`]);a!=null&&V(n,[`safetyAttributes`],gc(a));let o=H(e,[`prompt`]);return o!=null&&V(n,[`enhancedPrompt`],o),n}function Rs(e,t){let n={},r=H(e,[`_self`]);r!=null&&V(n,[`mask`],Ys(r));let i=H(e,[`labels`]);if(i!=null){let e=i;Array.isArray(e)&&(e=e.map(e=>e)),V(n,[`labels`],e)}return n}function zs(e,t){let n={},r=H(e,[`video`]);return r!=null&&V(n,[`video`],Ic(r)),n}function Bs(e,t){let n={},r=H(e,[`_self`]);return r!=null&&V(n,[`video`],Lc(r)),n}function Vs(e,t){let n={},r=H(e,[`modelSelectionConfig`]);r!=null&&V(n,[`modelConfig`],r);let i=H(e,[`responseJsonSchema`]);i!=null&&V(n,[`responseJsonSchema`],i);let a=H(e,[`audioTimestamp`]);a!=null&&V(n,[`audioTimestamp`],a);let o=H(e,[`candidateCount`]);o!=null&&V(n,[`candidateCount`],o);let s=H(e,[`enableAffectiveDialog`]);s!=null&&V(n,[`enableAffectiveDialog`],s);let c=H(e,[`frequencyPenalty`]);c!=null&&V(n,[`frequencyPenalty`],c);let l=H(e,[`logprobs`]);l!=null&&V(n,[`logprobs`],l);let u=H(e,[`maxOutputTokens`]);u!=null&&V(n,[`maxOutputTokens`],u);let d=H(e,[`mediaResolution`]);d!=null&&V(n,[`mediaResolution`],d);let f=H(e,[`presencePenalty`]);f!=null&&V(n,[`presencePenalty`],f);let p=H(e,[`responseLogprobs`]);p!=null&&V(n,[`responseLogprobs`],p);let m=H(e,[`responseMimeType`]);m!=null&&V(n,[`responseMimeType`],m);let h=H(e,[`responseModalities`]);h!=null&&V(n,[`responseModalities`],h);let g=H(e,[`responseSchema`]);g!=null&&V(n,[`responseSchema`],g);let _=H(e,[`routingConfig`]);_!=null&&V(n,[`routingConfig`],_);let v=H(e,[`seed`]);v!=null&&V(n,[`seed`],v);let y=H(e,[`speechConfig`]);y!=null&&V(n,[`speechConfig`],y);let b=H(e,[`stopSequences`]);b!=null&&V(n,[`stopSequences`],b);let x=H(e,[`temperature`]);x!=null&&V(n,[`temperature`],x);let S=H(e,[`thinkingConfig`]);S!=null&&V(n,[`thinkingConfig`],S);let C=H(e,[`topK`]);C!=null&&V(n,[`topK`],C);let w=H(e,[`topP`]);if(w!=null&&V(n,[`topP`],w),H(e,[`enableEnhancedCivicAnswers`])!==void 0)throw Error(`enableEnhancedCivicAnswers parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).`);return n}function Hs(e,t,n){let r={},i=H(t,[`model`]);return i!=null&&V(r,[`_url`,`name`],W(e,i)),r}function Us(e,t,n){let r={},i=H(t,[`model`]);return i!=null&&V(r,[`_url`,`name`],W(e,i)),r}function Ws(e,t){let n={},r=H(e,[`authConfig`]);r!=null&&V(n,[`authConfig`],No(r));let i=H(e,[`enableWidget`]);return i!=null&&V(n,[`enableWidget`],i),n}function Gs(e,t){let n={},r=H(e,[`searchTypes`]);if(r!=null&&V(n,[`searchTypes`],r),H(e,[`blockingConfidence`])!==void 0)throw Error(`blockingConfidence parameter is not supported in Gemini API.`);if(H(e,[`excludeDomains`])!==void 0)throw Error(`excludeDomains parameter is not supported in Gemini API.`);let i=H(e,[`timeRangeFilter`]);return i!=null&&V(n,[`timeRangeFilter`],i),n}function Ks(e,t){let n={},r=H(e,[`aspectRatio`]);r!=null&&V(n,[`aspectRatio`],r);let i=H(e,[`imageSize`]);if(i!=null&&V(n,[`imageSize`],i),H(e,[`personGeneration`])!==void 0)throw Error(`personGeneration parameter is not supported in Gemini API.`);if(H(e,[`prominentPeople`])!==void 0)throw Error(`prominentPeople parameter is not supported in Gemini API.`);if(H(e,[`outputMimeType`])!==void 0)throw Error(`outputMimeType parameter is not supported in Gemini API.`);if(H(e,[`outputCompressionQuality`])!==void 0)throw Error(`outputCompressionQuality parameter is not supported in Gemini API.`);if(H(e,[`imageOutputOptions`])!==void 0)throw Error(`imageOutputOptions parameter is not supported in Gemini API.`);return n}function qs(e,t){let n={},r=H(e,[`aspectRatio`]);r!=null&&V(n,[`aspectRatio`],r);let i=H(e,[`imageSize`]);i!=null&&V(n,[`imageSize`],i);let a=H(e,[`personGeneration`]);a!=null&&V(n,[`personGeneration`],a);let o=H(e,[`prominentPeople`]);o!=null&&V(n,[`prominentPeople`],o);let s=H(e,[`outputMimeType`]);s!=null&&V(n,[`imageOutputOptions`,`mimeType`],s);let c=H(e,[`outputCompressionQuality`]);c!=null&&V(n,[`imageOutputOptions`,`compressionQuality`],c);let l=H(e,[`imageOutputOptions`]);return l!=null&&V(n,[`imageOutputOptions`],l),n}function Js(e,t){let n={},r=H(e,[`bytesBase64Encoded`]);r!=null&&V(n,[`imageBytes`],Rr(r));let i=H(e,[`mimeType`]);return i!=null&&V(n,[`mimeType`],i),n}function Ys(e,t){let n={},r=H(e,[`gcsUri`]);r!=null&&V(n,[`gcsUri`],r);let i=H(e,[`bytesBase64Encoded`]);i!=null&&V(n,[`imageBytes`],Rr(i));let a=H(e,[`mimeType`]);return a!=null&&V(n,[`mimeType`],a),n}function Xs(e,t){let n={};if(H(e,[`gcsUri`])!==void 0)throw Error(`gcsUri parameter is not supported in Gemini API.`);let r=H(e,[`imageBytes`]);r!=null&&V(n,[`bytesBase64Encoded`],Rr(r));let i=H(e,[`mimeType`]);return i!=null&&V(n,[`mimeType`],i),n}function Zs(e,t){let n={},r=H(e,[`gcsUri`]);r!=null&&V(n,[`gcsUri`],r);let i=H(e,[`imageBytes`]);i!=null&&V(n,[`bytesBase64Encoded`],Rr(i));let a=H(e,[`mimeType`]);return a!=null&&V(n,[`mimeType`],a),n}function Qs(e,t,n,r){let i={},a=H(t,[`pageSize`]);n!==void 0&&a!=null&&V(n,[`_query`,`pageSize`],a);let o=H(t,[`pageToken`]);n!==void 0&&o!=null&&V(n,[`_query`,`pageToken`],o);let s=H(t,[`filter`]);n!==void 0&&s!=null&&V(n,[`_query`,`filter`],s);let c=H(t,[`queryBase`]);return n!==void 0&&c!=null&&V(n,[`_url`,`models_url`],Ur(e,c)),i}function $s(e,t,n,r){let i={},a=H(t,[`pageSize`]);n!==void 0&&a!=null&&V(n,[`_query`,`pageSize`],a);let o=H(t,[`pageToken`]);n!==void 0&&o!=null&&V(n,[`_query`,`pageToken`],o);let s=H(t,[`filter`]);n!==void 0&&s!=null&&V(n,[`_query`,`filter`],s);let c=H(t,[`queryBase`]);return n!==void 0&&c!=null&&V(n,[`_url`,`models_url`],Ur(e,c)),i}function ec(e,t,n){let r={},i=H(t,[`config`]);return i!=null&&Qs(e,i,r),r}function tc(e,t,n){let r={},i=H(t,[`config`]);return i!=null&&$s(e,i,r),r}function nc(e,t){let n={},r=H(e,[`sdkHttpResponse`]);r!=null&&V(n,[`sdkHttpResponse`],r);let i=H(e,[`nextPageToken`]);i!=null&&V(n,[`nextPageToken`],i);let a=H(e,[`_self`]);if(a!=null){let e=Wr(a);Array.isArray(e)&&(e=e.map(e=>ac(e))),V(n,[`models`],e)}return n}function rc(e,t){let n={},r=H(e,[`sdkHttpResponse`]);r!=null&&V(n,[`sdkHttpResponse`],r);let i=H(e,[`nextPageToken`]);i!=null&&V(n,[`nextPageToken`],i);let a=H(e,[`_self`]);if(a!=null){let e=Wr(a);Array.isArray(e)&&(e=e.map(e=>oc(e))),V(n,[`models`],e)}return n}function ic(e,t){let n={},r=H(e,[`maskMode`]);r!=null&&V(n,[`maskMode`],r);let i=H(e,[`segmentationClasses`]);i!=null&&V(n,[`maskClasses`],i);let a=H(e,[`maskDilation`]);return a!=null&&V(n,[`dilation`],a),n}function ac(e,t){let n={},r=H(e,[`name`]);r!=null&&V(n,[`name`],r);let i=H(e,[`displayName`]);i!=null&&V(n,[`displayName`],i);let a=H(e,[`description`]);a!=null&&V(n,[`description`],a);let o=H(e,[`version`]);o!=null&&V(n,[`version`],o);let s=H(e,[`_self`]);s!=null&&V(n,[`tunedModelInfo`],Dc(s));let c=H(e,[`inputTokenLimit`]);c!=null&&V(n,[`inputTokenLimit`],c);let l=H(e,[`outputTokenLimit`]);l!=null&&V(n,[`outputTokenLimit`],l);let u=H(e,[`supportedGenerationMethods`]);u!=null&&V(n,[`supportedActions`],u);let d=H(e,[`temperature`]);d!=null&&V(n,[`temperature`],d);let f=H(e,[`maxTemperature`]);f!=null&&V(n,[`maxTemperature`],f);let p=H(e,[`topP`]);p!=null&&V(n,[`topP`],p);let m=H(e,[`topK`]);m!=null&&V(n,[`topK`],m);let h=H(e,[`thinking`]);return h!=null&&V(n,[`thinking`],h),n}function oc(e,t){let n={},r=H(e,[`name`]);r!=null&&V(n,[`name`],r);let i=H(e,[`displayName`]);i!=null&&V(n,[`displayName`],i);let a=H(e,[`description`]);a!=null&&V(n,[`description`],a);let o=H(e,[`versionId`]);o!=null&&V(n,[`version`],o);let s=H(e,[`deployedModels`]);if(s!=null){let e=s;Array.isArray(e)&&(e=e.map(e=>ls(e))),V(n,[`endpoints`],e)}let c=H(e,[`labels`]);c!=null&&V(n,[`labels`],c);let l=H(e,[`_self`]);l!=null&&V(n,[`tunedModelInfo`],Oc(l));let u=H(e,[`defaultCheckpointId`]);u!=null&&V(n,[`defaultCheckpointId`],u);let d=H(e,[`checkpoints`]);if(d!=null){let e=d;Array.isArray(e)&&(e=e.map(e=>e)),V(n,[`checkpoints`],e)}return n}function sc(e,t){let n={},r=H(e,[`mediaResolution`]);r!=null&&V(n,[`mediaResolution`],r);let i=H(e,[`codeExecutionResult`]);i!=null&&V(n,[`codeExecutionResult`],i);let a=H(e,[`executableCode`]);a!=null&&V(n,[`executableCode`],a);let o=H(e,[`fileData`]);o!=null&&V(n,[`fileData`],us(o));let s=H(e,[`functionCall`]);s!=null&&V(n,[`functionCall`],ds(s));let c=H(e,[`functionResponse`]);c!=null&&V(n,[`functionResponse`],c);let l=H(e,[`inlineData`]);l!=null&&V(n,[`inlineData`],Po(l));let u=H(e,[`text`]);u!=null&&V(n,[`text`],u);let d=H(e,[`thought`]);d!=null&&V(n,[`thought`],d);let f=H(e,[`thoughtSignature`]);f!=null&&V(n,[`thoughtSignature`],f);let p=H(e,[`videoMetadata`]);p!=null&&V(n,[`videoMetadata`],p);let m=H(e,[`toolCall`]);m!=null&&V(n,[`toolCall`],m);let h=H(e,[`toolResponse`]);h!=null&&V(n,[`toolResponse`],h);let g=H(e,[`partMetadata`]);return g!=null&&V(n,[`partMetadata`],g),n}function cc(e,t){let n={},r=H(e,[`mediaResolution`]);r!=null&&V(n,[`mediaResolution`],r);let i=H(e,[`codeExecutionResult`]);i!=null&&V(n,[`codeExecutionResult`],i);let a=H(e,[`executableCode`]);a!=null&&V(n,[`executableCode`],a);let o=H(e,[`fileData`]);o!=null&&V(n,[`fileData`],o);let s=H(e,[`functionCall`]);s!=null&&V(n,[`functionCall`],s);let c=H(e,[`functionResponse`]);c!=null&&V(n,[`functionResponse`],c);let l=H(e,[`inlineData`]);l!=null&&V(n,[`inlineData`],l);let u=H(e,[`text`]);u!=null&&V(n,[`text`],u);let d=H(e,[`thought`]);d!=null&&V(n,[`thought`],d);let f=H(e,[`thoughtSignature`]);f!=null&&V(n,[`thoughtSignature`],f);let p=H(e,[`videoMetadata`]);if(p!=null&&V(n,[`videoMetadata`],p),H(e,[`toolCall`])!==void 0)throw Error(`toolCall parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).`);if(H(e,[`toolResponse`])!==void 0)throw Error(`toolResponse parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).`);if(H(e,[`partMetadata`])!==void 0)throw Error(`partMetadata parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).`);return n}function lc(e,t){let n={},r=H(e,[`productImage`]);return r!=null&&V(n,[`image`],Zs(r)),n}function uc(e,t,n){let r={},i=H(e,[`numberOfImages`]);t!==void 0&&i!=null&&V(t,[`parameters`,`sampleCount`],i);let a=H(e,[`baseSteps`]);t!==void 0&&a!=null&&V(t,[`parameters`,`baseSteps`],a);let o=H(e,[`outputGcsUri`]);t!==void 0&&o!=null&&V(t,[`parameters`,`storageUri`],o);let s=H(e,[`seed`]);t!==void 0&&s!=null&&V(t,[`parameters`,`seed`],s);let c=H(e,[`safetyFilterLevel`]);t!==void 0&&c!=null&&V(t,[`parameters`,`safetySetting`],c);let l=H(e,[`personGeneration`]);t!==void 0&&l!=null&&V(t,[`parameters`,`personGeneration`],l);let u=H(e,[`addWatermark`]);t!==void 0&&u!=null&&V(t,[`parameters`,`addWatermark`],u);let d=H(e,[`outputMimeType`]);t!==void 0&&d!=null&&V(t,[`parameters`,`outputOptions`,`mimeType`],d);let f=H(e,[`outputCompressionQuality`]);t!==void 0&&f!=null&&V(t,[`parameters`,`outputOptions`,`compressionQuality`],f);let p=H(e,[`enhancePrompt`]);t!==void 0&&p!=null&&V(t,[`parameters`,`enhancePrompt`],p);let m=H(e,[`labels`]);return t!==void 0&&m!=null&&V(t,[`labels`],m),r}function dc(e,t,n){let r={},i=H(t,[`model`]);i!=null&&V(r,[`_url`,`model`],W(e,i));let a=H(t,[`source`]);a!=null&&pc(a,r);let o=H(t,[`config`]);return o!=null&&uc(o,r),r}function fc(e,t){let n={},r=H(e,[`predictions`]);if(r!=null){let e=r;Array.isArray(e)&&(e=e.map(e=>Ls(e))),V(n,[`generatedImages`],e)}return n}function pc(e,t,n){let r={},i=H(e,[`prompt`]);t!==void 0&&i!=null&&V(t,[`instances[0]`,`prompt`],i);let a=H(e,[`personImage`]);t!==void 0&&a!=null&&V(t,[`instances[0]`,`personImage`,`image`],Zs(a));let o=H(e,[`productImages`]);if(t!==void 0&&o!=null){let e=o;Array.isArray(e)&&(e=e.map(e=>lc(e))),V(t,[`instances[0]`,`productImages`],e)}return r}function mc(e,t){let n={},r=H(e,[`referenceImage`]);r!=null&&V(n,[`referenceImage`],Zs(r));let i=H(e,[`referenceId`]);i!=null&&V(n,[`referenceId`],i);let a=H(e,[`referenceType`]);a!=null&&V(n,[`referenceType`],a);let o=H(e,[`maskImageConfig`]);o!=null&&V(n,[`maskImageConfig`],ic(o));let s=H(e,[`controlImageConfig`]);s!=null&&V(n,[`controlImageConfig`],Uo(s));let c=H(e,[`styleImageConfig`]);c!=null&&V(n,[`styleImageConfig`],c);let l=H(e,[`subjectImageConfig`]);return l!=null&&V(n,[`subjectImageConfig`],l),n}function hc(e,t){let n={},r=H(e,[`safetyAttributes`,`categories`]);r!=null&&V(n,[`categories`],r);let i=H(e,[`safetyAttributes`,`scores`]);i!=null&&V(n,[`scores`],i);let a=H(e,[`contentType`]);return a!=null&&V(n,[`contentType`],a),n}function gc(e,t){let n={},r=H(e,[`safetyAttributes`,`categories`]);r!=null&&V(n,[`categories`],r);let i=H(e,[`safetyAttributes`,`scores`]);i!=null&&V(n,[`scores`],i);let a=H(e,[`contentType`]);return a!=null&&V(n,[`contentType`],a),n}function _c(e,t){let n={},r=H(e,[`category`]);if(r!=null&&V(n,[`category`],r),H(e,[`method`])!==void 0)throw Error(`method parameter is not supported in Gemini API.`);let i=H(e,[`threshold`]);return i!=null&&V(n,[`threshold`],i),n}function vc(e,t){let n={},r=H(e,[`image`]);return r!=null&&V(n,[`image`],Zs(r)),n}function yc(e,t,n){let r={},i=H(e,[`mode`]);t!==void 0&&i!=null&&V(t,[`parameters`,`mode`],i);let a=H(e,[`maxPredictions`]);t!==void 0&&a!=null&&V(t,[`parameters`,`maxPredictions`],a);let o=H(e,[`confidenceThreshold`]);t!==void 0&&o!=null&&V(t,[`parameters`,`confidenceThreshold`],o);let s=H(e,[`maskDilation`]);t!==void 0&&s!=null&&V(t,[`parameters`,`maskDilation`],s);let c=H(e,[`binaryColorThreshold`]);t!==void 0&&c!=null&&V(t,[`parameters`,`binaryColorThreshold`],c);let l=H(e,[`labels`]);return t!==void 0&&l!=null&&V(t,[`labels`],l),r}function bc(e,t,n){let r={},i=H(t,[`model`]);i!=null&&V(r,[`_url`,`model`],W(e,i));let a=H(t,[`source`]);a!=null&&Sc(a,r);let o=H(t,[`config`]);return o!=null&&yc(o,r),r}function xc(e,t){let n={},r=H(e,[`predictions`]);if(r!=null){let e=r;Array.isArray(e)&&(e=e.map(e=>Rs(e))),V(n,[`generatedMasks`],e)}return n}function Sc(e,t,n){let r={},i=H(e,[`prompt`]);t!==void 0&&i!=null&&V(t,[`instances[0]`,`prompt`],i);let a=H(e,[`image`]);t!==void 0&&a!=null&&V(t,[`instances[0]`,`image`],Zs(a));let o=H(e,[`scribbleImage`]);return t!==void 0&&o!=null&&V(t,[`instances[0]`,`scribble`],vc(o)),r}function Cc(e,t){let n={},r=H(e,[`retrievalConfig`]);r!=null&&V(n,[`retrievalConfig`],r);let i=H(e,[`functionCallingConfig`]);i!=null&&V(n,[`functionCallingConfig`],fs(i));let a=H(e,[`includeServerSideToolInvocations`]);return a!=null&&V(n,[`includeServerSideToolInvocations`],a),n}function wc(e,t){let n={},r=H(e,[`retrievalConfig`]);r!=null&&V(n,[`retrievalConfig`],r);let i=H(e,[`functionCallingConfig`]);if(i!=null&&V(n,[`functionCallingConfig`],i),H(e,[`includeServerSideToolInvocations`])!==void 0)throw Error(`includeServerSideToolInvocations parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).`);return n}function Tc(e,t){let n={};if(H(e,[`retrieval`])!==void 0)throw Error(`retrieval parameter is not supported in Gemini API.`);let r=H(e,[`computerUse`]);r!=null&&V(n,[`computerUse`],r);let i=H(e,[`fileSearch`]);i!=null&&V(n,[`fileSearch`],i);let a=H(e,[`googleSearch`]);a!=null&&V(n,[`googleSearch`],Gs(a));let o=H(e,[`googleMaps`]);o!=null&&V(n,[`googleMaps`],Ws(o));let s=H(e,[`codeExecution`]);if(s!=null&&V(n,[`codeExecution`],s),H(e,[`enterpriseWebSearch`])!==void 0)throw Error(`enterpriseWebSearch parameter is not supported in Gemini API.`);let c=H(e,[`functionDeclarations`]);if(c!=null){let e=c;Array.isArray(e)&&(e=e.map(e=>e)),V(n,[`functionDeclarations`],e)}let l=H(e,[`googleSearchRetrieval`]);if(l!=null&&V(n,[`googleSearchRetrieval`],l),H(e,[`parallelAiSearch`])!==void 0)throw Error(`parallelAiSearch parameter is not supported in Gemini API.`);let u=H(e,[`urlContext`]);u!=null&&V(n,[`urlContext`],u);let d=H(e,[`mcpServers`]);if(d!=null){let e=d;Array.isArray(e)&&(e=e.map(e=>e)),V(n,[`mcpServers`],e)}return n}function Ec(e,t){let n={},r=H(e,[`retrieval`]);r!=null&&V(n,[`retrieval`],r);let i=H(e,[`computerUse`]);if(i!=null&&V(n,[`computerUse`],i),H(e,[`fileSearch`])!==void 0)throw Error(`fileSearch parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).`);let a=H(e,[`googleSearch`]);a!=null&&V(n,[`googleSearch`],a);let o=H(e,[`googleMaps`]);o!=null&&V(n,[`googleMaps`],o);let s=H(e,[`codeExecution`]);s!=null&&V(n,[`codeExecution`],s);let c=H(e,[`enterpriseWebSearch`]);c!=null&&V(n,[`enterpriseWebSearch`],c);let l=H(e,[`functionDeclarations`]);if(l!=null){let e=l;Array.isArray(e)&&(e=e.map(e=>ps(e))),V(n,[`functionDeclarations`],e)}let u=H(e,[`googleSearchRetrieval`]);u!=null&&V(n,[`googleSearchRetrieval`],u);let d=H(e,[`parallelAiSearch`]);d!=null&&V(n,[`parallelAiSearch`],d);let f=H(e,[`urlContext`]);if(f!=null&&V(n,[`urlContext`],f),H(e,[`mcpServers`])!==void 0)throw Error(`mcpServers parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).`);return n}function Dc(e,t){let n={},r=H(e,[`baseModel`]);r!=null&&V(n,[`baseModel`],r);let i=H(e,[`createTime`]);i!=null&&V(n,[`createTime`],i);let a=H(e,[`updateTime`]);return a!=null&&V(n,[`updateTime`],a),n}function Oc(e,t){let n={},r=H(e,[`labels`,`google-vertex-llm-tuning-base-model-id`]);r!=null&&V(n,[`baseModel`],r);let i=H(e,[`createTime`]);i!=null&&V(n,[`createTime`],i);let a=H(e,[`updateTime`]);return a!=null&&V(n,[`updateTime`],a),n}function kc(e,t,n){let r={},i=H(e,[`displayName`]);t!==void 0&&i!=null&&V(t,[`displayName`],i);let a=H(e,[`description`]);t!==void 0&&a!=null&&V(t,[`description`],a);let o=H(e,[`defaultCheckpointId`]);return t!==void 0&&o!=null&&V(t,[`defaultCheckpointId`],o),r}function Ac(e,t,n){let r={},i=H(e,[`displayName`]);t!==void 0&&i!=null&&V(t,[`displayName`],i);let a=H(e,[`description`]);t!==void 0&&a!=null&&V(t,[`description`],a);let o=H(e,[`defaultCheckpointId`]);return t!==void 0&&o!=null&&V(t,[`defaultCheckpointId`],o),r}function jc(e,t,n){let r={},i=H(t,[`model`]);i!=null&&V(r,[`_url`,`name`],W(e,i));let a=H(t,[`config`]);return a!=null&&kc(a,r),r}function Mc(e,t,n){let r={},i=H(t,[`model`]);i!=null&&V(r,[`_url`,`model`],W(e,i));let a=H(t,[`config`]);return a!=null&&Ac(a,r),r}function Nc(e,t,n){let r={},i=H(e,[`outputGcsUri`]);t!==void 0&&i!=null&&V(t,[`parameters`,`storageUri`],i);let a=H(e,[`safetyFilterLevel`]);t!==void 0&&a!=null&&V(t,[`parameters`,`safetySetting`],a);let o=H(e,[`personGeneration`]);t!==void 0&&o!=null&&V(t,[`parameters`,`personGeneration`],o);let s=H(e,[`includeRaiReason`]);t!==void 0&&s!=null&&V(t,[`parameters`,`includeRaiReason`],s);let c=H(e,[`outputMimeType`]);t!==void 0&&c!=null&&V(t,[`parameters`,`outputOptions`,`mimeType`],c);let l=H(e,[`outputCompressionQuality`]);t!==void 0&&l!=null&&V(t,[`parameters`,`outputOptions`,`compressionQuality`],l);let u=H(e,[`enhanceInputImage`]);t!==void 0&&u!=null&&V(t,[`parameters`,`upscaleConfig`,`enhanceInputImage`],u);let d=H(e,[`imagePreservationFactor`]);t!==void 0&&d!=null&&V(t,[`parameters`,`upscaleConfig`,`imagePreservationFactor`],d);let f=H(e,[`labels`]);t!==void 0&&f!=null&&V(t,[`labels`],f);let p=H(e,[`numberOfImages`]);t!==void 0&&p!=null&&V(t,[`parameters`,`sampleCount`],p);let m=H(e,[`mode`]);return t!==void 0&&m!=null&&V(t,[`parameters`,`mode`],m),r}function Pc(e,t,n){let r={},i=H(t,[`model`]);i!=null&&V(r,[`_url`,`model`],W(e,i));let a=H(t,[`image`]);a!=null&&V(r,[`instances[0]`,`image`],Zs(a));let o=H(t,[`upscaleFactor`]);o!=null&&V(r,[`parameters`,`upscaleConfig`,`upscaleFactor`],o);let s=H(t,[`config`]);return s!=null&&Nc(s,r),r}function Fc(e,t){let n={},r=H(e,[`sdkHttpResponse`]);r!=null&&V(n,[`sdkHttpResponse`],r);let i=H(e,[`predictions`]);if(i!=null){let e=i;Array.isArray(e)&&(e=e.map(e=>Ls(e))),V(n,[`generatedImages`],e)}return n}function Ic(e,t){let n={},r=H(e,[`uri`]);r!=null&&V(n,[`uri`],r);let i=H(e,[`encodedVideo`]);i!=null&&V(n,[`videoBytes`],Rr(i));let a=H(e,[`encoding`]);return a!=null&&V(n,[`mimeType`],a),n}function Lc(e,t){let n={},r=H(e,[`gcsUri`]);r!=null&&V(n,[`uri`],r);let i=H(e,[`bytesBase64Encoded`]);i!=null&&V(n,[`videoBytes`],Rr(i));let a=H(e,[`mimeType`]);return a!=null&&V(n,[`mimeType`],a),n}function Rc(e,t){let n={},r=H(e,[`image`]);r!=null&&V(n,[`_self`],Zs(r));let i=H(e,[`maskMode`]);return i!=null&&V(n,[`maskMode`],i),n}function zc(e,t){let n={},r=H(e,[`image`]);r!=null&&V(n,[`image`],Xs(r));let i=H(e,[`referenceType`]);return i!=null&&V(n,[`referenceType`],i),n}function Bc(e,t){let n={},r=H(e,[`image`]);r!=null&&V(n,[`image`],Zs(r));let i=H(e,[`referenceType`]);return i!=null&&V(n,[`referenceType`],i),n}function Vc(e,t){let n={},r=H(e,[`uri`]);r!=null&&V(n,[`uri`],r);let i=H(e,[`videoBytes`]);i!=null&&V(n,[`encodedVideo`],Rr(i));let a=H(e,[`mimeType`]);return a!=null&&V(n,[`encoding`],a),n}function Hc(e,t){let n={},r=H(e,[`uri`]);r!=null&&V(n,[`gcsUri`],r);let i=H(e,[`videoBytes`]);i!=null&&V(n,[`bytesBase64Encoded`],Rr(i));let a=H(e,[`mimeType`]);return a!=null&&V(n,[`mimeType`],a),n}
111
+ /**
112
+ * @license
113
+ * Copyright 2025 Google LLC
114
+ * SPDX-License-Identifier: Apache-2.0
115
+ */
116
+ function Uc(e,t,n){let r={},i=H(t,[`displayName`]);n!==void 0&&i!=null&&V(n,[`displayName`],i);let a=H(t,[`embeddingModel`]);return n!==void 0&&a!=null&&V(n,[`embeddingModel`],W(e,a)),r}function Wc(e,t){let n={},r=H(t,[`config`]);return r!=null&&Uc(e,r,n),n}function Gc(e,t){let n={},r=H(e,[`force`]);return t!==void 0&&r!=null&&V(t,[`_query`,`force`],r),n}function Kc(e){let t={},n=H(e,[`name`]);n!=null&&V(t,[`_url`,`name`],n);let r=H(e,[`config`]);return r!=null&&Gc(r,t),t}function qc(e){let t={},n=H(e,[`name`]);return n!=null&&V(t,[`_url`,`name`],n),t}function Jc(e,t){let n={},r=H(e,[`customMetadata`]);if(t!==void 0&&r!=null){let e=r;Array.isArray(e)&&(e=e.map(e=>e)),V(t,[`customMetadata`],e)}let i=H(e,[`chunkingConfig`]);return t!==void 0&&i!=null&&V(t,[`chunkingConfig`],i),n}function Yc(e){let t={},n=H(e,[`name`]);n!=null&&V(t,[`name`],n);let r=H(e,[`metadata`]);r!=null&&V(t,[`metadata`],r);let i=H(e,[`done`]);i!=null&&V(t,[`done`],i);let a=H(e,[`error`]);a!=null&&V(t,[`error`],a);let o=H(e,[`response`]);return o!=null&&V(t,[`response`],Zc(o)),t}function Xc(e){let t={},n=H(e,[`fileSearchStoreName`]);n!=null&&V(t,[`_url`,`file_search_store_name`],n);let r=H(e,[`fileName`]);r!=null&&V(t,[`fileName`],r);let i=H(e,[`config`]);return i!=null&&Jc(i,t),t}function Zc(e){let t={},n=H(e,[`sdkHttpResponse`]);n!=null&&V(t,[`sdkHttpResponse`],n);let r=H(e,[`parent`]);r!=null&&V(t,[`parent`],r);let i=H(e,[`documentName`]);return i!=null&&V(t,[`documentName`],i),t}function Qc(e,t){let n={},r=H(e,[`pageSize`]);t!==void 0&&r!=null&&V(t,[`_query`,`pageSize`],r);let i=H(e,[`pageToken`]);return t!==void 0&&i!=null&&V(t,[`_query`,`pageToken`],i),n}function $c(e){let t={},n=H(e,[`config`]);return n!=null&&Qc(n,t),t}function el(e){let t={},n=H(e,[`sdkHttpResponse`]);n!=null&&V(t,[`sdkHttpResponse`],n);let r=H(e,[`nextPageToken`]);r!=null&&V(t,[`nextPageToken`],r);let i=H(e,[`fileSearchStores`]);if(i!=null){let e=i;Array.isArray(e)&&(e=e.map(e=>e)),V(t,[`fileSearchStores`],e)}return t}function tl(e,t){let n={},r=H(e,[`mimeType`]);t!==void 0&&r!=null&&V(t,[`mimeType`],r);let i=H(e,[`displayName`]);t!==void 0&&i!=null&&V(t,[`displayName`],i);let a=H(e,[`customMetadata`]);if(t!==void 0&&a!=null){let e=a;Array.isArray(e)&&(e=e.map(e=>e)),V(t,[`customMetadata`],e)}let o=H(e,[`chunkingConfig`]);return t!==void 0&&o!=null&&V(t,[`chunkingConfig`],o),n}function nl(e){let t={},n=H(e,[`fileSearchStoreName`]);n!=null&&V(t,[`_url`,`file_search_store_name`],n);let r=H(e,[`config`]);return r!=null&&tl(r,t),t}function rl(e){let t={},n=H(e,[`sdkHttpResponse`]);return n!=null&&V(t,[`sdkHttpResponse`],n),t}
117
+ /**
118
+ * @license
119
+ * Copyright 2025 Google LLC
120
+ * SPDX-License-Identifier: Apache-2.0
121
+ */
122
+ const il=`x-goog-api-client`,al=new Set([`us`,`eu`]),ol=[408,429,500,502,503,504];var sl=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&&al.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===pn.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&&ll(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 cl(e),new Hn(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 cl(e),this.processStreamResponse(e))).catch(e=>{throw e instanceof Error?e:Error(JSON.stringify(e))})}processStreamResponse(e){return J(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=[`
123
+
124
+ `,`\r\r`,`\r
125
+ \r
126
+ `];for(;;){let{done:a,value:o}=yield q(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 Ka({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 q(new Hn(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,st.default)(async()=>{let n=await fetch(e,t);if(n.ok)return n;throw ol.includes(n.status)?Error(`Retryable HTTP Error: ${n.statusText}`):new st.AbortError(`Non-retryable exception ${n.statusText} sending request`)},{retries:(n.attempts??5)-1})}getDefaultHeaders(){let e={},t=`google-genai-sdk/1.52.0 `+this.clientOptions.userAgentExtra;return e[`User-Agent`]=t,e[il]=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=B(`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&&tl(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 cl(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 Ka({message:r,status:t}):Error(r)}}function ll(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 ul(e){for(let t of e)if(fl(t)||typeof t==`object`&&`inputSchema`in t)return!0;return!1}function dl(e){e[il]=((e[il]??``)+` mcp_used/unknown`).trimStart()}function fl(e){return typeof e==`object`&&!!e&&e instanceof ml}function pl(e){return J(this,arguments,function*(e,t=100){let n,r=0;for(;r<t;){let t=yield q(e.listTools({cursor:n}));for(let e of t.tools)yield yield q(e),r++;if(!t.nextCursor)break;n=t.nextCursor}})}var ml=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,Y(pl(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(),qr(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}};
127
+ /**
128
+ * @license
129
+ * Copyright 2025 Google LLC
130
+ * SPDX-License-Identifier: Apache-2.0
131
+ */
132
+ async function hl(e,t,n){let r=new hr,i;i=n.data instanceof Blob?JSON.parse(await n.data.text()):JSON.parse(n.data),Object.assign(r,i),t(r)}var gl=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=yl(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=>{hl(l,s.onmessage,e)},onerror:s?.onerror??function(e){},onclose:s?.onclose??function(e){}},d=this.webSocketFactory.create(i,vl(r),u);d.connect(),await o;let f={setup:{model:W(this.apiClient,e.model)}};return d.send(JSON.stringify(f)),new _l(d,this.apiClient)}},_l=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=xo(e);this.conn.send(JSON.stringify({clientContent:t}))}async setMusicGenerationConfig(e){e.musicGenerationConfig||={};let t=bo(e);this.conn.send(JSON.stringify(t))}sendPlaybackControl(e){let t={playbackControl:e};this.conn.send(JSON.stringify(t))}play(){this.sendPlaybackControl(Vn.PLAY)}pause(){this.sendPlaybackControl(Vn.PAUSE)}stop(){this.sendPlaybackControl(Vn.STOP)}resetContext(){this.sendPlaybackControl(Vn.RESET_CONTEXT)}close(){this.conn.close()}};function vl(e){let t={};return e.forEach((e,n)=>{t[n]=e}),t}function yl(e){let t=new Headers;for(let[n,r]of Object.entries(e))t.append(n,r);return t}async function bl(e,t,n){let r=new mr,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=wo(a);Object.assign(r,e)}else{let e=a;Object.assign(r,e)}t(r)}var xl=class{constructor(e,t,n){this.apiClient=e,this.auth=t,this.webSocketFactory=n,this.music=new gl(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&&ul(e.config.tools)&&dl(i);let a=Tl(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=>{bl(u,c.onmessage,e)},onerror:c?.onerror??function(e){},onclose:c?.onclose??function(e){}},f=this.webSocketFactory.create(r,wl(a),d);f.connect(),await s;let p=W(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:[$t.AUDIO]}:e.config.responseModalities=[$t.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()?yo(this.apiClient,_):vo(this.apiClient,_),delete m.config,f.send(JSON.stringify(m)),new Cl(f,this.apiClient)}isCallableTool(e){return`callTool`in e&&typeof e.callTool==`function`}};const Sl={turnComplete:!0};var Cl=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=K(t.turns),e.isVertexAI()||(n=n.map(e=>Vo(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({},Sl),e);let t=this.tLiveClientContent(this.apiClient,e);this.conn.send(JSON.stringify(t))}sendRealtimeInput(e){let t={};t=this.apiClient.isVertexAI()?{realtimeInput:Co(e)}:{realtimeInput:So(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 wl(e){let t={};return e.forEach((e,n)=>{t[n]=e}),t}function Tl(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(Dl(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 Dl(e){return`callTool`in e&&typeof e.callTool==`function`}function Ol(e){return(e.config?.tools)?.some(e=>Dl(e))??!1}function kl(e){let t=[];return e?.config?.tools&&e.config.tools.forEach((e,n)=>{if(Dl(e))return;let r=e;r.functionDeclarations&&r.functionDeclarations.length>0&&t.push(n)}),t}function Al(e){return!e?.automaticFunctionCalling?.ignoreCallHistory}
133
+ /**
134
+ * @license
135
+ * Copyright 2025 Google LLC
136
+ * SPDX-License-Identifier: Apache-2.0
137
+ */
138
+ var jl=class extends dt{constructor(e){super(),this.apiClient=e,this.embedContent=async e=>{if(!this.apiClient.isVertexAI())return e.model.includes(`gemini-embedding-2`)&&(e.contents=K(e.contents)),await this.embedContentInternal(e);if(e.model.includes(`gemini`)&&e.model!==`gemini-embedding-001`||e.model.includes(`maas`)){let t=K(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:gn.EMBED_CONTENT});return await this.embedContentInternal(n)}else{let t=Object.assign(Object.assign({},e),{embeddingApiType:gn.PREDICT});return await this.embedContentInternal(t)}},this.generateContent=async e=>{let t=await this.processParamsMaybeAddMcpUsage(e);if(this.maybeMoveToResponseJsonSchem(e),!Ol(e)||El(e.config))return await this.generateContentInternal(t);let n=kl(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=K(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(Dl(t)){let e=await t.callTool(r.functionCalls);o.push(...e)}s++,i={role:`user`,parts:o},t.contents=K(t.contents),t.contents.push(n),t.contents.push(i),Al(t.config)&&(a.push(n),a.push(i))}return Al(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=kl(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 Gemini Enterprise Agent Platform (previously known as Vertex AI) is not currently supported`);t.config.filter=`labels.tune-type:*`}return new $i(Qi.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=>Dl(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&&ul(e.config.tools)){let t=e.config.httpOptions?.headers??{},n=Object.assign({},t);Object.keys(n).length===0&&(n=this.apiClient.getDefaultHeaders()),dl(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(Dl(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 J(this,arguments,function*(){for(var o,s,c,l;r<t;){n&&=(r++,!1);let p=yield q(e.processParamsMaybeAddMcpUsage(a)),m=yield q(e.generateContentStreamInternal(p)),h=[],g=[];try{for(var u=!0,d=(s=void 0,Y(m)),f;f=yield q(d.next()),o=f.done,!o;u=!0){l=f.value,u=!1;let e=l;if(yield yield q(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 q(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 q(c.call(d)))}finally{if(s)throw s.error}}if(h.length>0){n=!0;let e=new Un;e.candidates=[{content:{role:`user`,parts:h}}],yield yield q(e);let t=[];t.push(...g),t.push({role:`user`,parts:h}),a.contents=K(a.contents).concat(t)}else break}})})(this,i,e)}async generateContentInternal(e){let t,n=``,r={};if(this.apiClient.isVertexAI()){let i=_s(this.apiClient,e);return n=B(`{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=ys(e),n=new Un;return Object.assign(n,t),n})}else{let i=gs(this.apiClient,e);return n=B(`{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=vs(e),n=new Un;return Object.assign(n,t),n})}}async generateContentStreamInternal(e){let t,n=``,r={};if(this.apiClient.isVertexAI()){let i=_s(this.apiClient,e);return n=B(`{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 J(this,arguments,function*(){var n,r,i,a;try{for(var o=!0,s=Y(t),c;c=yield q(s.next()),n=c.done,!n;o=!0){a=c.value,o=!1;let t=a,n=ys(yield q(t.json()),e);n.sdkHttpResponse={headers:t.headers};let r=new Un;Object.assign(r,n),yield yield q(r)}}catch(e){r={error:e}}finally{try{!o&&!n&&(i=s.return)&&(yield q(i.call(s)))}finally{if(r)throw r.error}}})})}else{let i=gs(this.apiClient,e);return n=B(`{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 J(this,arguments,function*(){var n,r,i,a;try{for(var o=!0,s=Y(t),c;c=yield q(s.next()),n=c.done,!n;o=!0){a=c.value,o=!1;let t=a,n=vs(yield q(t.json()),e);n.sdkHttpResponse={headers:t.headers};let r=new Un;Object.assign(r,n),yield yield q(r)}}catch(e){r={error:e}}finally{try{!o&&!n&&(i=s.return)&&(yield q(i.call(s)))}finally{if(r)throw r.error}}})})}}async embedContentInternal(e){let t,n=``,r={};if(this.apiClient.isVertexAI()){let i=os(this.apiClient,e,e);return n=B($r(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=cs(t,e),r=new Wn;return Object.assign(r,n),r})}else{let i=as(this.apiClient,e);return n=B(`{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=ss(e),n=new Wn;return Object.assign(n,t),n})}}async generateImagesInternal(e){let t,n=``,r={};if(this.apiClient.isVertexAI()){let i=Cs(this.apiClient,e);return n=B(`{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=Ts(e),n=new Gn;return Object.assign(n,t),n})}else{let i=Ss(this.apiClient,e);return n=B(`{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=ws(e),n=new Gn;return Object.assign(n,t),n})}}async editImageInternal(e){let t,n=``,r={};if(this.apiClient.isVertexAI()){let i=ts(this.apiClient,e);return n=B(`{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=ns(e),n=new Kn;return Object.assign(n,t),n})}else throw Error(`This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).`)}async upscaleImageInternal(e){let t,n=``,r={};if(this.apiClient.isVertexAI()){let i=Pc(this.apiClient,e);return n=B(`{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=Fc(e),n=new qn;return Object.assign(n,t),n})}else throw Error(`This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).`)}async recontextImage(e){let t,n=``,r={};if(this.apiClient.isVertexAI()){let i=dc(this.apiClient,e);return n=B(`{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=fc(e),n=new Jn;return Object.assign(n,t),n})}else throw Error(`This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).`)}async segmentImage(e){let t,n=``,r={};if(this.apiClient.isVertexAI()){let i=bc(this.apiClient,e);return n=B(`{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=xc(e),n=new Yn;return Object.assign(n,t),n})}else throw Error(`This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).`)}async get(e){let t,n=``,r={};if(this.apiClient.isVertexAI()){let i=Us(this.apiClient,e);return n=B(`{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=>oc(e))}else{let i=Hs(this.apiClient,e);return n=B(`{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=>ac(e))}}async listInternal(e){let t,n=``,r={};if(this.apiClient.isVertexAI()){let i=tc(this.apiClient,e);return n=B(`{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=rc(e),n=new Xn;return Object.assign(n,t),n})}else{let i=ec(this.apiClient,e);return n=B(`{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=nc(e),n=new Xn;return Object.assign(n,t),n})}}async update(e){let t,n=``,r={};if(this.apiClient.isVertexAI()){let i=Mc(this.apiClient,e);return n=B(`{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=>oc(e))}else{let i=jc(this.apiClient,e);return n=B(`{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=>ac(e))}}async delete(e){let t,n=``,r={};if(this.apiClient.isVertexAI()){let i=Zo(this.apiClient,e);return n=B(`{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=$o(e),n=new Zn;return Object.assign(n,t),n})}else{let i=Xo(this.apiClient,e);return n=B(`{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=Qo(e),n=new Zn;return Object.assign(n,t),n})}}async countTokens(e){let t,n=``,r={};if(this.apiClient.isVertexAI()){let i=qo(this.apiClient,e);return n=B(`{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=Yo(e),n=new Qn;return Object.assign(n,t),n})}else{let i=Ko(this.apiClient,e);return n=B(`{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=Jo(e),n=new Qn;return Object.assign(n,t),n})}}async computeTokens(e){let t,n=``,r={};if(this.apiClient.isVertexAI()){let i=Lo(this.apiClient,e);return n=B(`{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=Ro(e),n=new $n;return Object.assign(n,t),n})}else throw Error(`This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).`)}async generateVideosInternal(e){let t,n=``,r={};if(this.apiClient.isVertexAI()){let i=js(this.apiClient,e);return n=B(`{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=ks(e),n=new er;return Object.assign(n,t),n})}else{let i=As(this.apiClient,e);return n=B(`{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=Os(e),n=new er;return Object.assign(n,t),n})}}},Ml=class extends dt{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=Ct(e);return n=B(`{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=St(e);return n=B(`{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=ht(e);return n=B(`{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 Gemini Enterprise Agent Platform (previously known as Vertex AI).`)}};
139
+ /**
140
+ * @license
141
+ * Copyright 2025 Google LLC
142
+ * SPDX-License-Identifier: Apache-2.0
143
+ */
144
+ function Nl(e){let t={};if(H(e,[`languageCodes`])!==void 0)throw Error(`languageCodes parameter is not supported in Gemini API.`);return t}function Pl(e){let t={},n=H(e,[`apiKey`]);if(n!=null&&V(t,[`apiKey`],n),H(e,[`apiKeyConfig`])!==void 0)throw Error(`apiKeyConfig parameter is not supported in Gemini API.`);if(H(e,[`authType`])!==void 0)throw Error(`authType parameter is not supported in Gemini API.`);if(H(e,[`googleServiceAccountConfig`])!==void 0)throw Error(`googleServiceAccountConfig parameter is not supported in Gemini API.`);if(H(e,[`httpBasicAuthConfig`])!==void 0)throw Error(`httpBasicAuthConfig parameter is not supported in Gemini API.`);if(H(e,[`oauthConfig`])!==void 0)throw Error(`oauthConfig parameter is not supported in Gemini API.`);if(H(e,[`oidcConfig`])!==void 0)throw Error(`oidcConfig parameter is not supported in Gemini API.`);return t}function Fl(e){let t={},n=H(e,[`data`]);if(n!=null&&V(t,[`data`],n),H(e,[`displayName`])!==void 0)throw Error(`displayName parameter is not supported in Gemini API.`);let r=H(e,[`mimeType`]);return r!=null&&V(t,[`mimeType`],r),t}function Il(e){let t={},n=H(e,[`parts`]);if(n!=null){let e=n;Array.isArray(e)&&(e=e.map(e=>Gl(e))),V(t,[`parts`],e)}let r=H(e,[`role`]);return r!=null&&V(t,[`role`],r),t}function Ll(e,t,n){let r={},i=H(t,[`expireTime`]);n!==void 0&&i!=null&&V(n,[`expireTime`],i);let a=H(t,[`newSessionExpireTime`]);n!==void 0&&a!=null&&V(n,[`newSessionExpireTime`],a);let o=H(t,[`uses`]);n!==void 0&&o!=null&&V(n,[`uses`],o);let s=H(t,[`liveConnectConstraints`]);n!==void 0&&s!=null&&V(n,[`bidiGenerateContentSetup`],Wl(e,s));let c=H(t,[`lockAdditionalFields`]);return n!==void 0&&c!=null&&V(n,[`fieldMask`],c),r}function Rl(e,t){let n={},r=H(t,[`config`]);return r!=null&&V(n,[`config`],Ll(e,r,n)),n}function zl(e){let t={};if(H(e,[`displayName`])!==void 0)throw Error(`displayName parameter is not supported in Gemini API.`);let n=H(e,[`fileUri`]);n!=null&&V(t,[`fileUri`],n);let r=H(e,[`mimeType`]);return r!=null&&V(t,[`mimeType`],r),t}function Bl(e){let t={},n=H(e,[`id`]);n!=null&&V(t,[`id`],n);let r=H(e,[`args`]);r!=null&&V(t,[`args`],r);let i=H(e,[`name`]);if(i!=null&&V(t,[`name`],i),H(e,[`partialArgs`])!==void 0)throw Error(`partialArgs parameter is not supported in Gemini API.`);if(H(e,[`willContinue`])!==void 0)throw Error(`willContinue parameter is not supported in Gemini API.`);return t}function Vl(e){let t={},n=H(e,[`authConfig`]);n!=null&&V(t,[`authConfig`],Pl(n));let r=H(e,[`enableWidget`]);return r!=null&&V(t,[`enableWidget`],r),t}function Hl(e){let t={},n=H(e,[`searchTypes`]);if(n!=null&&V(t,[`searchTypes`],n),H(e,[`blockingConfidence`])!==void 0)throw Error(`blockingConfidence parameter is not supported in Gemini API.`);if(H(e,[`excludeDomains`])!==void 0)throw Error(`excludeDomains parameter is not supported in Gemini API.`);let r=H(e,[`timeRangeFilter`]);return r!=null&&V(t,[`timeRangeFilter`],r),t}function Ul(e,t){let n={},r=H(e,[`generationConfig`]);t!==void 0&&r!=null&&V(t,[`setup`,`generationConfig`],r);let i=H(e,[`responseModalities`]);t!==void 0&&i!=null&&V(t,[`setup`,`generationConfig`,`responseModalities`],i);let a=H(e,[`temperature`]);t!==void 0&&a!=null&&V(t,[`setup`,`generationConfig`,`temperature`],a);let o=H(e,[`topP`]);t!==void 0&&o!=null&&V(t,[`setup`,`generationConfig`,`topP`],o);let s=H(e,[`topK`]);t!==void 0&&s!=null&&V(t,[`setup`,`generationConfig`,`topK`],s);let c=H(e,[`maxOutputTokens`]);t!==void 0&&c!=null&&V(t,[`setup`,`generationConfig`,`maxOutputTokens`],c);let l=H(e,[`mediaResolution`]);t!==void 0&&l!=null&&V(t,[`setup`,`generationConfig`,`mediaResolution`],l);let u=H(e,[`seed`]);t!==void 0&&u!=null&&V(t,[`setup`,`generationConfig`,`seed`],u);let d=H(e,[`speechConfig`]);t!==void 0&&d!=null&&V(t,[`setup`,`generationConfig`,`speechConfig`],Mr(d));let f=H(e,[`thinkingConfig`]);t!==void 0&&f!=null&&V(t,[`setup`,`generationConfig`,`thinkingConfig`],f);let p=H(e,[`enableAffectiveDialog`]);t!==void 0&&p!=null&&V(t,[`setup`,`generationConfig`,`enableAffectiveDialog`],p);let m=H(e,[`systemInstruction`]);t!==void 0&&m!=null&&V(t,[`setup`,`systemInstruction`],Il(G(m)));let h=H(e,[`tools`]);if(t!==void 0&&h!=null){let e=Pr(h);Array.isArray(e)&&(e=e.map(e=>Jl(Nr(e)))),V(t,[`setup`,`tools`],e)}let g=H(e,[`sessionResumption`]);t!==void 0&&g!=null&&V(t,[`setup`,`sessionResumption`],ql(g));let _=H(e,[`inputAudioTranscription`]);t!==void 0&&_!=null&&V(t,[`setup`,`inputAudioTranscription`],Nl(_));let v=H(e,[`outputAudioTranscription`]);t!==void 0&&v!=null&&V(t,[`setup`,`outputAudioTranscription`],Nl(v));let y=H(e,[`realtimeInputConfig`]);t!==void 0&&y!=null&&V(t,[`setup`,`realtimeInputConfig`],y);let b=H(e,[`contextWindowCompression`]);t!==void 0&&b!=null&&V(t,[`setup`,`contextWindowCompression`],b);let x=H(e,[`proactivity`]);if(t!==void 0&&x!=null&&V(t,[`setup`,`proactivity`],x),H(e,[`explicitVadSignal`])!==void 0)throw Error(`explicitVadSignal parameter is not supported in Gemini API.`);let S=H(e,[`avatarConfig`]);t!==void 0&&S!=null&&V(t,[`setup`,`avatarConfig`],S);let C=H(e,[`safetySettings`]);if(t!==void 0&&C!=null){let e=C;Array.isArray(e)&&(e=e.map(e=>Kl(e))),V(t,[`setup`,`safetySettings`],e)}return n}function Wl(e,t){let n={},r=H(t,[`model`]);r!=null&&V(n,[`setup`,`model`],W(e,r));let i=H(t,[`config`]);return i!=null&&V(n,[`config`],Ul(i,n)),n}function Gl(e){let t={},n=H(e,[`mediaResolution`]);n!=null&&V(t,[`mediaResolution`],n);let r=H(e,[`codeExecutionResult`]);r!=null&&V(t,[`codeExecutionResult`],r);let i=H(e,[`executableCode`]);i!=null&&V(t,[`executableCode`],i);let a=H(e,[`fileData`]);a!=null&&V(t,[`fileData`],zl(a));let o=H(e,[`functionCall`]);o!=null&&V(t,[`functionCall`],Bl(o));let s=H(e,[`functionResponse`]);s!=null&&V(t,[`functionResponse`],s);let c=H(e,[`inlineData`]);c!=null&&V(t,[`inlineData`],Fl(c));let l=H(e,[`text`]);l!=null&&V(t,[`text`],l);let u=H(e,[`thought`]);u!=null&&V(t,[`thought`],u);let d=H(e,[`thoughtSignature`]);d!=null&&V(t,[`thoughtSignature`],d);let f=H(e,[`videoMetadata`]);f!=null&&V(t,[`videoMetadata`],f);let p=H(e,[`toolCall`]);p!=null&&V(t,[`toolCall`],p);let m=H(e,[`toolResponse`]);m!=null&&V(t,[`toolResponse`],m);let h=H(e,[`partMetadata`]);return h!=null&&V(t,[`partMetadata`],h),t}function Kl(e){let t={},n=H(e,[`category`]);if(n!=null&&V(t,[`category`],n),H(e,[`method`])!==void 0)throw Error(`method parameter is not supported in Gemini API.`);let r=H(e,[`threshold`]);return r!=null&&V(t,[`threshold`],r),t}function ql(e){let t={},n=H(e,[`handle`]);if(n!=null&&V(t,[`handle`],n),H(e,[`transparent`])!==void 0)throw Error(`transparent parameter is not supported in Gemini API.`);return t}function Jl(e){let t={};if(H(e,[`retrieval`])!==void 0)throw Error(`retrieval parameter is not supported in Gemini API.`);let n=H(e,[`computerUse`]);n!=null&&V(t,[`computerUse`],n);let r=H(e,[`fileSearch`]);r!=null&&V(t,[`fileSearch`],r);let i=H(e,[`googleSearch`]);i!=null&&V(t,[`googleSearch`],Hl(i));let a=H(e,[`googleMaps`]);a!=null&&V(t,[`googleMaps`],Vl(a));let o=H(e,[`codeExecution`]);if(o!=null&&V(t,[`codeExecution`],o),H(e,[`enterpriseWebSearch`])!==void 0)throw Error(`enterpriseWebSearch parameter is not supported in Gemini API.`);let s=H(e,[`functionDeclarations`]);if(s!=null){let e=s;Array.isArray(e)&&(e=e.map(e=>e)),V(t,[`functionDeclarations`],e)}let c=H(e,[`googleSearchRetrieval`]);if(c!=null&&V(t,[`googleSearchRetrieval`],c),H(e,[`parallelAiSearch`])!==void 0)throw Error(`parallelAiSearch parameter is not supported in Gemini API.`);let l=H(e,[`urlContext`]);l!=null&&V(t,[`urlContext`],l);let u=H(e,[`mcpServers`]);if(u!=null){let e=u;Array.isArray(e)&&(e=e.map(e=>e)),V(t,[`mcpServers`],e)}return t}
145
+ /**
146
+ * @license
147
+ * Copyright 2025 Google LLC
148
+ * SPDX-License-Identifier: Apache-2.0
149
+ */
150
+ function Yl(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 Xl(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=Yl(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 Zl=class extends dt{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=Rl(this.apiClient,e);n=B(`auth_tokens`,i._url),r=i._query,delete i.config,delete i._url,delete i._query;let a=Xl(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)}}};
151
+ /**
152
+ * @license
153
+ * Copyright 2025 Google LLC
154
+ * SPDX-License-Identifier: Apache-2.0
155
+ */
156
+ function Ql(e,t){let n={},r=H(e,[`force`]);return t!==void 0&&r!=null&&V(t,[`_query`,`force`],r),n}function $l(e){let t={},n=H(e,[`name`]);n!=null&&V(t,[`_url`,`name`],n);let r=H(e,[`config`]);return r!=null&&Ql(r,t),t}function eu(e){let t={},n=H(e,[`name`]);return n!=null&&V(t,[`_url`,`name`],n),t}function tu(e,t){let n={},r=H(e,[`pageSize`]);t!==void 0&&r!=null&&V(t,[`_query`,`pageSize`],r);let i=H(e,[`pageToken`]);return t!==void 0&&i!=null&&V(t,[`_query`,`pageToken`],i),n}function nu(e){let t={},n=H(e,[`parent`]);n!=null&&V(t,[`_url`,`parent`],n);let r=H(e,[`config`]);return r!=null&&tu(r,t),t}function ru(e){let t={},n=H(e,[`sdkHttpResponse`]);n!=null&&V(t,[`sdkHttpResponse`],n);let r=H(e,[`nextPageToken`]);r!=null&&V(t,[`nextPageToken`],r);let i=H(e,[`documents`]);if(i!=null){let e=i;Array.isArray(e)&&(e=e.map(e=>e)),V(t,[`documents`],e)}return t}
157
+ /**
158
+ * @license
159
+ * Copyright 2025 Google LLC
160
+ * SPDX-License-Identifier: Apache-2.0
161
+ */
162
+ var iu=class extends dt{constructor(e){super(),this.apiClient=e,this.list=async e=>new $i(Qi.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=eu(e);return n=B(`{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=$l(e);t=B(`{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=nu(e);return n=B(`{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=ru(e),n=new ar;return Object.assign(n,t),n})}}},au=class extends dt{constructor(e,t=new iu(e)){super(),this.apiClient=e,this.documents=t,this.list=async(e={})=>new $i(Qi.PAGED_ITEM_FILE_SEARCH_STORES,e=>this.listInternal(e),await this.listInternal(e),e)}async uploadToFileSearchStore(e){if(this.apiClient.isVertexAI())throw Error(`Gemini Enterprise Agent Platform (previously known as Vertex AI) does not support uploading files to a file search store.`);return this.apiClient.uploadFileToFileSearchStore(e.fileSearchStoreName,e.file,e.config)}async downloadMedia(e,t){if(this.apiClient.isVertexAI())throw Error(`This method is only supported in the Gemini Developer client.`);let n=new URL(e,`http://dummy.com`),r=n.pathname;if(r.startsWith(`/`)&&(r=r.slice(1)),!r.includes(`/media/`))throw Error(`Invalid uri format: ${e}. Expected to contain /media/`);let i={};n.searchParams.forEach((e,t)=>{i[t]=e}),i.alt=`media`;let a=Object.assign({},t?.httpOptions),o=await this.apiClient.request({path:r,httpMethod:`GET`,queryParams:i,httpOptions:a});if(o instanceof Hn){let e=await o.responseInternal.arrayBuffer();return new Uint8Array(e)}else throw Error(`Unexpected response type from downloadMedia`)}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=Wc(this.apiClient,e);return n=B(`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=qc(e);return n=B(`{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=Kc(e);t=B(`{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=$c(e);return n=B(`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=el(e),n=new or;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=nl(e);return n=B(`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=rl(e),n=new sr;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=Xc(e);return n=B(`{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=Yc(e),n=new cr;return Object.assign(n,t),n})}}};
163
+ /**
164
+ * @license
165
+ * Copyright 2025 Google LLC
166
+ * SPDX-License-Identifier: Apache-2.0
167
+ */
168
+ let ou=function(){let{crypto:e}=globalThis;if(e?.randomUUID)return ou=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 su=()=>ou();
169
+ /**
170
+ * @license
171
+ * Copyright 2025 Google LLC
172
+ * SPDX-License-Identifier: Apache-2.0
173
+ */
174
+ function cu(e){return typeof e==`object`&&!!e&&(`name`in e&&e.name===`AbortError`||`message`in e&&String(e.message).includes(`FetchRequestCanceledException`))}const lu=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)};
175
+ /**
176
+ * @license
177
+ * Copyright 2025 Google LLC
178
+ * SPDX-License-Identifier: Apache-2.0
179
+ */
180
+ var X=class extends Error{},Z=class e extends X{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 du({message:r,cause:lu(n)});let a=n;return t===400?new pu(t,a,r,i):t===401?new mu(t,a,r,i):t===403?new hu(t,a,r,i):t===404?new gu(t,a,r,i):t===409?new _u(t,a,r,i):t===422?new vu(t,a,r,i):t===429?new yu(t,a,r,i):t>=500?new bu(t,a,r,i):new e(t,a,r,i)}},uu=class extends Z{constructor({message:e}={}){super(void 0,void 0,e||`Request was aborted.`,void 0)}},du=class extends Z{constructor({message:e,cause:t}){super(void 0,void 0,e||`Connection error.`,void 0),t&&(this.cause=t)}},fu=class extends du{constructor({message:e}={}){super({message:e??`Request timed out.`})}},pu=class extends Z{},mu=class extends Z{},hu=class extends Z{},gu=class extends Z{},_u=class extends Z{},vu=class extends Z{},yu=class extends Z{},bu=class extends Z{};
181
+ /**
182
+ * @license
183
+ * Copyright 2025 Google LLC
184
+ * SPDX-License-Identifier: Apache-2.0
185
+ */
186
+ const xu=/^[a-z][a-z0-9+.-]*:/i,Su=e=>xu.test(e);let Cu=e=>(Cu=Array.isArray,Cu(e));const wu=Cu;function Tu(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 Du=(e,t)=>{if(typeof t!=`number`||!Number.isInteger(t))throw new X(`${e} must be an integer`);if(t<0)throw new X(`${e} must be a positive integer`);return t},Ou=e=>{try{return JSON.parse(e)}catch{return}},ku=e=>new Promise(t=>setTimeout(t,e));
187
+ /**
188
+ * @license
189
+ * Copyright 2025 Google LLC
190
+ * SPDX-License-Identifier: Apache-2.0
191
+ */
192
+ function Au(){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 ju(...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 Mu(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return ju({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 Nu(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 Pu(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}
193
+ /**
194
+ * @license
195
+ * Copyright 2025 Google LLC
196
+ * SPDX-License-Identifier: Apache-2.0
197
+ */
198
+ const Fu=({headers:e,body:t})=>({bodyHeaders:{"content-type":`application/json`},body:JSON.stringify(t)});
199
+ /**
200
+ * @license
201
+ * Copyright 2025 Google LLC
202
+ * SPDX-License-Identifier: Apache-2.0
203
+ */
204
+ function Iu(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 X(`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(`&`)}
205
+ /**
206
+ * @license
207
+ * Copyright 2025 Google LLC
208
+ * SPDX-License-Identifier: Apache-2.0
209
+ */
210
+ const Lu=()=>{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 Ru(e,t,n){return Lu(),new File(e,t??`unknown_file`,n)}function zu(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 Bu=e=>typeof e==`object`&&!!e&&typeof e[Symbol.asyncIterator]==`function`,Vu=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`,Hu=e=>typeof e==`object`&&!!e&&typeof e.name==`string`&&typeof e.lastModified==`number`&&Vu(e),Uu=e=>typeof e==`object`&&!!e&&typeof e.url==`string`&&typeof e.blob==`function`;async function Wu(e,t,n){if(Lu(),e=await e,Hu(e))return e instanceof File?e:Ru([await e.arrayBuffer()],e.name);if(Uu(e)){let r=await e.blob();return t||=new URL(e.url).pathname.split(/[\\/]/).pop(),Ru(await Gu(r),t,n)}let r=await Gu(e);if(t||=zu(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 Ru(r,t,n)}async function Gu(e){var t,n,r,i;let a=[];if(typeof e==`string`||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)a.push(e);else if(Vu(e))a.push(e instanceof Blob?e:await e.arrayBuffer());else if(Bu(e))try{for(var o=!0,s=Y(e),c;c=await s.next(),t=c.done,!t;o=!0){i=c.value,o=!1;let e=i;a.push(...await Gu(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}`:``}${Ku(e)}`)}return a}function Ku(e){return typeof e!=`object`||!e?``:`; props: [${Object.getOwnPropertyNames(e).map(e=>`"${e}"`).join(`, `)}]`}
211
+ /**
212
+ * @license
213
+ * Copyright 2025 Google LLC
214
+ * SPDX-License-Identifier: Apache-2.0
215
+ */
216
+ var qu=class{constructor(e){this._client=e}};qu._key=[];
217
+ /**
218
+ * @license
219
+ * Copyright 2025 Google LLC
220
+ * SPDX-License-Identifier: Apache-2.0
221
+ */
222
+ function Ju(e){return e.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}const Yu=Object.freeze(Object.create(null)),Xu=((e=Ju)=>(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??Yu)??Yu)?.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?1:0,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 X(`Path parameters result in path with invalid segments:\n${i.map(e=>e.error).join(`
223
+ `)}\n${a}\n${t}`)}return a}))(Ju);
224
+ /**
225
+ * @license
226
+ * Copyright 2025 Google LLC
227
+ * SPDX-License-Identifier: Apache-2.0
228
+ */
229
+ var Zu=class extends qu{create(e,t){let{api_version:n=this._client.apiVersion}=e,r=Ra(e,[`api_version`]);if(`model`in r&&`agent_config`in r)throw new X("Invalid request: specified `model` and `agent_config`. If specifying `model`, use `generation_config`.");if(`agent`in r&&`generation_config`in r)throw new X("Invalid request: specified `agent` and `generation_config`. If specifying `agent`, use `agent_config`.");return this._client.post(Xu`/${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(Xu`/${r}/interactions/${e}`,n)}cancel(e,t={},n){let{api_version:r=this._client.apiVersion}=t??{};return this._client.post(Xu`/${r}/interactions/${e}/cancel`,n)}get(e,t={},n){let r=t??{},{api_version:i=this._client.apiVersion}=r,a=Ra(r,[`api_version`]);return this._client.get(Xu`/${i}/interactions/${e}`,Object.assign(Object.assign({query:a},n),{stream:t?.stream??!1}))}};Zu._key=Object.freeze([`interactions`]);var Qu=class extends Zu{},$u=class extends qu{create(e,t){let{api_version:n=this._client.apiVersion}=e,r=Ra(e,[`api_version`]);return this._client.post(Xu`/${n}/webhooks`,Object.assign({body:r},t))}update(e,t={},n){let r=t??{},{api_version:i=this._client.apiVersion,update_mask:a}=r,o=Ra(r,[`api_version`,`update_mask`]);return this._client.patch(Xu`/${i}/webhooks/${e}`,Object.assign({query:{update_mask:a},body:o},n))}list(e={},t){let n=e??{},{api_version:r=this._client.apiVersion}=n,i=Ra(n,[`api_version`]);return this._client.get(Xu`/${r}/webhooks`,Object.assign({query:i},t))}delete(e,t={},n){let{api_version:r=this._client.apiVersion}=t??{};return this._client.delete(Xu`/${r}/webhooks/${e}`,n)}get(e,t={},n){let{api_version:r=this._client.apiVersion}=t??{};return this._client.get(Xu`/${r}/webhooks/${e}`,n)}ping(e,t=void 0,n){let{api_version:r=this._client.apiVersion,body:i}=t??{};return this._client.post(Xu`/${r}/webhooks/${e}:ping`,Object.assign({body:i},n))}rotateSigningSecret(e,t={},n){let r=t??{},{api_version:i=this._client.apiVersion}=r,a=Ra(r,[`api_version`]);return this._client.post(Xu`/${i}/webhooks/${e}:rotateSigningSecret`,Object.assign({body:a},n))}};$u._key=Object.freeze([`webhooks`]);var ed=class extends $u{};
230
+ /**
231
+ * @license
232
+ * Copyright 2025 Google LLC
233
+ * SPDX-License-Identifier: Apache-2.0
234
+ */
235
+ function td(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 nd;function rd(e){let t;return(nd??=(t=new globalThis.TextEncoder,t.encode.bind(t)))(e)}let id;function ad(e){let t;return(id??=(t=new globalThis.TextDecoder,t.decode.bind(t)))(e)}
236
+ /**
237
+ * @license
238
+ * Copyright 2025 Google LLC
239
+ * SPDX-License-Identifier: Apache-2.0
240
+ */
241
+ var od=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`?rd(e):e;this.buffer=td([this.buffer,t]);let n=[],r;for(;(r=sd(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(ad(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=ad(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(`
242
+ `):[]}};od.NEWLINE_CHARS=new Set([`
243
+ `,`\r`]),od.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function sd(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}}
244
+ /**
245
+ * @license
246
+ * Copyright 2025 Google LLC
247
+ * SPDX-License-Identifier: Apache-2.0
248
+ */
249
+ const cd={off:0,error:200,warn:300,info:400,debug:500},ld=(e,t,n)=>{if(e){if(Eu(cd,e))return e;Q(n).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(cd))}`)}};function ud(){}function dd(e,t,n){return!t||cd[e]>cd[n]?ud:t[e].bind(t)}const fd={error:ud,warn:ud,info:ud,debug:ud};let pd=new WeakMap;function Q(e){let t=e.logger,n=e.logLevel??`off`;if(!t)return fd;let r=pd.get(t);if(r&&r[0]===n)return r[1];let i={error:dd(`error`,t,n),warn:dd(`warn`,t,n),info:dd(`info`,t,n),debug:dd(`debug`,t,n)};return pd.set(t,[n,i]),i}const md=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);
250
+ /**
251
+ * @license
252
+ * Copyright 2025 Google LLC
253
+ * SPDX-License-Identifier: Apache-2.0
254
+ */
255
+ var hd=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 J(this,arguments,function*(){var e,r,o,s;if(i)throw new X("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");i=!0;let c=!1;try{try{for(var l=!0,u=Y(gd(t,n)),d;d=yield q(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 q(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 q(o.call(u)))}finally{if(r)throw r.error}}c=!0}catch(e){if(cu(e))return yield q(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 J(this,arguments,function*(){var e,n,r,i;let a=new od,o=Nu(t);try{for(var s=!0,c=Y(o),l;l=yield q(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 q(t)}}catch(e){n={error:e}}finally{try{!s&&!e&&(r=c.return)&&(yield q(r.call(c)))}finally{if(n)throw n.error}}for(let e of a.flush())yield yield q(e)})}function o(){return J(this,arguments,function*(){var e,t,r,o;if(i)throw new X("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");i=!0;let s=!1;try{try{for(var c=!0,l=Y(a()),u;u=yield q(l.next()),e=u.done,!e;c=!0){o=u.value,c=!1;let e=o;s||e&&(yield yield q(JSON.parse(e)))}}catch(e){t={error:e}}finally{try{!c&&!e&&(r=l.return)&&(yield q(r.call(l)))}finally{if(t)throw t.error}}s=!0}catch(e){if(cu(e))return yield q(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 ju({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=rd(JSON.stringify(n)+`
256
+ `);e.enqueue(i)}catch(t){e.error(t)}},async cancel(){await t.return?.call(t)}})}};function gd(e,t){return J(this,arguments,function*(){var n,r,i,a;if(!e.body)throw t.abort(),globalThis.navigator!==void 0&&globalThis.navigator.product===`ReactNative`?new X(`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 X(`Attempted to iterate over a response with no body`);let o=new vd,s=new od,c=Nu(e.body);try{for(var l=!0,u=Y(_d(c)),d;d=yield q(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 q(e))}}}catch(e){r={error:e}}finally{try{!l&&!n&&(i=u.return)&&(yield q(i.call(u)))}finally{if(r)throw r.error}}for(let e of s.flush()){let t=o.decode(e);t&&(yield yield q(t))}})}function _d(e){return J(this,arguments,function*(){var t,n,r,i;try{for(var a=!0,o=Y(e),s;s=yield q(o.next()),t=s.done,!t;a=!0){i=s.value,a=!1;let e=i;e!=null&&(yield yield q(e instanceof ArrayBuffer?new Uint8Array(e):typeof e==`string`?rd(e):e))}}catch(e){n={error:e}}finally{try{!a&&!t&&(r=o.return)&&(yield q(r.call(o)))}finally{if(n)throw n.error}}})}var vd=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(`
257
+ `),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]=yd(e,`:`);return r.startsWith(` `)&&(r=r.substring(1)),t===`event`?this.event=r:t===`data`&&this.data.push(r),null}};function yd(e,t){let n=e.indexOf(t);return n===-1?[e,``,``]:[e.substring(0,n),t,e.substring(n+t.length)]}
258
+ /**
259
+ * @license
260
+ * Copyright 2025 Google LLC
261
+ * SPDX-License-Identifier: Apache-2.0
262
+ */
263
+ async function bd(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):hd.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`,md({retryOfRequestLogID:i,url:n.url,status:n.status,body:o,durationMs:Date.now()-a})),o}
264
+ /**
265
+ * @license
266
+ * Copyright 2025 Google LLC
267
+ * SPDX-License-Identifier: Apache-2.0
268
+ */
269
+ var xd=class e extends Promise{constructor(e,t,n=bd){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)}};
270
+ /**
271
+ * @license
272
+ * Copyright 2025 Google LLC
273
+ * SPDX-License-Identifier: Apache-2.0
274
+ */
275
+ const Sd=Symbol(`brand.privateNullableHeaders`);function*Cd(e){if(!e)return;if(Sd 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():wu(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=wu(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 wd=e=>{let t=new Headers,n=new Set;for(let r of e){let e=new Set;for(let[i,a]of Cd(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{[Sd]:!0,values:t,nulls:n}},Td=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};
276
+ /**
277
+ * @license
278
+ * Copyright 2025 Google LLC
279
+ * SPDX-License-Identifier: Apache-2.0
280
+ */
281
+ var Ed,Dd=class e{constructor(t){var{baseURL:n=Td(`GEMINI_NEXT_GEN_API_BASE_URL`),apiKey:r=Td(`GEMINI_API_KEY`)??null,apiVersion:i=`v1beta`}=t,a=Ra(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=ld(o.logLevel,`ClientOptions.logLevel`,this)??ld(Td(`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??Au(),this.encoder=Fu,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=wd([e.headers]);if(!(t.values.has(`authorization`)||t.values.has(`x-goog-api-key`))){if(this.apiKey)return wd([{"x-goog-api-key":this.apiKey}]);if(this.clientAdapter&&this.clientAdapter.isVertexAI())return wd([await this.clientAdapter.getAuthHeaders()])}}stringifyQuery(e){return Iu(e)}getUserAgent(){return`${this.constructor.name}/JS 0.0.1`}defaultIdempotencyKey(){return`stainless-node-retry-${su()}`}makeStatusError(e,t,n,r){return Z.generate(e,t,n,r)}buildURL(e,t,n){let r=!this.baseURLOverridden()&&n||this.baseURL,i=Su(e)?new URL(e):new URL(r+(r.endsWith(`/`)&&e.startsWith(`/`)?e.slice(1):e)),a=this.defaultQuery(),o=Object.fromEntries(i.searchParams);return(!Tu(a)||!Tu(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 xd(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`,md({retryOfRequestLogID:n,method:r.method,url:o,options:r,headers:a.headers})),r.signal?.aborted)throw new uu;let d=new AbortController,f=await this.fetchWithTimeout(o,a,s,d).catch(lu),p=Date.now();if(f instanceof globalThis.Error){let e=`retrying, ${t} attempts remaining`;if(r.signal?.aborted)throw new uu;let i=cu(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})`,md({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)`,md({retryOfRequestLogID:n,url:o,durationMs:p-u,message:f.message})),i?new fu:new du({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 Pu(f.body),Q(this).info(`${m} - ${e}`),Q(this).debug(`[${c}] response error (${e})`,md({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=>lu(e).message),o=Ou(a),s=o?void 0:a;throw Q(this).debug(`[${c}] response error (${i})`,md({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`,md({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=Ra(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 ku(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&&Du(`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=wd([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=wd([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:Mu(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})}};Dd.DEFAULT_TIMEOUT=6e4;var $=class extends Dd{constructor(){super(...arguments),this.interactions=new Qu(this),this.webhooks=new ed(this)}};Ed=$,$.GeminiNextGenAPIClient=Ed,$.GeminiNextGenAPIClientError=X,$.APIError=Z,$.APIConnectionError=du,$.APIConnectionTimeoutError=fu,$.APIUserAbortError=uu,$.NotFoundError=gu,$.ConflictError=_u,$.RateLimitError=yu,$.BadRequestError=pu,$.AuthenticationError=mu,$.InternalServerError=bu,$.PermissionDeniedError=hu,$.UnprocessableEntityError=vu,$.toFile=Wu,$.Interactions=Qu,$.Webhooks=ed;
282
+ /**
283
+ * @license
284
+ * Copyright 2025 Google LLC
285
+ * SPDX-License-Identifier: Apache-2.0
286
+ */
287
+ const Od=`x-goog-api-key`,kd=`https://www.googleapis.com/auth/cloud-platform`;var Ad=class{constructor(e){if(e.apiKey!==void 0){this.apiKey=e.apiKey;return}this.googleAuth=new ct.GoogleAuth(jd(e.googleAuthOptions))}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(Od)===null){if(this.apiKey===void 0)throw Error(`Trying to set API key header but apiKey is not set`);e.append(Od,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 jd(e){let t;if(e){if(t=e,!t.scopes)return t.scopes=[kd],t;if(typeof t.scopes==`string`&&t.scopes!==kd||Array.isArray(t.scopes)&&t.scopes.indexOf(kd)<0)throw Error(`Invalid auth scopes. Scopes must include: ${kd}`);return t}else return t={scopes:[kd]},t}
288
+ /**
289
+ * @license
290
+ * Copyright 2025 Google LLC
291
+ * SPDX-License-Identifier: Apache-2.0
292
+ */
293
+ var Md=class{async download(e,t){if(e.downloadPath){let n=await Nd(e,t);if(n instanceof Hn){let t=a(e.downloadPath);s.fromWeb(n.responseInternal.body).pipe(t),await c(t)}else try{await u(e.downloadPath,n,{encoding:`base64`})}catch(t){throw Error(`Failed to write file to ${e.downloadPath}: ${t}`)}}}};async function Nd(e,t){let n=Hr(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(Br(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(Vr(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`)}
294
+ /**
295
+ * @license
296
+ * Copyright 2025 Google LLC
297
+ * SPDX-License-Identifier: Apache-2.0
298
+ */
299
+ var Pd=class{create(e,t,n){return new Fd(e,t,n)}},Fd=class{constructor(e,t,n){this.url=e,this.headers=t,this.callbacks=n}connect(){this.ws=new ot.default(this.url,{headers:this.headers}),this.ws.onopen=this.callbacks.onopen,this.ws.onerror=this.callbacks.onerror,this.ws.onclose=this.callbacks.onclose,this.ws.onmessage=this.callbacks.onmessage}send(e){if(this.ws===void 0)throw Error(`WebSocket is not connected`);this.ws.send(e)}close(){if(this.ws===void 0)throw Error(`WebSocket is not connected`);this.ws.close()}};
300
+ /**
301
+ * @license
302
+ * Copyright 2025 Google LLC
303
+ * SPDX-License-Identifier: Apache-2.0
304
+ */
305
+ function Id(e,t){let n={},r=H(e,[`name`]);return r!=null&&V(n,[`_url`,`name`],r),n}function Ld(e,t){let n={},r=H(e,[`name`]);return r!=null&&V(n,[`_url`,`name`],r),n}function Rd(e,t){let n={},r=H(e,[`sdkHttpResponse`]);return r!=null&&V(n,[`sdkHttpResponse`],r),n}function zd(e,t){let n={},r=H(e,[`sdkHttpResponse`]);return r!=null&&V(n,[`sdkHttpResponse`],r),n}function Bd(e,t,n){let r={};if(H(e,[`validationDataset`])!==void 0)throw Error(`validationDataset parameter is not supported in Gemini API.`);let i=H(e,[`tunedModelDisplayName`]);if(t!==void 0&&i!=null&&V(t,[`displayName`],i),H(e,[`description`])!==void 0)throw Error(`description parameter is not supported in Gemini API.`);let a=H(e,[`epochCount`]);t!==void 0&&a!=null&&V(t,[`tuningTask`,`hyperparameters`,`epochCount`],a);let o=H(e,[`learningRateMultiplier`]);if(o!=null&&V(r,[`tuningTask`,`hyperparameters`,`learningRateMultiplier`],o),H(e,[`exportLastCheckpointOnly`])!==void 0)throw Error(`exportLastCheckpointOnly parameter is not supported in Gemini API.`);if(H(e,[`preTunedModelCheckpointId`])!==void 0)throw Error(`preTunedModelCheckpointId parameter is not supported in Gemini API.`);if(H(e,[`adapterSize`])!==void 0)throw Error(`adapterSize parameter is not supported in Gemini API.`);if(H(e,[`tuningMode`])!==void 0)throw Error(`tuningMode parameter is not supported in Gemini API.`);if(H(e,[`customBaseModel`])!==void 0)throw Error(`customBaseModel parameter is not supported in Gemini API.`);let s=H(e,[`batchSize`]);t!==void 0&&s!=null&&V(t,[`tuningTask`,`hyperparameters`,`batchSize`],s);let c=H(e,[`learningRate`]);if(t!==void 0&&c!=null&&V(t,[`tuningTask`,`hyperparameters`,`learningRate`],c),H(e,[`labels`])!==void 0)throw Error(`labels parameter is not supported in Gemini API.`);if(H(e,[`beta`])!==void 0)throw Error(`beta parameter is not supported in Gemini API.`);if(H(e,[`baseTeacherModel`])!==void 0)throw Error(`baseTeacherModel parameter is not supported in Gemini API.`);if(H(e,[`tunedTeacherModelSource`])!==void 0)throw Error(`tunedTeacherModelSource parameter is not supported in Gemini API.`);if(H(e,[`sftLossWeightMultiplier`])!==void 0)throw Error(`sftLossWeightMultiplier parameter is not supported in Gemini API.`);if(H(e,[`outputUri`])!==void 0)throw Error(`outputUri parameter is not supported in Gemini API.`);if(H(e,[`encryptionSpec`])!==void 0)throw Error(`encryptionSpec parameter is not supported in Gemini API.`);return r}function Vd(e,t,n){let r={},i=H(n,[`config`,`method`]);if(i===void 0&&(i=`SUPERVISED_FINE_TUNING`),i===`SUPERVISED_FINE_TUNING`){let n=H(e,[`validationDataset`]);t!==void 0&&n!=null&&V(t,[`supervisedTuningSpec`],tf(n))}else if(i===`PREFERENCE_TUNING`){let n=H(e,[`validationDataset`]);t!==void 0&&n!=null&&V(t,[`preferenceOptimizationSpec`],tf(n))}else if(i===`DISTILLATION`){let n=H(e,[`validationDataset`]);t!==void 0&&n!=null&&V(t,[`distillationSpec`],tf(n))}let a=H(e,[`tunedModelDisplayName`]);t!==void 0&&a!=null&&V(t,[`tunedModelDisplayName`],a);let o=H(e,[`description`]);t!==void 0&&o!=null&&V(t,[`description`],o);let s=H(n,[`config`,`method`]);if(s===void 0&&(s=`SUPERVISED_FINE_TUNING`),s===`SUPERVISED_FINE_TUNING`){let n=H(e,[`epochCount`]);t!==void 0&&n!=null&&V(t,[`supervisedTuningSpec`,`hyperParameters`,`epochCount`],n)}else if(s===`PREFERENCE_TUNING`){let n=H(e,[`epochCount`]);t!==void 0&&n!=null&&V(t,[`preferenceOptimizationSpec`,`hyperParameters`,`epochCount`],n)}else if(s===`DISTILLATION`){let n=H(e,[`epochCount`]);t!==void 0&&n!=null&&V(t,[`distillationSpec`,`hyperParameters`,`epochCount`],n)}let c=H(n,[`config`,`method`]);if(c===void 0&&(c=`SUPERVISED_FINE_TUNING`),c===`SUPERVISED_FINE_TUNING`){let n=H(e,[`learningRateMultiplier`]);t!==void 0&&n!=null&&V(t,[`supervisedTuningSpec`,`hyperParameters`,`learningRateMultiplier`],n)}else if(c===`PREFERENCE_TUNING`){let n=H(e,[`learningRateMultiplier`]);t!==void 0&&n!=null&&V(t,[`preferenceOptimizationSpec`,`hyperParameters`,`learningRateMultiplier`],n)}else if(c===`DISTILLATION`){let n=H(e,[`learningRateMultiplier`]);t!==void 0&&n!=null&&V(t,[`distillationSpec`,`hyperParameters`,`learningRateMultiplier`],n)}let l=H(n,[`config`,`method`]);if(l===void 0&&(l=`SUPERVISED_FINE_TUNING`),l===`SUPERVISED_FINE_TUNING`){let n=H(e,[`exportLastCheckpointOnly`]);t!==void 0&&n!=null&&V(t,[`supervisedTuningSpec`,`exportLastCheckpointOnly`],n)}else if(l===`PREFERENCE_TUNING`){let n=H(e,[`exportLastCheckpointOnly`]);t!==void 0&&n!=null&&V(t,[`preferenceOptimizationSpec`,`exportLastCheckpointOnly`],n)}else if(l===`DISTILLATION`){let n=H(e,[`exportLastCheckpointOnly`]);t!==void 0&&n!=null&&V(t,[`distillationSpec`,`exportLastCheckpointOnly`],n)}let u=H(n,[`config`,`method`]);if(u===void 0&&(u=`SUPERVISED_FINE_TUNING`),u===`SUPERVISED_FINE_TUNING`){let n=H(e,[`adapterSize`]);t!==void 0&&n!=null&&V(t,[`supervisedTuningSpec`,`hyperParameters`,`adapterSize`],n)}else if(u===`PREFERENCE_TUNING`){let n=H(e,[`adapterSize`]);t!==void 0&&n!=null&&V(t,[`preferenceOptimizationSpec`,`hyperParameters`,`adapterSize`],n)}else if(u===`DISTILLATION`){let n=H(e,[`adapterSize`]);t!==void 0&&n!=null&&V(t,[`distillationSpec`,`hyperParameters`,`adapterSize`],n)}let d=H(n,[`config`,`method`]);if(d===void 0&&(d=`SUPERVISED_FINE_TUNING`),d===`SUPERVISED_FINE_TUNING`){let n=H(e,[`tuningMode`]);t!==void 0&&n!=null&&V(t,[`supervisedTuningSpec`,`tuningMode`],n)}else if(d===`DISTILLATION`){let n=H(e,[`tuningMode`]);t!==void 0&&n!=null&&V(t,[`distillationSpec`,`tuningMode`],n)}let f=H(e,[`customBaseModel`]);t!==void 0&&f!=null&&V(t,[`customBaseModel`],f);let p=H(n,[`config`,`method`]);if(p===void 0&&(p=`SUPERVISED_FINE_TUNING`),p===`SUPERVISED_FINE_TUNING`){let n=H(e,[`batchSize`]);t!==void 0&&n!=null&&V(t,[`supervisedTuningSpec`,`hyperParameters`,`batchSize`],n)}else if(p===`DISTILLATION`){let n=H(e,[`batchSize`]);t!==void 0&&n!=null&&V(t,[`distillationSpec`,`hyperParameters`,`batchSize`],n)}let m=H(n,[`config`,`method`]);if(m===void 0&&(m=`SUPERVISED_FINE_TUNING`),m===`SUPERVISED_FINE_TUNING`){let n=H(e,[`learningRate`]);t!==void 0&&n!=null&&V(t,[`supervisedTuningSpec`,`hyperParameters`,`learningRate`],n)}else if(m===`DISTILLATION`){let n=H(e,[`learningRate`]);t!==void 0&&n!=null&&V(t,[`distillationSpec`,`hyperParameters`,`learningRate`],n)}let h=H(e,[`labels`]);t!==void 0&&h!=null&&V(t,[`labels`],h);let g=H(e,[`beta`]);t!==void 0&&g!=null&&V(t,[`preferenceOptimizationSpec`,`hyperParameters`,`beta`],g);let _=H(e,[`baseTeacherModel`]);t!==void 0&&_!=null&&V(t,[`distillationSpec`,`baseTeacherModel`],_);let v=H(e,[`tunedTeacherModelSource`]);t!==void 0&&v!=null&&V(t,[`distillationSpec`,`tunedTeacherModelSource`],v);let y=H(e,[`sftLossWeightMultiplier`]);t!==void 0&&y!=null&&V(t,[`distillationSpec`,`hyperParameters`,`sftLossWeightMultiplier`],y);let b=H(e,[`outputUri`]);t!==void 0&&b!=null&&V(t,[`outputUri`],b);let x=H(e,[`encryptionSpec`]);return t!==void 0&&x!=null&&V(t,[`encryptionSpec`],x),r}function Hd(e,t){let n={},r=H(e,[`baseModel`]);r!=null&&V(n,[`baseModel`],r);let i=H(e,[`preTunedModel`]);i!=null&&V(n,[`preTunedModel`],i);let a=H(e,[`trainingDataset`]);a!=null&&Xd(a);let o=H(e,[`config`]);return o!=null&&Bd(o,n),n}function Ud(e,t){let n={},r=H(e,[`baseModel`]);r!=null&&V(n,[`baseModel`],r);let i=H(e,[`preTunedModel`]);i!=null&&V(n,[`preTunedModel`],i);let a=H(e,[`trainingDataset`]);a!=null&&Zd(a,n,t);let o=H(e,[`config`]);return o!=null&&Vd(o,n,t),n}function Wd(e,t){let n={},r=H(e,[`name`]);return r!=null&&V(n,[`_url`,`name`],r),n}function Gd(e,t){let n={},r=H(e,[`name`]);return r!=null&&V(n,[`_url`,`name`],r),n}function Kd(e,t,n){let r={},i=H(e,[`pageSize`]);t!==void 0&&i!=null&&V(t,[`_query`,`pageSize`],i);let a=H(e,[`pageToken`]);t!==void 0&&a!=null&&V(t,[`_query`,`pageToken`],a);let o=H(e,[`filter`]);return t!==void 0&&o!=null&&V(t,[`_query`,`filter`],o),r}function qd(e,t){let n={},r=H(e,[`config`]);return r!=null&&Kd(r,n),n}function Jd(e,t){let n={},r=H(e,[`sdkHttpResponse`]);r!=null&&V(n,[`sdkHttpResponse`],r);let i=H(e,[`nextPageToken`]);i!=null&&V(n,[`nextPageToken`],i);let a=H(e,[`tuningJobs`]);if(a!=null){let e=a;Array.isArray(e)&&(e=e.map(e=>$d(e))),V(n,[`tuningJobs`],e)}return n}function Yd(e,t){let n={},r=H(e,[`name`]);r!=null&&V(n,[`model`],r);let i=H(e,[`name`]);return i!=null&&V(n,[`endpoint`],i),n}function Xd(e,t){let n={};if(H(e,[`gcsUri`])!==void 0)throw Error(`gcsUri parameter is not supported in Gemini API.`);if(H(e,[`vertexDatasetResource`])!==void 0)throw Error(`vertexDatasetResource parameter is not supported in Gemini API.`);let r=H(e,[`examples`]);if(r!=null){let e=r;Array.isArray(e)&&(e=e.map(e=>e)),V(n,[`examples`,`examples`],e)}return n}function Zd(e,t,n){let r={},i=H(n,[`config`,`method`]);if(i===void 0&&(i=`SUPERVISED_FINE_TUNING`),i===`SUPERVISED_FINE_TUNING`){let n=H(e,[`gcsUri`]);t!==void 0&&n!=null&&V(t,[`supervisedTuningSpec`,`trainingDatasetUri`],n)}else if(i===`PREFERENCE_TUNING`){let n=H(e,[`gcsUri`]);t!==void 0&&n!=null&&V(t,[`preferenceOptimizationSpec`,`trainingDatasetUri`],n)}else if(i===`DISTILLATION`){let n=H(e,[`gcsUri`]);t!==void 0&&n!=null&&V(t,[`distillationSpec`,`promptDatasetUri`],n)}let a=H(n,[`config`,`method`]);if(a===void 0&&(a=`SUPERVISED_FINE_TUNING`),a===`SUPERVISED_FINE_TUNING`){let n=H(e,[`vertexDatasetResource`]);t!==void 0&&n!=null&&V(t,[`supervisedTuningSpec`,`trainingDatasetUri`],n)}else if(a===`PREFERENCE_TUNING`){let n=H(e,[`vertexDatasetResource`]);t!==void 0&&n!=null&&V(t,[`preferenceOptimizationSpec`,`trainingDatasetUri`],n)}else if(a===`DISTILLATION`){let n=H(e,[`vertexDatasetResource`]);t!==void 0&&n!=null&&V(t,[`distillationSpec`,`promptDatasetUri`],n)}if(H(e,[`examples`])!==void 0)throw Error(`examples parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).`);return r}function Qd(e,t){let n={},r=H(e,[`sdkHttpResponse`]);r!=null&&V(n,[`sdkHttpResponse`],r);let i=H(e,[`name`]);i!=null&&V(n,[`name`],i);let a=H(e,[`state`]);a!=null&&V(n,[`state`],Lr(a));let o=H(e,[`createTime`]);o!=null&&V(n,[`createTime`],o);let s=H(e,[`tuningTask`,`startTime`]);s!=null&&V(n,[`startTime`],s);let c=H(e,[`tuningTask`,`completeTime`]);c!=null&&V(n,[`endTime`],c);let l=H(e,[`updateTime`]);l!=null&&V(n,[`updateTime`],l);let u=H(e,[`description`]);u!=null&&V(n,[`description`],u);let d=H(e,[`baseModel`]);d!=null&&V(n,[`baseModel`],d);let f=H(e,[`_self`]);return f!=null&&V(n,[`tunedModel`],Yd(f)),n}function $d(e,t){let n={},r=H(e,[`sdkHttpResponse`]);r!=null&&V(n,[`sdkHttpResponse`],r);let i=H(e,[`name`]);i!=null&&V(n,[`name`],i);let a=H(e,[`state`]);a!=null&&V(n,[`state`],Lr(a));let o=H(e,[`createTime`]);o!=null&&V(n,[`createTime`],o);let s=H(e,[`startTime`]);s!=null&&V(n,[`startTime`],s);let c=H(e,[`endTime`]);c!=null&&V(n,[`endTime`],c);let l=H(e,[`updateTime`]);l!=null&&V(n,[`updateTime`],l);let u=H(e,[`error`]);u!=null&&V(n,[`error`],u);let d=H(e,[`description`]);d!=null&&V(n,[`description`],d);let f=H(e,[`baseModel`]);f!=null&&V(n,[`baseModel`],f);let p=H(e,[`tunedModel`]);p!=null&&V(n,[`tunedModel`],p);let m=H(e,[`preTunedModel`]);m!=null&&V(n,[`preTunedModel`],m);let h=H(e,[`supervisedTuningSpec`]);h!=null&&V(n,[`supervisedTuningSpec`],h);let g=H(e,[`preferenceOptimizationSpec`]);g!=null&&V(n,[`preferenceOptimizationSpec`],g);let _=H(e,[`distillationSpec`]);_!=null&&V(n,[`distillationSpec`],_);let v=H(e,[`tuningDataStats`]);v!=null&&V(n,[`tuningDataStats`],v);let y=H(e,[`encryptionSpec`]);y!=null&&V(n,[`encryptionSpec`],y);let b=H(e,[`partnerModelTuningSpec`]);b!=null&&V(n,[`partnerModelTuningSpec`],b);let x=H(e,[`customBaseModel`]);x!=null&&V(n,[`customBaseModel`],x);let S=H(e,[`evaluateDatasetRuns`]);if(S!=null){let e=S;Array.isArray(e)&&(e=e.map(e=>e)),V(n,[`evaluateDatasetRuns`],e)}let C=H(e,[`experiment`]);C!=null&&V(n,[`experiment`],C);let w=H(e,[`fullFineTuningSpec`]);w!=null&&V(n,[`fullFineTuningSpec`],w);let T=H(e,[`labels`]);T!=null&&V(n,[`labels`],T);let E=H(e,[`outputUri`]);E!=null&&V(n,[`outputUri`],E);let D=H(e,[`pipelineJob`]);D!=null&&V(n,[`pipelineJob`],D);let O=H(e,[`serviceAccount`]);O!=null&&V(n,[`serviceAccount`],O);let k=H(e,[`tunedModelDisplayName`]);k!=null&&V(n,[`tunedModelDisplayName`],k);let A=H(e,[`tuningJobState`]);A!=null&&V(n,[`tuningJobState`],A);let j=H(e,[`veoTuningSpec`]);j!=null&&V(n,[`veoTuningSpec`],j);let M=H(e,[`distillationSamplingSpec`]);M!=null&&V(n,[`distillationSamplingSpec`],M);let N=H(e,[`tuningJobMetadata`]);return N!=null&&V(n,[`tuningJobMetadata`],N),n}function ef(e,t){let n={},r=H(e,[`sdkHttpResponse`]);r!=null&&V(n,[`sdkHttpResponse`],r);let i=H(e,[`name`]);i!=null&&V(n,[`name`],i);let a=H(e,[`metadata`]);a!=null&&V(n,[`metadata`],a);let o=H(e,[`done`]);o!=null&&V(n,[`done`],o);let s=H(e,[`error`]);return s!=null&&V(n,[`error`],s),n}function tf(e,t){let n={},r=H(e,[`gcsUri`]);r!=null&&V(n,[`validationDatasetUri`],r);let i=H(e,[`vertexDatasetResource`]);return i!=null&&V(n,[`validationDatasetUri`],i),n}
306
+ /**
307
+ * @license
308
+ * Copyright 2025 Google LLC
309
+ * SPDX-License-Identifier: Apache-2.0
310
+ */
311
+ var nf=class extends dt{constructor(e){super(),this.apiClient=e,this.list=async(e={})=>new $i(Qi.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:an.JOB_STATE_QUEUED}}}}async getInternal(e){let t,n=``,r={};if(this.apiClient.isVertexAI()){let i=Gd(e);return n=B(`{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=>$d(e))}else{let i=Wd(e);return n=B(`{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=>Qd(e))}}async listInternal(e){let t,n=``,r={};if(this.apiClient.isVertexAI()){let i=qd(e);return n=B(`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=Jd(e),n=new tr;return Object.assign(n,t),n})}else throw Error(`This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).`)}async cancel(e){let t,n=``,r={};if(this.apiClient.isVertexAI()){let i=Ld(e);return n=B(`{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=zd(e),n=new nr;return Object.assign(n,t),n})}else{let i=Id(e);return n=B(`{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=Rd(e),n=new nr;return Object.assign(n,t),n})}}async tuneInternal(e){let t,n=``,r={};if(this.apiClient.isVertexAI()){let i=Ud(e,e);return n=B(`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=>$d(e))}else throw Error(`This method is only supported by the Gemini Enterprise Agent Platform (previously known as 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=B(`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=>ef(e))}}};const rf=1024*1024*8,af=1e3,of=`x-goog-upload-status`;async function sf(e,t,n,r){let i=await lf(e,t,n,r),a=await i?.json();if(i?.headers?.[of]!==`final`)throw Error(`Failed to upload file: Upload status is not finalized.`);return a.file}async function cf(e,t,n,r){let i=await lf(e,t,n,r),a=await i?.json();if(i?.headers?.[of]!==`final`)throw Error(`Failed to upload file: Upload status is not finalized.`);let o=Et(a),s=new gr;return Object.assign(s,o),s}async function lf(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 Hn(new Response),l=`upload`;for(o=e.size;s<o;){let t=Math.min(rf,o-s),a=e.slice(s,s+t);s+t>=o&&(l+=`, finalize`);let u=0,d=af;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?.[of])break;u++,await df(d),d*=2}if(s+=t,c?.headers?.[of]!==`active`)break;if(o<=s)throw Error(`All content has been uploaded, but the upload status is not finalized.`)}return c}async function uf(e){return{size:e.size,type:e.type}}function df(e){return new Promise(t=>setTimeout(t,e))}
312
+ /**
313
+ * @license
314
+ * Copyright 2025 Google LLC
315
+ * SPDX-License-Identifier: Apache-2.0
316
+ */
317
+ var ff=class{async stat(e){let t={size:0,type:void 0};return typeof e==`string`?(t.size=(await l.stat(e)).size,t.type=this.inferMimeType(e),t):await uf(e)}async upload(e,t,n,r){return typeof e==`string`?await this.uploadFileFromPath(e,t,n,r):sf(e,t,n,r)}async uploadToFileSearchStore(e,t,n,r){return typeof e==`string`?await this.uploadFileToFileSearchStoreFromPath(e,t,n,r):cf(e,t,n,r)}inferMimeType(e){let t=e.slice(e.lastIndexOf(`.`)+1);return{aac:`audio/aac`,abw:`application/x-abiword`,arc:`application/x-freearc`,avi:`video/x-msvideo`,azw:`application/vnd.amazon.ebook`,bin:`application/octet-stream`,bmp:`image/bmp`,bz:`application/x-bzip`,bz2:`application/x-bzip2`,csh:`application/x-csh`,css:`text/css`,csv:`text/csv`,doc:`application/msword`,docx:`application/vnd.openxmlformats-officedocument.wordprocessingml.document`,eot:`application/vnd.ms-fontobject`,epub:`application/epub+zip`,gz:`application/gzip`,gif:`image/gif`,htm:`text/html`,html:`text/html`,ico:`image/vnd.microsoft.icon`,ics:`text/calendar`,jar:`application/java-archive`,jpeg:`image/jpeg`,jpg:`image/jpeg`,js:`text/javascript`,json:`application/json`,jsonld:`application/ld+json`,kml:`application/vnd.google-earth.kml+xml`,kmz:`application/vnd.google-earth.kmz+xml`,mjs:`text/javascript`,mp3:`audio/mpeg`,mp4:`video/mp4`,mpeg:`video/mpeg`,mpkg:`application/vnd.apple.installer+xml`,odt:`application/vnd.oasis.opendocument.text`,oga:`audio/ogg`,ogv:`video/ogg`,ogx:`application/ogg`,opus:`audio/opus`,otf:`font/otf`,png:`image/png`,pdf:`application/pdf`,php:`application/x-httpd-php`,ppt:`application/vnd.ms-powerpoint`,pptx:`application/vnd.openxmlformats-officedocument.presentationml.presentation`,rar:`application/vnd.rar`,rtf:`application/rtf`,sh:`application/x-sh`,svg:`image/svg+xml`,swf:`application/x-shockwave-flash`,tar:`application/x-tar`,tif:`image/tiff`,tiff:`image/tiff`,ts:`video/mp2t`,ttf:`font/ttf`,txt:`text/plain`,vsd:`application/vnd.visio`,wav:`audio/wav`,weba:`audio/webm`,webm:`video/webm`,webp:`image/webp`,woff:`font/woff`,woff2:`font/woff2`,xhtml:`application/xhtml+xml`,xls:`application/vnd.ms-excel`,xlsx:`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`,xml:`application/xml`,xul:`application/vnd.mozilla.xul+xml`,zip:`application/zip`,"3gp":`video/3gpp`,"3g2":`video/3gpp2`,"7z":`application/x-7z-compressed`}[t.toLowerCase()]}async uploadFileFromPath(e,t,n,r){let i=await this.uploadFileFromPathInternal(e,t,n,r),a=await i?.json();if(i?.headers?.[of]!==`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?.[of]!==`final`)throw Error(`Failed to upload file: Upload status is not finalized.`);let o=Et(a),s=new gr;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 s=0,c=0,u=new Hn(new Response),d=`upload`,f,p=o.basename(e);try{if(f=await l.open(e,`r`),!f)throw Error(`Failed to open file`);for(s=(await f.stat()).size;c<s;){let e=Math.min(rf,s-c);c+e>=s&&(d+=`, finalize`);let t=new Uint8Array(e),{bytesRead:a}=await f.read(t,0,e,c);if(a!==e)throw Error(`Failed to read ${e} bytes from file at offset ${c}. bytes actually read: ${a}`);let o=new Blob([t]),l=0,m=af;for(;l<3;){let e=Object.assign(Object.assign({},r?.headers||{}),{"X-Goog-Upload-Command":d,"X-Goog-Upload-Offset":String(c),"Content-Length":String(a),"X-Goog-Upload-File-Name":p});if(u=await n.request({path:``,body:o,httpMethod:`POST`,httpOptions:Object.assign(Object.assign({},r),{apiVersion:``,baseUrl:i,headers:e})}),u?.headers?.[of])break;l++,await df(m),m*=2}if(c+=a,u?.headers?.[of]!==`active`)break;if(s<=c)throw Error(`All content has been uploaded, but the upload status is not finalized.`)}return u}finally{f&&await f.close()}}},pf=class extends ro{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})})})}};function mf(e){if(e.enterprise!==void 0||e.vertexai!==void 0){if(e.enterprise!==void 0&&e.vertexai!==void 0&&e.enterprise!==e.vertexai)throw Error(`enterprise and vertexAI flags have conflicting values, please set enterprise value only.`);return e.enterprise??e.vertexai}let t=gf(`GOOGLE_GENAI_USE_ENTERPRISE`),n=gf(`GOOGLE_GENAI_USE_VERTEXAI`),r=_f(t),i=_f(n);return t!==void 0&&n!==void 0&&r!==i&&console.warn(`Warning: Both GOOGLE_GENAI_USE_ENTERPRISE and GOOGLE_GENAI_USE_VERTEXAI are set with conflicting values. The value of GOOGLE_GENAI_USE_ENTERPRISE will be used.`),t===void 0?n===void 0?!1:i:r}var hf=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=mf(e);let t=vf(),n=gf(`GOOGLE_CLOUD_PROJECT`),r=gf(`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.`),this.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=ut(e.httpOptions,this.vertexai,gf(`GOOGLE_VERTEX_BASE_URL`),gf(`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 Ad({apiKey:this.apiKey,googleAuthOptions:e.googleAuthOptions});this.apiClient=new sl({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 ff,downloader:new Md}),this.models=new jl(this.apiClient),this.live=new xl(this.apiClient,a,new Pd),this.batches=new ea(this.apiClient),this.chats=new Wa(this.models,this.apiClient),this.caches=new La(this.apiClient),this.files=new pf(this.apiClient),this.operations=new Ml(this.apiClient),this.authTokens=new Zl(this.apiClient),this.tunings=new nf(this.apiClient),this.fileSearchStores=new au(this.apiClient)}};function gf(e){return((process==null?void 0:process.env)?.[e])?.trim()??void 0}function _f(e){return e===void 0?!1:e.toLowerCase()===`true`}function vf(){let e=gf(`GOOGLE_API_KEY`),t=gf(`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 yf(e){return e.thought===!0}function bf(e,t){return typeof t==`string`&&t.length>0?t:e}const xf=/^[A-Za-z0-9+/]+={0,2}$/;function Sf(e){return!e||e.length%4!=0?!1:xf.test(e)}function Cf(e,t){return e&&Sf(t)?t:void 0}function wf(e){return e.startsWith(`claude-`)||e.startsWith(`gpt-oss-`)}function Tf(e){let t=e.toLowerCase().match(/^gemini(?:-live)?-(\d+)/);if(t)return Number.parseInt(t[1],10)}function Ef(e){let t=Tf(e);return t===void 0?!0:t>=3}function Df(e,t){let n=[],a=i(t.messages,e,t=>wf(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=Cf(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=Cf(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=Cf(a,n.thoughtSignature),r={functionCall:{name:n.name,args:n.arguments??{},...wf(e.id)?{id:n.id}:{}},...t&&{thoughtSignature:t}};i.push(r)}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(`
318
+ `),a=e.input.includes(`image`)?t.content.filter(e=>e.type===`image`):[],o=i.length>0,s=a.length>0,c=Ef(e.id),l=o?r(i):s?`(see attached image)`:``,u=a.map(e=>({inlineData:{mimeType:e.mimeType,data:e.data}})),d=wf(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 Of=new Set([`$schema`,`$id`,`$anchor`,`$dynamicAnchor`,`$vocabulary`,`$comment`,`$defs`,`definitions`]);function kf(e){if(typeof e!=`object`||!e||Array.isArray(e))return e;let t={};for(let[n,r]of Object.entries(e))Of.has(n)||(t[n]=kf(r));return t}function Af(e,t=!1){if(e.length!==0)return[{functionDeclarations:e.map(e=>({name:e.name,description:e.description,...t?{parameters:kf(e.parameters)}:{parametersJsonSchema:e.parameters}}))}]}function jf(e){switch(e){case`auto`:return Vt.AUTO;case`none`:return Vt.NONE;case`any`:return Vt.ANY;default:return Vt.AUTO}}function Mf(e){switch(e){case U.STOP:return`stop`;case U.MAX_TOKENS:return`length`;case U.BLOCKLIST:case U.PROHIBITED_CONTENT:case U.SPII:case U.SAFETY:case U.IMAGE_SAFETY:case U.IMAGE_PROHIBITED_CONTENT:case U.IMAGE_RECITATION:case U.IMAGE_OTHER:case U.RECITATION:case U.FINISH_REASON_UNSPECIFIED:case U.OTHER:case U.LANGUAGE:case U.MALFORMED_FUNCTION_CALL:case U.UNEXPECTED_TOOL_CALL:case U.NO_IMAGE:return`error`;default:{let t=e;throw Error(`Unhandled stop reason: ${t}`)}}}export{jf as a,pn as c,Mf as i,Ht as l,Af as n,bf as o,yf as r,hf as s,Df as t};