noskills 4.5.0 → 4.5.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (91) hide show
  1. package/chunks/{ajan-bridge-T5M4DPDT.js → ajan-bridge-BNPC757J.js} +1 -1
  2. package/chunks/{anthropic-TS7EMQML.js → anthropic-ZKOMTKX2.js} +1 -1
  3. package/chunks/{approve-HEW3VFYH.js → approve-3TKOHYHH.js} +1 -1
  4. package/chunks/{ask-AXHTCVD6.js → ask-UB26SBWQ.js} +1 -1
  5. package/chunks/{block-VN76CXZW.js → block-Q4WAIX7X.js} +1 -1
  6. package/chunks/{cancel-7WRAST62.js → cancel-DY76ADX4.js} +1 -1
  7. package/chunks/{chunk-4PF2MT7S.js → chunk-34RPTI4K.js} +7 -7
  8. package/chunks/chunk-3JTDWOAJ.js +2 -0
  9. package/chunks/{chunk-GQTHILPL.js → chunk-5FX4EBFY.js} +1 -1
  10. package/chunks/chunk-5OTECUN7.js +1 -0
  11. package/chunks/{chunk-6YSS6PEL.js → chunk-7PBHRFOZ.js} +1 -1
  12. package/chunks/{chunk-7GC46XEU.js → chunk-AB3N327V.js} +1 -1
  13. package/chunks/{chunk-KMLNG3EC.js → chunk-BYPCI5VU.js} +1 -1
  14. package/chunks/{chunk-QKWJ72HI.js → chunk-CKIZYL4O.js} +1 -1
  15. package/chunks/{chunk-S4MUTKHT.js → chunk-DYCGJ4RY.js} +1 -1
  16. package/chunks/{chunk-UE56BMAW.js → chunk-EVJYA7S3.js} +1 -1
  17. package/chunks/{chunk-LN4NDYT6.js → chunk-FYFUEK4U.js} +1 -1
  18. package/chunks/chunk-GNMOE7H3.js +48 -0
  19. package/chunks/chunk-HB62UGZI.js +2 -0
  20. package/chunks/{chunk-EIMBEXUJ.js → chunk-IM73MYMS.js} +1 -1
  21. package/chunks/{chunk-KM64FL2X.js → chunk-J25XTDQQ.js} +1 -1
  22. package/chunks/{chunk-JL3MAFYQ.js → chunk-LGQEWL5X.js} +1 -1
  23. package/chunks/{chunk-5DZHAHXW.js → chunk-LKZZ4JN5.js} +1 -1
  24. package/chunks/{chunk-DBKXMYLF.js → chunk-NPWXEWRN.js} +1 -1
  25. package/chunks/{chunk-PKEQKXZW.js → chunk-ONJVI5AZ.js} +1 -1
  26. package/chunks/{chunk-EIGFDYGQ.js → chunk-OP4XAIGW.js} +1 -1
  27. package/chunks/{chunk-W4TQLLUK.js → chunk-T6NZVA6P.js} +1 -1
  28. package/chunks/{chunk-5PBNUBBY.js → chunk-TCSIXKUD.js} +1 -1
  29. package/chunks/{chunk-KRKOWSYW.js → chunk-WDKWHGJU.js} +5 -7
  30. package/chunks/{chunk-PRQ5CRIG.js → chunk-XDPATEP5.js} +1 -1
  31. package/chunks/{chunk-CML74SNT.js → chunk-Y45DQJSS.js} +1 -1
  32. package/chunks/{chunk-RAQY37P6.js → chunk-YUTDPPXX.js} +1 -1
  33. package/chunks/claude-code-OQJIUKZP.js +1 -0
  34. package/chunks/{concern-QSENGU6C.js → concern-UIGVWDFS.js} +1 -1
  35. package/chunks/{config-S3UXTJN2.js → config-72Z4PIJN.js} +1 -1
  36. package/chunks/{decision-ledger-GY2W6VWL.js → decision-ledger-5IPPTRT7.js} +1 -1
  37. package/chunks/{delegate-WKXIER7E.js → delegate-OV6NY434.js} +1 -1
  38. package/chunks/{diagrams-A7W2EBYV.js → diagrams-OX4FBDGP.js} +1 -1
  39. package/chunks/{done-WR3UFYJT.js → done-V54GSSTY.js} +1 -1
  40. package/chunks/{followup-5EGZEF5Q.js → followup-NL7EPIGF.js} +1 -1
  41. package/chunks/{free-KJQHRYZA.js → free-KD344KRL.js} +1 -1
  42. package/chunks/{gemini-IWP24T63.js → gemini-23EOEXSF.js} +1 -1
  43. package/chunks/{init-437SU6XH.js → init-WDRNFT57.js} +1 -1
  44. package/chunks/{invoke-hook-LMCWNF65.js → invoke-hook-I3NTD36Q.js} +1 -1
  45. package/chunks/kiro-TPAAIMY6.js +1 -0
  46. package/chunks/{learn-ZTYKBZER.js → learn-WBWNJEB2.js} +1 -1
  47. package/chunks/{ledger-FOOPJ2UO.js → ledger-QYK252DV.js} +1 -1
  48. package/chunks/{list-HNGIOVBK.js → list-WO6RS7JX.js} +1 -1
  49. package/chunks/{manager-2MOLEJ4Q.js → manager-ZSPRC5R4.js} +1 -1
  50. package/chunks/{mod-AJIRKRAH.js → mod-B6LBGYON.js} +1 -1
  51. package/chunks/{mod-6EZYRKWV.js → mod-MMHDQRNF.js} +1 -1
  52. package/chunks/{mod-7X5TKHKC.js → mod-RBGAMGZA.js} +1 -1
  53. package/chunks/{mod-TGOMO3CJ.js → mod-SV4VELMH.js} +1 -1
  54. package/chunks/{next-Y6FOPM4Z.js → next-QXCLZ7P3.js} +1 -1
  55. package/chunks/node-2XIHQ2M4.js +1 -0
  56. package/chunks/node-BXYZKSJY.js +15 -0
  57. package/chunks/node-DMUOWFGA.js +69 -0
  58. package/chunks/ollama-MXRDGQDF.js +1 -0
  59. package/chunks/openai-LE47IWMQ.js +30 -0
  60. package/chunks/{openai-YES2XJDU.js → openai-MSJF4B6H.js} +1 -1
  61. package/chunks/opencode-ZDHKR2P6.js +1 -0
  62. package/chunks/{pack-KUT53Z24.js → pack-NS64WU6M.js} +1 -1
  63. package/chunks/{plan-export-PG2BVRQZ.js → plan-export-HECAF7D4.js} +1 -1
  64. package/chunks/{purge-JGNJNEET.js → purge-PSQNN42H.js} +1 -1
  65. package/chunks/{reopen-RPDXN3CF.js → reopen-L37M5XUI.js} +1 -1
  66. package/chunks/{reset-RBCQO2RF.js → reset-OOTZXW6Q.js} +1 -1
  67. package/chunks/{review-VMS5MYOV.js → review-QLD6WSOB.js} +1 -1
  68. package/chunks/{rule-IB4VKSBC.js → rule-OOANQBHB.js} +1 -1
  69. package/chunks/{run-62PWXVII.js → run-YHCIRY7Z.js} +1 -1
  70. package/chunks/{sdk-FR7Z4YSC.js → sdk-OQIHH3OY.js} +1 -1
  71. package/chunks/{session-Q43KMFL2.js → session-OWWDH7KA.js} +1 -1
  72. package/chunks/{spec-4RKLPOEM.js → spec-O7F525UN.js} +1 -1
  73. package/chunks/{status-OGLFEFF7.js → status-SZZXY7V3.js} +1 -1
  74. package/chunks/{sync-H35O5DN5.js → sync-3RYRGTEA.js} +1 -1
  75. package/chunks/{validate-JX7UTAK5.js → validate-UZD6JBSG.js} +1 -1
  76. package/chunks/{vertexai-WF5CKMYI.js → vertexai-CVCRCO24.js} +1 -1
  77. package/chunks/{watch-SOZDHLSC.js → watch-5DNM646U.js} +1 -1
  78. package/chunks/{web-3VGRM3W4.js → web-662LNB3K.js} +1 -1
  79. package/chunks/{wontfix-RBOGLLWJ.js → wontfix-UDCTLHNB.js} +1 -1
  80. package/noskills.js +1 -1
  81. package/package.json +1 -1
  82. package/chunks/chunk-3ZJ3UGQL.js +0 -48
  83. package/chunks/chunk-575Y3OEG.js +0 -1
  84. package/chunks/chunk-IGDFEGCH.js +0 -2
  85. package/chunks/claude-code-DIWRQKZA.js +0 -1
  86. package/chunks/kiro-THWCXS5L.js +0 -1
  87. package/chunks/node-AZK2C657.js +0 -12
  88. package/chunks/node-GQQ42DT2.js +0 -68
  89. package/chunks/ollama-2KAMCXVL.js +0 -1
  90. package/chunks/openai-HHE35TAX.js +0 -31
  91. package/chunks/opencode-S4M7WJTO.js +0 -1
@@ -1,68 +0,0 @@
1
- import{a as W,c as F,e as ht}from"./chunk-HISXAZ4Y.js";var Ku=F((dk,Xu)=>{function Xe(t,e){typeof e=="boolean"&&(e={forever:e}),this._originalTimeouts=JSON.parse(JSON.stringify(t)),this._timeouts=t,this._options=e||{},this._maxRetryTime=e&&e.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))}Xu.exports=Xe;Xe.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)};Xe.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null};Xe.prototype.retry=function(t){if(this._timeout&&clearTimeout(this._timeout),!t)return!1;var e=new Date().getTime();if(t&&e-this._operationStart>=this._maxRetryTime)return this._errors.push(t),this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(t);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};Xe.prototype.attempt=function(t,e){this._fn=t,e&&(e.timeout&&(this._operationTimeout=e.timeout),e.cb&&(this._operationTimeoutCb=e.cb));var n=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){n._operationTimeoutCb()},n._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)};Xe.prototype.try=function(t){console.log("Using RetryOperation.try() is deprecated"),this.attempt(t)};Xe.prototype.start=function(t){console.log("Using RetryOperation.start() is deprecated"),this.attempt(t)};Xe.prototype.start=Xe.prototype.try;Xe.prototype.errors=function(){return this._errors};Xe.prototype.attempts=function(){return this._attempts};Xe.prototype.mainError=function(){if(this._errors.length===0)return null;for(var t={},e=null,n=0,r=0;r<this._errors.length;r++){var i=this._errors[r],o=i.message,a=(t[o]||0)+1;t[o]=a,a>=n&&(e=i,n=a)}return e}});var Yu=F(tn=>{var V_=Ku();tn.operation=function(t){var e=tn.timeouts(t);return new V_(e,{forever:t&&(t.forever||t.retries===1/0),unref:t&&t.unref,maxRetryTime:t&&t.maxRetryTime})};tn.timeouts=function(t){if(t instanceof Array)return[].concat(t);var e={retries:10,factor:2,minTimeout:1*1e3,maxTimeout:1/0,randomize:!1};for(var n in t)e[n]=t[n];if(e.minTimeout>e.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var r=[],i=0;i<e.retries;i++)r.push(this.createTimeout(i,e));return t&&t.forever&&!r.length&&r.push(this.createTimeout(i,e)),r.sort(function(o,a){return o-a}),r};tn.createTimeout=function(t,e){var n=e.randomize?Math.random()+1:1,r=Math.round(n*Math.max(e.minTimeout,1)*Math.pow(e.factor,t));return r=Math.min(r,e.maxTimeout),r};tn.wrap=function(t,e,n){if(e instanceof Array&&(n=e,e=null),!n){n=[];for(var r in t)typeof t[r]=="function"&&n.push(r)}for(var i=0;i<n.length;i++){var o=n[i],a=t[o];t[o]=function(c){var d=tn.operation(e),f=Array.prototype.slice.call(arguments,1),p=f.pop();f.push(function(h){d.retry(h)||(h&&(arguments[0]=d.mainError()),p.apply(this,arguments))}),d.attempt(function(){c.apply(t,f)})}.bind(t,a),t[o].options=e}}});var Qu=F((pk,zu)=>{zu.exports=Yu()});var ju=F((hk,Ur)=>{"use strict";var $_=Qu(),J_=["Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed"],Mr=class extends Error{constructor(e){super(),e instanceof Error?(this.originalError=e,{message:e}=e):(this.originalError=new Error(e),this.originalError.stack=this.stack),this.name="AbortError",this.message=e}},W_=(t,e,n)=>{let r=n.retries-(e-1);return t.attemptNumber=e,t.retriesLeft=r,t},X_=t=>J_.includes(t),Zu=(t,e)=>new Promise((n,r)=>{e={onFailedAttempt:()=>{},retries:10,...e};let i=$_.operation(e);i.attempt(async o=>{try{n(await t(o))}catch(a){if(!(a instanceof Error)){r(new TypeError(`Non-error was thrown: "${a}". You should only throw errors.`));return}if(a instanceof Mr)i.stop(),r(a.originalError);else if(a instanceof TypeError&&!X_(a.message))i.stop(),r(a);else{W_(a,o,e);try{await e.onFailedAttempt(a)}catch(u){r(u);return}i.retry(a)||r(i.mainError())}}})});Ur.exports=Zu;Ur.exports.default=Zu;Ur.exports.AbortError=Mr});var Mo=F((mk,ac)=>{"use strict";var br=Object.prototype.hasOwnProperty,sc=Object.prototype.toString,ec=Object.defineProperty,tc=Object.getOwnPropertyDescriptor,nc=function(e){return typeof Array.isArray=="function"?Array.isArray(e):sc.call(e)==="[object Array]"},rc=function(e){if(!e||sc.call(e)!=="[object Object]")return!1;var n=br.call(e,"constructor"),r=e.constructor&&e.constructor.prototype&&br.call(e.constructor.prototype,"isPrototypeOf");if(e.constructor&&!n&&!r)return!1;var i;for(i in e);return typeof i>"u"||br.call(e,i)},ic=function(e,n){ec&&n.name==="__proto__"?ec(e,n.name,{enumerable:!0,configurable:!0,value:n.newValue,writable:!0}):e[n.name]=n.newValue},oc=function(e,n){if(n==="__proto__")if(br.call(e,n)){if(tc)return tc(e,n).value}else return;return e[n]};ac.exports=function t(){var e,n,r,i,o,a,u=arguments[0],c=1,d=arguments.length,f=!1;for(typeof u=="boolean"&&(f=u,u=arguments[1]||{},c=2),(u==null||typeof u!="object"&&typeof u!="function")&&(u={});c<d;++c)if(e=arguments[c],e!=null)for(n in e)r=oc(u,n),i=oc(e,n),u!==i&&(f&&i&&(rc(i)||(o=nc(i)))?(o?(o=!1,a=r&&nc(r)?r:[]):a=r&&rc(r)?r:{},ic(u,{name:n,newValue:t(f,a,i)})):typeof i<"u"&&ic(u,{name:n,newValue:i}));return u}});var lc=F((gk,K_)=>{K_.exports={name:"gaxios",version:"7.3.0",description:"A simple common HTTP client specifically for Google APIs and services.",main:"build/cjs/src/index.js",types:"build/cjs/src/index.d.ts",files:["build/"],exports:{".":{import:{types:"./build/esm/src/index.d.ts",default:"./build/esm/src/index.js"},require:{types:"./build/cjs/src/index.d.ts",default:"./build/cjs/src/index.js"}}},scripts:{lint:"gts check --no-inline-config",test:"c8 mocha build/esm/test","presystem-test":"npm run compile","system-test":"mocha build/esm/system-test --timeout 80000",compile:"tsc -b ./tsconfig.json ./tsconfig.cjs.json && node utils/enable-esm.mjs",fix:"gts fix",prepare:"npm run compile",pretest:"npm run compile",webpack:"webpack","prebrowser-test":"npm run compile","browser-test":"node build/browser-test/browser-test-runner.js",docs:"jsdoc -c .jsdoc.js","samples-test":"cd samples/ && npm link ../ && npm test && cd ../",prelint:"cd samples; npm link ../; npm install",clean:"gts clean"},repository:{type:"git",directory:"core/packages/gaxios",url:"https://github.com/googleapis/google-cloud-node.git"},keywords:["google"],engines:{node:">=18"},author:"Google, LLC",license:"Apache-2.0",devDependencies:{"@babel/plugin-proposal-private-methods":"^7.18.6","@types/cors":"^2.8.6","@types/express":"^5.0.0","@types/extend":"^3.0.1","@types/mocha":"^10.0.10","@types/multiparty":"4.2.1","@types/mv":"^2.1.0","@types/ncp":"^2.0.8","@types/node":"^24.0.0","@types/sinon":"^21.0.0","@types/tmp":"^0.2.6",assert:"^2.0.0",browserify:"^17.0.0",c8:"^10.1.3",cors:"^2.8.5",express:"^5.0.0",gts:"^6.0.2","is-docker":"^3.0.0",jsdoc:"^4.0.4","jsdoc-fresh":"^5.0.0","jsdoc-region-tag":"^4.0.0",karma:"^6.0.0","karma-chrome-launcher":"^3.0.0","karma-coverage":"^2.0.0","karma-firefox-launcher":"^2.0.0","karma-mocha":"^2.0.0","karma-remap-coverage":"^0.1.5","karma-sourcemap-loader":"^0.4.0","karma-webpack":"^5.0.1",mocha:"^11.1.0",multiparty:"^4.2.1",mv:"^2.1.1",ncp:"^2.0.0",nock:"14.0.5","null-loader":"^4.0.1","pack-n-play":"^4.0.0",puppeteer:"^24.0.0",sinon:"21.0.3","stream-browserify":"^3.0.0",tmp:"0.2.6","ts-loader":"^9.5.2",typescript:"5.8.3","undici-types":"^7.24.1",webpack:"^5.97.1","webpack-cli":"^6.0.1"},dependencies:{extend:"^3.0.2","https-proxy-agent":"^7.0.1","node-fetch":"^3.3.2"},homepage:"https://github.com/googleapis/google-cloud-node/tree/main/core/packages/gaxios"}});var cc=F((_k,uc)=>{"use strict";var Y_=lc();uc.exports={pkg:Y_}});var Go=F(Ke=>{"use strict";var fc=Ke&&Ke.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Ke,"__esModule",{value:!0});Ke.GaxiosError=Ke.GAXIOS_ERROR_SYMBOL=void 0;Ke.defaultErrorRedactor=pc;var dc=fc(Mo()),z_=fc(cc()),Uo=z_.default.pkg;Ke.GAXIOS_ERROR_SYMBOL=Symbol.for(`${Uo.name}-gaxios-error`);var bo=class t extends Error{config;response;code;status;error;[Ke.GAXIOS_ERROR_SYMBOL]=Uo.version;static[Symbol.hasInstance](e){return e&&typeof e=="object"&&Ke.GAXIOS_ERROR_SYMBOL in e&&e[Ke.GAXIOS_ERROR_SYMBOL]===Uo.version?!0:Function.prototype[Symbol.hasInstance].call(t,e)}constructor(e,n,r,i){if(super(e,{cause:i}),this.config=n,this.response=r,this.error=i instanceof Error?i:void 0,this.config=(0,dc.default)(!0,{},n),this.response&&(this.response.config=(0,dc.default)(!0,{},this.response.config)),this.response){try{this.response.data=Q_(this.config.responseType,this.response?.bodyUsed?this.response?.data:void 0)}catch{}this.status=this.response.status}i instanceof DOMException?this.code=i.name:i&&typeof i=="object"&&"code"in i&&(typeof i.code=="string"||typeof i.code=="number")&&(this.code=i.code)}static extractAPIErrorFromResponse(e,n="The request failed"){let r=n;if(typeof e.data=="string"&&(r=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"){r="message"in e.data.error&&typeof e.data.error.message=="string"?e.data.error.message:r;let i="status"in e.data.error&&typeof e.data.error.status=="string"?e.data.error.status:e.statusText,o="code"in e.data.error&&typeof e.data.error.code=="number"?e.data.error.code:e.status;if("errors"in e.data.error&&Array.isArray(e.data.error.errors)){let a=[];for(let u of e.data.error.errors)typeof u=="object"&&"message"in u&&typeof u.message=="string"&&a.push(u.message);return Object.assign({message:a.join(`
2
- `)||r,code:o,status:i},e.data.error)}return Object.assign({message:r,code:o,status:i},e.data.error)}}return{message:r,code:e.status,status:e.statusText}}};Ke.GaxiosError=bo;function Q_(t,e){switch(t){case"stream":return e;case"json":return JSON.parse(JSON.stringify(e));case"arraybuffer":return JSON.parse(Buffer.from(e).toString("utf8"));case"blob":return JSON.parse(e.text());default:return e}}function pc(t){let e="<<REDACTED> - See `errorRedactor` option in `gaxios` for configuration>.";function n(o){o&&o.forEach((a,u)=>{(/^authentication$/i.test(u)||/^authorization$/i.test(u)||/secret/i.test(u))&&o.set(u,e)})}function r(o,a){if(typeof o=="object"&&o!==null&&typeof o[a]=="string"){let u=o[a];(/grant_type=/i.test(u)||/assertion=/i.test(u)||/secret/i.test(u))&&(o[a]=e)}}function i(o){!o||typeof o!="object"||(o instanceof FormData||o instanceof URLSearchParams||"forEach"in o&&"set"in o?o.forEach((a,u)=>{(["grant_type","assertion"].includes(u)||/secret/.test(u))&&o.set(u,e)}):("grant_type"in o&&(o.grant_type=e),"assertion"in o&&(o.assertion=e),"client_secret"in o&&(o.client_secret=e)))}return t.config&&(n(t.config.headers),r(t.config,"data"),i(t.config.data),r(t.config,"body"),i(t.config.body),t.config.url.searchParams.has("token")&&t.config.url.searchParams.set("token",e),t.config.url.searchParams.has("client_secret")&&t.config.url.searchParams.set("client_secret",e)),t.response&&(pc({config:t.response.config}),n(t.response.headers),t.response.bodyUsed&&(r(t.response,"data"),i(t.response.data))),t}});var mc=F(Lo=>{"use strict";Object.defineProperty(Lo,"__esModule",{value:!0});Lo.getRetryConfig=Z_;async function Z_(t){let e=hc(t);if(!t||!t.config||!e&&!t.config.retry)return{shouldRetry:!1};e=e||{},e.currentRetryAttempt=e.currentRetryAttempt||0,e.retry=e.retry===void 0||e.retry===null?3:e.retry,e.httpMethodsToRetry=e.httpMethodsToRetry||["GET","HEAD","PUT","OPTIONS","DELETE"],e.noResponseRetries=e.noResponseRetries===void 0||e.noResponseRetries===null?2:e.noResponseRetries,e.retryDelayMultiplier=e.retryDelayMultiplier?e.retryDelayMultiplier:2,e.timeOfFirstRequest=e.timeOfFirstRequest?e.timeOfFirstRequest:Date.now(),e.totalTimeout=e.totalTimeout?e.totalTimeout:Number.MAX_SAFE_INTEGER,e.maxRetryDelay=e.maxRetryDelay?e.maxRetryDelay:Number.MAX_SAFE_INTEGER;let n=[[100,199],[408,408],[429,429],[500,599]];if(e.statusCodesToRetry=e.statusCodesToRetry||n,t.config.retryConfig=e,!await(e.shouldRetry||j_)(t))return{shouldRetry:!1,config:t.config};let i=ey(e);t.config.retryConfig.currentRetryAttempt+=1;let o=e.retryBackoff?e.retryBackoff(t,i):new Promise(a=>{setTimeout(a,i)});return e.onRetryAttempt&&await e.onRetryAttempt(t),await o,{shouldRetry:!0,config:t.config}}function j_(t){let e=hc(t);if(t.config.signal?.aborted&&t.code!=="TimeoutError"||t.code==="AbortError"||!e||e.retry===0||!t.response&&(e.currentRetryAttempt||0)>=e.noResponseRetries||!e.httpMethodsToRetry||!e.httpMethodsToRetry.includes(t.config.method?.toUpperCase()||"GET"))return!1;if(t.response&&t.response.status){let n=!1;for(let[r,i]of e.statusCodesToRetry){let o=t.response.status;if(o>=r&&o<=i){n=!0;break}}if(!n)return!1}return e.currentRetryAttempt=e.currentRetryAttempt||0,!(e.currentRetryAttempt>=e.retry)}function hc(t){if(t&&t.config&&t.config.retryConfig)return t.config.retryConfig}function ey(t){let n=(t.currentRetryAttempt?0:t.retryDelay??100)+(Math.pow(t.retryDelayMultiplier,t.currentRetryAttempt)-1)/2*1e3,r=t.totalTimeout-(Date.now()-t.timeOfFirstRequest);return Math.min(n,r,t.maxRetryDelay)}});var qo=F(Gr=>{"use strict";Object.defineProperty(Gr,"__esModule",{value:!0});Gr.GaxiosInterceptorManager=void 0;var Oo=class extends Set{};Gr.GaxiosInterceptorManager=Oo});var yc=F(gn=>{"use strict";var ty=gn&&gn.__importDefault||function(t){return t&&t.__esModule?t:{default:t}},mn;Object.defineProperty(gn,"__esModule",{value:!0});gn.Gaxios=void 0;var ny=ty(Mo()),ry=W("https"),nn=Go(),iy=mc(),gc=W("stream"),_c=qo(),oy=async()=>globalThis.crypto?.randomUUID()||(await import("crypto")).randomUUID(),sy=204,Lr=class{agentCache=new Map;defaults;interceptors;constructor(e){this.defaults=e||{},this.interceptors={request:new _c.GaxiosInterceptorManager,response:new _c.GaxiosInterceptorManager}}fetch(...e){let n=e[0],r=e[1],i,o=new Headers;return typeof n=="string"?i=new URL(n):n instanceof URL?i=n:n&&n.url&&(i=new URL(n.url)),n&&typeof n=="object"&&"headers"in n&&mn.mergeHeaders(o,n.headers),r&&mn.mergeHeaders(o,new Headers(r.headers)),typeof n=="object"&&!(n instanceof URL)?this.request({...r,...n,headers:o,url:i}):this.request({...r,headers:o,url:i})}async request(e={}){let n=await this.#r(e);return n=await this.#t(n),this.#n(this._request(n))}async _defaultAdapter(e){let n=e.fetchImplementation||this.defaults.fetchImplementation||await mn.#l(),r={...e};delete r.data;let i=await n(e.url,r),o=await this.getResponseData(e,i);return Object.getOwnPropertyDescriptor(i,"data")?.configurable||Object.defineProperties(i,{data:{configurable:!0,writable:!0,enumerable:!0,value:o}}),Object.assign(i,{config:e,data:o})}async _request(e){try{let n;if(e.adapter?n=await e.adapter(e,this._defaultAdapter.bind(this)):n=await this._defaultAdapter(e),!e.validateStatus(n.status)){if(e.responseType==="stream"){let i=[];for await(let o of n.data)i.push(o);n.data=Buffer.concat(i.map(o=>typeof o=="string"?Buffer.from(o):o)).toString("utf8")}let r=nn.GaxiosError.extractAPIErrorFromResponse(n,`Request failed with status code ${n.status}`);throw new nn.GaxiosError(r?.message,e,n,r)}return n}catch(n){let r;n instanceof nn.GaxiosError?r=n:n instanceof Error?r=new nn.GaxiosError(n.message,e,void 0,n):r=new nn.GaxiosError("Unexpected Gaxios Error",e,void 0,n);let{shouldRetry:i,config:o}=await(0,iy.getRetryConfig)(r);if(i&&o)return r.config.retryConfig.currentRetryAttempt=o.retryConfig.currentRetryAttempt,e.retryConfig=r.config?.retryConfig,this.#i(e),this._request(e);throw e.errorRedactor&&e.errorRedactor(r),r}}async getResponseData(e,n){if(n.status===sy)return"";if(e.maxContentLength&&n.headers.has("content-length")&&e.maxContentLength<Number.parseInt(n.headers?.get("content-length")||""))throw new nn.GaxiosError("Response's `Content-Length` is over the limit.",e,Object.assign(n,{config:e}));switch(e.responseType){case"stream":return n.body;case"json":{let r=await n.text();try{return JSON.parse(r)}catch{return r}}case"arraybuffer":return n.arrayBuffer();case"blob":return n.blob();case"text":return n.text();default:return this.getResponseDataFromContentType(n)}}#e(e,n=[]){let r=new URL(e),i=[...n],o=(process.env.NO_PROXY??process.env.no_proxy)?.split(",")||[];for(let a of o)i.push(a.trim());for(let a of i)if(a instanceof RegExp){if(a.test(r.toString()))return!1}else if(a instanceof URL){if(a.origin===r.origin)return!1}else if(a.startsWith("*.")||a.startsWith(".")){let u=a.replace(/^\*\./,".");if(r.hostname.endsWith(u))return!1}else if(a===r.origin||a===r.hostname||a===r.href)return!1;return!0}async#t(e){let n=Promise.resolve(e);for(let r of this.interceptors.request.values())r&&(n=n.then(r.resolved,r.rejected));return n}async#n(e){let n=Promise.resolve(e);for(let r of this.interceptors.response.values())r&&(n=n.then(r.resolved,r.rejected));return n}async#r(e){let n=new Headers(this.defaults.headers);mn.mergeHeaders(n,e.headers);let r=(0,ny.default)(!0,{},this.defaults,e);if(!r.url)throw new Error("URL is required.");if(r.baseURL&&(r.url=new URL(r.url,r.baseURL)),r.url=new URL(r.url),r.params)if(r.paramsSerializer){let a=r.paramsSerializer(r.params);a.startsWith("?")&&(a=a.slice(1));let u=r.url.toString().includes("?")?"&":"?";r.url=r.url+u+a}else{let a=r.url instanceof URL?r.url:new URL(r.url);for(let[u,c]of new URLSearchParams(r.params))a.searchParams.append(u,c);r.url=a}typeof e.maxContentLength=="number"&&(r.size=e.maxContentLength),typeof e.maxRedirects=="number"&&(r.follow=e.maxRedirects);let i=typeof r.data=="string"||r.data instanceof ArrayBuffer||r.data instanceof Blob||globalThis.File&&r.data instanceof File||r.data instanceof FormData||r.data instanceof gc.Readable||r.data instanceof ReadableStream||r.data instanceof String||r.data instanceof URLSearchParams||ArrayBuffer.isView(r.data)||["Blob","File","FormData"].includes(r.data?.constructor?.name||"");if(r.multipart?.length){let a=await oy();n.set("content-type",`multipart/related; boundary=${a}`),r.body=gc.Readable.from(this.getMultipartRequest(r.multipart,a))}else i?r.body=r.data:typeof r.data=="object"?n.get("Content-Type")==="application/x-www-form-urlencoded"?r.body=r.paramsSerializer?r.paramsSerializer(r.data):new URLSearchParams(r.data):(n.has("content-type")||n.set("content-type","application/json"),r.body=JSON.stringify(r.data)):r.data&&(r.body=r.data);r.validateStatus=r.validateStatus||this.validateStatus,r.responseType=r.responseType||"unknown",!n.has("accept")&&r.responseType==="json"&&n.set("accept","application/json");let o=r.proxy||process?.env?.HTTPS_PROXY||process?.env?.https_proxy||process?.env?.HTTP_PROXY||process?.env?.http_proxy;if(!r.agent)if(o&&this.#e(r.url,r.noProxy)){let a=await mn.#a();this.agentCache.has(o)?r.agent=this.agentCache.get(o):(r.agent=new a(o,{cert:r.cert,key:r.key}),this.agentCache.set(o,r.agent))}else r.cert&&r.key&&(this.agentCache.has(r.key)?r.agent=this.agentCache.get(r.key):(r.agent=new ry.Agent({cert:r.cert,key:r.key}),this.agentCache.set(r.key,r.agent)));return typeof r.errorRedactor!="function"&&r.errorRedactor!==!1&&(r.errorRedactor=nn.defaultErrorRedactor),r.body&&!("duplex"in r)&&(r.duplex="half"),this.#i(r),Object.assign(r,{headers:n,url:r.url instanceof URL?r.url:new URL(r.url)})}#i(e){if(e.timeout){let n=AbortSignal.timeout(e.timeout);e.signal&&!e.signal.aborted?e.signal=AbortSignal.any([e.signal,n]):e.signal=n}}validateStatus(e){return e>=200&&e<300}async getResponseDataFromContentType(e){let n=e.headers.get("Content-Type");if(n===null)return e.text();if(n=n.toLowerCase(),n.includes("application/json")){let r=await e.text();try{r=JSON.parse(r)}catch{}return r}else return n.match(/^text\//)?e.text():e.blob()}async*getMultipartRequest(e,n){let r=`--${n}--`;for(let i of e){let o=i.headers.get("Content-Type")||"application/octet-stream";yield`--${n}\r
3
- Content-Type: ${o}\r
4
- \r
5
- `,typeof i.content=="string"?yield i.content:yield*i.content,yield`\r
6
- `}yield r}static#o;static#s;static async#a(){return this.#o||=(await import("./dist-3MH5UCQU.js")).HttpsProxyAgent,this.#o}static async#l(){let e=typeof window<"u"&&!!window;return this.#s||=e?window.fetch:(await import("./src-HXQVVTGQ.js")).default,this.#s}static mergeHeaders(e,...n){e=e instanceof Headers?e:new Headers(e);for(let r of n)(r instanceof Headers?r:new Headers(r)).forEach((o,a)=>{a==="set-cookie"?e.append(a,o):e.set(a,o)});return e}};gn.Gaxios=Lr;mn=Lr});var ke=F(Ge=>{"use strict";var ay=Ge&&Ge.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(e,n);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,i)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),ly=Ge&&Ge.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&ay(e,t,n)};Object.defineProperty(Ge,"__esModule",{value:!0});Ge.instance=Ge.Gaxios=Ge.GaxiosError=void 0;Ge.request=cy;var Ec=yc();Object.defineProperty(Ge,"Gaxios",{enumerable:!0,get:function(){return Ec.Gaxios}});var uy=Go();Object.defineProperty(Ge,"GaxiosError",{enumerable:!0,get:function(){return uy.GaxiosError}});ly(qo(),Ge);Ge.instance=new Ec.Gaxios;async function cy(t){return Ge.instance.request(t)}});var Fo=F((vc,Or)=>{(function(t){"use strict";var e,n=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,r=Math.ceil,i=Math.floor,o="[BigNumber Error] ",a=o+"Number primitive has more than 15 significant digits: ",u=1e14,c=14,d=9007199254740991,f=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],p=1e7,h=1e9;function m(P){var G,O,B,k=H.prototype={constructor:H,toString:null,valueOf:null},V=new H(1),X=20,Z=4,ne=-7,D=21,K=-1e7,j=1e7,_e=!1,Pe=1,Ae=0,Re={prefix:"",groupSize:3,secondaryGroupSize:0,groupSeparator:",",decimalSeparator:".",fractionGroupSize:0,fractionGroupSeparator:"\xA0",suffix:""},qe="0123456789abcdefghijklmnopqrstuvwxyz",Ro=!0;function H(v,T){var S,U,R,x,L,w,N,b,M=this;if(!(M instanceof H))return new H(v,T);if(T==null){if(v&&v._isBigNumber===!0){M.s=v.s,!v.c||v.e>j?M.c=M.e=null:v.e<K?M.c=[M.e=0]:(M.e=v.e,M.c=v.c.slice());return}if((w=typeof v=="number")&&v*0==0){if(M.s=1/v<0?(v=-v,-1):1,v===~~v){for(x=0,L=v;L>=10;L/=10,x++);x>j?M.c=M.e=null:(M.e=x,M.c=[v]);return}b=String(v)}else{if(!n.test(b=String(v)))return B(M,b,w);M.s=b.charCodeAt(0)==45?(b=b.slice(1),-1):1}(x=b.indexOf("."))>-1&&(b=b.replace(".","")),(L=b.search(/e/i))>0?(x<0&&(x=L),x+=+b.slice(L+1),b=b.substring(0,L)):x<0&&(x=b.length)}else{if(y(T,2,qe.length,"Base"),T==10&&Ro)return M=new H(v),Je(M,X+M.e+1,Z);if(b=String(v),w=typeof v=="number"){if(v*0!=0)return B(M,b,w,T);if(M.s=1/v<0?(b=b.slice(1),-1):1,H.DEBUG&&b.replace(/^0\.0*|\./,"").length>15)throw Error(a+v)}else M.s=b.charCodeAt(0)===45?(b=b.slice(1),-1):1;for(S=qe.slice(0,T),x=L=0,N=b.length;L<N;L++)if(S.indexOf(U=b.charAt(L))<0){if(U=="."){if(L>x){x=N;continue}}else if(!R&&(b==b.toUpperCase()&&(b=b.toLowerCase())||b==b.toLowerCase()&&(b=b.toUpperCase()))){R=!0,L=-1,x=0;continue}return B(M,String(v),w,T)}w=!1,b=O(b,T,10,M.s),(x=b.indexOf("."))>-1?b=b.replace(".",""):x=b.length}for(L=0;b.charCodeAt(L)===48;L++);for(N=b.length;b.charCodeAt(--N)===48;);if(b=b.slice(L,++N)){if(N-=L,w&&H.DEBUG&&N>15&&(v>d||v!==i(v)))throw Error(a+M.s*v);if((x=x-L-1)>j)M.c=M.e=null;else if(x<K)M.c=[M.e=0];else{if(M.e=x,M.c=[],L=(x+1)%c,x<0&&(L+=c),L<N){for(L&&M.c.push(+b.slice(0,L)),N-=c;L<N;)M.c.push(+b.slice(L,L+=c));L=c-(b=b.slice(L)).length}else L-=N;for(;L--;b+="0");M.c.push(+b)}}else M.c=[M.e=0]}H.clone=m,H.ROUND_UP=0,H.ROUND_DOWN=1,H.ROUND_CEIL=2,H.ROUND_FLOOR=3,H.ROUND_HALF_UP=4,H.ROUND_HALF_DOWN=5,H.ROUND_HALF_EVEN=6,H.ROUND_HALF_CEIL=7,H.ROUND_HALF_FLOOR=8,H.EUCLID=9,H.config=H.set=function(v){var T,S;if(v!=null)if(typeof v=="object"){if(v.hasOwnProperty(T="DECIMAL_PLACES")&&(S=v[T],y(S,0,h,T),X=S),v.hasOwnProperty(T="ROUNDING_MODE")&&(S=v[T],y(S,0,8,T),Z=S),v.hasOwnProperty(T="EXPONENTIAL_AT")&&(S=v[T],S&&S.pop?(y(S[0],-h,0,T),y(S[1],0,h,T),ne=S[0],D=S[1]):(y(S,-h,h,T),ne=-(D=S<0?-S:S))),v.hasOwnProperty(T="RANGE"))if(S=v[T],S&&S.pop)y(S[0],-h,-1,T),y(S[1],1,h,T),K=S[0],j=S[1];else if(y(S,-h,h,T),S)K=-(j=S<0?-S:S);else throw Error(o+T+" cannot be zero: "+S);if(v.hasOwnProperty(T="CRYPTO"))if(S=v[T],S===!!S)if(S)if(typeof crypto<"u"&&crypto&&(crypto.getRandomValues||crypto.randomBytes))_e=S;else throw _e=!S,Error(o+"crypto unavailable");else _e=S;else throw Error(o+T+" not true or false: "+S);if(v.hasOwnProperty(T="MODULO_MODE")&&(S=v[T],y(S,0,9,T),Pe=S),v.hasOwnProperty(T="POW_PRECISION")&&(S=v[T],y(S,0,h,T),Ae=S),v.hasOwnProperty(T="FORMAT"))if(S=v[T],typeof S=="object")Re=S;else throw Error(o+T+" not an object: "+S);if(v.hasOwnProperty(T="ALPHABET"))if(S=v[T],typeof S=="string"&&!/^.?$|[+\-.\s]|(.).*\1/.test(S))Ro=S.slice(0,10)=="0123456789",qe=S;else throw Error(o+T+" invalid: "+S)}else throw Error(o+"Object expected: "+v);return{DECIMAL_PLACES:X,ROUNDING_MODE:Z,EXPONENTIAL_AT:[ne,D],RANGE:[K,j],CRYPTO:_e,MODULO_MODE:Pe,POW_PRECISION:Ae,FORMAT:Re,ALPHABET:qe}},H.isBigNumber=function(v){if(!v||v._isBigNumber!==!0)return!1;if(!H.DEBUG)return!0;var T,S,U=v.c,R=v.e,x=v.s;e:if({}.toString.call(U)=="[object Array]"){if((x===1||x===-1)&&R>=-h&&R<=h&&R===i(R)){if(U[0]===0){if(R===0&&U.length===1)return!0;break e}if(T=(R+1)%c,T<1&&(T+=c),String(U[0]).length==T){for(T=0;T<U.length;T++)if(S=U[T],S<0||S>=u||S!==i(S))break e;if(S!==0)return!0}}}else if(U===null&&R===null&&(x===null||x===1||x===-1))return!0;throw Error(o+"Invalid BigNumber: "+v)},H.maximum=H.max=function(){return Wu(arguments,-1)},H.minimum=H.min=function(){return Wu(arguments,1)},H.random=(function(){var v=9007199254740992,T=Math.random()*v&2097151?function(){return i(Math.random()*v)}:function(){return(Math.random()*1073741824|0)*8388608+(Math.random()*8388608|0)};return function(S){var U,R,x,L,w,N=0,b=[],M=new H(V);if(S==null?S=X:y(S,0,h),L=r(S/c),_e)if(crypto.getRandomValues){for(U=crypto.getRandomValues(new Uint32Array(L*=2));N<L;)w=U[N]*131072+(U[N+1]>>>11),w>=9e15?(R=crypto.getRandomValues(new Uint32Array(2)),U[N]=R[0],U[N+1]=R[1]):(b.push(w%1e14),N+=2);N=L/2}else if(crypto.randomBytes){for(U=crypto.randomBytes(L*=7);N<L;)w=(U[N]&31)*281474976710656+U[N+1]*1099511627776+U[N+2]*4294967296+U[N+3]*16777216+(U[N+4]<<16)+(U[N+5]<<8)+U[N+6],w>=9e15?crypto.randomBytes(7).copy(U,N):(b.push(w%1e14),N+=7);N=L/7}else throw _e=!1,Error(o+"crypto unavailable");if(!_e)for(;N<L;)w=T(),w<9e15&&(b[N++]=w%1e14);for(L=b[--N],S%=c,L&&S&&(w=f[c-S],b[N]=i(L/w)*w);b[N]===0;b.pop(),N--);if(N<0)b=[x=0];else{for(x=-1;b[0]===0;b.splice(0,1),x-=c);for(N=1,w=b[0];w>=10;w/=10,N++);N<c&&(x-=c-N)}return M.e=x,M.c=b,M}})(),H.sum=function(){for(var v=1,T=arguments,S=new H(T[0]);v<T.length;)S=S.plus(T[v++]);return S},O=(function(){var v="0123456789";function T(S,U,R,x){for(var L,w=[0],N,b=0,M=S.length;b<M;){for(N=w.length;N--;w[N]*=U);for(w[0]+=x.indexOf(S.charAt(b++)),L=0;L<w.length;L++)w[L]>R-1&&(w[L+1]==null&&(w[L+1]=0),w[L+1]+=w[L]/R|0,w[L]%=R)}return w.reverse()}return function(S,U,R,x,L){var w,N,b,M,q,Y,z,oe,Ce=S.indexOf("."),we=X,re=Z;for(Ce>=0&&(M=Ae,Ae=0,S=S.replace(".",""),oe=new H(U),Y=oe.pow(S.length-Ce),Ae=M,oe.c=T(I(g(Y.c),Y.e,"0"),10,R,v),oe.e=oe.c.length),z=T(S,U,R,L?(w=qe,v):(w=v,qe)),b=M=z.length;z[--M]==0;z.pop());if(!z[0])return w.charAt(0);if(Ce<0?--b:(Y.c=z,Y.e=b,Y.s=x,Y=G(Y,oe,we,re,R),z=Y.c,q=Y.r,b=Y.e),N=b+we+1,Ce=z[N],M=R/2,q=q||N<0||z[N+1]!=null,q=re<4?(Ce!=null||q)&&(re==0||re==(Y.s<0?3:2)):Ce>M||Ce==M&&(re==4||q||re==6&&z[N-1]&1||re==(Y.s<0?8:7)),N<1||!z[0])S=q?I(w.charAt(1),-we,w.charAt(0)):w.charAt(0);else{if(z.length=N,q)for(--R;++z[--N]>R;)z[N]=0,N||(++b,z=[1].concat(z));for(M=z.length;!z[--M];);for(Ce=0,S="";Ce<=M;S+=w.charAt(z[Ce++]));S=I(S,b,w.charAt(0))}return S}})(),G=(function(){function v(U,R,x){var L,w,N,b,M=0,q=U.length,Y=R%p,z=R/p|0;for(U=U.slice();q--;)N=U[q]%p,b=U[q]/p|0,L=z*N+b*Y,w=Y*N+L%p*p+M,M=(w/x|0)+(L/p|0)+z*b,U[q]=w%x;return M&&(U=[M].concat(U)),U}function T(U,R,x,L){var w,N;if(x!=L)N=x>L?1:-1;else for(w=N=0;w<x;w++)if(U[w]!=R[w]){N=U[w]>R[w]?1:-1;break}return N}function S(U,R,x,L){for(var w=0;x--;)U[x]-=w,w=U[x]<R[x]?1:0,U[x]=w*L+U[x]-R[x];for(;!U[0]&&U.length>1;U.splice(0,1));}return function(U,R,x,L,w){var N,b,M,q,Y,z,oe,Ce,we,re,ae,De,Dr,ko,Do,pt,tr,We=U.s==R.s?1:-1,be=U.c,Se=R.c;if(!be||!be[0]||!Se||!Se[0])return new H(!U.s||!R.s||(be?Se&&be[0]==Se[0]:!Se)?NaN:be&&be[0]==0||!Se?We*0:We/0);for(Ce=new H(We),we=Ce.c=[],b=U.e-R.e,We=x+b+1,w||(w=u,b=_(U.e/c)-_(R.e/c),We=We/c|0),M=0;Se[M]==(be[M]||0);M++);if(Se[M]>(be[M]||0)&&b--,We<0)we.push(1),q=!0;else{for(ko=be.length,pt=Se.length,M=0,We+=2,Y=i(w/(Se[0]+1)),Y>1&&(Se=v(Se,Y,w),be=v(be,Y,w),pt=Se.length,ko=be.length),Dr=pt,re=be.slice(0,pt),ae=re.length;ae<pt;re[ae++]=0);tr=Se.slice(),tr=[0].concat(tr),Do=Se[0],Se[1]>=w/2&&Do++;do{if(Y=0,N=T(Se,re,pt,ae),N<0){if(De=re[0],pt!=ae&&(De=De*w+(re[1]||0)),Y=i(De/Do),Y>1)for(Y>=w&&(Y=w-1),z=v(Se,Y,w),oe=z.length,ae=re.length;T(z,re,oe,ae)==1;)Y--,S(z,pt<oe?tr:Se,oe,w),oe=z.length,N=1;else Y==0&&(N=Y=1),z=Se.slice(),oe=z.length;if(oe<ae&&(z=[0].concat(z)),S(re,z,ae,w),ae=re.length,N==-1)for(;T(Se,re,pt,ae)<1;)Y++,S(re,pt<ae?tr:Se,ae,w),ae=re.length}else N===0&&(Y++,re=[0]);we[M++]=Y,re[0]?re[ae++]=be[Dr]||0:(re=[be[Dr]],ae=1)}while((Dr++<ko||re[0]!=null)&&We--);q=re[0]!=null,we[0]||we.splice(0,1)}if(w==u){for(M=1,We=we[0];We>=10;We/=10,M++);Je(Ce,x+(Ce.e=M+b*c-1)+1,L,q)}else Ce.e=b,Ce.r=+q;return Ce}})();function No(v,T,S,U){var R,x,L,w,N;if(S==null?S=Z:y(S,0,8),!v.c)return v.toString();if(R=v.c[0],L=v.e,T==null)N=g(v.c),N=U==1||U==2&&(L<=ne||L>=D)?A(N,L):I(N,L,"0");else if(v=Je(new H(v),T,S),x=v.e,N=g(v.c),w=N.length,U==1||U==2&&(T<=x||x<=ne)){for(;w<T;N+="0",w++);N=A(N,x)}else if(T-=L+(U===2&&x>L),N=I(N,x,"0"),x+1>w){if(--T>0)for(N+=".";T--;N+="0");}else if(T+=x-w,T>0)for(x+1==w&&(N+=".");T--;N+="0");return v.s<0&&R?"-"+N:N}function Wu(v,T){for(var S,U,R=1,x=new H(v[0]);R<v.length;R++)U=new H(v[R]),(!U.s||(S=E(x,U))===T||S===0&&x.s===T)&&(x=U);return x}function xo(v,T,S){for(var U=1,R=T.length;!T[--R];T.pop());for(R=T[0];R>=10;R/=10,U++);return(S=U+S*c-1)>j?v.c=v.e=null:S<K?v.c=[v.e=0]:(v.e=S,v.c=T),v}B=(function(){var v=/^(-?)0([xbo])(?=\w[\w.]*$)/i,T=/^([^.]+)\.$/,S=/^\.([^.]+)$/,U=/^-?(Infinity|NaN)$/,R=/^\s*\+(?=[\w.])|^\s+|\s+$/g;return function(x,L,w,N){var b,M=w?L:L.replace(R,"");if(U.test(M))x.s=isNaN(M)?null:M<0?-1:1;else{if(!w&&(M=M.replace(v,function(q,Y,z){return b=(z=z.toLowerCase())=="x"?16:z=="b"?2:8,!N||N==b?Y:q}),N&&(b=N,M=M.replace(T,"$1").replace(S,"0.$1")),L!=M))return new H(M,b);if(H.DEBUG)throw Error(o+"Not a"+(N?" base "+N:"")+" number: "+L);x.s=null}x.c=x.e=null}})();function Je(v,T,S,U){var R,x,L,w,N,b,M,q=v.c,Y=f;if(q){e:{for(R=1,w=q[0];w>=10;w/=10,R++);if(x=T-R,x<0)x+=c,L=T,N=q[b=0],M=i(N/Y[R-L-1]%10);else if(b=r((x+1)/c),b>=q.length)if(U){for(;q.length<=b;q.push(0));N=M=0,R=1,x%=c,L=x-c+1}else break e;else{for(N=w=q[b],R=1;w>=10;w/=10,R++);x%=c,L=x-c+R,M=L<0?0:i(N/Y[R-L-1]%10)}if(U=U||T<0||q[b+1]!=null||(L<0?N:N%Y[R-L-1]),U=S<4?(M||U)&&(S==0||S==(v.s<0?3:2)):M>5||M==5&&(S==4||U||S==6&&(x>0?L>0?N/Y[R-L]:0:q[b-1])%10&1||S==(v.s<0?8:7)),T<1||!q[0])return q.length=0,U?(T-=v.e+1,q[0]=Y[(c-T%c)%c],v.e=-T||0):q[0]=v.e=0,v;if(x==0?(q.length=b,w=1,b--):(q.length=b+1,w=Y[c-x],q[b]=L>0?i(N/Y[R-L]%Y[L])*w:0),U)for(;;)if(b==0){for(x=1,L=q[0];L>=10;L/=10,x++);for(L=q[0]+=w,w=1;L>=10;L/=10,w++);x!=w&&(v.e++,q[0]==u&&(q[0]=1));break}else{if(q[b]+=w,q[b]!=u)break;q[b--]=0,w=1}for(x=q.length;q[--x]===0;q.pop());}v.e>j?v.c=v.e=null:v.e<K&&(v.c=[v.e=0])}return v}function St(v){var T,S=v.e;return S===null?v.toString():(T=g(v.c),T=S<=ne||S>=D?A(T,S):I(T,S,"0"),v.s<0?"-"+T:T)}return k.absoluteValue=k.abs=function(){var v=new H(this);return v.s<0&&(v.s=1),v},k.comparedTo=function(v,T){return E(this,new H(v,T))},k.decimalPlaces=k.dp=function(v,T){var S,U,R,x=this;if(v!=null)return y(v,0,h),T==null?T=Z:y(T,0,8),Je(new H(x),v+x.e+1,T);if(!(S=x.c))return null;if(U=((R=S.length-1)-_(this.e/c))*c,R=S[R])for(;R%10==0;R/=10,U--);return U<0&&(U=0),U},k.dividedBy=k.div=function(v,T){return G(this,new H(v,T),X,Z)},k.dividedToIntegerBy=k.idiv=function(v,T){return G(this,new H(v,T),0,1)},k.exponentiatedBy=k.pow=function(v,T){var S,U,R,x,L,w,N,b,M,q=this;if(v=new H(v),v.c&&!v.isInteger())throw Error(o+"Exponent not an integer: "+St(v));if(T!=null&&(T=new H(T)),w=v.e>14,!q.c||!q.c[0]||q.c[0]==1&&!q.e&&q.c.length==1||!v.c||!v.c[0])return M=new H(Math.pow(+St(q),w?v.s*(2-C(v)):+St(v))),T?M.mod(T):M;if(N=v.s<0,T){if(T.c?!T.c[0]:!T.s)return new H(NaN);U=!N&&q.isInteger()&&T.isInteger(),U&&(q=q.mod(T))}else{if(v.e>9&&(q.e>0||q.e<-1||(q.e==0?q.c[0]>1||w&&q.c[1]>=24e7:q.c[0]<8e13||w&&q.c[0]<=9999975e7)))return x=q.s<0&&C(v)?-0:0,q.e>-1&&(x=1/x),new H(N?1/x:x);Ae&&(x=r(Ae/c+2))}for(w?(S=new H(.5),N&&(v.s=1),b=C(v)):(R=Math.abs(+St(v)),b=R%2),M=new H(V);;){if(b){if(M=M.times(q),!M.c)break;x?M.c.length>x&&(M.c.length=x):U&&(M=M.mod(T))}if(R){if(R=i(R/2),R===0)break;b=R%2}else if(v=v.times(S),Je(v,v.e+1,1),v.e>14)b=C(v);else{if(R=+St(v),R===0)break;b=R%2}q=q.times(q),x?q.c&&q.c.length>x&&(q.c.length=x):U&&(q=q.mod(T))}return U?M:(N&&(M=V.div(M)),T?M.mod(T):x?Je(M,Ae,Z,L):M)},k.integerValue=function(v){var T=new H(this);return v==null?v=Z:y(v,0,8),Je(T,T.e+1,v)},k.isEqualTo=k.eq=function(v,T){return E(this,new H(v,T))===0},k.isFinite=function(){return!!this.c},k.isGreaterThan=k.gt=function(v,T){return E(this,new H(v,T))>0},k.isGreaterThanOrEqualTo=k.gte=function(v,T){return(T=E(this,new H(v,T)))===1||T===0},k.isInteger=function(){return!!this.c&&_(this.e/c)>this.c.length-2},k.isLessThan=k.lt=function(v,T){return E(this,new H(v,T))<0},k.isLessThanOrEqualTo=k.lte=function(v,T){return(T=E(this,new H(v,T)))===-1||T===0},k.isNaN=function(){return!this.s},k.isNegative=function(){return this.s<0},k.isPositive=function(){return this.s>0},k.isZero=function(){return!!this.c&&this.c[0]==0},k.minus=function(v,T){var S,U,R,x,L=this,w=L.s;if(v=new H(v,T),T=v.s,!w||!T)return new H(NaN);if(w!=T)return v.s=-T,L.plus(v);var N=L.e/c,b=v.e/c,M=L.c,q=v.c;if(!N||!b){if(!M||!q)return M?(v.s=-T,v):new H(q?L:NaN);if(!M[0]||!q[0])return q[0]?(v.s=-T,v):new H(M[0]?L:Z==3?-0:0)}if(N=_(N),b=_(b),M=M.slice(),w=N-b){for((x=w<0)?(w=-w,R=M):(b=N,R=q),R.reverse(),T=w;T--;R.push(0));R.reverse()}else for(U=(x=(w=M.length)<(T=q.length))?w:T,w=T=0;T<U;T++)if(M[T]!=q[T]){x=M[T]<q[T];break}if(x&&(R=M,M=q,q=R,v.s=-v.s),T=(U=q.length)-(S=M.length),T>0)for(;T--;M[S++]=0);for(T=u-1;U>w;){if(M[--U]<q[U]){for(S=U;S&&!M[--S];M[S]=T);--M[S],M[U]+=u}M[U]-=q[U]}for(;M[0]==0;M.splice(0,1),--b);return M[0]?xo(v,M,b):(v.s=Z==3?-1:1,v.c=[v.e=0],v)},k.modulo=k.mod=function(v,T){var S,U,R=this;return v=new H(v,T),!R.c||!v.s||v.c&&!v.c[0]?new H(NaN):!v.c||R.c&&!R.c[0]?new H(R):(Pe==9?(U=v.s,v.s=1,S=G(R,v,0,3),v.s=U,S.s*=U):S=G(R,v,0,Pe),v=R.minus(S.times(v)),!v.c[0]&&Pe==1&&(v.s=R.s),v)},k.multipliedBy=k.times=function(v,T){var S,U,R,x,L,w,N,b,M,q,Y,z,oe,Ce,we,re=this,ae=re.c,De=(v=new H(v,T)).c;if(!ae||!De||!ae[0]||!De[0])return!re.s||!v.s||ae&&!ae[0]&&!De||De&&!De[0]&&!ae?v.c=v.e=v.s=null:(v.s*=re.s,!ae||!De?v.c=v.e=null:(v.c=[0],v.e=0)),v;for(U=_(re.e/c)+_(v.e/c),v.s*=re.s,N=ae.length,q=De.length,N<q&&(oe=ae,ae=De,De=oe,R=N,N=q,q=R),R=N+q,oe=[];R--;oe.push(0));for(Ce=u,we=p,R=q;--R>=0;){for(S=0,Y=De[R]%we,z=De[R]/we|0,L=N,x=R+L;x>R;)b=ae[--L]%we,M=ae[L]/we|0,w=z*b+M*Y,b=Y*b+w%we*we+oe[x]+S,S=(b/Ce|0)+(w/we|0)+z*M,oe[x--]=b%Ce;oe[x]=S}return S?++U:oe.splice(0,1),xo(v,oe,U)},k.negated=function(){var v=new H(this);return v.s=-v.s||null,v},k.plus=function(v,T){var S,U=this,R=U.s;if(v=new H(v,T),T=v.s,!R||!T)return new H(NaN);if(R!=T)return v.s=-T,U.minus(v);var x=U.e/c,L=v.e/c,w=U.c,N=v.c;if(!x||!L){if(!w||!N)return new H(R/0);if(!w[0]||!N[0])return N[0]?v:new H(w[0]?U:R*0)}if(x=_(x),L=_(L),w=w.slice(),R=x-L){for(R>0?(L=x,S=N):(R=-R,S=w),S.reverse();R--;S.push(0));S.reverse()}for(R=w.length,T=N.length,R-T<0&&(S=N,N=w,w=S,T=R),R=0;T;)R=(w[--T]=w[T]+N[T]+R)/u|0,w[T]=u===w[T]?0:w[T]%u;return R&&(w=[R].concat(w),++L),xo(v,w,L)},k.precision=k.sd=function(v,T){var S,U,R,x=this;if(v!=null&&v!==!!v)return y(v,1,h),T==null?T=Z:y(T,0,8),Je(new H(x),v,T);if(!(S=x.c))return null;if(R=S.length-1,U=R*c+1,R=S[R]){for(;R%10==0;R/=10,U--);for(R=S[0];R>=10;R/=10,U++);}return v&&x.e+1>U&&(U=x.e+1),U},k.shiftedBy=function(v){return y(v,-d,d),this.times("1e"+v)},k.squareRoot=k.sqrt=function(){var v,T,S,U,R,x=this,L=x.c,w=x.s,N=x.e,b=X+4,M=new H("0.5");if(w!==1||!L||!L[0])return new H(!w||w<0&&(!L||L[0])?NaN:L?x:1/0);if(w=Math.sqrt(+St(x)),w==0||w==1/0?(T=g(L),(T.length+N)%2==0&&(T+="0"),w=Math.sqrt(+T),N=_((N+1)/2)-(N<0||N%2),w==1/0?T="5e"+N:(T=w.toExponential(),T=T.slice(0,T.indexOf("e")+1)+N),S=new H(T)):S=new H(w+""),S.c[0]){for(N=S.e,w=N+b,w<3&&(w=0);;)if(R=S,S=M.times(R.plus(G(x,R,b,1))),g(R.c).slice(0,w)===(T=g(S.c)).slice(0,w))if(S.e<N&&--w,T=T.slice(w-3,w+1),T=="9999"||!U&&T=="4999"){if(!U&&(Je(R,R.e+X+2,0),R.times(R).eq(x))){S=R;break}b+=4,w+=4,U=1}else{(!+T||!+T.slice(1)&&T.charAt(0)=="5")&&(Je(S,S.e+X+2,1),v=!S.times(S).eq(x));break}}return Je(S,S.e+X+1,Z,v)},k.toExponential=function(v,T){return v!=null&&(y(v,0,h),v++),No(this,v,T,1)},k.toFixed=function(v,T){return v!=null&&(y(v,0,h),v=v+this.e+1),No(this,v,T)},k.toFormat=function(v,T,S){var U,R=this;if(S==null)v!=null&&T&&typeof T=="object"?(S=T,T=null):v&&typeof v=="object"?(S=v,v=T=null):S=Re;else if(typeof S!="object")throw Error(o+"Argument not an object: "+S);if(U=R.toFixed(v,T),R.c){var x,L=U.split("."),w=+S.groupSize,N=+S.secondaryGroupSize,b=S.groupSeparator||"",M=L[0],q=L[1],Y=R.s<0,z=Y?M.slice(1):M,oe=z.length;if(N&&(x=w,w=N,N=x,oe-=x),w>0&&oe>0){for(x=oe%w||w,M=z.substr(0,x);x<oe;x+=w)M+=b+z.substr(x,w);N>0&&(M+=b+z.slice(x)),Y&&(M="-"+M)}U=q?M+(S.decimalSeparator||"")+((N=+S.fractionGroupSize)?q.replace(new RegExp("\\d{"+N+"}\\B","g"),"$&"+(S.fractionGroupSeparator||"")):q):M}return(S.prefix||"")+U+(S.suffix||"")},k.toFraction=function(v){var T,S,U,R,x,L,w,N,b,M,q,Y,z=this,oe=z.c;if(v!=null&&(w=new H(v),!w.isInteger()&&(w.c||w.s!==1)||w.lt(V)))throw Error(o+"Argument "+(w.isInteger()?"out of range: ":"not an integer: ")+St(w));if(!oe)return new H(z);for(T=new H(V),b=S=new H(V),U=N=new H(V),Y=g(oe),x=T.e=Y.length-z.e-1,T.c[0]=f[(L=x%c)<0?c+L:L],v=!v||w.comparedTo(T)>0?x>0?T:b:w,L=j,j=1/0,w=new H(Y),N.c[0]=0;M=G(w,T,0,1),R=S.plus(M.times(U)),R.comparedTo(v)!=1;)S=U,U=R,b=N.plus(M.times(R=b)),N=R,T=w.minus(M.times(R=T)),w=R;return R=G(v.minus(S),U,0,1),N=N.plus(R.times(b)),S=S.plus(R.times(U)),N.s=b.s=z.s,x=x*2,q=G(b,U,x,Z).minus(z).abs().comparedTo(G(N,S,x,Z).minus(z).abs())<1?[b,U]:[N,S],j=L,q},k.toNumber=function(){return+St(this)},k.toPrecision=function(v,T){return v!=null&&y(v,1,h),No(this,v,T,2)},k.toString=function(v){var T,S=this,U=S.s,R=S.e;return R===null?U?(T="Infinity",U<0&&(T="-"+T)):T="NaN":(v==null?T=R<=ne||R>=D?A(g(S.c),R):I(g(S.c),R,"0"):v===10&&Ro?(S=Je(new H(S),X+R+1,Z),T=I(g(S.c),S.e,"0")):(y(v,2,qe.length,"Base"),T=O(I(g(S.c),R,"0"),10,v,U,!0)),U<0&&S.c[0]&&(T="-"+T)),T},k.valueOf=k.toJSON=function(){return St(this)},k._isBigNumber=!0,P!=null&&H.set(P),H}function _(P){var G=P|0;return P>0||P===G?G:G-1}function g(P){for(var G,O,B=1,k=P.length,V=P[0]+"";B<k;){for(G=P[B++]+"",O=c-G.length;O--;G="0"+G);V+=G}for(k=V.length;V.charCodeAt(--k)===48;);return V.slice(0,k+1||1)}function E(P,G){var O,B,k=P.c,V=G.c,X=P.s,Z=G.s,ne=P.e,D=G.e;if(!X||!Z)return null;if(O=k&&!k[0],B=V&&!V[0],O||B)return O?B?0:-Z:X;if(X!=Z)return X;if(O=X<0,B=ne==D,!k||!V)return B?0:!k^O?1:-1;if(!B)return ne>D^O?1:-1;for(Z=(ne=k.length)<(D=V.length)?ne:D,X=0;X<Z;X++)if(k[X]!=V[X])return k[X]>V[X]^O?1:-1;return ne==D?0:ne>D^O?1:-1}function y(P,G,O,B){if(P<G||P>O||P!==i(P))throw Error(o+(B||"Argument")+(typeof P=="number"?P<G||P>O?" out of range: ":" not an integer: ":" not a primitive number: ")+String(P))}function C(P){var G=P.c.length-1;return _(P.e/c)==G&&P.c[G]%2!=0}function A(P,G){return(P.length>1?P.charAt(0)+"."+P.slice(1):P)+(G<0?"e":"e+")+G}function I(P,G,O){var B,k;if(G<0){for(k=O+".";++G;k+=O);P=k+P}else if(B=P.length,++G>B){for(k=O,G-=B;--G;k+=O);P+=k}else G<B&&(P=P.slice(0,G)+"."+P.slice(G));return P}e=m(),e.default=e.BigNumber=e,typeof define=="function"&&define.amd?define(function(){return e}):typeof Or<"u"&&Or.exports?Or.exports=e:(t||(t=typeof self<"u"&&self?self:window),t.BigNumber=e)})(vc)});var Sc=F((Ck,Cc)=>{var Tc=Fo(),Ac=Cc.exports;(function(){"use strict";function t(d){return d<10?"0"+d:d}var e=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,n=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,r,i,o={"\b":"\\b"," ":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"},a;function u(d){return n.lastIndex=0,n.test(d)?'"'+d.replace(n,function(f){var p=o[f];return typeof p=="string"?p:"\\u"+("0000"+f.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+d+'"'}function c(d,f){var p,h,m,_,g=r,E,y=f[d],C=y!=null&&(y instanceof Tc||Tc.isBigNumber(y));switch(y&&typeof y=="object"&&typeof y.toJSON=="function"&&(y=y.toJSON(d)),typeof a=="function"&&(y=a.call(f,d,y)),typeof y){case"string":return C?y:u(y);case"number":return isFinite(y)?String(y):"null";case"boolean":case"null":case"bigint":return String(y);case"object":if(!y)return"null";if(r+=i,E=[],Object.prototype.toString.apply(y)==="[object Array]"){for(_=y.length,p=0;p<_;p+=1)E[p]=c(p,y)||"null";return m=E.length===0?"[]":r?`[
7
- `+r+E.join(`,
8
- `+r)+`
9
- `+g+"]":"["+E.join(",")+"]",r=g,m}if(a&&typeof a=="object")for(_=a.length,p=0;p<_;p+=1)typeof a[p]=="string"&&(h=a[p],m=c(h,y),m&&E.push(u(h)+(r?": ":":")+m));else Object.keys(y).forEach(function(A){var I=c(A,y);I&&E.push(u(A)+(r?": ":":")+I)});return m=E.length===0?"{}":r?`{
10
- `+r+E.join(`,
11
- `+r)+`
12
- `+g+"}":"{"+E.join(",")+"}",r=g,m}}typeof Ac.stringify!="function"&&(Ac.stringify=function(d,f,p){var h;if(r="",i="",typeof p=="number")for(h=0;h<p;h+=1)i+=" ";else typeof p=="string"&&(i=p);if(a=f,f&&typeof f!="function"&&(typeof f!="object"||typeof f.length!="number"))throw new Error("JSON.stringify");return c("",{"":d})})})()});var wc=F((Sk,Ic)=>{var qr=null,dy=/(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])/,fy=/(?: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)/,py=function(t){"use strict";var e={strict:!1,storeAsString:!1,alwaysParseAsBig:!1,useNativeBigInt:!1,protoAction:"error",constructorAction:"error"};if(t!=null){if(t.strict===!0&&(e.strict=!0),t.storeAsString===!0&&(e.storeAsString=!0),e.alwaysParseAsBig=t.alwaysParseAsBig===!0?t.alwaysParseAsBig:!1,e.useNativeBigInt=t.useNativeBigInt===!0?t.useNativeBigInt:!1,typeof t.constructorAction<"u")if(t.constructorAction==="error"||t.constructorAction==="ignore"||t.constructorAction==="preserve")e.constructorAction=t.constructorAction;else throw new Error(`Incorrect value for constructorAction option, must be "error", "ignore" or undefined but passed ${t.constructorAction}`);if(typeof t.protoAction<"u")if(t.protoAction==="error"||t.protoAction==="ignore"||t.protoAction==="preserve")e.protoAction=t.protoAction;else throw new Error(`Incorrect value for protoAction option, must be "error", "ignore" or undefined but passed ${t.protoAction}`)}var n,r,i={'"':'"',"\\":"\\","/":"/",b:"\b",f:"\f",n:`
13
- `,r:"\r",t:" "},o,a=function(g){throw{name:"SyntaxError",message:g,at:n,text:o}},u=function(g){return g&&g!==r&&a("Expected '"+g+"' instead of '"+r+"'"),r=o.charAt(n),n+=1,r},c=function(){var g,E="";for(r==="-"&&(E="-",u("-"));r>="0"&&r<="9";)E+=r,u();if(r===".")for(E+=".";u()&&r>="0"&&r<="9";)E+=r;if(r==="e"||r==="E")for(E+=r,u(),(r==="-"||r==="+")&&(E+=r,u());r>="0"&&r<="9";)E+=r,u();if(g=+E,!isFinite(g))a("Bad number");else return qr==null&&(qr=Fo()),E.length>15?e.storeAsString?E:e.useNativeBigInt?BigInt(E):new qr(E):e.alwaysParseAsBig?e.useNativeBigInt?BigInt(g):new qr(g):g},d=function(){var g,E,y="",C;if(r==='"')for(var A=n;u();){if(r==='"')return n-1>A&&(y+=o.substring(A,n-1)),u(),y;if(r==="\\"){if(n-1>A&&(y+=o.substring(A,n-1)),u(),r==="u"){for(C=0,E=0;E<4&&(g=parseInt(u(),16),!!isFinite(g));E+=1)C=C*16+g;y+=String.fromCharCode(C)}else if(typeof i[r]=="string")y+=i[r];else break;A=n}}a("Bad string")},f=function(){for(;r&&r<=" ";)u()},p=function(){switch(r){case"t":return u("t"),u("r"),u("u"),u("e"),!0;case"f":return u("f"),u("a"),u("l"),u("s"),u("e"),!1;case"n":return u("n"),u("u"),u("l"),u("l"),null}a("Unexpected '"+r+"'")},h,m=function(){var g=[];if(r==="["){if(u("["),f(),r==="]")return u("]"),g;for(;r;){if(g.push(h()),f(),r==="]")return u("]"),g;u(","),f()}}a("Bad array")},_=function(){var g,E=Object.create(null);if(r==="{"){if(u("{"),f(),r==="}")return u("}"),E;for(;r;){if(g=d(),f(),u(":"),e.strict===!0&&Object.hasOwnProperty.call(E,g)&&a('Duplicate key "'+g+'"'),dy.test(g)===!0?e.protoAction==="error"?a("Object contains forbidden prototype property"):e.protoAction==="ignore"?h():E[g]=h():fy.test(g)===!0?e.constructorAction==="error"?a("Object contains forbidden constructor property"):e.constructorAction==="ignore"?h():E[g]=h():E[g]=h(),f(),r==="}")return u("}"),E;u(","),f()}}a("Bad object")};return h=function(){switch(f(),r){case"{":return _();case"[":return m();case'"':return d();case"-":return c();default:return r>="0"&&r<="9"?c():p()}},function(g,E){var y;return o=g+"",n=0,r=" ",y=h(),f(),r&&a("Syntax error"),typeof E=="function"?(function C(A,I){var P,G,O=A[I];return O&&typeof O=="object"&&Object.keys(O).forEach(function(B){G=C(O,B),G!==void 0?O[B]=G:delete O[B]}),E.call(A,I,O)})({"":y},""):y}};Ic.exports=py});var Nc=F((Ik,Fr)=>{var Pc=Sc().stringify,Rc=wc();Fr.exports=function(t){return{parse:Rc(t),stringify:Pc}};Fr.exports.parse=Rc();Fr.exports.stringify=Pc});var Bo=F(it=>{"use strict";Object.defineProperty(it,"__esModule",{value:!0});it.GCE_LINUX_BIOS_PATHS=void 0;it.isGoogleCloudServerless=Dc;it.isGoogleComputeEngineLinux=Mc;it.isGoogleComputeEngineMACAddress=Uc;it.isGoogleComputeEngine=bc;it.detectGCPResidency=my;var xc=W("fs"),kc=W("os");it.GCE_LINUX_BIOS_PATHS={BIOS_DATE:"/sys/class/dmi/id/bios_date",BIOS_VENDOR:"/sys/class/dmi/id/bios_vendor"};var hy=/^42:01/;function Dc(){return!!(process.env.CLOUD_RUN_JOB||process.env.FUNCTION_NAME||process.env.K_SERVICE)}function Mc(){if((0,kc.platform)()!=="linux")return!1;try{(0,xc.statSync)(it.GCE_LINUX_BIOS_PATHS.BIOS_DATE);let t=(0,xc.readFileSync)(it.GCE_LINUX_BIOS_PATHS.BIOS_VENDOR,"utf8");return/Google/.test(t)}catch{return!1}}function Uc(){let t=(0,kc.networkInterfaces)();for(let e of Object.values(t))if(e){for(let{mac:n}of e)if(hy.test(n))return!0}return!1}function bc(){return Mc()||Uc()}function my(){return Dc()||bc()}});var Gc=F(Br=>{"use strict";Object.defineProperty(Br,"__esModule",{value:!0});Br.Colours=void 0;var Me=class t{static isEnabled(e){return e&&e.isTTY&&(typeof e.getColorDepth=="function"?e.getColorDepth()>2:!0)}static refresh(){t.enabled=t.isEnabled(process==null?void 0:process.stderr),this.enabled?(t.reset="\x1B[0m",t.bright="\x1B[1m",t.dim="\x1B[2m",t.red="\x1B[31m",t.green="\x1B[32m",t.yellow="\x1B[33m",t.blue="\x1B[34m",t.magenta="\x1B[35m",t.cyan="\x1B[36m",t.white="\x1B[37m",t.grey="\x1B[90m"):(t.reset="",t.bright="",t.dim="",t.red="",t.green="",t.yellow="",t.blue="",t.magenta="",t.cyan="",t.white="",t.grey="")}};Br.Colours=Me;Me.enabled=!1;Me.reset="";Me.bright="";Me.dim="";Me.red="";Me.green="";Me.yellow="";Me.blue="";Me.magenta="";Me.cyan="";Me.white="";Me.grey="";Me.refresh()});var Fc=F(le=>{"use strict";var gy=le&&le.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(e,n);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,i)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),_y=le&&le.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),Lc=le&&le.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(r[r.length]=i);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),i=0;i<r.length;i++)r[i]!=="default"&&gy(n,e,r[i]);return _y(n,e),n}})();Object.defineProperty(le,"__esModule",{value:!0});le.env=le.DebugLogBackendBase=le.placeholder=le.AdhocDebugLogger=le.LogSeverity=void 0;le.getNodeBackend=Vo;le.getDebugBackend=Ey;le.getStructuredBackend=vy;le.setBackend=Ty;le.log=qc;var yy=W("events"),nr=Lc(W("process")),Oc=Lc(W("util")),Fe=Gc(),ot;(function(t){t.DEFAULT="DEFAULT",t.DEBUG="DEBUG",t.INFO="INFO",t.WARNING="WARNING",t.ERROR="ERROR"})(ot||(le.LogSeverity=ot={}));var rr=class extends yy.EventEmitter{constructor(e,n){super(),this.namespace=e,this.upstream=n,this.func=Object.assign(this.invoke.bind(this),{instance:this,on:(r,i)=>this.on(r,i)}),this.func.debug=(...r)=>this.invokeSeverity(ot.DEBUG,...r),this.func.info=(...r)=>this.invokeSeverity(ot.INFO,...r),this.func.warn=(...r)=>this.invokeSeverity(ot.WARNING,...r),this.func.error=(...r)=>this.invokeSeverity(ot.ERROR,...r),this.func.sublog=r=>qc(r,this.func)}invoke(e,...n){if(this.upstream)try{this.upstream(e,...n)}catch{}try{this.emit("log",e,n)}catch{}}invokeSeverity(e,...n){this.invoke({severity:e},...n)}};le.AdhocDebugLogger=rr;le.placeholder=new rr("",()=>{}).func;var _n=class{constructor(){var e;this.cached=new Map,this.filters=[],this.filtersSet=!1;let n=(e=nr.env[le.env.nodeEnables])!==null&&e!==void 0?e:"*";n==="all"&&(n="*"),this.filters=n.split(",")}log(e,n,...r){try{this.filtersSet||(this.setFilters(),this.filtersSet=!0);let i=this.cached.get(e);i||(i=this.makeLogger(e),this.cached.set(e,i)),i(n,...r)}catch(i){console.error(i)}}};le.DebugLogBackendBase=_n;var Ho=class extends _n{constructor(){super(...arguments),this.enabledRegexp=/.*/g}isEnabled(e){return this.enabledRegexp.test(e)}makeLogger(e){return this.enabledRegexp.test(e)?(n,...r)=>{var i;let o=`${Fe.Colours.green}${e}${Fe.Colours.reset}`,a=`${Fe.Colours.yellow}${nr.pid}${Fe.Colours.reset}`,u;switch(n.severity){case ot.ERROR:u=`${Fe.Colours.red}${n.severity}${Fe.Colours.reset}`;break;case ot.INFO:u=`${Fe.Colours.magenta}${n.severity}${Fe.Colours.reset}`;break;case ot.WARNING:u=`${Fe.Colours.yellow}${n.severity}${Fe.Colours.reset}`;break;default:u=(i=n.severity)!==null&&i!==void 0?i:ot.DEFAULT;break}let c=Oc.formatWithOptions({colors:Fe.Colours.enabled},...r),d=Object.assign({},n);delete d.severity;let f=Object.getOwnPropertyNames(d).length?JSON.stringify(d):"",p=f?`${Fe.Colours.grey}${f}${Fe.Colours.reset}`:"";console.error("%s [%s|%s] %s%s",a,o,u,c,f?` ${p}`:"")}:()=>{}}setFilters(){let n=this.filters.join(",").replace(/[|\\{}()[\]^$+?.]/g,"\\$&").replace(/\*/g,".*").replace(/,/g,"$|^");this.enabledRegexp=new RegExp(`^${n}$`,"i")}};function Vo(){return new Ho}var $o=class extends _n{constructor(e){super(),this.debugPkg=e}makeLogger(e){let n=this.debugPkg(e);return(r,...i)=>{n(i[0],...i.slice(1))}}setFilters(){var e;let n=(e=nr.env.NODE_DEBUG)!==null&&e!==void 0?e:"";nr.env.NODE_DEBUG=`${n}${n?",":""}${this.filters.join(",")}`}};function Ey(t){return new $o(t)}var Jo=class extends _n{constructor(e){var n;super(),this.upstream=(n=e)!==null&&n!==void 0?n:void 0}makeLogger(e){var n;let r=(n=this.upstream)===null||n===void 0?void 0:n.makeLogger(e);return(i,...o)=>{var a;let u=(a=i.severity)!==null&&a!==void 0?a:ot.INFO,c=Object.assign({severity:u,message:Oc.format(...o)},i),d=JSON.stringify(c);r?r(i,d):console.log("%s",d)}}setFilters(){var e;(e=this.upstream)===null||e===void 0||e.setFilters()}};function vy(t){return new Jo(t)}le.env={nodeEnables:"GOOGLE_SDK_NODE_LOGGING"};var Wo=new Map,Be;function Ty(t){Be=t,Wo.clear()}function qc(t,e){if(!Be&&!nr.env[le.env.nodeEnables]||!t)return le.placeholder;e&&(t=`${e.instance.namespace}:${t}`);let n=Wo.get(t);if(n)return n.func;if(Be===null)return le.placeholder;Be===void 0&&(Be=Vo());let r=(()=>{let i;return new rr(t,(a,...u)=>{if(i!==Be){if(Be===null)return;Be===void 0&&(Be=Vo()),i=Be}Be?.log(t,a,...u)})})();return Wo.set(t,r),r.func}});var Xo=F(rn=>{"use strict";var Ay=rn&&rn.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(e,n);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,i)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),Cy=rn&&rn.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&Ay(e,t,n)};Object.defineProperty(rn,"__esModule",{value:!0});Cy(Fc(),rn)});var or=F(Q=>{"use strict";var Hc=Q&&Q.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(e,n);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,i)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),Sy=Q&&Q.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),Iy=Q&&Q.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(r[r.length]=i);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),i=0;i<r.length;i++)r[i]!=="default"&&Hc(n,e,r[i]);return Sy(n,e),n}})(),wy=Q&&Q.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&Hc(e,t,n)};Object.defineProperty(Q,"__esModule",{value:!0});Q.gcpResidencyCache=Q.METADATA_SERVER_DETECTION=Q.HEADERS=Q.HEADER_VALUE=Q.HEADER_NAME=Q.SECONDARY_HOST_ADDRESS=Q.HOST_ADDRESS=Q.BASE_PATH=void 0;Q.instance=Dy;Q.project=My;Q.universe=Uy;Q.bulk=by;Q.isAvailable=Ly;Q.resetIsAvailableCache=Oy;Q.getGCPResidency=zo;Q.setGCPResidency=Vc;Q.requestTimeout=$c;var Ko=ke(),Py=Nc(),Ry=Bo(),Ny=Iy(Xo());Q.BASE_PATH="/computeMetadata/v1";Q.HOST_ADDRESS="http://169.254.169.254";Q.SECONDARY_HOST_ADDRESS="http://metadata.google.internal.";Q.HEADER_NAME="Metadata-Flavor";Q.HEADER_VALUE="Google";Q.HEADERS=Object.freeze({[Q.HEADER_NAME]:Q.HEADER_VALUE});var Bc=Ny.log("gcp-metadata");Q.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 Yo(t){return t||(t=process.env.GCE_METADATA_IP||process.env.GCE_METADATA_HOST||Q.HOST_ADDRESS),/^https?:\/\//.test(t)||(t=`http://${t}`),new URL(Q.BASE_PATH,t).href}function xy(t){Object.keys(t).forEach(e=>{switch(e){case"params":case"property":case"headers":break;case"qs":throw new Error("'qs' is not a valid configuration option. Please use 'params' instead.");default:throw new Error(`'${e}' is not a valid configuration option.`)}})}async function ir(t,e={},n=3,r=!1){let i=new Headers(Q.HEADERS),o="",a={};if(typeof t=="object"){let p=t;new Headers(p.headers).forEach((h,m)=>i.set(m,h)),o=p.metadataKey,a=p.params||a,n=p.noResponseRetries||n,r=p.fastFail||r}else o=t;typeof e=="string"?o+=`/${e}`:(xy(e),e.property&&(o+=`/${e.property}`),new Headers(e.headers).forEach((p,h)=>i.set(h,p)),a=e.params||a);let u=r?ky:Ko.request,c={url:`${Yo()}/${o}`,headers:i,retryConfig:{noResponseRetries:n},params:a,responseType:"text",timeout:$c()};Bc.info("instance request %j",c);let d=await u(c);Bc.info("instance metadata is %s",d.data);let f=d.headers.get(Q.HEADER_NAME);if(f!==Q.HEADER_VALUE)throw new RangeError(`Invalid response from metadata service: incorrect ${Q.HEADER_NAME} header. Expected '${Q.HEADER_VALUE}', got ${f?`'${f}'`:"no header"}`);if(typeof d.data=="string")try{return Py.parse(d.data)}catch{}return d.data}async function ky(t){let e={...t,url:t.url?.toString().replace(Yo(),Yo(Q.SECONDARY_HOST_ADDRESS))},n=(0,Ko.request)(t),r=(0,Ko.request)(e);return Promise.any([n,r])}function Dy(t){return ir("instance",t)}function My(t){return ir("project",t)}function Uy(t){return ir("universe",t)}async function by(t){let e={};return await Promise.all(t.map(n=>(async()=>{let r=await ir(n),i=n.metadataKey;e[i]=r})())),e}function Gy(){return process.env.DETECT_GCP_RETRIES?Number(process.env.DETECT_GCP_RETRIES):0}var Hr;async function Ly(){if(process.env.METADATA_SERVER_DETECTION){let t=process.env.METADATA_SERVER_DETECTION.trim().toLocaleLowerCase();if(!(t in Q.METADATA_SERVER_DETECTION))throw new RangeError(`Unknown \`METADATA_SERVER_DETECTION\` env variable. Got \`${t}\`, but it should be \`${Object.keys(Q.METADATA_SERVER_DETECTION).join("`, `")}\`, or unset`);switch(t){case"assume-present":return!0;case"none":return!1;case"bios-only":return zo();case"ping-only":}}try{return Hr===void 0&&(Hr=ir("instance",void 0,Gy(),!(process.env.GCE_METADATA_IP||process.env.GCE_METADATA_HOST))),await Hr,!0}catch(t){let e=t;if(process.env.DEBUG_AUTH&&console.info(e),e.type==="request-timeout"||e.response&&e.response.status===404)return!1;if(!(e.response&&e.response.status===404)&&(!e.code||!["EHOSTDOWN","EHOSTUNREACH","ENETUNREACH","ENOENT","ENOTFOUND","ECONNREFUSED"].includes(e.code.toString()))){let n="UNKNOWN";e.code&&(n=e.code.toString()),process.emitWarning(`received unexpected error = ${e.message} code = ${n}`,"MetadataLookupWarning")}return!1}}function Oy(){Hr=void 0}Q.gcpResidencyCache=null;function zo(){return Q.gcpResidencyCache===null&&Vc(),Q.gcpResidencyCache}function Vc(t=null){Q.gcpResidencyCache=t!==null?t:(0,Ry.detectGCPResidency)()}function $c(){return zo()?0:3e3}wy(Bo(),Q)});var Xc=F(Vr=>{"use strict";Vr.byteLength=Fy;Vr.toByteArray=Hy;Vr.fromByteArray=Jy;var mt=[],Ye=[],qy=typeof Uint8Array<"u"?Uint8Array:Array,Qo="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(on=0,Jc=Qo.length;on<Jc;++on)mt[on]=Qo[on],Ye[Qo.charCodeAt(on)]=on;var on,Jc;Ye[45]=62;Ye[95]=63;function Wc(t){var e=t.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var n=t.indexOf("=");n===-1&&(n=e);var r=n===e?0:4-n%4;return[n,r]}function Fy(t){var e=Wc(t),n=e[0],r=e[1];return(n+r)*3/4-r}function By(t,e,n){return(e+n)*3/4-n}function Hy(t){var e,n=Wc(t),r=n[0],i=n[1],o=new qy(By(t,r,i)),a=0,u=i>0?r-4:r,c;for(c=0;c<u;c+=4)e=Ye[t.charCodeAt(c)]<<18|Ye[t.charCodeAt(c+1)]<<12|Ye[t.charCodeAt(c+2)]<<6|Ye[t.charCodeAt(c+3)],o[a++]=e>>16&255,o[a++]=e>>8&255,o[a++]=e&255;return i===2&&(e=Ye[t.charCodeAt(c)]<<2|Ye[t.charCodeAt(c+1)]>>4,o[a++]=e&255),i===1&&(e=Ye[t.charCodeAt(c)]<<10|Ye[t.charCodeAt(c+1)]<<4|Ye[t.charCodeAt(c+2)]>>2,o[a++]=e>>8&255,o[a++]=e&255),o}function Vy(t){return mt[t>>18&63]+mt[t>>12&63]+mt[t>>6&63]+mt[t&63]}function $y(t,e,n){for(var r,i=[],o=e;o<n;o+=3)r=(t[o]<<16&16711680)+(t[o+1]<<8&65280)+(t[o+2]&255),i.push(Vy(r));return i.join("")}function Jy(t){for(var e,n=t.length,r=n%3,i=[],o=16383,a=0,u=n-r;a<u;a+=o)i.push($y(t,a,a+o>u?u:a+o));return r===1?(e=t[n-1],i.push(mt[e>>2]+mt[e<<4&63]+"==")):r===2&&(e=(t[n-2]<<8)+t[n-1],i.push(mt[e>>10]+mt[e>>4&63]+mt[e<<2&63]+"=")),i.join("")}});var jo=F(Zo=>{"use strict";Object.defineProperty(Zo,"__esModule",{value:!0});Zo.fromArrayBufferToHex=Wy;function Wy(t){return Array.from(new Uint8Array(t)).map(n=>n.toString(16).padStart(2,"0")).join("")}});var Kc=F($r=>{"use strict";Object.defineProperty($r,"__esModule",{value:!0});$r.BrowserCrypto=void 0;var yn=Xc(),Xy=jo(),es=class t{constructor(){if(typeof window>"u"||window.crypto===void 0||window.crypto.subtle===void 0)throw new Error("SubtleCrypto not found. Make sure it's an https:// website.")}async sha256DigestBase64(e){let n=new TextEncoder().encode(e),r=await window.crypto.subtle.digest("SHA-256",n);return yn.fromByteArray(new Uint8Array(r))}randomBytesBase64(e){let n=new Uint8Array(e);return window.crypto.getRandomValues(n),yn.fromByteArray(n)}static padBase64(e){for(;e.length%4!==0;)e+="=";return e}async verify(e,n,r){let i={name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},o=new TextEncoder().encode(n),a=yn.toByteArray(t.padBase64(r)),u=await window.crypto.subtle.importKey("jwk",e,i,!0,["verify"]);return await window.crypto.subtle.verify(i,u,Buffer.from(a),o)}async sign(e,n){let r={name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},i=new TextEncoder().encode(n),o=await window.crypto.subtle.importKey("jwk",e,r,!0,["sign"]),a=await window.crypto.subtle.sign(r,o,i);return yn.fromByteArray(new Uint8Array(a))}decodeBase64StringUtf8(e){let n=yn.toByteArray(t.padBase64(e));return new TextDecoder().decode(n)}encodeBase64StringUtf8(e){let n=new TextEncoder().encode(e);return yn.fromByteArray(n)}async sha256DigestHex(e){let n=new TextEncoder().encode(e),r=await window.crypto.subtle.digest("SHA-256",n);return(0,Xy.fromArrayBufferToHex)(r)}async signWithHmacSha256(e,n){let r=typeof e=="string"?e:String.fromCharCode(...new Uint16Array(e)),i=new TextEncoder,o=await window.crypto.subtle.importKey("raw",i.encode(r),{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return window.crypto.subtle.sign("HMAC",o,i.encode(n))}};$r.BrowserCrypto=es});var Yc=F(Jr=>{"use strict";Object.defineProperty(Jr,"__esModule",{value:!0});Jr.NodeCrypto=void 0;var En=W("crypto"),ts=class{async sha256DigestBase64(e){return En.createHash("sha256").update(e).digest("base64")}randomBytesBase64(e){return En.randomBytes(e).toString("base64")}async verify(e,n,r){let i=En.createVerify("RSA-SHA256");return i.update(n),i.end(),i.verify(e,r,"base64")}async sign(e,n){let r=En.createSign("RSA-SHA256");return r.update(n),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 En.createHash("sha256").update(e).digest("hex")}async signWithHmacSha256(e,n){let r=typeof e=="string"?e:Yy(e);return Ky(En.createHmac("sha256",r).update(n).digest())}};Jr.NodeCrypto=ts;function Ky(t){let e=new ArrayBuffer(t.length),n=new Uint8Array(e);for(let r=0;r<t.length;++r)n[r]=t[r];return e}function Yy(t){return Buffer.from(t)}});var sr=F(It=>{"use strict";var zy=It&&It.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(e,n);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,i)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),Qy=It&&It.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&zy(e,t,n)};Object.defineProperty(It,"__esModule",{value:!0});It.createCrypto=eE;It.hasBrowserCrypto=zc;var Zy=Kc(),jy=Yc();Qy(jo(),It);function eE(){return zc()?new Zy.BrowserCrypto:new jy.NodeCrypto}function zc(){return typeof window<"u"&&typeof window.crypto<"u"&&typeof window.crypto.subtle<"u"}});var vn=F((ns,Zc)=>{var Wr=W("buffer"),gt=Wr.Buffer;function Qc(t,e){for(var n in t)e[n]=t[n]}gt.from&&gt.alloc&&gt.allocUnsafe&&gt.allocUnsafeSlow?Zc.exports=Wr:(Qc(Wr,ns),ns.Buffer=sn);function sn(t,e,n){return gt(t,e,n)}sn.prototype=Object.create(gt.prototype);Qc(gt,sn);sn.from=function(t,e,n){if(typeof t=="number")throw new TypeError("Argument must not be a number");return gt(t,e,n)};sn.alloc=function(t,e,n){if(typeof t!="number")throw new TypeError("Argument must be a number");var r=gt(t);return e!==void 0?typeof n=="string"?r.fill(e,n):r.fill(e):r.fill(0),r};sn.allocUnsafe=function(t){if(typeof t!="number")throw new TypeError("Argument must be a number");return gt(t)};sn.allocUnsafeSlow=function(t){if(typeof t!="number")throw new TypeError("Argument must be a number");return Wr.SlowBuffer(t)}});var ed=F((Gk,jc)=>{"use strict";function rs(t){var e=(t/8|0)+(t%8===0?0:1);return e}var tE={ES256:rs(256),ES384:rs(384),ES512:rs(521)};function nE(t){var e=tE[t];if(e)return e;throw new Error('Unknown algorithm "'+t+'"')}jc.exports=nE});var is=F((Lk,sd)=>{"use strict";var Xr=vn().Buffer,nd=ed(),Kr=128,rd=0,rE=32,iE=16,oE=2,id=iE|rE|rd<<6,Yr=oE|rd<<6;function sE(t){return t.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function od(t){if(Xr.isBuffer(t))return t;if(typeof t=="string")return Xr.from(t,"base64");throw new TypeError("ECDSA signature must be a Base64 string or a Buffer")}function aE(t,e){t=od(t);var n=nd(e),r=n+1,i=t.length,o=0;if(t[o++]!==id)throw new Error('Could not find expected "seq"');var a=t[o++];if(a===(Kr|1)&&(a=t[o++]),i-o<a)throw new Error('"seq" specified length of "'+a+'", only "'+(i-o)+'" remaining');if(t[o++]!==Yr)throw new Error('Could not find expected "int" for "r"');var u=t[o++];if(i-o-2<u)throw new Error('"r" specified length of "'+u+'", only "'+(i-o-2)+'" available');if(r<u)throw new Error('"r" specified length of "'+u+'", max of "'+r+'" is acceptable');var c=o;if(o+=u,t[o++]!==Yr)throw new Error('Could not find expected "int" for "s"');var d=t[o++];if(i-o!==d)throw new Error('"s" specified length of "'+d+'", expected "'+(i-o)+'"');if(r<d)throw new Error('"s" specified length of "'+d+'", max of "'+r+'" is acceptable');var f=o;if(o+=d,o!==i)throw new Error('Expected to consume entire buffer, but "'+(i-o)+'" bytes remain');var p=n-u,h=n-d,m=Xr.allocUnsafe(p+u+h+d);for(o=0;o<p;++o)m[o]=0;t.copy(m,o,c+Math.max(-p,0),c+u),o=n;for(var _=o;o<_+h;++o)m[o]=0;return t.copy(m,o,f+Math.max(-h,0),f+d),m=m.toString("base64"),m=sE(m),m}function td(t,e,n){for(var r=0;e+r<n&&t[e+r]===0;)++r;var i=t[e+r]>=Kr;return i&&--r,r}function lE(t,e){t=od(t);var n=nd(e),r=t.length;if(r!==n*2)throw new TypeError('"'+e+'" signatures must be "'+n*2+'" bytes, saw "'+r+'"');var i=td(t,0,n),o=td(t,n,t.length),a=n-i,u=n-o,c=2+a+1+1+u,d=c<Kr,f=Xr.allocUnsafe((d?2:3)+c),p=0;return f[p++]=id,d?f[p++]=c:(f[p++]=Kr|1,f[p++]=c&255),f[p++]=Yr,f[p++]=a,i<0?(f[p++]=0,p+=t.copy(f,p,0,n)):p+=t.copy(f,p,i,n),f[p++]=Yr,f[p++]=u,o<0?(f[p++]=0,t.copy(f,p,n)):t.copy(f,p,n+o),f}sd.exports={derToJose:aE,joseToDer:lE}});var st=F(wt=>{"use strict";Object.defineProperty(wt,"__esModule",{value:!0});wt.LRUCache=void 0;wt.snakeToCamel=ld;wt.originalOrCamelOptions=fE;wt.removeUndefinedValuesInObject=pE;wt.isValidFile=hE;wt.getWellKnownCertificateConfigFileLocation=mE;var uE=W("fs"),cE=W("os"),os=W("path"),dE="certificate_config.json",ad="gcloud";function ld(t){return t.replace(/([_][^_])/g,e=>e.slice(1).toUpperCase())}function fE(t){function e(n){let r=t||{};return r[n]??r[ld(n)]}return{get:e}}var ss=class{capacity;#e=new Map;maxAge;constructor(e){this.capacity=e.capacity,this.maxAge=e.maxAge}#t(e,n){this.#e.delete(e),this.#e.set(e,{value:n,lastAccessed:Date.now()})}set(e,n){this.#t(e,n),this.#n()}get(e){let n=this.#e.get(e);if(n)return this.#t(e,n.value),this.#n(),n.value}#n(){let e=this.maxAge?Date.now()-this.maxAge:0,n=this.#e.entries().next();for(;!n.done&&(this.#e.size>this.capacity||n.value[1].lastAccessed<e);)this.#e.delete(n.value[0]),n=this.#e.entries().next()}};wt.LRUCache=ss;function pE(t){return Object.entries(t).forEach(([e,n])=>{(n===void 0||n==="undefined")&&delete t[e]}),t}async function hE(t){try{return(await uE.promises.lstat(t)).isFile()}catch{return!1}}function mE(){let t=process.env.CLOUDSDK_CONFIG||(gE()?os.join(process.env.APPDATA||"",ad):os.join(process.env.HOME||"",".config",ad));return os.join(t,dE)}function gE(){return cE.platform().startsWith("win")}});var ud=F((qk,_E)=>{_E.exports={name:"google-auth-library",version:"10.9.1",author:"Google Inc.",description:"Google APIs Authentication Client Library for Node.js",engines:{node:">=18"},main:"./build/src/index.js",types:"./build/src/index.d.ts",repository:{type:"git",directory:"core/packages/google-auth-library-nodejs",url:"https://github.com/googleapis/google-cloud-node.git"},keywords:["google","api","google apis","client","client library"],dependencies:{"base64-js":"^1.3.0","ecdsa-sig-formatter":"^1.0.11",gaxios:"^7.1.4","gcp-metadata":"8.1.2","google-logging-utils":"1.1.3",jws:"^4.0.0"},devDependencies:{"@types/base64-js":"^1.2.5","@types/jws":"^3.1.0","@types/mocha":"^10.0.10","@types/mv":"^2.1.0","@types/ncp":"^2.0.8","@types/node":"^24.0.0","@types/sinon":"^21.0.0","assert-rejects":"^1.0.0",c8:"^10.1.3",codecov:"^3.8.3",gts:"^6.0.2","is-docker":"^3.0.0",jsdoc:"^4.0.4","jsdoc-fresh":"^5.0.0","jsdoc-region-tag":"^4.0.0",karma:"^6.0.0","karma-chrome-launcher":"^3.0.0","karma-coverage":"^2.0.0","karma-firefox-launcher":"^2.0.0","karma-mocha":"^2.0.0","karma-sourcemap-loader":"^0.4.0","karma-webpack":"^5.0.1",keypair:"^1.0.4",mocha:"^11.1.0",mv:"^2.1.1",ncp:"^2.0.0",nock:"^14.0.5","null-loader":"^4.0.1",puppeteer:"^24.0.0",sinon:"21.0.3","ts-loader":"^9.5.2",typescript:"5.8.3",webpack:"^5.97.1","webpack-cli":"^6.0.1"},files:["build/src","!build/src/**/*.map"],scripts:{test:"c8 mocha build/test",clean:"gts clean",prepare:"npm run compile",lint:"gts check --no-inline-config",compile:"tsc -p .",fix:"gts fix",pretest:"npm run compile -- --sourceMap",docs:"jsdoc -c .jsdoc.js","samples-setup":"cd samples/ && npm link ../ && npm run setup && cd ../","samples-test":"cd samples/ && npm link ../ && npm test && cd ../","system-test":"mocha build/system-test --timeout 60000","presystem-test":"npm run compile -- --sourceMap",webpack:"webpack","browser-test":"karma start",prelint:"cd samples; npm link ../; npm install"},license:"Apache-2.0",homepage:"https://github.com/googleapis/google-cloud-node/tree/main/core/packages/google-auth-library-nodejs"}});var as=F(Lt=>{"use strict";Object.defineProperty(Lt,"__esModule",{value:!0});Lt.USER_AGENT=Lt.PRODUCT_NAME=Lt.pkg=void 0;var cd=ud();Lt.pkg=cd;var dd="google-api-nodejs-client";Lt.PRODUCT_NAME=dd;var yE=`${dd}/${cd.version}`;Lt.USER_AGENT=yE});var He=F(at=>{"use strict";Object.defineProperty(at,"__esModule",{value:!0});at.AuthClient=at.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS=at.DEFAULT_UNIVERSE=void 0;var EE=W("events"),ls=ke(),vE=st(),TE=Xo(),us=as();at.DEFAULT_UNIVERSE="googleapis.com";at.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS=300*1e3;var cs=class t extends EE.EventEmitter{apiKey;projectId;quotaProjectId;transporter;credentials={};eagerRefreshThresholdMillis=at.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS;forceRefreshOnFailure=!1;universeDomain=at.DEFAULT_UNIVERSE;static RequestMethodNameSymbol=Symbol("request method name");static RequestLogIdSymbol=Symbol("request log id");constructor(e={}){super();let n=(0,vE.originalOrCamelOptions)(e);this.apiKey=e.apiKey,this.projectId=n.get("project_id")??null,this.quotaProjectId=n.get("quota_project_id"),this.credentials=n.get("credentials")??{},this.universeDomain=n.get("universe_domain")??at.DEFAULT_UNIVERSE,this.transporter=e.transporter??new ls.Gaxios(e.transporterOptions),n.get("useAuthRequestParameters")!==!1&&(this.transporter.interceptors.request.add(t.DEFAULT_REQUEST_INTERCEPTOR),this.transporter.interceptors.response.add(t.DEFAULT_RESPONSE_INTERCEPTOR)),e.eagerRefreshThresholdMillis&&(this.eagerRefreshThresholdMillis=e.eagerRefreshThresholdMillis),this.forceRefreshOnFailure=e.forceRefreshOnFailure??!1}fetch(...e){let n=e[0],r=e[1],i,o=new Headers;return typeof n=="string"?i=new URL(n):n instanceof URL?i=n:n&&n.url&&(i=new URL(n.url)),n&&typeof n=="object"&&"headers"in n&&ls.Gaxios.mergeHeaders(o,n.headers),r&&ls.Gaxios.mergeHeaders(o,new Headers(r.headers)),typeof n=="object"&&!(n instanceof URL)?this.request({...r,...n,headers:o,url:i}):this.request({...r,headers:o,url:i})}setCredentials(e){this.credentials=e}addSharedMetadataHeaders(e){return!e.has("x-goog-user-project")&&this.quotaProjectId&&e.set("x-goog-user-project",this.quotaProjectId),e}addUserProjectAndAuthHeaders(e,n){let r=n.get("x-goog-user-project"),i=n.get("authorization");return r&&e.set("x-goog-user-project",r),i&&e.set("authorization",i),e}static log=(0,TE.log)("auth");static DEFAULT_REQUEST_INTERCEPTOR={resolved:async e=>{if(!e.headers.has("x-goog-api-client")){let r=process.version.replace(/^v/,"");e.headers.set("x-goog-api-client",`gl-node/${r}`)}let n=e.headers.get("User-Agent");n?n.includes(`${us.PRODUCT_NAME}/`)||e.headers.set("User-Agent",`${n} ${us.USER_AGENT}`):e.headers.set("User-Agent",us.USER_AGENT);try{let r=e,i=r[t.RequestMethodNameSymbol],o=`${Math.floor(Math.random()*1e3)}`;r[t.RequestLogIdSymbol]=o;let a={url:e.url,headers:e.headers};i?t.log.info("%s [%s] request %j",i,o,a):t.log.info("[%s] request %j",o,a)}catch{}return e}};static DEFAULT_RESPONSE_INTERCEPTOR={resolved:async e=>{try{let n=e.config,r=n[t.RequestMethodNameSymbol],i=n[t.RequestLogIdSymbol];r?t.log.info("%s [%s] response %j",r,i,e.data):t.log.info("[%s] response %j",i,e.data)}catch{}return e},rejected:async e=>{try{let n=e.config,r=n[t.RequestMethodNameSymbol],i=n[t.RequestLogIdSymbol];r?t.log.info("%s [%s] error %j",r,i,e.response?.data):t.log.error("[%s] error %j",i,e.response?.data)}catch{}throw e}};static setMethodName(e,n){try{let r=e;r[t.RequestMethodNameSymbol]=n}catch{}}static get RETRY_CONFIG(){return{retry:!0,retryConfig:{httpMethodsToRetry:["GET","PUT","POST","HEAD","OPTIONS","DELETE"]}}}};at.AuthClient=cs});var fs=F(zr=>{"use strict";Object.defineProperty(zr,"__esModule",{value:!0});zr.LoginTicket=void 0;var ds=class{envelope;payload;constructor(e,n){this.envelope=e,this.payload=n}getEnvelope(){return this.envelope}getPayload(){return this.payload}getUserId(){let e=this.getPayload();return e&&e.sub?e.sub:null}getAttributes(){return{envelope:this.getEnvelope(),payload:this.getPayload()}}};zr.LoginTicket=ds});var Ot=F(_t=>{"use strict";Object.defineProperty(_t,"__esModule",{value:!0});_t.OAuth2Client=_t.ClientAuthentication=_t.CertificateFormat=_t.CodeChallengeMethod=void 0;var fd=ke(),AE=W("querystring"),CE=W("stream"),SE=is(),pd=st(),ps=sr(),Tn=He(),IE=fs(),hd;(function(t){t.Plain="plain",t.S256="S256"})(hd||(_t.CodeChallengeMethod=hd={}));var Pt;(function(t){t.PEM="PEM",t.JWK="JWK"})(Pt||(_t.CertificateFormat=Pt={}));var ar;(function(t){t.ClientSecretPost="ClientSecretPost",t.ClientSecretBasic="ClientSecretBasic",t.None="None"})(ar||(_t.ClientAuthentication=ar={}));var hs=class t extends Tn.AuthClient{redirectUri;certificateCache={};certificateExpiry=null;certificateCacheFormat=Pt.PEM;refreshTokenPromises=new Map;endpoints;issuers;clientAuthentication;_clientId;_clientSecret;refreshHandler;constructor(e={},n,r){super(typeof e=="object"?e:{}),typeof e!="object"&&(e={clientId:e,clientSecret:n,redirectUri:r}),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||ar.ClientSecretPost,this.issuers=e.issuers||["accounts.google.com","https://accounts.google.com",this.universeDomain]}static GOOGLE_TOKEN_INFO_URL="https://oauth2.googleapis.com/tokeninfo";static CLOCK_SKEW_SECS_=300;static DEFAULT_MAX_TOKEN_LIFETIME_SECS_=86400;generateAuthUrl(e={}){if(e.code_challenge_method&&!e.code_challenge)throw new Error("If a code_challenge_method is provided, code_challenge must be included.");return e.response_type=e.response_type||"code",e.client_id=e.client_id||this._clientId,e.redirect_uri=e.redirect_uri||this.redirectUri,Array.isArray(e.scope)&&(e.scope=e.scope.join(" ")),this.endpoints.oauth2AuthBaseUrl.toString()+"?"+AE.stringify(e)}generateCodeVerifier(){throw new Error("generateCodeVerifier is removed, please use generateCodeVerifierAsync instead.")}async generateCodeVerifierAsync(){let e=(0,ps.createCrypto)(),r=e.randomBytesBase64(96).replace(/\+/g,"~").replace(/=/g,"_").replace(/\//g,"-"),o=(await e.sha256DigestBase64(r)).split("=")[0].replace(/\+/g,"-").replace(/\//g,"_");return{codeVerifier:r,codeChallenge:o}}getToken(e,n){let r=typeof e=="string"?{code:e}:e;if(n)this.getTokenAsync(r).then(i=>n(null,i.tokens,i.res),i=>n(i,null,i.response));else return this.getTokenAsync(r)}async getTokenAsync(e){let n=this.endpoints.oauth2TokenUrl.toString(),r=new Headers,i={client_id:e.client_id||this._clientId,code_verifier:e.codeVerifier,code:e.code,grant_type:"authorization_code",redirect_uri:e.redirect_uri||this.redirectUri};if(this.clientAuthentication===ar.ClientSecretBasic){let c=Buffer.from(`${this._clientId}:${this._clientSecret}`);r.set("authorization",`Basic ${c.toString("base64")}`)}this.clientAuthentication===ar.ClientSecretPost&&(i.client_secret=this._clientSecret);let o={...t.RETRY_CONFIG,method:"POST",url:n,data:new URLSearchParams((0,pd.removeUndefinedValuesInObject)(i)),headers:r};Tn.AuthClient.setMethodName(o,"getTokenAsync");let a=await this.transporter.request(o),u=a.data;return a.data&&a.data.expires_in&&(u.expiry_date=new Date().getTime()+a.data.expires_in*1e3,delete u.expires_in),this.emit("tokens",u),{tokens:u,res:a}}async refreshToken(e){if(!e)return this.refreshTokenNoCache(e);if(this.refreshTokenPromises.has(e))return this.refreshTokenPromises.get(e);let n=this.refreshTokenNoCache(e).then(r=>(this.refreshTokenPromises.delete(e),r),r=>{throw this.refreshTokenPromises.delete(e),r});return this.refreshTokenPromises.set(e,n),n}async refreshTokenNoCache(e){if(!e)throw new Error("No refresh token is set.");let n=this.endpoints.oauth2TokenUrl.toString(),r={refresh_token:e,client_id:this._clientId,client_secret:this._clientSecret,grant_type:"refresh_token"},i;try{let a={...t.RETRY_CONFIG,method:"POST",url:n,data:new URLSearchParams((0,pd.removeUndefinedValuesInObject)(r))};Tn.AuthClient.setMethodName(a,"refreshTokenNoCache"),i=await this.transporter.request(a)}catch(a){throw a instanceof fd.GaxiosError&&a.message==="invalid_grant"&&a.response?.data&&/ReAuth/i.test(a.response.data.error_description)&&(a.message=JSON.stringify(a.response.data)),a}let o=i.data;return i.data&&i.data.expires_in&&(o.expiry_date=new Date().getTime()+i.data.expires_in*1e3,delete o.expires_in),this.emit("tokens",o),{tokens:o,res:i}}refreshAccessToken(e){if(e)this.refreshAccessTokenAsync().then(n=>e(null,n.credentials,n.res),e);else return this.refreshAccessTokenAsync()}async refreshAccessTokenAsync(){let e=await this.refreshToken(this.credentials.refresh_token),n=e.tokens;return n.refresh_token=this.credentials.refresh_token,this.credentials=n,{credentials:this.credentials,res:e.res}}getAccessToken(e){if(e)this.getAccessTokenAsync().then(n=>e(null,n.token,n.res),e);else return this.getAccessTokenAsync()}async getAccessTokenAsync(){if(!this.credentials.access_token||this.isTokenExpiring()){if(!this.credentials.refresh_token)if(this.refreshHandler){let r=await this.processAndValidateRefreshHandler();if(r?.access_token)return this.setCredentials(r),{token:this.credentials.access_token}}else throw new Error("No refresh token or refresh handler callback is set.");let n=await this.refreshAccessTokenAsync();if(!n.credentials||n.credentials&&!n.credentials.access_token)throw new Error("Could not refresh access token.");return{token:n.credentials.access_token,res:n.res}}else return{token:this.credentials.access_token}}async getRequestHeaders(e){return(await this.getRequestMetadataAsync(e)).headers}async getRequestMetadataAsync(e){let n=this.credentials;if(!n.access_token&&!n.refresh_token&&!this.apiKey&&!this.refreshHandler)throw new Error("No access, refresh token, API key or refresh handler callback is set.");if(n.access_token&&!this.isTokenExpiring()){n.token_type=n.token_type||"Bearer";let u=new Headers({authorization:n.token_type+" "+n.access_token});return{headers:this.addSharedMetadataHeaders(u)}}if(this.refreshHandler){let u=await this.processAndValidateRefreshHandler();if(u?.access_token){this.setCredentials(u);let c=new Headers({authorization:"Bearer "+this.credentials.access_token});return{headers:this.addSharedMetadataHeaders(c)}}}if(this.apiKey)return{headers:new Headers({"X-Goog-Api-Key":this.apiKey})};let r=null,i=null;try{r=await this.refreshToken(n.refresh_token),i=r.tokens}catch(u){let c=u;throw c.response&&(c.response.status===403||c.response.status===404)&&(c.message=`Could not refresh access token: ${c.message}`),c}let o=this.credentials;o.token_type=o.token_type||"Bearer",i.refresh_token=o.refresh_token,this.credentials=i;let a=new Headers({authorization:o.token_type+" "+i.access_token});return{headers:this.addSharedMetadataHeaders(a),res:r.res}}static getRevokeTokenUrl(e){return new t().getRevokeTokenURL(e).toString()}getRevokeTokenURL(e){let n=new URL(this.endpoints.oauth2RevokeUrl);return n.searchParams.append("token",e),n}revokeToken(e,n){let r={...t.RETRY_CONFIG,url:this.getRevokeTokenURL(e).toString(),method:"POST"};if(Tn.AuthClient.setMethodName(r,"revokeToken"),n)this.transporter.request(r).then(i=>n(null,i),n);else return this.transporter.request(r)}revokeCredentials(e){if(e)this.revokeCredentialsAsync().then(n=>e(null,n),e);else return this.revokeCredentialsAsync()}async revokeCredentialsAsync(){let e=this.credentials.access_token;if(this.credentials={},e)return this.revokeToken(e);throw new Error("No access token to revoke.")}request(e,n){if(n)this.requestAsync(e).then(r=>n(null,r),r=>n(r,r.response));else return this.requestAsync(e)}async requestAsync(e,n=!1){try{let r=await this.getRequestMetadataAsync();return e.headers=fd.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,r.headers),this.apiKey&&e.headers.set("X-Goog-Api-Key",this.apiKey),await this.transporter.request(e)}catch(r){let i=r.response;if(i){let o=i.status,a=this.credentials&&this.credentials.access_token&&this.credentials.refresh_token&&(!this.credentials.expiry_date||this.forceRefreshOnFailure),u=this.credentials&&this.credentials.access_token&&!this.credentials.refresh_token&&(!this.credentials.expiry_date||this.forceRefreshOnFailure)&&this.refreshHandler,c=i.config.data instanceof CE.Readable,d=o===401||o===403;if(!n&&d&&!c&&a)return await this.refreshAccessTokenAsync(),this.requestAsync(e,!0);if(!n&&d&&!c&&u){let f=await this.processAndValidateRefreshHandler();return f?.access_token&&this.setCredentials(f),this.requestAsync(e,!0)}}throw r}}verifyIdToken(e,n){if(n&&typeof n!="function")throw new Error("This method accepts an options object as the first parameter, which includes the idToken, audience, and maxExpiry.");if(n)this.verifyIdTokenAsync(e).then(r=>n(null,r),n);else return this.verifyIdTokenAsync(e)}async verifyIdTokenAsync(e){if(!e.idToken)throw new Error("The verifyIdToken method requires an ID Token");let n=await this.getFederatedSignonCertsAsync();return await this.verifySignedJwtWithCertsAsync(e.idToken,n.certs,e.audience,this.issuers,e.maxExpiry)}async getTokenInfo(e){let{data:n}=await this.transporter.request({...t.RETRY_CONFIG,method:"POST",headers:{"content-type":"application/x-www-form-urlencoded;charset=UTF-8",authorization:`Bearer ${e}`},url:this.endpoints.tokenInfoUrl.toString()}),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(n=>e(null,n.certs,n.res),e);else return this.getFederatedSignonCertsAsync()}async getFederatedSignonCertsAsync(){let e=new Date().getTime(),n=(0,ps.hasBrowserCrypto)()?Pt.JWK:Pt.PEM;if(this.certificateExpiry&&e<this.certificateExpiry.getTime()&&this.certificateCacheFormat===n)return{certs:this.certificateCache,format:n};let r,i;switch(n){case Pt.PEM:i=this.endpoints.oauth2FederatedSignonPemCertsUrl.toString();break;case Pt.JWK:i=this.endpoints.oauth2FederatedSignonJwkCertsUrl.toString();break;default:throw new Error(`Unsupported certificate format ${n}`)}try{let d={...t.RETRY_CONFIG,url:i};Tn.AuthClient.setMethodName(d,"getFederatedSignonCertsAsync"),r=await this.transporter.request(d)}catch(d){throw d instanceof Error&&(d.message=`Failed to retrieve verification certificates: ${d.message}`),d}let o=r?.headers.get("cache-control"),a=-1;if(o){let d=/max-age=(?<maxAge>[0-9]+)/.exec(o)?.groups?.maxAge;d&&(a=Number(d)*1e3)}let u={};switch(n){case Pt.PEM:u=r.data;break;case Pt.JWK:for(let d of r.data.keys)u[d.kid]=d;break;default:throw new Error(`Unsupported certificate format ${n}`)}let c=new Date;return this.certificateExpiry=a===-1?null:new Date(c.getTime()+a),this.certificateCache=u,this.certificateCacheFormat=n,{certs:u,format:n,res:r}}getIapPublicKeys(e){if(e)this.getIapPublicKeysAsync().then(n=>e(null,n.pubkeys,n.res),e);else return this.getIapPublicKeysAsync()}async getIapPublicKeysAsync(){let e,n=this.endpoints.oauth2IapPublicKeyUrl.toString();try{let r={...t.RETRY_CONFIG,url:n};Tn.AuthClient.setMethodName(r,"getIapPublicKeysAsync"),e=await this.transporter.request(r)}catch(r){throw r instanceof Error&&(r.message=`Failed to retrieve verification certificates: ${r.message}`),r}return{pubkeys:e.data,res:e}}verifySignedJwtWithCerts(){throw new Error("verifySignedJwtWithCerts is removed, please use verifySignedJwtWithCertsAsync instead.")}async verifySignedJwtWithCertsAsync(e,n,r,i,o){let a=(0,ps.createCrypto)();o||(o=t.DEFAULT_MAX_TOKEN_LIFETIME_SECS_);let u=e.split(".");if(u.length!==3)throw new Error("Wrong number of segments in token: "+e);let c=u[0]+"."+u[1],d=u[2],f,p;try{f=JSON.parse(a.decodeBase64StringUtf8(u[0]))}catch(A){throw A instanceof Error&&(A.message=`Can't parse token envelope: ${u[0]}': ${A.message}`),A}if(!f)throw new Error("Can't parse token envelope: "+u[0]);try{p=JSON.parse(a.decodeBase64StringUtf8(u[1]))}catch(A){throw A instanceof Error&&(A.message=`Can't parse token payload '${u[0]}`),A}if(!p)throw new Error("Can't parse token payload: "+u[1]);if(!Object.prototype.hasOwnProperty.call(n,f.kid))throw new Error("No pem found for envelope: "+JSON.stringify(f));let h=n[f.kid];if(f.alg==="ES256"&&(d=SE.joseToDer(d,"ES256").toString("base64")),!await a.verify(h,c,d))throw new Error("Invalid token signature: "+e);if(!p.iat)throw new Error("No issue time in token: "+JSON.stringify(p));if(!p.exp)throw new Error("No expiration time in token: "+JSON.stringify(p));let _=Number(p.iat);if(isNaN(_))throw new Error("iat field using invalid format");let g=Number(p.exp);if(isNaN(g))throw new Error("exp field using invalid format");let E=new Date().getTime()/1e3;if(g>=E+o)throw new Error("Expiration time too far in future: "+JSON.stringify(p));let y=_-t.CLOCK_SKEW_SECS_,C=g+t.CLOCK_SKEW_SECS_;if(E<y)throw new Error("Token used too early, "+E+" < "+y+": "+JSON.stringify(p));if(E>C)throw new Error("Token used too late, "+E+" > "+C+": "+JSON.stringify(p));if(i&&i.indexOf(p.iss)<0)throw new Error("Invalid issuer, expected one of ["+i+"], but got "+p.iss);if(typeof r<"u"&&r!==null){let A=p.aud,I=!1;if(r.constructor===Array?I=r.indexOf(A)>-1:I=A===r,!I)throw new Error("Wrong recipient, payload audience != requiredAudience")}return new IE.LoginTicket(f,p)}async processAndValidateRefreshHandler(){if(this.refreshHandler){let e=await this.refreshHandler();if(!e.access_token)throw new Error("No access token is returned by the refreshHandler callback.");return e}}isTokenExpiring(){let e=this.credentials.expiry_date;return e?e<=new Date().getTime()+this.eagerRefreshThresholdMillis:!1}};_t.OAuth2Client=hs});var gs=F(Qr=>{"use strict";Object.defineProperty(Qr,"__esModule",{value:!0});Qr.Compute=void 0;var wE=ke(),md=or(),PE=Ot(),ms=class extends PE.OAuth2Client{serviceAccountEmail;scopes;constructor(e={}){super(e),this.credentials={expiry_date:1,refresh_token:"compute-placeholder"},this.serviceAccountEmail=e.serviceAccountEmail||"default",this.scopes=Array.isArray(e.scopes)?e.scopes:e.scopes?[e.scopes]:[]}async refreshTokenNoCache(){let e=`service-accounts/${this.serviceAccountEmail}/token`,n;try{let i={property:e};this.scopes.length>0&&(i.params={scopes:this.scopes.join(",")}),n=await md.instance(i)}catch(i){throw i instanceof wE.GaxiosError&&(i.message=`Could not refresh access token: ${i.message}`,this.wrapError(i)),i}let r=n;return n&&n.expires_in&&(r.expiry_date=new Date().getTime()+n.expires_in*1e3,delete r.expires_in),this.emit("tokens",r),{tokens:r,res:null}}async fetchIdToken(e){let n=`service-accounts/${this.serviceAccountEmail}/identity?format=full&audience=${e}`,r;try{let i={property:n};r=await md.instance(i)}catch(i){throw i instanceof Error&&(i.message=`Could not fetch ID token: ${i.message}`),i}return r}wrapError(e){let n=e.response;n&&n.status&&(e.status=n.status,n.status===403?e.message="A Forbidden error was returned while attempting to retrieve an access token for the Compute Engine built-in service account. This may be because the Compute Engine instance does not have the correct permission scopes specified: "+e.message:n.status===404&&(e.message="A Not Found error was returned while attempting to retrieve an accesstoken for the Compute Engine built-in service account. This may be because the Compute Engine instance does not have any permission scopes specified: "+e.message))}};Qr.Compute=ms});var ys=F(Zr=>{"use strict";Object.defineProperty(Zr,"__esModule",{value:!0});Zr.IdTokenClient=void 0;var RE=Ot(),_s=class extends RE.OAuth2Client{targetAudience;idTokenProvider;constructor(e){super(e),this.targetAudience=e.targetAudience,this.idTokenProvider=e.idTokenProvider}async getRequestMetadataAsync(){if(!this.credentials.id_token||!this.credentials.expiry_date||this.isTokenExpiring()){let n=await this.idTokenProvider.fetchIdToken(this.targetAudience);this.credentials={id_token:n,expiry_date:this.getIdTokenExpiryDate(n)}}return{headers:new Headers({authorization:"Bearer "+this.credentials.id_token})}}getIdTokenExpiryDate(e){let n=e.split(".")[1];if(n)return JSON.parse(Buffer.from(n,"base64").toString("ascii")).exp*1e3}};Zr.IdTokenClient=_s});var Es=F(An=>{"use strict";Object.defineProperty(An,"__esModule",{value:!0});An.GCPEnv=void 0;An.clear=NE;An.getEnv=xE;var gd=or(),yt;(function(t){t.APP_ENGINE="APP_ENGINE",t.KUBERNETES_ENGINE="KUBERNETES_ENGINE",t.CLOUD_FUNCTIONS="CLOUD_FUNCTIONS",t.COMPUTE_ENGINE="COMPUTE_ENGINE",t.CLOUD_RUN="CLOUD_RUN",t.CLOUD_RUN_JOBS="CLOUD_RUN_JOBS",t.NONE="NONE"})(yt||(An.GCPEnv=yt={}));var lr;function NE(){lr=void 0}async function xE(){return lr||(lr=kE(),lr)}async function kE(){let t=yt.NONE;return DE()?t=yt.APP_ENGINE:ME()?t=yt.CLOUD_FUNCTIONS:await LE()?await GE()?t=yt.KUBERNETES_ENGINE:UE()?t=yt.CLOUD_RUN:bE()?t=yt.CLOUD_RUN_JOBS:t=yt.COMPUTE_ENGINE:t=yt.NONE,t}function DE(){return!!(process.env.GAE_SERVICE||process.env.GAE_MODULE_NAME)}function ME(){return!!(process.env.FUNCTION_NAME||process.env.FUNCTION_TARGET)}function UE(){return!!process.env.K_CONFIGURATION}function bE(){return!!process.env.CLOUD_RUN_JOB}async function GE(){try{return await gd.instance("attributes/cluster-name"),!0}catch{return!1}}async function LE(){return gd.isAvailable()}});var vs=F((Xk,_d)=>{var jr=vn().Buffer,OE=W("stream"),qE=W("util");function ei(t){if(this.buffer=null,this.writable=!0,this.readable=!0,!t)return this.buffer=jr.alloc(0),this;if(typeof t.pipe=="function")return this.buffer=jr.alloc(0),t.pipe(this),this;if(t.length||typeof t=="object")return this.buffer=t,this.writable=!1,process.nextTick(function(){this.emit("end",t),this.readable=!1,this.emit("close")}.bind(this)),this;throw new TypeError("Unexpected data type ("+typeof t+")")}qE.inherits(ei,OE);ei.prototype.write=function(e){this.buffer=jr.concat([this.buffer,jr.from(e)]),this.emit("data",e)};ei.prototype.end=function(e){e&&this.write(e),this.emit("end",e),this.emit("close"),this.writable=!1,this.readable=!1};_d.exports=ei});var Ed=F((Kk,yd)=>{"use strict";var ur=W("buffer").Buffer,Ts=W("buffer").SlowBuffer;yd.exports=ti;function ti(t,e){if(!ur.isBuffer(t)||!ur.isBuffer(e)||t.length!==e.length)return!1;for(var n=0,r=0;r<t.length;r++)n|=t[r]^e[r];return n===0}ti.install=function(){ur.prototype.equal=Ts.prototype.equal=function(e){return ti(this,e)}};var FE=ur.prototype.equal,BE=Ts.prototype.equal;ti.restore=function(){ur.prototype.equal=FE,Ts.prototype.equal=BE}});var Is=F((Yk,Rd)=>{var Sn=vn().Buffer,ze=W("crypto"),Td=is(),vd=W("util"),HE=`"%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".`,cr="secret must be a string or buffer",Cn="key must be a string or a buffer",VE="key must be a string, a buffer or an object",Cs=typeof ze.createPublicKey=="function";Cs&&(Cn+=" or a KeyObject",cr+="or a KeyObject");function Ad(t){if(!Sn.isBuffer(t)&&typeof t!="string"&&(!Cs||typeof t!="object"||typeof t.type!="string"||typeof t.asymmetricKeyType!="string"||typeof t.export!="function"))throw lt(Cn)}function Cd(t){if(!Sn.isBuffer(t)&&typeof t!="string"&&typeof t!="object")throw lt(VE)}function $E(t){if(!Sn.isBuffer(t)){if(typeof t=="string")return t;if(!Cs||typeof t!="object"||t.type!=="secret"||typeof t.export!="function")throw lt(cr)}}function Ss(t){return t.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function Sd(t){t=t.toString();var e=4-t.length%4;if(e!==4)for(var n=0;n<e;++n)t+="=";return t.replace(/\-/g,"+").replace(/_/g,"/")}function lt(t){var e=[].slice.call(arguments,1),n=vd.format.bind(vd,t).apply(null,e);return new TypeError(n)}function JE(t){return Sn.isBuffer(t)||typeof t=="string"}function dr(t){return JE(t)||(t=JSON.stringify(t)),t}function Id(t){return function(n,r){$E(r),n=dr(n);var i=ze.createHmac("sha"+t,r),o=(i.update(n),i.digest("base64"));return Ss(o)}}var As,WE="timingSafeEqual"in ze?function(e,n){return e.byteLength!==n.byteLength?!1:ze.timingSafeEqual(e,n)}:function(e,n){return As||(As=Ed()),As(e,n)};function XE(t){return function(n,r,i){var o=Id(t)(n,i);return WE(Sn.from(r),Sn.from(o))}}function wd(t){return function(n,r){Cd(r),n=dr(n);var i=ze.createSign("RSA-SHA"+t),o=(i.update(n),i.sign(r,"base64"));return Ss(o)}}function Pd(t){return function(n,r,i){Ad(i),n=dr(n),r=Sd(r);var o=ze.createVerify("RSA-SHA"+t);return o.update(n),o.verify(i,r,"base64")}}function KE(t){return function(n,r){Cd(r),n=dr(n);var i=ze.createSign("RSA-SHA"+t),o=(i.update(n),i.sign({key:r,padding:ze.constants.RSA_PKCS1_PSS_PADDING,saltLength:ze.constants.RSA_PSS_SALTLEN_DIGEST},"base64"));return Ss(o)}}function YE(t){return function(n,r,i){Ad(i),n=dr(n),r=Sd(r);var o=ze.createVerify("RSA-SHA"+t);return o.update(n),o.verify({key:i,padding:ze.constants.RSA_PKCS1_PSS_PADDING,saltLength:ze.constants.RSA_PSS_SALTLEN_DIGEST},r,"base64")}}function zE(t){var e=wd(t);return function(){var r=e.apply(null,arguments);return r=Td.derToJose(r,"ES"+t),r}}function QE(t){var e=Pd(t);return function(r,i,o){i=Td.joseToDer(i,"ES"+t).toString("base64");var a=e(r,i,o);return a}}function ZE(){return function(){return""}}function jE(){return function(e,n){return n===""}}Rd.exports=function(e){var n={hs:Id,rs:wd,ps:KE,es:zE,none:ZE},r={hs:XE,rs:Pd,ps:YE,es:QE,none:jE},i=e.match(/^(RS|PS|ES|HS)(256|384|512)$|^(none)$/);if(!i)throw lt(HE,e);var o=(i[1]||i[3]).toLowerCase(),a=i[2];return{sign:n[o](a),verify:r[o](a)}}});var ws=F((zk,Nd)=>{var ev=W("buffer").Buffer;Nd.exports=function(e){return typeof e=="string"?e:typeof e=="number"||ev.isBuffer(e)?e.toString():JSON.stringify(e)}});var bd=F((Qk,Ud)=>{var tv=vn().Buffer,xd=vs(),nv=Is(),rv=W("stream"),kd=ws(),Ps=W("util");function Dd(t,e){return tv.from(t,e).toString("base64").replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function iv(t,e,n){n=n||"utf8";var r=Dd(kd(t),"binary"),i=Dd(kd(e),n);return Ps.format("%s.%s",r,i)}function Md(t){var e=t.header,n=t.payload,r=t.secret||t.privateKey,i=t.encoding,o=nv(e.alg),a=iv(e,n,i),u=o.sign(a,r);return Ps.format("%s.%s",a,u)}function ni(t){var e=t.secret;if(e=e??t.privateKey,e=e??t.key,/^hs/i.test(t.header.alg)===!0&&e==null)throw new TypeError("secret must be a string or buffer or a KeyObject");var n=new xd(e);this.readable=!0,this.header=t.header,this.encoding=t.encoding,this.secret=this.privateKey=this.key=n,this.payload=new xd(t.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))}Ps.inherits(ni,rv);ni.prototype.sign=function(){try{var e=Md({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(n){this.readable=!1,this.emit("error",n),this.emit("close")}};ni.sign=Md;Ud.exports=ni});var Jd=F((Zk,$d)=>{var Ld=vn().Buffer,Gd=vs(),ov=Is(),sv=W("stream"),Od=ws(),av=W("util"),lv=/^[a-zA-Z0-9\-_]+?\.[a-zA-Z0-9\-_]+?\.([a-zA-Z0-9\-_]+)?$/;function uv(t){return Object.prototype.toString.call(t)==="[object Object]"}function cv(t){if(uv(t))return t;try{return JSON.parse(t)}catch{return}}function qd(t){var e=t.split(".",1)[0];return cv(Ld.from(e,"base64").toString("binary"))}function dv(t){return t.split(".",2).join(".")}function Fd(t){return t.split(".")[2]}function fv(t,e){e=e||"utf8";var n=t.split(".")[1];return Ld.from(n,"base64").toString(e)}function Bd(t){return lv.test(t)&&!!qd(t)}function Hd(t,e,n){if(!e){var r=new Error("Missing algorithm parameter for jws.verify");throw r.code="MISSING_ALGORITHM",r}t=Od(t);var i=Fd(t),o=dv(t),a=ov(e);return a.verify(o,i,n)}function Vd(t,e){if(e=e||{},t=Od(t),!Bd(t))return null;var n=qd(t);if(!n)return null;var r=fv(t);return(n.typ==="JWT"||e.json)&&(r=JSON.parse(r,e.encoding)),{header:n,payload:r,signature:Fd(t)}}function In(t){t=t||{};var e=t.secret;if(e=e??t.publicKey,e=e??t.key,/^hs/i.test(t.algorithm)===!0&&e==null)throw new TypeError("secret must be a string or buffer or a KeyObject");var n=new Gd(e);this.readable=!0,this.algorithm=t.algorithm,this.encoding=t.encoding,this.secret=this.publicKey=this.key=n,this.signature=new Gd(t.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))}av.inherits(In,sv);In.prototype.verify=function(){try{var e=Hd(this.signature.buffer,this.algorithm,this.key.buffer),n=Vd(this.signature.buffer,this.encoding);return this.emit("done",e,n),this.emit("data",e),this.emit("end"),this.readable=!1,e}catch(r){this.readable=!1,this.emit("error",r),this.emit("close")}};In.decode=Vd;In.isValid=Bd;In.verify=Hd;$d.exports=In});var Rs=F(qt=>{var Wd=bd(),ri=Jd(),pv=["HS256","HS384","HS512","RS256","RS384","RS512","PS256","PS384","PS512","ES256","ES384","ES512"];qt.ALGORITHMS=pv;qt.sign=Wd.sign;qt.verify=ri.verify;qt.decode=ri.decode;qt.isValid=ri.isValid;qt.createSign=function(e){return new Wd(e)};qt.createVerify=function(e){return new ri(e)}});var Kd=F(ii=>{"use strict";Object.defineProperty(ii,"__esModule",{value:!0});ii.buildPayloadForJwsSign=Xd;ii.getJwsSign=_v;var hv=Rs(),mv="RS256",gv="https://oauth2.googleapis.com/token";function Xd(t){let e=Math.floor(new Date().getTime()/1e3);return{iss:t.iss,scope:t.scope,aud:gv,exp:e+3600,iat:e,sub:t.sub,...t.additionalClaims}}function _v(t){let e=Xd(t);return(0,hv.sign)({header:{alg:mv},payload:e,secret:t.key})}});var Yd=F(Ns=>{"use strict";Object.defineProperty(Ns,"__esModule",{value:!0});Ns.getToken=Av;var yv=Kd(),Ev="https://oauth2.googleapis.com/token",vv="urn:ietf:params:oauth:grant-type:jwt-bearer",Tv=t=>({method:"POST",url:Ev,data:new URLSearchParams({grant_type:vv,assertion:(0,yv.getJwsSign)(t)}),responseType:"json",retryConfig:{httpMethodsToRetry:["POST"]}});async function Av(t){if(!t.transporter)throw new Error("No transporter set.");try{let e=Tv(t);return(await t.transporter.request(e)).data}catch(e){let n=e,r=n.response?.data;throw r?.error&&(n.message=`${r.error}: ${r.error_description}`),n}}});var zd=F(oi=>{"use strict";Object.defineProperty(oi,"__esModule",{value:!0});oi.ErrorWithCode=void 0;var xs=class extends Error{code;constructor(e,n){super(e),this.code=n}};oi.ErrorWithCode=xs});var Gs=F(bs=>{"use strict";Object.defineProperty(bs,"__esModule",{value:!0});bs.getCredentials=Iv;var Cv=W("path"),Qd=W("fs"),Sv=W("util"),si=zd(),Zd=Qd.readFile?(0,Sv.promisify)(Qd.readFile):async()=>{throw new si.ErrorWithCode("use key rather than keyFile.","MISSING_CREDENTIALS")},Ft;(function(t){t.JSON=".json",t.DER=".der",t.CRT=".crt",t.PEM=".pem",t.P12=".p12",t.PFX=".pfx"})(Ft||(Ft={}));var ks=class{keyFilePath;constructor(e){this.keyFilePath=e}async getCredentials(){let e=await Zd(this.keyFilePath,"utf8"),n;try{n=JSON.parse(e)}catch(o){let a=o;throw new Error(`Invalid JSON key file: ${a.message}`)}let r=n.private_key,i=n.client_email;if(!r||!i)throw new si.ErrorWithCode("private_key and client_email are required.","MISSING_CREDENTIALS");return{privateKey:r,clientEmail:i}}},Ds=class{keyFilePath;constructor(e){this.keyFilePath=e}async getCredentials(){return{privateKey:await Zd(this.keyFilePath,"utf8")}}},Ms=class{async getCredentials(){throw new si.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")}},Us=class{static create(e){switch(Cv.extname(e)){case Ft.JSON:return new ks(e);case Ft.DER:case Ft.CRT:case Ft.PEM:return new Ds(e);case Ft.P12:case Ft.PFX:return new Ms;default:throw new si.ErrorWithCode("Unknown certificate type. Type is determined based on file extension. Current supported extensions are *.json, and *.pem.","UNKNOWN_CERTIFICATE_TYPE")}}};async function Iv(t){return Us.create(t).getCredentials()}});var jd=F(ai=>{"use strict";Object.defineProperty(ai,"__esModule",{value:!0});ai.TokenHandler=void 0;var wv=Yd(),Pv=Gs(),Ls=class{token;tokenExpiresAt;inFlightRequest;tokenOptions;constructor(e){this.tokenOptions=e}async processCredentials(){if(!this.tokenOptions.key&&!this.tokenOptions.keyFile)throw new Error("No key or keyFile set.");if(!this.tokenOptions.key&&this.tokenOptions.keyFile){let e=await(0,Pv.getCredentials)(this.tokenOptions.keyFile);this.tokenOptions.key=e.privateKey,this.tokenOptions.email=e.clientEmail}}isTokenExpiring(){if(!this.token||!this.tokenExpiresAt)return!0;let e=new Date().getTime(),n=this.tokenOptions.eagerRefreshThresholdMillis??0;return this.tokenExpiresAt<=e+n}hasExpired(){let e=new Date().getTime();return this.token&&this.tokenExpiresAt?new Date().getTime()>=this.tokenExpiresAt:!0}async getToken(e){if(await this.processCredentials(),this.inFlightRequest&&!e)return this.inFlightRequest;if(this.token&&!this.isTokenExpiring()&&!e)return this.token;try{this.inFlightRequest=(0,wv.getToken)(this.tokenOptions);let n=await this.inFlightRequest;return this.token=n,this.tokenExpiresAt=new Date().getTime()+(n.expires_in??0)*1e3,n}finally{this.inFlightRequest=void 0}}};ai.TokenHandler=Ls});var ef=F(Os=>{"use strict";Object.defineProperty(Os,"__esModule",{value:!0});Os.revokeToken=xv;var Rv="https://oauth2.googleapis.com/revoke?token=",Nv=!0;async function xv(t,e){let n=Rv+t;return await e.request({url:n,retry:Nv})}});var Fs=F(li=>{"use strict";Object.defineProperty(li,"__esModule",{value:!0});li.GoogleToken=void 0;var kv=ke(),tf=jd(),Dv=ef(),qs=class{tokenOptions;tokenHandler;constructor(e){this.tokenOptions=e||{},this.tokenOptions.transporter=this.tokenOptions.transporter||{request:n=>(0,kv.request)(n)},this.tokenOptions.iss||(this.tokenOptions.iss=this.tokenOptions.email),typeof this.tokenOptions.scope=="object"&&(this.tokenOptions.scope=this.tokenOptions.scope.join(" ")),this.tokenHandler=new tf.TokenHandler(this.tokenOptions)}get expiresAt(){return this.tokenHandler.tokenExpiresAt}get accessToken(){return this.tokenHandler.token?.access_token}get idToken(){return this.tokenHandler.token?.id_token}get tokenType(){return this.tokenHandler.token?.token_type}get refreshToken(){return this.tokenHandler.token?.refresh_token}hasExpired(){return this.tokenHandler.hasExpired()}isTokenExpiring(){return this.tokenHandler.isTokenExpiring()}getToken(e,n={forceRefresh:!1}){let r;typeof e=="function"?r=e:typeof e=="object"&&(n=e);let i=this.tokenHandler.getToken(n.forceRefresh??!1);return r&&i.then(o=>r(null,o),r),i}revokeToken(e){if(!this.accessToken)return Promise.reject(new Error("No token to revoke."));let n=(0,Dv.revokeToken)(this.accessToken,this.tokenOptions.transporter);e&&n.then(()=>e(),e),this.tokenHandler=new tf.TokenHandler(this.tokenOptions)}get googleTokenOptions(){return this.tokenOptions}};li.GoogleToken=qs});var Hs=F(ui=>{"use strict";Object.defineProperty(ui,"__esModule",{value:!0});ui.JWTAccess=void 0;var Mv=Rs(),Uv=st(),nf={alg:"RS256",typ:"JWT"},Bs=class t{email;key;keyId;projectId;eagerRefreshThresholdMillis;cache=new Uv.LRUCache({capacity:500,maxAge:3600*1e3});constructor(e,n,r,i){this.email=e,this.key=n,this.keyId=r,this.eagerRefreshThresholdMillis=i??300*1e3}getCachedKey(e,n){let r=e;if(n&&Array.isArray(n)&&n.length?r=e?`${e}_${n.join("_")}`:`${n.join("_")}`:typeof n=="string"&&(r=e?`${e}_${n}`:n),!r)throw Error("Scopes or url must be provided");return r}getRequestHeaders(e,n,r){let i=this.getCachedKey(e,r),o=this.cache.get(i),a=Date.now();if(o&&o.expiration-a>this.eagerRefreshThresholdMillis)return new Headers(o.headers);let u=Math.floor(Date.now()/1e3),c=t.getExpirationTime(u),d;if(Array.isArray(r)&&(r=r.join(" ")),r?d={iss:this.email,sub:this.email,scope:r,exp:c,iat:u}:d={iss:this.email,sub:this.email,aud:e,exp:c,iat:u},n){for(let _ in d)if(n[_])throw new Error(`The '${_}' property is not allowed when passing additionalClaims. This claim is included in the JWT by default.`)}let f=this.keyId?{...nf,kid:this.keyId}:nf,p=Object.assign(d,n),h=Mv.sign({header:f,payload:p,secret:this.key}),m=new Headers({authorization:`Bearer ${h}`});return this.cache.set(i,{expiration:c*1e3,headers:m}),m}static getExpirationTime(e){return e+3600}fromJSON(e){if(!e)throw new Error("Must pass in a JSON object containing the service account auth settings.");if(!e.client_email)throw new Error("The incoming JSON object does not contain a client_email field");if(!e.private_key)throw new Error("The incoming JSON object does not contain a private_key field");this.email=e.client_email,this.key=e.private_key,this.keyId=e.private_key_id,this.projectId=e.project_id}fromStream(e,n){if(n)this.fromStreamAsync(e).then(()=>n(),n);else return this.fromStreamAsync(e)}fromStreamAsync(e){return new Promise((n,r)=>{e||r(new Error("Must pass in a stream containing the service account auth settings."));let i="";e.setEncoding("utf8").on("data",o=>i+=o).on("error",r).on("end",()=>{try{let o=JSON.parse(i);this.fromJSON(o),n()}catch(o){r(o)}})})}};ui.JWTAccess=Bs});var $s=F(di=>{"use strict";Object.defineProperty(di,"__esModule",{value:!0});di.JWT=void 0;var rf=Fs(),bv=Gs(),Gv=Hs(),Lv=Ot(),ci=He(),Vs=class t extends Lv.OAuth2Client{email;keyFile;key;keyId;defaultScopes;scopes;scope;subject;gtoken;additionalClaims;useJWTAccessWithScope;defaultServicePath;access;constructor(e={}){super(e),this.email=e.email,this.keyFile=e.keyFile,this.key=e.key,this.keyId=e.keyId,this.scopes=e.scopes,this.subject=e.subject,this.additionalClaims=e.additionalClaims,this.credentials={refresh_token:"jwt-placeholder",expiry_date:1}}createScoped(e){let n=new t(this);return n.scopes=e,n}async getRequestMetadataAsync(e){e=this.defaultServicePath?`https://${this.defaultServicePath}/`:e;let n=!this.hasUserScopes()&&e||this.useJWTAccessWithScope&&this.hasAnyScopes()||this.universeDomain!==ci.DEFAULT_UNIVERSE;if(this.subject&&this.universeDomain!==ci.DEFAULT_UNIVERSE)throw new RangeError(`Service Account user is configured for the credential. Domain-wide delegation is not supported in universes other than ${ci.DEFAULT_UNIVERSE}`);if(!this.apiKey&&n)if(this.additionalClaims&&this.additionalClaims.target_audience){let{tokens:r}=await this.refreshToken();return{headers:this.addSharedMetadataHeaders(new Headers({authorization:`Bearer ${r.id_token}`}))}}else{this.access||(this.access=new Gv.JWTAccess(this.email,this.key,this.keyId,this.eagerRefreshThresholdMillis));let r;this.hasUserScopes()?r=this.scopes:e||(r=this.defaultScopes);let i=this.useJWTAccessWithScope||this.universeDomain!==ci.DEFAULT_UNIVERSE,o=await this.access.getRequestHeaders(e??void 0,this.additionalClaims,i?r:void 0);return{headers:this.addSharedMetadataHeaders(o)}}else return this.hasAnyScopes()||this.apiKey?super.getRequestMetadataAsync(e):{headers:new Headers}}async fetchIdToken(e){let n=new rf.GoogleToken({iss:this.email,sub:this.subject,scope:this.scopes||this.defaultScopes,keyFile:this.keyFile,key:this.key,additionalClaims:{target_audience:e},transporter:this.transporter});if(await n.getToken({forceRefresh:!0}),!n.idToken)throw new Error("Unknown error: Failed to fetch ID token");return n.idToken}hasUserScopes(){return this.scopes?this.scopes.length>0:!1}hasAnyScopes(){return!!(this.scopes&&this.scopes.length>0||this.defaultScopes&&this.defaultScopes.length>0)}authorize(e){if(e)this.authorizeAsync().then(n=>e(null,n),e);else return this.authorizeAsync()}async authorizeAsync(){let e=await this.refreshToken();if(!e)throw new Error("No result returned");return this.credentials=e.tokens,this.credentials.refresh_token="jwt-placeholder",this.key=this.gtoken.googleTokenOptions?.key,this.email=this.gtoken.googleTokenOptions?.iss,e.tokens}async refreshTokenNoCache(){let e=this.createGToken(),r={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",r),{res:null,tokens:r}}createGToken(){return this.gtoken||(this.gtoken=new rf.GoogleToken({iss:this.email,sub:this.subject,scope:this.scopes||this.defaultScopes,keyFile:this.keyFile,key:this.key,additionalClaims:this.additionalClaims,transporter:this.transporter})),this.gtoken}fromJSON(e){if(!e)throw new Error("Must pass in a JSON object containing the service account auth settings.");if(!e.client_email)throw new Error("The incoming JSON object does not contain a client_email field");if(!e.private_key)throw new Error("The incoming JSON object does not contain a private_key field");this.email=e.client_email,this.key=e.private_key,this.keyId=e.private_key_id,this.projectId=e.project_id,this.quotaProjectId=e.quota_project_id,this.universeDomain=e.universe_domain||this.universeDomain}fromStream(e,n){if(n)this.fromStreamAsync(e).then(()=>n(),n);else return this.fromStreamAsync(e)}fromStreamAsync(e){return new Promise((n,r)=>{if(!e)throw new Error("Must pass in a stream containing the service account auth settings.");let i="";e.setEncoding("utf8").on("error",r).on("data",o=>i+=o).on("end",()=>{try{let o=JSON.parse(i);this.fromJSON(o),n()}catch(o){r(o)}})})}fromAPIKey(e){if(typeof e!="string")throw new Error("Must provide an API Key string.");this.apiKey=e}async getCredentials(){if(this.key)return{private_key:this.key,client_email:this.email};if(this.keyFile){let e=this.createGToken(),n=await(0,bv.getCredentials)(this.keyFile);return{private_key:n.privateKey,client_email:n.clientEmail}}throw new Error("A key or a keyFile must be provided to getCredentials.")}};di.JWT=Vs});var Ws=F(wn=>{"use strict";Object.defineProperty(wn,"__esModule",{value:!0});wn.UserRefreshClient=wn.USER_REFRESH_ACCOUNT_TYPE=void 0;var Ov=Ot(),qv=He();wn.USER_REFRESH_ACCOUNT_TYPE="authorized_user";var Js=class t extends Ov.OAuth2Client{_refreshToken;constructor(e,n,r,i,o){let a=e&&typeof e=="object"?e:{clientId:e,clientSecret:n,refreshToken:r,eagerRefreshThresholdMillis:i,forceRefreshOnFailure:o};super(a),this._refreshToken=a.refreshToken,this.credentials.refresh_token=a.refreshToken}async refreshTokenNoCache(){return super.refreshTokenNoCache(this._refreshToken)}async fetchIdToken(e){let n={...t.RETRY_CONFIG,url:this.endpoints.oauth2TokenUrl,method:"POST",data:new URLSearchParams({client_id:this._clientId,client_secret:this._clientSecret,grant_type:"refresh_token",refresh_token:this._refreshToken,target_audience:e}),responseType:"json"};return qv.AuthClient.setMethodName(n,"fetchIdToken"),(await this.transporter.request(n)).data.id_token}fromJSON(e){if(!e)throw new Error("Must pass in a JSON object containing the user refresh token");if(e.type!=="authorized_user")throw new Error('The incoming JSON object does not have the "authorized_user" type');if(!e.client_id)throw new Error("The incoming JSON object does not contain a client_id field");if(!e.client_secret)throw new Error("The incoming JSON object does not contain a client_secret field");if(!e.refresh_token)throw new Error("The incoming JSON object does not contain a refresh_token field");this._clientId=e.client_id,this._clientSecret=e.client_secret,this._refreshToken=e.refresh_token,this.credentials.refresh_token=e.refresh_token,this.quotaProjectId=e.quota_project_id,this.universeDomain=e.universe_domain||this.universeDomain}fromStream(e,n){if(n)this.fromStreamAsync(e).then(()=>n(),n);else return this.fromStreamAsync(e)}async fromStreamAsync(e){return new Promise((n,r)=>{if(!e)return r(new Error("Must pass in a stream containing the user refresh token."));let i="";e.setEncoding("utf8").on("error",r).on("data",o=>i+=o).on("end",()=>{try{let o=JSON.parse(i);return this.fromJSON(o),n()}catch(o){return r(o)}})})}static fromJSON(e){let n=new t;return n.fromJSON(e),n}};wn.UserRefreshClient=Js});var Ks=F(Pn=>{"use strict";Object.defineProperty(Pn,"__esModule",{value:!0});Pn.Impersonated=Pn.IMPERSONATED_ACCOUNT_TYPE=void 0;var of=Ot(),Fv=ke(),Bv=st();Pn.IMPERSONATED_ACCOUNT_TYPE="impersonated_service_account";var Xs=class t extends of.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 of.OAuth2Client,this.targetPrincipal=e.targetPrincipal??"",this.delegates=e.delegates??[],this.targetScopes=e.targetScopes??[],this.lifetime=e.lifetime??3600,!!!(0,Bv.originalOrCamelOptions)(e).get("universe_domain"))this.universeDomain=this.sourceClient.universeDomain;else if(this.sourceClient.universeDomain!==this.universeDomain)throw new RangeError(`Universe domain ${this.sourceClient.universeDomain} in source credentials does not match ${this.universeDomain} universe domain set for impersonated credentials.`);this.endpoint=e.endpoint??`https://iamcredentials.${this.universeDomain}`}async sign(e){await this.sourceClient.getAccessToken();let n=`projects/-/serviceAccounts/${this.targetPrincipal}`,r=`${this.endpoint}/v1/${n}:signBlob`,i={delegates:this.delegates,payload:Buffer.from(e).toString("base64")};return(await this.sourceClient.request({...t.RETRY_CONFIG,url:r,data:i,method:"POST"})).data}getTargetPrincipal(){return this.targetPrincipal}async refreshToken(){try{await this.sourceClient.getAccessToken();let e="projects/-/serviceAccounts/"+this.targetPrincipal,n=`${this.endpoint}/v1/${e}:generateAccessToken`,r={delegates:this.delegates,scope:this.targetScopes,lifetime:this.lifetime+"s"},i=await this.sourceClient.request({...t.RETRY_CONFIG,url:n,data:r,method:"POST"}),o=i.data;return this.credentials.access_token=o.accessToken,this.credentials.expiry_date=Date.parse(o.expireTime),{tokens:this.credentials,res:i}}catch(e){if(!(e instanceof Error))throw e;let n=0,r="";throw e instanceof Fv.GaxiosError&&(n=e?.response?.data?.error?.status,r=e?.response?.data?.error?.message),n&&r?(e.message=`${n}: unable to impersonate: ${r}`,e):(e.message=`unable to impersonate: ${e}`,e)}}async fetchIdToken(e,n){await this.sourceClient.getAccessToken();let r=`projects/-/serviceAccounts/${this.targetPrincipal}`,i=`${this.endpoint}/v1/${r}:generateIdToken`,o={delegates:this.delegates,audience:e,includeEmail:n?.includeEmail??!0,useEmailAzp:n?.includeEmail??!0};return(await this.sourceClient.request({...t.RETRY_CONFIG,url:i,data:o,method:"POST"})).data.token}};Pn.Impersonated=Xs});var zs=F(fr=>{"use strict";Object.defineProperty(fr,"__esModule",{value:!0});fr.OAuthClientAuthHandler=void 0;fr.getErrorFromOAuthErrorResponse=$v;var Rn=ke(),Hv=sr(),Vv=["PUT","POST","PATCH"],Ys=class{#e=(0,Hv.createCrypto)();#t;transporter;constructor(e){e&&"clientId"in e?(this.#t=e,this.transporter=new Rn.Gaxios):(this.#t=e?.clientAuthentication,this.transporter=e?.transporter||new Rn.Gaxios)}applyClientAuthenticationOptions(e,n){e.headers=Rn.Gaxios.mergeHeaders(e.headers),this.injectAuthenticatedHeaders(e,n),n||this.injectAuthenticatedRequestBody(e)}injectAuthenticatedHeaders(e,n){if(n)e.headers=Rn.Gaxios.mergeHeaders(e.headers,{authorization:`Bearer ${n}`});else if(this.#t?.confidentialClientType==="basic"){e.headers=Rn.Gaxios.mergeHeaders(e.headers);let r=this.#t.clientId,i=this.#t.clientSecret||"",o=this.#e.encodeBase64StringUtf8(`${r}:${i}`);Rn.Gaxios.mergeHeaders(e.headers,{authorization:`Basic ${o}`})}}injectAuthenticatedRequestBody(e){if(this.#t?.confidentialClientType==="request-body"){let n=(e.method||"GET").toUpperCase();if(!Vv.includes(n))throw new Error(`${n} HTTP method does not support ${this.#t.confidentialClientType} client authentication`);let i=new Headers(e.headers).get("content-type");if(i?.startsWith("application/x-www-form-urlencoded")||e.data instanceof URLSearchParams){let o=new URLSearchParams(e.data??"");o.append("client_id",this.#t.clientId),o.append("client_secret",this.#t.clientSecret||""),e.data=o}else if(i?.startsWith("application/json"))e.data=e.data||{},Object.assign(e.data,{client_id:this.#t.clientId,client_secret:this.#t.clientSecret||""});else throw new Error(`${i} content-types are not supported with ${this.#t.confidentialClientType} client authentication`)}}static get RETRY_CONFIG(){return{retry:!0,retryConfig:{httpMethodsToRetry:["GET","PUT","POST","HEAD","OPTIONS","DELETE"]}}}};fr.OAuthClientAuthHandler=Ys;function $v(t,e){let n=t.error,r=t.error_description,i=t.error_uri,o=`Error code ${n}`;typeof r<"u"&&(o+=`: ${r}`),typeof i<"u"&&(o+=` - ${i}`);let a=new Error(o);if(e){let u=Object.keys(e);e.stack&&u.push("stack"),u.forEach(c=>{c!=="message"&&Object.defineProperty(a,c,{value:e[c],writable:!1,enumerable:!0})})}return a}});var pi=F(fi=>{"use strict";Object.defineProperty(fi,"__esModule",{value:!0});fi.StsCredentials=void 0;var Jv=ke(),Wv=He(),sf=zs(),Xv=st(),Qs=class t extends sf.OAuthClientAuthHandler{#e;constructor(e={tokenExchangeEndpoint:""},n){(typeof e!="object"||e instanceof URL)&&(e={tokenExchangeEndpoint:e,clientAuthentication:n}),super(e),this.#e=e.tokenExchangeEndpoint}async exchangeToken(e,n,r){let i={grant_type:e.grantType,resource:e.resource,audience:e.audience,scope:e.scope?.join(" "),requested_token_type:e.requestedTokenType,subject_token:e.subjectToken,subject_token_type:e.subjectTokenType,actor_token:e.actingParty?.actorToken,actor_token_type:e.actingParty?.actorTokenType,options:r&&JSON.stringify(r)},o={...t.RETRY_CONFIG,url:this.#e.toString(),method:"POST",headers:n,data:new URLSearchParams((0,Xv.removeUndefinedValuesInObject)(i)),responseType:"json"};Wv.AuthClient.setMethodName(o,"exchangeToken"),this.applyClientAuthenticationOptions(o);try{let a=await this.transporter.request(o),u=a.data;return u.res=a,u}catch(a){throw a instanceof Jv.GaxiosError&&a.response?(0,sf.getErrorFromOAuthErrorResponse)(a.response.data,a):a}}};fi.StsCredentials=Qs});var Bt=F(Qe=>{"use strict";Object.defineProperty(Qe,"__esModule",{value:!0});Qe.BaseExternalAccountClient=Qe.CLOUD_RESOURCE_MANAGER=Qe.EXTERNAL_ACCOUNT_TYPE=Qe.EXPIRATION_TIME_OFFSET=void 0;var Kv=ke(),Yv=W("stream"),Zs=He(),zv=pi(),af=st(),Qv=as(),Zv="urn:ietf:params:oauth:grant-type:token-exchange",jv="urn:ietf:params:oauth:token-type:access_token",js="https://www.googleapis.com/auth/cloud-platform",eT=3600;Qe.EXPIRATION_TIME_OFFSET=300*1e3;Qe.EXTERNAL_ACCOUNT_TYPE="external_account";Qe.CLOUD_RESOURCE_MANAGER="https://cloudresourcemanager.googleapis.com/v1/projects/";var tT="//iam\\.googleapis\\.com/locations/[^/]+/workforcePools/[^/]+/providers/.+",nT="https://sts.{universeDomain}/v1/token",ea=class t extends Zs.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,af.originalOrCamelOptions)(e),r=n.get("type");if(r&&r!==Qe.EXTERNAL_ACCOUNT_TYPE)throw new Error(`Expected "${Qe.EXTERNAL_ACCOUNT_TYPE}" type but received "${e.type}"`);let i=n.get("client_id"),o=n.get("client_secret");this.tokenUrl=n.get("token_url")??nT.replace("{universeDomain}",this.universeDomain);let a=n.get("subject_token_type"),u=n.get("workforce_pool_user_project"),c=n.get("service_account_impersonation_url"),d=n.get("service_account_impersonation"),f=(0,af.originalOrCamelOptions)(d).get("token_lifetime_seconds");this.cloudResourceManagerURL=new URL(n.get("cloud_resource_manager_url")||`https://cloudresourcemanager.${this.universeDomain}/v1/projects/`),i&&(this.clientAuth={confidentialClientType:"basic",clientId:i,clientSecret:o}),this.stsCredential=new zv.StsCredentials({tokenExchangeEndpoint:this.tokenUrl,clientAuthentication:this.clientAuth}),this.scopes=n.get("scopes")||[js],this.cachedAccessToken=null,this.audience=n.get("audience"),this.subjectTokenType=a,this.workforcePoolUserProject=u;let p=new RegExp(tT);if(this.workforcePoolUserProject&&!this.audience.match(p))throw new Error("workforcePoolUserProject should not be set for non-workforce pool credentials.");this.serviceAccountImpersonationUrl=c,this.serviceAccountImpersonationLifetime=f,this.serviceAccountImpersonationLifetime?this.configLifetimeRequested=!0:(this.configLifetimeRequested=!1,this.serviceAccountImpersonationLifetime=eT),this.projectNumber=this.getProjectNumber(this.audience),this.supplierContext={audience:this.audience,subjectTokenType:this.subjectTokenType,transporter:this.transporter}}getServiceAccountEmail(){if(this.serviceAccountImpersonationUrl){if(this.serviceAccountImpersonationUrl.length>256)throw new RangeError(`URL is too long: ${this.serviceAccountImpersonationUrl}`);return/serviceAccounts\/(?<email>[^:]+):generateAccessToken$/.exec(this.serviceAccountImpersonationUrl)?.groups?.email||null}return null}setCredentials(e){super.setCredentials(e),this.cachedAccessToken=e}async getAccessToken(){return(!this.cachedAccessToken||this.isExpired(this.cachedAccessToken))&&await this.refreshAccessTokenAsync(),{token:this.cachedAccessToken.access_token,res:this.cachedAccessToken.res}}async getRequestHeaders(){let e=await this.getAccessToken(),n=new Headers({authorization:`Bearer ${e.token}`});return this.addSharedMetadataHeaders(n)}request(e,n){if(n)this.requestAsync(e).then(r=>n(null,r),r=>n(r,r.response));else return this.requestAsync(e)}async getProjectId(){let e=this.projectNumber||this.workforcePoolUserProject;if(this.projectId)return this.projectId;if(e){let n=await this.getRequestHeaders(),r={...t.RETRY_CONFIG,headers:n,url:`${this.cloudResourceManagerURL.toString()}${e}`,responseType:"json"};Zs.AuthClient.setMethodName(r,"getProjectId");let i=await this.transporter.request(r);return this.projectId=i.data.projectId,this.projectId}return null}async requestAsync(e,n=!1){let r;try{let i=await this.getRequestHeaders();e.headers=Kv.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,i),r=await this.transporter.request(e)}catch(i){let o=i.response;if(o){let a=o.status,u=o.config.data instanceof Yv.Readable;if(!n&&(a===401||a===403)&&!u&&this.forceRefreshOnFailure)return await this.refreshAccessTokenAsync(),await this.requestAsync(e,!0)}throw i}return r}async refreshAccessTokenAsync(){this.#e=this.#e||this.#t();try{return await this.#e}finally{this.#e=null}}async#t(){let e=await this.retrieveSubjectToken(),n={grantType:Zv,audience:this.audience,requestedTokenType:jv,subjectToken:e,subjectTokenType:this.subjectTokenType,scope:this.serviceAccountImpersonationUrl?[js]:this.getScopesArray()},r=!this.clientAuth&&this.workforcePoolUserProject?{userProject:this.workforcePoolUserProject}:void 0,i=new Headers({"x-goog-api-client":this.getMetricsHeaderValue()}),o=await this.stsCredential.exchangeToken(n,i,r);return this.serviceAccountImpersonationUrl?this.cachedAccessToken=await this.getImpersonatedAccessToken(o.access_token):o.expires_in?this.cachedAccessToken={access_token:o.access_token,expiry_date:new Date().getTime()+o.expires_in*1e3,res:o.res}:this.cachedAccessToken={access_token:o.access_token,res:o.res},this.credentials={},Object.assign(this.credentials,this.cachedAccessToken),delete this.credentials.res,this.emit("tokens",{refresh_token:null,expiry_date:this.cachedAccessToken.expiry_date,access_token:this.cachedAccessToken.access_token,token_type:"Bearer",id_token:null}),this.cachedAccessToken}getProjectNumber(e){let n=e.match(/\/projects\/([^/]+)/);return n?n[1]:null}async getImpersonatedAccessToken(e){let n={...t.RETRY_CONFIG,url:this.serviceAccountImpersonationUrl,method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e}`},data:{scope:this.getScopesArray(),lifetime:this.serviceAccountImpersonationLifetime+"s"},responseType:"json"};Zs.AuthClient.setMethodName(n,"getImpersonatedAccessToken");let r=await this.transporter.request(n),i=r.data;return{access_token:i.accessToken,expiry_date:new Date(i.expireTime).getTime(),res:r}}isExpired(e){let n=new Date().getTime();return e.expiry_date?n>=e.expiry_date-this.eagerRefreshThresholdMillis:!1}getScopesArray(){return typeof this.scopes=="string"?[this.scopes]:this.scopes||[js]}getMetricsHeaderValue(){let e=process.version.replace(/^v/,""),n=this.serviceAccountImpersonationUrl!==void 0,r=this.credentialSourceType?this.credentialSourceType:"unknown";return`gl-node/${e} auth/${Qv.pkg.version} google-byoid-sdk source/${r} sa-impersonation/${n} config-lifetime/${this.configLifetimeRequested}`}getTokenUrl(){return this.tokenUrl}};Qe.BaseExternalAccountClient=ea});var lf=F(hi=>{"use strict";Object.defineProperty(hi,"__esModule",{value:!0});hi.FileSubjectTokenSupplier=void 0;var na=W("util"),ra=W("fs"),rT=(0,na.promisify)(ra.readFile??(()=>{})),iT=(0,na.promisify)(ra.realpath??(()=>{})),oT=(0,na.promisify)(ra.lstat??(()=>{})),ta=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 iT(e),!(await oT(e)).isFile())throw new Error}catch(i){throw i instanceof Error&&(i.message=`The file at ${e} does not exist, or it is not a file. ${i.message}`),i}let n,r=await rT(e,{encoding:"utf8"});if(this.formatType==="text"?n=r:this.formatType==="json"&&this.subjectTokenFieldName&&(n=JSON.parse(r)[this.subjectTokenFieldName]),!n)throw new Error("Unable to parse the subject_token from the credential_source file");return n}};hi.FileSubjectTokenSupplier=ta});var uf=F(mi=>{"use strict";Object.defineProperty(mi,"__esModule",{value:!0});mi.UrlSubjectTokenSupplier=void 0;var sT=He(),ia=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};sT.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 new Error("Unable to parse the subject_token from the credential_source URL");return r}};mi.UrlSubjectTokenSupplier=ia});var cf=F(Ve=>{"use strict";Object.defineProperty(Ve,"__esModule",{value:!0});Ve.CertificateSubjectTokenSupplier=Ve.InvalidConfigurationError=Ve.CertificateSourceUnavailableError=Ve.CERTIFICATE_CONFIGURATION_ENV_VARIABLE=void 0;var gi=st(),_i=W("fs"),yi=W("crypto"),aT=W("https");Ve.CERTIFICATE_CONFIGURATION_ENV_VARIABLE="GOOGLE_API_CERTIFICATE_CONFIG";var Et=class extends Error{constructor(e){super(e),this.name="CertificateSourceUnavailableError"}};Ve.CertificateSourceUnavailableError=Et;var Ze=class extends Error{constructor(e){super(e),this.name="InvalidConfigurationError"}};Ve.InvalidConfigurationError=Ze;var oa=class{certificateConfigPath;trustChainPath;cert;key;constructor(e){if(!e.useDefaultCertificateConfig&&!e.certificateConfigLocation)throw new Ze("Either `useDefaultCertificateConfig` must be true or a `certificateConfigLocation` must be provided.");if(e.useDefaultCertificateConfig&&e.certificateConfigLocation)throw new Ze("Both `useDefaultCertificateConfig` and `certificateConfigLocation` cannot be provided.");this.trustChainPath=e.trustChainPath,this.certificateConfigPath=e.certificateConfigLocation??""}async createMtlsHttpsAgent(){if(!this.key||!this.cert)throw new Ze("Cannot create mTLS Agent with missing certificate or key");return new aT.Agent({key:this.key,cert:this.cert})}async getSubjectToken(){this.certificateConfigPath=await this.#e();let{certPath:e,keyPath:n}=await this.#t();return{cert:this.cert,key:this.key}=await this.#n(e,n),await this.#r(this.cert)}async#e(){let e=this.certificateConfigPath;if(e){if(await(0,gi.isValidFile)(e))return e;throw new Et(`Provided certificate config path is invalid: ${e}`)}let n=process.env[Ve.CERTIFICATE_CONFIGURATION_ENV_VARIABLE];if(n){if(await(0,gi.isValidFile)(n))return n;throw new Et(`Path from environment variable "${Ve.CERTIFICATE_CONFIGURATION_ENV_VARIABLE}" is invalid: ${n}`)}let r=(0,gi.getWellKnownCertificateConfigFileLocation)();if(await(0,gi.isValidFile)(r))return r;throw new Et(`Could not find certificate configuration file. Searched override path, the "${Ve.CERTIFICATE_CONFIGURATION_ENV_VARIABLE}" env var, and the gcloud path (${r}).`)}async#t(){let e=this.certificateConfigPath,n;try{n=await _i.promises.readFile(e,"utf8")}catch{throw new Et(`Failed to read certificate config file at: ${e}`)}try{let r=JSON.parse(n),i=r?.cert_configs?.workload?.cert_path,o=r?.cert_configs?.workload?.key_path;if(!i||!o)throw new Ze(`Certificate config file (${e}) is missing required "cert_path" or "key_path" in the workload config.`);return{certPath:i,keyPath:o}}catch(r){throw r instanceof Ze?r:new Ze(`Failed to parse certificate config from ${e}: ${r.message}`)}}async#n(e,n){let r,i;try{r=await _i.promises.readFile(e),new yi.X509Certificate(r)}catch(o){let a=o instanceof Error?o.message:String(o);throw new Et(`Failed to read certificate file at ${e}: ${a}`)}try{i=await _i.promises.readFile(n),(0,yi.createPrivateKey)(i)}catch(o){let a=o instanceof Error?o.message:String(o);throw new Et(`Failed to read private key file at ${n}: ${a}`)}return{cert:r,key:i}}async#r(e){let n=new yi.X509Certificate(e);if(!this.trustChainPath)return JSON.stringify([n.raw.toString("base64")]);try{let o=((await _i.promises.readFile(this.trustChainPath,"utf8")).match(/-----BEGIN CERTIFICATE-----[^-]+-----END CERTIFICATE-----/g)??[]).map((c,d)=>{try{return new yi.X509Certificate(c)}catch(f){let p=f instanceof Error?f.message:String(f);throw new Ze(`Failed to parse certificate at index ${d} in trust chain file ${this.trustChainPath}: ${p}`)}}),a=o.findIndex(c=>n.raw.equals(c.raw)),u;if(a===-1)u=[n,...o];else if(a===0)u=o;else throw new Ze(`Leaf certificate exists in the trust chain but is not the first entry (found at index ${a}).`);return JSON.stringify(u.map(c=>c.raw.toString("base64")))}catch(r){if(r instanceof Ze)throw r;let i=r instanceof Error?r.message:String(r);throw new Et(`Failed to process certificate chain from ${this.trustChainPath}: ${i}`)}}};Ve.CertificateSubjectTokenSupplier=oa});var la=F(Ei=>{"use strict";Object.defineProperty(Ei,"__esModule",{value:!0});Ei.IdentityPoolClient=void 0;var lT=Bt(),sa=st(),uT=lf(),cT=uf(),df=cf(),dT=pi(),ff=ke(),aa=class t extends lT.BaseExternalAccountClient{subjectTokenSupplier;constructor(e){super(e);let n=(0,sa.originalOrCamelOptions)(e),r=n.get("credential_source"),i=n.get("subject_token_supplier");if(!r&&!i)throw new Error("A credential source or subject token supplier must be specified.");if(r&&i)throw new Error("Only one of credential source or subject token supplier can be specified.");if(i)this.subjectTokenSupplier=i,this.credentialSourceType="programmatic";else{let o=(0,sa.originalOrCamelOptions)(r),a=(0,sa.originalOrCamelOptions)(o.get("format")),u=a.get("type")||"text",c=a.get("subject_token_field_name");if(u!=="json"&&u!=="text")throw new Error(`Invalid credential_source format "${u}"`);if(u==="json"&&!c)throw new Error("Missing subject_token_field_name for JSON credential_source format");let d=o.get("file"),f=o.get("url"),p=o.get("certificate"),h=o.get("headers");if(d&&f||f&&p||d&&p)throw new Error('No valid Identity Pool "credential_source" provided, must be either file, url, or certificate.');if(d)this.credentialSourceType="file",this.subjectTokenSupplier=new uT.FileSubjectTokenSupplier({filePath:d,formatType:u,subjectTokenFieldName:c});else if(f)this.credentialSourceType="url",this.subjectTokenSupplier=new cT.UrlSubjectTokenSupplier({url:f,formatType:u,subjectTokenFieldName:c,headers:h,additionalGaxiosOptions:t.RETRY_CONFIG});else if(p){this.credentialSourceType="certificate";let m=new df.CertificateSubjectTokenSupplier({useDefaultCertificateConfig:p.use_default_certificate_config,certificateConfigLocation:p.certificate_config_location,trustChainPath:p.trust_chain_path});this.subjectTokenSupplier=m}else throw new Error('No valid Identity Pool "credential_source" provided, must be either file, url, or certificate.')}}async retrieveSubjectToken(){let e=await this.subjectTokenSupplier.getSubjectToken(this.supplierContext);if(this.subjectTokenSupplier instanceof df.CertificateSubjectTokenSupplier){let n=await this.subjectTokenSupplier.createMtlsHttpsAgent();this.stsCredential=new dT.StsCredentials({tokenExchangeEndpoint:this.getTokenUrl(),clientAuthentication:this.clientAuth,transporter:new ff.Gaxios({agent:n})}),this.transporter=new ff.Gaxios({...this.transporter.defaults||{},agent:n})}return e}};Ei.IdentityPoolClient=aa});var ca=F(Ti=>{"use strict";Object.defineProperty(Ti,"__esModule",{value:!0});Ti.AwsRequestSigner=void 0;var vi=ke(),hf=sr(),pf="AWS4-HMAC-SHA256",fT="aws4_request",ua=class{getCredentials;region;crypto;constructor(e,n){this.getCredentials=e,this.region=n,this.crypto=(0,hf.createCrypto)()}async getRequestOptions(e){if(!e.url)throw new RangeError('"url" is required in "amzOptions"');let n=typeof e.data=="object"?JSON.stringify(e.data):e.data,r=e.url,i=e.method||"GET",o=e.body||n,a=e.headers,u=await this.getCredentials(),c=new URL(r);if(typeof o!="string"&&o!==void 0)throw new TypeError(`'requestPayload' is expected to be a string if provided. Got: ${o}`);let d=await hT({crypto:this.crypto,host:c.host,canonicalUri:c.pathname,canonicalQuerystring:c.search.slice(1),method:i,region:this.region,securityCredentials:u,requestPayload:o,additionalAmzHeaders:a}),f=vi.Gaxios.mergeHeaders(d.amzDate?{"x-amz-date":d.amzDate}:{},{authorization:d.authorizationHeader,host:c.host},a||{});u.token&&vi.Gaxios.mergeHeaders(f,{"x-amz-security-token":u.token});let p={url:r,method:i,headers:f};return o!==void 0&&(p.body=o),p}};Ti.AwsRequestSigner=ua;async function pr(t,e,n){return await t.signWithHmacSha256(e,n)}async function pT(t,e,n,r,i){let o=await pr(t,`AWS4${e}`,n),a=await pr(t,o,r),u=await pr(t,a,i);return await pr(t,u,"aws4_request")}async function hT(t){let e=vi.Gaxios.mergeHeaders(t.additionalAmzHeaders),n=t.requestPayload||"",r=t.host.split(".")[0],i=new Date,o=i.toISOString().replace(/[-:]/g,"").replace(/\.[0-9]+/,""),a=i.toISOString().replace(/[-]/g,"").replace(/T.*/,"");t.securityCredentials.token&&e.set("x-amz-security-token",t.securityCredentials.token);let u=vi.Gaxios.mergeHeaders({host:t.host},e.has("date")?{}:{"x-amz-date":o},e),c="",d=[...u.keys()].sort();d.forEach(C=>{c+=`${C}:${u.get(C)}
16
- `});let f=d.join(";"),p=await t.crypto.sha256DigestHex(n),h=`${t.method.toUpperCase()}
17
- ${t.canonicalUri}
18
- ${t.canonicalQuerystring}
19
- ${c}
20
- ${f}
21
- ${p}`,m=`${a}/${t.region}/${r}/${fT}`,_=`${pf}
22
- ${o}
23
- ${m}
24
- `+await t.crypto.sha256DigestHex(h),g=await pT(t.crypto,t.securityCredentials.secretAccessKey,a,t.region,r),E=await pr(t.crypto,g,_),y=`${pf} Credential=${t.securityCredentials.accessKeyId}/${m}, SignedHeaders=${f}, Signature=${(0,hf.fromArrayBufferToHex)(E)}`;return{amzDate:e.has("date")?void 0:o,authorizationHeader:y,canonicalQuerystring:t.canonicalQuerystring}}});var mf=F(Ci=>{"use strict";Object.defineProperty(Ci,"__esModule",{value:!0});Ci.DefaultAwsSecurityCredentialsSupplier=void 0;var Ai=He(),da=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 new 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};Ai.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 n=new Headers;this.imdsV2SessionTokenUrl&&n.set("x-aws-ec2-metadata-token",await this.#e(e.transporter));let r=await this.#t(n,e.transporter),i=await this.#n(r,n,e.transporter);return{accessKeyId:i.AccessKeyId,secretAccessKey:i.SecretAccessKey,token:i.Token}}async#e(e){let n={...this.additionalGaxiosOptions,url:this.imdsV2SessionTokenUrl,method:"PUT",responseType:"text",headers:{"x-aws-ec2-metadata-token-ttl-seconds":"300"}};return Ai.AuthClient.setMethodName(n,"#getImdsV2SessionToken"),(await e.request(n)).data}async#t(e,n){if(!this.securityCredentialsUrl)throw new Error('Unable to determine AWS role name due to missing "options.credential_source.url"');let r={...this.additionalGaxiosOptions,url:this.securityCredentialsUrl,method:"GET",responseType:"text",headers:e};return Ai.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 Ai.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}};Ci.DefaultAwsSecurityCredentialsSupplier=da});var pa=F(Si=>{"use strict";Object.defineProperty(Si,"__esModule",{value:!0});Si.AwsClient=void 0;var mT=ca(),gT=Bt(),_T=mf(),gf=st(),yT=ke(),fa=class t extends gT.BaseExternalAccountClient{environmentId;awsSecurityCredentialsSupplier;regionalCredVerificationUrl;awsRequestSigner;region;static#e="https://sts.{region}.amazonaws.com?Action=GetCallerIdentity&Version=2011-06-15";static AWS_EC2_METADATA_IPV4_ADDRESS="169.254.169.254";static AWS_EC2_METADATA_IPV6_ADDRESS="fd00:ec2::254";constructor(e){super(e);let n=(0,gf.originalOrCamelOptions)(e),r=n.get("credential_source"),i=n.get("aws_security_credentials_supplier");if(!r&&!i)throw new Error("A credential source or AWS security credentials supplier must be specified.");if(r&&i)throw new Error("Only one of credential source or AWS security credentials supplier can be specified.");if(i)this.awsSecurityCredentialsSupplier=i,this.regionalCredVerificationUrl=t.#e,this.credentialSourceType="programmatic";else{let o=(0,gf.originalOrCamelOptions)(r);this.environmentId=o.get("environment_id");let a=o.get("region_url"),u=o.get("url"),c=o.get("imdsv2_session_token_url");this.awsSecurityCredentialsSupplier=new _T.DefaultAwsSecurityCredentialsSupplier({regionUrl:a,securityCredentialsUrl:u,imdsV2SessionTokenUrl:c}),this.regionalCredVerificationUrl=o.get("regional_cred_verification_url"),this.credentialSourceType="aws",this.validateEnvironmentId()}this.awsRequestSigner=null,this.region=""}validateEnvironmentId(){let e=this.environmentId?.match(/^(aws)(\d+)$/);if(!e||!this.regionalCredVerificationUrl)throw new Error('No valid AWS "credential_source" provided');if(parseInt(e[2],10)!==1)throw new Error(`aws version "${e[2]}" is not supported in the current build.`)}async retrieveSubjectToken(){this.awsRequestSigner||(this.region=await this.awsSecurityCredentialsSupplier.getAwsRegion(this.supplierContext),this.awsRequestSigner=new mT.AwsRequestSigner(async()=>this.awsSecurityCredentialsSupplier.getAwsSecurityCredentials(this.supplierContext),this.region));let e=await this.awsRequestSigner.getRequestOptions({...t.RETRY_CONFIG,url:this.regionalCredVerificationUrl.replace("{region}",this.region),method:"POST"}),n=[];return yT.Gaxios.mergeHeaders({"x-goog-cloud-target-resource":this.audience},e.headers).forEach((i,o)=>n.push({key:o,value:i})),encodeURIComponent(JSON.stringify({url:e.url,method:e.method,headers:n}))}};Si.AwsClient=fa});var ya=F(Ie=>{"use strict";Object.defineProperty(Ie,"__esModule",{value:!0});Ie.InvalidSubjectTokenError=Ie.InvalidMessageFieldError=Ie.InvalidCodeFieldError=Ie.InvalidTokenTypeFieldError=Ie.InvalidExpirationTimeFieldError=Ie.InvalidSuccessFieldError=Ie.InvalidVersionFieldError=Ie.ExecutableResponseError=Ie.ExecutableResponse=void 0;var Ii="urn:ietf:params:oauth:token-type:saml2",ha="urn:ietf:params:oauth:token-type:id_token",ma="urn:ietf:params:oauth:token-type:jwt",ga=class{version;success;expirationTime;tokenType;errorCode;errorMessage;subjectToken;constructor(e){if(!e.version)throw new wi("Executable response must contain a 'version' field.");if(e.success===void 0)throw new Pi("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!==Ii&&this.tokenType!==ha&&this.tokenType!==ma)throw new Ri(`Executable response must contain a 'token_type' field when successful and it must be one of ${ha}, ${ma}, or ${Ii}.`);if(this.tokenType===Ii){if(!e.saml_response)throw new hr(`Executable response must contain a 'saml_response' field when token_type=${Ii}.`);this.subjectToken=e.saml_response}else{if(!e.id_token)throw new hr(`Executable response must contain a 'id_token' field when token_type=${ha} or ${ma}.`);this.subjectToken=e.id_token}}else{if(!e.code)throw new Ni("Executable response must contain a 'code' field when unsuccessful.");if(!e.message)throw new xi("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)}};Ie.ExecutableResponse=ga;var vt=class extends Error{constructor(e){super(e),Object.setPrototypeOf(this,new.target.prototype)}};Ie.ExecutableResponseError=vt;var wi=class extends vt{};Ie.InvalidVersionFieldError=wi;var Pi=class extends vt{};Ie.InvalidSuccessFieldError=Pi;var _a=class extends vt{};Ie.InvalidExpirationTimeFieldError=_a;var Ri=class extends vt{};Ie.InvalidTokenTypeFieldError=Ri;var Ni=class extends vt{};Ie.InvalidCodeFieldError=Ni;var xi=class extends vt{};Ie.InvalidMessageFieldError=xi;var hr=class extends vt{};Ie.InvalidSubjectTokenError=hr});var Ta=F(Nn=>{"use strict";Object.defineProperty(Nn,"__esModule",{value:!0});Nn.PluggableAuthHandler=Nn.ExecutableError=void 0;var an=ya(),ET=W("child_process"),Ea=W("fs"),ki=class extends Error{code;constructor(e,n){super(`The executable failed with exit code: ${n} and error message: ${e}.`),this.code=n,Object.setPrototypeOf(this,new.target.prototype)}};Nn.ExecutableError=ki;var va=class t{commandComponents;timeoutMillis;outputFile;constructor(e){if(!e.command)throw new Error("No command provided.");if(this.commandComponents=t.parseCommand(e.command),this.timeoutMillis=e.timeoutMillis,!this.timeoutMillis)throw new Error("No timeoutMillis provided.");this.outputFile=e.outputFile}retrieveResponseFromExecutable(e){return new Promise((n,r)=>{let i=ET.spawn(this.commandComponents[0],this.commandComponents.slice(1),{env:{...process.env,...Object.fromEntries(e)}}),o="";i.stdout.on("data",u=>{o+=u}),i.stderr.on("data",u=>{o+=u});let a=setTimeout(()=>(i.removeAllListeners(),i.kill(),r(new Error("The executable failed to finish within the timeout specified."))),this.timeoutMillis);i.on("close",u=>{if(clearTimeout(a),u===0)try{let c=JSON.parse(o),d=new an.ExecutableResponse(c);return n(d)}catch(c){return c instanceof an.ExecutableResponseError?r(c):r(new an.ExecutableResponseError(`The executable returned an invalid response: ${o}`))}else return r(new ki(o,u.toString()))})})}async retrieveCachedResponse(){if(!this.outputFile||this.outputFile.length===0)return;let e;try{e=await Ea.promises.realpath(this.outputFile)}catch{return}if(!(await Ea.promises.lstat(e)).isFile())return;let n=await Ea.promises.readFile(e,{encoding:"utf8"});if(n!=="")try{let r=JSON.parse(n);return new an.ExecutableResponse(r).isValid()?new an.ExecutableResponse(r):void 0}catch(r){throw r instanceof an.ExecutableResponseError?r:new an.ExecutableResponseError(`The output file contained an invalid response: ${n}`)}}static parseCommand(e){let n=e.match(/(?:[^\s"]+|"[^"]*")+/g);if(!n)throw new Error(`Provided command: "${e}" could not be parsed.`);for(let r=0;r<n.length;r++)n[r][0]==='"'&&n[r].slice(-1)==='"'&&(n[r]=n[r].slice(1,-1));return n}};Nn.PluggableAuthHandler=va});var Ca=F(xn=>{"use strict";Object.defineProperty(xn,"__esModule",{value:!0});xn.PluggableAuthClient=xn.ExecutableError=void 0;var vT=Bt(),TT=ya(),_f=Ta(),AT=Ta();Object.defineProperty(xn,"ExecutableError",{enumerable:!0,get:function(){return AT.ExecutableError}});var CT=30*1e3,yf=5*1e3,Ef=120*1e3,ST="GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES",vf=1,Aa=class extends vT.BaseExternalAccountClient{command;timeoutMillis;outputFile;handler;constructor(e){if(super(e),!e.credential_source.executable)throw new Error('No valid Pluggable Auth "credential_source" provided.');if(this.command=e.credential_source.executable.command,!this.command)throw new Error('No valid Pluggable Auth "credential_source" provided.');if(e.credential_source.executable.timeout_millis===void 0)this.timeoutMillis=CT;else if(this.timeoutMillis=e.credential_source.executable.timeout_millis,this.timeoutMillis<yf||this.timeoutMillis>Ef)throw new Error(`Timeout must be between ${yf} and ${Ef} milliseconds.`);this.outputFile=e.credential_source.executable.output_file,this.handler=new _f.PluggableAuthHandler({command:this.command,timeoutMillis:this.timeoutMillis,outputFile:this.outputFile}),this.credentialSourceType="executable"}async retrieveSubjectToken(){if(process.env[ST]!=="1")throw new Error("Pluggable Auth executables need to be explicitly allowed to run by setting the GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES environment Variable to 1.");let e;if(this.outputFile&&(e=await this.handler.retrieveCachedResponse()),!e){let n=new Map;n.set("GOOGLE_EXTERNAL_ACCOUNT_AUDIENCE",this.audience),n.set("GOOGLE_EXTERNAL_ACCOUNT_TOKEN_TYPE",this.subjectTokenType),n.set("GOOGLE_EXTERNAL_ACCOUNT_INTERACTIVE","0"),this.outputFile&&n.set("GOOGLE_EXTERNAL_ACCOUNT_OUTPUT_FILE",this.outputFile);let r=this.getServiceAccountEmail();r&&n.set("GOOGLE_EXTERNAL_ACCOUNT_IMPERSONATED_EMAIL",r),e=await this.handler.retrieveResponseFromExecutable(n)}if(e.version>vf)throw new Error(`Version of executable is not currently supported, maximum supported version is ${vf}.`);if(!e.success)throw new _f.ExecutableError(e.errorMessage,e.errorCode);if(this.outputFile&&!e.expirationTime)throw new TT.InvalidExpirationTimeFieldError("The executable response must contain the `expiration_time` field for successful responses when an output_file has been specified in the configuration.");if(e.isExpired())throw new Error("Executable response is expired.");return e.subjectToken}};xn.PluggableAuthClient=Aa});var Ia=F(Di=>{"use strict";Object.defineProperty(Di,"__esModule",{value:!0});Di.ExternalAccountClient=void 0;var IT=Bt(),wT=la(),PT=pa(),RT=Ca(),Sa=class{constructor(){throw new Error("ExternalAccountClients should be initialized via: ExternalAccountClient.fromJSON(), directly via explicit constructors, eg. new AwsClient(options), new IdentityPoolClient(options), newPluggableAuthClientOptions, or via new GoogleAuth(options).getClient()")}static fromJSON(e){return e&&e.type===IT.EXTERNAL_ACCOUNT_TYPE?e.credential_source?.environment_id?new PT.AwsClient(e):e.credential_source?.executable?new RT.PluggableAuthClient(e):new wT.IdentityPoolClient(e):null}};Di.ExternalAccountClient=Sa});var Ra=F(kn=>{"use strict";Object.defineProperty(kn,"__esModule",{value:!0});kn.ExternalAccountAuthorizedUserClient=kn.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE=void 0;var Af=He(),Tf=zs(),Cf=ke(),NT=W("stream"),xT=Bt();kn.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE="external_account_authorized_user";var kT="https://sts.{universeDomain}/v1/oauthtoken",wa=class t extends Tf.OAuthClientAuthHandler{#e;constructor(e){super(e),this.#e=e.tokenRefreshEndpoint}async refreshToken(e,n){let r={...t.RETRY_CONFIG,url:this.#e,method:"POST",headers:n,data:new URLSearchParams({grant_type:"refresh_token",refresh_token:e}),responseType:"json"};Af.AuthClient.setMethodName(r,"refreshToken"),this.applyClientAuthenticationOptions(r);try{let i=await this.transporter.request(r),o=i.data;return o.res=i,o}catch(i){throw i instanceof Cf.GaxiosError&&i.response?(0,Tf.getErrorFromOAuthErrorResponse)(i.response.data,i):i}}},Pa=class extends Af.AuthClient{cachedAccessToken;externalAccountAuthorizedUserHandler;refreshToken;constructor(e){super(e),e.universe_domain&&(this.universeDomain=e.universe_domain),this.refreshToken=e.refresh_token;let n={confidentialClientType:"basic",clientId:e.client_id,clientSecret:e.client_secret};this.externalAccountAuthorizedUserHandler=new wa({tokenRefreshEndpoint:e.token_url??kT.replace("{universeDomain}",this.universeDomain),transporter:this.transporter,clientAuthentication:n}),this.cachedAccessToken=null,this.quotaProjectId=e.quota_project_id,typeof e?.eagerRefreshThresholdMillis!="number"?this.eagerRefreshThresholdMillis=xT.EXPIRATION_TIME_OFFSET:this.eagerRefreshThresholdMillis=e.eagerRefreshThresholdMillis,this.forceRefreshOnFailure=!!e?.forceRefreshOnFailure}async getAccessToken(){return(!this.cachedAccessToken||this.isExpired(this.cachedAccessToken))&&await this.refreshAccessTokenAsync(),{token:this.cachedAccessToken.access_token,res:this.cachedAccessToken.res}}async getRequestHeaders(){let e=await this.getAccessToken(),n=new Headers({authorization:`Bearer ${e.token}`});return this.addSharedMetadataHeaders(n)}request(e,n){if(n)this.requestAsync(e).then(r=>n(null,r),r=>n(r,r.response));else return this.requestAsync(e)}async requestAsync(e,n=!1){let r;try{let i=await this.getRequestHeaders();e.headers=Cf.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,i),r=await this.transporter.request(e)}catch(i){let o=i.response;if(o){let a=o.status,u=o.config.data instanceof NT.Readable;if(!n&&(a===401||a===403)&&!u&&this.forceRefreshOnFailure)return await this.refreshAccessTokenAsync(),await this.requestAsync(e,!0)}throw i}return r}async refreshAccessTokenAsync(){let e=await this.externalAccountAuthorizedUserHandler.refreshToken(this.refreshToken);return this.cachedAccessToken={access_token:e.access_token,expiry_date:new Date().getTime()+e.expires_in*1e3,res:e.res},e.refresh_token!==void 0&&(this.refreshToken=e.refresh_token),this.cachedAccessToken}isExpired(e){let n=new Date().getTime();return e.expiry_date?n>=e.expiry_date-this.eagerRefreshThresholdMillis:!1}};kn.ExternalAccountAuthorizedUserClient=Pa});var xa=F(Ht=>{"use strict";Object.defineProperty(Ht,"__esModule",{value:!0});Ht.GdchClient=Ht.GDCH_SERVICE_ACCOUNT_TYPE=void 0;var DT=W("crypto"),MT=W("fs"),UT=W("https"),bT=Ot(),GT=3600;Ht.GDCH_SERVICE_ACCOUNT_TYPE="gdch_service_account";var Na=class t extends bT.OAuth2Client{projectId;privateKeyId;privateKey;serviceIdentityName;tokenServerUri;caCertPath;apiAudience;lifetime;gdchOptions;caAgentPromise;cachedCaCertPath;lastCaCertReadTime=0;CA_CERT_TTL_MS=300*1e3;constructor(e={}){super(e),this.gdchOptions=e,this.projectId=e.projectId||void 0,this.privateKeyId=e.privateKeyId,this.privateKey=e.privateKey,this.serviceIdentityName=e.serviceIdentityName,this.tokenServerUri=e.tokenServerUri,this.caCertPath=e.caCertPath,this.apiAudience=e.apiAudience,this.lifetime=e.lifetime||GT,this.credentials={refresh_token:"gdch-placeholder",expiry_date:1}}createWithGdchAudience(e){if(!e)throw new Error("Audience cannot be null or empty for GDCH service account credentials.");return new t({...this.gdchOptions,projectId:this.projectId,privateKeyId:this.privateKeyId,privateKey:this.privateKey,serviceIdentityName:this.serviceIdentityName,tokenServerUri:this.tokenServerUri,caCertPath:this.caCertPath,lifetime:this.lifetime,apiAudience:e})}fromJSON(e){if(!e)throw new Error("Must pass in a JSON object containing the GDCH credentials settings.");if(e.type!==Ht.GDCH_SERVICE_ACCOUNT_TYPE)throw new Error(`The incoming JSON object does not have the "${Ht.GDCH_SERVICE_ACCOUNT_TYPE}" type`);if(e.format_version!=="1")throw new Error("Only format version 1 is supported.");if(!e.project)throw new Error("The incoming JSON object does not contain a project field");if(!e.private_key_id)throw new Error("The incoming JSON object does not contain a private_key_id field");if(!e.private_key)throw new Error("The incoming JSON object does not contain a private_key field");if(!e.name)throw new Error("The incoming JSON object does not contain a name field");if(!e.token_uri)throw new Error("The incoming JSON object does not contain a token_uri field");this.projectId=e.project,this.privateKeyId=e.private_key_id,this.privateKey=e.private_key,this.serviceIdentityName=e.name,this.tokenServerUri=e.token_uri,this.caCertPath=e.ca_cert_path,this.gdchOptions={...this.gdchOptions,projectId:e.project,privateKeyId:e.private_key_id,privateKey:e.private_key,serviceIdentityName:e.name,tokenServerUri:e.token_uri,caCertPath:e.ca_cert_path}}async refreshTokenNoCache(){if(!this.apiAudience)throw new Error("Audience cannot be null or empty for GDCH service account credentials. Specify the audience by calling createWithGdchAudience.");if(!this.privateKey)throw new Error("Private key is not configured for GDCH credentials.");if(!this.privateKeyId)throw new Error("Private key ID is not configured for GDCH credentials.");if(!this.projectId)throw new Error("Project is not configured for GDCH credentials.");if(!this.serviceIdentityName)throw new Error("Service identity name is not configured for GDCH credentials.");if(!this.tokenServerUri)throw new Error("Token server URI is not configured for GDCH credentials.");let e=this.createAssertion(),n={audience:this.apiAudience,grant_type:"urn:ietf:params:oauth:token-type:token-exchange",requested_token_type:"urn:ietf:params:oauth:token-type:access_token",subject_token:e,subject_token_type:"urn:k8s:params:oauth:token-type:serviceaccount"},r={url:this.tokenServerUri,method:"POST",headers:{"Content-Type":"application/json"},data:n,responseType:"json",timeout:1e4,retry:!0,retryConfig:{httpMethodsToRetry:["POST"],statusCodesToRetry:[[500,599]],noResponseRetries:3}};this.caCertPath&&(r.agent=await this.getCaAgent());try{let i=await this.transporter.request(r),o=i.data;if(!o.access_token)throw new Error("Token response did not contain an access_token.");if(!o.expires_in)throw new Error("Token response did not contain an expires_in field.");let a={access_token:o.access_token,token_type:"STS-Bearer",expiry_date:Date.now()+o.expires_in*1e3};return this.emit("tokens",a),{res:i,tokens:a}}catch(i){if(i&&i.config&&i.config.data)try{if(typeof i.config.data=="string"){let o=JSON.parse(i.config.data);o.subject_token&&(o.subject_token="***REDACTED***",i.config.data=JSON.stringify(o))}else typeof i.config.data=="object"&&i.config.data.subject_token&&(i.config.data.subject_token="***REDACTED***")}catch{}throw i instanceof Error&&(i.message=`Error getting access token for GDCH service account: ${i.message}, iss: ${this.serviceIdentityName}`),i}}createAssertion(){let e={alg:"ES256",typ:"JWT",kid:this.privateKeyId},n=`system:serviceaccount:${this.projectId}:${this.serviceIdentityName}`,r=Math.floor(Date.now()/1e3),i={iss:n,sub:n,iat:r,exp:r+this.lifetime,aud:this.tokenServerUri},o=this.base64UrlEncode(JSON.stringify(e)),a=this.base64UrlEncode(JSON.stringify(i)),u=`${o}.${a}`,c=DT.sign("sha256",Buffer.from(u),{key:this.privateKey,dsaEncoding:"ieee-p1363"}),d=this.base64UrlEncode(c);return`${u}.${d}`}async requestAsync(e,n=!1){if(this.caCertPath&&!e.agent){let r=(e.url||"").toString();!r.includes("googleapis.com")&&!r.includes("google.com")&&(e.agent=await this.getCaAgent())}return super.requestAsync(e,n)}getCaAgent(){if(!this.caCertPath){this.caAgentPromise=void 0,this.cachedCaCertPath=void 0,this.lastCaCertReadTime=0;return}let e=Date.now(),n=e-this.lastCaCertReadTime>this.CA_CERT_TTL_MS;if(this.caAgentPromise&&this.caCertPath===this.cachedCaCertPath&&!n)return this.caAgentPromise;this.cachedCaCertPath=this.caCertPath,this.lastCaCertReadTime=e;let r=this.caCertPath;return this.caAgentPromise=(async()=>{try{let i=await MT.promises.readFile(r);return new UT.Agent({ca:i})}catch(i){throw this.cachedCaCertPath===r&&(this.caAgentPromise=void 0,this.cachedCaCertPath=void 0,this.lastCaCertReadTime=0),i instanceof Error&&(i.message=`Error reading certificate file from CA cert path, value '${r}': ${i.message}`),i}})(),this.caAgentPromise}toJSON(){return{...this,privateKey:this.privateKey?"***REDACTED***":void 0,_clientSecret:this._clientSecret?"***REDACTED***":void 0,apiKey:this.apiKey?"***REDACTED***":void 0,gdchOptions:this.gdchOptions?{...this.gdchOptions,privateKey:this.gdchOptions.privateKey?"***REDACTED***":void 0,clientSecret:this.gdchOptions.clientSecret?"***REDACTED***":void 0,client_secret:this.gdchOptions.client_secret?"***REDACTED***":void 0,apiKey:this.gdchOptions.apiKey?"***REDACTED***":void 0,credentials:this.gdchOptions.credentials?{...this.gdchOptions.credentials,access_token:this.gdchOptions.credentials.access_token?"***REDACTED***":void 0,refresh_token:this.gdchOptions.credentials.refresh_token?"***REDACTED***":void 0}:void 0}:void 0,credentials:{...this.credentials,access_token:this.credentials?.access_token?"***REDACTED***":void 0,refresh_token:this.credentials?.refresh_token?"***REDACTED***":void 0}}}[Symbol.for("nodejs.util.inspect.custom")](){return this.toJSON()}base64UrlEncode(e){return(typeof e=="string"?Buffer.from(e):e).toString("base64url")}};Ht.GdchClient=Na});var Pf=F(ut=>{"use strict";Object.defineProperty(ut,"__esModule",{value:!0});ut.GoogleAuth=ut.GoogleAuthExceptionMessages=void 0;var LT=W("child_process"),mr=W("fs"),OT=ke(),gr=or(),qT=W("os"),Mi=W("path"),FT=sr(),BT=gs(),HT=ys(),VT=Es(),Dn=$s(),Sf=Ws(),Mn=Ks(),$T=Ia(),_r=Bt(),ka=He(),If=Ra(),Da=xa(),wf=st();ut.GoogleAuthExceptionMessages={API_KEY_WITH_CREDENTIALS:"API Keys and Credentials are mutually exclusive authentication methods and cannot be used together.",NO_PROJECT_ID_FOUND:`Unable to detect a Project Id in the current environment.
25
- To learn more about authentication and Google APIs, visit:
26
- https://cloud.google.com/docs/authentication/getting-started`,NO_CREDENTIALS_FOUND:`Unable to find credentials in current environment.
27
- To learn more about authentication and Google APIs, visit:
28
- 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.
29
- To learn more about Universe Domain retrieval, visit:
30
- https://cloud.google.com/compute/docs/metadata/predefined-metadata-keys`};var Ma=class{checkIsGCE=void 0;useJWTAccessWithScope;defaultServicePath;get isGCE(){return this.checkIsGCE}_findProjectIdPromise;_cachedProjectId;jsonContent=null;apiKey;cachedCredential=null;#e=null;defaultScopes;keyFilename;scopes;clientOptions={};constructor(e={}){if(this._cachedProjectId=e.projectId||null,this.cachedCredential=e.authClient||null,this.keyFilename=e.keyFilename||e.keyFile,this.scopes=e.scopes,this.clientOptions=e.clientOptions||{},this.jsonContent=e.credentials||null,this.apiKey=e.apiKey||this.clientOptions.apiKey||null,this.apiKey&&(this.jsonContent||this.clientOptions.credentials))throw new RangeError(ut.GoogleAuthExceptionMessages.API_KEY_WITH_CREDENTIALS);e.universeDomain&&(this.clientOptions.universeDomain=e.universeDomain)}setGapicJWTValues(e){e.defaultServicePath=this.defaultServicePath,e.useJWTAccessWithScope=this.useJWTAccessWithScope,e.defaultScopes=this.defaultScopes}getProjectId(e){if(e)this.getProjectIdAsync().then(n=>e(null,n),e);else return this.getProjectIdAsync()}async getProjectIdOptional(){try{return await this.getProjectId()}catch(e){if(e instanceof Error&&e.message===ut.GoogleAuthExceptionMessages.NO_PROJECT_ID_FOUND)return null;throw e}}async findAndCacheProjectId(){let e=null;if(e||=await this.getProductionProjectId(),e||=await this.getFileProjectId(),e||=await this.getDefaultServiceProjectId(),e||=await this.getGCEProjectId(),e||=await this.getExternalAccountClientProjectId(),e)return this._cachedProjectId=e,e;throw new Error(ut.GoogleAuthExceptionMessages.NO_PROJECT_ID_FOUND)}async getProjectIdAsync(){return this._cachedProjectId?this._cachedProjectId:(this._findProjectIdPromise||(this._findProjectIdPromise=this.findAndCacheProjectId()),this._findProjectIdPromise)}async getUniverseDomainFromMetadataServer(){let e;try{e=await gr.universe("universe-domain"),e||=ka.DEFAULT_UNIVERSE}catch(n){if(n&&n?.response?.status===404)e=ka.DEFAULT_UNIVERSE;else throw n}return e}async getUniverseDomain(){let e=(0,wf.originalOrCamelOptions)(this.clientOptions).get("universe_domain");try{e??=(await this.getClient()).universeDomain}catch{e??=ka.DEFAULT_UNIVERSE}return e}getAnyScopes(){return this.scopes||this.defaultScopes}getApplicationDefault(e={},n){let r;if(typeof e=="function"?n=e:r=e,n)this.getApplicationDefaultAsync(r).then(i=>n(null,i.credential,i.projectId),n);else return this.getApplicationDefaultAsync(r)}async getApplicationDefaultAsync(e={}){if(this.cachedCredential)return await this.#t(this.cachedCredential,null);let n;if(n=await this._tryGetApplicationCredentialsFromEnvironmentVariable(e),n)return n instanceof Dn.JWT?n.scopes=this.scopes:n instanceof _r.BaseExternalAccountClient&&(n.scopes=this.getAnyScopes()),await this.#t(n);if(n=await this._tryGetApplicationCredentialsFromWellKnownFile(e),n)return n instanceof Dn.JWT?n.scopes=this.scopes:n instanceof _r.BaseExternalAccountClient&&(n.scopes=this.getAnyScopes()),await this.#t(n);if(await this._checkIsGCE())return e.scopes=this.getAnyScopes(),await this.#t(new BT.Compute(e));throw new Error(ut.GoogleAuthExceptionMessages.NO_ADC_FOUND)}async#t(e,n=process.env.GOOGLE_CLOUD_QUOTA_PROJECT||null){let r=await this.getProjectIdOptional();return n&&(e.quotaProjectId=n),this.cachedCredential=e,{credential:e,projectId:r}}async _checkIsGCE(){return this.checkIsGCE===void 0&&(this.checkIsGCE=gr.getGCPResidency()||await gr.isAvailable()),this.checkIsGCE}async _tryGetApplicationCredentialsFromEnvironmentVariable(e){let n=process.env.GOOGLE_APPLICATION_CREDENTIALS||process.env.google_application_credentials;if(!n||n.length===0)return null;try{return await this._getApplicationCredentialsFromFilePath(n,e)}catch(r){throw r instanceof Error&&(r.message=`Unable to read the credential file specified by the GOOGLE_APPLICATION_CREDENTIALS environment variable: ${r.message}`),r}}async _tryGetApplicationCredentialsFromWellKnownFile(e){let n=process.env.CLOUDSDK_CONFIG;if(!n)if(this._isWindows())process.env.APPDATA&&(n=Mi.join(process.env.APPDATA,"gcloud"));else{let o=process.env.HOME;o&&(n=Mi.join(o,".config","gcloud"))}if(!n)return null;let r=Mi.join(n,"application_default_credentials.json");return mr.existsSync(r)?await this._getApplicationCredentialsFromFilePath(r,e):null}async _getApplicationCredentialsFromFilePath(e,n={}){if(!e||e.length===0)throw new Error("The file path is invalid.");try{if(e=mr.realpathSync(e),!mr.lstatSync(e).isFile())throw new Error}catch(i){throw i instanceof Error&&(i.message=`The file at ${e} does not exist, or it is not a file. ${i.message}`),i}let r=mr.createReadStream(e);return this.fromStream(r,n)}fromImpersonatedJSON(e){if(!e)throw new Error("Must pass in a JSON object containing an impersonated refresh token");if(e.type!==Mn.IMPERSONATED_ACCOUNT_TYPE)throw new Error(`The incoming JSON object does not have the "${Mn.IMPERSONATED_ACCOUNT_TYPE}" type`);if(!e.source_credentials)throw new Error("The incoming JSON object does not contain a source_credentials field");if(!e.service_account_impersonation_url)throw new Error("The incoming JSON object does not contain a service_account_impersonation_url field");let n=this.fromJSON(e.source_credentials);if(e.service_account_impersonation_url?.length>256)throw new RangeError(`Target principal is too long: ${e.service_account_impersonation_url}`);let r=/(?<target>[^/]+):(generateAccessToken|generateIdToken)$/.exec(e.service_account_impersonation_url)?.groups?.target;if(!r)throw new RangeError(`Cannot extract target principal from ${e.service_account_impersonation_url}`);let i=(this.scopes||e.scopes||this.defaultScopes)??[];return new Mn.Impersonated({...e,sourceClient:n,targetPrincipal:r,targetScopes:Array.isArray(i)?i:[i]})}fromJSON(e,n={}){let r,i=(0,wf.originalOrCamelOptions)(n).get("universe_domain");return e.type===Sf.USER_REFRESH_ACCOUNT_TYPE?(r=new Sf.UserRefreshClient(n),r.fromJSON(e)):e.type===Mn.IMPERSONATED_ACCOUNT_TYPE?r=this.fromImpersonatedJSON(e):e.type===_r.EXTERNAL_ACCOUNT_TYPE?(r=$T.ExternalAccountClient.fromJSON({...e,...n}),r.scopes=this.getAnyScopes()):e.type===If.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE?r=new If.ExternalAccountAuthorizedUserClient({...e,...n}):e.type===Da.GDCH_SERVICE_ACCOUNT_TYPE?(r=new Da.GdchClient(n),r.fromJSON(e)):(n.scopes=this.scopes,r=new Dn.JWT(n),this.setGapicJWTValues(r),r.fromJSON(e)),i&&(r.universeDomain=i),r}_cacheClientFromJSON(e,n){let r=this.fromJSON(e,n);return this.jsonContent=e,this.cachedCredential=r,r}fromStream(e,n={},r){let i={};if(typeof n=="function"?r=n:i=n,r)this.fromStreamAsync(e,i).then(o=>r(null,o),r);else return this.fromStreamAsync(e,i)}fromStreamAsync(e,n){return new Promise((r,i)=>{if(!e)throw new Error("Must pass in a stream containing the Google auth settings.");let o=[];e.setEncoding("utf8").on("error",i).on("data",a=>o.push(a)).on("end",()=>{try{try{let a=JSON.parse(o.join("")),u=this._cacheClientFromJSON(a,n);return r(u)}catch(a){if(!this.keyFilename)throw a;let u=new Dn.JWT({...this.clientOptions,keyFile:this.keyFilename});return this.cachedCredential=u,this.setGapicJWTValues(u),r(u)}}catch(a){return i(a)}})})}fromAPIKey(e,n={}){return new Dn.JWT({...n,apiKey:e})}_isWindows(){let e=qT.platform();return!!(e&&e.length>=3&&e.substring(0,3).toLowerCase()==="win")}async getDefaultServiceProjectId(){return new Promise(e=>{(0,LT.exec)("gcloud config config-helper --format json",(n,r)=>{if(!n&&r)try{let i=JSON.parse(r).configuration.properties.core.project;e(i);return}catch{}e(null)})})}getProductionProjectId(){return process.env.GCLOUD_PROJECT||process.env.GOOGLE_CLOUD_PROJECT||process.env.gcloud_project||process.env.google_cloud_project}async getFileProjectId(){if(this.cachedCredential)return this.cachedCredential.projectId;if(this.keyFilename){let n=await this.getClient();if(n&&n.projectId)return n.projectId}let e=await this._tryGetApplicationCredentialsFromEnvironmentVariable();return e?e.projectId:null}async getExternalAccountClientProjectId(){return!this.jsonContent||this.jsonContent.type!==_r.EXTERNAL_ACCOUNT_TYPE?null:await(await this.getClient()).getProjectId()}async getGCEProjectId(){try{return await gr.project("project-id")}catch{return null}}getCredentials(e){if(e)this.getCredentialsAsync().then(n=>e(null,n),e);else return this.getCredentialsAsync()}async getCredentialsAsync(){let e=await this.getClient();if(e instanceof Mn.Impersonated)return{client_email:e.getTargetPrincipal()};if(e instanceof _r.BaseExternalAccountClient){let n=e.getServiceAccountEmail();if(n)return{client_email:n,universe_domain:e.universeDomain}}if(this.jsonContent)return{client_email:this.jsonContent.client_email,private_key:this.jsonContent.private_key,universe_domain:this.jsonContent.universe_domain};if(await this._checkIsGCE()){let[n,r]=await Promise.all([gr.instance("service-accounts/default/email"),this.getUniverseDomain()]);return{client_email:n,universe_domain:r}}throw new Error(ut.GoogleAuthExceptionMessages.NO_CREDENTIALS_FOUND)}async getClient(){if(this.cachedCredential)return this.cachedCredential;this.#e=this.#e||this.#n();try{let e=await this.#e;if(e instanceof Da.GdchClient&&!e.apiAudience){let n=this.clientOptions,r=n.apiEndpoint||n.servicePath;if(r){let o=`${r.startsWith("http")?"":"https://"}${r}`.replace(/\/+$/,""),a=e.createWithGdchAudience(o);return this.cachedCredential=a,a}}return e}finally{this.#e=null}}async#n(){if(this.jsonContent)return this._cacheClientFromJSON(this.jsonContent,this.clientOptions);if(this.keyFilename){let e=Mi.resolve(this.keyFilename),n=mr.createReadStream(e);return await this.fromStreamAsync(n,this.clientOptions)}else if(this.apiKey){let e=await this.fromAPIKey(this.apiKey,this.clientOptions);e.scopes=this.scopes;let{credential:n}=await this.#t(e);return n}else{let{credential:e}=await this.getApplicationDefaultAsync(this.clientOptions);return e}}async getIdTokenClient(e){let n=await this.getClient();if(!("fetchIdToken"in n))throw new Error("Cannot fetch ID token in this environment, use GCE or set the GOOGLE_APPLICATION_CREDENTIALS environment variable to a service account credentials JSON file.");return new HT.IdTokenClient({targetAudience:e,idTokenProvider:n})}async getAccessToken(){return(await(await this.getClient()).getAccessToken()).token}async getRequestHeaders(e){return(await this.getClient()).getRequestHeaders(e)}async authorizeRequest(e={}){let n=e.url,i=await(await this.getClient()).getRequestHeaders(n);return e.headers=OT.Gaxios.mergeHeaders(e.headers,i),e}async fetch(...e){return(await this.getClient()).fetch(...e)}async request(e){return(await this.getClient()).request(e)}getEnv(){return(0,VT.getEnv)()}async sign(e,n){let r=await this.getClient(),i=await this.getUniverseDomain();if(n=n||`https://iamcredentials.${i}/v1/projects/-/serviceAccounts/`,r instanceof Mn.Impersonated)return(await r.sign(e)).signedBlob;let o=(0,FT.createCrypto)();if(r instanceof Dn.JWT&&r.key)return await o.sign(r.key,e);let a=await this.getCredentials();if(!a.client_email)throw new Error("Cannot sign data without `client_email`.");return this.signBlob(o,a.client_email,e,n)}async signBlob(e,n,r,i){let o=new URL(i+`${n}:signBlob`);return(await this.request({method:"POST",url:o.href,data:{payload:e.encodeBase64StringUtf8(r)},retry:!0,retryConfig:{httpMethodsToRetry:["POST"]}})).data.signedBlob}};ut.GoogleAuth=Ma});var Rf=F(Ui=>{"use strict";Object.defineProperty(Ui,"__esModule",{value:!0});Ui.IAMAuth=void 0;var Ua=class{selector;token;constructor(e,n){this.selector=e,this.token=n,this.selector=e,this.token=n}getRequestHeaders(){return{"x-goog-iam-authority-selector":this.selector,"x-goog-iam-authorization-token":this.token}}};Ui.IAMAuth=Ua});var Nf=F(Tt=>{"use strict";Object.defineProperty(Tt,"__esModule",{value:!0});Tt.DownscopedClient=Tt.EXPIRATION_TIME_OFFSET=Tt.MAX_ACCESS_BOUNDARY_RULES_COUNT=void 0;var JT=ke(),WT=W("stream"),ba=He(),XT=pi(),KT="urn:ietf:params:oauth:grant-type:token-exchange",YT="urn:ietf:params:oauth:token-type:access_token",zT="urn:ietf:params:oauth:token-type:access_token";Tt.MAX_ACCESS_BOUNDARY_RULES_COUNT=10;Tt.EXPIRATION_TIME_OFFSET=300*1e3;var Ga=class extends ba.AuthClient{authClient;credentialAccessBoundary;cachedDownscopedAccessToken;stsCredential;constructor(e,n={accessBoundary:{accessBoundaryRules:[]}}){if(super(e instanceof ba.AuthClient?{}:e),e instanceof ba.AuthClient?(this.authClient=e,this.credentialAccessBoundary=n):(this.authClient=e.authClient,this.credentialAccessBoundary=e.credentialAccessBoundary),this.credentialAccessBoundary.accessBoundary.accessBoundaryRules.length===0)throw new Error("At least one access boundary rule needs to be defined.");if(this.credentialAccessBoundary.accessBoundary.accessBoundaryRules.length>Tt.MAX_ACCESS_BOUNDARY_RULES_COUNT)throw new Error(`The provided access boundary has more than ${Tt.MAX_ACCESS_BOUNDARY_RULES_COUNT} access boundary rules.`);for(let r of this.credentialAccessBoundary.accessBoundary.accessBoundaryRules)if(r.availablePermissions.length===0)throw new Error("At least one permission should be defined in access boundary rules.");this.stsCredential=new XT.StsCredentials({tokenExchangeEndpoint:`https://sts.${this.universeDomain}/v1/token`}),this.cachedDownscopedAccessToken=null}setCredentials(e){if(!e.expiry_date)throw new Error("The access token expiry_date field is missing in the provided credentials.");super.setCredentials(e),this.cachedDownscopedAccessToken=e}async getAccessToken(){return(!this.cachedDownscopedAccessToken||this.isExpired(this.cachedDownscopedAccessToken))&&await this.refreshAccessTokenAsync(),{token:this.cachedDownscopedAccessToken.access_token,expirationTime:this.cachedDownscopedAccessToken.expiry_date,res:this.cachedDownscopedAccessToken.res}}async getRequestHeaders(){let e=await this.getAccessToken(),n=new Headers({authorization:`Bearer ${e.token}`});return this.addSharedMetadataHeaders(n)}request(e,n){if(n)this.requestAsync(e).then(r=>n(null,r),r=>n(r,r.response));else return this.requestAsync(e)}async requestAsync(e,n=!1){let r;try{let i=await this.getRequestHeaders();e.headers=JT.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,i),r=await this.transporter.request(e)}catch(i){let o=i.response;if(o){let a=o.status,u=o.config.data instanceof WT.Readable;if(!n&&(a===401||a===403)&&!u&&this.forceRefreshOnFailure)return await this.refreshAccessTokenAsync(),await this.requestAsync(e,!0)}throw i}return r}async refreshAccessTokenAsync(){let e=(await this.authClient.getAccessToken()).token,n={grantType:KT,requestedTokenType:YT,subjectToken:e,subjectTokenType:zT},r=await this.stsCredential.exchangeToken(n,void 0,this.credentialAccessBoundary),i=this.authClient.credentials?.expiry_date||null,o=r.expires_in?new Date().getTime()+r.expires_in*1e3:i;return this.cachedDownscopedAccessToken={access_token:r.access_token,expiry_date:o,res:r.res},this.credentials={},Object.assign(this.credentials,this.cachedDownscopedAccessToken),delete this.credentials.res,this.emit("tokens",{refresh_token:null,expiry_date:this.cachedDownscopedAccessToken.expiry_date,access_token:this.cachedDownscopedAccessToken.access_token,token_type:"Bearer",id_token:null}),this.cachedDownscopedAccessToken}isExpired(e){let n=new Date().getTime();return e.expiry_date?n>=e.expiry_date-this.eagerRefreshThresholdMillis:!1}};Tt.DownscopedClient=Ga});var xf=F(bi=>{"use strict";Object.defineProperty(bi,"__esModule",{value:!0});bi.PassThroughClient=void 0;var QT=He(),La=class extends QT.AuthClient{async request(e){return this.transporter.request(e)}async getAccessToken(){return{}}async getRequestHeaders(){return new Headers}};bi.PassThroughClient=La});var Gf=F(J=>{"use strict";var ZT=J&&J.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(e,n);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,i)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),jT=J&&J.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&ZT(e,t,n)};Object.defineProperty(J,"__esModule",{value:!0});J.GoogleAuth=J.auth=J.GDCH_SERVICE_ACCOUNT_TYPE=J.GdchClient=J.PassThroughClient=J.ExternalAccountAuthorizedUserClient=J.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE=J.ExecutableError=J.PluggableAuthClient=J.DownscopedClient=J.BaseExternalAccountClient=J.ExternalAccountClient=J.IdentityPoolClient=J.AwsRequestSigner=J.AwsClient=J.UserRefreshClient=J.LoginTicket=J.ClientAuthentication=J.OAuth2Client=J.CodeChallengeMethod=J.Impersonated=J.JWT=J.JWTAccess=J.IdTokenClient=J.IAMAuth=J.GCPEnv=J.Compute=J.DEFAULT_UNIVERSE=J.AuthClient=J.gaxios=J.gcpMetadata=void 0;var kf=Pf();Object.defineProperty(J,"GoogleAuth",{enumerable:!0,get:function(){return kf.GoogleAuth}});J.gcpMetadata=or();J.gaxios=ke();var Df=He();Object.defineProperty(J,"AuthClient",{enumerable:!0,get:function(){return Df.AuthClient}});Object.defineProperty(J,"DEFAULT_UNIVERSE",{enumerable:!0,get:function(){return Df.DEFAULT_UNIVERSE}});var eA=gs();Object.defineProperty(J,"Compute",{enumerable:!0,get:function(){return eA.Compute}});var tA=Es();Object.defineProperty(J,"GCPEnv",{enumerable:!0,get:function(){return tA.GCPEnv}});var nA=Rf();Object.defineProperty(J,"IAMAuth",{enumerable:!0,get:function(){return nA.IAMAuth}});var rA=ys();Object.defineProperty(J,"IdTokenClient",{enumerable:!0,get:function(){return rA.IdTokenClient}});var iA=Hs();Object.defineProperty(J,"JWTAccess",{enumerable:!0,get:function(){return iA.JWTAccess}});var oA=$s();Object.defineProperty(J,"JWT",{enumerable:!0,get:function(){return oA.JWT}});var sA=Ks();Object.defineProperty(J,"Impersonated",{enumerable:!0,get:function(){return sA.Impersonated}});var Oa=Ot();Object.defineProperty(J,"CodeChallengeMethod",{enumerable:!0,get:function(){return Oa.CodeChallengeMethod}});Object.defineProperty(J,"OAuth2Client",{enumerable:!0,get:function(){return Oa.OAuth2Client}});Object.defineProperty(J,"ClientAuthentication",{enumerable:!0,get:function(){return Oa.ClientAuthentication}});var aA=fs();Object.defineProperty(J,"LoginTicket",{enumerable:!0,get:function(){return aA.LoginTicket}});var lA=Ws();Object.defineProperty(J,"UserRefreshClient",{enumerable:!0,get:function(){return lA.UserRefreshClient}});var uA=pa();Object.defineProperty(J,"AwsClient",{enumerable:!0,get:function(){return uA.AwsClient}});var cA=ca();Object.defineProperty(J,"AwsRequestSigner",{enumerable:!0,get:function(){return cA.AwsRequestSigner}});var dA=la();Object.defineProperty(J,"IdentityPoolClient",{enumerable:!0,get:function(){return dA.IdentityPoolClient}});var fA=Ia();Object.defineProperty(J,"ExternalAccountClient",{enumerable:!0,get:function(){return fA.ExternalAccountClient}});var pA=Bt();Object.defineProperty(J,"BaseExternalAccountClient",{enumerable:!0,get:function(){return pA.BaseExternalAccountClient}});var hA=Nf();Object.defineProperty(J,"DownscopedClient",{enumerable:!0,get:function(){return hA.DownscopedClient}});var Mf=Ca();Object.defineProperty(J,"PluggableAuthClient",{enumerable:!0,get:function(){return Mf.PluggableAuthClient}});Object.defineProperty(J,"ExecutableError",{enumerable:!0,get:function(){return Mf.ExecutableError}});var Uf=Ra();Object.defineProperty(J,"EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE",{enumerable:!0,get:function(){return Uf.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE}});Object.defineProperty(J,"ExternalAccountAuthorizedUserClient",{enumerable:!0,get:function(){return Uf.ExternalAccountAuthorizedUserClient}});var mA=xf();Object.defineProperty(J,"PassThroughClient",{enumerable:!0,get:function(){return mA.PassThroughClient}});var bf=xa();Object.defineProperty(J,"GdchClient",{enumerable:!0,get:function(){return bf.GdchClient}});Object.defineProperty(J,"GDCH_SERVICE_ACCOUNT_TYPE",{enumerable:!0,get:function(){return bf.GDCH_SERVICE_ACCOUNT_TYPE}});jT(Fs(),J);var gA=new kf.GoogleAuth;J.auth=gA});var Rt=F((DD,qf)=>{"use strict";var Lf=["nodebuffer","arraybuffer","fragments"],Of=typeof Blob<"u";Of&&Lf.push("blob");qf.exports={BINARY_TYPES:Lf,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:Of,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var yr=F((MD,Gi)=>{"use strict";var{EMPTY_BUFFER:_A}=Rt(),qa=Buffer[Symbol.species];function yA(t,e){if(t.length===0)return _A;if(t.length===1)return t[0];let n=Buffer.allocUnsafe(e),r=0;for(let i=0;i<t.length;i++){let o=t[i];n.set(o,r),r+=o.length}return r<e?new qa(n.buffer,n.byteOffset,r):n}function Ff(t,e,n,r,i){for(let o=0;o<i;o++)n[r+o]=t[o]^e[o&3]}function Bf(t,e){for(let n=0;n<t.length;n++)t[n]^=e[n&3]}function EA(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function Fa(t){if(Fa.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new qa(t):ArrayBuffer.isView(t)?e=new qa(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),Fa.readOnly=!1),e}Gi.exports={concat:yA,mask:Ff,toArrayBuffer:EA,toBuffer:Fa,unmask:Bf};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=W("bufferutil");Gi.exports.mask=function(e,n,r,i,o){o<48?Ff(e,n,r,i,o):t.mask(e,n,r,i,o)},Gi.exports.unmask=function(e,n){e.length<32?Bf(e,n):t.unmask(e,n)}}catch{}});var $f=F((UD,Vf)=>{"use strict";var Hf=Symbol("kDone"),Ba=Symbol("kRun"),Ha=class{constructor(e){this[Hf]=()=>{this.pending--,this[Ba]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[Ba]()}[Ba](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[Hf])}}};Vf.exports=Ha});var Gn=F((bD,Kf)=>{"use strict";var Er=W("zlib"),Jf=yr(),vA=$f(),{kStatusCode:Wf}=Rt(),TA=Buffer[Symbol.species],AA=Buffer.from([0,0,255,255]),Oi=Symbol("permessage-deflate"),Nt=Symbol("total-length"),Un=Symbol("callback"),Vt=Symbol("buffers"),bn=Symbol("error"),Li,Va=class{constructor(e){if(this._options=e||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._maxPayload=this._options.maxPayload|0,this._isServer=!!this._options.isServer,this._deflate=null,this._inflate=null,this.params=null,!Li){let n=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Li=new vA(n)}}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==null&&(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(),this._inflate=null),this._deflate){let e=this._deflate[Un];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let n=this._options,r=e.find(i=>!(n.serverNoContextTakeover===!1&&i.server_no_context_takeover||i.server_max_window_bits&&(n.serverMaxWindowBits===!1||typeof n.serverMaxWindowBits=="number"&&n.serverMaxWindowBits>i.server_max_window_bits)||typeof n.clientMaxWindowBits=="number"&&!i.client_max_window_bits));if(!r)throw new Error("None of the extension offers can be accepted");return n.serverNoContextTakeover&&(r.server_no_context_takeover=!0),n.clientNoContextTakeover&&(r.client_no_context_takeover=!0),typeof n.serverMaxWindowBits=="number"&&(r.server_max_window_bits=n.serverMaxWindowBits),typeof n.clientMaxWindowBits=="number"?r.client_max_window_bits=n.clientMaxWindowBits:(r.client_max_window_bits===!0||n.clientMaxWindowBits===!1)&&delete r.client_max_window_bits,r}acceptAsClient(e){let n=e[0];if(this._options.clientNoContextTakeover===!1&&n.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!n.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(n.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&n.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return n}normalizeParams(e){return e.forEach(n=>{Object.keys(n).forEach(r=>{let i=n[r];if(i.length>1)throw new Error(`Parameter "${r}" must have only a single value`);if(i=i[0],r==="client_max_window_bits"){if(i!==!0){let o=+i;if(!Number.isInteger(o)||o<8||o>15)throw new TypeError(`Invalid value for parameter "${r}": ${i}`);i=o}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${r}": ${i}`)}else if(r==="server_max_window_bits"){let o=+i;if(!Number.isInteger(o)||o<8||o>15)throw new TypeError(`Invalid value for parameter "${r}": ${i}`);i=o}else if(r==="client_no_context_takeover"||r==="server_no_context_takeover"){if(i!==!0)throw new TypeError(`Invalid value for parameter "${r}": ${i}`)}else throw new Error(`Unknown parameter "${r}"`);n[r]=i})}),e}decompress(e,n,r){Li.add(i=>{this._decompress(e,n,(o,a)=>{i(),r(o,a)})})}compress(e,n,r){Li.add(i=>{this._compress(e,n,(o,a)=>{i(),r(o,a)})})}_decompress(e,n,r){let i=this._isServer?"client":"server";if(!this._inflate){let o=`${i}_max_window_bits`,a=typeof this.params[o]!="number"?Er.Z_DEFAULT_WINDOWBITS:this.params[o];this._inflate=Er.createInflateRaw({...this._options.zlibInflateOptions,windowBits:a}),this._inflate[Oi]=this,this._inflate[Nt]=0,this._inflate[Vt]=[],this._inflate.on("error",SA),this._inflate.on("data",Xf)}this._inflate[Un]=r,this._inflate.write(e),n&&this._inflate.write(AA),this._inflate.flush(()=>{let o=this._inflate[bn];if(o){this._inflate.close(),this._inflate=null,r(o);return}let a=Jf.concat(this._inflate[Vt],this._inflate[Nt]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[Nt]=0,this._inflate[Vt]=[],n&&this.params[`${i}_no_context_takeover`]&&this._inflate.reset()),r(null,a)})}_compress(e,n,r){let i=this._isServer?"server":"client";if(!this._deflate){let o=`${i}_max_window_bits`,a=typeof this.params[o]!="number"?Er.Z_DEFAULT_WINDOWBITS:this.params[o];this._deflate=Er.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:a}),this._deflate[Nt]=0,this._deflate[Vt]=[],this._deflate.on("data",CA)}this._deflate[Un]=r,this._deflate.write(e),this._deflate.flush(Er.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let o=Jf.concat(this._deflate[Vt],this._deflate[Nt]);n&&(o=new TA(o.buffer,o.byteOffset,o.length-4)),this._deflate[Un]=null,this._deflate[Nt]=0,this._deflate[Vt]=[],n&&this.params[`${i}_no_context_takeover`]&&this._deflate.reset(),r(null,o)})}};Kf.exports=Va;function CA(t){this[Vt].push(t),this[Nt]+=t.length}function Xf(t){if(this[Nt]+=t.length,this[Oi]._maxPayload<1||this[Nt]<=this[Oi]._maxPayload){this[Vt].push(t);return}this[bn]=new RangeError("Max payload size exceeded"),this[bn].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[bn][Wf]=1009,this.removeListener("data",Xf),this.reset()}function SA(t){if(this[Oi]._inflate=null,this[bn]){this[Un](this[bn]);return}t[Wf]=1007,this[Un](t)}});var Ln=F((GD,qi)=>{"use strict";var{isUtf8:Yf}=W("buffer"),{hasBlob:IA}=Rt(),wA=[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 PA(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function $a(t){let e=t.length,n=0;for(;n<e;)if((t[n]&128)===0)n++;else if((t[n]&224)===192){if(n+1===e||(t[n+1]&192)!==128||(t[n]&254)===192)return!1;n+=2}else if((t[n]&240)===224){if(n+2>=e||(t[n+1]&192)!==128||(t[n+2]&192)!==128||t[n]===224&&(t[n+1]&224)===128||t[n]===237&&(t[n+1]&224)===160)return!1;n+=3}else if((t[n]&248)===240){if(n+3>=e||(t[n+1]&192)!==128||(t[n+2]&192)!==128||(t[n+3]&192)!==128||t[n]===240&&(t[n+1]&240)===128||t[n]===244&&t[n+1]>143||t[n]>244)return!1;n+=4}else return!1;return!0}function RA(t){return IA&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}qi.exports={isBlob:RA,isValidStatusCode:PA,isValidUTF8:$a,tokenChars:wA};if(Yf)qi.exports.isValidUTF8=function(t){return t.length<24?$a(t):Yf(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=W("utf-8-validate");qi.exports.isValidUTF8=function(e){return e.length<32?$a(e):t(e)}}catch{}});var Ya=F((LD,np)=>{"use strict";var{Writable:NA}=W("stream"),zf=Gn(),{BINARY_TYPES:xA,EMPTY_BUFFER:Qf,kStatusCode:kA,kWebSocket:DA}=Rt(),{concat:Ja,toArrayBuffer:MA,unmask:UA}=yr(),{isValidStatusCode:bA,isValidUTF8:Zf}=Ln(),Fi=Buffer[Symbol.species],je=0,jf=1,ep=2,tp=3,Wa=4,Xa=5,Bi=6,Ka=class extends NA{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||xA[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxBufferedChunks=e.maxBufferedChunks|0,this._maxFragments=e.maxFragments|0,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[DA]=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._numFragments=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=je}_write(e,n,r){if(this._opcode===8&&this._state==je)return r();if(this._maxBufferedChunks>0&&this._buffers.length>=this._maxBufferedChunks){r(this.createError(RangeError,"Too many buffered chunks",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS"));return}this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(r)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let r=this._buffers[0];return this._buffers[0]=new Fi(r.buffer,r.byteOffset+e,r.length-e),new Fi(r.buffer,r.byteOffset,e)}let n=Buffer.allocUnsafe(e);do{let r=this._buffers[0],i=n.length-e;e>=r.length?n.set(this._buffers.shift(),i):(n.set(new Uint8Array(r.buffer,r.byteOffset,e),i),this._buffers[0]=new Fi(r.buffer,r.byteOffset+e,r.length-e)),e-=r.length}while(e>0);return n}startLoop(e){this._loop=!0;do switch(this._state){case je:this.getInfo(e);break;case jf:this.getPayloadLength16(e);break;case ep:this.getPayloadLength64(e);break;case tp:this.getMask();break;case Wa:this.getData(e);break;case Xa:case Bi:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let n=this.consume(2);if((n[0]&48)!==0){let i=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(i);return}let r=(n[0]&64)===64;if(r&&!this._extensions[zf.extensionName]){let i=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(i);return}if(this._fin=(n[0]&128)===128,this._opcode=n[0]&15,this._payloadLength=n[1]&127,this._opcode===0){if(r){let i=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(i);return}if(!this._fragmented){let i=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(i);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let i=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(i);return}this._compressed=r}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let i=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(i);return}if(r){let i=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(i);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let i=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(i);return}}else{let i=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(i);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(n[1]&128)===128,this._isServer){if(!this._masked){let i=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(i);return}}else if(this._masked){let i=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(i);return}this._payloadLength===126?this._state=jf:this._payloadLength===127?this._state=ep: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 n=this.consume(8),r=n.readUInt32BE(0);if(r>Math.pow(2,21)-1){let i=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(i);return}this._payloadLength=r*Math.pow(2,32)+n.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let n=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(n);return}this._masked?this._state=tp:this._state=Wa}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=Wa}getData(e){let n=Qf;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}n=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&UA(n,this._mask)}if(this._opcode>7){this.controlMessage(n,e);return}if(this._maxFragments>0&&++this._numFragments>this._maxFragments){let r=this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");e(r);return}if(this._compressed){this._state=Xa,this.decompress(n,e);return}n.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(n)),this.dataMessage(e)}decompress(e,n){this._extensions[zf.extensionName].decompress(e,this._fin,(i,o)=>{if(i)return n(i);if(o.length){if(this._messageLength+=o.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let a=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");n(a);return}this._fragments.push(o)}this.dataMessage(n),this._state===je&&this.startLoop(n)})}dataMessage(e){if(!this._fin){this._state=je;return}let n=this._messageLength,r=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._numFragments=0,this._fragments=[],this._opcode===2){let i;this._binaryType==="nodebuffer"?i=Ja(r,n):this._binaryType==="arraybuffer"?i=MA(Ja(r,n)):this._binaryType==="blob"?i=new Blob(r):i=r,this._allowSynchronousEvents?(this.emit("message",i,!0),this._state=je):(this._state=Bi,setImmediate(()=>{this.emit("message",i,!0),this._state=je,this.startLoop(e)}))}else{let i=Ja(r,n);if(!this._skipUTF8Validation&&!Zf(i)){let o=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(o);return}this._state===Xa||this._allowSynchronousEvents?(this.emit("message",i,!1),this._state=je):(this._state=Bi,setImmediate(()=>{this.emit("message",i,!1),this._state=je,this.startLoop(e)}))}}controlMessage(e,n){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,Qf),this.end();else{let r=e.readUInt16BE(0);if(!bA(r)){let o=this.createError(RangeError,`invalid status code ${r}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");n(o);return}let i=new Fi(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!Zf(i)){let o=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");n(o);return}this._loop=!1,this.emit("conclude",r,i),this.end()}this._state=je;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=je):(this._state=Bi,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=je,this.startLoop(n)}))}createError(e,n,r,i,o){this._loop=!1,this._errored=!0;let a=new e(r?`Invalid WebSocket frame: ${n}`:n);return Error.captureStackTrace(a,this.createError),a.code=o,a[kA]=i,a}};np.exports=Ka});var Za=F((qD,op)=>{"use strict";var{Duplex:OD}=W("stream"),{randomFillSync:GA}=W("crypto"),{types:{isUint8Array:LA}}=W("util"),rp=Gn(),{EMPTY_BUFFER:OA,kWebSocket:qA,NOOP:FA}=Rt(),{isBlob:On,isValidStatusCode:BA}=Ln(),{mask:ip,toBuffer:ln}=yr(),et=Symbol("kByteLength"),HA=Buffer.alloc(4),Hi=8*1024,un,qn=Hi,ct=0,VA=1,$A=2,za=class t{constructor(e,n,r){this._extensions=n||{},r&&(this._generateMask=r,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=ct,this.onerror=FA,this[qA]=void 0}static frame(e,n){let r,i=!1,o=2,a=!1;n.mask&&(r=n.maskBuffer||HA,n.generateMask?n.generateMask(r):(qn===Hi&&(un===void 0&&(un=Buffer.alloc(Hi)),GA(un,0,Hi),qn=0),r[0]=un[qn++],r[1]=un[qn++],r[2]=un[qn++],r[3]=un[qn++]),a=(r[0]|r[1]|r[2]|r[3])===0,o=6);let u;typeof e=="string"?(!n.mask||a)&&n[et]!==void 0?u=n[et]:(e=Buffer.from(e),u=e.length):(u=e.length,i=n.mask&&n.readOnly&&!a);let c=u;u>=65536?(o+=8,c=127):u>125&&(o+=2,c=126);let d=Buffer.allocUnsafe(i?u+o:o);return d[0]=n.fin?n.opcode|128:n.opcode,n.rsv1&&(d[0]|=64),d[1]=c,c===126?d.writeUInt16BE(u,2):c===127&&(d[2]=d[3]=0,d.writeUIntBE(u,4,6)),n.mask?(d[1]|=128,d[o-4]=r[0],d[o-3]=r[1],d[o-2]=r[2],d[o-1]=r[3],a?[d,e]:i?(ip(e,r,d,o,u),[d]):(ip(e,r,e,0,u),[d,e])):[d,e]}close(e,n,r,i){let o;if(e===void 0)o=OA;else{if(typeof e!="number"||!BA(e))throw new TypeError("First argument must be a valid error code number");if(n===void 0||!n.length)o=Buffer.allocUnsafe(2),o.writeUInt16BE(e,0);else{let u=Buffer.byteLength(n);if(u>123)throw new RangeError("The message must not be greater than 123 bytes");if(o=Buffer.allocUnsafe(2+u),o.writeUInt16BE(e,0),typeof n=="string")o.write(n,2);else if(LA(n))o.set(n,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}let a={[et]:o.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==ct?this.enqueue([this.dispatch,o,!1,a,i]):this.sendFrame(t.frame(o,a),i)}ping(e,n,r){let i,o;if(typeof e=="string"?(i=Buffer.byteLength(e),o=!1):On(e)?(i=e.size,o=!1):(e=ln(e),i=e.length,o=ln.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");let a={[et]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:o,rsv1:!1};On(e)?this._state!==ct?this.enqueue([this.getBlobData,e,!1,a,r]):this.getBlobData(e,!1,a,r):this._state!==ct?this.enqueue([this.dispatch,e,!1,a,r]):this.sendFrame(t.frame(e,a),r)}pong(e,n,r){let i,o;if(typeof e=="string"?(i=Buffer.byteLength(e),o=!1):On(e)?(i=e.size,o=!1):(e=ln(e),i=e.length,o=ln.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");let a={[et]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:o,rsv1:!1};On(e)?this._state!==ct?this.enqueue([this.getBlobData,e,!1,a,r]):this.getBlobData(e,!1,a,r):this._state!==ct?this.enqueue([this.dispatch,e,!1,a,r]):this.sendFrame(t.frame(e,a),r)}send(e,n,r){let i=this._extensions[rp.extensionName],o=n.binary?2:1,a=n.compress,u,c;typeof e=="string"?(u=Buffer.byteLength(e),c=!1):On(e)?(u=e.size,c=!1):(e=ln(e),u=e.length,c=ln.readOnly),this._firstFragment?(this._firstFragment=!1,a&&i&&i.params[i._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(a=u>=i._threshold),this._compress=a):(a=!1,o=0),n.fin&&(this._firstFragment=!0);let d={[et]:u,fin:n.fin,generateMask:this._generateMask,mask:n.mask,maskBuffer:this._maskBuffer,opcode:o,readOnly:c,rsv1:a};On(e)?this._state!==ct?this.enqueue([this.getBlobData,e,this._compress,d,r]):this.getBlobData(e,this._compress,d,r):this._state!==ct?this.enqueue([this.dispatch,e,this._compress,d,r]):this.dispatch(e,this._compress,d,r)}getBlobData(e,n,r,i){this._bufferedBytes+=r[et],this._state=$A,e.arrayBuffer().then(o=>{if(this._socket.destroyed){let u=new Error("The socket was closed while the blob was being read");process.nextTick(Qa,this,u,i);return}this._bufferedBytes-=r[et];let a=ln(o);n?this.dispatch(a,n,r,i):(this._state=ct,this.sendFrame(t.frame(a,r),i),this.dequeue())}).catch(o=>{process.nextTick(JA,this,o,i)})}dispatch(e,n,r,i){if(!n){this.sendFrame(t.frame(e,r),i);return}let o=this._extensions[rp.extensionName];this._bufferedBytes+=r[et],this._state=VA,o.compress(e,r.fin,(a,u)=>{if(this._socket.destroyed){let c=new Error("The socket was closed while data was being compressed");Qa(this,c,i);return}this._bufferedBytes-=r[et],this._state=ct,r.readOnly=!1,this.sendFrame(t.frame(u,r),i),this.dequeue()})}dequeue(){for(;this._state===ct&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][et],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][et],this._queue.push(e)}sendFrame(e,n){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],n),this._socket.uncork()):this._socket.write(e[0],n)}};op.exports=za;function Qa(t,e,n){typeof n=="function"&&n(e);for(let r=0;r<t._queue.length;r++){let i=t._queue[r],o=i[i.length-1];typeof o=="function"&&o(e)}}function JA(t,e,n){Qa(t,e,n),t.onerror(e)}});var hp=F((FD,pp)=>{"use strict";var{kForOnEventAttribute:vr,kListener:ja}=Rt(),sp=Symbol("kCode"),ap=Symbol("kData"),lp=Symbol("kError"),up=Symbol("kMessage"),cp=Symbol("kReason"),Fn=Symbol("kTarget"),dp=Symbol("kType"),fp=Symbol("kWasClean"),xt=class{constructor(e){this[Fn]=null,this[dp]=e}get target(){return this[Fn]}get type(){return this[dp]}};Object.defineProperty(xt.prototype,"target",{enumerable:!0});Object.defineProperty(xt.prototype,"type",{enumerable:!0});var cn=class extends xt{constructor(e,n={}){super(e),this[sp]=n.code===void 0?0:n.code,this[cp]=n.reason===void 0?"":n.reason,this[fp]=n.wasClean===void 0?!1:n.wasClean}get code(){return this[sp]}get reason(){return this[cp]}get wasClean(){return this[fp]}};Object.defineProperty(cn.prototype,"code",{enumerable:!0});Object.defineProperty(cn.prototype,"reason",{enumerable:!0});Object.defineProperty(cn.prototype,"wasClean",{enumerable:!0});var Bn=class extends xt{constructor(e,n={}){super(e),this[lp]=n.error===void 0?null:n.error,this[up]=n.message===void 0?"":n.message}get error(){return this[lp]}get message(){return this[up]}};Object.defineProperty(Bn.prototype,"error",{enumerable:!0});Object.defineProperty(Bn.prototype,"message",{enumerable:!0});var Tr=class extends xt{constructor(e,n={}){super(e),this[ap]=n.data===void 0?null:n.data}get data(){return this[ap]}};Object.defineProperty(Tr.prototype,"data",{enumerable:!0});var WA={addEventListener(t,e,n={}){for(let i of this.listeners(t))if(!n[vr]&&i[ja]===e&&!i[vr])return;let r;if(t==="message")r=function(o,a){let u=new Tr("message",{data:a?o:o.toString()});u[Fn]=this,Vi(e,this,u)};else if(t==="close")r=function(o,a){let u=new cn("close",{code:o,reason:a.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});u[Fn]=this,Vi(e,this,u)};else if(t==="error")r=function(o){let a=new Bn("error",{error:o,message:o.message});a[Fn]=this,Vi(e,this,a)};else if(t==="open")r=function(){let o=new xt("open");o[Fn]=this,Vi(e,this,o)};else return;r[vr]=!!n[vr],r[ja]=e,n.once?this.once(t,r):this.on(t,r)},removeEventListener(t,e){for(let n of this.listeners(t))if(n[ja]===e&&!n[vr]){this.removeListener(t,n);break}}};pp.exports={CloseEvent:cn,ErrorEvent:Bn,Event:xt,EventTarget:WA,MessageEvent:Tr};function Vi(t,e,n){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,n):t.call(e,n)}});var $i=F((BD,mp)=>{"use strict";var{tokenChars:Ar}=Ln();function At(t,e,n){t[e]===void 0?t[e]=[n]:t[e].push(n)}function XA(t){let e=Object.create(null),n=Object.create(null),r=!1,i=!1,o=!1,a,u,c=-1,d=-1,f=-1,p=0;for(;p<t.length;p++)if(d=t.charCodeAt(p),a===void 0)if(f===-1&&Ar[d]===1)c===-1&&(c=p);else if(p!==0&&(d===32||d===9))f===-1&&c!==-1&&(f=p);else if(d===59||d===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p);let m=t.slice(c,f);d===44?(At(e,m,n),n=Object.create(null)):a=m,c=f=-1}else throw new SyntaxError(`Unexpected character at index ${p}`);else if(u===void 0)if(f===-1&&Ar[d]===1)c===-1&&(c=p);else if(d===32||d===9)f===-1&&c!==-1&&(f=p);else if(d===59||d===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p),At(n,t.slice(c,f),!0),d===44&&(At(e,a,n),n=Object.create(null),a=void 0),c=f=-1}else if(d===61&&c!==-1&&f===-1)u=t.slice(c,p),c=f=-1;else throw new SyntaxError(`Unexpected character at index ${p}`);else if(i){if(Ar[d]!==1)throw new SyntaxError(`Unexpected character at index ${p}`);c===-1?c=p:r||(r=!0),i=!1}else if(o)if(Ar[d]===1)c===-1&&(c=p);else if(d===34&&c!==-1)o=!1,f=p;else if(d===92)i=!0;else throw new SyntaxError(`Unexpected character at index ${p}`);else if(d===34&&t.charCodeAt(p-1)===61)o=!0;else if(f===-1&&Ar[d]===1)c===-1&&(c=p);else if(c!==-1&&(d===32||d===9))f===-1&&(f=p);else if(d===59||d===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p);let m=t.slice(c,f);r&&(m=m.replace(/\\/g,""),r=!1),At(n,u,m),d===44&&(At(e,a,n),n=Object.create(null),a=void 0),u=void 0,c=f=-1}else throw new SyntaxError(`Unexpected character at index ${p}`);if(c===-1||o||d===32||d===9)throw new SyntaxError("Unexpected end of input");f===-1&&(f=p);let h=t.slice(c,f);return a===void 0?At(e,h,n):(u===void 0?At(n,h,!0):r?At(n,u,h.replace(/\\/g,"")):At(n,u,h),At(e,a,n)),e}function KA(t){return Object.keys(t).map(e=>{let n=t[e];return Array.isArray(n)||(n=[n]),n.map(r=>[e].concat(Object.keys(r).map(i=>{let o=r[i];return Array.isArray(o)||(o=[o]),o.map(a=>a===!0?i:`${i}=${a}`).join("; ")})).join("; ")).join(", ")}).join(", ")}mp.exports={format:KA,parse:XA}});var Ki=F(($D,Pp)=>{"use strict";var YA=W("events"),zA=W("https"),QA=W("http"),yp=W("net"),ZA=W("tls"),{randomBytes:jA,createHash:eC}=W("crypto"),{Duplex:HD,Readable:VD}=W("stream"),{URL:el}=W("url"),$t=Gn(),tC=Ya(),nC=Za(),{isBlob:rC}=Ln(),{BINARY_TYPES:gp,CLOSE_TIMEOUT:iC,EMPTY_BUFFER:Ji,GUID:oC,kForOnEventAttribute:tl,kListener:sC,kStatusCode:aC,kWebSocket:Ne,NOOP:Ep}=Rt(),{EventTarget:{addEventListener:lC,removeEventListener:uC}}=hp(),{format:cC,parse:dC}=$i(),{toBuffer:fC}=yr(),vp=Symbol("kAborted"),nl=[8,13],kt=["CONNECTING","OPEN","CLOSING","CLOSED"],pC=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,Te=class t extends YA{constructor(e,n,r){super(),this._binaryType=gp[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Ji,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=t.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,e!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,n===void 0?n=[]:Array.isArray(n)||(typeof n=="object"&&n!==null?(r=n,n=[]):n=[n]),Tp(this,e,n,r)):(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){gp.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(e,n,r){let i=new tC({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxBufferedChunks:r.maxBufferedChunks,maxFragments:r.maxFragments,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),o=new nC(e,this._extensions,r.generateMask);this._receiver=i,this._sender=o,this._socket=e,i[Ne]=this,o[Ne]=this,e[Ne]=this,i.on("conclude",gC),i.on("drain",_C),i.on("error",yC),i.on("message",EC),i.on("ping",vC),i.on("pong",TC),o.onerror=AC,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),n.length>0&&e.unshift(n),e.on("close",Sp),e.on("data",Xi),e.on("end",Ip),e.on("error",wp),this._readyState=t.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[$t.extensionName]&&this._extensions[$t.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,n){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){$e(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===t.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=t.CLOSING,this._sender.close(e,n,!this._isServer,r=>{r||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),Cp(this)}}pause(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,n,r){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(r=e,e=n=void 0):typeof n=="function"&&(r=n,n=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){rl(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.ping(e||Ji,n,r)}pong(e,n,r){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(r=e,e=n=void 0):typeof n=="function"&&(r=n,n=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){rl(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.pong(e||Ji,n,r)}resume(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,n,r){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof n=="function"&&(r=n,n={}),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){rl(this,e,r);return}let i={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[$t.extensionName]||(i.compress=!1),this._sender.send(e||Ji,i,r)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){$e(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(Te,"CONNECTING",{enumerable:!0,value:kt.indexOf("CONNECTING")});Object.defineProperty(Te.prototype,"CONNECTING",{enumerable:!0,value:kt.indexOf("CONNECTING")});Object.defineProperty(Te,"OPEN",{enumerable:!0,value:kt.indexOf("OPEN")});Object.defineProperty(Te.prototype,"OPEN",{enumerable:!0,value:kt.indexOf("OPEN")});Object.defineProperty(Te,"CLOSING",{enumerable:!0,value:kt.indexOf("CLOSING")});Object.defineProperty(Te.prototype,"CLOSING",{enumerable:!0,value:kt.indexOf("CLOSING")});Object.defineProperty(Te,"CLOSED",{enumerable:!0,value:kt.indexOf("CLOSED")});Object.defineProperty(Te.prototype,"CLOSED",{enumerable:!0,value:kt.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(Te.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(Te.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[tl])return e[sC];return null},set(e){for(let n of this.listeners(t))if(n[tl]){this.removeListener(t,n);break}typeof e=="function"&&this.addEventListener(t,e,{[tl]:!0})}})});Te.prototype.addEventListener=lC;Te.prototype.removeEventListener=uC;Pp.exports=Te;function Tp(t,e,n,r){let i={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:iC,protocolVersion:nl[1],maxBufferedChunks:262144,maxFragments:16384,maxPayload:104857600,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(t._autoPong=i.autoPong,t._closeTimeout=i.closeTimeout,!nl.includes(i.protocolVersion))throw new RangeError(`Unsupported protocol version: ${i.protocolVersion} (supported versions: ${nl.join(", ")})`);let o;if(e instanceof el)o=e;else try{o=new el(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}o.protocol==="http:"?o.protocol="ws:":o.protocol==="https:"&&(o.protocol="wss:"),t._url=o.href;let a=o.protocol==="wss:",u=o.protocol==="ws+unix:",c;if(o.protocol!=="ws:"&&!a&&!u?c=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:u&&!o.pathname?c="The URL's pathname is empty":o.hash&&(c="The URL contains a fragment identifier"),c){let g=new SyntaxError(c);if(t._redirects===0)throw g;Wi(t,g);return}let d=a?443:80,f=jA(16).toString("base64"),p=a?zA.request:QA.request,h=new Set,m;if(i.createConnection=i.createConnection||(a?mC:hC),i.defaultPort=i.defaultPort||d,i.port=o.port||d,i.host=o.hostname.startsWith("[")?o.hostname.slice(1,-1):o.hostname,i.headers={...i.headers,"Sec-WebSocket-Version":i.protocolVersion,"Sec-WebSocket-Key":f,Connection:"Upgrade",Upgrade:"websocket"},i.path=o.pathname+o.search,i.timeout=i.handshakeTimeout,i.perMessageDeflate&&(m=new $t({...i.perMessageDeflate,isServer:!1,maxPayload:i.maxPayload}),i.headers["Sec-WebSocket-Extensions"]=cC({[$t.extensionName]:m.offer()})),n.length){for(let g of n){if(typeof g!="string"||!pC.test(g)||h.has(g))throw new SyntaxError("An invalid or duplicated subprotocol was specified");h.add(g)}i.headers["Sec-WebSocket-Protocol"]=n.join(",")}if(i.origin&&(i.protocolVersion<13?i.headers["Sec-WebSocket-Origin"]=i.origin:i.headers.Origin=i.origin),(o.username||o.password)&&(i.auth=`${o.username}:${o.password}`),u){let g=i.path.split(":");i.socketPath=g[0],i.path=g[1]}let _;if(i.followRedirects){if(t._redirects===0){t._originalIpc=u,t._originalSecure=a,t._originalHostOrSocketPath=u?i.socketPath:o.host;let g=r&&r.headers;if(r={...r,headers:{}},g)for(let[E,y]of Object.entries(g))r.headers[E.toLowerCase()]=y}else if(t.listenerCount("redirect")===0){let g=u?t._originalIpc?i.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:o.host===t._originalHostOrSocketPath;(!g||t._originalSecure&&!a)&&(delete i.headers.authorization,delete i.headers.cookie,g||delete i.headers.host,i.auth=void 0)}i.auth&&!r.headers.authorization&&(r.headers.authorization="Basic "+Buffer.from(i.auth).toString("base64")),_=t._req=p(i),t._redirects&&t.emit("redirect",t.url,_)}else _=t._req=p(i);i.timeout&&_.on("timeout",()=>{$e(t,_,"Opening handshake has timed out")}),_.on("error",g=>{_===null||_[vp]||(_=t._req=null,Wi(t,g))}),_.on("response",g=>{let E=g.headers.location,y=g.statusCode;if(E&&i.followRedirects&&y>=300&&y<400){if(++t._redirects>i.maxRedirects){$e(t,_,"Maximum redirects exceeded");return}_.abort();let C;try{C=new el(E,e)}catch{let I=new SyntaxError(`Invalid URL: ${E}`);Wi(t,I);return}Tp(t,C,n,r)}else t.emit("unexpected-response",_,g)||$e(t,_,`Unexpected server response: ${g.statusCode}`)}),_.on("upgrade",(g,E,y)=>{if(t.emit("upgrade",g),t.readyState!==Te.CONNECTING)return;_=t._req=null;let C=g.headers.upgrade;if(C===void 0||C.toLowerCase()!=="websocket"){$e(t,E,"Invalid Upgrade header");return}let A=eC("sha1").update(f+oC).digest("base64");if(g.headers["sec-websocket-accept"]!==A){$e(t,E,"Invalid Sec-WebSocket-Accept header");return}let I=g.headers["sec-websocket-protocol"],P;if(I!==void 0?h.size?h.has(I)||(P="Server sent an invalid subprotocol"):P="Server sent a subprotocol but none was requested":h.size&&(P="Server sent no subprotocol"),P){$e(t,E,P);return}I&&(t._protocol=I);let G=g.headers["sec-websocket-extensions"];if(G!==void 0){if(!m){$e(t,E,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let O;try{O=dC(G)}catch{$e(t,E,"Invalid Sec-WebSocket-Extensions header");return}let B=Object.keys(O);if(B.length!==1||B[0]!==$t.extensionName){$e(t,E,"Server indicated an extension that was not requested");return}try{m.accept(O[$t.extensionName])}catch{$e(t,E,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[$t.extensionName]=m}t.setSocket(E,y,{allowSynchronousEvents:i.allowSynchronousEvents,generateMask:i.generateMask,maxBufferedChunks:i.maxBufferedChunks,maxFragments:i.maxFragments,maxPayload:i.maxPayload,skipUTF8Validation:i.skipUTF8Validation})}),i.finishRequest?i.finishRequest(_,t):_.end()}function Wi(t,e){t._readyState=Te.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function hC(t){return t.path=t.socketPath,yp.connect(t)}function mC(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=yp.isIP(t.host)?"":t.host),ZA.connect(t)}function $e(t,e,n){t._readyState=Te.CLOSING;let r=new Error(n);Error.captureStackTrace(r,$e),e.setHeader?(e[vp]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(Wi,t,r)):(e.destroy(r),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function rl(t,e,n){if(e){let r=rC(e)?e.size:fC(e).length;t._socket?t._sender._bufferedBytes+=r:t._bufferedAmount+=r}if(n){let r=new Error(`WebSocket is not open: readyState ${t.readyState} (${kt[t.readyState]})`);process.nextTick(n,r)}}function gC(t,e){let n=this[Ne];n._closeFrameReceived=!0,n._closeMessage=e,n._closeCode=t,n._socket[Ne]!==void 0&&(n._socket.removeListener("data",Xi),process.nextTick(Ap,n._socket),t===1005?n.close():n.close(t,e))}function _C(){let t=this[Ne];t.isPaused||t._socket.resume()}function yC(t){let e=this[Ne];e._socket[Ne]!==void 0&&(e._socket.removeListener("data",Xi),process.nextTick(Ap,e._socket),e.close(t[aC])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function _p(){this[Ne].emitClose()}function EC(t,e){this[Ne].emit("message",t,e)}function vC(t){let e=this[Ne];e._autoPong&&e.pong(t,!this._isServer,Ep),e.emit("ping",t)}function TC(t){this[Ne].emit("pong",t)}function Ap(t){t.resume()}function AC(t){let e=this[Ne];e.readyState!==Te.CLOSED&&(e.readyState===Te.OPEN&&(e._readyState=Te.CLOSING,Cp(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function Cp(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function Sp(){let t=this[Ne];if(this.removeListener("close",Sp),this.removeListener("data",Xi),this.removeListener("end",Ip),t._readyState=Te.CLOSING,!this._readableState.endEmitted&&!t._closeFrameReceived&&!t._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);t._receiver.write(e)}t._receiver.end(),this[Ne]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",_p),t._receiver.on("finish",_p))}function Xi(t){this[Ne]._receiver.write(t)||this.pause()}function Ip(){let t=this[Ne];t._readyState=Te.CLOSING,t._receiver.end(),this.end()}function wp(){let t=this[Ne];this.removeListener("error",wp),this.on("error",Ep),t&&(t._readyState=Te.CLOSING,this.destroy())}});var kp=F((WD,xp)=>{"use strict";var JD=Ki(),{Duplex:CC}=W("stream");function Rp(t){t.emit("close")}function SC(){!this.destroyed&&this._writableState.finished&&this.destroy()}function Np(t){this.removeListener("error",Np),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function IC(t,e){let n=!0,r=new CC({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return t.on("message",function(o,a){let u=!a&&r._readableState.objectMode?o.toString():o;r.push(u)||t.pause()}),t.once("error",function(o){r.destroyed||(n=!1,r.destroy(o))}),t.once("close",function(){r.destroyed||r.push(null)}),r._destroy=function(i,o){if(t.readyState===t.CLOSED){o(i),process.nextTick(Rp,r);return}let a=!1;t.once("error",function(c){a=!0,o(c)}),t.once("close",function(){a||o(i),process.nextTick(Rp,r)}),n&&t.terminate()},r._final=function(i){if(t.readyState===t.CONNECTING){t.once("open",function(){r._final(i)});return}t._socket!==null&&(t._socket._writableState.finished?(i(),r._readableState.endEmitted&&r.destroy()):(t._socket.once("finish",function(){i()}),t.close()))},r._read=function(){t.isPaused&&t.resume()},r._write=function(i,o,a){if(t.readyState===t.CONNECTING){t.once("open",function(){r._write(i,o,a)});return}t.send(i,a)},r.on("end",SC),r.on("error",Np),r}xp.exports=IC});var il=F((XD,Dp)=>{"use strict";var{tokenChars:wC}=Ln();function PC(t){let e=new Set,n=-1,r=-1,i=0;for(i;i<t.length;i++){let a=t.charCodeAt(i);if(r===-1&&wC[a]===1)n===-1&&(n=i);else if(i!==0&&(a===32||a===9))r===-1&&n!==-1&&(r=i);else if(a===44){if(n===-1)throw new SyntaxError(`Unexpected character at index ${i}`);r===-1&&(r=i);let u=t.slice(n,r);if(e.has(u))throw new SyntaxError(`The "${u}" subprotocol is duplicated`);e.add(u),n=r=-1}else throw new SyntaxError(`Unexpected character at index ${i}`)}if(n===-1||r!==-1)throw new SyntaxError("Unexpected end of input");let o=t.slice(n,i);if(e.has(o))throw new SyntaxError(`The "${o}" subprotocol is duplicated`);return e.add(o),e}Dp.exports={parse:PC}});var qp=F((YD,Op)=>{"use strict";var RC=W("events"),Yi=W("http"),{Duplex:KD}=W("stream"),{createHash:NC}=W("crypto"),Mp=$i(),dn=Gn(),xC=il(),kC=Ki(),{CLOSE_TIMEOUT:DC,GUID:MC,kWebSocket:UC}=Rt(),bC=/^[+/0-9A-Za-z]{22}==$/,Up=0,bp=1,Lp=2,ol=class extends RC{constructor(e,n){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxBufferedChunks:256*1024,maxFragments:16*1024,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:DC,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:kC,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(e.port!=null?(this._server=Yi.createServer((r,i)=>{let o=Yi.STATUS_CODES[426];i.writeHead(426,{"Content-Length":o.length,"Content-Type":"text/plain"}),i.end(o)}),this._server.listen(e.port,e.host,e.backlog,n)):e.server&&(this._server=e.server),this._server){let r=this.emit.bind(this,"connection");this._removeListeners=GC(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(i,o,a)=>{this.handleUpgrade(i,o,a,r)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=Up}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(e){if(this._state===Lp){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(Cr,this);return}if(e&&this.once("close",e),this._state!==bp)if(this._state=bp,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(Cr,this):process.nextTick(Cr,this);else{let n=this._server;this._removeListeners(),this._removeListeners=this._server=null,n.close(()=>{Cr(this)})}}shouldHandle(e){if(this.options.path){let n=e.url.indexOf("?");if((n!==-1?e.url.slice(0,n):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,n,r,i){n.on("error",Gp);let o=e.headers["sec-websocket-key"],a=e.headers.upgrade,u=+e.headers["sec-websocket-version"];if(e.method!=="GET"){fn(this,e,n,405,"Invalid HTTP method");return}if(a===void 0||a.toLowerCase()!=="websocket"){fn(this,e,n,400,"Invalid Upgrade header");return}if(o===void 0||!bC.test(o)){fn(this,e,n,400,"Missing or invalid Sec-WebSocket-Key header");return}if(u!==13&&u!==8){fn(this,e,n,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){Sr(n,400);return}let c=e.headers["sec-websocket-protocol"],d=new Set;if(c!==void 0)try{d=xC.parse(c)}catch{fn(this,e,n,400,"Invalid Sec-WebSocket-Protocol header");return}let f=e.headers["sec-websocket-extensions"],p={};if(this.options.perMessageDeflate&&f!==void 0){let h=new dn({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let m=Mp.parse(f);m[dn.extensionName]&&(h.accept(m[dn.extensionName]),p[dn.extensionName]=h)}catch{fn(this,e,n,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let h={origin:e.headers[`${u===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(h,(m,_,g,E)=>{if(!m)return Sr(n,_||401,g,E);this.completeUpgrade(p,o,d,e,n,r,i)});return}if(!this.options.verifyClient(h))return Sr(n,401)}this.completeUpgrade(p,o,d,e,n,r,i)}completeUpgrade(e,n,r,i,o,a,u){if(!o.readable||!o.writable)return o.destroy();if(o[UC])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>Up)return Sr(o,503);let d=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${NC("sha1").update(n+MC).digest("base64")}`],f=new this.options.WebSocket(null,void 0,this.options);if(r.size){let p=this.options.handleProtocols?this.options.handleProtocols(r,i):r.values().next().value;p&&(d.push(`Sec-WebSocket-Protocol: ${p}`),f._protocol=p)}if(e[dn.extensionName]){let p=e[dn.extensionName].params,h=Mp.format({[dn.extensionName]:[p]});d.push(`Sec-WebSocket-Extensions: ${h}`),f._extensions=e}this.emit("headers",d,i),o.write(d.concat(`\r
31
- `).join(`\r
32
- `)),o.removeListener("error",Gp),f.setSocket(o,a,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxBufferedChunks:this.options.maxBufferedChunks,maxFragments:this.options.maxFragments,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(f),f.on("close",()=>{this.clients.delete(f),this._shouldEmitClose&&!this.clients.size&&process.nextTick(Cr,this)})),u(f,i)}};Op.exports=ol;function GC(t,e){for(let n of Object.keys(e))t.on(n,e[n]);return function(){for(let r of Object.keys(e))t.removeListener(r,e[r])}}function Cr(t){t._state=Lp,t.emit("close")}function Gp(){this.destroy()}function Sr(t,e,n,r){n=n||Yi.STATUS_CODES[e],r={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(n),...r},t.once("finish",t.destroy),t.end(`HTTP/1.1 ${e} ${Yi.STATUS_CODES[e]}\r
33
- `+Object.keys(r).map(i=>`${i}: ${r[i]}`).join(`\r
34
- `)+`\r
35
- \r
36
- `+n)}function fn(t,e,n,r,i,o){if(t.listenerCount("wsClientError")){let a=new Error(i);Error.captureStackTrace(a,fn),t.emit("wsClientError",a,n,e)}else Sr(n,r,i,o)}});var pg=ht(ju(),1),hg=ht(Gf(),1);import{createWriteStream as JC}from"fs";import*as Io from"fs/promises";import{writeFile as WC}from"fs/promises";import{Readable as XC}from"node:stream";import{finished as KC}from"node:stream/promises";var LC=ht(kp(),1),OC=ht($i(),1),qC=ht(Gn(),1),FC=ht(Ya(),1),BC=ht(Za(),1),HC=ht(il(),1),sl=ht(Ki(),1),VC=ht(qp(),1);import*as mg from"path";var gg,_g;function eM(t){gg=t.geminiUrl,_g=t.vertexUrl}function YC(){return{geminiUrl:gg,vertexUrl:_g}}function zC(t,e,n,r){var i,o;if(!t?.baseUrl){let a=YC();return e?(i=a.vertexUrl)!==null&&i!==void 0?i:n:(o=a.geminiUrl)!==null&&o!==void 0?o:r}return t.baseUrl}var dt=class{};function $(t,e){let n=/\{([^}]+)\}/g;return t.replace(n,(r,i)=>{if(Object.prototype.hasOwnProperty.call(e,i)){let o=e[i];return o!=null?String(o):""}else throw new Error(`Key '${i}' not found in valueMap.`)})}function l(t,e,n){for(let o=0;o<e.length-1;o++){let a=e[o];if(a.endsWith("[]")){let u=a.slice(0,-2);if(!(u in t))if(Array.isArray(n))t[u]=Array.from({length:n.length},()=>({}));else throw new Error(`Value must be a list given an array path ${a}`);if(Array.isArray(t[u])){let c=t[u];if(Array.isArray(n))for(let d=0;d<c.length;d++){let f=c[d];l(f,e.slice(o+1),n[d])}else for(let d of c)l(d,e.slice(o+1),n)}return}else if(a.endsWith("[0]")){let u=a.slice(0,-3);u in t||(t[u]=[{}]);let c=t[u];l(c[0],e.slice(o+1),n);return}(!t[a]||typeof t[a]!="object")&&(t[a]={}),t=t[a]}let r=e[e.length-1],i=t[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 new Error(`Cannot set value for an existing key. Key: ${r}`)}else r==="_self"&&typeof n=="object"&&n!==null&&!Array.isArray(n)?Object.assign(t,n):t[r]=n}function s(t,e,n=void 0){try{if(e.length===1&&e[0]==="_self")return t;for(let r=0;r<e.length;r++){if(typeof t!="object"||t===null)return n;let i=e[r];if(i.endsWith("[]")){let o=i.slice(0,-2);if(o in t){let a=t[o];return Array.isArray(a)?a.map(u=>s(u,e.slice(r+1),n)):n}else return n}else t=t[i]}return t}catch(r){if(r instanceof TypeError)return n;throw r}}function QC(t,e){for(let[n,r]of Object.entries(e)){let i=n.split("."),o=r.split("."),a=new Set,u=-1;for(let c=0;c<i.length;c++)if(i[c]==="*"){u=c;break}if(u!==-1&&o.length>u)for(let c=u;c<o.length;c++){let d=o[c];d!=="*"&&!d.endsWith("[]")&&!d.endsWith("[0]")&&a.add(d)}cl(t,i,o,0,a)}}function cl(t,e,n,r,i){if(r>=e.length||typeof t!="object"||t===null)return;let o=e[r];if(o.endsWith("[]")){let a=o.slice(0,-2),u=t;if(a in u&&Array.isArray(u[a]))for(let c of u[a])cl(c,e,n,r+1,i)}else if(o==="*"){if(typeof t=="object"&&t!==null&&!Array.isArray(t)){let a=t,u=Object.keys(a).filter(d=>!d.startsWith("_")&&!i.has(d)),c={};for(let d of u)c[d]=a[d];for(let[d,f]of Object.entries(c)){let p=[];for(let h of n.slice(r))h==="*"?p.push(d):p.push(h);l(a,p,f)}for(let d of u)delete a[d]}}else{let a=t;o in a&&cl(a[o],e,n,r+1,i)}}function Ou(t){if(typeof t!="string")throw new Error("fromImageBytes must be a string");return t}function ZC(t){let e={},n=s(t,["operationName"]);n!=null&&l(e,["operationName"],n);let r=s(t,["resourceName"]);return r!=null&&l(e,["_url","resourceName"],r),e}function jC(t){let e={},n=s(t,["name"]);n!=null&&l(e,["name"],n);let r=s(t,["metadata"]);r!=null&&l(e,["metadata"],r);let i=s(t,["done"]);i!=null&&l(e,["done"],i);let o=s(t,["error"]);o!=null&&l(e,["error"],o);let a=s(t,["response","generateVideoResponse"]);return a!=null&&l(e,["response"],t0(a)),e}function e0(t){let e={},n=s(t,["name"]);n!=null&&l(e,["name"],n);let r=s(t,["metadata"]);r!=null&&l(e,["metadata"],r);let i=s(t,["done"]);i!=null&&l(e,["done"],i);let o=s(t,["error"]);o!=null&&l(e,["error"],o);let a=s(t,["response"]);return a!=null&&l(e,["response"],n0(a)),e}function t0(t){let e={},n=s(t,["generatedSamples"]);if(n!=null){let o=n;Array.isArray(o)&&(o=o.map(a=>r0(a))),l(e,["generatedVideos"],o)}let r=s(t,["raiMediaFilteredCount"]);r!=null&&l(e,["raiMediaFilteredCount"],r);let i=s(t,["raiMediaFilteredReasons"]);return i!=null&&l(e,["raiMediaFilteredReasons"],i),e}function n0(t){let e={},n=s(t,["videos"]);if(n!=null){let o=n;Array.isArray(o)&&(o=o.map(a=>i0(a))),l(e,["generatedVideos"],o)}let r=s(t,["raiMediaFilteredCount"]);r!=null&&l(e,["raiMediaFilteredCount"],r);let i=s(t,["raiMediaFilteredReasons"]);return i!=null&&l(e,["raiMediaFilteredReasons"],i),e}function r0(t){let e={},n=s(t,["video"]);return n!=null&&l(e,["video"],c0(n)),e}function i0(t){let e={},n=s(t,["_self"]);return n!=null&&l(e,["video"],d0(n)),e}function o0(t){let e={},n=s(t,["operationName"]);return n!=null&&l(e,["_url","operationName"],n),e}function s0(t){let e={},n=s(t,["operationName"]);return n!=null&&l(e,["_url","operationName"],n),e}function a0(t){let e={},n=s(t,["name"]);n!=null&&l(e,["name"],n);let r=s(t,["metadata"]);r!=null&&l(e,["metadata"],r);let i=s(t,["done"]);i!=null&&l(e,["done"],i);let o=s(t,["error"]);o!=null&&l(e,["error"],o);let a=s(t,["response"]);return a!=null&&l(e,["response"],l0(a)),e}function l0(t){let e={},n=s(t,["sdkHttpResponse"]);n!=null&&l(e,["sdkHttpResponse"],n);let r=s(t,["parent"]);r!=null&&l(e,["parent"],r);let i=s(t,["documentName"]);return i!=null&&l(e,["documentName"],i),e}function qu(t){let e={},n=s(t,["name"]);n!=null&&l(e,["name"],n);let r=s(t,["metadata"]);r!=null&&l(e,["metadata"],r);let i=s(t,["done"]);i!=null&&l(e,["done"],i);let o=s(t,["error"]);o!=null&&l(e,["error"],o);let a=s(t,["response"]);return a!=null&&l(e,["response"],u0(a)),e}function u0(t){let e={},n=s(t,["sdkHttpResponse"]);n!=null&&l(e,["sdkHttpResponse"],n);let r=s(t,["parent"]);r!=null&&l(e,["parent"],r);let i=s(t,["documentName"]);return i!=null&&l(e,["documentName"],i),e}function c0(t){let e={},n=s(t,["uri"]);n!=null&&l(e,["uri"],n);let r=s(t,["encodedVideo"]);r!=null&&l(e,["videoBytes"],Ou(r));let i=s(t,["encoding"]);return i!=null&&l(e,["mimeType"],i),e}function d0(t){let e={},n=s(t,["gcsUri"]);n!=null&&l(e,["uri"],n);let r=s(t,["bytesBase64Encoded"]);r!=null&&l(e,["videoBytes"],Ou(r));let i=s(t,["mimeType"]);return i!=null&&l(e,["mimeType"],i),e}var Fp;(function(t){t.OUTCOME_UNSPECIFIED="OUTCOME_UNSPECIFIED",t.OUTCOME_OK="OUTCOME_OK",t.OUTCOME_FAILED="OUTCOME_FAILED",t.OUTCOME_DEADLINE_EXCEEDED="OUTCOME_DEADLINE_EXCEEDED"})(Fp||(Fp={}));var Bp;(function(t){t.LANGUAGE_UNSPECIFIED="LANGUAGE_UNSPECIFIED",t.PYTHON="PYTHON"})(Bp||(Bp={}));var Hp;(function(t){t.SCHEDULING_UNSPECIFIED="SCHEDULING_UNSPECIFIED",t.SILENT="SILENT",t.WHEN_IDLE="WHEN_IDLE",t.INTERRUPT="INTERRUPT"})(Hp||(Hp={}));var Jt;(function(t){t.TYPE_UNSPECIFIED="TYPE_UNSPECIFIED",t.STRING="STRING",t.NUMBER="NUMBER",t.INTEGER="INTEGER",t.BOOLEAN="BOOLEAN",t.ARRAY="ARRAY",t.OBJECT="OBJECT",t.NULL="NULL"})(Jt||(Jt={}));var Vp;(function(t){t.AUTH_TYPE_UNSPECIFIED="AUTH_TYPE_UNSPECIFIED",t.NO_AUTH="NO_AUTH",t.API_KEY_AUTH="API_KEY_AUTH",t.HTTP_BASIC_AUTH="HTTP_BASIC_AUTH",t.GOOGLE_SERVICE_ACCOUNT_AUTH="GOOGLE_SERVICE_ACCOUNT_AUTH",t.OAUTH="OAUTH",t.OIDC_AUTH="OIDC_AUTH"})(Vp||(Vp={}));var $p;(function(t){t.HTTP_IN_UNSPECIFIED="HTTP_IN_UNSPECIFIED",t.HTTP_IN_QUERY="HTTP_IN_QUERY",t.HTTP_IN_HEADER="HTTP_IN_HEADER",t.HTTP_IN_PATH="HTTP_IN_PATH",t.HTTP_IN_BODY="HTTP_IN_BODY",t.HTTP_IN_COOKIE="HTTP_IN_COOKIE"})($p||($p={}));var Jp;(function(t){t.API_SPEC_UNSPECIFIED="API_SPEC_UNSPECIFIED",t.SIMPLE_SEARCH="SIMPLE_SEARCH",t.ELASTIC_SEARCH="ELASTIC_SEARCH"})(Jp||(Jp={}));var Wp;(function(t){t.ENVIRONMENT_UNSPECIFIED="ENVIRONMENT_UNSPECIFIED",t.ENVIRONMENT_BROWSER="ENVIRONMENT_BROWSER",t.ENVIRONMENT_MOBILE="ENVIRONMENT_MOBILE",t.ENVIRONMENT_DESKTOP="ENVIRONMENT_DESKTOP"})(Wp||(Wp={}));var Xp;(function(t){t.SAFETY_POLICY_UNSPECIFIED="SAFETY_POLICY_UNSPECIFIED",t.FINANCIAL_TRANSACTIONS="FINANCIAL_TRANSACTIONS",t.SENSITIVE_DATA_MODIFICATION="SENSITIVE_DATA_MODIFICATION",t.COMMUNICATION_TOOL="COMMUNICATION_TOOL",t.ACCOUNT_CREATION="ACCOUNT_CREATION",t.DATA_MODIFICATION="DATA_MODIFICATION",t.USER_CONSENT_MANAGEMENT="USER_CONSENT_MANAGEMENT",t.LEGAL_TERMS_AND_AGREEMENTS="LEGAL_TERMS_AND_AGREEMENTS"})(Xp||(Xp={}));var Kp;(function(t){t.PHISH_BLOCK_THRESHOLD_UNSPECIFIED="PHISH_BLOCK_THRESHOLD_UNSPECIFIED",t.BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",t.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",t.BLOCK_HIGH_AND_ABOVE="BLOCK_HIGH_AND_ABOVE",t.BLOCK_HIGHER_AND_ABOVE="BLOCK_HIGHER_AND_ABOVE",t.BLOCK_VERY_HIGH_AND_ABOVE="BLOCK_VERY_HIGH_AND_ABOVE",t.BLOCK_ONLY_EXTREMELY_HIGH="BLOCK_ONLY_EXTREMELY_HIGH"})(Kp||(Kp={}));var Yp;(function(t){t.UNSPECIFIED="UNSPECIFIED",t.BLOCKING="BLOCKING",t.NON_BLOCKING="NON_BLOCKING"})(Yp||(Yp={}));var zp;(function(t){t.MODE_UNSPECIFIED="MODE_UNSPECIFIED",t.MODE_DYNAMIC="MODE_DYNAMIC"})(zp||(zp={}));var Qp;(function(t){t.THINKING_LEVEL_UNSPECIFIED="THINKING_LEVEL_UNSPECIFIED",t.MINIMAL="MINIMAL",t.LOW="LOW",t.MEDIUM="MEDIUM",t.HIGH="HIGH"})(Qp||(Qp={}));var Zp;(function(t){t.DONT_ALLOW="DONT_ALLOW",t.ALLOW_ADULT="ALLOW_ADULT",t.ALLOW_ALL="ALLOW_ALL"})(Zp||(Zp={}));var jp;(function(t){t.PROMINENT_PEOPLE_UNSPECIFIED="PROMINENT_PEOPLE_UNSPECIFIED",t.ALLOW_PROMINENT_PEOPLE="ALLOW_PROMINENT_PEOPLE",t.BLOCK_PROMINENT_PEOPLE="BLOCK_PROMINENT_PEOPLE"})(jp||(jp={}));var eh;(function(t){t.HARM_CATEGORY_UNSPECIFIED="HARM_CATEGORY_UNSPECIFIED",t.HARM_CATEGORY_HARASSMENT="HARM_CATEGORY_HARASSMENT",t.HARM_CATEGORY_HATE_SPEECH="HARM_CATEGORY_HATE_SPEECH",t.HARM_CATEGORY_SEXUALLY_EXPLICIT="HARM_CATEGORY_SEXUALLY_EXPLICIT",t.HARM_CATEGORY_DANGEROUS_CONTENT="HARM_CATEGORY_DANGEROUS_CONTENT",t.HARM_CATEGORY_CIVIC_INTEGRITY="HARM_CATEGORY_CIVIC_INTEGRITY",t.HARM_CATEGORY_IMAGE_HATE="HARM_CATEGORY_IMAGE_HATE",t.HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT="HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT",t.HARM_CATEGORY_IMAGE_HARASSMENT="HARM_CATEGORY_IMAGE_HARASSMENT",t.HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT="HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT",t.HARM_CATEGORY_JAILBREAK="HARM_CATEGORY_JAILBREAK"})(eh||(eh={}));var th;(function(t){t.HARM_BLOCK_METHOD_UNSPECIFIED="HARM_BLOCK_METHOD_UNSPECIFIED",t.SEVERITY="SEVERITY",t.PROBABILITY="PROBABILITY"})(th||(th={}));var nh;(function(t){t.HARM_BLOCK_THRESHOLD_UNSPECIFIED="HARM_BLOCK_THRESHOLD_UNSPECIFIED",t.BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",t.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",t.BLOCK_ONLY_HIGH="BLOCK_ONLY_HIGH",t.BLOCK_NONE="BLOCK_NONE",t.OFF="OFF"})(nh||(nh={}));var rh;(function(t){t.MODE_UNSPECIFIED="MODE_UNSPECIFIED",t.AUTO="AUTO",t.ANY="ANY",t.NONE="NONE",t.VALIDATED="VALIDATED"})(rh||(rh={}));var ih;(function(t){t.FINISH_REASON_UNSPECIFIED="FINISH_REASON_UNSPECIFIED",t.STOP="STOP",t.MAX_TOKENS="MAX_TOKENS",t.SAFETY="SAFETY",t.RECITATION="RECITATION",t.LANGUAGE="LANGUAGE",t.OTHER="OTHER",t.BLOCKLIST="BLOCKLIST",t.PROHIBITED_CONTENT="PROHIBITED_CONTENT",t.SPII="SPII",t.MALFORMED_FUNCTION_CALL="MALFORMED_FUNCTION_CALL",t.IMAGE_SAFETY="IMAGE_SAFETY",t.UNEXPECTED_TOOL_CALL="UNEXPECTED_TOOL_CALL",t.IMAGE_PROHIBITED_CONTENT="IMAGE_PROHIBITED_CONTENT",t.NO_IMAGE="NO_IMAGE",t.IMAGE_RECITATION="IMAGE_RECITATION",t.IMAGE_OTHER="IMAGE_OTHER"})(ih||(ih={}));var oh;(function(t){t.HARM_PROBABILITY_UNSPECIFIED="HARM_PROBABILITY_UNSPECIFIED",t.NEGLIGIBLE="NEGLIGIBLE",t.LOW="LOW",t.MEDIUM="MEDIUM",t.HIGH="HIGH"})(oh||(oh={}));var sh;(function(t){t.HARM_SEVERITY_UNSPECIFIED="HARM_SEVERITY_UNSPECIFIED",t.HARM_SEVERITY_NEGLIGIBLE="HARM_SEVERITY_NEGLIGIBLE",t.HARM_SEVERITY_LOW="HARM_SEVERITY_LOW",t.HARM_SEVERITY_MEDIUM="HARM_SEVERITY_MEDIUM",t.HARM_SEVERITY_HIGH="HARM_SEVERITY_HIGH"})(sh||(sh={}));var ah;(function(t){t.URL_RETRIEVAL_STATUS_UNSPECIFIED="URL_RETRIEVAL_STATUS_UNSPECIFIED",t.URL_RETRIEVAL_STATUS_SUCCESS="URL_RETRIEVAL_STATUS_SUCCESS",t.URL_RETRIEVAL_STATUS_ERROR="URL_RETRIEVAL_STATUS_ERROR",t.URL_RETRIEVAL_STATUS_PAYWALL="URL_RETRIEVAL_STATUS_PAYWALL",t.URL_RETRIEVAL_STATUS_UNSAFE="URL_RETRIEVAL_STATUS_UNSAFE"})(ah||(ah={}));var lh;(function(t){t.BLOCKED_REASON_UNSPECIFIED="BLOCKED_REASON_UNSPECIFIED",t.SAFETY="SAFETY",t.OTHER="OTHER",t.BLOCKLIST="BLOCKLIST",t.PROHIBITED_CONTENT="PROHIBITED_CONTENT",t.IMAGE_SAFETY="IMAGE_SAFETY",t.MODEL_ARMOR="MODEL_ARMOR",t.JAILBREAK="JAILBREAK"})(lh||(lh={}));var uh;(function(t){t.TRAFFIC_TYPE_UNSPECIFIED="TRAFFIC_TYPE_UNSPECIFIED",t.ON_DEMAND="ON_DEMAND",t.ON_DEMAND_PRIORITY="ON_DEMAND_PRIORITY",t.ON_DEMAND_FLEX="ON_DEMAND_FLEX",t.PROVISIONED_THROUGHPUT="PROVISIONED_THROUGHPUT"})(uh||(uh={}));var ch;(function(t){t.MODALITY_UNSPECIFIED="MODALITY_UNSPECIFIED",t.TEXT="TEXT",t.IMAGE="IMAGE",t.VIDEO="VIDEO",t.AUDIO="AUDIO",t.DOCUMENT="DOCUMENT"})(ch||(ch={}));var dh;(function(t){t.MODEL_STAGE_UNSPECIFIED="MODEL_STAGE_UNSPECIFIED",t.UNSTABLE_EXPERIMENTAL="UNSTABLE_EXPERIMENTAL",t.EXPERIMENTAL="EXPERIMENTAL",t.PREVIEW="PREVIEW",t.STABLE="STABLE",t.LEGACY="LEGACY",t.DEPRECATED="DEPRECATED",t.RETIRED="RETIRED"})(dh||(dh={}));var fh;(function(t){t.MEDIA_RESOLUTION_UNSPECIFIED="MEDIA_RESOLUTION_UNSPECIFIED",t.MEDIA_RESOLUTION_LOW="MEDIA_RESOLUTION_LOW",t.MEDIA_RESOLUTION_MEDIUM="MEDIA_RESOLUTION_MEDIUM",t.MEDIA_RESOLUTION_HIGH="MEDIA_RESOLUTION_HIGH"})(fh||(fh={}));var no;(function(t){t.MODALITY_UNSPECIFIED="MODALITY_UNSPECIFIED",t.TEXT="TEXT",t.IMAGE="IMAGE",t.AUDIO="AUDIO",t.VIDEO="VIDEO"})(no||(no={}));var ph;(function(t){t.DELIVERY_UNSPECIFIED="DELIVERY_UNSPECIFIED",t.INLINE="INLINE",t.URI="URI"})(ph||(ph={}));var hh;(function(t){t.ASPECT_RATIO_UNSPECIFIED="ASPECT_RATIO_UNSPECIFIED",t.ASPECT_RATIO_ONE_BY_ONE="ASPECT_RATIO_ONE_BY_ONE",t.ASPECT_RATIO_TWO_BY_THREE="ASPECT_RATIO_TWO_BY_THREE",t.ASPECT_RATIO_THREE_BY_TWO="ASPECT_RATIO_THREE_BY_TWO",t.ASPECT_RATIO_THREE_BY_FOUR="ASPECT_RATIO_THREE_BY_FOUR",t.ASPECT_RATIO_FOUR_BY_THREE="ASPECT_RATIO_FOUR_BY_THREE",t.ASPECT_RATIO_FOUR_BY_FIVE="ASPECT_RATIO_FOUR_BY_FIVE",t.ASPECT_RATIO_FIVE_BY_FOUR="ASPECT_RATIO_FIVE_BY_FOUR",t.ASPECT_RATIO_NINE_BY_SIXTEEN="ASPECT_RATIO_NINE_BY_SIXTEEN",t.ASPECT_RATIO_SIXTEEN_BY_NINE="ASPECT_RATIO_SIXTEEN_BY_NINE",t.ASPECT_RATIO_TWENTY_ONE_BY_NINE="ASPECT_RATIO_TWENTY_ONE_BY_NINE",t.ASPECT_RATIO_ONE_BY_EIGHT="ASPECT_RATIO_ONE_BY_EIGHT",t.ASPECT_RATIO_EIGHT_BY_ONE="ASPECT_RATIO_EIGHT_BY_ONE",t.ASPECT_RATIO_ONE_BY_FOUR="ASPECT_RATIO_ONE_BY_FOUR",t.ASPECT_RATIO_FOUR_BY_ONE="ASPECT_RATIO_FOUR_BY_ONE"})(hh||(hh={}));var mh;(function(t){t.IMAGE_SIZE_UNSPECIFIED="IMAGE_SIZE_UNSPECIFIED",t.IMAGE_SIZE_FIVE_TWELVE="IMAGE_SIZE_FIVE_TWELVE",t.IMAGE_SIZE_ONE_K="IMAGE_SIZE_ONE_K",t.IMAGE_SIZE_TWO_K="IMAGE_SIZE_TWO_K",t.IMAGE_SIZE_FOUR_K="IMAGE_SIZE_FOUR_K"})(mh||(mh={}));var gh;(function(t){t.TUNING_MODE_UNSPECIFIED="TUNING_MODE_UNSPECIFIED",t.TUNING_MODE_FULL="TUNING_MODE_FULL",t.TUNING_MODE_PEFT_ADAPTER="TUNING_MODE_PEFT_ADAPTER"})(gh||(gh={}));var _h;(function(t){t.ADAPTER_SIZE_UNSPECIFIED="ADAPTER_SIZE_UNSPECIFIED",t.ADAPTER_SIZE_ONE="ADAPTER_SIZE_ONE",t.ADAPTER_SIZE_TWO="ADAPTER_SIZE_TWO",t.ADAPTER_SIZE_FOUR="ADAPTER_SIZE_FOUR",t.ADAPTER_SIZE_EIGHT="ADAPTER_SIZE_EIGHT",t.ADAPTER_SIZE_SIXTEEN="ADAPTER_SIZE_SIXTEEN",t.ADAPTER_SIZE_THIRTY_TWO="ADAPTER_SIZE_THIRTY_TWO"})(_h||(_h={}));var yh;(function(t){t.RESPONSE_PARSE_TYPE_UNSPECIFIED="RESPONSE_PARSE_TYPE_UNSPECIFIED",t.IDENTITY="IDENTITY",t.REGEX_EXTRACT="REGEX_EXTRACT"})(yh||(yh={}));var Eh;(function(t){t.MATCH_OPERATION_UNSPECIFIED="MATCH_OPERATION_UNSPECIFIED",t.REGEX_CONTAINS="REGEX_CONTAINS",t.PARTIAL_MATCH="PARTIAL_MATCH",t.EXACT_MATCH="EXACT_MATCH"})(Eh||(Eh={}));var vh;(function(t){t.REINFORCEMENT_TUNING_THINKING_LEVEL_UNSPECIFIED="REINFORCEMENT_TUNING_THINKING_LEVEL_UNSPECIFIED",t.MINIMAL="MINIMAL",t.HIGH="HIGH"})(vh||(vh={}));var dl;(function(t){t.JOB_STATE_UNSPECIFIED="JOB_STATE_UNSPECIFIED",t.JOB_STATE_QUEUED="JOB_STATE_QUEUED",t.JOB_STATE_PENDING="JOB_STATE_PENDING",t.JOB_STATE_RUNNING="JOB_STATE_RUNNING",t.JOB_STATE_SUCCEEDED="JOB_STATE_SUCCEEDED",t.JOB_STATE_FAILED="JOB_STATE_FAILED",t.JOB_STATE_CANCELLING="JOB_STATE_CANCELLING",t.JOB_STATE_CANCELLED="JOB_STATE_CANCELLED",t.JOB_STATE_PAUSED="JOB_STATE_PAUSED",t.JOB_STATE_EXPIRED="JOB_STATE_EXPIRED",t.JOB_STATE_UPDATING="JOB_STATE_UPDATING",t.JOB_STATE_PARTIALLY_SUCCEEDED="JOB_STATE_PARTIALLY_SUCCEEDED"})(dl||(dl={}));var Th;(function(t){t.TUNING_JOB_STATE_UNSPECIFIED="TUNING_JOB_STATE_UNSPECIFIED",t.TUNING_JOB_STATE_WAITING_FOR_QUOTA="TUNING_JOB_STATE_WAITING_FOR_QUOTA",t.TUNING_JOB_STATE_PROCESSING_DATASET="TUNING_JOB_STATE_PROCESSING_DATASET",t.TUNING_JOB_STATE_WAITING_FOR_CAPACITY="TUNING_JOB_STATE_WAITING_FOR_CAPACITY",t.TUNING_JOB_STATE_TUNING="TUNING_JOB_STATE_TUNING",t.TUNING_JOB_STATE_POST_PROCESSING="TUNING_JOB_STATE_POST_PROCESSING"})(Th||(Th={}));var Ah;(function(t){t.AGGREGATION_METRIC_UNSPECIFIED="AGGREGATION_METRIC_UNSPECIFIED",t.AVERAGE="AVERAGE",t.MODE="MODE",t.STANDARD_DEVIATION="STANDARD_DEVIATION",t.VARIANCE="VARIANCE",t.MINIMUM="MINIMUM",t.MAXIMUM="MAXIMUM",t.MEDIAN="MEDIAN",t.PERCENTILE_P90="PERCENTILE_P90",t.PERCENTILE_P95="PERCENTILE_P95",t.PERCENTILE_P99="PERCENTILE_P99"})(Ah||(Ah={}));var Ch;(function(t){t.PAIRWISE_CHOICE_UNSPECIFIED="PAIRWISE_CHOICE_UNSPECIFIED",t.BASELINE="BASELINE",t.CANDIDATE="CANDIDATE",t.TIE="TIE"})(Ch||(Ch={}));var Sh;(function(t){t.VIDEO_ORIENTATION_UNSPECIFIED="VIDEO_ORIENTATION_UNSPECIFIED",t.LANDSCAPE="LANDSCAPE",t.PORTRAIT="PORTRAIT"})(Sh||(Sh={}));var Ih;(function(t){t.TUNING_SPEED_UNSPECIFIED="TUNING_SPEED_UNSPECIFIED",t.REGULAR="REGULAR",t.FAST="FAST"})(Ih||(Ih={}));var wh;(function(t){t.TUNING_TASK_UNSPECIFIED="TUNING_TASK_UNSPECIFIED",t.TUNING_TASK_I2V="TUNING_TASK_I2V",t.TUNING_TASK_T2V="TUNING_TASK_T2V",t.TUNING_TASK_R2V="TUNING_TASK_R2V"})(wh||(wh={}));var Ph;(function(t){t.STATE_UNSPECIFIED="STATE_UNSPECIFIED",t.STATE_PENDING="STATE_PENDING",t.STATE_ACTIVE="STATE_ACTIVE",t.STATE_FAILED="STATE_FAILED"})(Ph||(Ph={}));var Rh;(function(t){t.UNSPECIFIED="unspecified",t.FLEX="flex",t.STANDARD="standard",t.PRIORITY="priority"})(Rh||(Rh={}));var Nh;(function(t){t.MEDIA_RESOLUTION_UNSPECIFIED="MEDIA_RESOLUTION_UNSPECIFIED",t.MEDIA_RESOLUTION_LOW="MEDIA_RESOLUTION_LOW",t.MEDIA_RESOLUTION_MEDIUM="MEDIA_RESOLUTION_MEDIUM",t.MEDIA_RESOLUTION_HIGH="MEDIA_RESOLUTION_HIGH",t.MEDIA_RESOLUTION_ULTRA_HIGH="MEDIA_RESOLUTION_ULTRA_HIGH"})(Nh||(Nh={}));var xh;(function(t){t.TOOL_TYPE_UNSPECIFIED="TOOL_TYPE_UNSPECIFIED",t.GOOGLE_SEARCH_WEB="GOOGLE_SEARCH_WEB",t.GOOGLE_SEARCH_IMAGE="GOOGLE_SEARCH_IMAGE",t.URL_CONTEXT="URL_CONTEXT",t.GOOGLE_MAPS="GOOGLE_MAPS",t.FILE_SEARCH="FILE_SEARCH"})(xh||(xh={}));var fl;(function(t){t.COLLECTION="COLLECTION"})(fl||(fl={}));var kh;(function(t){t.FEATURE_SELECTION_PREFERENCE_UNSPECIFIED="FEATURE_SELECTION_PREFERENCE_UNSPECIFIED",t.PRIORITIZE_QUALITY="PRIORITIZE_QUALITY",t.BALANCED="BALANCED",t.PRIORITIZE_COST="PRIORITIZE_COST"})(kh||(kh={}));var ro;(function(t){t.PREDICT="PREDICT",t.EMBED_CONTENT="EMBED_CONTENT"})(ro||(ro={}));var Dh;(function(t){t.BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",t.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",t.BLOCK_ONLY_HIGH="BLOCK_ONLY_HIGH",t.BLOCK_NONE="BLOCK_NONE"})(Dh||(Dh={}));var Mh;(function(t){t.auto="auto",t.en="en",t.ja="ja",t.ko="ko",t.hi="hi",t.zh="zh",t.pt="pt",t.es="es"})(Mh||(Mh={}));var Uh;(function(t){t.MASK_MODE_DEFAULT="MASK_MODE_DEFAULT",t.MASK_MODE_USER_PROVIDED="MASK_MODE_USER_PROVIDED",t.MASK_MODE_BACKGROUND="MASK_MODE_BACKGROUND",t.MASK_MODE_FOREGROUND="MASK_MODE_FOREGROUND",t.MASK_MODE_SEMANTIC="MASK_MODE_SEMANTIC"})(Uh||(Uh={}));var bh;(function(t){t.CONTROL_TYPE_DEFAULT="CONTROL_TYPE_DEFAULT",t.CONTROL_TYPE_CANNY="CONTROL_TYPE_CANNY",t.CONTROL_TYPE_SCRIBBLE="CONTROL_TYPE_SCRIBBLE",t.CONTROL_TYPE_FACE_MESH="CONTROL_TYPE_FACE_MESH"})(bh||(bh={}));var Gh;(function(t){t.SUBJECT_TYPE_DEFAULT="SUBJECT_TYPE_DEFAULT",t.SUBJECT_TYPE_PERSON="SUBJECT_TYPE_PERSON",t.SUBJECT_TYPE_ANIMAL="SUBJECT_TYPE_ANIMAL",t.SUBJECT_TYPE_PRODUCT="SUBJECT_TYPE_PRODUCT"})(Gh||(Gh={}));var Lh;(function(t){t.EDIT_MODE_DEFAULT="EDIT_MODE_DEFAULT",t.EDIT_MODE_INPAINT_REMOVAL="EDIT_MODE_INPAINT_REMOVAL",t.EDIT_MODE_INPAINT_INSERTION="EDIT_MODE_INPAINT_INSERTION",t.EDIT_MODE_OUTPAINT="EDIT_MODE_OUTPAINT",t.EDIT_MODE_CONTROLLED_EDITING="EDIT_MODE_CONTROLLED_EDITING",t.EDIT_MODE_STYLE="EDIT_MODE_STYLE",t.EDIT_MODE_BGSWAP="EDIT_MODE_BGSWAP",t.EDIT_MODE_PRODUCT_IMAGE="EDIT_MODE_PRODUCT_IMAGE"})(Lh||(Lh={}));var Oh;(function(t){t.FOREGROUND="FOREGROUND",t.BACKGROUND="BACKGROUND",t.PROMPT="PROMPT",t.SEMANTIC="SEMANTIC",t.INTERACTIVE="INTERACTIVE"})(Oh||(Oh={}));var qh;(function(t){t.ASSET="ASSET",t.STYLE="STYLE"})(qh||(qh={}));var Fh;(function(t){t.INSERT="INSERT",t.REMOVE="REMOVE",t.REMOVE_STATIC="REMOVE_STATIC",t.OUTPAINT="OUTPAINT"})(Fh||(Fh={}));var Bh;(function(t){t.OPTIMIZED="OPTIMIZED",t.LOSSLESS="LOSSLESS"})(Bh||(Bh={}));var Hh;(function(t){t.CROP="CROP",t.PAD="PAD"})(Hh||(Hh={}));var Vh;(function(t){t.SUPERVISED_FINE_TUNING="SUPERVISED_FINE_TUNING",t.PREFERENCE_TUNING="PREFERENCE_TUNING",t.DISTILLATION="DISTILLATION",t.REINFORCEMENT_TUNING="REINFORCEMENT_TUNING"})(Vh||(Vh={}));var $h;(function(t){t.STATE_UNSPECIFIED="STATE_UNSPECIFIED",t.PROCESSING="PROCESSING",t.ACTIVE="ACTIVE",t.FAILED="FAILED"})($h||($h={}));var Jh;(function(t){t.SOURCE_UNSPECIFIED="SOURCE_UNSPECIFIED",t.UPLOADED="UPLOADED",t.GENERATED="GENERATED",t.REGISTERED="REGISTERED"})(Jh||(Jh={}));var Wh;(function(t){t.TURN_COMPLETE_REASON_UNSPECIFIED="TURN_COMPLETE_REASON_UNSPECIFIED",t.MALFORMED_FUNCTION_CALL="MALFORMED_FUNCTION_CALL",t.RESPONSE_REJECTED="RESPONSE_REJECTED",t.NEED_MORE_INPUT="NEED_MORE_INPUT",t.PROHIBITED_INPUT_CONTENT="PROHIBITED_INPUT_CONTENT",t.IMAGE_PROHIBITED_INPUT_CONTENT="IMAGE_PROHIBITED_INPUT_CONTENT",t.INPUT_TEXT_CONTAIN_PROMINENT_PERSON_PROHIBITED="INPUT_TEXT_CONTAIN_PROMINENT_PERSON_PROHIBITED",t.INPUT_IMAGE_CELEBRITY="INPUT_IMAGE_CELEBRITY",t.INPUT_IMAGE_PHOTO_REALISTIC_CHILD_PROHIBITED="INPUT_IMAGE_PHOTO_REALISTIC_CHILD_PROHIBITED",t.INPUT_TEXT_NCII_PROHIBITED="INPUT_TEXT_NCII_PROHIBITED",t.INPUT_OTHER="INPUT_OTHER",t.INPUT_IP_PROHIBITED="INPUT_IP_PROHIBITED",t.BLOCKLIST="BLOCKLIST",t.UNSAFE_PROMPT_FOR_IMAGE_GENERATION="UNSAFE_PROMPT_FOR_IMAGE_GENERATION",t.GENERATED_IMAGE_SAFETY="GENERATED_IMAGE_SAFETY",t.GENERATED_CONTENT_SAFETY="GENERATED_CONTENT_SAFETY",t.GENERATED_AUDIO_SAFETY="GENERATED_AUDIO_SAFETY",t.GENERATED_VIDEO_SAFETY="GENERATED_VIDEO_SAFETY",t.GENERATED_CONTENT_PROHIBITED="GENERATED_CONTENT_PROHIBITED",t.GENERATED_CONTENT_BLOCKLIST="GENERATED_CONTENT_BLOCKLIST",t.GENERATED_IMAGE_PROHIBITED="GENERATED_IMAGE_PROHIBITED",t.GENERATED_IMAGE_CELEBRITY="GENERATED_IMAGE_CELEBRITY",t.GENERATED_IMAGE_PROMINENT_PEOPLE_DETECTED_BY_REWRITER="GENERATED_IMAGE_PROMINENT_PEOPLE_DETECTED_BY_REWRITER",t.GENERATED_IMAGE_IDENTIFIABLE_PEOPLE="GENERATED_IMAGE_IDENTIFIABLE_PEOPLE",t.GENERATED_IMAGE_MINORS="GENERATED_IMAGE_MINORS",t.OUTPUT_IMAGE_IP_PROHIBITED="OUTPUT_IMAGE_IP_PROHIBITED",t.GENERATED_OTHER="GENERATED_OTHER",t.MAX_REGENERATION_REACHED="MAX_REGENERATION_REACHED"})(Wh||(Wh={}));var Xh;(function(t){t.VAD_SIGNAL_TYPE_UNSPECIFIED="VAD_SIGNAL_TYPE_UNSPECIFIED",t.VAD_SIGNAL_TYPE_SOS="VAD_SIGNAL_TYPE_SOS",t.VAD_SIGNAL_TYPE_EOS="VAD_SIGNAL_TYPE_EOS"})(Xh||(Xh={}));var Kh;(function(t){t.TYPE_UNSPECIFIED="TYPE_UNSPECIFIED",t.ACTIVITY_START="ACTIVITY_START",t.ACTIVITY_END="ACTIVITY_END"})(Kh||(Kh={}));var Yh;(function(t){t.START_SENSITIVITY_UNSPECIFIED="START_SENSITIVITY_UNSPECIFIED",t.START_SENSITIVITY_HIGH="START_SENSITIVITY_HIGH",t.START_SENSITIVITY_LOW="START_SENSITIVITY_LOW"})(Yh||(Yh={}));var zh;(function(t){t.END_SENSITIVITY_UNSPECIFIED="END_SENSITIVITY_UNSPECIFIED",t.END_SENSITIVITY_HIGH="END_SENSITIVITY_HIGH",t.END_SENSITIVITY_LOW="END_SENSITIVITY_LOW"})(zh||(zh={}));var Qh;(function(t){t.ACTIVITY_HANDLING_UNSPECIFIED="ACTIVITY_HANDLING_UNSPECIFIED",t.START_OF_ACTIVITY_INTERRUPTS="START_OF_ACTIVITY_INTERRUPTS",t.NO_INTERRUPTION="NO_INTERRUPTION"})(Qh||(Qh={}));var Zh;(function(t){t.TURN_COVERAGE_UNSPECIFIED="TURN_COVERAGE_UNSPECIFIED",t.TURN_INCLUDES_ONLY_ACTIVITY="TURN_INCLUDES_ONLY_ACTIVITY",t.TURN_INCLUDES_ALL_INPUT="TURN_INCLUDES_ALL_INPUT",t.TURN_INCLUDES_AUDIO_ACTIVITY_AND_ALL_VIDEO="TURN_INCLUDES_AUDIO_ACTIVITY_AND_ALL_VIDEO"})(Zh||(Zh={}));var jh;(function(t){t.SCALE_UNSPECIFIED="SCALE_UNSPECIFIED",t.C_MAJOR_A_MINOR="C_MAJOR_A_MINOR",t.D_FLAT_MAJOR_B_FLAT_MINOR="D_FLAT_MAJOR_B_FLAT_MINOR",t.D_MAJOR_B_MINOR="D_MAJOR_B_MINOR",t.E_FLAT_MAJOR_C_MINOR="E_FLAT_MAJOR_C_MINOR",t.E_MAJOR_D_FLAT_MINOR="E_MAJOR_D_FLAT_MINOR",t.F_MAJOR_D_MINOR="F_MAJOR_D_MINOR",t.G_FLAT_MAJOR_E_FLAT_MINOR="G_FLAT_MAJOR_E_FLAT_MINOR",t.G_MAJOR_E_MINOR="G_MAJOR_E_MINOR",t.A_FLAT_MAJOR_F_MINOR="A_FLAT_MAJOR_F_MINOR",t.A_MAJOR_G_FLAT_MINOR="A_MAJOR_G_FLAT_MINOR",t.B_FLAT_MAJOR_G_MINOR="B_FLAT_MAJOR_G_MINOR",t.B_MAJOR_A_FLAT_MINOR="B_MAJOR_A_FLAT_MINOR"})(jh||(jh={}));var em;(function(t){t.MUSIC_GENERATION_MODE_UNSPECIFIED="MUSIC_GENERATION_MODE_UNSPECIFIED",t.QUALITY="QUALITY",t.DIVERSITY="DIVERSITY",t.VOCALIZATION="VOCALIZATION"})(em||(em={}));var Vn;(function(t){t.PLAYBACK_CONTROL_UNSPECIFIED="PLAYBACK_CONTROL_UNSPECIFIED",t.PLAY="PLAY",t.PAUSE="PAUSE",t.STOP="STOP",t.RESET_CONTEXT="RESET_CONTEXT"})(Vn||(Vn={}));var tm=class{},nm=class{},rm=class{},im=class{};function tM(t,e){return{inlineData:{data:t,mimeType:e}}}function nM(t,e){return{fileData:{fileUri:t,mimeType:e}}}var om=class{};function rM(t,e,n){return Object.assign({fileData:{fileUri:t,mimeType:e}},n&&{mediaResolution:{level:n}})}function sm(t){return{text:t}}function iM(t,e){return{functionCall:{name:t,args:e}}}function oM(t,e,n,r=[]){return{functionResponse:Object.assign({id:t,name:e,response:n},r.length>0&&{parts:r})}}function sM(t,e,n){return Object.assign({inlineData:{data:t,mimeType:e}},n&&{mediaResolution:{level:n}})}function aM(t,e){return{codeExecutionResult:{outcome:t,output:e}}}function lM(t,e){return{executableCode:{code:t,language:e}}}function am(t){return typeof t=="object"&&t!==null?"fileData"in t||"text"in t||"functionCall"in t||"functionResponse"in t||"inlineData"in t||"videoMetadata"in t||"codeExecutionResult"in t||"executableCode"in t:!1}function yg(t){let e=[];if(typeof t=="string")e.push(sm(t));else if(am(t))e.push(t);else if(Array.isArray(t)){if(t.length===0)throw new Error("partOrString cannot be an empty array");for(let n of t)if(typeof n=="string")e.push(sm(n));else if(am(n))e.push(n);else throw new Error("element in PartUnion must be a Part object or string")}else throw new Error("partOrString must be a Part object, string, or array");return e}function uM(t){return{role:"user",parts:yg(t)}}function cM(t){return{role:"model",parts:yg(t)}}var Kt=class{constructor(e){let n={};for(let r of e.headers.entries())n[r[0]]=r[1];this.headers=n,this.responseInternal=e}json(){return this.responseInternal.json()}},lm=class{},um=class{},pn=class{get text(){var e,n,r,i,o,a,u,c;if(((i=(r=(n=(e=this.candidates)===null||e===void 0?void 0:e[0])===null||n===void 0?void 0:n.content)===null||r===void 0?void 0:r.parts)===null||i===void 0?void 0:i.length)===0)return;this.candidates&&this.candidates.length>1&&console.warn("there are multiple candidates in the response, returning text from the first one.");let d="",f=!1,p=[];for(let h of(c=(u=(a=(o=this.candidates)===null||o===void 0?void 0:o[0])===null||a===void 0?void 0:a.content)===null||u===void 0?void 0:u.parts)!==null&&c!==void 0?c:[]){for(let[m,_]of Object.entries(h))m!=="text"&&m!=="thought"&&m!=="thoughtSignature"&&(_!==null||_!==void 0)&&p.push(m);if(typeof h.text=="string"){if(typeof h.thought=="boolean"&&h.thought)continue;f=!0,d+=h.text}}return p.length>0&&console.warn(`there are non-text parts ${p} in the response, returning concatenation of all text parts. Please refer to the non text parts for a full response from model.`),f?d:void 0}get data(){var e,n,r,i,o,a,u,c;if(((i=(r=(n=(e=this.candidates)===null||e===void 0?void 0:e[0])===null||n===void 0?void 0:n.content)===null||r===void 0?void 0:r.parts)===null||i===void 0?void 0:i.length)===0)return;this.candidates&&this.candidates.length>1&&console.warn("there are multiple candidates in the response, returning data from the first one.");let d="",f=[];for(let p of(c=(u=(a=(o=this.candidates)===null||o===void 0?void 0:o[0])===null||a===void 0?void 0:a.content)===null||u===void 0?void 0:u.parts)!==null&&c!==void 0?c:[]){for(let[h,m]of Object.entries(p))h!=="inlineData"&&(m!==null||m!==void 0)&&f.push(h);p.inlineData&&typeof p.inlineData.data=="string"&&(d+=atob(p.inlineData.data))}return f.length>0&&console.warn(`there are non-data parts ${f} in the response, returning concatenation of all data parts. Please refer to the non data parts for a full response from model.`),d.length>0?btoa(d):void 0}get functionCalls(){var e,n,r,i,o,a,u,c;if(((i=(r=(n=(e=this.candidates)===null||e===void 0?void 0:e[0])===null||n===void 0?void 0:n.content)===null||r===void 0?void 0:r.parts)===null||i===void 0?void 0:i.length)===0)return;this.candidates&&this.candidates.length>1&&console.warn("there are multiple candidates in the response, returning function calls from the first one.");let d=(c=(u=(a=(o=this.candidates)===null||o===void 0?void 0:o[0])===null||a===void 0?void 0:a.content)===null||u===void 0?void 0:u.parts)===null||c===void 0?void 0:c.filter(f=>f.functionCall).map(f=>f.functionCall).filter(f=>f!==void 0);if(d?.length!==0)return d}get executableCode(){var e,n,r,i,o,a,u,c,d;if(((i=(r=(n=(e=this.candidates)===null||e===void 0?void 0:e[0])===null||n===void 0?void 0:n.content)===null||r===void 0?void 0:r.parts)===null||i===void 0?void 0:i.length)===0)return;this.candidates&&this.candidates.length>1&&console.warn("there are multiple candidates in the response, returning executable code from the first one.");let f=(c=(u=(a=(o=this.candidates)===null||o===void 0?void 0:o[0])===null||a===void 0?void 0:a.content)===null||u===void 0?void 0:u.parts)===null||c===void 0?void 0:c.filter(p=>p.executableCode).map(p=>p.executableCode).filter(p=>p!==void 0);if(f?.length!==0)return(d=f?.[0])===null||d===void 0?void 0:d.code}get codeExecutionResult(){var e,n,r,i,o,a,u,c,d;if(((i=(r=(n=(e=this.candidates)===null||e===void 0?void 0:e[0])===null||n===void 0?void 0:n.content)===null||r===void 0?void 0:r.parts)===null||i===void 0?void 0:i.length)===0)return;this.candidates&&this.candidates.length>1&&console.warn("there are multiple candidates in the response, returning code execution result from the first one.");let f=(c=(u=(a=(o=this.candidates)===null||o===void 0?void 0:o[0])===null||a===void 0?void 0:a.content)===null||u===void 0?void 0:u.parts)===null||c===void 0?void 0:c.filter(p=>p.codeExecutionResult).map(p=>p.codeExecutionResult).filter(p=>p!==void 0);if(f?.length!==0)return(d=f?.[0])===null||d===void 0?void 0:d.output}},io=class{},oo=class{},pl=class{},hl=class{},ml=class{},gl=class{},so=class{},ao=class{},cm=class{},dm=class{},fm=class{},pm=class{},hm=class{},lo=class{},_l=class{},mm=class{},uo=class t{_fromAPIResponse({apiResponse:e,_isVertexAI:n}){let r=new t,i,o=e;return n?i=e0(o):i=jC(o),Object.assign(r,i),r}},gm=class{},_m=class{},ym=class{},yl=class{},co=class{},El=class{},fo=class{},po=class{},vl=class{},Tl=class{},Al=class{},Em=class{},Cl=class t{_fromAPIResponse({apiResponse:e,_isVertexAI:n}){let r=new t,o=a0(e);return Object.assign(r,o),r}},Sl=class{},Il=class{},wl=class{},Pl=class{},vm=class{},Tm=class{},Am=class{},ho=class{},Cm=class{},Sm=class{toReferenceImageAPI(){return{referenceType:"REFERENCE_TYPE_RAW",referenceImage:this.referenceImage,referenceId:this.referenceId}}},Im=class{toReferenceImageAPI(){return{referenceType:"REFERENCE_TYPE_MASK",referenceImage:this.referenceImage,referenceId:this.referenceId,maskImageConfig:this.config}}},wm=class{toReferenceImageAPI(){return{referenceType:"REFERENCE_TYPE_CONTROL",referenceImage:this.referenceImage,referenceId:this.referenceId,controlImageConfig:this.config}}},Pm=class{toReferenceImageAPI(){return{referenceType:"REFERENCE_TYPE_STYLE",referenceImage:this.referenceImage,referenceId:this.referenceId,styleImageConfig:this.config}}},Rm=class{toReferenceImageAPI(){return{referenceType:"REFERENCE_TYPE_SUBJECT",referenceImage:this.referenceImage,referenceId:this.referenceId,subjectImageConfig:this.config}}},Nm=class{toReferenceImageAPI(){return{referenceType:"REFERENCE_TYPE_CONTENT",referenceImage:this.referenceImage,referenceId:this.referenceId}}},Rl=class{get text(){var e,n,r;let i="",o=!1,a=[];for(let u of(r=(n=(e=this.serverContent)===null||e===void 0?void 0:e.modelTurn)===null||n===void 0?void 0:n.parts)!==null&&r!==void 0?r:[]){for(let[c,d]of Object.entries(u))c!=="text"&&c!=="thought"&&d!==null&&a.push(c);if(typeof u.text=="string"){if(typeof u.thought=="boolean"&&u.thought)continue;o=!0,i+=u.text}}return a.length>0&&console.warn(`there are non-text parts ${a} in the response, returning concatenation of all text parts. Please refer to the non text parts for a full response from model.`),o?i:void 0}get data(){var e,n,r;let i="",o=[];for(let a of(r=(n=(e=this.serverContent)===null||e===void 0?void 0:e.modelTurn)===null||n===void 0?void 0:n.parts)!==null&&r!==void 0?r:[]){for(let[u,c]of Object.entries(a))u!=="inlineData"&&c!==null&&o.push(u);a.inlineData&&typeof a.inlineData.data=="string"&&(i+=atob(a.inlineData.data))}return o.length>0&&console.warn(`there are non-data parts ${o} in the response, returning concatenation of all data parts. Please refer to the non data parts for a full response from model.`),i.length>0?btoa(i):void 0}},xm=class{},km=class{constructor(){this.functionResponses=[]}},Nl=class{get audioChunk(){if(this.serverContent&&this.serverContent.audioChunks&&this.serverContent.audioChunks.length>0)return this.serverContent.audioChunks[0]}},Dm=class{},mo=class t{_fromAPIResponse({apiResponse:e,_isVertexAI:n}){let r=new t,o=qu(e);return Object.assign(r,o),r}};function ie(t,e){if(!e||typeof e!="string")throw new Error("model is required and must be a string");if(e.includes("..")||e.includes("?")||e.includes("&"))throw new Error("invalid model parameter");if(t.isVertexAI()){if(e.startsWith("publishers/")||e.startsWith("projects/")||e.startsWith("models/"))return e;if(e.indexOf("/")>=0){let n=e.split("/",2);return`publishers/${n[0]}/models/${n[1]}`}else return`publishers/google/models/${e}`}else return e.startsWith("models/")||e.startsWith("tunedModels/")?e:`models/${e}`}function Eg(t,e){let n=ie(t,e);return n?n.startsWith("publishers/")&&t.isVertexAI()?`projects/${t.getProject()}/locations/${t.getLocation()}/${n}`:n.startsWith("models/")&&t.isVertexAI()?`projects/${t.getProject()}/locations/${t.getLocation()}/publishers/google/${n}`:n:""}function vg(t){return Array.isArray(t)?t.map(e=>go(e)):[go(t)]}function go(t){if(typeof t=="object"&&t!==null)return t;throw new Error(`Could not parse input as Blob. Unsupported blob type: ${typeof t}`)}function Tg(t){let e=go(t);if(e.mimeType&&e.mimeType.startsWith("image/"))return e;throw new Error(`Unsupported mime type: ${e.mimeType}`)}function Ag(t){let e=go(t);if(e.mimeType&&e.mimeType.startsWith("audio/"))return e;throw new Error(`Unsupported mime type: ${e.mimeType}`)}function Mm(t){if(t==null)throw new Error("PartUnion is required");if(typeof t=="object")return t;if(typeof t=="string")return{text:t};throw new Error(`Unsupported part type: ${typeof t}`)}function Cg(t){if(t==null||Array.isArray(t)&&t.length===0)throw new Error("PartListUnion is required");return Array.isArray(t)?t.map(e=>Mm(e)):[Mm(t)]}function xl(t){return t!=null&&typeof t=="object"&&"parts"in t&&Array.isArray(t.parts)}function Um(t){return t!=null&&typeof t=="object"&&"functionCall"in t}function bm(t){return t!=null&&typeof t=="object"&&"functionResponse"in t}function xe(t){if(t==null)throw new Error("ContentUnion is required");return xl(t)?t:{role:"user",parts:Cg(t)}}function Fu(t,e){if(!e)return[];if(t.isVertexAI()&&Array.isArray(e))return e.flatMap(n=>{let r=xe(n);return r.parts&&r.parts.length>0&&r.parts[0].text!==void 0?[r.parts[0].text]:[]});if(t.isVertexAI()){let n=xe(e);return n.parts&&n.parts.length>0&&n.parts[0].text!==void 0?[n.parts[0].text]:[]}return Array.isArray(e)?e.map(n=>xe(n)):[xe(e)]}function Le(t){if(t==null||Array.isArray(t)&&t.length===0)throw new Error("contents are required");if(!Array.isArray(t)){if(Um(t)||bm(t))throw new Error("To specify functionCall or functionResponse parts, please wrap them in a Content object, specifying the role for them");return[xe(t)]}let e=[],n=[],r=xl(t[0]);for(let i of t){let o=xl(i);if(o!=r)throw new Error("Mixing Content and Parts is not supported, please group the parts into a the appropriate Content objects and specify the roles for them");if(o)e.push(i);else{if(Um(i)||bm(i))throw new Error("To specify functionCall or functionResponse parts, please wrap them, and any other parts, in Content objects as appropriate, specifying the role for them");n.push(i)}}return r||e.push({role:"user",parts:Cg(n)}),e}function f0(t,e){t.includes("null")&&(e.nullable=!0);let n=t.filter(r=>r!=="null");if(n.length===1)e.type=Object.values(Jt).includes(n[0].toUpperCase())?n[0].toUpperCase():Jt.TYPE_UNSPECIFIED;else{e.anyOf=[];for(let r of n)e.anyOf.push({type:Object.values(Jt).includes(r.toUpperCase())?r.toUpperCase():Jt.TYPE_UNSPECIFIED})}}function Wn(t){let e={},n=["items"],r=["anyOf"],i=["properties"];if(t.type&&t.anyOf)throw new Error("type and anyOf cannot be both populated.");let o=t.anyOf;o!=null&&o.length==2&&(o[0].type==="null"?(e.nullable=!0,t=o[1]):o[1].type==="null"&&(e.nullable=!0,t=o[0])),t.type instanceof Array&&f0(t.type,e);for(let[a,u]of Object.entries(t))if(u!=null)if(a=="type"){if(u==="null")throw new Error("type: null can not be the only possible type for the field.");if(u instanceof Array)continue;e.type=Object.values(Jt).includes(u.toUpperCase())?u.toUpperCase():Jt.TYPE_UNSPECIFIED}else if(n.includes(a))e[a]=Wn(u);else if(r.includes(a)){let c=[];for(let d of u){if(d.type=="null"){e.nullable=!0;continue}c.push(Wn(d))}e[a]=c}else if(i.includes(a)){let c={};for(let[d,f]of Object.entries(u))c[d]=Wn(f);e[a]=c}else{if(a==="additionalProperties")continue;e[a]=u}return e}function Bu(t){return Wn(t)}function Hu(t){if(typeof t=="object")return t;if(typeof t=="string")return{voiceConfig:{prebuiltVoiceConfig:{voiceName:t}}};throw new Error(`Unsupported speechConfig type: ${typeof t}`)}function Vu(t){if("multiSpeakerVoiceConfig"in t)throw new Error("multiSpeakerVoiceConfig is not supported in the live API.");return t}function Qn(t){if(t.functionDeclarations)for(let e of t.functionDeclarations)e.parameters&&(Object.keys(e.parameters).includes("$schema")?e.parametersJsonSchema||(e.parametersJsonSchema=e.parameters,delete e.parameters):e.parameters=Wn(e.parameters)),e.response&&(Object.keys(e.response).includes("$schema")?e.responseJsonSchema||(e.responseJsonSchema=e.response,delete e.response):e.response=Wn(e.response));return t}function Zn(t){if(t==null)throw new Error("tools is required");if(!Array.isArray(t))throw new Error("tools is required and must be an array of Tools");let e=[];for(let n of t)e.push(n);return e}function p0(t,e,n,r=1){let i=!e.startsWith(`${n}/`)&&e.split("/").length===r;return t.isVertexAI()?e.startsWith("projects/")?e:e.startsWith("locations/")?`projects/${t.getProject()}/${e}`:e.startsWith(`${n}/`)?`projects/${t.getProject()}/locations/${t.getLocation()}/${e}`:i?`projects/${t.getProject()}/locations/${t.getLocation()}/${n}/${e}`:e:i?`${n}/${e}`:e}function bt(t,e){if(typeof e!="string")throw new Error("name must be a string");return p0(t,e,"cachedContents")}function Sg(t){switch(t){case"STATE_UNSPECIFIED":return"JOB_STATE_UNSPECIFIED";case"CREATING":return"JOB_STATE_RUNNING";case"ACTIVE":return"JOB_STATE_SUCCEEDED";case"FAILED":return"JOB_STATE_FAILED";default:return t}}function en(t){return Ou(t)}function h0(t){return t!=null&&typeof t=="object"&&"name"in t}function Ig(t){return t!=null&&typeof t=="object"&&"video"in t}function wg(t){return t!=null&&typeof t=="object"&&"uri"in t}function $u(t){var e;let n;if(h0(t)&&(n=t.name),!(wg(t)&&(n=t.uri,n===void 0))&&!(Ig(t)&&(n=(e=t.video)===null||e===void 0?void 0:e.uri,n===void 0))){if(typeof t=="string"&&(n=t),n===void 0)throw new Error("Could not extract file name from the provided input.");if(n.startsWith("https://")){let i=n.split("files/")[1].match(/[a-z0-9]+/);if(i===null)throw new Error(`Could not extract file name from URI ${n}`);n=i[0]}else n.startsWith("files/")&&(n=n.split("files/")[1]);return n}}function Pg(t,e){let n;return t.isVertexAI()?n=e?"publishers/google/models":"models":n=e?"models":"tunedModels",n}function Rg(t){for(let e of["models","tunedModels","publisherModels"])if(m0(t,e))return t[e];return[]}function m0(t,e){return t!==null&&typeof t=="object"&&e in t}function g0(t,e={}){let n=t,r={name:n.name,description:n.description,parametersJsonSchema:n.inputSchema};return n.outputSchema&&(r.responseJsonSchema=n.outputSchema),e.behavior&&(r.behavior=e.behavior),{functionDeclarations:[r]}}function _0(t,e={}){let n=[],r=new Set;for(let i of t){let o=i.name;if(r.has(o))throw new Error(`Duplicate function name ${o} found in MCP tools. Please ensure function names are unique.`);r.add(o);let a=g0(i,e);a.functionDeclarations&&n.push(...a.functionDeclarations)}return{functionDeclarations:n}}function Ng(t,e){let n;if(typeof e=="string")if(t.isVertexAI())if(e.startsWith("gs://"))n={format:"jsonl",gcsUri:[e]};else if(e.startsWith("bq://"))n={format:"bigquery",bigqueryUri:e};else if(/^projects\/[^/]+\/locations\/[^/]+\/datasets\/[^/]+$/.test(e))n={format:"vertex-dataset",vertexDatasetName:e};else throw new Error(`Unsupported string source for Vertex AI: ${e}`);else if(e.startsWith("files/"))n={fileName:e};else throw new Error(`Unsupported string source for Gemini API: ${e}`);else if(Array.isArray(e)){if(t.isVertexAI())throw new Error("InlinedRequest[] is not supported in Vertex AI.");n={inlinedRequests:e}}else n=e;let r=[n.gcsUri,n.bigqueryUri,n.vertexDatasetName].filter(Boolean).length,i=[n.inlinedRequests,n.fileName].filter(Boolean).length;if(t.isVertexAI()){if(i>0||r!==1)throw new Error("Exactly one of `gcsUri`, `bigqueryUri`, or `vertexDatasetName` must be set for Vertex AI.")}else if(r>0||i!==1)throw new Error("Exactly one of `inlinedRequests`, `fileName`, must be set for Gemini API.");return n}function y0(t){if(typeof t!="string")return t;let e=t;if(e.startsWith("gs://"))return{format:"jsonl",gcsUri:e};if(e.startsWith("bq://"))return{format:"bigquery",bigqueryUri:e};throw new Error(`Unsupported destination: ${e}`)}function xg(t){if(typeof t!="object"||t===null)return{};let e=t,n=e.inlinedResponses;if(typeof n!="object"||n===null)return t;let i=n.inlinedResponses;if(!Array.isArray(i)||i.length===0)return t;let o=!1;for(let a of i){if(typeof a!="object"||a===null)continue;let c=a.response;if(typeof c!="object"||c===null)continue;if(c.embedding!==void 0){o=!0;break}}return o&&(e.inlinedEmbedContentResponses=e.inlinedResponses,delete e.inlinedResponses),t}function jn(t,e){let n=e;if(!t.isVertexAI()){if(/batches\/[^/]+$/.test(n))return n.split("/").pop();throw new Error(`Invalid batch job name: ${n}.`)}if(/^projects\/[^/]+\/locations\/[^/]+\/batchPredictionJobs\/[^/]+$/.test(n))return n.split("/").pop();if(/^\d+$/.test(n))return n;throw new Error(`Invalid batch job name: ${n}.`)}function kg(t){let e=t;return e==="BATCH_STATE_UNSPECIFIED"?"JOB_STATE_UNSPECIFIED":e==="BATCH_STATE_PENDING"?"JOB_STATE_PENDING":e==="BATCH_STATE_RUNNING"?"JOB_STATE_RUNNING":e==="BATCH_STATE_SUCCEEDED"?"JOB_STATE_SUCCEEDED":e==="BATCH_STATE_FAILED"?"JOB_STATE_FAILED":e==="BATCH_STATE_CANCELLED"?"JOB_STATE_CANCELLED":e==="BATCH_STATE_EXPIRED"?"JOB_STATE_EXPIRED":e}function E0(t){return t.includes("gemini")&&t!=="gemini-embedding-001"||t.includes("maas")}function v0(t){let e={},n=s(t,["apiKey"]);if(n!=null&&l(e,["apiKey"],n),s(t,["apiKeyConfig"])!==void 0)throw new Error("apiKeyConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["authType"])!==void 0)throw new Error("authType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["googleServiceAccountConfig"])!==void 0)throw new Error("googleServiceAccountConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["httpBasicAuthConfig"])!==void 0)throw new Error("httpBasicAuthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["oauthConfig"])!==void 0)throw new Error("oauthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["oidcConfig"])!==void 0)throw new Error("oidcConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return e}function T0(t){let e={},n=s(t,["responsesFile"]);n!=null&&l(e,["fileName"],n);let r=s(t,["inlinedResponses","inlinedResponses"]);if(r!=null){let o=r;Array.isArray(o)&&(o=o.map(a=>tS(a))),l(e,["inlinedResponses"],o)}let i=s(t,["inlinedEmbedContentResponses","inlinedResponses"]);if(i!=null){let o=i;Array.isArray(o)&&(o=o.map(a=>a)),l(e,["inlinedEmbedContentResponses"],o)}return e}function A0(t){let e={},n=s(t,["predictionsFormat"]);n!=null&&l(e,["format"],n);let r=s(t,["gcsDestination","outputUriPrefix"]);r!=null&&l(e,["gcsUri"],r);let i=s(t,["bigqueryDestination","outputUri"]);i!=null&&l(e,["bigqueryUri"],i);let o=s(t,["vertexMultimodalDatasetDestination"]);return o!=null&&l(e,["vertexDataset"],fS(o)),e}function C0(t){let e={},n=s(t,["format"]);n!=null&&l(e,["predictionsFormat"],n);let r=s(t,["gcsUri"]);r!=null&&l(e,["gcsDestination","outputUriPrefix"],r);let i=s(t,["bigqueryUri"]);i!=null&&l(e,["bigqueryDestination","outputUri"],i);let o=s(t,["vertexDataset"]);if(o!=null&&l(e,["vertexMultimodalDatasetDestination"],pS(o)),s(t,["fileName"])!==void 0)throw new Error("fileName parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(s(t,["inlinedResponses"])!==void 0)throw new Error("inlinedResponses parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(s(t,["inlinedEmbedContentResponses"])!==void 0)throw new Error("inlinedEmbedContentResponses parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return e}function eo(t){let e={},n=s(t,["name"]);n!=null&&l(e,["name"],n);let r=s(t,["metadata","displayName"]);r!=null&&l(e,["displayName"],r);let i=s(t,["metadata","state"]);i!=null&&l(e,["state"],kg(i));let o=s(t,["metadata","createTime"]);o!=null&&l(e,["createTime"],o);let a=s(t,["metadata","endTime"]);a!=null&&l(e,["endTime"],a);let u=s(t,["metadata","updateTime"]);u!=null&&l(e,["updateTime"],u);let c=s(t,["metadata","model"]);c!=null&&l(e,["model"],c);let d=s(t,["metadata","output"]);return d!=null&&l(e,["dest"],T0(xg(d))),e}function kl(t){let e={},n=s(t,["name"]);n!=null&&l(e,["name"],n);let r=s(t,["displayName"]);r!=null&&l(e,["displayName"],r);let i=s(t,["state"]);i!=null&&l(e,["state"],kg(i));let o=s(t,["error"]);o!=null&&l(e,["error"],o);let a=s(t,["createTime"]);a!=null&&l(e,["createTime"],a);let u=s(t,["startTime"]);u!=null&&l(e,["startTime"],u);let c=s(t,["endTime"]);c!=null&&l(e,["endTime"],c);let d=s(t,["updateTime"]);d!=null&&l(e,["updateTime"],d);let f=s(t,["model"]);f!=null&&l(e,["model"],f);let p=s(t,["inputConfig"]);p!=null&&l(e,["src"],S0(p));let h=s(t,["outputConfig"]);h!=null&&l(e,["dest"],A0(xg(h)));let m=s(t,["outputInfo"]);m!=null&&l(e,["outputInfo"],m);let _=s(t,["completionStats"]);return _!=null&&l(e,["completionStats"],_),e}function S0(t){let e={},n=s(t,["instancesFormat"]);n!=null&&l(e,["format"],n);let r=s(t,["gcsSource","uris"]);r!=null&&l(e,["gcsUri"],r);let i=s(t,["bigquerySource","inputUri"]);i!=null&&l(e,["bigqueryUri"],i);let o=s(t,["vertexMultimodalDatasetSource","datasetName"]);return o!=null&&l(e,["vertexDatasetName"],o),e}function I0(t,e){let n={};if(s(e,["format"])!==void 0)throw new Error("format parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(e,["gcsUri"])!==void 0)throw new Error("gcsUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(e,["bigqueryUri"])!==void 0)throw new Error("bigqueryUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(e,["vertexDatasetName"])!==void 0)throw new Error("vertexDatasetName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let r=s(e,["fileName"]);r!=null&&l(n,["fileName"],r);let i=s(e,["inlinedRequests"]);if(i!=null){let o=i;Array.isArray(o)&&(o=o.map(a=>eS(t,a))),l(n,["requests","requests"],o)}return n}function w0(t){let e={},n=s(t,["format"]);n!=null&&l(e,["instancesFormat"],n);let r=s(t,["gcsUri"]);r!=null&&l(e,["gcsSource","uris"],r);let i=s(t,["bigqueryUri"]);i!=null&&l(e,["bigquerySource","inputUri"],i);let o=s(t,["vertexDatasetName"]);if(o!=null&&l(e,["vertexMultimodalDatasetSource","datasetName"],o),s(t,["fileName"])!==void 0)throw new Error("fileName parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(s(t,["inlinedRequests"])!==void 0)throw new Error("inlinedRequests parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return e}function P0(t){let e={},n=s(t,["data"]);if(n!=null&&l(e,["data"],n),s(t,["displayName"])!==void 0)throw new Error("displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let r=s(t,["mimeType"]);return r!=null&&l(e,["mimeType"],r),e}function R0(t,e){let n={},r=s(e,["name"]);return r!=null&&l(n,["_url","name"],jn(t,r)),n}function N0(t,e){let n={},r=s(e,["name"]);return r!=null&&l(n,["_url","name"],jn(t,r)),n}function x0(t){let e={},n=s(t,["content"]);n!=null&&l(e,["content"],n);let r=s(t,["citationMetadata"]);r!=null&&l(e,["citationMetadata"],k0(r));let i=s(t,["tokenCount"]);i!=null&&l(e,["tokenCount"],i);let o=s(t,["finishReason"]);o!=null&&l(e,["finishReason"],o);let a=s(t,["groundingMetadata"]);a!=null&&l(e,["groundingMetadata"],a);let u=s(t,["avgLogprobs"]);u!=null&&l(e,["avgLogprobs"],u);let c=s(t,["index"]);c!=null&&l(e,["index"],c);let d=s(t,["logprobsResult"]);d!=null&&l(e,["logprobsResult"],d);let f=s(t,["safetyRatings"]);if(f!=null){let h=f;Array.isArray(h)&&(h=h.map(m=>m)),l(e,["safetyRatings"],h)}let p=s(t,["urlContextMetadata"]);return p!=null&&l(e,["urlContextMetadata"],p),e}function k0(t){let e={},n=s(t,["citationSources"]);if(n!=null){let r=n;Array.isArray(r)&&(r=r.map(i=>i)),l(e,["citations"],r)}return e}function Dg(t){let e={},n=s(t,["parts"]);if(n!=null){let i=n;Array.isArray(i)&&(i=i.map(o=>lS(o))),l(e,["parts"],i)}let r=s(t,["role"]);return r!=null&&l(e,["role"],r),e}function D0(t,e){let n={},r=s(t,["displayName"]);if(e!==void 0&&r!=null&&l(e,["batch","displayName"],r),s(t,["dest"])!==void 0)throw new Error("dest parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let i=s(t,["webhookConfig"]);return e!==void 0&&i!=null&&l(e,["batch","webhookConfig"],i),n}function M0(t,e){let n={},r=s(t,["displayName"]);e!==void 0&&r!=null&&l(e,["displayName"],r);let i=s(t,["dest"]);if(e!==void 0&&i!=null&&l(e,["outputConfig"],C0(y0(i))),s(t,["webhookConfig"])!==void 0)throw new Error("webhookConfig parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return n}function Gm(t,e){let n={},r=s(e,["model"]);r!=null&&l(n,["_url","model"],ie(t,r));let i=s(e,["src"]);i!=null&&l(n,["batch","inputConfig"],I0(t,Ng(t,i)));let o=s(e,["config"]);return o!=null&&D0(o,n),n}function U0(t,e){let n={},r=s(e,["model"]);r!=null&&l(n,["model"],ie(t,r));let i=s(e,["src"]);i!=null&&l(n,["inputConfig"],w0(Ng(t,i)));let o=s(e,["config"]);return o!=null&&M0(o,n),n}function b0(t,e){let n={},r=s(t,["displayName"]);return e!==void 0&&r!=null&&l(e,["batch","displayName"],r),n}function G0(t,e){let n={},r=s(e,["model"]);r!=null&&l(n,["_url","model"],ie(t,r));let i=s(e,["src"]);i!=null&&l(n,["batch","inputConfig"],V0(t,i));let o=s(e,["config"]);return o!=null&&b0(o,n),n}function L0(t,e){let n={},r=s(e,["name"]);return r!=null&&l(n,["_url","name"],jn(t,r)),n}function O0(t,e){let n={},r=s(e,["name"]);return r!=null&&l(n,["_url","name"],jn(t,r)),n}function q0(t){let e={},n=s(t,["sdkHttpResponse"]);n!=null&&l(e,["sdkHttpResponse"],n);let r=s(t,["name"]);r!=null&&l(e,["name"],r);let i=s(t,["done"]);i!=null&&l(e,["done"],i);let o=s(t,["error"]);return o!=null&&l(e,["error"],o),e}function F0(t){let e={},n=s(t,["sdkHttpResponse"]);n!=null&&l(e,["sdkHttpResponse"],n);let r=s(t,["name"]);r!=null&&l(e,["name"],r);let i=s(t,["done"]);i!=null&&l(e,["done"],i);let o=s(t,["error"]);return o!=null&&l(e,["error"],o),e}function B0(t,e){let n={},r=s(e,["contents"]);if(r!=null){let o=Fu(t,r);Array.isArray(o)&&(o=o.map(a=>a)),l(n,["requests[]","request","content"],o)}let i=s(e,["config"]);return i!=null&&(l(n,["_self"],H0(i,n)),QC(n,{"requests[].*":"requests[].request.*"})),n}function H0(t,e){let n={},r=s(t,["taskType"]);e!==void 0&&r!=null&&l(e,["requests[]","taskType"],r);let i=s(t,["title"]);e!==void 0&&i!=null&&l(e,["requests[]","title"],i);let o=s(t,["outputDimensionality"]);if(e!==void 0&&o!=null&&l(e,["requests[]","outputDimensionality"],o),s(t,["mimeType"])!==void 0)throw new Error("mimeType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["autoTruncate"])!==void 0)throw new Error("autoTruncate parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["documentOcr"])!==void 0)throw new Error("documentOcr parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["audioTrackExtraction"])!==void 0)throw new Error("audioTrackExtraction parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return n}function V0(t,e){let n={},r=s(e,["fileName"]);r!=null&&l(n,["file_name"],r);let i=s(e,["inlinedRequests"]);return i!=null&&l(n,["requests"],B0(t,i)),n}function $0(t){let e={};if(s(t,["displayName"])!==void 0)throw new Error("displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let n=s(t,["fileUri"]);n!=null&&l(e,["fileUri"],n);let r=s(t,["mimeType"]);return r!=null&&l(e,["mimeType"],r),e}function J0(t){let e={},n=s(t,["args"]);n!=null&&l(e,["args"],n);let r=s(t,["id"]);r!=null&&l(e,["id"],r);let i=s(t,["name"]);if(i!=null&&l(e,["name"],i),s(t,["partialArgs"])!==void 0)throw new Error("partialArgs parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["willContinue"])!==void 0)throw new Error("willContinue parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return e}function W0(t){let e={},n=s(t,["allowedFunctionNames"]);n!=null&&l(e,["allowedFunctionNames"],n);let r=s(t,["mode"]);if(r!=null&&l(e,["mode"],r),s(t,["streamFunctionCallArguments"])!==void 0)throw new Error("streamFunctionCallArguments parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return e}function X0(t,e,n){let r={},i=s(e,["serviceTier"]);n!==void 0&&i!=null&&l(n,["serviceTier"],i);let o=s(e,["systemInstruction"]);n!==void 0&&o!=null&&l(n,["systemInstruction"],Dg(xe(o)));let a=s(e,["temperature"]);a!=null&&l(r,["temperature"],a);let u=s(e,["topP"]);u!=null&&l(r,["topP"],u);let c=s(e,["topK"]);c!=null&&l(r,["topK"],c);let d=s(e,["candidateCount"]);d!=null&&l(r,["candidateCount"],d);let f=s(e,["maxOutputTokens"]);f!=null&&l(r,["maxOutputTokens"],f);let p=s(e,["stopSequences"]);p!=null&&l(r,["stopSequences"],p);let h=s(e,["responseLogprobs"]);h!=null&&l(r,["responseLogprobs"],h);let m=s(e,["logprobs"]);m!=null&&l(r,["logprobs"],m);let _=s(e,["presencePenalty"]);_!=null&&l(r,["presencePenalty"],_);let g=s(e,["frequencyPenalty"]);g!=null&&l(r,["frequencyPenalty"],g);let E=s(e,["seed"]);E!=null&&l(r,["seed"],E);let y=s(e,["responseMimeType"]);y!=null&&l(r,["responseMimeType"],y);let C=s(e,["responseSchema"]);C!=null&&l(r,["responseSchema"],Bu(C));let A=s(e,["responseJsonSchema"]);if(A!=null&&l(r,["responseJsonSchema"],A),s(e,["routingConfig"])!==void 0)throw new Error("routingConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(e,["modelSelectionConfig"])!==void 0)throw new Error("modelSelectionConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let I=s(e,["safetySettings"]);if(n!==void 0&&I!=null){let K=I;Array.isArray(K)&&(K=K.map(j=>uS(j))),l(n,["safetySettings"],K)}let P=s(e,["tools"]);if(n!==void 0&&P!=null){let K=Zn(P);Array.isArray(K)&&(K=K.map(j=>dS(Qn(j)))),l(n,["tools"],K)}let G=s(e,["toolConfig"]);if(n!==void 0&&G!=null&&l(n,["toolConfig"],cS(G)),s(e,["labels"])!==void 0)throw new Error("labels parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let O=s(e,["cachedContent"]);n!==void 0&&O!=null&&l(n,["cachedContent"],bt(t,O));let B=s(e,["responseModalities"]);B!=null&&l(r,["responseModalities"],B);let k=s(e,["mediaResolution"]);k!=null&&l(r,["mediaResolution"],k);let V=s(e,["speechConfig"]);if(V!=null&&l(r,["speechConfig"],Hu(V)),s(e,["audioTimestamp"])!==void 0)throw new Error("audioTimestamp parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let X=s(e,["thinkingConfig"]);X!=null&&l(r,["thinkingConfig"],X);let Z=s(e,["audioTranscriptionConfig"]);Z!=null&&l(r,["audioTranscriptionConfig"],Z);let ne=s(e,["imageConfig"]);ne!=null&&l(r,["imageConfig"],j0(ne));let D=s(e,["enableEnhancedCivicAnswers"]);if(D!=null&&l(r,["enableEnhancedCivicAnswers"],D),s(e,["modelArmorConfig"])!==void 0)throw new Error("modelArmorConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return r}function K0(t){let e={},n=s(t,["sdkHttpResponse"]);n!=null&&l(e,["sdkHttpResponse"],n);let r=s(t,["candidates"]);if(r!=null){let d=r;Array.isArray(d)&&(d=d.map(f=>x0(f))),l(e,["candidates"],d)}let i=s(t,["modelVersion"]);i!=null&&l(e,["modelVersion"],i);let o=s(t,["promptFeedback"]);o!=null&&l(e,["promptFeedback"],o);let a=s(t,["responseId"]);a!=null&&l(e,["responseId"],a);let u=s(t,["usageMetadata"]);u!=null&&l(e,["usageMetadata"],u);let c=s(t,["modelStatus"]);return c!=null&&l(e,["modelStatus"],c),e}function Y0(t,e){let n={},r=s(e,["name"]);return r!=null&&l(n,["_url","name"],jn(t,r)),n}function z0(t,e){let n={},r=s(e,["name"]);return r!=null&&l(n,["_url","name"],jn(t,r)),n}function Q0(t){let e={},n=s(t,["authConfig"]);n!=null&&l(e,["authConfig"],v0(n));let r=s(t,["enableWidget"]);if(r!=null&&l(e,["enableWidget"],r),s(t,["groundingTypes"])!==void 0)throw new Error("groundingTypes parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return e}function Z0(t){let e={};if(s(t,["blockingConfidence"])!==void 0)throw new Error("blockingConfidence parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["excludeDomains"])!==void 0)throw new Error("excludeDomains parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let n=s(t,["searchTypes"]);n!=null&&l(e,["searchTypes"],n);let r=s(t,["timeRangeFilter"]);return r!=null&&l(e,["timeRangeFilter"],r),e}function j0(t){let e={},n=s(t,["aspectRatio"]);n!=null&&l(e,["aspectRatio"],n);let r=s(t,["imageSize"]);if(r!=null&&l(e,["imageSize"],r),s(t,["personGeneration"])!==void 0)throw new Error("personGeneration parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["outputMimeType"])!==void 0)throw new Error("outputMimeType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["outputCompressionQuality"])!==void 0)throw new Error("outputCompressionQuality parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["imageOutputOptions"])!==void 0)throw new Error("imageOutputOptions parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["prominentPeople"])!==void 0)throw new Error("prominentPeople parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return e}function eS(t,e){let n={},r=s(e,["model"]);r!=null&&l(n,["request","model"],ie(t,r));let i=s(e,["contents"]);if(i!=null){let u=Le(i);Array.isArray(u)&&(u=u.map(c=>Dg(c))),l(n,["request","contents"],u)}let o=s(e,["metadata"]);o!=null&&l(n,["metadata"],o);let a=s(e,["config"]);return a!=null&&l(n,["request","generationConfig"],X0(t,a,s(n,["request"],{}))),n}function tS(t){let e={},n=s(t,["response"]);n!=null&&l(e,["response"],K0(n));let r=s(t,["metadata"]);r!=null&&l(e,["metadata"],r);let i=s(t,["error"]);return i!=null&&l(e,["error"],i),e}function nS(t,e){let n={},r=s(t,["pageSize"]);e!==void 0&&r!=null&&l(e,["_query","pageSize"],r);let i=s(t,["pageToken"]);if(e!==void 0&&i!=null&&l(e,["_query","pageToken"],i),s(t,["filter"])!==void 0)throw new Error("filter parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return n}function rS(t,e){let n={},r=s(t,["pageSize"]);e!==void 0&&r!=null&&l(e,["_query","pageSize"],r);let i=s(t,["pageToken"]);e!==void 0&&i!=null&&l(e,["_query","pageToken"],i);let o=s(t,["filter"]);return e!==void 0&&o!=null&&l(e,["_query","filter"],o),n}function iS(t){let e={},n=s(t,["config"]);return n!=null&&nS(n,e),e}function oS(t){let e={},n=s(t,["config"]);return n!=null&&rS(n,e),e}function sS(t){let e={},n=s(t,["sdkHttpResponse"]);n!=null&&l(e,["sdkHttpResponse"],n);let r=s(t,["nextPageToken"]);r!=null&&l(e,["nextPageToken"],r);let i=s(t,["operations"]);if(i!=null){let o=i;Array.isArray(o)&&(o=o.map(a=>eo(a))),l(e,["batchJobs"],o)}return e}function aS(t){let e={},n=s(t,["sdkHttpResponse"]);n!=null&&l(e,["sdkHttpResponse"],n);let r=s(t,["nextPageToken"]);r!=null&&l(e,["nextPageToken"],r);let i=s(t,["batchPredictionJobs"]);if(i!=null){let o=i;Array.isArray(o)&&(o=o.map(a=>kl(a))),l(e,["batchJobs"],o)}return e}function lS(t){let e={},n=s(t,["mediaResolution"]);n!=null&&l(e,["mediaResolution"],n);let r=s(t,["toolCall"]);r!=null&&l(e,["toolCall"],r);let i=s(t,["toolResponse"]);i!=null&&l(e,["toolResponse"],i);let o=s(t,["audioTranscription"]);o!=null&&l(e,["audioTranscription"],o);let a=s(t,["codeExecutionResult"]);a!=null&&l(e,["codeExecutionResult"],a);let u=s(t,["executableCode"]);u!=null&&l(e,["executableCode"],u);let c=s(t,["fileData"]);c!=null&&l(e,["fileData"],$0(c));let d=s(t,["functionCall"]);d!=null&&l(e,["functionCall"],J0(d));let f=s(t,["functionResponse"]);f!=null&&l(e,["functionResponse"],f);let p=s(t,["inlineData"]);p!=null&&l(e,["inlineData"],P0(p));let h=s(t,["text"]);h!=null&&l(e,["text"],h);let m=s(t,["thought"]);m!=null&&l(e,["thought"],m);let _=s(t,["thoughtSignature"]);_!=null&&l(e,["thoughtSignature"],_);let g=s(t,["videoMetadata"]);g!=null&&l(e,["videoMetadata"],g);let E=s(t,["partMetadata"]);return E!=null&&l(e,["partMetadata"],E),e}function uS(t){let e={},n=s(t,["category"]);if(n!=null&&l(e,["category"],n),s(t,["method"])!==void 0)throw new Error("method parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let r=s(t,["threshold"]);return r!=null&&l(e,["threshold"],r),e}function cS(t){let e={},n=s(t,["functionCallingConfig"]);n!=null&&l(e,["functionCallingConfig"],W0(n));let r=s(t,["retrievalConfig"]);r!=null&&l(e,["retrievalConfig"],r);let i=s(t,["includeServerSideToolInvocations"]);return i!=null&&l(e,["includeServerSideToolInvocations"],i),e}function dS(t){let e={};if(s(t,["retrieval"])!==void 0)throw new Error("retrieval parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let n=s(t,["googleMaps"]);n!=null&&l(e,["googleMaps"],Q0(n));let r=s(t,["mcpServers"]);if(r!=null){let p=r;Array.isArray(p)&&(p=p.map(h=>h)),l(e,["mcpServers"],p)}let i=s(t,["codeExecution"]);i!=null&&l(e,["codeExecution"],i);let o=s(t,["computerUse"]);if(o!=null&&l(e,["computerUse"],o),s(t,["enterpriseWebSearch"])!==void 0)throw new Error("enterpriseWebSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["exaAiSearch"])!==void 0)throw new Error("exaAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let a=s(t,["functionDeclarations"]);if(a!=null){let p=a;Array.isArray(p)&&(p=p.map(h=>h)),l(e,["functionDeclarations"],p)}let u=s(t,["googleSearch"]);u!=null&&l(e,["googleSearch"],Z0(u));let c=s(t,["googleSearchRetrieval"]);if(c!=null&&l(e,["googleSearchRetrieval"],c),s(t,["parallelAiSearch"])!==void 0)throw new Error("parallelAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let d=s(t,["urlContext"]);d!=null&&l(e,["urlContext"],d);let f=s(t,["fileSearch"]);return f!=null&&l(e,["fileSearch"],f),e}function fS(t){let e={},n=s(t,["bigqueryDestination","outputUri"]);n!=null&&l(e,["bigqueryDestination"],n);let r=s(t,["displayName"]);return r!=null&&l(e,["displayName"],r),e}function pS(t){let e={},n=s(t,["bigqueryDestination"]);n!=null&&l(e,["bigqueryDestination","outputUri"],n);let r=s(t,["displayName"]);return r!=null&&l(e,["displayName"],r),e}var Mt;(function(t){t.PAGED_ITEM_BATCH_JOBS="batchJobs",t.PAGED_ITEM_MODELS="models",t.PAGED_ITEM_TUNING_JOBS="tuningJobs",t.PAGED_ITEM_FILES="files",t.PAGED_ITEM_CACHED_CONTENTS="cachedContents",t.PAGED_ITEM_FILE_SEARCH_STORES="fileSearchStores",t.PAGED_ITEM_DOCUMENTS="documents",t.PAGED_ITEM_SKILLS="skills"})(Mt||(Mt={}));var Ut=class{constructor(e,n,r,i){this.pageInternal=[],this.paramsInternal={},this.requestInternal=n,this.init(e,r,i)}init(e,n,r){var i,o;this.nameInternal=e,this.pageInternal=n[this.nameInternal]||[],this.sdkHttpResponseInternal=n?.sdkHttpResponse,this.idxInternal=0;let a={config:{}};!r||Object.keys(r).length===0?a={config:{}}:typeof r=="object"?a=Object.assign({},r):a=r,a.config&&(a.config.pageToken=n.nextPageToken),this.paramsInternal=a,this.pageInternalSize=(o=(i=a.config)===null||i===void 0?void 0:i.pageSize)!==null&&o!==void 0?o:this.pageInternal.length}initNextPage(e){this.init(this.nameInternal,e,this.paramsInternal)}get page(){return this.pageInternal}get name(){return this.nameInternal}get pageSize(){return this.pageInternalSize}get sdkHttpResponse(){return this.sdkHttpResponseInternal}get params(){return this.paramsInternal}get pageLength(){return this.pageInternal.length}getItem(e){return this.pageInternal[e]}[Symbol.asyncIterator](){return{next:async()=>{if(this.idxInternal>=this.pageLength)if(this.hasNextPage())await this.nextPage();else return{value:void 0,done:!0};let e=this.getItem(this.idxInternal);return this.idxInternal+=1,{value:e,done:!1}},return:async()=>({value:void 0,done:!0})}}async nextPage(){if(!this.hasNextPage())throw new Error("No more pages to fetch.");let e=await this.requestInternal(this.params);return this.initNextPage(e),this.page}hasNextPage(){var e;return((e=this.params.config)===null||e===void 0?void 0:e.pageToken)!==void 0}};var Dl=class extends dt{constructor(e){super(),this.apiClient=e,this.list=async(n={})=>new Ut(Mt.PAGED_ITEM_BATCH_JOBS,r=>this.listInternal(r),await this.listInternal(n),n),this.create=async n=>(this.apiClient.isVertexAI()&&(n.config=this.formatDestination(n.src,n.config)),this.createInternal(n)),this.createEmbeddings=async n=>{if(console.warn("batches.createEmbeddings() is experimental and may change without notice."),this.apiClient.isVertexAI())throw new Error("Gemini Enterprise Agent Platform (previously known as Vertex AI) does not support batches.createEmbeddings.");return this.createEmbeddingsInternal(n)}}createInlinedGenerateContentRequest(e){let n=Gm(this.apiClient,e),r=n._url,i=$("{model}:batchGenerateContent",r),u=n.batch.inputConfig.requests,c=u.requests,d=[];for(let f of c){let p=Object.assign({},f);if(p.systemInstruction){let h=p.systemInstruction;delete p.systemInstruction;let m=p.request;m.systemInstruction=h,p.request=m}d.push(p)}return u.requests=d,delete n.config,delete n._url,delete n._query,{path:i,body:n}}getGcsUri(e){if(typeof e=="string")return e.startsWith("gs://")?e:void 0;if(!Array.isArray(e)&&e.gcsUri&&e.gcsUri.length>0)return e.gcsUri[0]}getBigqueryUri(e){if(typeof e=="string")return e.startsWith("bq://")?e:void 0;if(!Array.isArray(e))return e.bigqueryUri}formatDestination(e,n){let r=n?Object.assign({},n):{},i=Date.now().toString();if(r.displayName||(r.displayName=`genaiBatchJob_${i}`),r.dest===void 0){let o=this.getGcsUri(e),a=this.getBigqueryUri(e);if(o)o.endsWith(".jsonl")?r.dest=`${o.slice(0,-6)}/dest`:r.dest=`${o}_dest_${i}`;else if(a)r.dest=`${a}_dest_${i}`;else throw new Error("Unsupported source for Gemini Enterprise Agent Platform (previously known as Vertex AI): No GCS or BigQuery URI found.")}return r}async createInternal(e){var n,r,i,o;let a,u="",c={};if(this.apiClient.isVertexAI()){let d=U0(this.apiClient,e);return u=$("batchPredictionJobs",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(f=>f.json()),a.then(f=>kl(f))}else{let d=Gm(this.apiClient,e);return u=$("{model}:batchGenerateContent",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(f=>f.json()),a.then(f=>eo(f))}}async createEmbeddingsInternal(e){var n,r;let i,o="",a={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let u=G0(this.apiClient,e);return o=$("{model}:asyncBatchEmbedContent",u._url),a=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:o,queryParams:a,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(c=>c.json()),i.then(c=>eo(c))}}async get(e){var n,r,i,o;let a,u="",c={};if(this.apiClient.isVertexAI()){let d=z0(this.apiClient,e);return u=$("batchPredictionJobs/{name}",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(f=>f.json()),a.then(f=>kl(f))}else{let d=Y0(this.apiClient,e);return u=$("batches/{name}",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"GET",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(f=>f.json()),a.then(f=>eo(f))}}async cancel(e){var n,r,i,o;let a="",u={};if(this.apiClient.isVertexAI()){let c=N0(this.apiClient,e);a=$("batchPredictionJobs/{name}:cancel",c._url),u=c._query,delete c._url,delete c._query,await this.apiClient.request({path:a,queryParams:u,body:JSON.stringify(c),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal})}else{let c=R0(this.apiClient,e);a=$("batches/{name}:cancel",c._url),u=c._query,delete c._url,delete c._query,await this.apiClient.request({path:a,queryParams:u,body:JSON.stringify(c),httpMethod:"POST",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal})}}async listInternal(e){var n,r,i,o;let a,u="",c={};if(this.apiClient.isVertexAI()){let d=oS(e);return u=$("batchPredictionJobs",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(f=>f.json().then(p=>{let h=p;return h.sdkHttpResponse={headers:f.headers},h})),a.then(f=>{let p=aS(f),h=new ho;return Object.assign(h,p),h})}else{let d=iS(e);return u=$("batches",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"GET",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(f=>f.json().then(p=>{let h=p;return h.sdkHttpResponse={headers:f.headers},h})),a.then(f=>{let p=sS(f),h=new ho;return Object.assign(h,p),h})}}async delete(e){var n,r,i,o;let a,u="",c={};if(this.apiClient.isVertexAI()){let d=O0(this.apiClient,e);return u=$("batchPredictionJobs/{name}",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"DELETE",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(f=>f.json().then(p=>{let h=p;return h.sdkHttpResponse={headers:f.headers},h})),a.then(f=>F0(f))}else{let d=L0(this.apiClient,e);return u=$("batches/{name}",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"DELETE",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(f=>f.json().then(p=>{let h=p;return h.sdkHttpResponse={headers:f.headers},h})),a.then(f=>q0(f))}}};function hS(t){let e={},n=s(t,["apiKey"]);if(n!=null&&l(e,["apiKey"],n),s(t,["apiKeyConfig"])!==void 0)throw new Error("apiKeyConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["authType"])!==void 0)throw new Error("authType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["googleServiceAccountConfig"])!==void 0)throw new Error("googleServiceAccountConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["httpBasicAuthConfig"])!==void 0)throw new Error("httpBasicAuthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["oauthConfig"])!==void 0)throw new Error("oauthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["oidcConfig"])!==void 0)throw new Error("oidcConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return e}function mS(t){let e={},n=s(t,["data"]);if(n!=null&&l(e,["data"],n),s(t,["displayName"])!==void 0)throw new Error("displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let r=s(t,["mimeType"]);return r!=null&&l(e,["mimeType"],r),e}function gS(t){let e={},n=s(t,["outcome"]);n!=null&&l(e,["outcome"],n);let r=s(t,["output"]);if(r!=null&&l(e,["output"],r),s(t,["id"])!==void 0)throw new Error("id parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return e}function _S(t){let e={},n=s(t,["enablePromptInjectionDetection"]);n!=null&&l(e,["enablePromptInjectionDetection"],n);let r=s(t,["environment"]);r!=null&&l(e,["environment"],r);let i=s(t,["excludedPredefinedFunctions"]);if(i!=null&&l(e,["excludedPredefinedFunctions"],i),s(t,["disabledSafetyPolicies"])!==void 0)throw new Error("disabledSafetyPolicies parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return e}function Lm(t){let e={},n=s(t,["parts"]);if(n!=null){let i=n;Array.isArray(i)&&(i=i.map(o=>BS(o))),l(e,["parts"],i)}let r=s(t,["role"]);return r!=null&&l(e,["role"],r),e}function Om(t){let e={},n=s(t,["parts"]);if(n!=null){let i=n;Array.isArray(i)&&(i=i.map(o=>HS(o))),l(e,["parts"],i)}let r=s(t,["role"]);return r!=null&&l(e,["role"],r),e}function yS(t,e){let n={},r=s(t,["ttl"]);e!==void 0&&r!=null&&l(e,["ttl"],r);let i=s(t,["expireTime"]);e!==void 0&&i!=null&&l(e,["expireTime"],i);let o=s(t,["displayName"]);e!==void 0&&o!=null&&l(e,["displayName"],o);let a=s(t,["contents"]);if(e!==void 0&&a!=null){let f=Le(a);Array.isArray(f)&&(f=f.map(p=>Lm(p))),l(e,["contents"],f)}let u=s(t,["systemInstruction"]);e!==void 0&&u!=null&&l(e,["systemInstruction"],Lm(xe(u)));let c=s(t,["tools"]);if(e!==void 0&&c!=null){let f=c;Array.isArray(f)&&(f=f.map(p=>JS(p))),l(e,["tools"],f)}let d=s(t,["toolConfig"]);if(e!==void 0&&d!=null&&l(e,["toolConfig"],VS(d)),s(t,["kmsKeyName"])!==void 0)throw new Error("kmsKeyName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return n}function ES(t,e){let n={},r=s(t,["ttl"]);e!==void 0&&r!=null&&l(e,["ttl"],r);let i=s(t,["expireTime"]);e!==void 0&&i!=null&&l(e,["expireTime"],i);let o=s(t,["displayName"]);e!==void 0&&o!=null&&l(e,["displayName"],o);let a=s(t,["contents"]);if(e!==void 0&&a!=null){let p=Le(a);Array.isArray(p)&&(p=p.map(h=>Om(h))),l(e,["contents"],p)}let u=s(t,["systemInstruction"]);e!==void 0&&u!=null&&l(e,["systemInstruction"],Om(xe(u)));let c=s(t,["tools"]);if(e!==void 0&&c!=null){let p=c;Array.isArray(p)&&(p=p.map(h=>WS(h))),l(e,["tools"],p)}let d=s(t,["toolConfig"]);e!==void 0&&d!=null&&l(e,["toolConfig"],$S(d));let f=s(t,["kmsKeyName"]);return e!==void 0&&f!=null&&l(e,["encryption_spec","kmsKeyName"],f),n}function vS(t,e){let n={},r=s(e,["model"]);r!=null&&l(n,["model"],Eg(t,r));let i=s(e,["config"]);return i!=null&&yS(i,n),n}function TS(t,e){let n={},r=s(e,["model"]);r!=null&&l(n,["model"],Eg(t,r));let i=s(e,["config"]);return i!=null&&ES(i,n),n}function AS(t,e){let n={},r=s(e,["name"]);return r!=null&&l(n,["_url","name"],bt(t,r)),n}function CS(t,e){let n={},r=s(e,["name"]);return r!=null&&l(n,["_url","name"],bt(t,r)),n}function SS(t){let e={},n=s(t,["sdkHttpResponse"]);return n!=null&&l(e,["sdkHttpResponse"],n),e}function IS(t){let e={},n=s(t,["sdkHttpResponse"]);return n!=null&&l(e,["sdkHttpResponse"],n),e}function wS(t){let e={},n=s(t,["code"]);n!=null&&l(e,["code"],n);let r=s(t,["language"]);if(r!=null&&l(e,["language"],r),s(t,["id"])!==void 0)throw new Error("id parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return e}function PS(t){let e={};if(s(t,["displayName"])!==void 0)throw new Error("displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let n=s(t,["fileUri"]);n!=null&&l(e,["fileUri"],n);let r=s(t,["mimeType"]);return r!=null&&l(e,["mimeType"],r),e}function RS(t){let e={},n=s(t,["args"]);n!=null&&l(e,["args"],n);let r=s(t,["id"]);r!=null&&l(e,["id"],r);let i=s(t,["name"]);if(i!=null&&l(e,["name"],i),s(t,["partialArgs"])!==void 0)throw new Error("partialArgs parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["willContinue"])!==void 0)throw new Error("willContinue parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return e}function NS(t){let e={},n=s(t,["allowedFunctionNames"]);n!=null&&l(e,["allowedFunctionNames"],n);let r=s(t,["mode"]);if(r!=null&&l(e,["mode"],r),s(t,["streamFunctionCallArguments"])!==void 0)throw new Error("streamFunctionCallArguments parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return e}function xS(t,e){let n={},r=s(e,["name"]);return r!=null&&l(n,["_url","name"],bt(t,r)),n}function kS(t,e){let n={},r=s(e,["name"]);return r!=null&&l(n,["_url","name"],bt(t,r)),n}function DS(t){let e={},n=s(t,["authConfig"]);n!=null&&l(e,["authConfig"],hS(n));let r=s(t,["enableWidget"]);if(r!=null&&l(e,["enableWidget"],r),s(t,["groundingTypes"])!==void 0)throw new Error("groundingTypes parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return e}function MS(t){let e={};if(s(t,["blockingConfidence"])!==void 0)throw new Error("blockingConfidence parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["excludeDomains"])!==void 0)throw new Error("excludeDomains parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let n=s(t,["searchTypes"]);n!=null&&l(e,["searchTypes"],n);let r=s(t,["timeRangeFilter"]);return r!=null&&l(e,["timeRangeFilter"],r),e}function US(t,e){let n={},r=s(t,["pageSize"]);e!==void 0&&r!=null&&l(e,["_query","pageSize"],r);let i=s(t,["pageToken"]);return e!==void 0&&i!=null&&l(e,["_query","pageToken"],i),n}function bS(t,e){let n={},r=s(t,["pageSize"]);e!==void 0&&r!=null&&l(e,["_query","pageSize"],r);let i=s(t,["pageToken"]);return e!==void 0&&i!=null&&l(e,["_query","pageToken"],i),n}function GS(t){let e={},n=s(t,["config"]);return n!=null&&US(n,e),e}function LS(t){let e={},n=s(t,["config"]);return n!=null&&bS(n,e),e}function OS(t){let e={},n=s(t,["sdkHttpResponse"]);n!=null&&l(e,["sdkHttpResponse"],n);let r=s(t,["nextPageToken"]);r!=null&&l(e,["nextPageToken"],r);let i=s(t,["cachedContents"]);if(i!=null){let o=i;Array.isArray(o)&&(o=o.map(a=>a)),l(e,["cachedContents"],o)}return e}function qS(t){let e={},n=s(t,["sdkHttpResponse"]);n!=null&&l(e,["sdkHttpResponse"],n);let r=s(t,["nextPageToken"]);r!=null&&l(e,["nextPageToken"],r);let i=s(t,["cachedContents"]);if(i!=null){let o=i;Array.isArray(o)&&(o=o.map(a=>a)),l(e,["cachedContents"],o)}return e}function FS(t){let e={};if(s(t,["name"])!==void 0)throw new Error("name parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(s(t,["streamableHttpTransport"])!==void 0)throw new Error("streamableHttpTransport parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return e}function BS(t){let e={},n=s(t,["mediaResolution"]);n!=null&&l(e,["mediaResolution"],n);let r=s(t,["toolCall"]);r!=null&&l(e,["toolCall"],r);let i=s(t,["toolResponse"]);i!=null&&l(e,["toolResponse"],i);let o=s(t,["audioTranscription"]);o!=null&&l(e,["audioTranscription"],o);let a=s(t,["codeExecutionResult"]);a!=null&&l(e,["codeExecutionResult"],a);let u=s(t,["executableCode"]);u!=null&&l(e,["executableCode"],u);let c=s(t,["fileData"]);c!=null&&l(e,["fileData"],PS(c));let d=s(t,["functionCall"]);d!=null&&l(e,["functionCall"],RS(d));let f=s(t,["functionResponse"]);f!=null&&l(e,["functionResponse"],f);let p=s(t,["inlineData"]);p!=null&&l(e,["inlineData"],mS(p));let h=s(t,["text"]);h!=null&&l(e,["text"],h);let m=s(t,["thought"]);m!=null&&l(e,["thought"],m);let _=s(t,["thoughtSignature"]);_!=null&&l(e,["thoughtSignature"],_);let g=s(t,["videoMetadata"]);g!=null&&l(e,["videoMetadata"],g);let E=s(t,["partMetadata"]);return E!=null&&l(e,["partMetadata"],E),e}function HS(t){let e={},n=s(t,["mediaResolution"]);if(n!=null&&l(e,["mediaResolution"],n),s(t,["toolCall"])!==void 0)throw new Error("toolCall parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(s(t,["toolResponse"])!==void 0)throw new Error("toolResponse parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");let r=s(t,["audioTranscription"]);r!=null&&l(e,["audioTranscription"],r);let i=s(t,["codeExecutionResult"]);i!=null&&l(e,["codeExecutionResult"],gS(i));let o=s(t,["executableCode"]);o!=null&&l(e,["executableCode"],wS(o));let a=s(t,["fileData"]);a!=null&&l(e,["fileData"],a);let u=s(t,["functionCall"]);u!=null&&l(e,["functionCall"],u);let c=s(t,["functionResponse"]);c!=null&&l(e,["functionResponse"],c);let d=s(t,["inlineData"]);d!=null&&l(e,["inlineData"],d);let f=s(t,["text"]);f!=null&&l(e,["text"],f);let p=s(t,["thought"]);p!=null&&l(e,["thought"],p);let h=s(t,["thoughtSignature"]);h!=null&&l(e,["thoughtSignature"],h);let m=s(t,["videoMetadata"]);if(m!=null&&l(e,["videoMetadata"],m),s(t,["partMetadata"])!==void 0)throw new Error("partMetadata parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return e}function VS(t){let e={},n=s(t,["functionCallingConfig"]);n!=null&&l(e,["functionCallingConfig"],NS(n));let r=s(t,["retrievalConfig"]);r!=null&&l(e,["retrievalConfig"],r);let i=s(t,["includeServerSideToolInvocations"]);return i!=null&&l(e,["includeServerSideToolInvocations"],i),e}function $S(t){let e={},n=s(t,["functionCallingConfig"]);n!=null&&l(e,["functionCallingConfig"],n);let r=s(t,["retrievalConfig"]);if(r!=null&&l(e,["retrievalConfig"],r),s(t,["includeServerSideToolInvocations"])!==void 0)throw new Error("includeServerSideToolInvocations parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return e}function JS(t){let e={};if(s(t,["retrieval"])!==void 0)throw new Error("retrieval parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let n=s(t,["googleMaps"]);n!=null&&l(e,["googleMaps"],DS(n));let r=s(t,["mcpServers"]);if(r!=null){let p=r;Array.isArray(p)&&(p=p.map(h=>h)),l(e,["mcpServers"],p)}let i=s(t,["codeExecution"]);i!=null&&l(e,["codeExecution"],i);let o=s(t,["computerUse"]);if(o!=null&&l(e,["computerUse"],o),s(t,["enterpriseWebSearch"])!==void 0)throw new Error("enterpriseWebSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["exaAiSearch"])!==void 0)throw new Error("exaAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let a=s(t,["functionDeclarations"]);if(a!=null){let p=a;Array.isArray(p)&&(p=p.map(h=>h)),l(e,["functionDeclarations"],p)}let u=s(t,["googleSearch"]);u!=null&&l(e,["googleSearch"],MS(u));let c=s(t,["googleSearchRetrieval"]);if(c!=null&&l(e,["googleSearchRetrieval"],c),s(t,["parallelAiSearch"])!==void 0)throw new Error("parallelAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let d=s(t,["urlContext"]);d!=null&&l(e,["urlContext"],d);let f=s(t,["fileSearch"]);return f!=null&&l(e,["fileSearch"],f),e}function WS(t){let e={},n=s(t,["retrieval"]);n!=null&&l(e,["retrieval"],n);let r=s(t,["googleMaps"]);r!=null&&l(e,["googleMaps"],r);let i=s(t,["mcpServers"]);if(i!=null){let _=i;Array.isArray(_)&&(_=_.map(g=>FS(g))),l(e,["mcpServers"],_)}let o=s(t,["codeExecution"]);o!=null&&l(e,["codeExecution"],o);let a=s(t,["computerUse"]);a!=null&&l(e,["computerUse"],_S(a));let u=s(t,["enterpriseWebSearch"]);u!=null&&l(e,["enterpriseWebSearch"],u);let c=s(t,["exaAiSearch"]);c!=null&&l(e,["exaAiSearch"],c);let d=s(t,["functionDeclarations"]);if(d!=null){let _=d;Array.isArray(_)&&(_=_.map(g=>g)),l(e,["functionDeclarations"],_)}let f=s(t,["googleSearch"]);f!=null&&l(e,["googleSearch"],f);let p=s(t,["googleSearchRetrieval"]);p!=null&&l(e,["googleSearchRetrieval"],p);let h=s(t,["parallelAiSearch"]);h!=null&&l(e,["parallelAiSearch"],h);let m=s(t,["urlContext"]);if(m!=null&&l(e,["urlContext"],m),s(t,["fileSearch"])!==void 0)throw new Error("fileSearch parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return e}function XS(t,e){let n={},r=s(t,["ttl"]);e!==void 0&&r!=null&&l(e,["ttl"],r);let i=s(t,["expireTime"]);return e!==void 0&&i!=null&&l(e,["expireTime"],i),n}function KS(t,e){let n={},r=s(t,["ttl"]);e!==void 0&&r!=null&&l(e,["ttl"],r);let i=s(t,["expireTime"]);return e!==void 0&&i!=null&&l(e,["expireTime"],i),n}function YS(t,e){let n={},r=s(e,["name"]);r!=null&&l(n,["_url","name"],bt(t,r));let i=s(e,["config"]);return i!=null&&XS(i,n),n}function zS(t,e){let n={},r=s(e,["name"]);r!=null&&l(n,["_url","name"],bt(t,r));let i=s(e,["config"]);return i!=null&&KS(i,n),n}var Ml=class extends dt{constructor(e){super(),this.apiClient=e,this.list=async(n={})=>new Ut(Mt.PAGED_ITEM_CACHED_CONTENTS,r=>this.listInternal(r),await this.listInternal(n),n)}async create(e){var n,r,i,o;let a,u="",c={};if(this.apiClient.isVertexAI()){let d=TS(this.apiClient,e);return u=$("cachedContents",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(f=>f.json()),a.then(f=>f)}else{let d=vS(this.apiClient,e);return u=$("cachedContents",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(f=>f.json()),a.then(f=>f)}}async get(e){var n,r,i,o;let a,u="",c={};if(this.apiClient.isVertexAI()){let d=kS(this.apiClient,e);return u=$("{name}",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(f=>f.json()),a.then(f=>f)}else{let d=xS(this.apiClient,e);return u=$("{name}",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"GET",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(f=>f.json()),a.then(f=>f)}}async delete(e){var n,r,i,o;let a,u="",c={};if(this.apiClient.isVertexAI()){let d=CS(this.apiClient,e);return u=$("{name}",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"DELETE",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(f=>f.json().then(p=>{let h=p;return h.sdkHttpResponse={headers:f.headers},h})),a.then(f=>{let p=IS(f),h=new fo;return Object.assign(h,p),h})}else{let d=AS(this.apiClient,e);return u=$("{name}",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"DELETE",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(f=>f.json().then(p=>{let h=p;return h.sdkHttpResponse={headers:f.headers},h})),a.then(f=>{let p=SS(f),h=new fo;return Object.assign(h,p),h})}}async update(e){var n,r,i,o;let a,u="",c={};if(this.apiClient.isVertexAI()){let d=zS(this.apiClient,e);return u=$("{name}",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"PATCH",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(f=>f.json()),a.then(f=>f)}else{let d=YS(this.apiClient,e);return u=$("{name}",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"PATCH",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(f=>f.json()),a.then(f=>f)}}async listInternal(e){var n,r,i,o;let a,u="",c={};if(this.apiClient.isVertexAI()){let d=LS(e);return u=$("cachedContents",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(f=>f.json().then(p=>{let h=p;return h.sdkHttpResponse={headers:f.headers},h})),a.then(f=>{let p=qS(f),h=new po;return Object.assign(h,p),h})}else{let d=GS(e);return u=$("cachedContents",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"GET",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(f=>f.json().then(p=>{let h=p;return h.sdkHttpResponse={headers:f.headers},h})),a.then(f=>{let p=OS(f),h=new po;return Object.assign(h,p),h})}}};function Ue(t,e){var n={};for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&e.indexOf(r)<0&&(n[r]=t[r]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,r=Object.getOwnPropertySymbols(t);i<r.length;i++)e.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(t,r[i])&&(n[r[i]]=t[r[i]]);return n}function qm(t){var e=typeof Symbol=="function"&&Symbol.iterator,n=e&&t[e],r=0;if(n)return n.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&r>=t.length&&(t=void 0),{value:t&&t[r++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function ye(t){return this instanceof ye?(this.v=t,this):new ye(t)}function Xn(t,e,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r=n.apply(t,e||[]),i,o=[];return i=Object.create((typeof AsyncIterator=="function"?AsyncIterator:Object).prototype),u("next"),u("throw"),u("return",a),i[Symbol.asyncIterator]=function(){return this},i;function a(m){return function(_){return Promise.resolve(_).then(m,p)}}function u(m,_){r[m]&&(i[m]=function(g){return new Promise(function(E,y){o.push([m,g,E,y])>1||c(m,g)})},_&&(i[m]=_(i[m])))}function c(m,_){try{d(r[m](_))}catch(g){h(o[0][3],g)}}function d(m){m.value instanceof ye?Promise.resolve(m.value.v).then(f,p):h(o[0][2],m)}function f(m){c("next",m)}function p(m){c("throw",m)}function h(m,_){m(_),o.shift(),o.length&&c(o[0][0],o[0][1])}}function Pr(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],n;return e?e.call(t):(t=typeof qm=="function"?qm(t):t[Symbol.iterator](),n={},r("next"),r("throw"),r("return"),n[Symbol.asyncIterator]=function(){return this},n);function r(o){n[o]=t[o]&&function(a){return new Promise(function(u,c){a=t[o](a),i(u,c,a.done,a.value)})}}function i(o,a,u,c){Promise.resolve(c).then(function(d){o({value:d,done:u})},a)}}function QS(t){var e;if(t.candidates==null||t.candidates.length===0)return!1;let n=(e=t.candidates[0])===null||e===void 0?void 0:e.content;return n===void 0?!1:Mg(n)}function Mg(t){if(t.parts===void 0||t.parts.length===0)return!1;for(let e of t.parts)if(e===void 0||Object.keys(e).length===0)return!1;return!0}function ZS(t){if(t.length!==0){for(let e of t)if(e.role!=="user"&&e.role!=="model")throw new Error(`Role must be user or model, but got ${e.role}.`)}}function Fm(t){if(t===void 0||t.length===0)return[];let e=[],n=t.length,r=0;for(;r<n;)if(t[r].role==="user")e.push(t[r]),r++;else{let i=[],o=!0;for(;r<n&&t[r].role==="model";)i.push(t[r]),o&&!Mg(t[r])&&(o=!1),r++;o?e.push(...i):e.pop()}return e}var Ul=class{constructor(e,n){this.modelsModule=e,this.apiClient=n}create(e){return new bl(this.apiClient,this.modelsModule,e.model,e.config,structuredClone(e.history))}},bl=class{constructor(e,n,r,i={},o=[]){this.apiClient=e,this.modelsModule=n,this.model=r,this.config=i,this.history=o,this.sendPromise=Promise.resolve(),ZS(o)}async sendMessage(e){var n;await this.sendPromise;let r=xe(e.message),i=this.modelsModule.generateContent({model:this.model,contents:this.getHistory(!0).concat(r),config:(n=e.config)!==null&&n!==void 0?n:this.config});return this.sendPromise=(async()=>{var o,a,u;let c=await i,d=(a=(o=c.candidates)===null||o===void 0?void 0:o[0])===null||a===void 0?void 0:a.content,f=c.automaticFunctionCallingHistory,p=this.getHistory(!0).length,h=[];f!=null&&(h=(u=f.slice(p))!==null&&u!==void 0?u:[]);let m=d?[d]:[];this.recordHistory(r,m,h)})(),await this.sendPromise.catch(()=>{this.sendPromise=Promise.resolve()}),i}async sendMessageStream(e){var n;await this.sendPromise;let r=xe(e.message),i=this.modelsModule.generateContentStream({model:this.model,contents:this.getHistory(!0).concat(r),config:(n=e.config)!==null&&n!==void 0?n:this.config});this.sendPromise=i.then(()=>{}).catch(()=>{});let o=await i;return this.processStreamResponse(o,r)}getHistory(e=!1){let n=e?Fm(this.history):this.history;return structuredClone(n)}processStreamResponse(e,n){return Xn(this,arguments,function*(){var i,o,a,u,c,d;let f=[];try{for(var p=!0,h=Pr(e),m;m=yield ye(h.next()),i=m.done,!i;p=!0){u=m.value,p=!1;let _=u;if(QS(_)){let g=(d=(c=_.candidates)===null||c===void 0?void 0:c[0])===null||d===void 0?void 0:d.content;g!==void 0&&f.push(g)}yield yield ye(_)}}catch(_){o={error:_}}finally{try{!p&&!i&&(a=h.return)&&(yield ye(a.call(h)))}finally{if(o)throw o.error}}this.recordHistory(n,f)})}recordHistory(e,n,r){let i=[];n.length>0&&n.every(o=>o.role!==void 0)?i=n:i.push({role:"model",parts:[]}),r&&r.length>0?this.history.push(...Fm(r)):this.history.push(e),this.history.push(...i)}};var _o=class t extends Error{constructor(e){super(e.message),this.name="ApiError",this.status=e.status,Object.setPrototypeOf(this,t.prototype)}};function jS(t){let e={},n=s(t,["file"]);return n!=null&&l(e,["file"],n),e}function eI(t){let e={},n=s(t,["sdkHttpResponse"]);return n!=null&&l(e,["sdkHttpResponse"],n),e}function tI(t){let e={},n=s(t,["name"]);return n!=null&&l(e,["_url","file"],$u(n)),e}function nI(t){let e={},n=s(t,["sdkHttpResponse"]);return n!=null&&l(e,["sdkHttpResponse"],n),e}function rI(t){let e={},n=s(t,["name"]);return n!=null&&l(e,["_url","file"],$u(n)),e}function iI(t){let e={},n=s(t,["uris"]);return n!=null&&l(e,["uris"],n),e}function oI(t,e){let n={},r=s(t,["pageSize"]);e!==void 0&&r!=null&&l(e,["_query","pageSize"],r);let i=s(t,["pageToken"]);return e!==void 0&&i!=null&&l(e,["_query","pageToken"],i),n}function sI(t){let e={},n=s(t,["config"]);return n!=null&&oI(n,e),e}function aI(t){let e={},n=s(t,["sdkHttpResponse"]);n!=null&&l(e,["sdkHttpResponse"],n);let r=s(t,["nextPageToken"]);r!=null&&l(e,["nextPageToken"],r);let i=s(t,["files"]);if(i!=null){let o=i;Array.isArray(o)&&(o=o.map(a=>a)),l(e,["files"],o)}return e}function lI(t){let e={},n=s(t,["sdkHttpResponse"]);n!=null&&l(e,["sdkHttpResponse"],n);let r=s(t,["files"]);if(r!=null){let i=r;Array.isArray(i)&&(i=i.map(o=>o)),l(e,["files"],i)}return e}var Gl=class extends dt{constructor(e){super(),this.apiClient=e,this.list=async(n={})=>new Ut(Mt.PAGED_ITEM_FILES,r=>this.listInternal(r),await this.listInternal(n),n)}async upload(e){if(this.apiClient.isVertexAI())throw new Error("Gemini Enterprise Agent Platform (previously known as Vertex AI) does not support uploading files. You can share files through a GCS bucket.");return this.apiClient.uploadFile(e.file,e.config).then(n=>n)}async download(e){await this.apiClient.downloadFile(e)}async registerFiles(e){throw new Error("registerFiles is only supported in Node.js environments.")}async _registerFiles(e){return this.registerFilesInternal(e)}async listInternal(e){var n,r;let i,o="",a={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let u=sI(e);return o=$("files",u._url),a=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:o,queryParams:a,body:JSON.stringify(u),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(c=>c.json().then(d=>{let f=d;return f.sdkHttpResponse={headers:c.headers},f})),i.then(c=>{let d=aI(c),f=new Sl;return Object.assign(f,d),f})}}async createInternal(e){var n,r;let i,o="",a={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let u=jS(e);return o=$("upload/v1beta/files",u._url),a=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:o,queryParams:a,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(c=>c.json()),i.then(c=>{let d=eI(c),f=new Il;return Object.assign(f,d),f})}}async get(e){var n,r;let i,o="",a={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let u=rI(e);return o=$("files/{file}",u._url),a=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:o,queryParams:a,body:JSON.stringify(u),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(c=>c.json()),i.then(c=>c)}}async delete(e){var n,r;let i,o="",a={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let u=tI(e);return o=$("files/{file}",u._url),a=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:o,queryParams:a,body:JSON.stringify(u),httpMethod:"DELETE",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(c=>c.json().then(d=>{let f=d;return f.sdkHttpResponse={headers:c.headers},f})),i.then(c=>{let d=nI(c),f=new wl;return Object.assign(f,d),f})}}async registerFilesInternal(e){var n,r;let i,o="",a={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let u=iI(e);return o=$("files:register",u._url),a=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:o,queryParams:a,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(c=>c.json()),i.then(c=>{let d=lI(c),f=new Pl;return Object.assign(f,d),f})}}};function uI(t){let e={},n=s(t,["apiKey"]);if(n!=null&&l(e,["apiKey"],n),s(t,["apiKeyConfig"])!==void 0)throw new Error("apiKeyConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["authType"])!==void 0)throw new Error("authType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["googleServiceAccountConfig"])!==void 0)throw new Error("googleServiceAccountConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["httpBasicAuthConfig"])!==void 0)throw new Error("httpBasicAuthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["oauthConfig"])!==void 0)throw new Error("oauthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["oidcConfig"])!==void 0)throw new Error("oidcConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return e}function to(t){let e={},n=s(t,["data"]);if(n!=null&&l(e,["data"],n),s(t,["displayName"])!==void 0)throw new Error("displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let r=s(t,["mimeType"]);return r!=null&&l(e,["mimeType"],r),e}function cI(t){let e={},n=s(t,["outcome"]);n!=null&&l(e,["outcome"],n);let r=s(t,["output"]);if(r!=null&&l(e,["output"],r),s(t,["id"])!==void 0)throw new Error("id parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return e}function dI(t){let e={},n=s(t,["enablePromptInjectionDetection"]);n!=null&&l(e,["enablePromptInjectionDetection"],n);let r=s(t,["environment"]);r!=null&&l(e,["environment"],r);let i=s(t,["excludedPredefinedFunctions"]);if(i!=null&&l(e,["excludedPredefinedFunctions"],i),s(t,["disabledSafetyPolicies"])!==void 0)throw new Error("disabledSafetyPolicies parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return e}function fI(t){let e={},n=s(t,["parts"]);if(n!=null){let i=n;Array.isArray(i)&&(i=i.map(o=>kI(o))),l(e,["parts"],i)}let r=s(t,["role"]);return r!=null&&l(e,["role"],r),e}function pI(t){let e={},n=s(t,["parts"]);if(n!=null){let i=n;Array.isArray(i)&&(i=i.map(o=>DI(o))),l(e,["parts"],i)}let r=s(t,["role"]);return r!=null&&l(e,["role"],r),e}function hI(t){let e={},n=s(t,["code"]);n!=null&&l(e,["code"],n);let r=s(t,["language"]);if(r!=null&&l(e,["language"],r),s(t,["id"])!==void 0)throw new Error("id parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return e}function mI(t){let e={};if(s(t,["displayName"])!==void 0)throw new Error("displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let n=s(t,["fileUri"]);n!=null&&l(e,["fileUri"],n);let r=s(t,["mimeType"]);return r!=null&&l(e,["mimeType"],r),e}function gI(t){let e={},n=s(t,["args"]);n!=null&&l(e,["args"],n);let r=s(t,["id"]);r!=null&&l(e,["id"],r);let i=s(t,["name"]);if(i!=null&&l(e,["name"],i),s(t,["partialArgs"])!==void 0)throw new Error("partialArgs parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["willContinue"])!==void 0)throw new Error("willContinue parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return e}function _I(t){let e={},n=s(t,["modelSelectionConfig"]);n!=null&&l(e,["modelConfig"],n);let r=s(t,["responseJsonSchema"]);r!=null&&l(e,["responseJsonSchema"],r);let i=s(t,["audioTranscriptionConfig"]);i!=null&&l(e,["audioTranscriptionConfig"],i);let o=s(t,["audioTimestamp"]);o!=null&&l(e,["audioTimestamp"],o);let a=s(t,["candidateCount"]);a!=null&&l(e,["candidateCount"],a);let u=s(t,["enableAffectiveDialog"]);u!=null&&l(e,["enableAffectiveDialog"],u);let c=s(t,["frequencyPenalty"]);c!=null&&l(e,["frequencyPenalty"],c);let d=s(t,["logprobs"]);d!=null&&l(e,["logprobs"],d);let f=s(t,["maxOutputTokens"]);f!=null&&l(e,["maxOutputTokens"],f);let p=s(t,["mediaResolution"]);p!=null&&l(e,["mediaResolution"],p);let h=s(t,["presencePenalty"]);h!=null&&l(e,["presencePenalty"],h);let m=s(t,["responseFormat"]);if(m!=null){let V=m;Array.isArray(V)&&(V=V.map(X=>X)),l(e,["responseFormat"],V)}let _=s(t,["responseLogprobs"]);_!=null&&l(e,["responseLogprobs"],_);let g=s(t,["responseMimeType"]);g!=null&&l(e,["responseMimeType"],g);let E=s(t,["responseModalities"]);E!=null&&l(e,["responseModalities"],E);let y=s(t,["responseSchema"]);y!=null&&l(e,["responseSchema"],y);let C=s(t,["routingConfig"]);C!=null&&l(e,["routingConfig"],C);let A=s(t,["seed"]);A!=null&&l(e,["seed"],A);let I=s(t,["speechConfig"]);I!=null&&l(e,["speechConfig"],Ug(I));let P=s(t,["stopSequences"]);P!=null&&l(e,["stopSequences"],P);let G=s(t,["temperature"]);G!=null&&l(e,["temperature"],G);let O=s(t,["thinkingConfig"]);O!=null&&l(e,["thinkingConfig"],O);let B=s(t,["topK"]);B!=null&&l(e,["topK"],B);let k=s(t,["topP"]);if(k!=null&&l(e,["topP"],k),s(t,["enableEnhancedCivicAnswers"])!==void 0)throw new Error("enableEnhancedCivicAnswers parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(s(t,["translationConfig"])!==void 0)throw new Error("translationConfig parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return e}function yI(t){let e={},n=s(t,["authConfig"]);n!=null&&l(e,["authConfig"],uI(n));let r=s(t,["enableWidget"]);if(r!=null&&l(e,["enableWidget"],r),s(t,["groundingTypes"])!==void 0)throw new Error("groundingTypes parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return e}function EI(t){let e={};if(s(t,["blockingConfidence"])!==void 0)throw new Error("blockingConfidence parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["excludeDomains"])!==void 0)throw new Error("excludeDomains parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let n=s(t,["searchTypes"]);n!=null&&l(e,["searchTypes"],n);let r=s(t,["timeRangeFilter"]);return r!=null&&l(e,["timeRangeFilter"],r),e}function vI(t,e){let n={},r=s(t,["generationConfig"]);e!==void 0&&r!=null&&l(e,["setup","generationConfig"],r);let i=s(t,["responseModalities"]);e!==void 0&&i!=null&&l(e,["setup","generationConfig","responseModalities"],i);let o=s(t,["temperature"]);e!==void 0&&o!=null&&l(e,["setup","generationConfig","temperature"],o);let a=s(t,["topP"]);e!==void 0&&a!=null&&l(e,["setup","generationConfig","topP"],a);let u=s(t,["topK"]);e!==void 0&&u!=null&&l(e,["setup","generationConfig","topK"],u);let c=s(t,["maxOutputTokens"]);e!==void 0&&c!=null&&l(e,["setup","generationConfig","maxOutputTokens"],c);let d=s(t,["mediaResolution"]);e!==void 0&&d!=null&&l(e,["setup","generationConfig","mediaResolution"],d);let f=s(t,["seed"]);e!==void 0&&f!=null&&l(e,["setup","generationConfig","seed"],f);let p=s(t,["speechConfig"]);e!==void 0&&p!=null&&l(e,["setup","generationConfig","speechConfig"],Vu(p));let h=s(t,["thinkingConfig"]);e!==void 0&&h!=null&&l(e,["setup","generationConfig","thinkingConfig"],h);let m=s(t,["enableAffectiveDialog"]);e!==void 0&&m!=null&&l(e,["setup","generationConfig","enableAffectiveDialog"],m);let _=s(t,["systemInstruction"]);e!==void 0&&_!=null&&l(e,["setup","systemInstruction"],fI(xe(_)));let g=s(t,["tools"]);if(e!==void 0&&g!=null){let k=Zn(g);Array.isArray(k)&&(k=k.map(V=>LI(Qn(V)))),l(e,["setup","tools"],k)}let E=s(t,["sessionResumption"]);e!==void 0&&E!=null&&l(e,["setup","sessionResumption"],bI(E));let y=s(t,["inputAudioTranscription"]);e!==void 0&&y!=null&&l(e,["setup","inputAudioTranscription"],y);let C=s(t,["outputAudioTranscription"]);e!==void 0&&C!=null&&l(e,["setup","outputAudioTranscription"],C);let A=s(t,["realtimeInputConfig"]);e!==void 0&&A!=null&&l(e,["setup","realtimeInputConfig"],A);let I=s(t,["contextWindowCompression"]);e!==void 0&&I!=null&&l(e,["setup","contextWindowCompression"],I);let P=s(t,["proactivity"]);if(e!==void 0&&P!=null&&l(e,["setup","proactivity"],P),s(t,["explicitVadSignal"])!==void 0)throw new Error("explicitVadSignal parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let G=s(t,["avatarConfig"]);e!==void 0&&G!=null&&l(e,["setup","avatarConfig"],G);let O=s(t,["safetySettings"]);if(e!==void 0&&O!=null){let k=O;Array.isArray(k)&&(k=k.map(V=>UI(V))),l(e,["setup","safetySettings"],k)}let B=s(t,["translationConfig"]);return e!==void 0&&B!=null&&l(e,["setup","generationConfig","translationConfig"],B),n}function TI(t,e){let n={},r=s(t,["generationConfig"]);e!==void 0&&r!=null&&l(e,["setup","generationConfig"],_I(r));let i=s(t,["responseModalities"]);e!==void 0&&i!=null&&l(e,["setup","generationConfig","responseModalities"],i);let o=s(t,["temperature"]);e!==void 0&&o!=null&&l(e,["setup","generationConfig","temperature"],o);let a=s(t,["topP"]);e!==void 0&&a!=null&&l(e,["setup","generationConfig","topP"],a);let u=s(t,["topK"]);e!==void 0&&u!=null&&l(e,["setup","generationConfig","topK"],u);let c=s(t,["maxOutputTokens"]);e!==void 0&&c!=null&&l(e,["setup","generationConfig","maxOutputTokens"],c);let d=s(t,["mediaResolution"]);e!==void 0&&d!=null&&l(e,["setup","generationConfig","mediaResolution"],d);let f=s(t,["seed"]);e!==void 0&&f!=null&&l(e,["setup","generationConfig","seed"],f);let p=s(t,["speechConfig"]);e!==void 0&&p!=null&&l(e,["setup","generationConfig","speechConfig"],Ug(Vu(p)));let h=s(t,["thinkingConfig"]);e!==void 0&&h!=null&&l(e,["setup","generationConfig","thinkingConfig"],h);let m=s(t,["enableAffectiveDialog"]);e!==void 0&&m!=null&&l(e,["setup","generationConfig","enableAffectiveDialog"],m);let _=s(t,["systemInstruction"]);e!==void 0&&_!=null&&l(e,["setup","systemInstruction"],pI(xe(_)));let g=s(t,["tools"]);if(e!==void 0&&g!=null){let k=Zn(g);Array.isArray(k)&&(k=k.map(V=>OI(Qn(V)))),l(e,["setup","tools"],k)}let E=s(t,["sessionResumption"]);e!==void 0&&E!=null&&l(e,["setup","sessionResumption"],E);let y=s(t,["inputAudioTranscription"]);e!==void 0&&y!=null&&l(e,["setup","inputAudioTranscription"],y);let C=s(t,["outputAudioTranscription"]);e!==void 0&&C!=null&&l(e,["setup","outputAudioTranscription"],C);let A=s(t,["realtimeInputConfig"]);e!==void 0&&A!=null&&l(e,["setup","realtimeInputConfig"],A);let I=s(t,["contextWindowCompression"]);e!==void 0&&I!=null&&l(e,["setup","contextWindowCompression"],I);let P=s(t,["proactivity"]);e!==void 0&&P!=null&&l(e,["setup","proactivity"],P);let G=s(t,["explicitVadSignal"]);e!==void 0&&G!=null&&l(e,["setup","explicitVadSignal"],G);let O=s(t,["avatarConfig"]);e!==void 0&&O!=null&&l(e,["setup","avatarConfig"],O);let B=s(t,["safetySettings"]);if(e!==void 0&&B!=null){let k=B;Array.isArray(k)&&(k=k.map(V=>V)),l(e,["setup","safetySettings"],k)}if(s(t,["translationConfig"])!==void 0)throw new Error("translationConfig parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return n}function AI(t,e){let n={},r=s(e,["model"]);r!=null&&l(n,["setup","model"],ie(t,r));let i=s(e,["config"]);return i!=null&&l(n,["config"],vI(i,n)),n}function CI(t,e){let n={},r=s(e,["model"]);r!=null&&l(n,["setup","model"],ie(t,r));let i=s(e,["config"]);return i!=null&&l(n,["config"],TI(i,n)),n}function SI(t){let e={},n=s(t,["musicGenerationConfig"]);return n!=null&&l(e,["musicGenerationConfig"],n),e}function II(t){let e={},n=s(t,["weightedPrompts"]);if(n!=null){let r=n;Array.isArray(r)&&(r=r.map(i=>i)),l(e,["weightedPrompts"],r)}return e}function wI(t){let e={},n=s(t,["media"]);if(n!=null){let d=vg(n);Array.isArray(d)&&(d=d.map(f=>to(f))),l(e,["mediaChunks"],d)}let r=s(t,["audio"]);r!=null&&l(e,["audio"],to(Ag(r)));let i=s(t,["audioStreamEnd"]);i!=null&&l(e,["audioStreamEnd"],i);let o=s(t,["video"]);o!=null&&l(e,["video"],to(Tg(o)));let a=s(t,["text"]);a!=null&&l(e,["text"],a);let u=s(t,["activityStart"]);u!=null&&l(e,["activityStart"],u);let c=s(t,["activityEnd"]);return c!=null&&l(e,["activityEnd"],c),e}function PI(t){let e={},n=s(t,["media"]);if(n!=null){let d=vg(n);Array.isArray(d)&&(d=d.map(f=>f)),l(e,["mediaChunks"],d)}let r=s(t,["audio"]);r!=null&&l(e,["audio"],Ag(r));let i=s(t,["audioStreamEnd"]);i!=null&&l(e,["audioStreamEnd"],i);let o=s(t,["video"]);o!=null&&l(e,["video"],Tg(o));let a=s(t,["text"]);a!=null&&l(e,["text"],a);let u=s(t,["activityStart"]);u!=null&&l(e,["activityStart"],u);let c=s(t,["activityEnd"]);return c!=null&&l(e,["activityEnd"],c),e}function RI(t){let e={},n=s(t,["setupComplete"]);n!=null&&l(e,["setupComplete"],n);let r=s(t,["serverContent"]);r!=null&&l(e,["serverContent"],r);let i=s(t,["toolCall"]);i!=null&&l(e,["toolCall"],i);let o=s(t,["toolCallCancellation"]);o!=null&&l(e,["toolCallCancellation"],o);let a=s(t,["usageMetadata"]);a!=null&&l(e,["usageMetadata"],qI(a));let u=s(t,["goAway"]);u!=null&&l(e,["goAway"],u);let c=s(t,["sessionResumptionUpdate"]);c!=null&&l(e,["sessionResumptionUpdate"],c);let d=s(t,["voiceActivityDetectionSignal"]);d!=null&&l(e,["voiceActivityDetectionSignal"],d);let f=s(t,["voiceActivity"]);return f!=null&&l(e,["voiceActivity"],FI(f)),e}function NI(t){let e={};if(s(t,["name"])!==void 0)throw new Error("name parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(s(t,["streamableHttpTransport"])!==void 0)throw new Error("streamableHttpTransport parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return e}function xI(t){let e={},n=s(t,["speakerVoiceConfigs"]);if(n!=null){let r=n;Array.isArray(r)&&(r=r.map(i=>GI(i))),l(e,["speakerVoiceConfigs"],r)}return e}function kI(t){let e={},n=s(t,["mediaResolution"]);n!=null&&l(e,["mediaResolution"],n);let r=s(t,["toolCall"]);r!=null&&l(e,["toolCall"],r);let i=s(t,["toolResponse"]);i!=null&&l(e,["toolResponse"],i);let o=s(t,["audioTranscription"]);o!=null&&l(e,["audioTranscription"],o);let a=s(t,["codeExecutionResult"]);a!=null&&l(e,["codeExecutionResult"],a);let u=s(t,["executableCode"]);u!=null&&l(e,["executableCode"],u);let c=s(t,["fileData"]);c!=null&&l(e,["fileData"],mI(c));let d=s(t,["functionCall"]);d!=null&&l(e,["functionCall"],gI(d));let f=s(t,["functionResponse"]);f!=null&&l(e,["functionResponse"],f);let p=s(t,["inlineData"]);p!=null&&l(e,["inlineData"],to(p));let h=s(t,["text"]);h!=null&&l(e,["text"],h);let m=s(t,["thought"]);m!=null&&l(e,["thought"],m);let _=s(t,["thoughtSignature"]);_!=null&&l(e,["thoughtSignature"],_);let g=s(t,["videoMetadata"]);g!=null&&l(e,["videoMetadata"],g);let E=s(t,["partMetadata"]);return E!=null&&l(e,["partMetadata"],E),e}function DI(t){let e={},n=s(t,["mediaResolution"]);if(n!=null&&l(e,["mediaResolution"],n),s(t,["toolCall"])!==void 0)throw new Error("toolCall parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(s(t,["toolResponse"])!==void 0)throw new Error("toolResponse parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");let r=s(t,["audioTranscription"]);r!=null&&l(e,["audioTranscription"],r);let i=s(t,["codeExecutionResult"]);i!=null&&l(e,["codeExecutionResult"],cI(i));let o=s(t,["executableCode"]);o!=null&&l(e,["executableCode"],hI(o));let a=s(t,["fileData"]);a!=null&&l(e,["fileData"],a);let u=s(t,["functionCall"]);u!=null&&l(e,["functionCall"],u);let c=s(t,["functionResponse"]);c!=null&&l(e,["functionResponse"],c);let d=s(t,["inlineData"]);d!=null&&l(e,["inlineData"],d);let f=s(t,["text"]);f!=null&&l(e,["text"],f);let p=s(t,["thought"]);p!=null&&l(e,["thought"],p);let h=s(t,["thoughtSignature"]);h!=null&&l(e,["thoughtSignature"],h);let m=s(t,["videoMetadata"]);if(m!=null&&l(e,["videoMetadata"],m),s(t,["partMetadata"])!==void 0)throw new Error("partMetadata parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return e}function MI(t){let e={},n=s(t,["mimeType"]);n!=null&&l(e,["mimeType"],n);let r=s(t,["voiceSampleAudio"]);if(r!=null&&l(e,["voiceSampleAudio"],r),s(t,["consentAudio"])!==void 0)throw new Error("consentAudio parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(s(t,["voiceConsentSignature"])!==void 0)throw new Error("voiceConsentSignature parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return e}function UI(t){let e={},n=s(t,["category"]);if(n!=null&&l(e,["category"],n),s(t,["method"])!==void 0)throw new Error("method parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let r=s(t,["threshold"]);return r!=null&&l(e,["threshold"],r),e}function bI(t){let e={},n=s(t,["handle"]);if(n!=null&&l(e,["handle"],n),s(t,["transparent"])!==void 0)throw new Error("transparent parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return e}function GI(t){let e={},n=s(t,["speaker"]);n!=null&&l(e,["speaker"],n);let r=s(t,["voiceConfig"]);return r!=null&&l(e,["voiceConfig"],bg(r)),e}function Ug(t){let e={},n=s(t,["voiceConfig"]);n!=null&&l(e,["voiceConfig"],bg(n));let r=s(t,["languageCode"]);r!=null&&l(e,["languageCode"],r);let i=s(t,["multiSpeakerVoiceConfig"]);return i!=null&&l(e,["multiSpeakerVoiceConfig"],xI(i)),e}function LI(t){let e={};if(s(t,["retrieval"])!==void 0)throw new Error("retrieval parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let n=s(t,["googleMaps"]);n!=null&&l(e,["googleMaps"],yI(n));let r=s(t,["mcpServers"]);if(r!=null){let p=r;Array.isArray(p)&&(p=p.map(h=>h)),l(e,["mcpServers"],p)}let i=s(t,["codeExecution"]);i!=null&&l(e,["codeExecution"],i);let o=s(t,["computerUse"]);if(o!=null&&l(e,["computerUse"],o),s(t,["enterpriseWebSearch"])!==void 0)throw new Error("enterpriseWebSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["exaAiSearch"])!==void 0)throw new Error("exaAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let a=s(t,["functionDeclarations"]);if(a!=null){let p=a;Array.isArray(p)&&(p=p.map(h=>h)),l(e,["functionDeclarations"],p)}let u=s(t,["googleSearch"]);u!=null&&l(e,["googleSearch"],EI(u));let c=s(t,["googleSearchRetrieval"]);if(c!=null&&l(e,["googleSearchRetrieval"],c),s(t,["parallelAiSearch"])!==void 0)throw new Error("parallelAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let d=s(t,["urlContext"]);d!=null&&l(e,["urlContext"],d);let f=s(t,["fileSearch"]);return f!=null&&l(e,["fileSearch"],f),e}function OI(t){let e={},n=s(t,["retrieval"]);n!=null&&l(e,["retrieval"],n);let r=s(t,["googleMaps"]);r!=null&&l(e,["googleMaps"],r);let i=s(t,["mcpServers"]);if(i!=null){let _=i;Array.isArray(_)&&(_=_.map(g=>NI(g))),l(e,["mcpServers"],_)}let o=s(t,["codeExecution"]);o!=null&&l(e,["codeExecution"],o);let a=s(t,["computerUse"]);a!=null&&l(e,["computerUse"],dI(a));let u=s(t,["enterpriseWebSearch"]);u!=null&&l(e,["enterpriseWebSearch"],u);let c=s(t,["exaAiSearch"]);c!=null&&l(e,["exaAiSearch"],c);let d=s(t,["functionDeclarations"]);if(d!=null){let _=d;Array.isArray(_)&&(_=_.map(g=>g)),l(e,["functionDeclarations"],_)}let f=s(t,["googleSearch"]);f!=null&&l(e,["googleSearch"],f);let p=s(t,["googleSearchRetrieval"]);p!=null&&l(e,["googleSearchRetrieval"],p);let h=s(t,["parallelAiSearch"]);h!=null&&l(e,["parallelAiSearch"],h);let m=s(t,["urlContext"]);if(m!=null&&l(e,["urlContext"],m),s(t,["fileSearch"])!==void 0)throw new Error("fileSearch parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return e}function qI(t){let e={},n=s(t,["candidatesTokenCount"]);n!=null&&l(e,["responseTokenCount"],n);let r=s(t,["candidatesTokensDetails"]);if(r!=null){let m=r;Array.isArray(m)&&(m=m.map(_=>_)),l(e,["responseTokensDetails"],m)}let i=s(t,["cacheTokensDetails"]);if(i!=null){let m=i;Array.isArray(m)&&(m=m.map(_=>_)),l(e,["cacheTokensDetails"],m)}let o=s(t,["cachedContentTokenCount"]);o!=null&&l(e,["cachedContentTokenCount"],o);let a=s(t,["promptTokenCount"]);a!=null&&l(e,["promptTokenCount"],a);let u=s(t,["promptTokensDetails"]);if(u!=null){let m=u;Array.isArray(m)&&(m=m.map(_=>_)),l(e,["promptTokensDetails"],m)}let c=s(t,["thoughtsTokenCount"]);c!=null&&l(e,["thoughtsTokenCount"],c);let d=s(t,["toolUsePromptTokenCount"]);d!=null&&l(e,["toolUsePromptTokenCount"],d);let f=s(t,["toolUsePromptTokensDetails"]);if(f!=null){let m=f;Array.isArray(m)&&(m=m.map(_=>_)),l(e,["toolUsePromptTokensDetails"],m)}let p=s(t,["totalTokenCount"]);p!=null&&l(e,["totalTokenCount"],p);let h=s(t,["trafficType"]);return h!=null&&l(e,["trafficType"],h),e}function FI(t){let e={},n=s(t,["type"]);n!=null&&l(e,["voiceActivityType"],n);let r=s(t,["audioOffset"]);return r!=null&&l(e,["audioOffset"],r),e}function bg(t){let e={},n=s(t,["replicatedVoiceConfig"]);n!=null&&l(e,["replicatedVoiceConfig"],MI(n));let r=s(t,["prebuiltVoiceConfig"]);return r!=null&&l(e,["prebuiltVoiceConfig"],r),e}function BI(t,e){let n={},r=s(t,["apiKey"]);if(r!=null&&l(n,["apiKey"],r),s(t,["apiKeyConfig"])!==void 0)throw new Error("apiKeyConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["authType"])!==void 0)throw new Error("authType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["googleServiceAccountConfig"])!==void 0)throw new Error("googleServiceAccountConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["httpBasicAuthConfig"])!==void 0)throw new Error("httpBasicAuthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["oauthConfig"])!==void 0)throw new Error("oauthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["oidcConfig"])!==void 0)throw new Error("oidcConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return n}function HI(t,e){let n={},r=s(t,["data"]);if(r!=null&&l(n,["data"],r),s(t,["displayName"])!==void 0)throw new Error("displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let i=s(t,["mimeType"]);return i!=null&&l(n,["mimeType"],i),n}function VI(t,e){let n={},r=s(t,["content"]);r!=null&&l(n,["content"],r);let i=s(t,["citationMetadata"]);i!=null&&l(n,["citationMetadata"],$I(i));let o=s(t,["tokenCount"]);o!=null&&l(n,["tokenCount"],o);let a=s(t,["finishReason"]);a!=null&&l(n,["finishReason"],a);let u=s(t,["groundingMetadata"]);u!=null&&l(n,["groundingMetadata"],u);let c=s(t,["avgLogprobs"]);c!=null&&l(n,["avgLogprobs"],c);let d=s(t,["index"]);d!=null&&l(n,["index"],d);let f=s(t,["logprobsResult"]);f!=null&&l(n,["logprobsResult"],f);let p=s(t,["safetyRatings"]);if(p!=null){let m=p;Array.isArray(m)&&(m=m.map(_=>_)),l(n,["safetyRatings"],m)}let h=s(t,["urlContextMetadata"]);return h!=null&&l(n,["urlContextMetadata"],h),n}function $I(t,e){let n={},r=s(t,["citationSources"]);if(r!=null){let i=r;Array.isArray(i)&&(i=i.map(o=>o)),l(n,["citations"],i)}return n}function JI(t,e){let n={},r=s(t,["outcome"]);r!=null&&l(n,["outcome"],r);let i=s(t,["output"]);if(i!=null&&l(n,["output"],i),s(t,["id"])!==void 0)throw new Error("id parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return n}function WI(t,e,n){let r={},i=s(e,["model"]);i!=null&&l(r,["_url","model"],ie(t,i));let o=s(e,["contents"]);if(o!=null){let a=Le(o);Array.isArray(a)&&(a=a.map(u=>er(u))),l(r,["contents"],a)}return r}function XI(t,e){let n={},r=s(t,["sdkHttpResponse"]);r!=null&&l(n,["sdkHttpResponse"],r);let i=s(t,["tokensInfo"]);if(i!=null){let o=i;Array.isArray(o)&&(o=o.map(a=>a)),l(n,["tokensInfo"],o)}return n}function KI(t,e){let n={},r=s(t,["enablePromptInjectionDetection"]);r!=null&&l(n,["enablePromptInjectionDetection"],r);let i=s(t,["environment"]);i!=null&&l(n,["environment"],i);let o=s(t,["excludedPredefinedFunctions"]);if(o!=null&&l(n,["excludedPredefinedFunctions"],o),s(t,["disabledSafetyPolicies"])!==void 0)throw new Error("disabledSafetyPolicies parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return n}function YI(t,e){let n={},r=s(t,["values"]);r!=null&&l(n,["values"],r);let i=s(t,["statistics"]);return i!=null&&l(n,["statistics"],zI(i)),n}function zI(t,e){let n={},r=s(t,["truncated"]);r!=null&&l(n,["truncated"],r);let i=s(t,["token_count"]);i!=null&&l(n,["tokenCount"],i);let o=s(t,["tokensDetails"]);if(o!=null){let a=o;Array.isArray(a)&&(a=a.map(u=>u)),l(n,["tokensDetails"],a)}return n}function kr(t,e){let n={},r=s(t,["parts"]);if(r!=null){let o=r;Array.isArray(o)&&(o=o.map(a=>aP(a))),l(n,["parts"],o)}let i=s(t,["role"]);return i!=null&&l(n,["role"],i),n}function er(t,e){let n={},r=s(t,["parts"]);if(r!=null){let o=r;Array.isArray(o)&&(o=o.map(a=>lP(a))),l(n,["parts"],o)}let i=s(t,["role"]);return i!=null&&l(n,["role"],i),n}function QI(t,e){let n={},r=s(t,["controlType"]);r!=null&&l(n,["controlType"],r);let i=s(t,["enableControlImageComputation"]);return i!=null&&l(n,["computeControl"],i),n}function ZI(t,e){let n={};if(s(t,["systemInstruction"])!==void 0)throw new Error("systemInstruction parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["tools"])!==void 0)throw new Error("tools parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["generationConfig"])!==void 0)throw new Error("generationConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return n}function jI(t,e,n){let r={},i=s(t,["systemInstruction"]);e!==void 0&&i!=null&&l(e,["systemInstruction"],er(xe(i)));let o=s(t,["tools"]);if(e!==void 0&&o!=null){let u=o;Array.isArray(u)&&(u=u.map(c=>Fg(c))),l(e,["tools"],u)}let a=s(t,["generationConfig"]);return e!==void 0&&a!=null&&l(e,["generationConfig"],$w(a)),r}function ew(t,e,n){let r={},i=s(e,["model"]);i!=null&&l(r,["_url","model"],ie(t,i));let o=s(e,["contents"]);if(o!=null){let u=Le(o);Array.isArray(u)&&(u=u.map(c=>kr(c))),l(r,["contents"],u)}let a=s(e,["config"]);return a!=null&&ZI(a),r}function tw(t,e,n){let r={},i=s(e,["model"]);i!=null&&l(r,["_url","model"],ie(t,i));let o=s(e,["contents"]);if(o!=null){let u=Le(o);Array.isArray(u)&&(u=u.map(c=>er(c))),l(r,["contents"],u)}let a=s(e,["config"]);return a!=null&&jI(a,r),r}function nw(t,e){let n={},r=s(t,["sdkHttpResponse"]);r!=null&&l(n,["sdkHttpResponse"],r);let i=s(t,["totalTokens"]);i!=null&&l(n,["totalTokens"],i);let o=s(t,["cachedContentTokenCount"]);return o!=null&&l(n,["cachedContentTokenCount"],o),n}function rw(t,e){let n={},r=s(t,["sdkHttpResponse"]);r!=null&&l(n,["sdkHttpResponse"],r);let i=s(t,["totalTokens"]);return i!=null&&l(n,["totalTokens"],i),n}function iw(t,e,n){let r={},i=s(e,["model"]);return i!=null&&l(r,["_url","name"],ie(t,i)),r}function ow(t,e,n){let r={},i=s(e,["model"]);return i!=null&&l(r,["_url","name"],ie(t,i)),r}function sw(t,e){let n={},r=s(t,["sdkHttpResponse"]);return r!=null&&l(n,["sdkHttpResponse"],r),n}function aw(t,e){let n={},r=s(t,["sdkHttpResponse"]);return r!=null&&l(n,["sdkHttpResponse"],r),n}function lw(t,e,n){let r={},i=s(t,["outputGcsUri"]);e!==void 0&&i!=null&&l(e,["parameters","storageUri"],i);let o=s(t,["negativePrompt"]);e!==void 0&&o!=null&&l(e,["parameters","negativePrompt"],o);let a=s(t,["numberOfImages"]);e!==void 0&&a!=null&&l(e,["parameters","sampleCount"],a);let u=s(t,["aspectRatio"]);e!==void 0&&u!=null&&l(e,["parameters","aspectRatio"],u);let c=s(t,["guidanceScale"]);e!==void 0&&c!=null&&l(e,["parameters","guidanceScale"],c);let d=s(t,["seed"]);e!==void 0&&d!=null&&l(e,["parameters","seed"],d);let f=s(t,["safetyFilterLevel"]);e!==void 0&&f!=null&&l(e,["parameters","safetySetting"],f);let p=s(t,["personGeneration"]);e!==void 0&&p!=null&&l(e,["parameters","personGeneration"],p);let h=s(t,["includeSafetyAttributes"]);e!==void 0&&h!=null&&l(e,["parameters","includeSafetyAttributes"],h);let m=s(t,["includeRaiReason"]);e!==void 0&&m!=null&&l(e,["parameters","includeRaiReason"],m);let _=s(t,["language"]);e!==void 0&&_!=null&&l(e,["parameters","language"],_);let g=s(t,["outputMimeType"]);e!==void 0&&g!=null&&l(e,["parameters","outputOptions","mimeType"],g);let E=s(t,["outputCompressionQuality"]);e!==void 0&&E!=null&&l(e,["parameters","outputOptions","compressionQuality"],E);let y=s(t,["addWatermark"]);e!==void 0&&y!=null&&l(e,["parameters","addWatermark"],y);let C=s(t,["labels"]);e!==void 0&&C!=null&&l(e,["labels"],C);let A=s(t,["editMode"]);e!==void 0&&A!=null&&l(e,["parameters","editMode"],A);let I=s(t,["baseSteps"]);return e!==void 0&&I!=null&&l(e,["parameters","editConfig","baseSteps"],I),r}function uw(t,e,n){let r={},i=s(e,["model"]);i!=null&&l(r,["_url","model"],ie(t,i));let o=s(e,["prompt"]);o!=null&&l(r,["instances[0]","prompt"],o);let a=s(e,["referenceImages"]);if(a!=null){let c=a;Array.isArray(c)&&(c=c.map(d=>hP(d))),l(r,["instances[0]","referenceImages"],c)}let u=s(e,["config"]);return u!=null&&lw(u,r),r}function cw(t,e){let n={},r=s(t,["sdkHttpResponse"]);r!=null&&l(n,["sdkHttpResponse"],r);let i=s(t,["predictions"]);if(i!=null){let o=i;Array.isArray(o)&&(o=o.map(a=>wo(a))),l(n,["generatedImages"],o)}return n}function dw(t,e,n){let r={},i=s(t,["taskType"]);e!==void 0&&i!=null&&l(e,["requests[]","taskType"],i);let o=s(t,["title"]);e!==void 0&&o!=null&&l(e,["requests[]","title"],o);let a=s(t,["outputDimensionality"]);if(e!==void 0&&a!=null&&l(e,["requests[]","outputDimensionality"],a),s(t,["mimeType"])!==void 0)throw new Error("mimeType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["autoTruncate"])!==void 0)throw new Error("autoTruncate parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["documentOcr"])!==void 0)throw new Error("documentOcr parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["audioTrackExtraction"])!==void 0)throw new Error("audioTrackExtraction parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return r}function fw(t,e,n){let r={},i=s(n,["embeddingApiType"]);if(i===void 0&&(i="PREDICT"),i==="PREDICT"){let p=s(t,["taskType"]);e!==void 0&&p!=null&&l(e,["instances[]","task_type"],p)}else if(i==="EMBED_CONTENT"){let p=s(t,["taskType"]);e!==void 0&&p!=null&&l(e,["embedContentConfig","taskType"],p)}let o=s(n,["embeddingApiType"]);if(o===void 0&&(o="PREDICT"),o==="PREDICT"){let p=s(t,["title"]);e!==void 0&&p!=null&&l(e,["instances[]","title"],p)}else if(o==="EMBED_CONTENT"){let p=s(t,["title"]);e!==void 0&&p!=null&&l(e,["embedContentConfig","title"],p)}let a=s(n,["embeddingApiType"]);if(a===void 0&&(a="PREDICT"),a==="PREDICT"){let p=s(t,["outputDimensionality"]);e!==void 0&&p!=null&&l(e,["parameters","outputDimensionality"],p)}else if(a==="EMBED_CONTENT"){let p=s(t,["outputDimensionality"]);e!==void 0&&p!=null&&l(e,["embedContentConfig","outputDimensionality"],p)}let u=s(n,["embeddingApiType"]);if(u===void 0&&(u="PREDICT"),u==="PREDICT"){let p=s(t,["mimeType"]);e!==void 0&&p!=null&&l(e,["instances[]","mimeType"],p)}let c=s(n,["embeddingApiType"]);if(c===void 0&&(c="PREDICT"),c==="PREDICT"){let p=s(t,["autoTruncate"]);e!==void 0&&p!=null&&l(e,["parameters","autoTruncate"],p)}else if(c==="EMBED_CONTENT"){let p=s(t,["autoTruncate"]);e!==void 0&&p!=null&&l(e,["embedContentConfig","autoTruncate"],p)}let d=s(n,["embeddingApiType"]);if(d===void 0&&(d="PREDICT"),d==="EMBED_CONTENT"){let p=s(t,["documentOcr"]);e!==void 0&&p!=null&&l(e,["embedContentConfig","documentOcr"],p)}let f=s(n,["embeddingApiType"]);if(f===void 0&&(f="PREDICT"),f==="EMBED_CONTENT"){let p=s(t,["audioTrackExtraction"]);e!==void 0&&p!=null&&l(e,["embedContentConfig","audioTrackExtraction"],p)}return r}function pw(t,e,n){let r={},i=s(e,["model"]);i!=null&&l(r,["_url","model"],ie(t,i));let o=s(e,["contents"]);if(o!=null){let d=Fu(t,o);Array.isArray(d)&&(d=d.map(f=>f)),l(r,["requests[]","content"],d)}let a=s(e,["content"]);a!=null&&kr(xe(a));let u=s(e,["config"]);u!=null&&dw(u,r);let c=s(e,["model"]);return c!==void 0&&l(r,["requests[]","model"],ie(t,c)),r}function hw(t,e,n){let r={},i=s(e,["model"]);i!=null&&l(r,["_url","model"],ie(t,i));let o=s(n,["embeddingApiType"]);if(o===void 0&&(o="PREDICT"),o==="PREDICT"){let c=s(e,["contents"]);if(c!=null){let d=Fu(t,c);Array.isArray(d)&&(d=d.map(f=>f)),l(r,["instances[]","content"],d)}}let a=s(n,["embeddingApiType"]);if(a===void 0&&(a="PREDICT"),a==="EMBED_CONTENT"){let c=s(e,["content"]);c!=null&&l(r,["content"],er(xe(c)))}let u=s(e,["config"]);return u!=null&&fw(u,r,n),r}function mw(t,e){let n={},r=s(t,["sdkHttpResponse"]);r!=null&&l(n,["sdkHttpResponse"],r);let i=s(t,["embeddings"]);if(i!=null){let a=i;Array.isArray(a)&&(a=a.map(u=>u)),l(n,["embeddings"],a)}let o=s(t,["metadata"]);return o!=null&&l(n,["metadata"],o),n}function gw(t,e){let n={},r=s(t,["sdkHttpResponse"]);r!=null&&l(n,["sdkHttpResponse"],r);let i=s(t,["predictions[]","embeddings"]);if(i!=null){let a=i;Array.isArray(a)&&(a=a.map(u=>YI(u))),l(n,["embeddings"],a)}let o=s(t,["metadata"]);if(o!=null&&l(n,["metadata"],o),e&&s(e,["embeddingApiType"])==="EMBED_CONTENT"){let a=s(t,["embedding"]),u=s(t,["usageMetadata"]),c=s(t,["truncated"]);if(a){let d={};u&&u.promptTokenCount&&(d.tokenCount=u.promptTokenCount),u&&u.promptTokensDetails&&(d.tokensDetails=u.promptTokensDetails),c&&(d.truncated=c),a.statistics=d,l(n,["embeddings"],[a])}}return n}function _w(t,e){let n={},r=s(t,["endpoint"]);r!=null&&l(n,["name"],r);let i=s(t,["deployedModelId"]);return i!=null&&l(n,["deployedModelId"],i),n}function yw(t,e){let n={},r=s(t,["code"]);r!=null&&l(n,["code"],r);let i=s(t,["language"]);if(i!=null&&l(n,["language"],i),s(t,["id"])!==void 0)throw new Error("id parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return n}function Ew(t,e){let n={};if(s(t,["displayName"])!==void 0)throw new Error("displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let r=s(t,["fileUri"]);r!=null&&l(n,["fileUri"],r);let i=s(t,["mimeType"]);return i!=null&&l(n,["mimeType"],i),n}function vw(t,e){let n={},r=s(t,["args"]);r!=null&&l(n,["args"],r);let i=s(t,["id"]);i!=null&&l(n,["id"],i);let o=s(t,["name"]);if(o!=null&&l(n,["name"],o),s(t,["partialArgs"])!==void 0)throw new Error("partialArgs parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["willContinue"])!==void 0)throw new Error("willContinue parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return n}function Tw(t,e){let n={},r=s(t,["allowedFunctionNames"]);r!=null&&l(n,["allowedFunctionNames"],r);let i=s(t,["mode"]);if(i!=null&&l(n,["mode"],i),s(t,["streamFunctionCallArguments"])!==void 0)throw new Error("streamFunctionCallArguments parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return n}function Aw(t,e,n,r){let i={},o=s(e,["serviceTier"]);n!==void 0&&o!=null&&l(n,["serviceTier"],o);let a=s(e,["systemInstruction"]);n!==void 0&&a!=null&&l(n,["systemInstruction"],kr(xe(a)));let u=s(e,["temperature"]);u!=null&&l(i,["temperature"],u);let c=s(e,["topP"]);c!=null&&l(i,["topP"],c);let d=s(e,["topK"]);d!=null&&l(i,["topK"],d);let f=s(e,["candidateCount"]);f!=null&&l(i,["candidateCount"],f);let p=s(e,["maxOutputTokens"]);p!=null&&l(i,["maxOutputTokens"],p);let h=s(e,["stopSequences"]);h!=null&&l(i,["stopSequences"],h);let m=s(e,["responseLogprobs"]);m!=null&&l(i,["responseLogprobs"],m);let _=s(e,["logprobs"]);_!=null&&l(i,["logprobs"],_);let g=s(e,["presencePenalty"]);g!=null&&l(i,["presencePenalty"],g);let E=s(e,["frequencyPenalty"]);E!=null&&l(i,["frequencyPenalty"],E);let y=s(e,["seed"]);y!=null&&l(i,["seed"],y);let C=s(e,["responseMimeType"]);C!=null&&l(i,["responseMimeType"],C);let A=s(e,["responseSchema"]);A!=null&&l(i,["responseSchema"],Bu(A));let I=s(e,["responseJsonSchema"]);if(I!=null&&l(i,["responseJsonSchema"],I),s(e,["routingConfig"])!==void 0)throw new Error("routingConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(e,["modelSelectionConfig"])!==void 0)throw new Error("modelSelectionConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let P=s(e,["safetySettings"]);if(n!==void 0&&P!=null){let j=P;Array.isArray(j)&&(j=j.map(_e=>gP(_e))),l(n,["safetySettings"],j)}let G=s(e,["tools"]);if(n!==void 0&&G!=null){let j=Zn(G);Array.isArray(j)&&(j=j.map(_e=>IP(Qn(_e)))),l(n,["tools"],j)}let O=s(e,["toolConfig"]);if(n!==void 0&&O!=null&&l(n,["toolConfig"],CP(O)),s(e,["labels"])!==void 0)throw new Error("labels parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let B=s(e,["cachedContent"]);n!==void 0&&B!=null&&l(n,["cachedContent"],bt(t,B));let k=s(e,["responseModalities"]);k!=null&&l(i,["responseModalities"],k);let V=s(e,["mediaResolution"]);V!=null&&l(i,["mediaResolution"],V);let X=s(e,["speechConfig"]);if(X!=null&&l(i,["speechConfig"],Hu(X)),s(e,["audioTimestamp"])!==void 0)throw new Error("audioTimestamp parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let Z=s(e,["thinkingConfig"]);Z!=null&&l(i,["thinkingConfig"],Z);let ne=s(e,["audioTranscriptionConfig"]);ne!=null&&l(i,["audioTranscriptionConfig"],ne);let D=s(e,["imageConfig"]);D!=null&&l(i,["imageConfig"],Yw(D));let K=s(e,["enableEnhancedCivicAnswers"]);if(K!=null&&l(i,["enableEnhancedCivicAnswers"],K),s(e,["modelArmorConfig"])!==void 0)throw new Error("modelArmorConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return i}function Cw(t,e,n,r){let i={},o=s(e,["serviceTier"]);n!==void 0&&o!=null&&l(n,["serviceTier"],o);let a=s(e,["systemInstruction"]);n!==void 0&&a!=null&&l(n,["systemInstruction"],er(xe(a)));let u=s(e,["temperature"]);u!=null&&l(i,["temperature"],u);let c=s(e,["topP"]);c!=null&&l(i,["topP"],c);let d=s(e,["topK"]);d!=null&&l(i,["topK"],d);let f=s(e,["candidateCount"]);f!=null&&l(i,["candidateCount"],f);let p=s(e,["maxOutputTokens"]);p!=null&&l(i,["maxOutputTokens"],p);let h=s(e,["stopSequences"]);h!=null&&l(i,["stopSequences"],h);let m=s(e,["responseLogprobs"]);m!=null&&l(i,["responseLogprobs"],m);let _=s(e,["logprobs"]);_!=null&&l(i,["logprobs"],_);let g=s(e,["presencePenalty"]);g!=null&&l(i,["presencePenalty"],g);let E=s(e,["frequencyPenalty"]);E!=null&&l(i,["frequencyPenalty"],E);let y=s(e,["seed"]);y!=null&&l(i,["seed"],y);let C=s(e,["responseMimeType"]);C!=null&&l(i,["responseMimeType"],C);let A=s(e,["responseSchema"]);A!=null&&l(i,["responseSchema"],Bu(A));let I=s(e,["responseJsonSchema"]);I!=null&&l(i,["responseJsonSchema"],I);let P=s(e,["routingConfig"]);P!=null&&l(i,["routingConfig"],P);let G=s(e,["modelSelectionConfig"]);G!=null&&l(i,["modelConfig"],G);let O=s(e,["safetySettings"]);if(n!==void 0&&O!=null){let Re=O;Array.isArray(Re)&&(Re=Re.map(qe=>qe)),l(n,["safetySettings"],Re)}let B=s(e,["tools"]);if(n!==void 0&&B!=null){let Re=Zn(B);Array.isArray(Re)&&(Re=Re.map(qe=>Fg(Qn(qe)))),l(n,["tools"],Re)}let k=s(e,["toolConfig"]);n!==void 0&&k!=null&&l(n,["toolConfig"],SP(k));let V=s(e,["labels"]);n!==void 0&&V!=null&&l(n,["labels"],V);let X=s(e,["cachedContent"]);n!==void 0&&X!=null&&l(n,["cachedContent"],bt(t,X));let Z=s(e,["responseModalities"]);Z!=null&&l(i,["responseModalities"],Z);let ne=s(e,["mediaResolution"]);ne!=null&&l(i,["mediaResolution"],ne);let D=s(e,["speechConfig"]);D!=null&&l(i,["speechConfig"],qg(Hu(D)));let K=s(e,["audioTimestamp"]);K!=null&&l(i,["audioTimestamp"],K);let j=s(e,["thinkingConfig"]);j!=null&&l(i,["thinkingConfig"],j);let _e=s(e,["audioTranscriptionConfig"]);_e!=null&&l(i,["audioTranscriptionConfig"],_e);let Pe=s(e,["imageConfig"]);if(Pe!=null&&l(i,["imageConfig"],zw(Pe)),s(e,["enableEnhancedCivicAnswers"])!==void 0)throw new Error("enableEnhancedCivicAnswers parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");let Ae=s(e,["modelArmorConfig"]);return n!==void 0&&Ae!=null&&l(n,["modelArmorConfig"],Ae),i}function Bm(t,e,n){let r={},i=s(e,["model"]);i!=null&&l(r,["_url","model"],ie(t,i));let o=s(e,["contents"]);if(o!=null){let u=Le(o);Array.isArray(u)&&(u=u.map(c=>kr(c))),l(r,["contents"],u)}let a=s(e,["config"]);return a!=null&&l(r,["generationConfig"],Aw(t,a,r)),r}function Hm(t,e,n){let r={},i=s(e,["model"]);i!=null&&l(r,["_url","model"],ie(t,i));let o=s(e,["contents"]);if(o!=null){let u=Le(o);Array.isArray(u)&&(u=u.map(c=>er(c))),l(r,["contents"],u)}let a=s(e,["config"]);return a!=null&&l(r,["generationConfig"],Cw(t,a,r)),r}function Vm(t,e){let n={},r=s(t,["sdkHttpResponse"]);r!=null&&l(n,["sdkHttpResponse"],r);let i=s(t,["candidates"]);if(i!=null){let f=i;Array.isArray(f)&&(f=f.map(p=>VI(p))),l(n,["candidates"],f)}let o=s(t,["modelVersion"]);o!=null&&l(n,["modelVersion"],o);let a=s(t,["promptFeedback"]);a!=null&&l(n,["promptFeedback"],a);let u=s(t,["responseId"]);u!=null&&l(n,["responseId"],u);let c=s(t,["usageMetadata"]);c!=null&&l(n,["usageMetadata"],c);let d=s(t,["modelStatus"]);return d!=null&&l(n,["modelStatus"],d),n}function $m(t,e){let n={},r=s(t,["sdkHttpResponse"]);r!=null&&l(n,["sdkHttpResponse"],r);let i=s(t,["candidates"]);if(i!=null){let f=i;Array.isArray(f)&&(f=f.map(p=>p)),l(n,["candidates"],f)}let o=s(t,["createTime"]);o!=null&&l(n,["createTime"],o);let a=s(t,["modelVersion"]);a!=null&&l(n,["modelVersion"],a);let u=s(t,["promptFeedback"]);u!=null&&l(n,["promptFeedback"],u);let c=s(t,["responseId"]);c!=null&&l(n,["responseId"],c);let d=s(t,["usageMetadata"]);return d!=null&&l(n,["usageMetadata"],d),n}function Sw(t,e,n){let r={};if(s(t,["outputGcsUri"])!==void 0)throw new Error("outputGcsUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["negativePrompt"])!==void 0)throw new Error("negativePrompt parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let i=s(t,["numberOfImages"]);e!==void 0&&i!=null&&l(e,["parameters","sampleCount"],i);let o=s(t,["aspectRatio"]);e!==void 0&&o!=null&&l(e,["parameters","aspectRatio"],o);let a=s(t,["guidanceScale"]);if(e!==void 0&&a!=null&&l(e,["parameters","guidanceScale"],a),s(t,["seed"])!==void 0)throw new Error("seed parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let u=s(t,["safetyFilterLevel"]);e!==void 0&&u!=null&&l(e,["parameters","safetySetting"],u);let c=s(t,["personGeneration"]);e!==void 0&&c!=null&&l(e,["parameters","personGeneration"],c);let d=s(t,["includeSafetyAttributes"]);e!==void 0&&d!=null&&l(e,["parameters","includeSafetyAttributes"],d);let f=s(t,["includeRaiReason"]);e!==void 0&&f!=null&&l(e,["parameters","includeRaiReason"],f);let p=s(t,["language"]);e!==void 0&&p!=null&&l(e,["parameters","language"],p);let h=s(t,["outputMimeType"]);e!==void 0&&h!=null&&l(e,["parameters","outputOptions","mimeType"],h);let m=s(t,["outputCompressionQuality"]);if(e!==void 0&&m!=null&&l(e,["parameters","outputOptions","compressionQuality"],m),s(t,["addWatermark"])!==void 0)throw new Error("addWatermark parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["labels"])!==void 0)throw new Error("labels parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let _=s(t,["imageSize"]);if(e!==void 0&&_!=null&&l(e,["parameters","sampleImageSize"],_),s(t,["enhancePrompt"])!==void 0)throw new Error("enhancePrompt parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return r}function Iw(t,e,n){let r={},i=s(t,["outputGcsUri"]);e!==void 0&&i!=null&&l(e,["parameters","storageUri"],i);let o=s(t,["negativePrompt"]);e!==void 0&&o!=null&&l(e,["parameters","negativePrompt"],o);let a=s(t,["numberOfImages"]);e!==void 0&&a!=null&&l(e,["parameters","sampleCount"],a);let u=s(t,["aspectRatio"]);e!==void 0&&u!=null&&l(e,["parameters","aspectRatio"],u);let c=s(t,["guidanceScale"]);e!==void 0&&c!=null&&l(e,["parameters","guidanceScale"],c);let d=s(t,["seed"]);e!==void 0&&d!=null&&l(e,["parameters","seed"],d);let f=s(t,["safetyFilterLevel"]);e!==void 0&&f!=null&&l(e,["parameters","safetySetting"],f);let p=s(t,["personGeneration"]);e!==void 0&&p!=null&&l(e,["parameters","personGeneration"],p);let h=s(t,["includeSafetyAttributes"]);e!==void 0&&h!=null&&l(e,["parameters","includeSafetyAttributes"],h);let m=s(t,["includeRaiReason"]);e!==void 0&&m!=null&&l(e,["parameters","includeRaiReason"],m);let _=s(t,["language"]);e!==void 0&&_!=null&&l(e,["parameters","language"],_);let g=s(t,["outputMimeType"]);e!==void 0&&g!=null&&l(e,["parameters","outputOptions","mimeType"],g);let E=s(t,["outputCompressionQuality"]);e!==void 0&&E!=null&&l(e,["parameters","outputOptions","compressionQuality"],E);let y=s(t,["addWatermark"]);e!==void 0&&y!=null&&l(e,["parameters","addWatermark"],y);let C=s(t,["labels"]);e!==void 0&&C!=null&&l(e,["labels"],C);let A=s(t,["imageSize"]);e!==void 0&&A!=null&&l(e,["parameters","sampleImageSize"],A);let I=s(t,["enhancePrompt"]);return e!==void 0&&I!=null&&l(e,["parameters","enhancePrompt"],I),r}function ww(t,e,n){let r={},i=s(e,["model"]);i!=null&&l(r,["_url","model"],ie(t,i));let o=s(e,["prompt"]);o!=null&&l(r,["instances[0]","prompt"],o);let a=s(e,["config"]);return a!=null&&Sw(a,r),r}function Pw(t,e,n){let r={},i=s(e,["model"]);i!=null&&l(r,["_url","model"],ie(t,i));let o=s(e,["prompt"]);o!=null&&l(r,["instances[0]","prompt"],o);let a=s(e,["config"]);return a!=null&&Iw(a,r),r}function Rw(t,e){let n={},r=s(t,["sdkHttpResponse"]);r!=null&&l(n,["sdkHttpResponse"],r);let i=s(t,["predictions"]);if(i!=null){let a=i;Array.isArray(a)&&(a=a.map(u=>Fw(u))),l(n,["generatedImages"],a)}let o=s(t,["positivePromptSafetyAttributes"]);return o!=null&&l(n,["positivePromptSafetyAttributes"],Lg(o)),n}function Nw(t,e){let n={},r=s(t,["sdkHttpResponse"]);r!=null&&l(n,["sdkHttpResponse"],r);let i=s(t,["predictions"]);if(i!=null){let a=i;Array.isArray(a)&&(a=a.map(u=>wo(u))),l(n,["generatedImages"],a)}let o=s(t,["positivePromptSafetyAttributes"]);return o!=null&&l(n,["positivePromptSafetyAttributes"],Og(o)),n}function xw(t,e,n){let r={},i=s(t,["numberOfVideos"]);if(e!==void 0&&i!=null&&l(e,["parameters","sampleCount"],i),s(t,["outputGcsUri"])!==void 0)throw new Error("outputGcsUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["fps"])!==void 0)throw new Error("fps parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let o=s(t,["durationSeconds"]);if(e!==void 0&&o!=null&&l(e,["parameters","durationSeconds"],o),s(t,["seed"])!==void 0)throw new Error("seed parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let a=s(t,["aspectRatio"]);e!==void 0&&a!=null&&l(e,["parameters","aspectRatio"],a);let u=s(t,["resolution"]);e!==void 0&&u!=null&&l(e,["parameters","resolution"],u);let c=s(t,["personGeneration"]);if(e!==void 0&&c!=null&&l(e,["parameters","personGeneration"],c),s(t,["pubsubTopic"])!==void 0)throw new Error("pubsubTopic parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let d=s(t,["negativePrompt"]);e!==void 0&&d!=null&&l(e,["parameters","negativePrompt"],d);let f=s(t,["enhancePrompt"]);if(e!==void 0&&f!=null&&l(e,["parameters","enhancePrompt"],f),s(t,["generateAudio"])!==void 0)throw new Error("generateAudio parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let p=s(t,["lastFrame"]);e!==void 0&&p!=null&&l(e,["instances[0]","lastFrame"],Po(p));let h=s(t,["referenceImages"]);if(e!==void 0&&h!=null){let _=h;Array.isArray(_)&&(_=_.map(g=>OP(g))),l(e,["instances[0]","referenceImages"],_)}if(s(t,["mask"])!==void 0)throw new Error("mask parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["compressionQuality"])!==void 0)throw new Error("compressionQuality parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["labels"])!==void 0)throw new Error("labels parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let m=s(t,["webhookConfig"]);if(e!==void 0&&m!=null&&l(e,["webhookConfig"],m),s(t,["resizeMode"])!==void 0)throw new Error("resizeMode parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return r}function kw(t,e,n){let r={},i=s(t,["numberOfVideos"]);e!==void 0&&i!=null&&l(e,["parameters","sampleCount"],i);let o=s(t,["outputGcsUri"]);e!==void 0&&o!=null&&l(e,["parameters","storageUri"],o);let a=s(t,["fps"]);e!==void 0&&a!=null&&l(e,["parameters","fps"],a);let u=s(t,["durationSeconds"]);e!==void 0&&u!=null&&l(e,["parameters","durationSeconds"],u);let c=s(t,["seed"]);e!==void 0&&c!=null&&l(e,["parameters","seed"],c);let d=s(t,["aspectRatio"]);e!==void 0&&d!=null&&l(e,["parameters","aspectRatio"],d);let f=s(t,["resolution"]);e!==void 0&&f!=null&&l(e,["parameters","resolution"],f);let p=s(t,["personGeneration"]);e!==void 0&&p!=null&&l(e,["parameters","personGeneration"],p);let h=s(t,["pubsubTopic"]);e!==void 0&&h!=null&&l(e,["parameters","pubsubTopic"],h);let m=s(t,["negativePrompt"]);e!==void 0&&m!=null&&l(e,["parameters","negativePrompt"],m);let _=s(t,["enhancePrompt"]);e!==void 0&&_!=null&&l(e,["parameters","enhancePrompt"],_);let g=s(t,["generateAudio"]);e!==void 0&&g!=null&&l(e,["parameters","generateAudio"],g);let E=s(t,["lastFrame"]);e!==void 0&&E!=null&&l(e,["instances[0]","lastFrame"],ft(E));let y=s(t,["referenceImages"]);if(e!==void 0&&y!=null){let G=y;Array.isArray(G)&&(G=G.map(O=>qP(O))),l(e,["instances[0]","referenceImages"],G)}let C=s(t,["mask"]);e!==void 0&&C!=null&&l(e,["instances[0]","mask"],LP(C));let A=s(t,["compressionQuality"]);e!==void 0&&A!=null&&l(e,["parameters","compressionQuality"],A);let I=s(t,["labels"]);if(e!==void 0&&I!=null&&l(e,["labels"],I),s(t,["webhookConfig"])!==void 0)throw new Error("webhookConfig parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");let P=s(t,["resizeMode"]);return e!==void 0&&P!=null&&l(e,["parameters","resizeMode"],P),r}function Dw(t,e){let n={},r=s(t,["name"]);r!=null&&l(n,["name"],r);let i=s(t,["metadata"]);i!=null&&l(n,["metadata"],i);let o=s(t,["done"]);o!=null&&l(n,["done"],o);let a=s(t,["error"]);a!=null&&l(n,["error"],a);let u=s(t,["response","generateVideoResponse"]);return u!=null&&l(n,["response"],Gw(u)),n}function Mw(t,e){let n={},r=s(t,["name"]);r!=null&&l(n,["name"],r);let i=s(t,["metadata"]);i!=null&&l(n,["metadata"],i);let o=s(t,["done"]);o!=null&&l(n,["done"],o);let a=s(t,["error"]);a!=null&&l(n,["error"],a);let u=s(t,["response"]);return u!=null&&l(n,["response"],Lw(u)),n}function Uw(t,e,n){let r={},i=s(e,["model"]);i!=null&&l(r,["_url","model"],ie(t,i));let o=s(e,["prompt"]);o!=null&&l(r,["instances[0]","prompt"],o);let a=s(e,["image"]);a!=null&&l(r,["instances[0]","image"],Po(a));let u=s(e,["video"]);u!=null&&l(r,["instances[0]","video"],Bg(u));let c=s(e,["source"]);c!=null&&Ow(c,r);let d=s(e,["config"]);return d!=null&&xw(d,r),r}function bw(t,e,n){let r={},i=s(e,["model"]);i!=null&&l(r,["_url","model"],ie(t,i));let o=s(e,["prompt"]);o!=null&&l(r,["instances[0]","prompt"],o);let a=s(e,["image"]);a!=null&&l(r,["instances[0]","image"],ft(a));let u=s(e,["video"]);u!=null&&l(r,["instances[0]","video"],Hg(u));let c=s(e,["source"]);c!=null&&qw(c,r);let d=s(e,["config"]);return d!=null&&kw(d,r),r}function Gw(t,e){let n={},r=s(t,["generatedSamples"]);if(r!=null){let a=r;Array.isArray(a)&&(a=a.map(u=>Hw(u))),l(n,["generatedVideos"],a)}let i=s(t,["raiMediaFilteredCount"]);i!=null&&l(n,["raiMediaFilteredCount"],i);let o=s(t,["raiMediaFilteredReasons"]);return o!=null&&l(n,["raiMediaFilteredReasons"],o),n}function Lw(t,e){let n={},r=s(t,["videos"]);if(r!=null){let a=r;Array.isArray(a)&&(a=a.map(u=>Vw(u))),l(n,["generatedVideos"],a)}let i=s(t,["raiMediaFilteredCount"]);i!=null&&l(n,["raiMediaFilteredCount"],i);let o=s(t,["raiMediaFilteredReasons"]);return o!=null&&l(n,["raiMediaFilteredReasons"],o),n}function Ow(t,e,n){let r={},i=s(t,["prompt"]);e!==void 0&&i!=null&&l(e,["instances[0]","prompt"],i);let o=s(t,["image"]);e!==void 0&&o!=null&&l(e,["instances[0]","image"],Po(o));let a=s(t,["video"]);return e!==void 0&&a!=null&&l(e,["instances[0]","video"],Bg(a)),r}function qw(t,e,n){let r={},i=s(t,["prompt"]);e!==void 0&&i!=null&&l(e,["instances[0]","prompt"],i);let o=s(t,["image"]);e!==void 0&&o!=null&&l(e,["instances[0]","image"],ft(o));let a=s(t,["video"]);return e!==void 0&&a!=null&&l(e,["instances[0]","video"],Hg(a)),r}function Fw(t,e){let n={},r=s(t,["_self"]);r!=null&&l(n,["image"],Qw(r));let i=s(t,["raiFilteredReason"]);i!=null&&l(n,["raiFilteredReason"],i);let o=s(t,["_self"]);return o!=null&&l(n,["safetyAttributes"],Lg(o)),n}function wo(t,e){let n={},r=s(t,["_self"]);r!=null&&l(n,["image"],Gg(r));let i=s(t,["raiFilteredReason"]);i!=null&&l(n,["raiFilteredReason"],i);let o=s(t,["_self"]);o!=null&&l(n,["safetyAttributes"],Og(o));let a=s(t,["prompt"]);return a!=null&&l(n,["enhancedPrompt"],a),n}function Bw(t,e){let n={},r=s(t,["_self"]);r!=null&&l(n,["mask"],Gg(r));let i=s(t,["labels"]);if(i!=null){let o=i;Array.isArray(o)&&(o=o.map(a=>a)),l(n,["labels"],o)}return n}function Hw(t,e){let n={},r=s(t,["video"]);return r!=null&&l(n,["video"],bP(r)),n}function Vw(t,e){let n={},r=s(t,["_self"]);return r!=null&&l(n,["video"],GP(r)),n}function $w(t,e){let n={},r=s(t,["modelSelectionConfig"]);r!=null&&l(n,["modelConfig"],r);let i=s(t,["responseJsonSchema"]);i!=null&&l(n,["responseJsonSchema"],i);let o=s(t,["audioTranscriptionConfig"]);o!=null&&l(n,["audioTranscriptionConfig"],o);let a=s(t,["audioTimestamp"]);a!=null&&l(n,["audioTimestamp"],a);let u=s(t,["candidateCount"]);u!=null&&l(n,["candidateCount"],u);let c=s(t,["enableAffectiveDialog"]);c!=null&&l(n,["enableAffectiveDialog"],c);let d=s(t,["frequencyPenalty"]);d!=null&&l(n,["frequencyPenalty"],d);let f=s(t,["logprobs"]);f!=null&&l(n,["logprobs"],f);let p=s(t,["maxOutputTokens"]);p!=null&&l(n,["maxOutputTokens"],p);let h=s(t,["mediaResolution"]);h!=null&&l(n,["mediaResolution"],h);let m=s(t,["presencePenalty"]);m!=null&&l(n,["presencePenalty"],m);let _=s(t,["responseFormat"]);if(_!=null){let X=_;Array.isArray(X)&&(X=X.map(Z=>Z)),l(n,["responseFormat"],X)}let g=s(t,["responseLogprobs"]);g!=null&&l(n,["responseLogprobs"],g);let E=s(t,["responseMimeType"]);E!=null&&l(n,["responseMimeType"],E);let y=s(t,["responseModalities"]);y!=null&&l(n,["responseModalities"],y);let C=s(t,["responseSchema"]);C!=null&&l(n,["responseSchema"],C);let A=s(t,["routingConfig"]);A!=null&&l(n,["routingConfig"],A);let I=s(t,["seed"]);I!=null&&l(n,["seed"],I);let P=s(t,["speechConfig"]);P!=null&&l(n,["speechConfig"],qg(P));let G=s(t,["stopSequences"]);G!=null&&l(n,["stopSequences"],G);let O=s(t,["temperature"]);O!=null&&l(n,["temperature"],O);let B=s(t,["thinkingConfig"]);B!=null&&l(n,["thinkingConfig"],B);let k=s(t,["topK"]);k!=null&&l(n,["topK"],k);let V=s(t,["topP"]);if(V!=null&&l(n,["topP"],V),s(t,["enableEnhancedCivicAnswers"])!==void 0)throw new Error("enableEnhancedCivicAnswers parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(s(t,["translationConfig"])!==void 0)throw new Error("translationConfig parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return n}function Jw(t,e,n){let r={},i=s(e,["model"]);return i!=null&&l(r,["_url","name"],ie(t,i)),r}function Ww(t,e,n){let r={},i=s(e,["model"]);return i!=null&&l(r,["_url","name"],ie(t,i)),r}function Xw(t,e){let n={},r=s(t,["authConfig"]);r!=null&&l(n,["authConfig"],BI(r));let i=s(t,["enableWidget"]);if(i!=null&&l(n,["enableWidget"],i),s(t,["groundingTypes"])!==void 0)throw new Error("groundingTypes parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return n}function Kw(t,e){let n={};if(s(t,["blockingConfidence"])!==void 0)throw new Error("blockingConfidence parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["excludeDomains"])!==void 0)throw new Error("excludeDomains parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let r=s(t,["searchTypes"]);r!=null&&l(n,["searchTypes"],r);let i=s(t,["timeRangeFilter"]);return i!=null&&l(n,["timeRangeFilter"],i),n}function Yw(t,e){let n={},r=s(t,["aspectRatio"]);r!=null&&l(n,["aspectRatio"],r);let i=s(t,["imageSize"]);if(i!=null&&l(n,["imageSize"],i),s(t,["personGeneration"])!==void 0)throw new Error("personGeneration parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["outputMimeType"])!==void 0)throw new Error("outputMimeType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["outputCompressionQuality"])!==void 0)throw new Error("outputCompressionQuality parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["imageOutputOptions"])!==void 0)throw new Error("imageOutputOptions parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["prominentPeople"])!==void 0)throw new Error("prominentPeople parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return n}function zw(t,e){let n={},r=s(t,["aspectRatio"]);r!=null&&l(n,["aspectRatio"],r);let i=s(t,["imageSize"]);i!=null&&l(n,["imageSize"],i);let o=s(t,["personGeneration"]);o!=null&&l(n,["personGeneration"],o);let a=s(t,["outputMimeType"]);a!=null&&l(n,["imageOutputOptions","mimeType"],a);let u=s(t,["outputCompressionQuality"]);u!=null&&l(n,["imageOutputOptions","compressionQuality"],u);let c=s(t,["imageOutputOptions"]);c!=null&&l(n,["imageOutputOptions"],c);let d=s(t,["prominentPeople"]);return d!=null&&l(n,["prominentPeople"],d),n}function Qw(t,e){let n={},r=s(t,["bytesBase64Encoded"]);r!=null&&l(n,["imageBytes"],en(r));let i=s(t,["mimeType"]);return i!=null&&l(n,["mimeType"],i),n}function Gg(t,e){let n={},r=s(t,["gcsUri"]);r!=null&&l(n,["gcsUri"],r);let i=s(t,["bytesBase64Encoded"]);i!=null&&l(n,["imageBytes"],en(i));let o=s(t,["mimeType"]);return o!=null&&l(n,["mimeType"],o),n}function Po(t,e){let n={};if(s(t,["gcsUri"])!==void 0)throw new Error("gcsUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let r=s(t,["imageBytes"]);r!=null&&l(n,["bytesBase64Encoded"],en(r));let i=s(t,["mimeType"]);return i!=null&&l(n,["mimeType"],i),n}function ft(t,e){let n={},r=s(t,["gcsUri"]);r!=null&&l(n,["gcsUri"],r);let i=s(t,["imageBytes"]);i!=null&&l(n,["bytesBase64Encoded"],en(i));let o=s(t,["mimeType"]);return o!=null&&l(n,["mimeType"],o),n}function Zw(t,e,n,r){let i={},o=s(e,["pageSize"]);n!==void 0&&o!=null&&l(n,["_query","pageSize"],o);let a=s(e,["pageToken"]);n!==void 0&&a!=null&&l(n,["_query","pageToken"],a);let u=s(e,["filter"]);n!==void 0&&u!=null&&l(n,["_query","filter"],u);let c=s(e,["queryBase"]);return n!==void 0&&c!=null&&l(n,["_url","models_url"],Pg(t,c)),i}function jw(t,e,n,r){let i={},o=s(e,["pageSize"]);n!==void 0&&o!=null&&l(n,["_query","pageSize"],o);let a=s(e,["pageToken"]);n!==void 0&&a!=null&&l(n,["_query","pageToken"],a);let u=s(e,["filter"]);n!==void 0&&u!=null&&l(n,["_query","filter"],u);let c=s(e,["queryBase"]);return n!==void 0&&c!=null&&l(n,["_url","models_url"],Pg(t,c)),i}function eP(t,e,n){let r={},i=s(e,["config"]);return i!=null&&Zw(t,i,r),r}function tP(t,e,n){let r={},i=s(e,["config"]);return i!=null&&jw(t,i,r),r}function nP(t,e){let n={},r=s(t,["sdkHttpResponse"]);r!=null&&l(n,["sdkHttpResponse"],r);let i=s(t,["nextPageToken"]);i!=null&&l(n,["nextPageToken"],i);let o=s(t,["_self"]);if(o!=null){let a=Rg(o);Array.isArray(a)&&(a=a.map(u=>Ll(u))),l(n,["models"],a)}return n}function rP(t,e){let n={},r=s(t,["sdkHttpResponse"]);r!=null&&l(n,["sdkHttpResponse"],r);let i=s(t,["nextPageToken"]);i!=null&&l(n,["nextPageToken"],i);let o=s(t,["_self"]);if(o!=null){let a=Rg(o);Array.isArray(a)&&(a=a.map(u=>Ol(u))),l(n,["models"],a)}return n}function iP(t,e){let n={},r=s(t,["maskMode"]);r!=null&&l(n,["maskMode"],r);let i=s(t,["segmentationClasses"]);i!=null&&l(n,["maskClasses"],i);let o=s(t,["maskDilation"]);return o!=null&&l(n,["dilation"],o),n}function oP(t,e){let n={};if(s(t,["name"])!==void 0)throw new Error("name parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(s(t,["streamableHttpTransport"])!==void 0)throw new Error("streamableHttpTransport parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return n}function Ll(t,e){let n={},r=s(t,["name"]);r!=null&&l(n,["name"],r);let i=s(t,["displayName"]);i!=null&&l(n,["displayName"],i);let o=s(t,["description"]);o!=null&&l(n,["description"],o);let a=s(t,["version"]);a!=null&&l(n,["version"],a);let u=s(t,["_self"]);u!=null&&l(n,["tunedModelInfo"],wP(u));let c=s(t,["inputTokenLimit"]);c!=null&&l(n,["inputTokenLimit"],c);let d=s(t,["outputTokenLimit"]);d!=null&&l(n,["outputTokenLimit"],d);let f=s(t,["supportedGenerationMethods"]);f!=null&&l(n,["supportedActions"],f);let p=s(t,["temperature"]);p!=null&&l(n,["temperature"],p);let h=s(t,["maxTemperature"]);h!=null&&l(n,["maxTemperature"],h);let m=s(t,["topP"]);m!=null&&l(n,["topP"],m);let _=s(t,["topK"]);_!=null&&l(n,["topK"],_);let g=s(t,["thinking"]);return g!=null&&l(n,["thinking"],g),n}function Ol(t,e){let n={},r=s(t,["name"]);r!=null&&l(n,["name"],r);let i=s(t,["displayName"]);i!=null&&l(n,["displayName"],i);let o=s(t,["description"]);o!=null&&l(n,["description"],o);let a=s(t,["versionId"]);a!=null&&l(n,["version"],a);let u=s(t,["deployedModels"]);if(u!=null){let h=u;Array.isArray(h)&&(h=h.map(m=>_w(m))),l(n,["endpoints"],h)}let c=s(t,["labels"]);c!=null&&l(n,["labels"],c);let d=s(t,["_self"]);d!=null&&l(n,["tunedModelInfo"],PP(d));let f=s(t,["defaultCheckpointId"]);f!=null&&l(n,["defaultCheckpointId"],f);let p=s(t,["checkpoints"]);if(p!=null){let h=p;Array.isArray(h)&&(h=h.map(m=>m)),l(n,["checkpoints"],h)}return n}function sP(t,e){let n={},r=s(t,["speakerVoiceConfigs"]);if(r!=null){let i=r;Array.isArray(i)&&(i=i.map(o=>AP(o))),l(n,["speakerVoiceConfigs"],i)}return n}function aP(t,e){let n={},r=s(t,["mediaResolution"]);r!=null&&l(n,["mediaResolution"],r);let i=s(t,["toolCall"]);i!=null&&l(n,["toolCall"],i);let o=s(t,["toolResponse"]);o!=null&&l(n,["toolResponse"],o);let a=s(t,["audioTranscription"]);a!=null&&l(n,["audioTranscription"],a);let u=s(t,["codeExecutionResult"]);u!=null&&l(n,["codeExecutionResult"],u);let c=s(t,["executableCode"]);c!=null&&l(n,["executableCode"],c);let d=s(t,["fileData"]);d!=null&&l(n,["fileData"],Ew(d));let f=s(t,["functionCall"]);f!=null&&l(n,["functionCall"],vw(f));let p=s(t,["functionResponse"]);p!=null&&l(n,["functionResponse"],p);let h=s(t,["inlineData"]);h!=null&&l(n,["inlineData"],HI(h));let m=s(t,["text"]);m!=null&&l(n,["text"],m);let _=s(t,["thought"]);_!=null&&l(n,["thought"],_);let g=s(t,["thoughtSignature"]);g!=null&&l(n,["thoughtSignature"],g);let E=s(t,["videoMetadata"]);E!=null&&l(n,["videoMetadata"],E);let y=s(t,["partMetadata"]);return y!=null&&l(n,["partMetadata"],y),n}function lP(t,e){let n={},r=s(t,["mediaResolution"]);if(r!=null&&l(n,["mediaResolution"],r),s(t,["toolCall"])!==void 0)throw new Error("toolCall parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(s(t,["toolResponse"])!==void 0)throw new Error("toolResponse parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");let i=s(t,["audioTranscription"]);i!=null&&l(n,["audioTranscription"],i);let o=s(t,["codeExecutionResult"]);o!=null&&l(n,["codeExecutionResult"],JI(o));let a=s(t,["executableCode"]);a!=null&&l(n,["executableCode"],yw(a));let u=s(t,["fileData"]);u!=null&&l(n,["fileData"],u);let c=s(t,["functionCall"]);c!=null&&l(n,["functionCall"],c);let d=s(t,["functionResponse"]);d!=null&&l(n,["functionResponse"],d);let f=s(t,["inlineData"]);f!=null&&l(n,["inlineData"],f);let p=s(t,["text"]);p!=null&&l(n,["text"],p);let h=s(t,["thought"]);h!=null&&l(n,["thought"],h);let m=s(t,["thoughtSignature"]);m!=null&&l(n,["thoughtSignature"],m);let _=s(t,["videoMetadata"]);if(_!=null&&l(n,["videoMetadata"],_),s(t,["partMetadata"])!==void 0)throw new Error("partMetadata parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return n}function uP(t,e){let n={},r=s(t,["productImage"]);return r!=null&&l(n,["image"],ft(r)),n}function cP(t,e,n){let r={},i=s(t,["numberOfImages"]);e!==void 0&&i!=null&&l(e,["parameters","sampleCount"],i);let o=s(t,["baseSteps"]);e!==void 0&&o!=null&&l(e,["parameters","baseSteps"],o);let a=s(t,["outputGcsUri"]);e!==void 0&&a!=null&&l(e,["parameters","storageUri"],a);let u=s(t,["seed"]);e!==void 0&&u!=null&&l(e,["parameters","seed"],u);let c=s(t,["safetyFilterLevel"]);e!==void 0&&c!=null&&l(e,["parameters","safetySetting"],c);let d=s(t,["personGeneration"]);e!==void 0&&d!=null&&l(e,["parameters","personGeneration"],d);let f=s(t,["addWatermark"]);e!==void 0&&f!=null&&l(e,["parameters","addWatermark"],f);let p=s(t,["outputMimeType"]);e!==void 0&&p!=null&&l(e,["parameters","outputOptions","mimeType"],p);let h=s(t,["outputCompressionQuality"]);e!==void 0&&h!=null&&l(e,["parameters","outputOptions","compressionQuality"],h);let m=s(t,["enhancePrompt"]);e!==void 0&&m!=null&&l(e,["parameters","enhancePrompt"],m);let _=s(t,["labels"]);return e!==void 0&&_!=null&&l(e,["labels"],_),r}function dP(t,e,n){let r={},i=s(e,["model"]);i!=null&&l(r,["_url","model"],ie(t,i));let o=s(e,["source"]);o!=null&&pP(o,r);let a=s(e,["config"]);return a!=null&&cP(a,r),r}function fP(t,e){let n={},r=s(t,["predictions"]);if(r!=null){let i=r;Array.isArray(i)&&(i=i.map(o=>wo(o))),l(n,["generatedImages"],i)}return n}function pP(t,e,n){let r={},i=s(t,["prompt"]);e!==void 0&&i!=null&&l(e,["instances[0]","prompt"],i);let o=s(t,["personImage"]);e!==void 0&&o!=null&&l(e,["instances[0]","personImage","image"],ft(o));let a=s(t,["productImages"]);if(e!==void 0&&a!=null){let u=a;Array.isArray(u)&&(u=u.map(c=>uP(c))),l(e,["instances[0]","productImages"],u)}return r}function hP(t,e){let n={},r=s(t,["referenceImage"]);r!=null&&l(n,["referenceImage"],ft(r));let i=s(t,["referenceId"]);i!=null&&l(n,["referenceId"],i);let o=s(t,["referenceType"]);o!=null&&l(n,["referenceType"],o);let a=s(t,["maskImageConfig"]);a!=null&&l(n,["maskImageConfig"],iP(a));let u=s(t,["controlImageConfig"]);u!=null&&l(n,["controlImageConfig"],QI(u));let c=s(t,["styleImageConfig"]);c!=null&&l(n,["styleImageConfig"],c);let d=s(t,["subjectImageConfig"]);return d!=null&&l(n,["subjectImageConfig"],d),n}function mP(t,e){let n={},r=s(t,["mimeType"]);r!=null&&l(n,["mimeType"],r);let i=s(t,["voiceSampleAudio"]);if(i!=null&&l(n,["voiceSampleAudio"],i),s(t,["consentAudio"])!==void 0)throw new Error("consentAudio parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(s(t,["voiceConsentSignature"])!==void 0)throw new Error("voiceConsentSignature parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return n}function Lg(t,e){let n={},r=s(t,["safetyAttributes","categories"]);r!=null&&l(n,["categories"],r);let i=s(t,["safetyAttributes","scores"]);i!=null&&l(n,["scores"],i);let o=s(t,["contentType"]);return o!=null&&l(n,["contentType"],o),n}function Og(t,e){let n={},r=s(t,["safetyAttributes","categories"]);r!=null&&l(n,["categories"],r);let i=s(t,["safetyAttributes","scores"]);i!=null&&l(n,["scores"],i);let o=s(t,["contentType"]);return o!=null&&l(n,["contentType"],o),n}function gP(t,e){let n={},r=s(t,["category"]);if(r!=null&&l(n,["category"],r),s(t,["method"])!==void 0)throw new Error("method parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let i=s(t,["threshold"]);return i!=null&&l(n,["threshold"],i),n}function _P(t,e){let n={},r=s(t,["image"]);return r!=null&&l(n,["image"],ft(r)),n}function yP(t,e,n){let r={},i=s(t,["mode"]);e!==void 0&&i!=null&&l(e,["parameters","mode"],i);let o=s(t,["maxPredictions"]);e!==void 0&&o!=null&&l(e,["parameters","maxPredictions"],o);let a=s(t,["confidenceThreshold"]);e!==void 0&&a!=null&&l(e,["parameters","confidenceThreshold"],a);let u=s(t,["maskDilation"]);e!==void 0&&u!=null&&l(e,["parameters","maskDilation"],u);let c=s(t,["binaryColorThreshold"]);e!==void 0&&c!=null&&l(e,["parameters","binaryColorThreshold"],c);let d=s(t,["labels"]);return e!==void 0&&d!=null&&l(e,["labels"],d),r}function EP(t,e,n){let r={},i=s(e,["model"]);i!=null&&l(r,["_url","model"],ie(t,i));let o=s(e,["source"]);o!=null&&TP(o,r);let a=s(e,["config"]);return a!=null&&yP(a,r),r}function vP(t,e){let n={},r=s(t,["predictions"]);if(r!=null){let i=r;Array.isArray(i)&&(i=i.map(o=>Bw(o))),l(n,["generatedMasks"],i)}return n}function TP(t,e,n){let r={},i=s(t,["prompt"]);e!==void 0&&i!=null&&l(e,["instances[0]","prompt"],i);let o=s(t,["image"]);e!==void 0&&o!=null&&l(e,["instances[0]","image"],ft(o));let a=s(t,["scribbleImage"]);return e!==void 0&&a!=null&&l(e,["instances[0]","scribble"],_P(a)),r}function AP(t,e){let n={},r=s(t,["speaker"]);r!=null&&l(n,["speaker"],r);let i=s(t,["voiceConfig"]);return i!=null&&l(n,["voiceConfig"],Vg(i)),n}function qg(t,e){let n={},r=s(t,["voiceConfig"]);r!=null&&l(n,["voiceConfig"],Vg(r));let i=s(t,["languageCode"]);i!=null&&l(n,["languageCode"],i);let o=s(t,["multiSpeakerVoiceConfig"]);return o!=null&&l(n,["multiSpeakerVoiceConfig"],sP(o)),n}function CP(t,e){let n={},r=s(t,["functionCallingConfig"]);r!=null&&l(n,["functionCallingConfig"],Tw(r));let i=s(t,["retrievalConfig"]);i!=null&&l(n,["retrievalConfig"],i);let o=s(t,["includeServerSideToolInvocations"]);return o!=null&&l(n,["includeServerSideToolInvocations"],o),n}function SP(t,e){let n={},r=s(t,["functionCallingConfig"]);r!=null&&l(n,["functionCallingConfig"],r);let i=s(t,["retrievalConfig"]);if(i!=null&&l(n,["retrievalConfig"],i),s(t,["includeServerSideToolInvocations"])!==void 0)throw new Error("includeServerSideToolInvocations parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return n}function IP(t,e){let n={};if(s(t,["retrieval"])!==void 0)throw new Error("retrieval parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let r=s(t,["googleMaps"]);r!=null&&l(n,["googleMaps"],Xw(r));let i=s(t,["mcpServers"]);if(i!=null){let h=i;Array.isArray(h)&&(h=h.map(m=>m)),l(n,["mcpServers"],h)}let o=s(t,["codeExecution"]);o!=null&&l(n,["codeExecution"],o);let a=s(t,["computerUse"]);if(a!=null&&l(n,["computerUse"],a),s(t,["enterpriseWebSearch"])!==void 0)throw new Error("enterpriseWebSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["exaAiSearch"])!==void 0)throw new Error("exaAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let u=s(t,["functionDeclarations"]);if(u!=null){let h=u;Array.isArray(h)&&(h=h.map(m=>m)),l(n,["functionDeclarations"],h)}let c=s(t,["googleSearch"]);c!=null&&l(n,["googleSearch"],Kw(c));let d=s(t,["googleSearchRetrieval"]);if(d!=null&&l(n,["googleSearchRetrieval"],d),s(t,["parallelAiSearch"])!==void 0)throw new Error("parallelAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let f=s(t,["urlContext"]);f!=null&&l(n,["urlContext"],f);let p=s(t,["fileSearch"]);return p!=null&&l(n,["fileSearch"],p),n}function Fg(t,e){let n={},r=s(t,["retrieval"]);r!=null&&l(n,["retrieval"],r);let i=s(t,["googleMaps"]);i!=null&&l(n,["googleMaps"],i);let o=s(t,["mcpServers"]);if(o!=null){let g=o;Array.isArray(g)&&(g=g.map(E=>oP(E))),l(n,["mcpServers"],g)}let a=s(t,["codeExecution"]);a!=null&&l(n,["codeExecution"],a);let u=s(t,["computerUse"]);u!=null&&l(n,["computerUse"],KI(u));let c=s(t,["enterpriseWebSearch"]);c!=null&&l(n,["enterpriseWebSearch"],c);let d=s(t,["exaAiSearch"]);d!=null&&l(n,["exaAiSearch"],d);let f=s(t,["functionDeclarations"]);if(f!=null){let g=f;Array.isArray(g)&&(g=g.map(E=>E)),l(n,["functionDeclarations"],g)}let p=s(t,["googleSearch"]);p!=null&&l(n,["googleSearch"],p);let h=s(t,["googleSearchRetrieval"]);h!=null&&l(n,["googleSearchRetrieval"],h);let m=s(t,["parallelAiSearch"]);m!=null&&l(n,["parallelAiSearch"],m);let _=s(t,["urlContext"]);if(_!=null&&l(n,["urlContext"],_),s(t,["fileSearch"])!==void 0)throw new Error("fileSearch parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return n}function wP(t,e){let n={},r=s(t,["baseModel"]);r!=null&&l(n,["baseModel"],r);let i=s(t,["createTime"]);i!=null&&l(n,["createTime"],i);let o=s(t,["updateTime"]);return o!=null&&l(n,["updateTime"],o),n}function PP(t,e){let n={},r=s(t,["labels","google-vertex-llm-tuning-base-model-id"]);r!=null&&l(n,["baseModel"],r);let i=s(t,["createTime"]);i!=null&&l(n,["createTime"],i);let o=s(t,["updateTime"]);return o!=null&&l(n,["updateTime"],o),n}function RP(t,e,n){let r={},i=s(t,["displayName"]);e!==void 0&&i!=null&&l(e,["displayName"],i);let o=s(t,["description"]);e!==void 0&&o!=null&&l(e,["description"],o);let a=s(t,["defaultCheckpointId"]);return e!==void 0&&a!=null&&l(e,["defaultCheckpointId"],a),r}function NP(t,e,n){let r={},i=s(t,["displayName"]);e!==void 0&&i!=null&&l(e,["displayName"],i);let o=s(t,["description"]);e!==void 0&&o!=null&&l(e,["description"],o);let a=s(t,["defaultCheckpointId"]);return e!==void 0&&a!=null&&l(e,["defaultCheckpointId"],a),r}function xP(t,e,n){let r={},i=s(e,["model"]);i!=null&&l(r,["_url","name"],ie(t,i));let o=s(e,["config"]);return o!=null&&RP(o,r),r}function kP(t,e,n){let r={},i=s(e,["model"]);i!=null&&l(r,["_url","model"],ie(t,i));let o=s(e,["config"]);return o!=null&&NP(o,r),r}function DP(t,e,n){let r={},i=s(t,["outputGcsUri"]);e!==void 0&&i!=null&&l(e,["parameters","storageUri"],i);let o=s(t,["safetyFilterLevel"]);e!==void 0&&o!=null&&l(e,["parameters","safetySetting"],o);let a=s(t,["personGeneration"]);e!==void 0&&a!=null&&l(e,["parameters","personGeneration"],a);let u=s(t,["includeRaiReason"]);e!==void 0&&u!=null&&l(e,["parameters","includeRaiReason"],u);let c=s(t,["outputMimeType"]);e!==void 0&&c!=null&&l(e,["parameters","outputOptions","mimeType"],c);let d=s(t,["outputCompressionQuality"]);e!==void 0&&d!=null&&l(e,["parameters","outputOptions","compressionQuality"],d);let f=s(t,["enhanceInputImage"]);e!==void 0&&f!=null&&l(e,["parameters","upscaleConfig","enhanceInputImage"],f);let p=s(t,["imagePreservationFactor"]);e!==void 0&&p!=null&&l(e,["parameters","upscaleConfig","imagePreservationFactor"],p);let h=s(t,["labels"]);e!==void 0&&h!=null&&l(e,["labels"],h);let m=s(t,["numberOfImages"]);e!==void 0&&m!=null&&l(e,["parameters","sampleCount"],m);let _=s(t,["mode"]);return e!==void 0&&_!=null&&l(e,["parameters","mode"],_),r}function MP(t,e,n){let r={},i=s(e,["model"]);i!=null&&l(r,["_url","model"],ie(t,i));let o=s(e,["image"]);o!=null&&l(r,["instances[0]","image"],ft(o));let a=s(e,["upscaleFactor"]);a!=null&&l(r,["parameters","upscaleConfig","upscaleFactor"],a);let u=s(e,["config"]);return u!=null&&DP(u,r),r}function UP(t,e){let n={},r=s(t,["sdkHttpResponse"]);r!=null&&l(n,["sdkHttpResponse"],r);let i=s(t,["predictions"]);if(i!=null){let o=i;Array.isArray(o)&&(o=o.map(a=>wo(a))),l(n,["generatedImages"],o)}return n}function bP(t,e){let n={},r=s(t,["uri"]);r!=null&&l(n,["uri"],r);let i=s(t,["encodedVideo"]);i!=null&&l(n,["videoBytes"],en(i));let o=s(t,["encoding"]);return o!=null&&l(n,["mimeType"],o),n}function GP(t,e){let n={},r=s(t,["gcsUri"]);r!=null&&l(n,["uri"],r);let i=s(t,["bytesBase64Encoded"]);i!=null&&l(n,["videoBytes"],en(i));let o=s(t,["mimeType"]);return o!=null&&l(n,["mimeType"],o),n}function LP(t,e){let n={},r=s(t,["image"]);r!=null&&l(n,["_self"],ft(r));let i=s(t,["maskMode"]);return i!=null&&l(n,["maskMode"],i),n}function OP(t,e){let n={},r=s(t,["image"]);r!=null&&l(n,["image"],Po(r));let i=s(t,["referenceType"]);return i!=null&&l(n,["referenceType"],i),n}function qP(t,e){let n={},r=s(t,["image"]);r!=null&&l(n,["image"],ft(r));let i=s(t,["referenceType"]);return i!=null&&l(n,["referenceType"],i),n}function Bg(t,e){let n={},r=s(t,["uri"]);r!=null&&l(n,["uri"],r);let i=s(t,["videoBytes"]);i!=null&&l(n,["encodedVideo"],en(i));let o=s(t,["mimeType"]);return o!=null&&l(n,["encoding"],o),n}function Hg(t,e){let n={},r=s(t,["uri"]);r!=null&&l(n,["gcsUri"],r);let i=s(t,["videoBytes"]);i!=null&&l(n,["bytesBase64Encoded"],en(i));let o=s(t,["mimeType"]);return o!=null&&l(n,["mimeType"],o),n}function Vg(t,e){let n={},r=s(t,["replicatedVoiceConfig"]);r!=null&&l(n,["replicatedVoiceConfig"],mP(r));let i=s(t,["prebuiltVoiceConfig"]);return i!=null&&l(n,["prebuiltVoiceConfig"],i),n}function FP(t,e,n){let r={},i=s(e,["displayName"]);n!==void 0&&i!=null&&l(n,["displayName"],i);let o=s(e,["embeddingModel"]);return n!==void 0&&o!=null&&l(n,["embeddingModel"],ie(t,o)),r}function BP(t,e){let n={},r=s(e,["config"]);return r!=null&&FP(t,r,n),n}function HP(t,e){let n={},r=s(t,["force"]);return e!==void 0&&r!=null&&l(e,["_query","force"],r),n}function VP(t){let e={},n=s(t,["name"]);n!=null&&l(e,["_url","name"],n);let r=s(t,["config"]);return r!=null&&HP(r,e),e}function $P(t){let e={},n=s(t,["name"]);return n!=null&&l(e,["_url","name"],n),e}function JP(t,e){let n={},r=s(t,["customMetadata"]);if(e!==void 0&&r!=null){let o=r;Array.isArray(o)&&(o=o.map(a=>a)),l(e,["customMetadata"],o)}let i=s(t,["chunkingConfig"]);return e!==void 0&&i!=null&&l(e,["chunkingConfig"],i),n}function WP(t){let e={},n=s(t,["name"]);n!=null&&l(e,["name"],n);let r=s(t,["metadata"]);r!=null&&l(e,["metadata"],r);let i=s(t,["done"]);i!=null&&l(e,["done"],i);let o=s(t,["error"]);o!=null&&l(e,["error"],o);let a=s(t,["response"]);return a!=null&&l(e,["response"],KP(a)),e}function XP(t){let e={},n=s(t,["fileSearchStoreName"]);n!=null&&l(e,["_url","file_search_store_name"],n);let r=s(t,["fileName"]);r!=null&&l(e,["fileName"],r);let i=s(t,["config"]);return i!=null&&JP(i,e),e}function KP(t){let e={},n=s(t,["sdkHttpResponse"]);n!=null&&l(e,["sdkHttpResponse"],n);let r=s(t,["parent"]);r!=null&&l(e,["parent"],r);let i=s(t,["documentName"]);return i!=null&&l(e,["documentName"],i),e}function YP(t,e){let n={},r=s(t,["pageSize"]);e!==void 0&&r!=null&&l(e,["_query","pageSize"],r);let i=s(t,["pageToken"]);return e!==void 0&&i!=null&&l(e,["_query","pageToken"],i),n}function zP(t){let e={},n=s(t,["config"]);return n!=null&&YP(n,e),e}function QP(t){let e={},n=s(t,["sdkHttpResponse"]);n!=null&&l(e,["sdkHttpResponse"],n);let r=s(t,["nextPageToken"]);r!=null&&l(e,["nextPageToken"],r);let i=s(t,["fileSearchStores"]);if(i!=null){let o=i;Array.isArray(o)&&(o=o.map(a=>a)),l(e,["fileSearchStores"],o)}return e}function $g(t,e){let n={},r=s(t,["mimeType"]);e!==void 0&&r!=null&&l(e,["mimeType"],r);let i=s(t,["displayName"]);e!==void 0&&i!=null&&l(e,["displayName"],i);let o=s(t,["customMetadata"]);if(e!==void 0&&o!=null){let u=o;Array.isArray(u)&&(u=u.map(c=>c)),l(e,["customMetadata"],u)}let a=s(t,["chunkingConfig"]);return e!==void 0&&a!=null&&l(e,["chunkingConfig"],a),n}function ZP(t){let e={},n=s(t,["fileSearchStoreName"]);n!=null&&l(e,["_url","file_search_store_name"],n);let r=s(t,["config"]);return r!=null&&$g(r,e),e}function jP(t){let e={},n=s(t,["sdkHttpResponse"]);return n!=null&&l(e,["sdkHttpResponse"],n),e}var eR="Content-Type",tR="X-Server-Timeout",nR="User-Agent",ql="x-goog-api-client",rR="2.15.0",iR=`google-genai-sdk/${rR}`,oR="v1beta1",sR="v1beta",aR=new Set(["us","eu"]),lR=5,uR=1,cR=60,dR=2,fR=1,pR=[408,429,500,502,503,504],Fl=class{constructor(e){var n,r,i;this.clientOptions=Object.assign({},e),this.customBaseUrl=(n=e.httpOptions)===null||n===void 0?void 0:n.baseUrl;let o={};if(this.clientOptions.vertexai){if(!this.clientOptions.location&&!this.clientOptions.apiKey&&!this.customBaseUrl&&(this.clientOptions.location="global"),!(this.clientOptions.project&&this.clientOptions.location||this.clientOptions.apiKey)&&!this.customBaseUrl)throw new Error("Authentication is not set up. Please provide either a project and location, or an API key, or a custom base URL.");let u=e.project&&e.location||!!e.apiKey;this.customBaseUrl&&!u?(o.baseUrl=this.customBaseUrl,this.clientOptions.project=void 0,this.clientOptions.location=void 0):this.clientOptions.apiKey&&!this.clientOptions.project||this.clientOptions.location==="global"?o.baseUrl="https://aiplatform.googleapis.com/":this.clientOptions.project&&this.clientOptions.location&&aR.has(this.clientOptions.location)?o.baseUrl=`https://aiplatform.${this.clientOptions.location}.rep.googleapis.com/`:this.clientOptions.project&&this.clientOptions.location&&(o.baseUrl=`https://${this.clientOptions.location}-aiplatform.googleapis.com/`),o.apiVersion=(r=this.clientOptions.apiVersion)!==null&&r!==void 0?r:oR}else this.clientOptions.apiKey||console.warn("API key should be set when using the Gemini API."),o.apiVersion=(i=this.clientOptions.apiVersion)!==null&&i!==void 0?i:sR,o.baseUrl="https://generativelanguage.googleapis.com/";o.headers=this.getDefaultHeaders(),this.clientOptions.httpOptions=o,e.httpOptions&&(this.clientOptions.httpOptions=this.patchHttpOptions(o,e.httpOptions))}isVertexAI(){var e;return(e=this.clientOptions.vertexai)!==null&&e!==void 0?e:!1}getProject(){return this.clientOptions.project}getLocation(){return this.clientOptions.location}getCustomBaseUrl(){return this.customBaseUrl}async getAuthHeaders(){let e=new Headers;return await this.clientOptions.auth.addAuthHeaders(e),e}getApiVersion(){if(this.clientOptions.httpOptions&&this.clientOptions.httpOptions.apiVersion!==void 0)return this.clientOptions.httpOptions.apiVersion;throw new Error("API version is not set.")}getBaseUrl(){if(this.clientOptions.httpOptions&&this.clientOptions.httpOptions.baseUrl!==void 0)return this.clientOptions.httpOptions.baseUrl;throw new Error("Base URL is not set.")}getRequestUrl(){return this.getRequestUrlInternal(this.clientOptions.httpOptions)}getHeaders(){if(this.clientOptions.httpOptions&&this.clientOptions.httpOptions.headers!==void 0)return this.clientOptions.httpOptions.headers;throw new Error("Headers are not set.")}getRequestUrlInternal(e){if(!e||e.baseUrl===void 0||e.apiVersion===void 0)throw new Error("HTTP options are not correctly set.");let r=[e.baseUrl.endsWith("/")?e.baseUrl.slice(0,-1):e.baseUrl];return e.apiVersion&&e.apiVersion!==""&&r.push(e.apiVersion),r.join("/")}getBaseResourcePath(){return`projects/${this.clientOptions.project}/locations/${this.clientOptions.location}`}getApiKey(){return this.clientOptions.apiKey}getWebsocketBaseUrl(){let e=this.getBaseUrl(),n=new URL(e);return n.protocol=n.protocol=="http:"?"ws":"wss",n.toString()}setBaseUrl(e){if(this.clientOptions.httpOptions)this.clientOptions.httpOptions.baseUrl=e;else throw new Error("HTTP options are not correctly set.")}constructUrl(e,n,r){let i=[this.getRequestUrlInternal(n)];return r&&i.push(this.getBaseResourcePath()),e!==""&&i.push(e),new URL(`${i.join("/")}`)}shouldPrependVertexProjectPath(e,n){return!(n.baseUrl&&n.baseUrlResourceScope===fl.COLLECTION||!this.clientOptions.vertexai||!this.clientOptions.project||!this.clientOptions.location||e.path.startsWith("projects/")||e.httpMethod==="GET"&&e.path.startsWith("publishers/google/models"))}async request(e){let n=this.clientOptions.httpOptions;e.httpOptions&&(n=this.patchHttpOptions(this.clientOptions.httpOptions,e.httpOptions));let r=this.shouldPrependVertexProjectPath(e,n),i=this.constructUrl(e.path,n,r);if(e.queryParams)for(let[a,u]of Object.entries(e.queryParams))i.searchParams.append(a,String(u));let o={};if(e.httpMethod==="GET"){if(e.body&&e.body!=="{}")throw new Error("Request body should be empty for GET request, but got non empty request body")}else o.body=e.body;return o=await this.includeExtraHttpOptionsToRequestInit(o,n,i.toString(),e.abortSignal),this.unaryApiCall(i,o,e.httpMethod,n.retryOptions)}patchHttpOptions(e,n){let r=JSON.parse(JSON.stringify(e));for(let[i,o]of Object.entries(n))typeof o=="object"?r[i]=Object.assign(Object.assign({},r[i]),o):o!==void 0&&(r[i]=o);return r}async requestStream(e){let n=this.clientOptions.httpOptions;e.httpOptions&&(n=this.patchHttpOptions(this.clientOptions.httpOptions,e.httpOptions));let r=this.shouldPrependVertexProjectPath(e,n),i=this.constructUrl(e.path,n,r);(!i.searchParams.has("alt")||i.searchParams.get("alt")!=="sse")&&i.searchParams.set("alt","sse");let o={};return o.body=e.body,o=await this.includeExtraHttpOptionsToRequestInit(o,n,i.toString(),e.abortSignal),this.streamApiCall(i,o,e.httpMethod,n.retryOptions)}async includeExtraHttpOptionsToRequestInit(e,n,r,i){if(n&&n.timeout||i){let o=new AbortController,a=o.signal;if(n.timeout&&n?.timeout>0){let c=globalThis[Symbol.for("undici.globalDispatcher.1")];if(c){let f=Object.getOwnPropertySymbols(c);for(let p of f){let h=p.description;if(h?.includes("headers timeout")||h?.includes("body timeout")){let m=c[p];typeof m=="number"&&(c[p]=Math.max(m,n.timeout))}}}let d=setTimeout(()=>o.abort(),n.timeout);d&&typeof d.unref=="function"&&d.unref()}i&&i.addEventListener("abort",()=>{o.abort()}),e.signal=a}return n&&n.extraBody!==null&&hR(e,n.extraBody),e.headers=await this.getHeadersInternal(n,r),e}async unaryApiCall(e,n,r,i){return this.apiCall(e.toString(),Object.assign(Object.assign({},n),{method:r}),i).then(async o=>(await al(o),new Kt(o))).catch(o=>{throw o instanceof Error?o:new Error(`exception ${o} sending request`,{cause:o})})}async streamApiCall(e,n,r,i){return this.apiCall(e.toString(),Object.assign(Object.assign({},n),{method:r}),i).then(async o=>(await al(o),this.processStreamResponse(o))).catch(o=>{throw o instanceof Error?o:new Error(`exception ${o} sending request`,{cause:o})})}processStreamResponse(e){return Xn(this,arguments,function*(){var r;let i=(r=e?.body)===null||r===void 0?void 0:r.getReader(),o=new TextDecoder("utf-8");if(!i)throw new Error("Response body is empty");try{let a="",u="data:",c=[`
37
-
38
- `,"\r\r",`\r
39
- \r
40
- `];for(;;){let{done:d,value:f}=yield ye(i.read());if(d){if(a.trim().length>0)throw new Error("Incomplete JSON segment at the end");break}let p=o.decode(f,{stream:!0});try{let _=JSON.parse(p);if("error"in _){let g=JSON.parse(JSON.stringify(_.error)),E=g.status,y=g.code,C=`got status: ${E}. ${JSON.stringify(_)}`;if(y>=400&&y<600)throw new _o({message:C,status:y})}}catch(_){if(_.name==="ApiError")throw _}a+=p;let h=-1,m=0;for(;;){h=-1,m=0;for(let E of c){let y=a.indexOf(E);y!==-1&&(h===-1||y<h)&&(h=y,m=E.length)}if(h===-1)break;let _=a.substring(0,h);a=a.substring(h+m);let g=_.trim();if(g.startsWith(u)){let E=g.substring(u.length).trim();try{let y=new Response(E,{headers:e?.headers,status:e?.status,statusText:e?.statusText});yield yield ye(new Kt(y))}catch(y){throw new Error(`exception parsing stream chunk ${E}. ${y}`)}}}}}finally{i.releaseLock()}})}async apiCall(e,n,r){var i,o,a,u,c,d;if(!r)return fetch(e,n);let f=(i=r.httpStatusCodes)!==null&&i!==void 0?i:pR,p=async()=>{let g=await fetch(e,n);return g.ok||!f.includes(g.status)||await al(g),g},h=Math.max(1,(o=r.attempts)!==null&&o!==void 0?o:lR),m=Math.round(((a=r.initialDelay)!==null&&a!==void 0?a:uR)*1e3),_=Math.max(m,Math.round(((u=r.maxDelay)!==null&&u!==void 0?u:cR)*1e3));return(0,pg.default)(p,{retries:h-1,factor:(c=r.expBase)!==null&&c!==void 0?c:dR,minTimeout:m,maxTimeout:_,randomize:((d=r.jitter)!==null&&d!==void 0?d:fR)>0})}getDefaultHeaders(){let e={},n=iR+" "+this.clientOptions.userAgentExtra;return e[nR]=n,e[ql]=n,e[eR]="application/json",e}async getHeadersInternal(e,n){let r=new Headers;if(e&&e.headers)for(let[i,o]of Object.entries(e.headers))r.append(i,o);return e?.timeout&&e.timeout>0&&r.append(tR,String(Math.ceil(e.timeout/1e3))),await this.clientOptions.auth.addAuthHeaders(r,n),r}getFileName(e){var n;let r="";return typeof e=="string"&&(r=e.replace(/[/\\]+$/,""),r=(n=r.split(/[/\\]/).pop())!==null&&n!==void 0?n:""),r}async uploadFile(e,n){var r;let i={};n!=null&&(i.mimeType=n.mimeType,i.name=n.name,i.displayName=n.displayName),i.name&&!i.name.startsWith("files/")&&(i.name=`files/${i.name}`);let o=this.clientOptions.uploader,a=await o.stat(e);i.sizeBytes=String(a.size);let u=(r=n?.mimeType)!==null&&r!==void 0?r:a.type;if(u===void 0||u==="")throw new Error("Can not determine mimeType. Please provide mimeType in the config.");i.mimeType=u;let c={file:i},d=this.getFileName(e),f=$("upload/v1beta/files",c._url),p=await this.fetchUploadUrl(f,i.sizeBytes,i.mimeType,d,c,n?.httpOptions);return o.upload(e,p,this)}async uploadFileToFileSearchStore(e,n,r){var i;let o=this.clientOptions.uploader,a=await o.stat(n),u=String(a.size),c=(i=r?.mimeType)!==null&&i!==void 0?i:a.type;if(c===void 0||c==="")throw new Error("Can not determine mimeType. Please provide mimeType in the config.");let d=`upload/v1beta/${e}:uploadToFileSearchStore`,f=this.getFileName(n),p={};r!=null&&$g(r,p);let h=await this.fetchUploadUrl(d,u,c,f,p,r?.httpOptions);return o.uploadToFileSearchStore(n,h,this)}async downloadFile(e){await this.clientOptions.downloader.download(e,this)}async fetchUploadUrl(e,n,r,i,o,a){var u;let c={};a?c=a:c={apiVersion:"",headers:Object.assign({"Content-Type":"application/json","X-Goog-Upload-Protocol":"resumable","X-Goog-Upload-Command":"start","X-Goog-Upload-Header-Content-Length":`${n}`,"X-Goog-Upload-Header-Content-Type":`${r}`},i?{"X-Goog-Upload-File-Name":i}:{})};let d=await this.request({path:e,body:JSON.stringify(o),httpMethod:"POST",httpOptions:c});if(!d||!d?.headers)throw new Error("Server did not return an HttpResponse or the returned HttpResponse did not have headers.");let f=(u=d?.headers)===null||u===void 0?void 0:u["x-goog-upload-url"];if(f===void 0)throw new Error("Failed to get upload url. Server did not return the x-google-upload-url in the headers");return f}};async function al(t){var e;if(t===void 0)throw new Error("response is undefined");if(!t.ok){let n=t.status,r;!((e=t.headers.get("content-type"))===null||e===void 0)&&e.includes("application/json")?r=await t.json():r={error:{message:await t.text(),code:t.status,status:t.statusText}};let i=JSON.stringify(r);throw n>=400&&n<600?new _o({message:i,status:n}):new Error(i)}}function hR(t,e){if(!e||Object.keys(e).length===0)return;if(t.body instanceof Blob){console.warn("includeExtraBodyToRequestInit: extraBody provided but current request body is a Blob. extraBody will be ignored as merging is not supported for Blob bodies.");return}let n={};if(typeof t.body=="string"&&t.body.length>0)try{let o=JSON.parse(t.body);if(typeof o=="object"&&o!==null&&!Array.isArray(o))n=o;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(o,a){let u=Object.assign({},o);for(let c in a)if(Object.prototype.hasOwnProperty.call(a,c)){let d=a[c],f=u[c];d&&typeof d=="object"&&!Array.isArray(d)&&f&&typeof f=="object"&&!Array.isArray(f)?u[c]=r(f,d):(f&&d&&typeof f!=typeof d&&console.warn(`includeExtraBodyToRequestInit:deepMerge: Type mismatch for key "${c}". Original type: ${typeof f}, New type: ${typeof d}. Overwriting.`),u[c]=d)}return u}let i=r(n,e);t.body=JSON.stringify(i)}var mR="mcp_used/unknown",Jg=!1;function Wg(t){for(let e of t)if(gR(e)||typeof e=="object"&&"inputSchema"in e)return!0;return Jg}function Xg(t){var e;let n=(e=t[ql])!==null&&e!==void 0?e:"";t[ql]=(n+` ${mR}`).trimStart()}function gR(t){return t!==null&&typeof t=="object"&&t instanceof Rr}function _R(t){return Xn(this,arguments,function*(n,r=100){let i,o=0;for(;o<r;){let a=yield ye(n.listTools({cursor:i}));for(let u of a.tools)yield yield ye(u),o++;if(!a.nextCursor)break;i=a.nextCursor}})}var Rr=class t{constructor(e=[],n){this.mcpTools=[],this.functionNameToMcpClient={},this.mcpClients=e,this.config=n}static create(e,n){return new t(e,n)}async initialize(){var e,n,r,i;if(this.mcpTools.length>0)return;let o={},a=[];for(let f of this.mcpClients)try{for(var u=!0,c=(n=void 0,Pr(_R(f))),d;d=await c.next(),e=d.done,!e;u=!0){i=d.value,u=!1;let p=i;a.push(p);let h=p.name;if(o[h])throw new Error(`Duplicate function name ${h} found in MCP tools. Please ensure function names are unique.`);o[h]=f}}catch(p){n={error:p}}finally{try{!u&&!e&&(r=c.return)&&await r.call(c)}finally{if(n)throw n.error}}this.mcpTools=a,this.functionNameToMcpClient=o}async tool(){return await this.initialize(),_0(this.mcpTools,this.config)}async callTool(e){await this.initialize();let n=[];for(let r of e)if(r.name in this.functionNameToMcpClient){let i=this.functionNameToMcpClient[r.name],o;this.config.timeout&&(o={timeout:this.config.timeout});let a=await i.callTool({name:r.name,arguments:r.args},void 0,o);n.push({functionResponse:{name:r.name,response:a.isError?{error:a}:a}})}return n}};function yR(t){return t!==null&&typeof t=="object"&&"listTools"in t&&typeof t.listTools=="function"}function dM(...t){if(Jg=!0,t.length===0)throw new Error("No MCP clients provided");let e=t[t.length-1];return yR(e)?Rr.create(t,{}):Rr.create(t.slice(0,t.length-1),e)}async function ER(t,e,n){let r=new Nl,i;n.data instanceof Blob?i=JSON.parse(await n.data.text()):i=JSON.parse(n.data),Object.assign(r,i),e(r)}var Bl=class{constructor(e,n,r){this.apiClient=e,this.auth=n,this.webSocketFactory=r}async connect(e){var n,r;if(this.apiClient.isVertexAI())throw new Error("Live music is not supported for Vertex AI.");console.warn("Live music generation is experimental and may change in future versions.");let i=this.apiClient.getWebsocketBaseUrl(),o=this.apiClient.getApiVersion(),a=TR(this.apiClient.getDefaultHeaders()),u=this.apiClient.getApiKey(),c=`${i}/ws/google.ai.generativelanguage.${o}.GenerativeService.BidiGenerateMusic?key=${u}`,d=()=>{},f=new Promise(A=>{d=A}),p=e.callbacks,h=function(){d({})},m=this.apiClient,_={onopen:h,onmessage:A=>{ER(m,p.onmessage,A)},onerror:(n=p?.onerror)!==null&&n!==void 0?n:function(A){},onclose:(r=p?.onclose)!==null&&r!==void 0?r:function(A){}},g=this.webSocketFactory.create(c,vR(a),_);g.connect(),await f;let C={setup:{model:ie(this.apiClient,e.model)}};return g.send(JSON.stringify(C)),new Hl(g,this.apiClient)}},Hl=class{constructor(e,n){this.conn=e,this.apiClient=n}async setWeightedPrompts(e){if(!e.weightedPrompts||Object.keys(e.weightedPrompts).length===0)throw new Error("Weighted prompts must be set and contain at least one entry.");let n=II(e);this.conn.send(JSON.stringify({clientContent:n}))}async setMusicGenerationConfig(e){e.musicGenerationConfig||(e.musicGenerationConfig={});let n=SI(e);this.conn.send(JSON.stringify(n))}sendPlaybackControl(e){let n={playbackControl:e};this.conn.send(JSON.stringify(n))}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 vR(t){let e={};return t.forEach((n,r)=>{e[r]=n}),e}function TR(t){let e=new Headers;for(let[n,r]of Object.entries(t))e.append(n,r);return e}var AR="FunctionResponse request must have an `id` field from the response of a ToolCall.FunctionalCalls in Google AI.";async function CR(t,e,n){let r=new Rl,i;n.data instanceof Blob?i=await n.data.text():n.data instanceof ArrayBuffer?i=new TextDecoder().decode(n.data):i=n.data;let o=JSON.parse(i);if(t.isVertexAI()){let a=RI(o);Object.assign(r,a)}else Object.assign(r,o);e(r)}var Vl=class{constructor(e,n,r){this.apiClient=e,this.auth=n,this.webSocketFactory=r,this.music=new Bl(this.apiClient,this.auth,this.webSocketFactory)}async connect(e){var n,r,i,o,a,u;if(e.config&&e.config.httpOptions)throw new Error("The Live module does not support httpOptions at request-level in LiveConnectConfig yet. Please use the client-level httpOptions configuration instead.");let c=this.apiClient.getWebsocketBaseUrl(),d=this.apiClient.getApiVersion(),f,p=this.apiClient.getHeaders();e.config&&e.config.tools&&Wg(e.config.tools)&&Xg(p);let h=wR(p);if(this.apiClient.isVertexAI()){let D=this.apiClient.getProject(),K=this.apiClient.getLocation(),j=this.apiClient.getApiKey(),_e=!!D&&!!K||!!j;this.apiClient.getCustomBaseUrl()&&!_e?f=c:(f=`${c}/ws/google.cloud.aiplatform.${d}.LlmBidiService/BidiGenerateContent`,await this.auth.addAuthHeaders(h,f))}else{let D=this.apiClient.getApiKey(),K="BidiGenerateContent",j="key";D?.startsWith("auth_tokens/")&&(console.warn("Warning: Ephemeral token support is experimental and may change in future versions."),d!=="v1alpha"&&console.warn("Warning: The SDK's ephemeral token support is in v1alpha only. Please use const ai = new GoogleGenAI({apiKey: token.name, httpOptions: { apiVersion: 'v1alpha' }}); before session connection."),K="BidiGenerateContentConstrained",j="access_token"),f=`${c}/ws/google.ai.generativelanguage.${d}.GenerativeService.${K}?${j}=${D}`}let m=()=>{},_=new Promise(D=>{m=D}),g=e.callbacks,E=function(){var D;(D=g?.onopen)===null||D===void 0||D.call(g),m({})},y=this.apiClient,C=!1,A=[],I=()=>{},P=new Promise(D=>{I=D}),G={onopen:E,onmessage:D=>{CR(y,K=>{K.setupComplete&&!ne.setupComplete&&(ne.setupComplete=K.setupComplete,I({})),C?g.onmessage(K):A.push(K)},D)},onerror:(n=g?.onerror)!==null&&n!==void 0?n:function(D){},onclose:(r=g?.onclose)!==null&&r!==void 0?r:function(D){}},O=this.webSocketFactory.create(f,IR(h),G);O.connect(),await _;let B=ie(this.apiClient,e.model);if(this.apiClient.isVertexAI()&&B.startsWith("publishers/")){let D=this.apiClient.getProject(),K=this.apiClient.getLocation();D&&K&&(B=`projects/${D}/locations/${K}/`+B)}let k={};this.apiClient.isVertexAI()&&((i=e.config)===null||i===void 0?void 0:i.responseModalities)===void 0&&(e.config===void 0?e.config={responseModalities:[no.AUDIO]}:e.config.responseModalities=[no.AUDIO]),!((o=e.config)===null||o===void 0)&&o.generationConfig&&console.warn("Setting `LiveConnectConfig.generation_config` is deprecated, please set the fields on `LiveConnectConfig` directly. It will be removed in the next major version (not before 7/31/2026).");let V=(u=(a=e.config)===null||a===void 0?void 0:a.tools)!==null&&u!==void 0?u:[],X=[];for(let D of V)if(this.isCallableTool(D)){let K=D;X.push(await K.tool())}else X.push(D);X.length>0&&(e.config.tools=X);let Z={model:B,config:e.config,callbacks:e.callbacks};this.apiClient.isVertexAI()?k=CI(this.apiClient,Z):k=AI(this.apiClient,Z),delete k.config;let ne=new $l(O,this.apiClient);O.send(JSON.stringify(k)),await P,C=!0;for(let D of A)g.onmessage(D);return ne}isCallableTool(e){return"callTool"in e&&typeof e.callTool=="function"}},SR={turnComplete:!0},$l=class{constructor(e,n){this.conn=e,this.apiClient=n}tLiveClientContent(e,n){if(n.turns!==null&&n.turns!==void 0){let r=[];try{r=Le(n.turns),e.isVertexAI()||(r=r.map(i=>kr(i)))}catch{throw new Error(`Failed to parse client content "turns", type: '${typeof n.turns}'`)}return{clientContent:{turns:r,turnComplete:n.turnComplete}}}return{clientContent:{turnComplete:n.turnComplete}}}tLiveClienttToolResponse(e,n){let r=[];if(n.functionResponses==null)throw new Error("functionResponses is required.");if(Array.isArray(n.functionResponses)?r=n.functionResponses:r=[n.functionResponses],r.length===0)throw new Error("functionResponses is required.");for(let o of r){if(typeof o!="object"||o===null||!("name"in o)||!("response"in o))throw new Error(`Could not parse function response, type '${typeof o}'.`);if(!e.isVertexAI()&&!("id"in o))throw new Error(AR)}return{toolResponse:{functionResponses:r}}}sendClientContent(e){e=Object.assign(Object.assign({},SR),e);let n=this.tLiveClientContent(this.apiClient,e);this.conn.send(JSON.stringify(n))}sendRealtimeInput(e){let n={};this.apiClient.isVertexAI()?n={realtimeInput:PI(e)}:n={realtimeInput:wI(e)},this.conn.send(JSON.stringify(n))}sendToolResponse(e){if(e.functionResponses==null)throw new Error("Tool response parameters are required.");let n=this.tLiveClienttToolResponse(this.apiClient,e);this.conn.send(JSON.stringify(n))}close(){this.conn.close()}};function IR(t){let e={};return t.forEach((n,r)=>{e[r]=n}),e}function wR(t){let e=new Headers;for(let[n,r]of Object.entries(t))e.append(n,r);return e}var Jm=10;function Wm(t){var e,n,r;if(!((e=t?.automaticFunctionCalling)===null||e===void 0)&&e.disable)return!0;let i=!1;for(let a of(n=t?.tools)!==null&&n!==void 0?n:[])if(Kn(a)){i=!0;break}if(!i)return!0;let o=(r=t?.automaticFunctionCalling)===null||r===void 0?void 0:r.maximumRemoteCalls;return o&&(o<0||!Number.isInteger(o))||o==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:",o),!0):!1}function Kn(t){return"callTool"in t&&typeof t.callTool=="function"}function PR(t){var e,n,r;return(r=(n=(e=t.config)===null||e===void 0?void 0:e.tools)===null||n===void 0?void 0:n.some(i=>Kn(i)))!==null&&r!==void 0?r:!1}function Xm(t){var e;let n=[];return!((e=t?.config)===null||e===void 0)&&e.tools&&t.config.tools.forEach((r,i)=>{if(Kn(r))return;let o=r;o.functionDeclarations&&o.functionDeclarations.length>0&&n.push(i)}),n}function Km(t){var e;return!(!((e=t?.automaticFunctionCalling)===null||e===void 0)&&e.ignoreCallHistory)}var Yn=class t extends dt{constructor(e){super(),this.apiClient=e,this.embedContent=async n=>{if(!this.apiClient.isVertexAI())return n.model.includes("gemini-embedding-2")&&(n.contents=Le(n.contents)),await this.embedContentInternal(n);if(n.model.includes("gemini")&&n.model!=="gemini-embedding-001"||n.model.includes("maas")){let i=Le(n.contents);if(i.length>1)throw new Error("The embedContent API for this model only supports one content at a time.");let o=Object.assign(Object.assign({},n),{content:i[0],embeddingApiType:ro.EMBED_CONTENT});return await this.embedContentInternal(o)}else{let i=Object.assign(Object.assign({},n),{embeddingApiType:ro.PREDICT});return await this.embedContentInternal(i)}},this.generateContent=async n=>{var r,i,o,a,u;let c=await this.processParamsMaybeAddMcpUsage(n);if(this.maybeMoveToResponseJsonSchema(n),!PR(n)||Wm(n.config))return await this.generateContentInternal(c);let d=Xm(n);if(d.length>0){let g=d.map(E=>`tools[${E}]`).join(", ");throw new Error(`Automatic function calling with CallableTools (or MCP objects) and basic FunctionDeclarations is not yet supported. Incompatible tools found at ${g}.`)}let f,p,h=Le(c.contents),m=(o=(i=(r=c.config)===null||r===void 0?void 0:r.automaticFunctionCalling)===null||i===void 0?void 0:i.maximumRemoteCalls)!==null&&o!==void 0?o:Jm,_=0;for(;_<m&&(f=await this.generateContentInternal(c),!(!f.functionCalls||f.functionCalls.length===0));){let g=f.candidates[0].content,E=[];for(let y of(u=(a=n.config)===null||a===void 0?void 0:a.tools)!==null&&u!==void 0?u:[])if(Kn(y)){let A=await y.callTool(f.functionCalls);E.push(...A)}_++,p={role:"user",parts:E},c.contents=Le(c.contents),c.contents.push(g),c.contents.push(p),Km(c.config)&&(h.push(g),h.push(p))}return Km(c.config)&&(f.automaticFunctionCallingHistory=h),f},this.generateContentStream=async n=>{var r,i,o,a,u;if(this.maybeMoveToResponseJsonSchema(n),Wm(n.config)){let p=await this.processParamsMaybeAddMcpUsage(n);return await this.generateContentStreamInternal(p)}let c=Xm(n);if(c.length>0){let p=c.map(h=>`tools[${h}]`).join(", ");throw new Error(`Incompatible tools found at ${p}. Automatic function calling with CallableTools (or MCP objects) and basic FunctionDeclarations" is not yet supported.`)}let d=(o=(i=(r=n?.config)===null||r===void 0?void 0:r.toolConfig)===null||i===void 0?void 0:i.functionCallingConfig)===null||o===void 0?void 0:o.streamFunctionCallArguments,f=(u=(a=n?.config)===null||a===void 0?void 0:a.automaticFunctionCalling)===null||u===void 0?void 0:u.disable;if(d&&!f)throw new Error("Running in streaming mode with 'streamFunctionCallArguments' enabled, this feature is not compatible with automatic function calling (AFC). Please set 'config.automaticFunctionCalling.disable' to true to disable AFC or leave 'config.toolConfig.functionCallingConfig.streamFunctionCallArguments' to be undefined or set to false to disable streaming function call arguments feature.");return await this.processAfcStream(n)},this.generateImages=async n=>(t.loggedGenerateImagesWarning||(t.loggedGenerateImagesWarning=!0,console.warn("The generateImages method is deprecated and will be removed in the next major release (not before Jan. 1 2027). Please use the generateContent method with image models instead. See https://ai.google.dev/gemini-api/docs/deprecations#imagen-models and https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/capabilities/image-generation#generate-images")),await this.generateImagesInternal(n).then(r=>{var i;let o,a=[];if(r?.generatedImages)for(let c of r.generatedImages)c&&c?.safetyAttributes&&((i=c?.safetyAttributes)===null||i===void 0?void 0:i.contentType)==="Positive Prompt"?o=c?.safetyAttributes:a.push(c);let u;return o?u={generatedImages:a,positivePromptSafetyAttributes:o,sdkHttpResponse:r.sdkHttpResponse}:u={generatedImages:a,sdkHttpResponse:r.sdkHttpResponse},u})),this.list=async n=>{var r;let a={config:Object.assign(Object.assign({},{queryBase:!0}),n?.config)};if(this.apiClient.isVertexAI()&&!a.config.queryBase){if(!((r=a.config)===null||r===void 0)&&r.filter)throw new Error("Filtering tuned models list is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");a.config.filter="labels.tune-type:*"}return new Ut(Mt.PAGED_ITEM_MODELS,u=>this.listInternal(u),await this.listInternal(a),a)},this.editImage=async n=>{t.loggedEditImageWarning||(t.loggedEditImageWarning=!0,console.warn("The editImage method is deprecated and will be removed in the next major release (not before Jan. 1 2027). Please use the generateContent method with image models instead. See https://ai.google.dev/gemini-api/docs/deprecations#imagen-models and https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/capabilities/gemini-edit-images#edit-an-image"));let r={model:n.model,prompt:n.prompt,referenceImages:[],config:n.config};return n.referenceImages&&n.referenceImages&&(r.referenceImages=n.referenceImages.map(i=>i.toReferenceImageAPI())),await this.editImageInternal(r)},this.upscaleImage=async n=>{let r={numberOfImages:1,mode:"upscale"};n.config&&(r=Object.assign(Object.assign({},r),n.config));let i={model:n.model,image:n.image,upscaleFactor:n.upscaleFactor,config:r};return await this.upscaleImageInternal(i)},this.generateVideos=async n=>{var r,i,o,a,u,c;if((n.prompt||n.image||n.video)&&n.source)throw new Error("Source and prompt/image/video are mutually exclusive. Please only use source.");return(n.prompt||n.image||n.video)&&(t.loggedGenerateVideosWarning||(t.loggedGenerateVideosWarning=!0,console.warn("The generateVideos method with prompt/image/video arguments is deprecated and will be removed in a future major release (not before 2026-07-31). Please use the source argument instead."))),this.apiClient.isVertexAI()||(!((r=n.video)===null||r===void 0)&&r.uri&&(!((i=n.video)===null||i===void 0)&&i.videoBytes)?n.video={uri:n.video.uri,mimeType:n.video.mimeType}:!((a=(o=n.source)===null||o===void 0?void 0:o.video)===null||a===void 0)&&a.uri&&(!((c=(u=n.source)===null||u===void 0?void 0:u.video)===null||c===void 0)&&c.videoBytes)&&(n.source.video={uri:n.source.video.uri,mimeType:n.source.video.mimeType})),await this.generateVideosInternal(n)}}maybeMoveToResponseJsonSchema(e){e.config&&e.config.responseSchema&&(e.config.responseJsonSchema||Object.keys(e.config.responseSchema).includes("$schema")&&(e.config.responseJsonSchema=e.config.responseSchema,delete e.config.responseSchema))}async processParamsMaybeAddMcpUsage(e){var n,r,i;let o=(n=e.config)===null||n===void 0?void 0:n.tools;if(!o)return e;let a=await Promise.all(o.map(async c=>Kn(c)?await c.tool():c)),u={model:e.model,contents:e.contents,config:Object.assign(Object.assign({},e.config),{tools:a})};if(u.config.tools=a,e.config&&e.config.tools&&Wg(e.config.tools)){let c=(i=(r=e.config.httpOptions)===null||r===void 0?void 0:r.headers)!==null&&i!==void 0?i:{},d=Object.assign({},c);Object.keys(d).length===0&&(d=this.apiClient.getDefaultHeaders()),Xg(d),u.config.httpOptions=Object.assign(Object.assign({},e.config.httpOptions),{headers:d})}return u}async initAfcToolsMap(e){var n,r,i;let o=new Map;for(let a of(r=(n=e.config)===null||n===void 0?void 0:n.tools)!==null&&r!==void 0?r:[])if(Kn(a)){let u=a,c=await u.tool();for(let d of(i=c.functionDeclarations)!==null&&i!==void 0?i:[]){if(!d.name)throw new Error("Function declaration name is required.");if(o.has(d.name))throw new Error(`Duplicate tool declaration name: ${d.name}`);o.set(d.name,u)}}return o}async processAfcStream(e){var n,r,i;let o=(i=(r=(n=e.config)===null||n===void 0?void 0:n.automaticFunctionCalling)===null||r===void 0?void 0:r.maximumRemoteCalls)!==null&&i!==void 0?i:Jm,a=!1,u=0,c=await this.initAfcToolsMap(e);return(function(d,f,p){return Xn(this,arguments,function*(){for(var h,m,_,g,E,y;u<o;){a&&(u++,a=!1);let P=yield ye(d.processParamsMaybeAddMcpUsage(p)),G=yield ye(d.generateContentStreamInternal(P)),O=[],B=[];try{for(var C=!0,A=(m=void 0,Pr(G)),I;I=yield ye(A.next()),h=I.done,!h;C=!0){g=I.value,C=!1;let k=g;if(yield yield ye(k),k.candidates&&(!((E=k.candidates[0])===null||E===void 0)&&E.content)){B.push(k.candidates[0].content);for(let V of(y=k.candidates[0].content.parts)!==null&&y!==void 0?y:[])if(u<o&&V.functionCall){if(!V.functionCall.name)throw new Error("Function call name was not returned by the model.");if(f.has(V.functionCall.name)){let X=yield ye(f.get(V.functionCall.name).callTool([V.functionCall]));O.push(...X)}else throw new Error(`Automatic function calling was requested, but not all the tools the model used implement the CallableTool interface. Available tools: ${f.keys()}, missing tool: ${V.functionCall.name}`)}}}}catch(k){m={error:k}}finally{try{!C&&!h&&(_=A.return)&&(yield ye(_.call(A)))}finally{if(m)throw m.error}}if(O.length>0){a=!0;let k=new pn;k.candidates=[{content:{role:"user",parts:O}}],yield yield ye(k);let V=[];V.push(...B),V.push({role:"user",parts:O});let X=Le(p.contents).concat(V);p.contents=X}else break}})})(this,c,e)}async generateContentInternal(e){var n,r,i,o;let a,u="",c={};if(this.apiClient.isVertexAI()){let d=Hm(this.apiClient,e);return u=$("{model}:generateContent",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(f=>f.json().then(p=>{let h=p;return h.sdkHttpResponse={headers:f.headers},h})),a.then(f=>{let p=$m(f),h=new pn;return Object.assign(h,p),h})}else{let d=Bm(this.apiClient,e);return u=$("{model}:generateContent",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(f=>f.json().then(p=>{let h=p;return h.sdkHttpResponse={headers:f.headers},h})),a.then(f=>{let p=Vm(f),h=new pn;return Object.assign(h,p),h})}}async generateContentStreamInternal(e){var n,r,i,o;let a,u="",c={};if(this.apiClient.isVertexAI()){let d=Hm(this.apiClient,e);return u=$("{model}:streamGenerateContent?alt=sse",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.requestStream({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}),a.then(function(p){return Xn(this,arguments,function*(){var h,m,_,g;try{for(var E=!0,y=Pr(p),C;C=yield ye(y.next()),h=C.done,!h;E=!0){g=C.value,E=!1;let A=g,I=$m(yield ye(A.json()),e);I.sdkHttpResponse={headers:A.headers};let P=new pn;Object.assign(P,I),yield yield ye(P)}}catch(A){m={error:A}}finally{try{!E&&!h&&(_=y.return)&&(yield ye(_.call(y)))}finally{if(m)throw m.error}}})})}else{let d=Bm(this.apiClient,e);return u=$("{model}:streamGenerateContent?alt=sse",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.requestStream({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}),a.then(function(p){return Xn(this,arguments,function*(){var h,m,_,g;try{for(var E=!0,y=Pr(p),C;C=yield ye(y.next()),h=C.done,!h;E=!0){g=C.value,E=!1;let A=g,I=Vm(yield ye(A.json()),e);I.sdkHttpResponse={headers:A.headers};let P=new pn;Object.assign(P,I),yield yield ye(P)}}catch(A){m={error:A}}finally{try{!E&&!h&&(_=y.return)&&(yield ye(_.call(y)))}finally{if(m)throw m.error}}})})}}async embedContentInternal(e){var n,r,i,o;let a,u="",c={};if(this.apiClient.isVertexAI()){let d=hw(this.apiClient,e,e),f=E0(e.model)?"{model}:embedContent":"{model}:predict";return u=$(f,d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(p=>p.json().then(h=>{let m=h;return m.sdkHttpResponse={headers:p.headers},m})),a.then(p=>{let h=gw(p,e),m=new io;return Object.assign(m,h),m})}else{let d=pw(this.apiClient,e);return u=$("{model}:batchEmbedContents",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(f=>f.json().then(p=>{let h=p;return h.sdkHttpResponse={headers:f.headers},h})),a.then(f=>{let p=mw(f),h=new io;return Object.assign(h,p),h})}}async generateImagesInternal(e){var n,r,i,o;let a,u="",c={};if(this.apiClient.isVertexAI()){let d=Pw(this.apiClient,e);return u=$("{model}:predict",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(f=>f.json().then(p=>{let h=p;return h.sdkHttpResponse={headers:f.headers},h})),a.then(f=>{let p=Nw(f),h=new oo;return Object.assign(h,p),h})}else{let d=ww(this.apiClient,e);return u=$("{model}:predict",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(f=>f.json().then(p=>{let h=p;return h.sdkHttpResponse={headers:f.headers},h})),a.then(f=>{let p=Rw(f),h=new oo;return Object.assign(h,p),h})}}async editImageInternal(e){var n,r;let i,o="",a={};if(this.apiClient.isVertexAI()){let u=uw(this.apiClient,e);return o=$("{model}:predict",u._url),a=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:o,queryParams:a,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(c=>c.json().then(d=>{let f=d;return f.sdkHttpResponse={headers:c.headers},f})),i.then(c=>{let d=cw(c),f=new pl;return Object.assign(f,d),f})}else throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async upscaleImageInternal(e){var n,r;let i,o="",a={};if(this.apiClient.isVertexAI()){let u=MP(this.apiClient,e);return o=$("{model}:predict",u._url),a=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:o,queryParams:a,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(c=>c.json().then(d=>{let f=d;return f.sdkHttpResponse={headers:c.headers},f})),i.then(c=>{let d=UP(c),f=new hl;return Object.assign(f,d),f})}else throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async recontextImage(e){var n,r;let i,o="",a={};if(this.apiClient.isVertexAI()){let u=dP(this.apiClient,e);return o=$("{model}:predict",u._url),a=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:o,queryParams:a,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(c=>c.json()),i.then(c=>{let d=fP(c),f=new ml;return Object.assign(f,d),f})}else throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async segmentImage(e){var n,r;let i,o="",a={};if(this.apiClient.isVertexAI()){let u=EP(this.apiClient,e);return o=$("{model}:predict",u._url),a=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:o,queryParams:a,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(c=>c.json()),i.then(c=>{let d=vP(c),f=new gl;return Object.assign(f,d),f})}else throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async get(e){var n,r,i,o;let a,u="",c={};if(this.apiClient.isVertexAI()){let d=Ww(this.apiClient,e);return u=$("{name}",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(f=>f.json()),a.then(f=>Ol(f))}else{let d=Jw(this.apiClient,e);return u=$("{name}",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"GET",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(f=>f.json()),a.then(f=>Ll(f))}}async listInternal(e){var n,r,i,o;let a,u="",c={};if(this.apiClient.isVertexAI()){let d=tP(this.apiClient,e);return u=$("{models_url}",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(f=>f.json().then(p=>{let h=p;return h.sdkHttpResponse={headers:f.headers},h})),a.then(f=>{let p=rP(f),h=new so;return Object.assign(h,p),h})}else{let d=eP(this.apiClient,e);return u=$("{models_url}",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"GET",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(f=>f.json().then(p=>{let h=p;return h.sdkHttpResponse={headers:f.headers},h})),a.then(f=>{let p=nP(f),h=new so;return Object.assign(h,p),h})}}async update(e){var n,r,i,o;let a,u="",c={};if(this.apiClient.isVertexAI()){let d=kP(this.apiClient,e);return u=$("{model}",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"PATCH",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(f=>f.json()),a.then(f=>Ol(f))}else{let d=xP(this.apiClient,e);return u=$("{name}",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"PATCH",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(f=>f.json()),a.then(f=>Ll(f))}}async delete(e){var n,r,i,o;let a,u="",c={};if(this.apiClient.isVertexAI()){let d=ow(this.apiClient,e);return u=$("{name}",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"DELETE",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(f=>f.json().then(p=>{let h=p;return h.sdkHttpResponse={headers:f.headers},h})),a.then(f=>{let p=aw(f),h=new ao;return Object.assign(h,p),h})}else{let d=iw(this.apiClient,e);return u=$("{name}",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"DELETE",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(f=>f.json().then(p=>{let h=p;return h.sdkHttpResponse={headers:f.headers},h})),a.then(f=>{let p=sw(f),h=new ao;return Object.assign(h,p),h})}}async countTokens(e){var n,r,i,o;let a,u="",c={};if(this.apiClient.isVertexAI()){let d=tw(this.apiClient,e);return u=$("{model}:countTokens",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(f=>f.json().then(p=>{let h=p;return h.sdkHttpResponse={headers:f.headers},h})),a.then(f=>{let p=rw(f),h=new lo;return Object.assign(h,p),h})}else{let d=ew(this.apiClient,e);return u=$("{model}:countTokens",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(f=>f.json().then(p=>{let h=p;return h.sdkHttpResponse={headers:f.headers},h})),a.then(f=>{let p=nw(f),h=new lo;return Object.assign(h,p),h})}}async computeTokens(e){var n,r;let i,o="",a={};if(this.apiClient.isVertexAI()){let u=WI(this.apiClient,e);return o=$("{model}:computeTokens",u._url),a=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:o,queryParams:a,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(c=>c.json().then(d=>{let f=d;return f.sdkHttpResponse={headers:c.headers},f})),i.then(c=>{let d=XI(c),f=new _l;return Object.assign(f,d),f})}else throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async generateVideosInternal(e){var n,r,i,o;let a,u="",c={};if(this.apiClient.isVertexAI()){let d=bw(this.apiClient,e);return u=$("{model}:predictLongRunning",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(f=>f.json()),a.then(f=>{let p=Mw(f),h=new uo;return Object.assign(h,p),h})}else{let d=Uw(this.apiClient,e);return u=$("{model}:predictLongRunning",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(f=>f.json()),a.then(f=>{let p=Dw(f),h=new uo;return Object.assign(h,p),h})}}};Yn.loggedGenerateImagesWarning=!1;Yn.loggedEditImageWarning=!1;Yn.loggedGenerateVideosWarning=!1;var Jl=class extends dt{constructor(e){super(),this.apiClient=e}async getVideosOperation(e){let n=e.operation,r=e.config;if(n.name===void 0||n.name==="")throw new Error("Operation name is required.");if(this.apiClient.isVertexAI()){let i=n.name.split("/operations/")[0],o;r&&"httpOptions"in r&&(o=r.httpOptions);let a=await this.fetchPredictVideosOperationInternal({operationName:n.name,resourceName:i,config:{httpOptions:o}});return n._fromAPIResponse({apiResponse:a,_isVertexAI:!0})}else{let i=await this.getVideosOperationInternal({operationName:n.name,config:r});return n._fromAPIResponse({apiResponse:i,_isVertexAI:!1})}}async get(e){let n=e.operation,r=e.config;if(n.name===void 0||n.name==="")throw new Error("Operation name is required.");if(this.apiClient.isVertexAI()){let i=n.name.split("/operations/")[0],o;r&&"httpOptions"in r&&(o=r.httpOptions);let a=await this.fetchPredictVideosOperationInternal({operationName:n.name,resourceName:i,config:{httpOptions:o}});return n._fromAPIResponse({apiResponse:a,_isVertexAI:!0})}else{let i=await this.getVideosOperationInternal({operationName:n.name,config:r});return n._fromAPIResponse({apiResponse:i,_isVertexAI:!1})}}async getVideosOperationInternal(e){var n,r,i,o;let a,u="",c={};if(this.apiClient.isVertexAI()){let d=s0(e);return u=$("{operationName}",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(f=>f.json()),a}else{let d=o0(e);return u=$("{operationName}",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"GET",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(f=>f.json()),a}}async fetchPredictVideosOperationInternal(e){var n,r;let i,o="",a={};if(this.apiClient.isVertexAI()){let u=ZC(e);return o=$("{resourceName}:fetchPredictOperation",u._url),a=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:o,queryParams:a,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(c=>c.json()),i}else throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}};function RR(t){let e={},n=s(t,["apiKey"]);if(n!=null&&l(e,["apiKey"],n),s(t,["apiKeyConfig"])!==void 0)throw new Error("apiKeyConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["authType"])!==void 0)throw new Error("authType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["googleServiceAccountConfig"])!==void 0)throw new Error("googleServiceAccountConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["httpBasicAuthConfig"])!==void 0)throw new Error("httpBasicAuthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["oauthConfig"])!==void 0)throw new Error("oauthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["oidcConfig"])!==void 0)throw new Error("oidcConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return e}function NR(t){let e={},n=s(t,["data"]);if(n!=null&&l(e,["data"],n),s(t,["displayName"])!==void 0)throw new Error("displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let r=s(t,["mimeType"]);return r!=null&&l(e,["mimeType"],r),e}function xR(t){let e={},n=s(t,["parts"]);if(n!=null){let i=n;Array.isArray(i)&&(i=i.map(o=>qR(o))),l(e,["parts"],i)}let r=s(t,["role"]);return r!=null&&l(e,["role"],r),e}function kR(t,e,n){let r={},i=s(e,["expireTime"]);n!==void 0&&i!=null&&l(n,["expireTime"],i);let o=s(e,["newSessionExpireTime"]);n!==void 0&&o!=null&&l(n,["newSessionExpireTime"],o);let a=s(e,["uses"]);n!==void 0&&a!=null&&l(n,["uses"],a);let u=s(e,["liveConnectConstraints"]);n!==void 0&&u!=null&&l(n,["bidiGenerateContentSetup"],OR(t,u));let c=s(e,["lockAdditionalFields"]);return n!==void 0&&c!=null&&l(n,["fieldMask"],c),r}function DR(t,e){let n={},r=s(e,["config"]);return r!=null&&l(n,["config"],kR(t,r,n)),n}function MR(t){let e={};if(s(t,["displayName"])!==void 0)throw new Error("displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let n=s(t,["fileUri"]);n!=null&&l(e,["fileUri"],n);let r=s(t,["mimeType"]);return r!=null&&l(e,["mimeType"],r),e}function UR(t){let e={},n=s(t,["args"]);n!=null&&l(e,["args"],n);let r=s(t,["id"]);r!=null&&l(e,["id"],r);let i=s(t,["name"]);if(i!=null&&l(e,["name"],i),s(t,["partialArgs"])!==void 0)throw new Error("partialArgs parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["willContinue"])!==void 0)throw new Error("willContinue parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return e}function bR(t){let e={},n=s(t,["authConfig"]);n!=null&&l(e,["authConfig"],RR(n));let r=s(t,["enableWidget"]);if(r!=null&&l(e,["enableWidget"],r),s(t,["groundingTypes"])!==void 0)throw new Error("groundingTypes parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return e}function GR(t){let e={};if(s(t,["blockingConfidence"])!==void 0)throw new Error("blockingConfidence parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["excludeDomains"])!==void 0)throw new Error("excludeDomains parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let n=s(t,["searchTypes"]);n!=null&&l(e,["searchTypes"],n);let r=s(t,["timeRangeFilter"]);return r!=null&&l(e,["timeRangeFilter"],r),e}function LR(t,e){let n={},r=s(t,["generationConfig"]);e!==void 0&&r!=null&&l(e,["setup","generationConfig"],r);let i=s(t,["responseModalities"]);e!==void 0&&i!=null&&l(e,["setup","generationConfig","responseModalities"],i);let o=s(t,["temperature"]);e!==void 0&&o!=null&&l(e,["setup","generationConfig","temperature"],o);let a=s(t,["topP"]);e!==void 0&&a!=null&&l(e,["setup","generationConfig","topP"],a);let u=s(t,["topK"]);e!==void 0&&u!=null&&l(e,["setup","generationConfig","topK"],u);let c=s(t,["maxOutputTokens"]);e!==void 0&&c!=null&&l(e,["setup","generationConfig","maxOutputTokens"],c);let d=s(t,["mediaResolution"]);e!==void 0&&d!=null&&l(e,["setup","generationConfig","mediaResolution"],d);let f=s(t,["seed"]);e!==void 0&&f!=null&&l(e,["setup","generationConfig","seed"],f);let p=s(t,["speechConfig"]);e!==void 0&&p!=null&&l(e,["setup","generationConfig","speechConfig"],Vu(p));let h=s(t,["thinkingConfig"]);e!==void 0&&h!=null&&l(e,["setup","generationConfig","thinkingConfig"],h);let m=s(t,["enableAffectiveDialog"]);e!==void 0&&m!=null&&l(e,["setup","generationConfig","enableAffectiveDialog"],m);let _=s(t,["systemInstruction"]);e!==void 0&&_!=null&&l(e,["setup","systemInstruction"],xR(xe(_)));let g=s(t,["tools"]);if(e!==void 0&&g!=null){let k=Zn(g);Array.isArray(k)&&(k=k.map(V=>HR(Qn(V)))),l(e,["setup","tools"],k)}let E=s(t,["sessionResumption"]);e!==void 0&&E!=null&&l(e,["setup","sessionResumption"],BR(E));let y=s(t,["inputAudioTranscription"]);e!==void 0&&y!=null&&l(e,["setup","inputAudioTranscription"],y);let C=s(t,["outputAudioTranscription"]);e!==void 0&&C!=null&&l(e,["setup","outputAudioTranscription"],C);let A=s(t,["realtimeInputConfig"]);e!==void 0&&A!=null&&l(e,["setup","realtimeInputConfig"],A);let I=s(t,["contextWindowCompression"]);e!==void 0&&I!=null&&l(e,["setup","contextWindowCompression"],I);let P=s(t,["proactivity"]);if(e!==void 0&&P!=null&&l(e,["setup","proactivity"],P),s(t,["explicitVadSignal"])!==void 0)throw new Error("explicitVadSignal parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let G=s(t,["avatarConfig"]);e!==void 0&&G!=null&&l(e,["setup","avatarConfig"],G);let O=s(t,["safetySettings"]);if(e!==void 0&&O!=null){let k=O;Array.isArray(k)&&(k=k.map(V=>FR(V))),l(e,["setup","safetySettings"],k)}let B=s(t,["translationConfig"]);return e!==void 0&&B!=null&&l(e,["setup","generationConfig","translationConfig"],B),n}function OR(t,e){let n={},r=s(e,["model"]);r!=null&&l(n,["setup","model"],ie(t,r));let i=s(e,["config"]);return i!=null&&l(n,["config"],LR(i,n)),n}function qR(t){let e={},n=s(t,["mediaResolution"]);n!=null&&l(e,["mediaResolution"],n);let r=s(t,["toolCall"]);r!=null&&l(e,["toolCall"],r);let i=s(t,["toolResponse"]);i!=null&&l(e,["toolResponse"],i);let o=s(t,["audioTranscription"]);o!=null&&l(e,["audioTranscription"],o);let a=s(t,["codeExecutionResult"]);a!=null&&l(e,["codeExecutionResult"],a);let u=s(t,["executableCode"]);u!=null&&l(e,["executableCode"],u);let c=s(t,["fileData"]);c!=null&&l(e,["fileData"],MR(c));let d=s(t,["functionCall"]);d!=null&&l(e,["functionCall"],UR(d));let f=s(t,["functionResponse"]);f!=null&&l(e,["functionResponse"],f);let p=s(t,["inlineData"]);p!=null&&l(e,["inlineData"],NR(p));let h=s(t,["text"]);h!=null&&l(e,["text"],h);let m=s(t,["thought"]);m!=null&&l(e,["thought"],m);let _=s(t,["thoughtSignature"]);_!=null&&l(e,["thoughtSignature"],_);let g=s(t,["videoMetadata"]);g!=null&&l(e,["videoMetadata"],g);let E=s(t,["partMetadata"]);return E!=null&&l(e,["partMetadata"],E),e}function FR(t){let e={},n=s(t,["category"]);if(n!=null&&l(e,["category"],n),s(t,["method"])!==void 0)throw new Error("method parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let r=s(t,["threshold"]);return r!=null&&l(e,["threshold"],r),e}function BR(t){let e={},n=s(t,["handle"]);if(n!=null&&l(e,["handle"],n),s(t,["transparent"])!==void 0)throw new Error("transparent parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return e}function HR(t){let e={};if(s(t,["retrieval"])!==void 0)throw new Error("retrieval parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let n=s(t,["googleMaps"]);n!=null&&l(e,["googleMaps"],bR(n));let r=s(t,["mcpServers"]);if(r!=null){let p=r;Array.isArray(p)&&(p=p.map(h=>h)),l(e,["mcpServers"],p)}let i=s(t,["codeExecution"]);i!=null&&l(e,["codeExecution"],i);let o=s(t,["computerUse"]);if(o!=null&&l(e,["computerUse"],o),s(t,["enterpriseWebSearch"])!==void 0)throw new Error("enterpriseWebSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["exaAiSearch"])!==void 0)throw new Error("exaAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let a=s(t,["functionDeclarations"]);if(a!=null){let p=a;Array.isArray(p)&&(p=p.map(h=>h)),l(e,["functionDeclarations"],p)}let u=s(t,["googleSearch"]);u!=null&&l(e,["googleSearch"],GR(u));let c=s(t,["googleSearchRetrieval"]);if(c!=null&&l(e,["googleSearchRetrieval"],c),s(t,["parallelAiSearch"])!==void 0)throw new Error("parallelAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let d=s(t,["urlContext"]);d!=null&&l(e,["urlContext"],d);let f=s(t,["fileSearch"]);return f!=null&&l(e,["fileSearch"],f),e}function VR(t){let e=[];for(let n in t)if(Object.prototype.hasOwnProperty.call(t,n)){let r=t[n];if(typeof r=="object"&&r!=null&&Object.keys(r).length>0){let i=Object.keys(r).map(o=>`${n}.${o}`);e.push(...i)}else e.push(n)}return e.join(",")}function $R(t,e){let n=null,r=t.bidiGenerateContentSetup;if(typeof r=="object"&&r!==null&&"setup"in r){let o=r.setup;typeof o=="object"&&o!==null?(t.bidiGenerateContentSetup=o,n=o):delete t.bidiGenerateContentSetup}else r!==void 0&&delete t.bidiGenerateContentSetup;let i=t.fieldMask;if(n){let o=VR(n);if(Array.isArray(e?.lockAdditionalFields)&&e?.lockAdditionalFields.length===0)o?t.fieldMask=o:delete t.fieldMask;else if(e?.lockAdditionalFields&&e.lockAdditionalFields.length>0&&i!==null&&Array.isArray(i)&&i.length>0){let a=["temperature","topK","topP","maxOutputTokens","responseModalities","seed","speechConfig"],u=[];i.length>0&&(u=i.map(d=>a.includes(d)?`generationConfig.${d}`:d));let c=[];o&&c.push(o),u.length>0&&c.push(...u),c.length>0?t.fieldMask=c.join(","):delete t.fieldMask}else delete t.fieldMask}else i!==null&&Array.isArray(i)&&i.length>0?t.fieldMask=i.join(","):delete t.fieldMask;return t}var Wl=class extends dt{constructor(e){super(),this.apiClient=e}async create(e){var n,r;let i,o="",a={};if(this.apiClient.isVertexAI())throw new Error("The client.tokens.create method is only supported by the Gemini Developer API.");{let u=DR(this.apiClient,e);o=$("auth_tokens",u._url),a=u._query,delete u.config,delete u._url,delete u._query;let c=$R(u,e.config);return i=this.apiClient.request({path:o,queryParams:a,body:JSON.stringify(c),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(d=>d.json()),i.then(d=>d)}}};function JR(t,e){let n={},r=s(t,["force"]);return e!==void 0&&r!=null&&l(e,["_query","force"],r),n}function WR(t){let e={},n=s(t,["name"]);n!=null&&l(e,["_url","name"],n);let r=s(t,["config"]);return r!=null&&JR(r,e),e}function XR(t){let e={},n=s(t,["name"]);return n!=null&&l(e,["_url","name"],n),e}function KR(t,e){let n={},r=s(t,["pageSize"]);e!==void 0&&r!=null&&l(e,["_query","pageSize"],r);let i=s(t,["pageToken"]);return e!==void 0&&i!=null&&l(e,["_query","pageToken"],i),n}function YR(t){let e={},n=s(t,["parent"]);n!=null&&l(e,["_url","parent"],n);let r=s(t,["config"]);return r!=null&&KR(r,e),e}function zR(t){let e={},n=s(t,["sdkHttpResponse"]);n!=null&&l(e,["sdkHttpResponse"],n);let r=s(t,["nextPageToken"]);r!=null&&l(e,["nextPageToken"],r);let i=s(t,["documents"]);if(i!=null){let o=i;Array.isArray(o)&&(o=o.map(a=>a)),l(e,["documents"],o)}return e}var Xl=class extends dt{constructor(e){super(),this.apiClient=e,this.list=async n=>new Ut(Mt.PAGED_ITEM_DOCUMENTS,r=>this.listInternal({parent:n.parent,config:r.config}),await this.listInternal(n),n)}async get(e){var n,r;let i,o="",a={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let u=XR(e);return o=$("{name}",u._url),a=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:o,queryParams:a,body:JSON.stringify(u),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(c=>c.json()),i.then(c=>c)}}async delete(e){var n,r;let i="",o={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let a=WR(e);i=$("{name}",a._url),o=a._query,delete a._url,delete a._query,await this.apiClient.request({path:i,queryParams:o,body:JSON.stringify(a),httpMethod:"DELETE",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal})}}async listInternal(e){var n,r;let i,o="",a={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let u=YR(e);return o=$("{parent}/documents",u._url),a=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:o,queryParams:a,body:JSON.stringify(u),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(c=>c.json()),i.then(c=>{let d=zR(c),f=new vl;return Object.assign(f,d),f})}}};var Kl=class extends dt{constructor(e,n=new Xl(e)){super(),this.apiClient=e,this.documents=n,this.list=async(r={})=>new Ut(Mt.PAGED_ITEM_FILE_SEARCH_STORES,i=>this.listInternal(i),await this.listInternal(r),r)}async uploadToFileSearchStore(e){if(this.apiClient.isVertexAI())throw new Error("Gemini Enterprise Agent Platform (previously known as Vertex AI) does not support uploading files to a file search store.");return this.apiClient.uploadFileToFileSearchStore(e.fileSearchStoreName,e.file,e.config)}async downloadMedia(e,n){if(this.apiClient.isVertexAI())throw new Error("This method is only supported in the Gemini Developer client.");let r=new URL(e,"http://dummy.com"),i=r.pathname;if(i.startsWith("/")&&(i=i.slice(1)),!i.includes("/media/"))throw new Error(`Invalid uri format: ${e}. Expected to contain /media/`);let o={};r.searchParams.forEach((c,d)=>{o[d]=c}),o.alt="media";let a=Object.assign({},n?.httpOptions),u=await this.apiClient.request({path:i,httpMethod:"GET",queryParams:o,httpOptions:a});if(u instanceof Kt){let c=await u.responseInternal.arrayBuffer();return new Uint8Array(c)}else throw new Error("Unexpected response type from downloadMedia")}async create(e){var n,r;let i,o="",a={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let u=BP(this.apiClient,e);return o=$("fileSearchStores",u._url),a=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:o,queryParams:a,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(c=>c.json()),i.then(c=>c)}}async get(e){var n,r;let i,o="",a={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let u=$P(e);return o=$("{name}",u._url),a=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:o,queryParams:a,body:JSON.stringify(u),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(c=>c.json()),i.then(c=>c)}}async delete(e){var n,r;let i="",o={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let a=VP(e);i=$("{name}",a._url),o=a._query,delete a._url,delete a._query,await this.apiClient.request({path:i,queryParams:o,body:JSON.stringify(a),httpMethod:"DELETE",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal})}}async listInternal(e){var n,r;let i,o="",a={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let u=zP(e);return o=$("fileSearchStores",u._url),a=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:o,queryParams:a,body:JSON.stringify(u),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(c=>c.json()),i.then(c=>{let d=QP(c),f=new Tl;return Object.assign(f,d),f})}}async uploadToFileSearchStoreInternal(e){var n,r;let i,o="",a={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let u=ZP(e);return o=$("upload/v1beta/{file_search_store_name}:uploadToFileSearchStore",u._url),a=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:o,queryParams:a,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(c=>c.json()),i.then(c=>{let d=jP(c),f=new Al;return Object.assign(f,d),f})}}async importFile(e){var n,r;let i,o="",a={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let u=XP(e);return o=$("{file_search_store_name}:importFile",u._url),a=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:o,queryParams:a,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(c=>c.json()),i.then(c=>{let d=WP(c),f=new Cl;return Object.assign(f,d),f})}}};function QR(){return"Deno"in globalThis}var zi;function Nr(){var t,e,n,r,i,o;if(zi)return zi;let a=globalThis,u={};return QR()?u=(r=(n=(e=(t=a.Deno)===null||t===void 0?void 0:t.env)===null||e===void 0?void 0:e.toObject)===null||n===void 0?void 0:n.call(e))!==null&&r!==void 0?r:{}:u=(o=(i=a.process)===null||i===void 0?void 0:i.env)!==null&&o!==void 0?o:{},zi=u,zi}function ZR(t){var e,n;let r=Object.assign({},t),i=Nr();return typeof i.GOOGLE_GENAI_API_VERSION<"u"&&((e=r.api_version)!==null&&e!==void 0||(r.api_version=i.GOOGLE_GENAI_API_VERSION)),typeof i.GOOGLE_GENAI_USER_PROJECT<"u"&&((n=r.user_project)!==null&&n!==void 0||(r.user_project=i.GOOGLE_GENAI_USER_PROJECT)),r}var Yl=class{constructor(e){this.options=e}getDefaultHeaders(){return this.options.defaultHeaders}async resolveGoogleGenAISecurity(e){return nN(await this.options.getAuthHeaders(e))}},zl=class{beforeCreateRequest(e,n){return Object.assign(Object.assign({},n),{url:jR(n.url)})}async beforeRequest(e,n){if(zm(n.headers,tN(e.security_source)),rN(e,n.headers),oN(n.headers))return n;let r=await eN(e.security_source,n.url);return zm(n.headers,r?.default_headers),iN(n.headers,r),n}};function jR(t){let[,e,...n]=t.pathname.split("/");if(!e)return t;let r=decodeURIComponent(e);if(!r.includes("/"))return t;let i=new URL(t);return i.pathname=`/${r}/${n.join("/")}`,i}async function eN(t,e){if(Yg(t))return t.resolveGoogleGenAISecurity(e);let n=typeof t=="function"?await t():t;return Kg(n)?Ym(n):Ym(void 0)}function tN(t){var e,n;if(Yg(t))return(n=(e=t.getDefaultHeaders)===null||e===void 0?void 0:e.call(t))!==null&&n!==void 0?n:t.defaultHeaders;if(Kg(t))return t.default_headers}function Ym(t){var e,n;let r=Nr(),i=Object.assign(Object.assign({},t),{api_key:(e=t?.api_key)!==null&&e!==void 0?e:r.GOOGLE_GENAI_API_KEY,access_token:(n=t?.access_token)!==null&&n!==void 0?n:r.GOOGLE_GENAI_ACCESS_TOKEN});return zg(i)?i:void 0}function nN(t){var e,n;let r={};for(let[o,a]of t){let u=o.toLowerCase();u!=="authorization"&&u!=="x-goog-api-key"&&(r[o]=a)}let i={access_token:(e=t.get("authorization"))!==null&&e!==void 0?e:void 0,api_key:(n=t.get("x-goog-api-key"))!==null&&n!==void 0?n:void 0,default_headers:Object.keys(r).length?r:void 0};return zg(i)?i:void 0}function zm(t,e){if(e)for(let[n,r]of new Headers(e))t.get(n)===null&&t.set(n,r)}function rN(t,e){t.options.user_project!==void 0&&e.get("x-goog-user-project")===null&&e.set("x-goog-user-project",t.options.user_project)}function iN(t,e){if(e){if(e.api_key){t.set("x-goog-api-key",e.api_key);return}e.access_token&&t.set("Authorization",sN(e.access_token))}}function oN(t){return t.get("authorization")!==null||t.get("x-goog-api-key")!==null}function sN(t){return t.slice(0,7).toLowerCase()==="bearer "?t:`Bearer ${t}`}function Kg(t){return typeof t=="object"&&t!==null}function Yg(t){return typeof t=="object"&&t!==null&&"resolveGoogleGenAISecurity"in t&&typeof t.resolveGoogleGenAISecurity=="function"}function zg(t){return t.api_key!==void 0||t.access_token!==void 0||t.default_headers!==void 0}var Yt=class extends Error{constructor(e,n){let r=e;n?.cause&&(r+=`: ${n.cause}`),super(r,n),this.name="HTTPClientError",typeof this.cause>"u"&&(this.cause=n?.cause)}},yo=class extends Yt{constructor(){super(...arguments),this.name="UnexpectedClientError"}},$n=class extends Yt{constructor(){super(...arguments),this.name="InvalidRequestError"}},Eo=class extends Yt{constructor(){super(...arguments),this.name="RequestAbortedError"}},vo=class extends Yt{constructor(){super(...arguments),this.name="RequestTimeoutError"}},To=class extends Yt{constructor(){super(...arguments),this.name="ConnectionError"}};var rt=class extends Error{constructor(e,n){var r,i,o,a;super(e),this.statusCode=(r=n?.response)===null||r===void 0?void 0:r.status,this.body=(i=n?.body)!==null&&i!==void 0?i:"",this.headers=(o=n?.response)===null||o===void 0?void 0:o.headers,this.contentType=((a=n?.response)===null||a===void 0?void 0:a.headers.get("content-type"))||"",this.rawResponse=n?.response,this.name="GoogleGenAiError"}};var Ql=class extends Error{},Oe=class t extends Ql{constructor(e,n,r,i){super(t.makeMessage(e,n,r)),this.status=e,this.headers=i,this.error=n,this.statusCode=e,this.body=Zm(n),this.contentType=i?.get("content-type")||"",this.rawResponse=void 0,this.cause=void 0,this.name=this.constructor.name,Object.setPrototypeOf(this,new.target.prototype)}static makeMessage(e,n,r){var i;let o=n&&cN(n)&&typeof n.message=="string"?n.message:void 0,a=Zm(n),u=(i=o??r)!==null&&i!==void 0?i:a||"An error occurred";return`${e?`${e} `:""}${u}`}static generate(e,n,r,i){return!e||!i?new zn({message:r,cause:n instanceof Error?n:void 0}):e===400?new eu(e,n,r,i):e===401?new tu(e,n,r,i):e===403?new nu(e,n,r,i):e===404?new ru(e,n,r,i):e===409?new iu(e,n,r,i):e===422?new ou(e,n,r,i):e===429?new su(e,n,r,i):e>=500?new au(e,n,r,i):new t(e,n,r,i)}},Zl=class extends Oe{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},zn=class extends Oe{constructor({message:e,cause:n}){super(void 0,void 0,e||"Connection error.",void 0),this.cause=n}},jl=class extends zn{constructor({message:e}={}){super({message:e||"Request timed out. This is a client-side timeout. You can increase the timeout by setting the `timeout` argument in your request or client http options."})}},eu=class extends Oe{},tu=class extends Oe{},nu=class extends Oe{},ru=class extends Oe{},iu=class extends Oe{},ou=class extends Oe{},su=class extends Oe{},au=class extends Oe{};function Jn(t){return dN(t)?t:t instanceof rt?aN(t):t instanceof Yt?lN(t):t}function aN(t){let e=uN(t),n=Oe.generate(t.statusCode,e,t.message,t.headers);return Ir(n,"body",t.body),Ir(n,"contentType",t.contentType),Ir(n,"rawResponse",t.rawResponse),Ir(n,"statusCode",t.statusCode),Ir(n,"cause",t),n}function lN(t){return t instanceof vo?new jl({message:t.message}):t instanceof Eo?new Zl({message:t.message}):t instanceof To?new zn({message:t.message,cause:t}):new zn({message:t.message,cause:t})}function uN(t){let e=Qm(t,"data$");if(e&&typeof e=="object")return e;try{let r=JSON.parse(t.body);if(r&&typeof r=="object")return r}catch{}let n=Qm(t,"error");return n&&typeof n=="object"?n:void 0}function Qm(t,e){return t&&typeof t=="object"?t[e]:void 0}function Zm(t){if(!t)return"";try{return JSON.stringify(t)}catch{return String(t)}}function cN(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function dN(t){return typeof t=="object"&&t!==null?Oe.prototype.isPrototypeOf(t):!1}function Ir(t,e,n){Object.defineProperty(t,e,{configurable:!0,enumerable:!0,value:n,writable:!1})}function fN(t){let e=new zl;t.registerBeforeCreateRequestHook(e),t.registerBeforeRequestHook(e)}var Ao=class{constructor(){this.sdkInitHooks=[],this.beforeCreateRequestHooks=[],this.beforeRequestHooks=[],this.afterSuccessHooks=[],this.afterErrorHooks=[];let e=[];for(let n of e)"sdkInit"in n&&this.registerSDKInitHook(n),"beforeCreateRequest"in n&&this.registerBeforeCreateRequestHook(n),"beforeRequest"in n&&this.registerBeforeRequestHook(n),"afterSuccess"in n&&this.registerAfterSuccessHook(n),"afterError"in n&&this.registerAfterErrorHook(n);fN(this)}registerSDKInitHook(e){this.sdkInitHooks.push(e)}registerBeforeCreateRequestHook(e){this.beforeCreateRequestHooks.push(e)}registerBeforeRequestHook(e){this.beforeRequestHooks.push(e)}registerAfterSuccessHook(e){this.afterSuccessHooks.push(e)}registerAfterErrorHook(e){this.afterErrorHooks.push(e)}sdkInit(e){return this.sdkInitHooks.reduce((n,r)=>r.sdkInit(n),e)}beforeCreateRequest(e,n){let r=n;for(let i of this.beforeCreateRequestHooks)r=i.beforeCreateRequest(e,r);return r}async beforeRequest(e,n){let r=n;for(let i of this.beforeRequestHooks)r=await i.beforeRequest(e,r);return r}async afterSuccess(e,n){let r=n;for(let i of this.afterSuccessHooks)r=await i.afterSuccess(e,r);return r}async afterError(e,n,r){let i=n,o=r;for(let a of this.afterErrorHooks){let u=await a.afterError(e,i,o);i=u.response,o=u.error}return{response:i,error:o}}};function jm(t){return{ok:!0,value:t}}function Dt(t){return{ok:!1,error:t}}function Ju(t){return btoa(String.fromCodePoint(...t))}function pN(t){return new TextEncoder().encode(t)}function hN(t){return Ju(pN(t))}var mN=Object.prototype.hasOwnProperty;function de(t,e){let n=/\{([a-zA-Z0-9_][a-zA-Z0-9_-]*?)\}/g;return function(i={}){return t.replace(n,function(o,a){if(!mN.call(i,a))throw new Error(`Parameter '${a}' is required`);let u=i[a];if(typeof u!="string"&&typeof u!="number")throw new Error(`Parameter '${a}' must be a string or number`);return`${u}`}).replace(/^\/+/,"")}}var eg=["https://generativelanguage.googleapis.com"];function gN(t){var e;let n=t.server_url,r={};if(!n){let o=(e=t.server_idx)!==null&&e!==void 0?e:0;if(o<0||o>=eg.length)throw new Error(`Invalid server index ${o}`);n=eg[o]||""}let i=de(n)(r);return new URL(i)}var _N={userAgent:"speakeasy-sdk/typescript 2.4.1-preview.4 2.924.0 v1beta @google/genai"};function yN(...t){let e=[];for(let n of t)n&&e.push(n);switch(e.length){case 0:case 1:return e[0]||null;default:return"any"in AbortSignal&&typeof AbortSignal.any=="function"?AbortSignal.any(e):EN(e)}}function EN(t){let e=new AbortController,n=e.signal;if(!t.length)return e.signal;if(t.length===1)return t[0]||e.signal;for(let a of t)if(a.aborted)return a;function r(){e.abort(this.reason),o()}let i=[];function o(){for(let a of i){let u=a.deref();u&&u.removeEventListener("abort",r)}}for(let a of t)i.push(new WeakRef(a)),a.addEventListener("abort",r);return n}function pe(t){let e={};for(let[n,r]of Object.entries(t))typeof r<"u"&&(e[n]=r);return e}function zt(t){if(t===null||typeof t!="object"||Object.prototype.toString.call(t)!=="[object Object]")return!1;let e=Object.getPrototypeOf(t);if(e===null||e===Object.prototype)return!0;try{return Object.getPrototypeOf(e)===null}catch{return!1}}function vN(t){return(e,n,r)=>{let i="",o=r?.explode?Zg(e,n):[[e,n]];if(o.every(([d,f])=>f==null))return;let a=d=>r?.charEncoding==="percent"?encodeURIComponent(d):d,u=d=>a(jg(d)),c=a(t);return o.forEach(([d,f])=>{var p,h;let m="",_=null;f!=null&&(Array.isArray(f)?_=(p=t_(f,g=>`${u(g)}`))===null||p===void 0?void 0:p.join(c):zt(f)?_=(h=n_(Object.entries(f),([g,E])=>`${a(g)}${c}${u(E)}`))===null||h===void 0?void 0:h.join(c):_=`${u(f)}`,_!=null&&(m=`${a(d)}=${_}`,!(!m||m==="=")&&(i+=`&${m}`)))}),i.slice(1)}}var Qg=vN(",");function Gt(t,e,n){if(typeof e>"u")return;let r=o=>n?.charEncoding==="percent"?encodeURIComponent(o):o,i=r(JSON.stringify(e,e_));return n?.explode?i:`${r(t)}=${i}`}var te=(t,e,n)=>{let r="",i=n?.explode?Zg(t,e):[[t,e]];if(i.every(([u,c])=>c==null))return;let o=u=>n?.charEncoding==="percent"?encodeURIComponent(u):u,a=u=>o(jg(u));return i.forEach(([u,c])=>{var d;let f="";if(c!=null){if(Array.isArray(c))f=(d=t_(c,p=>`${a(p)}`))===null||d===void 0?void 0:d.join(",");else if(zt(c)){let p=n_(Object.entries(c),([h,m])=>`,${o(h)},${a(m)}`);f=p?.join("").slice(1)}else f=`${n?.explode&&zt(e)?`${u}=`:""}${a(c)}`;r+=f?`,${f}`:""}}),r.slice(1)};function Zg(t,e){return Array.isArray(e)?e.map(n=>[t,n]):zt(e)?Object.entries(e??{}).map(([r,i])=>[r,i]):[[t,e]]}function jg(t){return t==null?"":t instanceof Date?t.toISOString():t instanceof Uint8Array?Ju(t):typeof t=="object"?JSON.stringify(t,e_):`${t}`}function e_(t,e){return e instanceof Uint8Array?Ju(e):e}function t_(t,e){let n=t.reduce((r,i)=>{if(i==null)return r;let o=e(i);return o==null||r.push(o),r},[]);return n.length?n:null}function n_(t,e){let n=[];for(let[r,i]of t){if(i==null)continue;let o=e([r,i]);o!=null&&n.push(o)}return n.length?n:null}function TN(...t){return t.filter(Boolean).join("&")}function AN(t){return function(n,r){var i,o,a;let u=Object.assign(Object.assign({},r),{explode:(i=r?.explode)!==null&&i!==void 0?i:!0,charEncoding:(o=r?.charEncoding)!==null&&o!==void 0?o:"percent"}),c=new Set((a=r?.allowEmptyValue)!==null&&a!==void 0?a:[]),d=Object.entries(n).map(([f,p])=>c.has(f)&&(p==null||p===""||Array.isArray(p)&&p.length===0)?`${encodeURIComponent(f)}=`:t(f,p,u));return TN(...d)}}var hn=AN(Qg);var CN=(t,e)=>e==null?fetch(t):fetch(t,e),lu=class t{constructor(e={}){this.requestHooks=[],this.requestErrorHooks=[],this.responseHooks=[],this.options=e,this.fetcher=e.fetcher||CN}async request(e){let n=e;for(let r of this.requestHooks){let i=await r(n);i&&(n=i)}try{let r=await this.fetcher(n);for(let i of this.responseHooks)await i(r,n);return r}catch(r){for(let i of this.requestErrorHooks)await i(r,n);throw r}}addHook(...e){if(e[0]==="beforeRequest")this.requestHooks.push(e[1]);else if(e[0]==="requestError")this.requestErrorHooks.push(e[1]);else if(e[0]==="response")this.responseHooks.push(e[1]);else throw new Error(`Invalid hook type: ${e[0]}`);return this}removeHook(...e){let n;if(e[0]==="beforeRequest")n=this.requestHooks;else if(e[0]==="requestError")n=this.requestErrorHooks;else if(e[0]==="response")n=this.responseHooks;else throw new Error(`Invalid hook type: ${e[0]}`);let r=n.findIndex(i=>i===e[1]);return r>=0&&n.splice(r,1),this}clone(){let e=new t(this.options);return e.requestHooks=this.requestHooks.slice(),e.requestErrorHooks=this.requestErrorHooks.slice(),e.responseHooks=this.responseHooks.slice(),e}},tg=/\s*;\s*/g;function Hn(t,e){var n;if(e==="*")return!0;let r=((n=t.headers.get("content-type"))===null||n===void 0?void 0:n.trim())||"application/octet-stream";r=r.toLowerCase();let i=e.toLowerCase().trim().split(tg),[o="",...a]=i;if(o.split("/").length!==2)return!1;let u=r.split(tg),[c="",...d]=u,[f="",p=""]=c.split("/");if(!f||!p||o!=="*/*"&&c!==o&&`${f}/*`!==o&&`*/${p}`!==o||d.length<a.length)return!1;let h=new Set(d);for(let m of a)if(!h.has(m))return!1;return!0}var SN=new RegExp("^[0-9]xx$","i");function ce(t,e){let n=`${t.status}`,r=Array.isArray(e)?e:[e];return r.length?r.some(i=>{let o=`${i}`;if(o==="default")return!0;if(!SN.test(`${o}`))return o===n;let a=o.charAt(0);if(!a)throw new Error("Invalid status code range");let u=n.charAt(0);if(!u)throw new Error(`Invalid response status code: ${n}`);return u===a}):!1}function IN(t,e,n){return ce(t,e)&&Hn(t,n)}function r_(t){if(typeof t!="object"||t==null)return!1;let e=t instanceof TypeError&&t.message.toLowerCase().startsWith("failed to fetch"),n=t instanceof TypeError&&t.message.toLowerCase().startsWith("fetch failed"),r="name"in t&&t.name==="ConnectionError",i="code"in t&&typeof t.code=="string"&&t.code.toLowerCase()==="econnreset";return e||n||i||r}function i_(t){if(typeof t!="object"||t==null)return!1;let e="name"in t&&t.name==="TimeoutError",n="code"in t&&t.code===23,r="code"in t&&typeof t.code=="string"&&t.code.toLowerCase()==="econnaborted";return e||n||r}function wN(t){if(typeof t!="object"||t==null)return!1;let e="name"in t&&t.name==="AbortError",n="code"in t&&t.code===20,r="code"in t&&typeof t.code=="string"&&t.code.toLowerCase()==="econnaborted";return e||n||r}var ng={initialInterval:500,maxInterval:6e4,exponent:1.5,maxElapsedTime:36e5},xr=class t extends Error{constructor(e,n){let r=e;n?.cause&&(r+=`: ${n.cause}`),super(r,n),this.name="PermanentError",typeof this.cause>"u"&&(this.cause=n?.cause),Object.setPrototypeOf(this,t.prototype)}},Qt=class t extends Error{constructor(e,n){super(e),this.response=n,this.name="TemporaryError",Object.setPrototypeOf(this,t.prototype)}};async function PN(t,e){var n;switch(e.config.strategy){case"backoff":return xN(rg(t,{statusCodes:e.statusCodes,retryConnectionErrors:!!e.config.retryConnectionErrors}),(n=e.config.backoff)!==null&&n!==void 0?n:ng);case"attempt-count-backoff":return kN(rg(t,{statusCodes:e.statusCodes,retryConnectionErrors:!!e.config.retryConnectionErrors}),Object.assign(Object.assign({},ng),e.config.backoff),e.config);default:return await t(0)}}function rg(t,e){return async n=>{try{let r=await t(n);if(NN(r,e.statusCodes))throw new Qt("Response failed with retryable status code",r);return r}catch(r){throw r instanceof Qt||e.retryConnectionErrors&&(i_(r)||r_(r))?r:new xr("Permanent error",{cause:r})}}}var RN=new RegExp("^[0-9]xx$","i");function NN(t,e){let n=`${t.status}`;return e.some(r=>{if(!RN.test(r))return r===n;let i=r.charAt(0);if(!i)throw new Error("Invalid status code range");let o=n.charAt(0);if(!o)throw new Error(`Invalid response status code: ${n}`);return o===i})}async function xN(t,e){let{maxElapsedTime:n,initialInterval:r,exponent:i,maxInterval:o}=e,a=Date.now(),u=0;for(;;)try{return await t(u)}catch(c){if(c instanceof xr)throw c.cause;if(Date.now()-a>n){if(c instanceof Qt)return c.response;throw c}let f=0;c instanceof Qt&&(f=o_(c.response)),f<=0&&(f=r*Math.pow(u,i)+Math.random()*1e3);let p=Math.min(f,o);await s_(p),u++}}async function kN(t,e,n){let r=0;for(;;)try{return await t(r)}catch(i){if(i instanceof xr)throw i.cause;if(r>=n.maxRetries){if(i instanceof Qt)return i.response;throw i}let o=0;i instanceof Qt&&(o=o_(i.response)),o<=0&&(o=e.initialInterval*Math.pow(e.exponent,r)*(1-Math.random()*.25));let a=Math.min(o,e.maxInterval);await s_(a),r++}}function o_(t){let e=t.headers.get("retry-after-ms");if(e){let o=Number(e);if(Number.isFinite(o)&&o>=0)return o}let n=t.headers.get("retry-after")||"";if(!n)return 0;let r=Number(n);if(Number.isInteger(r))return r*1e3;let i=Date.parse(n);if(Number.isInteger(i)){let o=i-Date.now();return o>0?Math.ceil(o):0}return 0}async function s_(t){return new Promise(e=>setTimeout(e,t))}var Qi=typeof globalThis>"u"?null:globalThis,DN=typeof Qi=="object"&&Qi!=null&&"importScripts"in Qi&&typeof Qi.importScripts=="function",MN=DN||typeof navigator<"u"&&"serviceWorker"in navigator||typeof window=="object"&&typeof window.document<"u",Zt=class{constructor(e={}){let n=e;typeof n=="object"&&n!=null&&"hooks"in n&&n.hooks instanceof Ao?this._hooks=n.hooks:this._hooks=new Ao;let r=new lu;e.http_client=e.http_client||r,e=this._hooks.sdkInit(e);let i=gN(e);i&&(i.pathname=i.pathname.replace(/\/+$/,"")+"/"),this._baseURL=i,this._httpClient=e.http_client||r,this._options=Object.assign(Object.assign({},ZR(e)),{hooks:this._hooks}),this._logger=this._options.debug_logger,!this._logger&&Nr().GOOGLE_GENAI_DEBUG&&(this._logger=console)}_createRequest(e,n,r){var i,o,a,u,c;let{method:d,path:f,query:p,headers:h,security:m}=n,_=(i=n.baseURL)!==null&&i!==void 0?i:this._baseURL;if(!_)return Dt(new $n("No base URL provided for operation"));let g=new URL(_),E;f?(g.pathname=g.pathname.replace(/\/+$/,"")+"/",E=new URL(f,g),!E.search&&g.search&&(E.search=g.search)):E=g,E.hash="";let y=(D,K)=>{if(!K)return D;let j=new Set(K.split("&").filter(Pe=>Pe!=="").map(Pe=>{var Ae;return(Ae=Pe.split("=")[0])!==null&&Ae!==void 0?Ae:""}));return[...D.split("&").filter(Pe=>{var Ae;return Pe!==""&&!j.has((Ae=Pe.split("=")[0])!==null&&Ae!==void 0?Ae:"")}),K].join("&")},C=D=>Object.entries(D).map(([K,j])=>{if(j==null)return;let _e=zt(j)?JSON.stringify(j):j;return Qg(K,_e,{explode:Array.isArray(_e),charEncoding:"percent"})}).filter(K=>typeof K<"u").join("&"),A=[p||"",C(r?.extra_query||{}),C(m?.queryParams||{})].reduce(y,E.search.slice(1));A&&(E.search=`?${A}`);let I=new Headers(h),P=m?.basic.username,G=m?.basic.password;if(P!=null||G!=null){let D=hN([P||"",G||""].join(":"));I.set("Authorization",`Basic ${D}`)}let O=new Headers(m?.headers||{});for(let[D,K]of O)I.set(D,K);let B=I.get("cookie")||"";for(let[D,K]of Object.entries(m?.cookies||{}))B+=`; ${D}=${K}`;B=B.startsWith("; ")?B.slice(2):B,I.set("cookie",B);let k=new Headers((o=r?.headers)!==null&&o!==void 0?o:(a=r?.fetch_options)===null||a===void 0?void 0:a.headers);for(let[D,K]of k)I.set(D,K);MN||I.set((u=n.uaHeader)!==null&&u!==void 0?u:"user-agent",(c=n.userAgent)!==null&&c!==void 0?c:_N.userAgent);let V=n.body,X=Object.fromEntries(Object.entries(r?.extra_body||{}).filter(([,D])=>typeof D<"u"));if(Object.keys(X).length>0){let D=new Headers(h).get("content-type")||"";if(!/^(application|text)\/([^+]+\+)*json/.test(D)||typeof V!="string"&&V!=null)return Dt(new $n("extra_body can only be merged into JSON object request bodies"));let j;try{j=V?JSON.parse(V):{}}catch(_e){return Dt(new $n("extra_body can only be merged into JSON object request bodies",{cause:_e}))}if(!zt(j))return Dt(new $n("extra_body can only be merged into JSON object request bodies"));V=JSON.stringify(Object.assign(Object.assign({},j),X)),I.delete("content-length")}let Z=Object.assign(Object.assign({},r?.fetch_options),r);!Z?.signal&&n.timeout_ms!=null&&n.timeout_ms>0&&(e.timeout_ms=n.timeout_ms),n.body instanceof ReadableStream&&Object.assign(Z,{duplex:"half"});let ne;try{ne=this._hooks.beforeCreateRequest(e,{url:E,options:Object.assign(Object.assign({},Z),{body:V??null,headers:I,method:d})})}catch(D){return Dt(new yo("Create request hook failed to execute",{cause:D}))}return jm(new Request(ne.url,ne.options))}async _do(e,n){let{context:r,isErrorStatusCode:i}=n,o=r.timeout_ms;return PN(async()=>{var a;let u=e.clone(),c=u;if(o!=null&&o>0){let p=AbortSignal.timeout(o),h=(a=yN(u.signal,p))!==null&&a!==void 0?a:p;c=new Request(u,{signal:h})}let d=await this._hooks.beforeRequest(r,c);await UN(this._logger,d).catch(p=>{var h;return(h=this._logger)===null||h===void 0?void 0:h.log("Failed to log request:",p)});let f=await this._httpClient.request(d);try{if(i(f.status)){let p=await this._hooks.afterError(r,f,null);if(p.error)throw p.error;f=p.response||f}else f=await this._hooks.afterSuccess(r,f)}finally{await bN(this._logger,f,d).catch(p=>{var h;return(h=this._logger)===null||h===void 0?void 0:h.log("Failed to log response:",p)})}return f},{config:n.retryConfig,statusCodes:n.retryCodes}).then(a=>jm(a),a=>{switch(!0){case wN(a):return Dt(new Eo("Request aborted by client",{cause:a}));case i_(a):return Dt(new vo("Request timed out",{cause:a}));case r_(a):return Dt(new To("Unable to make request",{cause:a}));default:return Dt(new yo("Unexpected HTTP client error",{cause:a}))}})}},a_=/^(application|text)\/([^+]+\+)*json.*/,ig=/^(application|text)\/([^+]+\+)*(jsonl|x-ndjson)\b.*/;async function UN(t,e){if(!t)return;let n=e.headers.get("content-type"),r=n?.split(";")[0]||"";t.group(`> Request: ${e.method} ${e.url}`),t.group("Headers:");for(let[i,o]of e.headers.entries())t.log(`${i}: ${o}`);switch(t.groupEnd(),t.group("Body:"),!0){case a_.test(r):t.log(await e.clone().json());break;case r.startsWith("text/"):t.log(await e.clone().text());break;case r==="multipart/form-data":{let i=await e.clone().formData();for(let[o,a]of i){let u=a instanceof Blob?"<Blob>":a;t.log(`${o}: ${u}`)}break}default:t.log(`<${n}>`);break}t.groupEnd(),t.groupEnd()}async function bN(t,e,n){if(!t)return;let r=e.headers.get("content-type"),i=r?.split(";")[0]||"";t.group(`< Response: ${n.method} ${n.url}`),t.log("Status Code:",e.status,e.statusText),t.group("Headers:");for(let[o,a]of e.headers.entries())t.log(`${o}: ${a}`);switch(t.groupEnd(),t.group("Body:"),!0){case(Hn(e,"application/json")||a_.test(i)&&!ig.test(i)):t.log(await e.clone().json());break;case(Hn(e,"application/jsonl")||ig.test(i)):case Hn(e,"text/event-stream"):t.log(`<${r}>`);break;case Hn(e,"text/*"):t.log(await e.clone().text());break;case Hn(e,"multipart/form-data"):{let o=await e.clone().formData();for(let[a,u]of o){let c=u instanceof Blob?"<Blob>":u;t.log(`${a}: ${c}`)}break}default:t.log(`<${r}>`);break}t.groupEnd(),t.groupEnd()}var Co=class extends rt{constructor(e,n){e&&(e+=": "),e+=`Status ${n.response.status}`;let r=n.response.headers.get("content-type")||'""';r!=="application/json"&&(e+=` Content-Type ${r.includes(" ")?`"${r}"`:r}`);let i=n.body||'""';e+=i.length>100?`
41
- `:". ";let o=i;if(i.length>1e4){let a=i.substring(0,1e4),u=i.length-1e4;o=`${a}...and ${u} more chars`}e+=`Body: ${o}`,e=e.trim(),super(e,n),this.name="GoogleGenAiDefaultError"}};function og(t){try{return JSON.parse(t)}catch{return t}}function GN(t,e={}){var n,r;let i=e.flattened===!0,o=(n=e.sentinel)!==null&&n!==void 0?n:"";return new uu(t,a=>o!==""&&a.data===o?{done:!0,value:void 0}:i?{done:!1,value:a.data==null?void 0:og(a.data)}:{done:!1,value:Object.assign(Object.assign({},a),{data:a.data==null?a.data:og(a.data)})},{dataRequired:(r=e.dataRequired)!==null&&r!==void 0?r:!0})}var uu=class extends ReadableStream{constructor(e,n,r){var i;let o=e.getReader(),a=new Uint8Array(4096),u=0,c=0,d={eventId:void 0},f=(i=r?.dataRequired)!==null&&i!==void 0?i:!0;super({async pull(p){try{for(;;){let h=ON(a,u,c);if(!h){c=Math.max(0,u-LN+1);let g=await o.read();if(g.done)return p.close();if(u+g.value.length>a.length){let E=new Uint8Array(Math.max(a.length*2,u+g.value.length));E.set(a.subarray(0,u)),a=E}a.set(g.value,u),u+=g.value.length;continue}let m=a.slice(0,h.index);if(a.copyWithin(0,h.index+h.length,u),u-=h.index+h.length,a.length>4096&&u<=a.length>>2){let g=new Uint8Array(Math.max(4096,u*2));g.set(a.subarray(0,u)),a=g}c=0;let _=qN(m,n,d,f);if(_&&!_.done)return p.enqueue(_.value);if(_?.done)return await o.cancel("done"),p.close()}}catch(h){p.error(h),await o.cancel(h)}},cancel:p=>o.cancel(p)})}[Symbol.asyncIterator](e){let n=ReadableStream.prototype[Symbol.asyncIterator];if(typeof n=="function")return n.call(this,e);let r=this.getReader(),i={next:async()=>{let a=await r.read();return a.done?(r.releaseLock(),{done:!0,value:void 0}):{done:!1,value:a.value}},throw:async a=>(await r.cancel(a),r.releaseLock(),{done:!0,value:void 0}),return:async()=>(await r.cancel("done"),r.releaseLock(),{done:!0,value:void 0}),[Symbol.asyncIterator](){return this}},o=Symbol.asyncDispose;return o&&(i[o]=async()=>{var a;await((a=i.return)===null||a===void 0?void 0:a.call(i))}),i}values(e){return this[Symbol.asyncIterator](e)}},tt=13,nt=10,l_=[[tt,nt,tt,nt],[tt,nt,tt],[tt,nt,nt],[tt,tt,nt],[nt,tt,nt],[tt,tt],[nt,tt],[nt,nt]],LN=l_.reduce((t,e)=>Math.max(t,e.length),0);function ON(t,e,n){for(let r=n;r<e;r++)if(!(t[r]!==tt&&t[r]!==nt))for(let i of l_){if(r+i.length>e)continue;let o=!0;for(let a=0;a<i.length;a++)if(t[r+a]!==i[a]){o=!1;break}if(o)return{index:r,length:i.length}}return null}function qN(t,e,n,r){let o=new TextDecoder().decode(t).split(/\r\n|\r|\n/),a=[],u={},c=!0;for(let d of o){if(!d||d.startsWith(":"))continue;c=!1;let f=d.indexOf(":"),p=d,h="";f>0&&(p=d.slice(0,f),h=d[f+1]===" "?d.slice(f+2):d.slice(f+1)),p==="data"?a.push(h):p==="event"?u.event=h:p==="id"&&!h.includes("\0")?n.eventId=h:p==="retry"&&/^\d+$/.test(h)&&(u.retry=Number(h))}if(!c){if(u.id=n.eventId,a.length)u.data=a.join(`
42
- `);else if(r)return;return e(u)}}var FN={jsonl:"application/jsonl",json:"application/json",text:"text/plain",bytes:"application/octet-stream",stream:"application/octet-stream",sse:"text/event-stream",nil:"*",fail:"*"};function jt(t,e,n){return Object.assign(Object.assign({},n),{err:!0,enc:"json",codes:t,errorClass:e})}function ve(t,e){return Object.assign(Object.assign({},e),{enc:"json",codes:t})}function u_(t,e,n){return Object.assign(Object.assign(Object.assign({},n),{enc:"sse",codes:t}),e?{sse:e}:{})}function BN(t,e){return Object.assign(Object.assign({},e),{enc:"nil",codes:t})}function ee(t){return{enc:"fail",codes:t}}function he(...t){return async function(n,r,i){let o,a;for(let h of t){let{codes:m}=h,_="ctype"in h?h.ctype:FN[h.enc];if(_&&IN(n,m,_)){a=h;break}else if(!_&&ce(n,m)){a=h;break}}if(!a)return[{ok:!1,error:new Co("Unexpected Status or Content-Type",{response:n,request:r,body:await n.text().catch(()=>"")})},o];let u=a.enc,c="";switch(u){case"json":c=await n.text();try{o=JSON.parse(c)}catch(h){if(!("err"in a))throw h;o=c}break;case"jsonl":o=n.body;break;case"bytes":o=new Uint8Array(await n.arrayBuffer());break;case"stream":o=n.body;break;case"text":c=await n.text(),o=c;break;case"sse":if(n.body){let h="sse"in a&&a.sse||{};o=GN(n.body,h)}else o=null;break;case"nil":c=await n.text(),o=void 0;break;case"fail":c=await n.text(),o=c;break;default:throw new Error(`Unsupported response type: ${u}`)}if(a.enc==="fail")return[{ok:!1,error:new Co("API error occurred",{request:r,response:n,body:c})},o];let d=a.key||i?.resultKey,f,p=a.hdrs?{headers:VN(n.headers)}:null;return"err"in a?f=Object.assign(Object.assign(Object.assign({},i?.extraFields),p),zt(o)?o:null):d?f=Object.assign(Object.assign(Object.assign({},i?.extraFields),p),{[d]:o}):a.hdrs?f=Object.assign(Object.assign(Object.assign({},i?.extraFields),p),zt(o)?o:null):f=o,"err"in a?[{ok:!1,error:a.errorClass?new a.errorClass(f,{request:r,response:n,body:c}):f},o]:[{ok:!0,value:f},o]}}var HN=/, */;function VN(t){let e={};for(let[n,r]of t.entries())e[n]=r.split(HN);return e}var sg={Incomplete:"incomplete",UnrecognisedSecurityType:"unrecognized_security_type"},cu=class t extends Error{constructor(e,n){super(n),this.code=e,this.name="SecurityError"}static incomplete(){return new t(sg.Incomplete,"Security requirements not met in order to perform the operation")}static unrecognizedType(e){return new t(sg.UnrecognisedSecurityType,`Unrecognised security type: ${e}`)}};function $N(...t){let e={basic:{},headers:{},queryParams:{},cookies:{},oauth2:{type:"none"}},n=t.find(r=>r.every(i=>{if(i.value==null)return!1;if(i.type==="http:basic")return i.value.username!=null||i.value.password!=null;if(i.type==="http:custom")return null;if(i.type==="oauth2:password")return typeof i.value=="string"&&!!i.value;if(i.type==="oauth2:client_credentials")return typeof i.value=="string"?!!i.value:i.value.client_id!=null||i.value.client_secret!=null;if(typeof i.value=="string")return!!i.value;throw new Error(`Unrecognized security type: ${i.type} (value type: ${typeof i.value})`)}));return n==null?null:(n.forEach(r=>{if(r.value==null)return;let{type:i}=r;switch(i){case"apiKey:header":e.headers[r.fieldName]=r.value;break;case"apiKey:query":e.queryParams[r.fieldName]=r.value;break;case"apiKey:cookie":e.cookies[r.fieldName]=r.value;break;case"http:basic":JN(e,r);break;case"http:custom":break;case"http:bearer":Zi(e,r);break;case"oauth2":Zi(e,r);break;case"oauth2:password":Zi(e,r);break;case"oauth2:client_credentials":break;case"openIdConnect":Zi(e,r);break;default:throw cu.unrecognizedType(i)}}),e)}function JN(t,e){e.value!=null&&(t.basic=e.value)}function Zi(t,e){if(typeof e.value!="string"||!e.value)return;let n=e.value;n.slice(0,7).toLowerCase()!=="bearer "&&(n=`Bearer ${n}`),e.fieldName!==void 0&&(t.headers[e.fieldName]=n)}function me(t,e){var n,r;let i=[[{fieldName:"apiKey",type:"http:custom",value:(n=t?.api_key)!==null&&n!==void 0?n:Nr().GOOGLE_GENAI_API_KEY},{fieldName:"accessToken",type:"http:custom",value:(r=t?.access_token)!==null&&r!==void 0?r:Nr().GOOGLE_GENAI_ACCESS_TOKEN},{fieldName:"defaultHeaders",type:"http:custom",value:t?.default_headers}]];return $N(...i)}async function ge(t){if(t!=null)return typeof t=="function"?t():t}var c_,se=class t{constructor(e,n){this[c_]="APIPromise",this._promise=e instanceof Promise?e:Promise.resolve(e),this._unwrapped=e instanceof Promise?null:Promise.resolve(e[0]),this._callSource=n??null}_getUnwrapped(){var e;return(e=this._unwrapped)!==null&&e!==void 0?e:this._unwrapped=this._promise.then(([n])=>n)}then(e,n){return this._promise.then(e?([r])=>e(r):void 0,n)}catch(e){return this._getUnwrapped().catch(e)}finally(e){return this._getUnwrapped().finally(e)}$inspect(){return this._promise}asResponse(){var e;return((e=this._callSource)!==null&&e!==void 0?e:this._callSource=this._promise.then(([,r])=>r)).then(r=>{if(!r.response)throw new Error("APIPromise.asResponse: response unavailable");return r.response})}async withResponse(){let[[e],n]=await Promise.all([this._promise,this.asResponse()]);return{data:e,response:n}}_thenUnwrap(e){var n;let r=this._promise.then(([i,o])=>[e(i),o]);return r.catch(()=>{}),new t(r,(n=this._callSource)!==null&&n!==void 0?n:void 0)}};c_=Symbol.toStringTag;function fe(t){let e=t.$inspect(),n=e.then(([i,o])=>{if(!i.ok)throw i.error;return[i.value,o]}),r=e.then(([i,o])=>{var a;if(!i.ok&&!(!((a=o.response)===null||a===void 0)&&a.ok))throw i.error;return o});return n.catch(()=>{}),r.catch(()=>{}),new se(n,r)}function d_(t,e,n,r){return new se(WN(t,e,n,r))}async function WN(t,e,n,r){var i,o,a;let c={body:e,api_version:n},d=Gt("body",c.body,{explode:!0}),f={api_version:te("api_version",(i=c.api_version)!==null&&i!==void 0?i:t._options.api_version,{explode:!1,charEncoding:"percent"})},p=de("/{api_version}/agents")(f),h=new Headers(pe({"Content-Type":"application/json",Accept:"application/json"})),m=await ge(t._options.security),_=me(m),g={options:t._options,base_url:(a=(o=r?.server_url)!==null&&o!==void 0?o:t._baseURL)!==null&&a!==void 0?a:"",operation_id:"CreateAgent",o_auth2_scopes:null,resolved_security:_,security_source:t._options.security,retry_config:r?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:r?.retry_codes||["408","409","429","5XX"]},E=t._createRequest(g,{security:_,method:"POST",baseURL:r?.server_url,path:p,headers:h,body:d,userAgent:t._options.user_agent,timeout_ms:r?.timeout_ms||t._options.timeout_ms||-1},r);if(!E.ok)return[E,{status:"invalid"}];let y=E.value,C=await t._do(y,{context:g,isErrorStatusCode:P=>ce({status:P},["4XX","5XX"]),retryConfig:g.retry_config,retryCodes:g.retry_codes});if(!C.ok)return[C,{status:"request-error",request:y}];let A=C.value,[I]=await he(ee("4XX"),ee("5XX"),ve("default"))(A,y);return I.ok?[I,{status:"complete",request:y,response:A}]:[I,{status:"complete",request:y,response:A}]}function f_(t,e,n,r){return new se(XN(t,e,n,r))}async function XN(t,e,n,r){var i,o,a;let c={id:e,api_version:n},d=null,f={api_version:te("api_version",(i=c.api_version)!==null&&i!==void 0?i:t._options.api_version,{explode:!1,charEncoding:"percent"}),id:te("id",c.id,{explode:!1,charEncoding:"percent"})},p=de("/{api_version}/agents/{id}")(f),h=new Headers(pe({Accept:"application/json"})),m=await ge(t._options.security),_=me(m),g={options:t._options,base_url:(a=(o=r?.server_url)!==null&&o!==void 0?o:t._baseURL)!==null&&a!==void 0?a:"",operation_id:"DeleteAgent",o_auth2_scopes:null,resolved_security:_,security_source:t._options.security,retry_config:r?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:r?.retry_codes||["408","409","429","5XX"]},E=t._createRequest(g,{security:_,method:"DELETE",baseURL:r?.server_url,path:p,headers:h,body:d,userAgent:t._options.user_agent,timeout_ms:r?.timeout_ms||t._options.timeout_ms||-1},r);if(!E.ok)return[E,{status:"invalid"}];let y=E.value,C=await t._do(y,{context:g,isErrorStatusCode:P=>ce({status:P},["4XX","5XX"]),retryConfig:g.retry_config,retryCodes:g.retry_codes});if(!C.ok)return[C,{status:"request-error",request:y}];let A=C.value,[I]=await he(ee("4XX"),ee("5XX"),ve("default"))(A,y);return I.ok?[I,{status:"complete",request:y,response:A}]:[I,{status:"complete",request:y,response:A}]}function p_(t,e,n,r){return new se(KN(t,e,n,r))}async function KN(t,e,n,r){var i,o,a;let c={id:e,api_version:n},d=null,f={api_version:te("api_version",(i=c.api_version)!==null&&i!==void 0?i:t._options.api_version,{explode:!1,charEncoding:"percent"}),id:te("id",c.id,{explode:!1,charEncoding:"percent"})},p=de("/{api_version}/agents/{id}")(f),h=new Headers(pe({Accept:"application/json"})),m=await ge(t._options.security),_=me(m),g={options:t._options,base_url:(a=(o=r?.server_url)!==null&&o!==void 0?o:t._baseURL)!==null&&a!==void 0?a:"",operation_id:"GetAgent",o_auth2_scopes:null,resolved_security:_,security_source:t._options.security,retry_config:r?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:r?.retry_codes||["408","409","429","5XX"]},E=t._createRequest(g,{security:_,method:"GET",baseURL:r?.server_url,path:p,headers:h,body:d,userAgent:t._options.user_agent,timeout_ms:r?.timeout_ms||t._options.timeout_ms||-1},r);if(!E.ok)return[E,{status:"invalid"}];let y=E.value,C=await t._do(y,{context:g,isErrorStatusCode:P=>ce({status:P},["4XX","5XX"]),retryConfig:g.retry_config,retryCodes:g.retry_codes});if(!C.ok)return[C,{status:"request-error",request:y}];let A=C.value,[I]=await he(ee("4XX"),ee("5XX"),ve("default"))(A,y);return I.ok?[I,{status:"complete",request:y,response:A}]:[I,{status:"complete",request:y,response:A}]}function h_(t,e,n,r,i,o){return new se(YN(t,e,n,r,i,o))}async function YN(t,e,n,r,i,o){var a,u,c;let f={api_version:e,page_size:n,page_token:r,parent:i},p=null,h={api_version:te("api_version",(a=f?.api_version)!==null&&a!==void 0?a:t._options.api_version,{explode:!1,charEncoding:"percent"})},m=de("/{api_version}/agents")(h),_=hn({page_size:f?.page_size,page_token:f?.page_token,parent:f?.parent}),g=new Headers(pe({Accept:"application/json"})),E=await ge(t._options.security),y=me(E),C={options:t._options,base_url:(c=(u=o?.server_url)!==null&&u!==void 0?u:t._baseURL)!==null&&c!==void 0?c:"",operation_id:"ListAgents",o_auth2_scopes:null,resolved_security:y,security_source:t._options.security,retry_config:o?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:o?.retry_codes||["408","409","429","5XX"]},A=t._createRequest(C,{security:y,method:"GET",baseURL:o?.server_url,path:m,headers:g,query:_,body:p,userAgent:t._options.user_agent,timeout_ms:o?.timeout_ms||t._options.timeout_ms||-1},o);if(!A.ok)return[A,{status:"invalid"}];let I=A.value,P=await t._do(I,{context:C,isErrorStatusCode:B=>ce({status:B},["4XX","5XX"]),retryConfig:C.retry_config,retryCodes:C.retry_codes});if(!P.ok)return[P,{status:"request-error",request:I}];let G=P.value,[O]=await he(ee("4XX"),ee("5XX"),ve("default"))(G,I);return O.ok?[O,{status:"complete",request:I,response:G}]:[O,{status:"complete",request:I,response:G}]}var du=class extends Zt{create(e,n){let{api_version:r}=e,i=Ue(e,["api_version"]);return fe(d_(this,i,r,n))}list(e,n){return fe(h_(this,e?.api_version,e?.page_size,e?.page_token,e?.parent,n))}get(e,n,r){return fe(p_(this,e,n?.api_version,r))}delete(e,n,r){return fe(f_(this,e,n?.api_version,r))}};function m_(t,e,n,r){return new se(zN(t,e,n,r))}async function zN(t,e,n,r){var i,o,a;let c={body:e,api_version:n},d=Gt("body",c.body,{explode:!0}),f={api_version:te("api_version",(i=c.api_version)!==null&&i!==void 0?i:t._options.api_version,{explode:!1,charEncoding:"percent"})},p=de("/{api_version}/environments")(f),h=new Headers(pe({"Content-Type":"application/json",Accept:"application/json"})),m=await ge(t._options.security),_=me(m),g={options:t._options,base_url:(a=(o=r?.server_url)!==null&&o!==void 0?o:t._baseURL)!==null&&a!==void 0?a:"",operation_id:"CreateEnvironment",o_auth2_scopes:null,resolved_security:_,security_source:t._options.security,retry_config:r?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:r?.retry_codes||["408","409","429","5XX"]},E=t._createRequest(g,{security:_,method:"POST",baseURL:r?.server_url,path:p,headers:h,body:d,userAgent:t._options.user_agent,timeout_ms:r?.timeout_ms||t._options.timeout_ms||-1},r);if(!E.ok)return[E,{status:"invalid"}];let y=E.value,C=await t._do(y,{context:g,isErrorStatusCode:P=>ce({status:P},["4XX","5XX"]),retryConfig:g.retry_config,retryCodes:g.retry_codes});if(!C.ok)return[C,{status:"request-error",request:y}];let A=C.value,[I]=await he(ee("4XX"),ee("5XX"),ve("default"))(A,y);return I.ok?[I,{status:"complete",request:y,response:A}]:[I,{status:"complete",request:y,response:A}]}function g_(t,e,n,r){return new se(QN(t,e,n,r))}async function QN(t,e,n,r){var i,o,a;let c={id:e,api_version:n},d=null,f={api_version:te("api_version",(i=c.api_version)!==null&&i!==void 0?i:t._options.api_version,{explode:!1,charEncoding:"percent"}),id:te("id",c.id,{explode:!1,charEncoding:"percent"})},p=de("/{api_version}/environments/{id}")(f),h=new Headers(pe({Accept:"application/json"})),m=await ge(t._options.security),_=me(m),g={options:t._options,base_url:(a=(o=r?.server_url)!==null&&o!==void 0?o:t._baseURL)!==null&&a!==void 0?a:"",operation_id:"DeleteEnvironment",o_auth2_scopes:null,resolved_security:_,security_source:t._options.security,retry_config:r?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:r?.retry_codes||["408","409","429","5XX"]},E=t._createRequest(g,{security:_,method:"DELETE",baseURL:r?.server_url,path:p,headers:h,body:d,userAgent:t._options.user_agent,timeout_ms:r?.timeout_ms||t._options.timeout_ms||-1},r);if(!E.ok)return[E,{status:"invalid"}];let y=E.value,C=await t._do(y,{context:g,isErrorStatusCode:P=>ce({status:P},["4XX","5XX"]),retryConfig:g.retry_config,retryCodes:g.retry_codes});if(!C.ok)return[C,{status:"request-error",request:y}];let A=C.value,[I]=await he(ee("4XX"),ee("5XX"),ve("default"))(A,y);return I.ok?[I,{status:"complete",request:y,response:A}]:[I,{status:"complete",request:y,response:A}]}function __(t,e,n,r){return new se(ZN(t,e,n,r))}async function ZN(t,e,n,r){var i,o,a;let c={id:e,api_version:n},d=null,f={api_version:te("api_version",(i=c.api_version)!==null&&i!==void 0?i:t._options.api_version,{explode:!1,charEncoding:"percent"}),id:te("id",c.id,{explode:!1,charEncoding:"percent"})},p=de("/{api_version}/environments/{id}")(f),h=new Headers(pe({Accept:"application/json"})),m=await ge(t._options.security),_=me(m),g={options:t._options,base_url:(a=(o=r?.server_url)!==null&&o!==void 0?o:t._baseURL)!==null&&a!==void 0?a:"",operation_id:"GetEnvironment",o_auth2_scopes:null,resolved_security:_,security_source:t._options.security,retry_config:r?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:r?.retry_codes||["408","409","429","5XX"]},E=t._createRequest(g,{security:_,method:"GET",baseURL:r?.server_url,path:p,headers:h,body:d,userAgent:t._options.user_agent,timeout_ms:r?.timeout_ms||t._options.timeout_ms||-1},r);if(!E.ok)return[E,{status:"invalid"}];let y=E.value,C=await t._do(y,{context:g,isErrorStatusCode:P=>ce({status:P},["4XX","5XX"]),retryConfig:g.retry_config,retryCodes:g.retry_codes});if(!C.ok)return[C,{status:"request-error",request:y}];let A=C.value,[I]=await he(ee("4XX"),ee("5XX"),ve("default"))(A,y);return I.ok?[I,{status:"complete",request:y,response:A}]:[I,{status:"complete",request:y,response:A}]}function y_(t,e,n,r,i){return new se(jN(t,e,n,r,i))}async function jN(t,e,n,r,i){var o,a,u;let d={api_version:e,page_size:n,page_token:r},f=null,p={api_version:te("api_version",(o=d?.api_version)!==null&&o!==void 0?o:t._options.api_version,{explode:!1,charEncoding:"percent"})},h=de("/{api_version}/environments")(p),m=hn({page_size:d?.page_size,page_token:d?.page_token}),_=new Headers(pe({Accept:"application/json"})),g=await ge(t._options.security),E=me(g),y={options:t._options,base_url:(u=(a=i?.server_url)!==null&&a!==void 0?a:t._baseURL)!==null&&u!==void 0?u:"",operation_id:"ListEnvironments",o_auth2_scopes:null,resolved_security:E,security_source:t._options.security,retry_config:i?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:i?.retry_codes||["408","409","429","5XX"]},C=t._createRequest(y,{security:E,method:"GET",baseURL:i?.server_url,path:h,headers:_,query:m,body:f,userAgent:t._options.user_agent,timeout_ms:i?.timeout_ms||t._options.timeout_ms||-1},i);if(!C.ok)return[C,{status:"invalid"}];let A=C.value,I=await t._do(A,{context:y,isErrorStatusCode:O=>ce({status:O},["4XX","5XX"]),retryConfig:y.retry_config,retryCodes:y.retry_codes});if(!I.ok)return[I,{status:"request-error",request:A}];let P=I.value,[G]=await he(ee("4XX"),ee("5XX"),ve("default"))(P,A);return G.ok?[G,{status:"complete",request:A,response:P}]:[G,{status:"complete",request:A,response:P}]}var fu=class extends Zt{createEnvironment(e,n,r){return fe(m_(this,e,n,r))}listEnvironments(e,n){return fe(y_(this,e?.api_version,e?.page_size,e?.page_token,n))}getEnvironment(e,n,r){return fe(__(this,e,n?.api_version,r))}deleteEnvironment(e,n,r){return fe(g_(this,e,n?.api_version,r))}};var pu=class extends rt{constructor(e,n){var r;let i=((r=e.error)===null||r===void 0?void 0:r.message)||`API error occurred: ${JSON.stringify(e)}`;super(i,n),this.data$=e,this.error=e.error,this.name="CancelInteractionByIdServerError"}},hu=class extends rt{constructor(e,n){var r;let i=((r=e.error)===null||r===void 0?void 0:r.message)||`API error occurred: ${JSON.stringify(e)}`;super(i,n),this.data$=e,this.error=e.error,this.name="CancelInteractionByIdClientError"}};var mu=class extends rt{constructor(e,n){var r;let i=((r=e.error)===null||r===void 0?void 0:r.message)||`API error occurred: ${JSON.stringify(e)}`;super(i,n),this.data$=e,this.error=e.error,this.name="CreateInteractionServerError"}},gu=class extends rt{constructor(e,n){var r;let i=((r=e.error)===null||r===void 0?void 0:r.message)||`API error occurred: ${JSON.stringify(e)}`;super(i,n),this.data$=e,this.error=e.error,this.name="CreateInteractionClientError"}};var _u=class extends rt{constructor(e,n){var r;let i=((r=e.error)===null||r===void 0?void 0:r.message)||`API error occurred: ${JSON.stringify(e)}`;super(i,n),this.data$=e,this.error=e.error,this.name="DeleteInteractionServerError"}},yu=class extends rt{constructor(e,n){var r;let i=((r=e.error)===null||r===void 0?void 0:r.message)||`API error occurred: ${JSON.stringify(e)}`;super(i,n),this.data$=e,this.error=e.error,this.name="DeleteInteractionClientError"}};var Eu=class extends rt{constructor(e,n){var r;let i=((r=e.error)===null||r===void 0?void 0:r.message)||`API error occurred: ${JSON.stringify(e)}`;super(i,n),this.data$=e,this.error=e.error,this.name="GetInteractionByIdServerError"}},vu=class extends rt{constructor(e,n){var r;let i=((r=e.error)===null||r===void 0?void 0:r.message)||`API error occurred: ${JSON.stringify(e)}`;super(i,n),this.data$=e,this.error=e.error,this.name="GetInteractionByIdClientError"}};function E_(t,e,n,r){return new se(ex(t,e,n,r))}async function ex(t,e,n,r){var i,o,a;let c={id:e,api_version:n},d=null,f={api_version:te("api_version",(i=c.api_version)!==null&&i!==void 0?i:t._options.api_version,{explode:!1,charEncoding:"percent"}),id:te("id",c.id,{explode:!1,charEncoding:"percent"})},p=de("/{api_version}/interactions/{id}/cancel")(f),h=new Headers(pe({Accept:"application/json"})),m=await ge(t._options.security),_=me(m),g={options:t._options,base_url:(a=(o=r?.server_url)!==null&&o!==void 0?o:t._baseURL)!==null&&a!==void 0?a:"",operation_id:"cancelInteractionById",o_auth2_scopes:null,resolved_security:_,security_source:t._options.security,retry_config:r?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:r?.retry_codes||["408","409","429","5XX"]},E=t._createRequest(g,{security:_,method:"POST",baseURL:r?.server_url,path:p,headers:h,body:d,userAgent:t._options.user_agent,timeout_ms:r?.timeout_ms||t._options.timeout_ms||-1},r);if(!E.ok)return[E,{status:"invalid"}];let y=E.value,C=await t._do(y,{context:g,isErrorStatusCode:G=>ce({status:G},["4XX","5XX"]),retryConfig:g.retry_config,retryCodes:g.retry_codes});if(!C.ok)return[C,{status:"request-error",request:y}];let A=C.value,I={httpMeta:{response:A,request:y}},[P]=await he(ve(200),jt("4XX",hu),jt("5XX",pu))(A,y,{extraFields:I});return P.ok?[P,{status:"complete",request:y,response:A}]:[P,{status:"complete",request:y,response:A}]}function v_(t,e,n,r){return new se(tx(t,e,n,r))}async function tx(t,e,n,r){var i,o,a,u;let c={body:e,api_version:n},d=c,f=Gt("body",d.body,{explode:!0}),p={api_version:te("api_version",(i=d.api_version)!==null&&i!==void 0?i:t._options.api_version,{explode:!1,charEncoding:"percent"})},h=de("/{api_version}/interactions")(p),m=new Headers(pe({"Content-Type":"application/json",Accept:!((o=c?.body)===null||o===void 0)&&o.stream?"text/event-stream":"application/json"})),_=await ge(t._options.security),g=me(_),E={options:t._options,base_url:(u=(a=r?.server_url)!==null&&a!==void 0?a:t._baseURL)!==null&&u!==void 0?u:"",operation_id:"CreateInteraction",o_auth2_scopes:null,resolved_security:g,security_source:t._options.security,retry_config:r?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:r?.retry_codes||["408","409","429","5XX"]},y=t._createRequest(E,{security:g,method:"POST",baseURL:r?.server_url,path:h,headers:m,body:f,userAgent:t._options.user_agent,timeout_ms:r?.timeout_ms||t._options.timeout_ms||-1},r);if(!y.ok)return[y,{status:"invalid"}];let C=y.value,A=await t._do(C,{context:E,isErrorStatusCode:O=>ce({status:O},["4XX","5XX"]),retryConfig:E.retry_config,retryCodes:E.retry_codes});if(!A.ok)return[A,{status:"request-error",request:C}];let I=A.value,P={httpMeta:{response:I,request:C}},[G]=await he(ve(200),u_(200,{sentinel:"[DONE]",flattened:!0}),jt("4XX",gu),jt("5XX",mu))(I,C,{extraFields:P});return G.ok?[G,{status:"complete",request:C,response:I}]:[G,{status:"complete",request:C,response:I}]}function nx(t,e,n,r){return new se(rx(t,e,n,r))}async function rx(t,e,n,r){var i,o,a;let c={id:e,api_version:n},d=null,f={api_version:te("api_version",(i=c.api_version)!==null&&i!==void 0?i:t._options.api_version,{explode:!1,charEncoding:"percent"}),id:te("id",c.id,{explode:!1,charEncoding:"percent"})},p=de("/{api_version}/interactions/{id}")(f),h=new Headers(pe({Accept:"application/json"})),m=await ge(t._options.security),_=me(m),g={options:t._options,base_url:(a=(o=r?.server_url)!==null&&o!==void 0?o:t._baseURL)!==null&&a!==void 0?a:"",operation_id:"deleteInteraction",o_auth2_scopes:null,resolved_security:_,security_source:t._options.security,retry_config:r?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:r?.retry_codes||["408","409","429","5XX"]},E=t._createRequest(g,{security:_,method:"DELETE",baseURL:r?.server_url,path:p,headers:h,body:d,userAgent:t._options.user_agent,timeout_ms:r?.timeout_ms||t._options.timeout_ms||-1},r);if(!E.ok)return[E,{status:"invalid"}];let y=E.value,C=await t._do(y,{context:g,isErrorStatusCode:G=>ce({status:G},["4XX","5XX"]),retryConfig:g.retry_config,retryCodes:g.retry_codes});if(!C.ok)return[C,{status:"request-error",request:y}];let A=C.value,I={httpMeta:{response:A,request:y}},[P]=await he(BN(200),jt("4XX",yu),jt("5XX",_u))(A,y,{extraFields:I});return P.ok?[P,{status:"complete",request:y,response:A}]:[P,{status:"complete",request:y,response:A}]}function T_(t,e,n,r,i,o,a){return new se(ix(t,e,n,r,i,o,a))}async function ix(t,e,n,r,i,o,a){var u,c,d;let f={id:e,stream:n,last_event_id:r,include_input:i,api_version:o},p=f,h=null,m={api_version:te("api_version",(u=p.api_version)!==null&&u!==void 0?u:t._options.api_version,{explode:!1,charEncoding:"percent"}),id:te("id",p.id,{explode:!1,charEncoding:"percent"})},_=de("/{api_version}/interactions/{id}")(m),g=hn({include_input:p.include_input,last_event_id:p.last_event_id,stream:p.stream}),E=new Headers(pe({Accept:f?.stream?"text/event-stream":"application/json"})),y=await ge(t._options.security),C=me(y),A={options:t._options,base_url:(d=(c=a?.server_url)!==null&&c!==void 0?c:t._baseURL)!==null&&d!==void 0?d:"",operation_id:"getInteractionById",o_auth2_scopes:null,resolved_security:C,security_source:t._options.security,retry_config:a?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:a?.retry_codes||["408","409","429","5XX"]},I=t._createRequest(A,{security:C,method:"GET",baseURL:a?.server_url,path:_,headers:E,query:g,body:h,userAgent:t._options.user_agent,timeout_ms:a?.timeout_ms||t._options.timeout_ms||-1},a);if(!I.ok)return[I,{status:"invalid"}];let P=I.value,G=await t._do(P,{context:A,isErrorStatusCode:V=>ce({status:V},["4XX","5XX"]),retryConfig:A.retry_config,retryCodes:A.retry_codes});if(!G.ok)return[G,{status:"request-error",request:P}];let O=G.value,B={httpMeta:{response:O,request:P}},[k]=await he(ve(200),u_(200,{sentinel:"[DONE]",flattened:!0}),jt("4XX",vu),jt("5XX",Eu))(O,P,{extraFields:B});return k.ok?[k,{status:"complete",request:P,response:O}]:[k,{status:"complete",request:P,response:O}]}var Tu=class extends Zt{create(e,n){let{api_version:r}=e,i=Ue(e,["api_version"]);return fe(v_(this,i,r,n))}get(e,n,r){return fe(T_(this,e,n?.stream,n?.last_event_id,n?.include_input,n?.api_version,r))}delete(e,n,r){return fe(nx(this,e,n?.api_version,r))}cancel(e,n,r){return fe(E_(this,e,n?.api_version,r))}};function A_(t,e,n,r){return new se(ox(t,e,n,r))}async function ox(t,e,n,r){var i,o,a;let c={body:e,api_version:n},d=Gt("body",c.body,{explode:!0}),f={api_version:te("api_version",(i=c.api_version)!==null&&i!==void 0?i:t._options.api_version,{explode:!1,charEncoding:"percent"})},p=de("/{api_version}/triggers")(f),h=new Headers(pe({"Content-Type":"application/json",Accept:"application/json"})),m=await ge(t._options.security),_=me(m),g={options:t._options,base_url:(a=(o=r?.server_url)!==null&&o!==void 0?o:t._baseURL)!==null&&a!==void 0?a:"",operation_id:"CreateTrigger",o_auth2_scopes:null,resolved_security:_,security_source:t._options.security,retry_config:r?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:r?.retry_codes||["408","409","429","5XX"]},E=t._createRequest(g,{security:_,method:"POST",baseURL:r?.server_url,path:p,headers:h,body:d,userAgent:t._options.user_agent,timeout_ms:r?.timeout_ms||t._options.timeout_ms||-1},r);if(!E.ok)return[E,{status:"invalid"}];let y=E.value,C=await t._do(y,{context:g,isErrorStatusCode:P=>ce({status:P},["4XX","5XX"]),retryConfig:g.retry_config,retryCodes:g.retry_codes});if(!C.ok)return[C,{status:"request-error",request:y}];let A=C.value,[I]=await he(ve(200),ee("4XX"),ee("5XX"))(A,y);return I.ok?[I,{status:"complete",request:y,response:A}]:[I,{status:"complete",request:y,response:A}]}function C_(t,e,n,r){return new se(sx(t,e,n,r))}async function sx(t,e,n,r){var i,o,a;let c={id:e,api_version:n},d=null,f={api_version:te("api_version",(i=c.api_version)!==null&&i!==void 0?i:t._options.api_version,{explode:!1,charEncoding:"percent"}),id:te("id",c.id,{explode:!1,charEncoding:"percent"})},p=de("/{api_version}/triggers/{id}")(f),h=new Headers(pe({Accept:"application/json"})),m=await ge(t._options.security),_=me(m),g={options:t._options,base_url:(a=(o=r?.server_url)!==null&&o!==void 0?o:t._baseURL)!==null&&a!==void 0?a:"",operation_id:"DeleteTrigger",o_auth2_scopes:null,resolved_security:_,security_source:t._options.security,retry_config:r?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:r?.retry_codes||["408","409","429","5XX"]},E=t._createRequest(g,{security:_,method:"DELETE",baseURL:r?.server_url,path:p,headers:h,body:d,userAgent:t._options.user_agent,timeout_ms:r?.timeout_ms||t._options.timeout_ms||-1},r);if(!E.ok)return[E,{status:"invalid"}];let y=E.value,C=await t._do(y,{context:g,isErrorStatusCode:P=>ce({status:P},["4XX","5XX"]),retryConfig:g.retry_config,retryCodes:g.retry_codes});if(!C.ok)return[C,{status:"request-error",request:y}];let A=C.value,[I]=await he(ve(200),ee("4XX"),ee("5XX"))(A,y);return I.ok?[I,{status:"complete",request:y,response:A}]:[I,{status:"complete",request:y,response:A}]}function S_(t,e,n,r){return new se(ax(t,e,n,r))}async function ax(t,e,n,r){var i,o,a;let c={id:e,api_version:n},d=null,f={api_version:te("api_version",(i=c.api_version)!==null&&i!==void 0?i:t._options.api_version,{explode:!1,charEncoding:"percent"}),id:te("id",c.id,{explode:!1,charEncoding:"percent"})},p=de("/{api_version}/triggers/{id}")(f),h=new Headers(pe({Accept:"application/json"})),m=await ge(t._options.security),_=me(m),g={options:t._options,base_url:(a=(o=r?.server_url)!==null&&o!==void 0?o:t._baseURL)!==null&&a!==void 0?a:"",operation_id:"GetTrigger",o_auth2_scopes:null,resolved_security:_,security_source:t._options.security,retry_config:r?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:r?.retry_codes||["408","409","429","5XX"]},E=t._createRequest(g,{security:_,method:"GET",baseURL:r?.server_url,path:p,headers:h,body:d,userAgent:t._options.user_agent,timeout_ms:r?.timeout_ms||t._options.timeout_ms||-1},r);if(!E.ok)return[E,{status:"invalid"}];let y=E.value,C=await t._do(y,{context:g,isErrorStatusCode:P=>ce({status:P},["4XX","5XX"]),retryConfig:g.retry_config,retryCodes:g.retry_codes});if(!C.ok)return[C,{status:"request-error",request:y}];let A=C.value,[I]=await he(ve(200),ee("4XX"),ee("5XX"))(A,y);return I.ok?[I,{status:"complete",request:y,response:A}]:[I,{status:"complete",request:y,response:A}]}function I_(t,e,n,r,i,o){return new se(lx(t,e,n,r,i,o))}async function lx(t,e,n,r,i,o){var a,u,c;let f={trigger_id:e,api_version:n,page_size:r,page_token:i},p=null,h={api_version:te("api_version",(a=f.api_version)!==null&&a!==void 0?a:t._options.api_version,{explode:!1,charEncoding:"percent"}),trigger_id:te("trigger_id",f.trigger_id,{explode:!1,charEncoding:"percent"})},m=de("/{api_version}/triggers/{trigger_id}/executions")(h),_=hn({page_size:f.page_size,page_token:f.page_token}),g=new Headers(pe({Accept:"application/json"})),E=await ge(t._options.security),y=me(E),C={options:t._options,base_url:(c=(u=o?.server_url)!==null&&u!==void 0?u:t._baseURL)!==null&&c!==void 0?c:"",operation_id:"ListTriggerExecutions",o_auth2_scopes:null,resolved_security:y,security_source:t._options.security,retry_config:o?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:o?.retry_codes||["408","409","429","5XX"]},A=t._createRequest(C,{security:y,method:"GET",baseURL:o?.server_url,path:m,headers:g,query:_,body:p,userAgent:t._options.user_agent,timeout_ms:o?.timeout_ms||t._options.timeout_ms||-1},o);if(!A.ok)return[A,{status:"invalid"}];let I=A.value,P=await t._do(I,{context:C,isErrorStatusCode:B=>ce({status:B},["4XX","5XX"]),retryConfig:C.retry_config,retryCodes:C.retry_codes});if(!P.ok)return[P,{status:"request-error",request:I}];let G=P.value,[O]=await he(ve(200),ee("4XX"),ee("5XX"))(G,I);return O.ok?[O,{status:"complete",request:I,response:G}]:[O,{status:"complete",request:I,response:G}]}function w_(t,e,n,r,i,o){return new se(ux(t,e,n,r,i,o))}async function ux(t,e,n,r,i,o){var a,u,c;let f={api_version:e,filter:n,page_size:r,page_token:i},p=null,h={api_version:te("api_version",(a=f?.api_version)!==null&&a!==void 0?a:t._options.api_version,{explode:!1,charEncoding:"percent"})},m=de("/{api_version}/triggers")(h),_=hn({filter:f?.filter,page_size:f?.page_size,page_token:f?.page_token}),g=new Headers(pe({Accept:"application/json"})),E=await ge(t._options.security),y=me(E),C={options:t._options,base_url:(c=(u=o?.server_url)!==null&&u!==void 0?u:t._baseURL)!==null&&c!==void 0?c:"",operation_id:"ListTriggers",o_auth2_scopes:null,resolved_security:y,security_source:t._options.security,retry_config:o?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:o?.retry_codes||["408","409","429","5XX"]},A=t._createRequest(C,{security:y,method:"GET",baseURL:o?.server_url,path:m,headers:g,query:_,body:p,userAgent:t._options.user_agent,timeout_ms:o?.timeout_ms||t._options.timeout_ms||-1},o);if(!A.ok)return[A,{status:"invalid"}];let I=A.value,P=await t._do(I,{context:C,isErrorStatusCode:B=>ce({status:B},["4XX","5XX"]),retryConfig:C.retry_config,retryCodes:C.retry_codes});if(!P.ok)return[P,{status:"request-error",request:I}];let G=P.value,[O]=await he(ve(200),ee("4XX"),ee("5XX"))(G,I);return O.ok?[O,{status:"complete",request:I,response:G}]:[O,{status:"complete",request:I,response:G}]}function P_(t,e,n,r){return new se(cx(t,e,n,r))}async function cx(t,e,n,r){var i,o,a;let c={trigger_id:e,api_version:n},d=null,f={api_version:te("api_version",(i=c.api_version)!==null&&i!==void 0?i:t._options.api_version,{explode:!1,charEncoding:"percent"}),trigger_id:te("trigger_id",c.trigger_id,{explode:!1,charEncoding:"percent"})},p=de("/{api_version}/triggers/{trigger_id}/executions")(f),h=new Headers(pe({Accept:"application/json"})),m=await ge(t._options.security),_=me(m),g={options:t._options,base_url:(a=(o=r?.server_url)!==null&&o!==void 0?o:t._baseURL)!==null&&a!==void 0?a:"",operation_id:"RunTrigger",o_auth2_scopes:null,resolved_security:_,security_source:t._options.security,retry_config:r?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:r?.retry_codes||["408","409","429","5XX"]},E=t._createRequest(g,{security:_,method:"POST",baseURL:r?.server_url,path:p,headers:h,body:d,userAgent:t._options.user_agent,timeout_ms:r?.timeout_ms||t._options.timeout_ms||-1},r);if(!E.ok)return[E,{status:"invalid"}];let y=E.value,C=await t._do(y,{context:g,isErrorStatusCode:P=>ce({status:P},["4XX","5XX"]),retryConfig:g.retry_config,retryCodes:g.retry_codes});if(!C.ok)return[C,{status:"request-error",request:y}];let A=C.value,[I]=await he(ve(200),ee("4XX"),ee("5XX"))(A,y);return I.ok?[I,{status:"complete",request:y,response:A}]:[I,{status:"complete",request:y,response:A}]}function R_(t,e,n,r,i){return new se(dx(t,e,n,r,i))}async function dx(t,e,n,r,i){var o,a,u;let d={id:e,body:n,api_version:r},f=Gt("body",d.body,{explode:!0}),p={api_version:te("api_version",(o=d.api_version)!==null&&o!==void 0?o:t._options.api_version,{explode:!1,charEncoding:"percent"}),id:te("id",d.id,{explode:!1,charEncoding:"percent"})},h=de("/{api_version}/triggers/{id}")(p),m=new Headers(pe({"Content-Type":"application/json",Accept:"application/json"})),_=await ge(t._options.security),g=me(_),E={options:t._options,base_url:(u=(a=i?.server_url)!==null&&a!==void 0?a:t._baseURL)!==null&&u!==void 0?u:"",operation_id:"UpdateTrigger",o_auth2_scopes:null,resolved_security:g,security_source:t._options.security,retry_config:i?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:i?.retry_codes||["408","409","429","5XX"]},y=t._createRequest(E,{security:g,method:"PATCH",baseURL:i?.server_url,path:h,headers:m,body:f,userAgent:t._options.user_agent,timeout_ms:i?.timeout_ms||t._options.timeout_ms||-1},i);if(!y.ok)return[y,{status:"invalid"}];let C=y.value,A=await t._do(C,{context:E,isErrorStatusCode:G=>ce({status:G},["4XX","5XX"]),retryConfig:E.retry_config,retryCodes:E.retry_codes});if(!A.ok)return[A,{status:"request-error",request:C}];let I=A.value,[P]=await he(ve(200),ee("4XX"),ee("5XX"))(I,C);return P.ok?[P,{status:"complete",request:C,response:I}]:[P,{status:"complete",request:C,response:I}]}var Au=class extends Zt{create(e,n){let{api_version:r}=e,i=Ue(e,["api_version"]);return fe(A_(this,i,r,n))}list(e,n){return fe(w_(this,e?.api_version,e?.filter,e?.page_size,e?.page_token,n))}get(e,n,r){return fe(S_(this,e,n?.api_version,r))}update(e,n,r){let{api_version:i}=n,o=Ue(n,["api_version"]);return fe(R_(this,e,o,i,r))}delete(e,n,r){return fe(C_(this,e,n?.api_version,r))}run(e,n,r){return fe(P_(this,e,n?.api_version,r))}listExecutions(e,n,r){return fe(I_(this,e,n?.api_version,n?.page_size,n?.page_token,r))}};function N_(t,e,n,r){return new se(fx(t,e,n,r))}async function fx(t,e,n,r){var i,o,a;let c={body:e,api_version:n},d=Gt("body",c.body,{explode:!0}),f={api_version:te("api_version",(i=c.api_version)!==null&&i!==void 0?i:t._options.api_version,{explode:!1,charEncoding:"percent"})},p=de("/{api_version}/webhooks")(f),h=new Headers(pe({"Content-Type":"application/json",Accept:"application/json"})),m=await ge(t._options.security),_=me(m),g={options:t._options,base_url:(a=(o=r?.server_url)!==null&&o!==void 0?o:t._baseURL)!==null&&a!==void 0?a:"",operation_id:"CreateWebhook",o_auth2_scopes:null,resolved_security:_,security_source:t._options.security,retry_config:r?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:r?.retry_codes||["408","409","429","5XX"]},E=t._createRequest(g,{security:_,method:"POST",baseURL:r?.server_url,path:p,headers:h,body:d,userAgent:t._options.user_agent,timeout_ms:r?.timeout_ms||t._options.timeout_ms||-1},r);if(!E.ok)return[E,{status:"invalid"}];let y=E.value,C=await t._do(y,{context:g,isErrorStatusCode:P=>ce({status:P},["4XX","5XX"]),retryConfig:g.retry_config,retryCodes:g.retry_codes});if(!C.ok)return[C,{status:"request-error",request:y}];let A=C.value,[I]=await he(ee("4XX"),ee("5XX"),ve("default"))(A,y);return I.ok?[I,{status:"complete",request:y,response:A}]:[I,{status:"complete",request:y,response:A}]}function x_(t,e,n,r){return new se(px(t,e,n,r))}async function px(t,e,n,r){var i,o,a;let c={id:e,api_version:n},d=null,f={api_version:te("api_version",(i=c.api_version)!==null&&i!==void 0?i:t._options.api_version,{explode:!1,charEncoding:"percent"}),id:te("id",c.id,{explode:!1,charEncoding:"percent"})},p=de("/{api_version}/webhooks/{id}")(f),h=new Headers(pe({Accept:"application/json"})),m=await ge(t._options.security),_=me(m),g={options:t._options,base_url:(a=(o=r?.server_url)!==null&&o!==void 0?o:t._baseURL)!==null&&a!==void 0?a:"",operation_id:"DeleteWebhook",o_auth2_scopes:null,resolved_security:_,security_source:t._options.security,retry_config:r?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:r?.retry_codes||["408","409","429","5XX"]},E=t._createRequest(g,{security:_,method:"DELETE",baseURL:r?.server_url,path:p,headers:h,body:d,userAgent:t._options.user_agent,timeout_ms:r?.timeout_ms||t._options.timeout_ms||-1},r);if(!E.ok)return[E,{status:"invalid"}];let y=E.value,C=await t._do(y,{context:g,isErrorStatusCode:P=>ce({status:P},["4XX","5XX"]),retryConfig:g.retry_config,retryCodes:g.retry_codes});if(!C.ok)return[C,{status:"request-error",request:y}];let A=C.value,[I]=await he(ee("4XX"),ee("5XX"),ve("default"))(A,y);return I.ok?[I,{status:"complete",request:y,response:A}]:[I,{status:"complete",request:y,response:A}]}function k_(t,e,n,r){return new se(hx(t,e,n,r))}async function hx(t,e,n,r){var i,o,a;let c={id:e,api_version:n},d=null,f={api_version:te("api_version",(i=c.api_version)!==null&&i!==void 0?i:t._options.api_version,{explode:!1,charEncoding:"percent"}),id:te("id",c.id,{explode:!1,charEncoding:"percent"})},p=de("/{api_version}/webhooks/{id}")(f),h=new Headers(pe({Accept:"application/json"})),m=await ge(t._options.security),_=me(m),g={options:t._options,base_url:(a=(o=r?.server_url)!==null&&o!==void 0?o:t._baseURL)!==null&&a!==void 0?a:"",operation_id:"GetWebhook",o_auth2_scopes:null,resolved_security:_,security_source:t._options.security,retry_config:r?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:r?.retry_codes||["408","409","429","5XX"]},E=t._createRequest(g,{security:_,method:"GET",baseURL:r?.server_url,path:p,headers:h,body:d,userAgent:t._options.user_agent,timeout_ms:r?.timeout_ms||t._options.timeout_ms||-1},r);if(!E.ok)return[E,{status:"invalid"}];let y=E.value,C=await t._do(y,{context:g,isErrorStatusCode:P=>ce({status:P},["4XX","5XX"]),retryConfig:g.retry_config,retryCodes:g.retry_codes});if(!C.ok)return[C,{status:"request-error",request:y}];let A=C.value,[I]=await he(ee("4XX"),ee("5XX"),ve("default"))(A,y);return I.ok?[I,{status:"complete",request:y,response:A}]:[I,{status:"complete",request:y,response:A}]}function D_(t,e,n,r,i){return new se(mx(t,e,n,r,i))}async function mx(t,e,n,r,i){var o,a,u;let d={api_version:e,page_size:n,page_token:r},f=null,p={api_version:te("api_version",(o=d?.api_version)!==null&&o!==void 0?o:t._options.api_version,{explode:!1,charEncoding:"percent"})},h=de("/{api_version}/webhooks")(p),m=hn({page_size:d?.page_size,page_token:d?.page_token}),_=new Headers(pe({Accept:"application/json"})),g=await ge(t._options.security),E=me(g),y={options:t._options,base_url:(u=(a=i?.server_url)!==null&&a!==void 0?a:t._baseURL)!==null&&u!==void 0?u:"",operation_id:"ListWebhooks",o_auth2_scopes:null,resolved_security:E,security_source:t._options.security,retry_config:i?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:i?.retry_codes||["408","409","429","5XX"]},C=t._createRequest(y,{security:E,method:"GET",baseURL:i?.server_url,path:h,headers:_,query:m,body:f,userAgent:t._options.user_agent,timeout_ms:i?.timeout_ms||t._options.timeout_ms||-1},i);if(!C.ok)return[C,{status:"invalid"}];let A=C.value,I=await t._do(A,{context:y,isErrorStatusCode:O=>ce({status:O},["4XX","5XX"]),retryConfig:y.retry_config,retryCodes:y.retry_codes});if(!I.ok)return[I,{status:"request-error",request:A}];let P=I.value,[G]=await he(ee("4XX"),ee("5XX"),ve("default"))(P,A);return G.ok?[G,{status:"complete",request:A,response:P}]:[G,{status:"complete",request:A,response:P}]}function M_(t,e,n,r,i){return new se(gx(t,e,n,r,i))}async function gx(t,e,n,r,i){var o,a,u;let d={id:e,api_version:n,body:r},f=Gt("body",d.body,{explode:!0}),p={api_version:te("api_version",(o=d.api_version)!==null&&o!==void 0?o:t._options.api_version,{explode:!1,charEncoding:"percent"}),id:te("id",d.id,{explode:!1,charEncoding:"percent"})},h=de("/{api_version}/webhooks/{id}:ping")(p),m=new Headers(pe({"Content-Type":"application/json",Accept:"application/json"})),_=await ge(t._options.security),g=me(_),E={options:t._options,base_url:(u=(a=i?.server_url)!==null&&a!==void 0?a:t._baseURL)!==null&&u!==void 0?u:"",operation_id:"PingWebhook",o_auth2_scopes:null,resolved_security:g,security_source:t._options.security,retry_config:i?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:i?.retry_codes||["408","409","429","5XX"]},y=t._createRequest(E,{security:g,method:"POST",baseURL:i?.server_url,path:h,headers:m,body:f,userAgent:t._options.user_agent,timeout_ms:i?.timeout_ms||t._options.timeout_ms||-1},i);if(!y.ok)return[y,{status:"invalid"}];let C=y.value,A=await t._do(C,{context:E,isErrorStatusCode:G=>ce({status:G},["4XX","5XX"]),retryConfig:E.retry_config,retryCodes:E.retry_codes});if(!A.ok)return[A,{status:"request-error",request:C}];let I=A.value,[P]=await he(ee("4XX"),ee("5XX"),ve("default"))(I,C);return P.ok?[P,{status:"complete",request:C,response:I}]:[P,{status:"complete",request:C,response:I}]}function U_(t,e,n,r,i){return new se(_x(t,e,n,r,i))}async function _x(t,e,n,r,i){var o,a,u;let d={id:e,api_version:n,body:r},f=Gt("body",d.body,{explode:!0}),p={api_version:te("api_version",(o=d.api_version)!==null&&o!==void 0?o:t._options.api_version,{explode:!1,charEncoding:"percent"}),id:te("id",d.id,{explode:!1,charEncoding:"percent"})},h=de("/{api_version}/webhooks/{id}:rotateSigningSecret")(p),m=new Headers(pe({"Content-Type":"application/json",Accept:"application/json"})),_=await ge(t._options.security),g=me(_),E={options:t._options,base_url:(u=(a=i?.server_url)!==null&&a!==void 0?a:t._baseURL)!==null&&u!==void 0?u:"",operation_id:"RotateSigningSecret",o_auth2_scopes:null,resolved_security:g,security_source:t._options.security,retry_config:i?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:i?.retry_codes||["408","409","429","5XX"]},y=t._createRequest(E,{security:g,method:"POST",baseURL:i?.server_url,path:h,headers:m,body:f,userAgent:t._options.user_agent,timeout_ms:i?.timeout_ms||t._options.timeout_ms||-1},i);if(!y.ok)return[y,{status:"invalid"}];let C=y.value,A=await t._do(C,{context:E,isErrorStatusCode:G=>ce({status:G},["4XX","5XX"]),retryConfig:E.retry_config,retryCodes:E.retry_codes});if(!A.ok)return[A,{status:"request-error",request:C}];let I=A.value,[P]=await he(ee("4XX"),ee("5XX"),ve("default"))(I,C);return P.ok?[P,{status:"complete",request:C,response:I}]:[P,{status:"complete",request:C,response:I}]}function b_(t,e,n,r,i,o){return new se(yx(t,e,n,r,i,o))}async function yx(t,e,n,r,i,o){var a,u,c;let f={id:e,api_version:n,update_mask:r,body:i},p=Gt("body",f.body,{explode:!0}),h={api_version:te("api_version",(a=f.api_version)!==null&&a!==void 0?a:t._options.api_version,{explode:!1,charEncoding:"percent"}),id:te("id",f.id,{explode:!1,charEncoding:"percent"})},m=de("/{api_version}/webhooks/{id}")(h),_=hn({update_mask:f.update_mask}),g=new Headers(pe({"Content-Type":"application/json",Accept:"application/json"})),E=await ge(t._options.security),y=me(E),C={options:t._options,base_url:(c=(u=o?.server_url)!==null&&u!==void 0?u:t._baseURL)!==null&&c!==void 0?c:"",operation_id:"UpdateWebhook",o_auth2_scopes:null,resolved_security:y,security_source:t._options.security,retry_config:o?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:o?.retry_codes||["408","409","429","5XX"]},A=t._createRequest(C,{security:y,method:"PATCH",baseURL:o?.server_url,path:m,headers:g,query:_,body:p,userAgent:t._options.user_agent,timeout_ms:o?.timeout_ms||t._options.timeout_ms||-1},o);if(!A.ok)return[A,{status:"invalid"}];let I=A.value,P=await t._do(I,{context:C,isErrorStatusCode:B=>ce({status:B},["4XX","5XX"]),retryConfig:C.retry_config,retryCodes:C.retry_codes});if(!P.ok)return[P,{status:"request-error",request:I}];let G=P.value,[O]=await he(ee("4XX"),ee("5XX"),ve("default"))(G,I);return O.ok?[O,{status:"complete",request:I,response:G}]:[O,{status:"complete",request:I,response:G}]}var Cu=class extends Zt{create(e,n){let{api_version:r}=e,i=Ue(e,["api_version"]);return fe(N_(this,i,r,n))}list(e,n){return fe(D_(this,e?.api_version,e?.page_size,e?.page_token,n))}get(e,n,r){return fe(k_(this,e,n?.api_version,r))}update(e,n,r){let i=n??{},{api_version:o,update_mask:a}=i,u=Ue(i,["api_version","update_mask"]),c=n===void 0||Object.keys(u).length===0?void 0:u;return fe(b_(this,e,o,a,c,r))}delete(e,n,r){return fe(x_(this,e,n?.api_version,r))}rotateSigningSecret(e,n,r,i){return fe(U_(this,e,n,r,i))}ping(e,n,r,i){return fe(M_(this,e,n,r,i))}};var Ex=class extends Zt{get interactions(){var e;return(e=this._interactions)!==null&&e!==void 0?e:this._interactions=new Tu(this._options)}get webhooks(){var e;return(e=this._webhooks)!==null&&e!==void 0?e:this._webhooks=new Cu(this._options)}get agents(){var e;return(e=this._agents)!==null&&e!==void 0?e:this._agents=new du(this._options)}get triggers(){var e;return(e=this._triggers)!==null&&e!==void 0?e:this._triggers=new Au(this._options)}get environments(){var e;return(e=this._environments)!==null&&e!==void 0?e:this._environments=new fu(this._options)}};var vx=new Set(["lyria-3-pro-preview","lyria-3-clip-preview"]);function Tx(t){let e=t.getBaseUrl();if(!e)throw new Error("Base URL must be set.");return e.replace(/\/+$/,"")}function Ax(t){let e=Cx(t.getApiVersion()),n=t.getProject(),r=t.getLocation();return t.isVertexAI()&&e&&n&&r?`${e}/projects/${encodeURIComponent(n)}/locations/${encodeURIComponent(r)}`:e}function Ct(t,e={}){var n,r,i,o,a;return new Ex(Object.assign(Object.assign({},e),{api_version:(n=e.api_version)!==null&&n!==void 0?n:Ax(t),security:(r=e.security)!==null&&r!==void 0?r:new Yl({defaultHeaders:Object.assign(Object.assign({},(i=t.getDefaultHeaders)===null||i===void 0?void 0:i.call(t)),(o=t.getHeaders)===null||o===void 0?void 0:o.call(t)),getAuthHeaders:c=>t.getAuthHeaders(c)}),server_url:(a=e.server_url)!==null&&a!==void 0?a:Tx(t)}))}var Su=class{constructor(e){this.parentClient=e}async create(e,n){let{api_version:r}=e,i=Ue(e,["api_version"]);if(i.stream===!0){let a=await ll(()=>this.getClient(r).interactions.create(Object.assign(Object.assign({},i),{stream:!0,api_version:r}),ue(n,!0)));return lg(a)}let o=await Ee(v_(this.getClient(r),i,r,ue(n)));return ul(o)}async get(e,n={},r){let{api_version:i,stream:o=!1,last_event_id:a,include_input:u}=n??{};if(o===!0){let d=await ll(()=>this.getClient(i).interactions.get(e,{stream:o,last_event_id:a,include_input:u,api_version:i},ue(r,!0)));return lg(d)}let c=await Ee(T_(this.getClient(i),e,o,a,u,i,ue(r)));return ul(c)}async delete(e,n={},r){return ll(()=>this.getClient(n?.api_version).interactions.delete(e,{api_version:n?.api_version},ue(r)))}async cancel(e,n={},r){return ul(await Ee(E_(this.getClient(n?.api_version),e,n?.api_version,ue(r))))}getClient(e){var n;return e?Ct(this.parentClient,{api_version:e}):((n=this.sdk)!==null&&n!==void 0||(this.sdk=Ct(this.parentClient)),this.sdk)}},Iu=class{constructor(e){this.parentClient=e}async create(e={},n){let r=e??{},{api_version:i}=r,o=Ue(r,["api_version"]);return Ee(d_(this.getClient(i),o,i,ue(n)))}async list(e={},n){let{api_version:r,pageSize:i,pageToken:o,parent:a}=e??{};return Ee(h_(this.getClient(r),r,i,o,a,ue(n)))}async get(e,n={},r){return Ee(p_(this.getClient(n?.api_version),e,n?.api_version,ue(r)))}async delete(e,n={},r){return Ee(f_(this.getClient(n?.api_version),e,n?.api_version,ue(r)))}getClient(e){var n;return e?Ct(this.parentClient,{api_version:e}):((n=this.sdk)!==null&&n!==void 0||(this.sdk=Ct(this.parentClient)),this.sdk)}},wu=class{constructor(e){this.parentClient=e}async create(e,n){let{api_version:r}=e,i=Ue(e,["api_version"]);return Ee(N_(this.getClient(),i,r,ue(n)))}async list(e={},n){let{api_version:r,page_size:i,page_token:o}=e??{};return Ee(D_(this.getClient(),r,i,o,ue(n)))}async get(e,n={},r){return Ee(k_(this.getClient(),e,n?.api_version,ue(r)))}async update(e,n={},r){let i=n??{},{api_version:o,update_mask:a}=i,u=Ue(i,["api_version","update_mask"]);return Ee(b_(this.getClient(),e,o,a,u,ue(r)))}async delete(e,n={},r){return Ee(x_(this.getClient(),e,n?.api_version,ue(r)))}async rotateSigningSecret(e,n={},r){let i=n??{},{api_version:o}=i,a=Ue(i,["api_version"]);return Ee(U_(this.getClient(),e,o,a,ue(r)))}async ping(e,n=void 0,r){let{api_version:i,body:o}=n??{};return Ee(M_(this.getClient(),e,i,o,ue(r)))}getClient(){var e;return(e=this.sdk)!==null&&e!==void 0||(this.sdk=Ct(this.parentClient)),this.sdk}},Pu=class{constructor(e){this.parentClient=e}async create(e,n){let{api_version:r}=e,i=Ue(e,["api_version"]);return Ee(A_(this.getClient(r),i,r,ue(n)))}async list(e={},n){let{api_version:r,filter:i,pageSize:o,pageToken:a}=e??{};return Ee(w_(this.getClient(r),r,i,o,a,ue(n)))}async get(e,n={},r){return Ee(S_(this.getClient(n?.api_version),e,n?.api_version,ue(r)))}async update(e,n,r){let{api_version:i}=n,o=Ue(n,["api_version"]);return Ee(R_(this.getClient(i),e,o,i,ue(r)))}async delete(e,n={},r){return Ee(C_(this.getClient(n?.api_version),e,n?.api_version,ue(r)))}async run(e,n={},r){return Ee(P_(this.getClient(n?.api_version),e,n?.api_version,ue(r)))}async listExecutions(e,n={},r){let{api_version:i,pageSize:o,pageToken:a}=n??{};return Ee(I_(this.getClient(i),e,i,o,a,ue(r)))}getClient(e){var n;return e?Ct(this.parentClient,{api_version:e}):((n=this.sdk)!==null&&n!==void 0||(this.sdk=Ct(this.parentClient)),this.sdk)}};function Cx(t){return t.replace(/^\/+|\/+$/g,"")}function ue(t,e=!1){var n,r,i,o;if(!t&&!e)return;let a=t??{},{timeout:u,maxRetries:c,defaultBaseURL:d,query:f,body:p,fetchOptions:h}=a,m=Ue(a,["timeout","maxRetries","defaultBaseURL","query","body","fetchOptions"]),_=Object.assign({},m);So(f)?_.extra_query=f:ag("query",f),So(p)?_.extra_body=p:ag("body",p);let g=(n=m.fetch_options)!==null&&n!==void 0?n:h;g&&(_.fetch_options=g);let E=(r=m.server_url)!==null&&r!==void 0?r:d;E&&(_.server_url=E);let y=(i=m.timeout_ms)!==null&&i!==void 0?i:u;if(y!==void 0&&(_.timeout_ms=y),c!==void 0&&(_.retries={strategy:"attempt-count-backoff",retryConnectionErrors:!0,maxRetries:c}),e){let C=new Headers((o=_.headers)!==null&&o!==void 0?o:g?.headers);C.set("Accept","text/event-stream"),_.headers=C}return _}function ag(t,e){e!=null&&console.warn(`GoogleGenAI.interactions: request option ${t} is not supported by the Google GenAI interactions bridge and will be ignored.`)}async function Ee(t){let[e,n]=await t.$inspect();if(!e.ok)throw Jn(e.error);return Sx(e.value,n)}async function ll(t){try{return await t()}catch(e){throw Jn(e)}}function lg(t){let e=t;return new Proxy(t,{get(n,r){if(r!==Symbol.asyncIterator){let i=Reflect.get(n,r,n);return typeof i=="function"?i.bind(n):i}return function(){let o=e[Symbol.asyncIterator]();return{async next(...a){try{return await o.next(...a)}catch(u){throw Jn(u)}},async return(a){if(!o.return)return{done:!0,value:a};try{return await o.return(a)}catch(u){throw Jn(u)}},async throw(a){if(!o.throw)throw Jn(a);try{return await o.throw(a)}catch(u){throw Jn(u)}},[Symbol.asyncIterator](){return this}}}}})}function Sx(t,e){return!So(t)||e.status!=="complete"?t:Object.assign(Object.assign({},t),{sdkHttpResponse:Ix(e.response,t)})}function Ix(t,e){let n={};for(let[r,i]of t.headers.entries())n[r]=i;return{headers:n,responseInternal:t,json:async()=>e}}function ul(t){let e=wx(t);return e?Rx(e):t}function wx(t){if(So(t)){if(Array.isArray(t.steps))return t;if(Px(t)){let e=t.outputs;if(Array.isArray(e)){let{outputs:n}=t,r=Ue(t,["outputs"]);return Object.assign(Object.assign({},r),{steps:[{type:"model_output",content:e}]})}}return Object.assign(Object.assign({},t),{steps:[]})}}function Px(t){let e=t.model;return typeof e=="string"&&vx.has(e)}function So(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Rx(t){var e,n;let r=Nx(t),i=(e=r.steps)!==null&&e!==void 0?e:[],o=[],a=!1;e:for(let p=i.length-1;p>=0;p--){let h=i[p];if(h.type==="user_input")break;if(h.type!=="model_output"||!h.content){if(a)break;continue}let m=h.content;for(let _=m.length-1;_>=0;_--){let g=m[_];if(g.type==="text")a=!0,o.push((n=g.text)!==null&&n!==void 0?n:"");else if(a)break e}}let u,c,d;for(let p=i.length-1;p>=0;p--){let h=i[p];if(h.type==="user_input")break;if(h.type==="model_output"&&h.content)for(let m=h.content.length-1;m>=0;m--){let _=h.content[m];_.type==="image"&&!u&&(u=_),_.type==="audio"&&!c&&(c=_),_.type==="video"&&!d&&(d=_)}}let f=o.reverse().join("");return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},r),f&&{output_text:f}),u?{output_image:u}:{}),c?{output_audio:c}:{}),d?{output_video:d}:{})}function Nx(t){return Object.assign(Object.assign({},t),{created:ug(t.created),updated:ug(t.updated)})}function ug(t){return t instanceof Date?t.toISOString():t}var Ru=class{constructor(e){this.parentClient=e}async create(e,n){let{api_version:r}=e,i=Ue(e,["api_version"]);return Ee(m_(this.getClient(r),i,r,ue(n)))}async list(e={},n){let{api_version:r,page_size:i,page_token:o}=e??{};return Ee(y_(this.getClient(r),r,i,o,ue(n)))}async get(e,n={},r){return Ee(__(this.getClient(n?.api_version),e,n?.api_version,ue(r)))}async delete(e,n={},r){return Ee(g_(this.getClient(n?.api_version),e,n?.api_version,ue(r)))}getClient(e){var n;return e?Ct(this.parentClient,{api_version:e}):((n=this.sdk)!==null&&n!==void 0||(this.sdk=Ct(this.parentClient)),this.sdk)}};var cg="x-goog-api-key",wr="https://www.googleapis.com/auth/cloud-platform",Nu=class{constructor(e){if(e.apiKey!==void 0){this.apiKey=e.apiKey;return}let n=xx(e.googleAuthOptions);this.googleAuth=new hg.GoogleAuth(n)}async addAuthHeaders(e,n){if(this.apiKey!==void 0){if(this.apiKey.startsWith("auth_tokens/"))throw new Error("Ephemeral tokens are only supported by the live API.");this.addKeyHeader(e);return}return this.addGoogleAuthHeaders(e,n)}addKeyHeader(e){if(e.get(cg)===null){if(this.apiKey===void 0)throw new Error("Trying to set API key header but apiKey is not set");e.append(cg,this.apiKey)}}async addGoogleAuthHeaders(e,n){if(this.googleAuth===void 0)throw new Error("Trying to set google-auth headers but googleAuth is unset");let r=await this.googleAuth.getRequestHeaders(n);for(let[i,o]of r)e.get(i)===null&&e.append(i,o)}};function xx(t){let e;if(t){if(e=t,e.scopes){if(typeof e.scopes=="string"&&e.scopes!==wr||Array.isArray(e.scopes)&&e.scopes.indexOf(wr)<0)throw new Error(`Invalid auth scopes. Scopes must include: ${wr}`)}else return e.scopes=[wr],e;return e}else return e={scopes:[wr]},e}var xu=class{async download(e,n){if(e.downloadPath){let r=await kx(e,n);if(r instanceof Kt){let i=JC(e.downloadPath);XC.fromWeb(r.responseInternal.body).pipe(i),await KC(i)}else try{await WC(e.downloadPath,r,{encoding:"base64"})}catch(i){throw new Error(`Failed to write file to ${e.downloadPath}: ${i}`)}}}};async function kx(t,e){var n,r,i;let o=$u(t.file);if(o!==void 0)return await e.request({path:`files/${o}:download`,httpMethod:"GET",queryParams:{alt:"media"},httpOptions:(n=t.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=t.config)===null||r===void 0?void 0:r.abortSignal});if(Ig(t.file)){let a=(i=t.file.video)===null||i===void 0?void 0:i.videoBytes;if(typeof a=="string")return a;throw new Error("Failed to download generated video, Uri or videoBytes not found.")}else if(wg(t.file)){let a=t.file.videoBytes;if(typeof a=="string")return a;throw new Error("Failed to download video, Uri or videoBytes not found.")}else throw new Error("Unsupported file type")}var ku=class{create(e,n,r){return new Du(e,n,r)}},Du=class{constructor(e,n,r){this.url=e,this.headers=n,this.callbacks=r}connect(){this.ws=new sl.default(this.url,{headers:this.headers}),this.ws.onopen=this.callbacks.onopen,this.ws.onerror=this.callbacks.onerror,this.ws.onclose=this.callbacks.onclose,this.ws.onmessage=this.callbacks.onmessage}send(e){if(this.ws===void 0)throw new Error("WebSocket is not connected");this.ws.send(e)}close(){if(this.ws===void 0)throw new Error("WebSocket is not connected");this.ws.close()}};function Dx(t,e){let n={},r=s(t,["name"]);return r!=null&&l(n,["_url","name"],r),n}function Mx(t,e){let n={},r=s(t,["name"]);return r!=null&&l(n,["_url","name"],r),n}function Ux(t,e){let n={},r=s(t,["sdkHttpResponse"]);return r!=null&&l(n,["sdkHttpResponse"],r),n}function bx(t,e){let n={},r=s(t,["sdkHttpResponse"]);return r!=null&&l(n,["sdkHttpResponse"],r),n}function Gx(t,e){let n={},r=s(t,["outcome"]);r!=null&&l(n,["outcome"],r);let i=s(t,["output"]);if(i!=null&&l(n,["output"],i),s(t,["id"])!==void 0)throw new Error("id parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return n}function Mu(t,e){let n={},r=s(t,["parts"]);if(r!=null){let o=r;Array.isArray(o)&&(o=o.map(a=>zx(a))),l(n,["parts"],o)}let i=s(t,["role"]);return i!=null&&l(n,["role"],i),n}function Lx(t,e,n){let r={};if(s(t,["validationDataset"])!==void 0)throw new Error("validationDataset parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let i=s(t,["tunedModelDisplayName"]);if(e!==void 0&&i!=null&&l(e,["displayName"],i),s(t,["description"])!==void 0)throw new Error("description parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let o=s(t,["epochCount"]);e!==void 0&&o!=null&&l(e,["tuningTask","hyperparameters","epochCount"],o);let a=s(t,["learningRateMultiplier"]);if(a!=null&&l(r,["tuningTask","hyperparameters","learningRateMultiplier"],a),s(t,["exportLastCheckpointOnly"])!==void 0)throw new Error("exportLastCheckpointOnly parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["preTunedModelCheckpointId"])!==void 0)throw new Error("preTunedModelCheckpointId parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["adapterSize"])!==void 0)throw new Error("adapterSize parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["tuningMode"])!==void 0)throw new Error("tuningMode parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["customBaseModel"])!==void 0)throw new Error("customBaseModel parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let u=s(t,["batchSize"]);e!==void 0&&u!=null&&l(e,["tuningTask","hyperparameters","batchSize"],u);let c=s(t,["learningRate"]);if(e!==void 0&&c!=null&&l(e,["tuningTask","hyperparameters","learningRate"],c),s(t,["labels"])!==void 0)throw new Error("labels parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["beta"])!==void 0)throw new Error("beta parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["baseTeacherModel"])!==void 0)throw new Error("baseTeacherModel parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["tunedTeacherModelSource"])!==void 0)throw new Error("tunedTeacherModelSource parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["sftLossWeightMultiplier"])!==void 0)throw new Error("sftLossWeightMultiplier parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["outputUri"])!==void 0)throw new Error("outputUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["rewardConfig"])!==void 0)throw new Error("rewardConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["compositeRewardConfig"])!==void 0)throw new Error("compositeRewardConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["samplesPerPrompt"])!==void 0)throw new Error("samplesPerPrompt parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["evaluateInterval"])!==void 0)throw new Error("evaluateInterval parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["checkpointInterval"])!==void 0)throw new Error("checkpointInterval parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["maxOutputTokens"])!==void 0)throw new Error("maxOutputTokens parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["thinkingLevel"])!==void 0)throw new Error("thinkingLevel parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["validationDatasetUri"])!==void 0)throw new Error("validationDatasetUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["encryptionSpec"])!==void 0)throw new Error("encryptionSpec parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return r}function Ox(t,e,n){let r={},i=s(n,["config","method"]);if(i===void 0&&(i="SUPERVISED_FINE_TUNING"),i==="SUPERVISED_FINE_TUNING"){let D=s(t,["validationDataset"]);e!==void 0&&D!=null&&l(e,["supervisedTuningSpec"],ji(D))}else if(i==="PREFERENCE_TUNING"){let D=s(t,["validationDataset"]);e!==void 0&&D!=null&&l(e,["preferenceOptimizationSpec"],ji(D))}else if(i==="DISTILLATION"){let D=s(t,["validationDataset"]);e!==void 0&&D!=null&&l(e,["distillationSpec"],ji(D))}else if(i==="REINFORCEMENT_TUNING"){let D=s(t,["validationDataset"]);e!==void 0&&D!=null&&l(e,["reinforcementTuningSpec"],ji(D))}let o=s(t,["tunedModelDisplayName"]);e!==void 0&&o!=null&&l(e,["tunedModelDisplayName"],o);let a=s(t,["description"]);e!==void 0&&a!=null&&l(e,["description"],a);let u=s(n,["config","method"]);if(u===void 0&&(u="SUPERVISED_FINE_TUNING"),u==="SUPERVISED_FINE_TUNING"){let D=s(t,["epochCount"]);e!==void 0&&D!=null&&l(e,["supervisedTuningSpec","hyperParameters","epochCount"],D)}else if(u==="PREFERENCE_TUNING"){let D=s(t,["epochCount"]);e!==void 0&&D!=null&&l(e,["preferenceOptimizationSpec","hyperParameters","epochCount"],D)}else if(u==="DISTILLATION"){let D=s(t,["epochCount"]);e!==void 0&&D!=null&&l(e,["distillationSpec","hyperParameters","epochCount"],D)}else if(u==="REINFORCEMENT_TUNING"){let D=s(t,["epochCount"]);e!==void 0&&D!=null&&l(e,["reinforcementTuningSpec","hyperParameters","epochCount"],D)}let c=s(n,["config","method"]);if(c===void 0&&(c="SUPERVISED_FINE_TUNING"),c==="SUPERVISED_FINE_TUNING"){let D=s(t,["learningRateMultiplier"]);e!==void 0&&D!=null&&l(e,["supervisedTuningSpec","hyperParameters","learningRateMultiplier"],D)}else if(c==="PREFERENCE_TUNING"){let D=s(t,["learningRateMultiplier"]);e!==void 0&&D!=null&&l(e,["preferenceOptimizationSpec","hyperParameters","learningRateMultiplier"],D)}else if(c==="DISTILLATION"){let D=s(t,["learningRateMultiplier"]);e!==void 0&&D!=null&&l(e,["distillationSpec","hyperParameters","learningRateMultiplier"],D)}else if(c==="REINFORCEMENT_TUNING"){let D=s(t,["learningRateMultiplier"]);e!==void 0&&D!=null&&l(e,["reinforcementTuningSpec","hyperParameters","learningRateMultiplier"],D)}let d=s(n,["config","method"]);if(d===void 0&&(d="SUPERVISED_FINE_TUNING"),d==="SUPERVISED_FINE_TUNING"){let D=s(t,["exportLastCheckpointOnly"]);e!==void 0&&D!=null&&l(e,["supervisedTuningSpec","exportLastCheckpointOnly"],D)}else if(d==="PREFERENCE_TUNING"){let D=s(t,["exportLastCheckpointOnly"]);e!==void 0&&D!=null&&l(e,["preferenceOptimizationSpec","exportLastCheckpointOnly"],D)}else if(d==="DISTILLATION"){let D=s(t,["exportLastCheckpointOnly"]);e!==void 0&&D!=null&&l(e,["distillationSpec","exportLastCheckpointOnly"],D)}let f=s(n,["config","method"]);if(f===void 0&&(f="SUPERVISED_FINE_TUNING"),f==="SUPERVISED_FINE_TUNING"){let D=s(t,["adapterSize"]);e!==void 0&&D!=null&&l(e,["supervisedTuningSpec","hyperParameters","adapterSize"],D)}else if(f==="PREFERENCE_TUNING"){let D=s(t,["adapterSize"]);e!==void 0&&D!=null&&l(e,["preferenceOptimizationSpec","hyperParameters","adapterSize"],D)}else if(f==="DISTILLATION"){let D=s(t,["adapterSize"]);e!==void 0&&D!=null&&l(e,["distillationSpec","hyperParameters","adapterSize"],D)}else if(f==="REINFORCEMENT_TUNING"){let D=s(t,["adapterSize"]);e!==void 0&&D!=null&&l(e,["reinforcementTuningSpec","hyperParameters","adapterSize"],D)}let p=s(n,["config","method"]);if(p===void 0&&(p="SUPERVISED_FINE_TUNING"),p==="SUPERVISED_FINE_TUNING"){let D=s(t,["tuningMode"]);e!==void 0&&D!=null&&l(e,["supervisedTuningSpec","tuningMode"],D)}else if(p==="DISTILLATION"){let D=s(t,["tuningMode"]);e!==void 0&&D!=null&&l(e,["distillationSpec","tuningMode"],D)}let h=s(t,["customBaseModel"]);e!==void 0&&h!=null&&l(e,["customBaseModel"],h);let m=s(n,["config","method"]);if(m===void 0&&(m="SUPERVISED_FINE_TUNING"),m==="SUPERVISED_FINE_TUNING"){let D=s(t,["batchSize"]);e!==void 0&&D!=null&&l(e,["supervisedTuningSpec","hyperParameters","batchSize"],D)}else if(m==="DISTILLATION"){let D=s(t,["batchSize"]);e!==void 0&&D!=null&&l(e,["distillationSpec","hyperParameters","batchSize"],D)}else if(m==="REINFORCEMENT_TUNING"){let D=s(t,["batchSize"]);e!==void 0&&D!=null&&l(e,["reinforcementTuningSpec","hyperParameters","batchSize"],D)}let _=s(n,["config","method"]);if(_===void 0&&(_="SUPERVISED_FINE_TUNING"),_==="SUPERVISED_FINE_TUNING"){let D=s(t,["learningRate"]);e!==void 0&&D!=null&&l(e,["supervisedTuningSpec","hyperParameters","learningRate"],D)}else if(_==="DISTILLATION"){let D=s(t,["learningRate"]);e!==void 0&&D!=null&&l(e,["distillationSpec","hyperParameters","learningRate"],D)}let g=s(t,["labels"]);e!==void 0&&g!=null&&l(e,["labels"],g);let E=s(t,["beta"]);e!==void 0&&E!=null&&l(e,["preferenceOptimizationSpec","hyperParameters","beta"],E);let y=s(t,["baseTeacherModel"]);e!==void 0&&y!=null&&l(e,["distillationSpec","baseTeacherModel"],y);let C=s(t,["tunedTeacherModelSource"]);e!==void 0&&C!=null&&l(e,["distillationSpec","tunedTeacherModelSource"],C);let A=s(t,["sftLossWeightMultiplier"]);e!==void 0&&A!=null&&l(e,["distillationSpec","hyperParameters","sftLossWeightMultiplier"],A);let I=s(t,["outputUri"]);e!==void 0&&I!=null&&l(e,["outputUri"],I);let P=s(t,["rewardConfig"]);e!==void 0&&P!=null&&l(e,["reinforcementTuningSpec","singleRewardConfig"],P);let G=s(t,["compositeRewardConfig"]);e!==void 0&&G!=null&&l(e,["reinforcementTuningSpec","compositeRewardConfig"],G);let O=s(t,["samplesPerPrompt"]);e!==void 0&&O!=null&&l(e,["reinforcementTuningSpec","hyperParameters","samplesPerPrompt"],O);let B=s(t,["evaluateInterval"]);e!==void 0&&B!=null&&l(e,["reinforcementTuningSpec","hyperParameters","evaluateInterval"],B);let k=s(t,["checkpointInterval"]);e!==void 0&&k!=null&&l(e,["reinforcementTuningSpec","hyperParameters","checkpointInterval"],k);let V=s(t,["maxOutputTokens"]);e!==void 0&&V!=null&&l(e,["reinforcementTuningSpec","hyperParameters","maxOutputTokens"],V);let X=s(t,["thinkingLevel"]);e!==void 0&&X!=null&&l(e,["reinforcementTuningSpec","hyperParameters","thinkingLevel"],X);let Z=s(t,["validationDatasetUri"]);e!==void 0&&Z!=null&&l(e,["reinforcementTuningSpec","validationDatasetUri"],Z);let ne=s(t,["encryptionSpec"]);return e!==void 0&&ne!=null&&l(e,["encryptionSpec"],ne),r}function qx(t,e){let n={},r=s(t,["baseModel"]);r!=null&&l(n,["baseModel"],r);let i=s(t,["preTunedModel"]);i!=null&&l(n,["preTunedModel"],i);let o=s(t,["trainingDataset"]);o!=null&&jx(o);let a=s(t,["config"]);return a!=null&&Lx(a,n),n}function Fx(t,e){let n={},r=s(t,["baseModel"]);r!=null&&l(n,["baseModel"],r);let i=s(t,["preTunedModel"]);i!=null&&l(n,["preTunedModel"],i);let o=s(t,["trainingDataset"]);o!=null&&ek(o,n,e);let a=s(t,["config"]);return a!=null&&Ox(a,n,e),n}function G_(t,e){let n={},r=s(t,["epochCount"]);r!=null&&l(n,["epochCount"],r);let i=s(t,["learningRateMultiplier"]);i!=null&&l(n,["learningRateMultiplier"],i);let o=s(t,["adapterSize"]);o!=null&&l(n,["adapterSize"],o);let a=s(t,["batchSize"]);a!=null&&l(n,["batchSize"],a);let u=s(t,["learningRate"]);u!=null&&l(n,["learningRate"],u);let c=s(t,["generationConfig"]);return c!=null&&l(n,["generationConfig"],$x(c)),n}function Bx(t,e){let n={},r=s(t,["promptDatasetUri"]);r!=null&&l(n,["promptDatasetUri"],r);let i=s(t,["validationDatasetUri"]);i!=null&&l(n,["validationDatasetUri"],i);let o=s(t,["baseTeacherModel"]);o!=null&&l(n,["baseTeacherModel"],o);let a=s(t,["tunedTeacherModelSource"]);a!=null&&l(n,["tunedTeacherModelSource"],a);let u=s(t,["hyperparameters"]);return u!=null&&l(n,["hyperparameters"],G_(u)),n}function Hx(t,e){let n={},r=s(t,["baseTeacherModel"]);r!=null&&l(n,["baseTeacherModel"],r);let i=s(t,["hyperParameters"]);i!=null&&l(n,["hyperParameters"],G_(i));let o=s(t,["pipelineRootDirectory"]);o!=null&&l(n,["pipelineRootDirectory"],o);let a=s(t,["promptDatasetUri"]);a!=null&&l(n,["promptDatasetUri"],a);let u=s(t,["studentModel"]);u!=null&&l(n,["studentModel"],u);let c=s(t,["trainingDatasetUri"]);c!=null&&l(n,["trainingDatasetUri"],c);let d=s(t,["tunedTeacherModelSource"]);d!=null&&l(n,["tunedTeacherModelSource"],d);let f=s(t,["tuningMode"]);f!=null&&l(n,["tuningMode"],f);let p=s(t,["validationDatasetUri"]);return p!=null&&l(n,["validationDatasetUri"],p),n}function Vx(t,e){let n={},r=s(t,["code"]);r!=null&&l(n,["code"],r);let i=s(t,["language"]);if(i!=null&&l(n,["language"],i),s(t,["id"])!==void 0)throw new Error("id parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return n}function $x(t,e){let n={},r=s(t,["modelConfig"]);r!=null&&l(n,["modelSelectionConfig"],r);let i=s(t,["responseJsonSchema"]);i!=null&&l(n,["responseJsonSchema"],i);let o=s(t,["audioTranscriptionConfig"]);o!=null&&l(n,["audioTranscriptionConfig"],o);let a=s(t,["audioTimestamp"]);a!=null&&l(n,["audioTimestamp"],a);let u=s(t,["candidateCount"]);u!=null&&l(n,["candidateCount"],u);let c=s(t,["enableAffectiveDialog"]);c!=null&&l(n,["enableAffectiveDialog"],c);let d=s(t,["frequencyPenalty"]);d!=null&&l(n,["frequencyPenalty"],d);let f=s(t,["logprobs"]);f!=null&&l(n,["logprobs"],f);let p=s(t,["maxOutputTokens"]);p!=null&&l(n,["maxOutputTokens"],p);let h=s(t,["mediaResolution"]);h!=null&&l(n,["mediaResolution"],h);let m=s(t,["presencePenalty"]);m!=null&&l(n,["presencePenalty"],m);let _=s(t,["responseFormat"]);if(_!=null){let X=_;Array.isArray(X)&&(X=X.map(Z=>Z)),l(n,["responseFormat"],X)}let g=s(t,["responseLogprobs"]);g!=null&&l(n,["responseLogprobs"],g);let E=s(t,["responseMimeType"]);E!=null&&l(n,["responseMimeType"],E);let y=s(t,["responseModalities"]);y!=null&&l(n,["responseModalities"],y);let C=s(t,["responseSchema"]);C!=null&&l(n,["responseSchema"],C);let A=s(t,["routingConfig"]);A!=null&&l(n,["routingConfig"],A);let I=s(t,["seed"]);I!=null&&l(n,["seed"],I);let P=s(t,["speechConfig"]);P!=null&&l(n,["speechConfig"],P);let G=s(t,["stopSequences"]);G!=null&&l(n,["stopSequences"],G);let O=s(t,["temperature"]);O!=null&&l(n,["temperature"],O);let B=s(t,["thinkingConfig"]);B!=null&&l(n,["thinkingConfig"],B);let k=s(t,["topK"]);k!=null&&l(n,["topK"],k);let V=s(t,["topP"]);return V!=null&&l(n,["topP"],V),n}function Jx(t,e){let n={},r=s(t,["name"]);return r!=null&&l(n,["_url","name"],r),n}function Wx(t,e){let n={},r=s(t,["name"]);return r!=null&&l(n,["_url","name"],r),n}function Xx(t,e,n){let r={},i=s(t,["pageSize"]);e!==void 0&&i!=null&&l(e,["_query","pageSize"],i);let o=s(t,["pageToken"]);e!==void 0&&o!=null&&l(e,["_query","pageToken"],o);let a=s(t,["filter"]);return e!==void 0&&a!=null&&l(e,["_query","filter"],a),r}function Kx(t,e){let n={},r=s(t,["config"]);return r!=null&&Xx(r,n),n}function Yx(t,e){let n={},r=s(t,["sdkHttpResponse"]);r!=null&&l(n,["sdkHttpResponse"],r);let i=s(t,["nextPageToken"]);i!=null&&l(n,["nextPageToken"],i);let o=s(t,["tuningJobs"]);if(o!=null){let a=o;Array.isArray(a)&&(a=a.map(u=>Uu(u))),l(n,["tuningJobs"],a)}return n}function zx(t,e){let n={},r=s(t,["mediaResolution"]);if(r!=null&&l(n,["mediaResolution"],r),s(t,["toolCall"])!==void 0)throw new Error("toolCall parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(s(t,["toolResponse"])!==void 0)throw new Error("toolResponse parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");let i=s(t,["audioTranscription"]);i!=null&&l(n,["audioTranscription"],i);let o=s(t,["codeExecutionResult"]);o!=null&&l(n,["codeExecutionResult"],Gx(o));let a=s(t,["executableCode"]);a!=null&&l(n,["executableCode"],Vx(a));let u=s(t,["fileData"]);u!=null&&l(n,["fileData"],u);let c=s(t,["functionCall"]);c!=null&&l(n,["functionCall"],c);let d=s(t,["functionResponse"]);d!=null&&l(n,["functionResponse"],d);let f=s(t,["inlineData"]);f!=null&&l(n,["inlineData"],f);let p=s(t,["text"]);p!=null&&l(n,["text"],p);let h=s(t,["thought"]);h!=null&&l(n,["thought"],h);let m=s(t,["thoughtSignature"]);m!=null&&l(n,["thoughtSignature"],m);let _=s(t,["videoMetadata"]);if(_!=null&&l(n,["videoMetadata"],_),s(t,["partMetadata"])!==void 0)throw new Error("partMetadata parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return n}function Qx(t,e){let n={},r=s(t,["references"]);r!=null&&l(n,["references"],r);let i=s(t,["contents"]);if(i!=null){let a=i;Array.isArray(a)&&(a=a.map(u=>Mu(u))),l(n,["contents"],a)}let o=s(t,["systemInstruction"]);return o!=null&&l(n,["systemInstruction"],Mu(o)),n}function Zx(t,e){let n={},r=s(t,["name"]);r!=null&&l(n,["model"],r);let i=s(t,["name"]);return i!=null&&l(n,["endpoint"],i),n}function jx(t,e){let n={};if(s(t,["gcsUri"])!==void 0)throw new Error("gcsUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["vertexDatasetResource"])!==void 0)throw new Error("vertexDatasetResource parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let r=s(t,["examples"]);if(r!=null){let i=r;Array.isArray(i)&&(i=i.map(o=>o)),l(n,["examples","examples"],i)}return n}function ek(t,e,n){let r={},i=s(n,["config","method"]);if(i===void 0&&(i="SUPERVISED_FINE_TUNING"),i==="SUPERVISED_FINE_TUNING"){let a=s(t,["gcsUri"]);e!==void 0&&a!=null&&l(e,["supervisedTuningSpec","trainingDatasetUri"],a)}else if(i==="PREFERENCE_TUNING"){let a=s(t,["gcsUri"]);e!==void 0&&a!=null&&l(e,["preferenceOptimizationSpec","trainingDatasetUri"],a)}else if(i==="DISTILLATION"){let a=s(t,["gcsUri"]);e!==void 0&&a!=null&&l(e,["distillationSpec","promptDatasetUri"],a)}else if(i==="REINFORCEMENT_TUNING"){let a=s(t,["gcsUri"]);e!==void 0&&a!=null&&l(e,["reinforcementTuningSpec","trainingDatasetUri"],a)}let o=s(n,["config","method"]);if(o===void 0&&(o="SUPERVISED_FINE_TUNING"),o==="SUPERVISED_FINE_TUNING"){let a=s(t,["vertexDatasetResource"]);e!==void 0&&a!=null&&l(e,["supervisedTuningSpec","trainingDatasetUri"],a)}else if(o==="PREFERENCE_TUNING"){let a=s(t,["vertexDatasetResource"]);e!==void 0&&a!=null&&l(e,["preferenceOptimizationSpec","trainingDatasetUri"],a)}else if(o==="DISTILLATION"){let a=s(t,["vertexDatasetResource"]);e!==void 0&&a!=null&&l(e,["distillationSpec","promptDatasetUri"],a)}else if(o==="REINFORCEMENT_TUNING"){let a=s(t,["vertexDatasetResource"]);e!==void 0&&a!=null&&l(e,["reinforcementTuningSpec","trainingDatasetUri"],a)}if(s(t,["examples"])!==void 0)throw new Error("examples parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return r}function tk(t,e){let n={},r=s(t,["sdkHttpResponse"]);r!=null&&l(n,["sdkHttpResponse"],r);let i=s(t,["name"]);i!=null&&l(n,["name"],i);let o=s(t,["state"]);o!=null&&l(n,["state"],Sg(o));let a=s(t,["createTime"]);a!=null&&l(n,["createTime"],a);let u=s(t,["tuningTask","startTime"]);u!=null&&l(n,["startTime"],u);let c=s(t,["tuningTask","completeTime"]);c!=null&&l(n,["endTime"],c);let d=s(t,["updateTime"]);d!=null&&l(n,["updateTime"],d);let f=s(t,["description"]);f!=null&&l(n,["description"],f);let p=s(t,["baseModel"]);p!=null&&l(n,["baseModel"],p);let h=s(t,["_self"]);return h!=null&&l(n,["tunedModel"],Zx(h)),n}function Uu(t,e){let n={},r=s(t,["sdkHttpResponse"]);r!=null&&l(n,["sdkHttpResponse"],r);let i=s(t,["name"]);i!=null&&l(n,["name"],i);let o=s(t,["state"]);o!=null&&l(n,["state"],Sg(o));let a=s(t,["createTime"]);a!=null&&l(n,["createTime"],a);let u=s(t,["startTime"]);u!=null&&l(n,["startTime"],u);let c=s(t,["endTime"]);c!=null&&l(n,["endTime"],c);let d=s(t,["updateTime"]);d!=null&&l(n,["updateTime"],d);let f=s(t,["error"]);f!=null&&l(n,["error"],f);let p=s(t,["description"]);p!=null&&l(n,["description"],p);let h=s(t,["baseModel"]);h!=null&&l(n,["baseModel"],h);let m=s(t,["tunedModel"]);m!=null&&l(n,["tunedModel"],m);let _=s(t,["preTunedModel"]);_!=null&&l(n,["preTunedModel"],_);let g=s(t,["supervisedTuningSpec"]);g!=null&&l(n,["supervisedTuningSpec"],g);let E=s(t,["preferenceOptimizationSpec"]);E!=null&&l(n,["preferenceOptimizationSpec"],E);let y=s(t,["distillationSamplingSpec"]);y!=null&&l(n,["distillationSamplingSpec"],Bx(y));let C=s(t,["distillationSpec"]);C!=null&&l(n,["distillationSpec"],Hx(C));let A=s(t,["reinforcementTuningSpec"]);A!=null&&l(n,["reinforcementTuningSpec"],A);let I=s(t,["tuningDataStats"]);I!=null&&l(n,["tuningDataStats"],I);let P=s(t,["encryptionSpec"]);P!=null&&l(n,["encryptionSpec"],P);let G=s(t,["partnerModelTuningSpec"]);G!=null&&l(n,["partnerModelTuningSpec"],G);let O=s(t,["customBaseModel"]);O!=null&&l(n,["customBaseModel"],O);let B=s(t,["evaluateDatasetRuns"]);if(B!=null){let Re=B;Array.isArray(Re)&&(Re=Re.map(qe=>qe)),l(n,["evaluateDatasetRuns"],Re)}let k=s(t,["experiment"]);k!=null&&l(n,["experiment"],k);let V=s(t,["fullFineTuningSpec"]);V!=null&&l(n,["fullFineTuningSpec"],V);let X=s(t,["labels"]);X!=null&&l(n,["labels"],X);let Z=s(t,["outputUri"]);Z!=null&&l(n,["outputUri"],Z);let ne=s(t,["pipelineJob"]);ne!=null&&l(n,["pipelineJob"],ne);let D=s(t,["serviceAccount"]);D!=null&&l(n,["serviceAccount"],D);let K=s(t,["tunedModelDisplayName"]);K!=null&&l(n,["tunedModelDisplayName"],K);let j=s(t,["tuningJobMetadata"]);j!=null&&l(n,["tuningJobMetadata"],j);let _e=s(t,["tuningJobState"]);_e!=null&&l(n,["tuningJobState"],_e);let Pe=s(t,["veoLoraTuningSpec"]);Pe!=null&&l(n,["veoLoraTuningSpec"],Pe);let Ae=s(t,["veoTuningSpec"]);return Ae!=null&&l(n,["veoTuningSpec"],Ae),n}function nk(t,e){let n={},r=s(t,["sdkHttpResponse"]);r!=null&&l(n,["sdkHttpResponse"],r);let i=s(t,["name"]);i!=null&&l(n,["name"],i);let o=s(t,["metadata"]);o!=null&&l(n,["metadata"],o);let a=s(t,["done"]);a!=null&&l(n,["done"],a);let u=s(t,["error"]);return u!=null&&l(n,["error"],u),n}function ji(t,e){let n={},r=s(t,["gcsUri"]);r!=null&&l(n,["validationDatasetUri"],r);let i=s(t,["vertexDatasetResource"]);return i!=null&&l(n,["validationDatasetUri"],i),n}function rk(t,e){let n={},r=s(t,["parent"]);r!=null&&l(n,["_url","parent"],r);let i=s(t,["sampleResponse"]);i!=null&&l(n,["sampleResponse"],Mu(i));let o=s(t,["example"]);o!=null&&l(n,["example"],Qx(o));let a=s(t,["singleRewardConfig"]);a!=null&&l(n,["singleRewardConfig"],a);let u=s(t,["compositeRewardConfig"]);return u!=null&&l(n,["compositeRewardConfig"],u),n}function ik(t,e){let n={},r=s(t,["sdkHttpResponse"]);r!=null&&l(n,["sdkHttpResponse"],r);let i=s(t,["overallReward"]);i!=null&&l(n,["overallReward"],i);let o=s(t,["error"]);o!=null&&l(n,["error"],o);let a=s(t,["rewardInfoDetails"]);return a!=null&&l(n,["rewardInfoDetails"],a),n}var bu=class extends dt{constructor(e){super(),this.apiClient=e,this.list=async(n={})=>new Ut(Mt.PAGED_ITEM_TUNING_JOBS,r=>this.listInternal(r),await this.listInternal(n),n),this.get=async n=>await this.getInternal(n),this.tune=async n=>{var r;if(this.apiClient.isVertexAI())if(n.baseModel.startsWith("projects/")){let i={tunedModelName:n.baseModel};!((r=n.config)===null||r===void 0)&&r.preTunedModelCheckpointId&&(i.checkpointId=n.config.preTunedModelCheckpointId);let o=Object.assign(Object.assign({},n),{preTunedModel:i});return o.baseModel=void 0,await this.tuneInternal(o)}else{let i=Object.assign({},n);return await this.tuneInternal(i)}else{let i=Object.assign({},n),o=await this.tuneMldevInternal(i),a="";return o.metadata!==void 0&&o.metadata.tunedModel!==void 0?a=o.metadata.tunedModel:o.name!==void 0&&o.name.includes("/operations/")&&(a=o.name.split("/operations/")[0]),{name:a,state:dl.JOB_STATE_QUEUED}}}}async getInternal(e){var n,r,i,o;let a,u="",c={};if(this.apiClient.isVertexAI()){let d=Wx(e);return u=$("{name}",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(f=>f.json().then(p=>{let h=p;return h.sdkHttpResponse={headers:f.headers},h})),a.then(f=>Uu(f))}else{let d=Jx(e);return u=$("{name}",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"GET",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(f=>f.json().then(p=>{let h=p;return h.sdkHttpResponse={headers:f.headers},h})),a.then(f=>tk(f))}}async listInternal(e){var n,r;let i,o="",a={};if(this.apiClient.isVertexAI()){let u=Kx(e);return o=$("tuningJobs",u._url),a=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:o,queryParams:a,body:JSON.stringify(u),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(c=>c.json().then(d=>{let f=d;return f.sdkHttpResponse={headers:c.headers},f})),i.then(c=>{let d=Yx(c),f=new yl;return Object.assign(f,d),f})}else throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async cancel(e){var n,r,i,o;let a,u="",c={};if(this.apiClient.isVertexAI()){let d=Mx(e);return u=$("{name}:cancel",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(f=>f.json().then(p=>{let h=p;return h.sdkHttpResponse={headers:f.headers},h})),a.then(f=>{let p=bx(f),h=new co;return Object.assign(h,p),h})}else{let d=Dx(e);return u=$("{name}:cancel",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(f=>f.json().then(p=>{let h=p;return h.sdkHttpResponse={headers:f.headers},h})),a.then(f=>{let p=Ux(f),h=new co;return Object.assign(h,p),h})}}async tuneInternal(e){var n,r;let i,o="",a={};if(this.apiClient.isVertexAI()){let u=Fx(e,e);return o=$("tuningJobs",u._url),a=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:o,queryParams:a,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(c=>c.json().then(d=>{let f=d;return f.sdkHttpResponse={headers:c.headers},f})),i.then(c=>Uu(c))}else throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async tuneMldevInternal(e){var n,r;let i,o="",a={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let u=qx(e);return o=$("tunedModels",u._url),a=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:o,queryParams:a,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(c=>c.json().then(d=>{let f=d;return f.sdkHttpResponse={headers:c.headers},f})),i.then(c=>nk(c))}}async validateReward(e){var n,r;let i,o="",a={};if(this.apiClient.isVertexAI()){let u=rk(e);return o=$("{parent}/tuningJobs:validateReinforcementTuningReward",u._url),a=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:o,queryParams:a,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(c=>c.json().then(d=>{let f=d;return f.sdkHttpResponse={headers:c.headers},f})),i.then(c=>{let d=ik(c),f=new El;return Object.assign(f,d),f})}else throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}},L_=1024*1024*8,O_=3,q_=1e3,F_=2,Wt="x-goog-upload-status";async function ok(t,e,n,r){var i;let o=await B_(t,e,n,r),a=await o?.json();if(((i=o?.headers)===null||i===void 0?void 0:i[Wt])!=="final")throw new Error("Failed to upload file: Upload status is not finalized.");return a.file}async function sk(t,e,n,r){var i;let o=await B_(t,e,n,r),a=await o?.json();if(((i=o?.headers)===null||i===void 0?void 0:i[Wt])!=="final")throw new Error("Failed to upload file: Upload status is not finalized.");let u=qu(a),c=new mo;return Object.assign(c,u),c}async function B_(t,e,n,r){var i,o,a;let u=e,c=r?.baseUrl||((i=n.clientOptions.httpOptions)===null||i===void 0?void 0:i.baseUrl);if(c){let m=new URL(c),_=new URL(e);_.protocol=m.protocol,_.host=m.host,_.port=m.port,u=_.toString()}let d=0,f=0,p=new Kt(new Response),h="upload";for(d=t.size;f<d;){let m=Math.min(L_,d-f),_=t.slice(f,f+m);f+m>=d&&(h+=", finalize");let g=0,E=q_;for(;g<O_;){let y=Object.assign(Object.assign({},r?.headers||{}),{"X-Goog-Upload-Command":h,"X-Goog-Upload-Offset":String(f),"Content-Length":String(m)});if(p=await n.request({path:"",body:_,httpMethod:"POST",httpOptions:Object.assign(Object.assign({},r),{apiVersion:"",baseUrl:u,headers:y})}),!((o=p?.headers)===null||o===void 0)&&o[Wt])break;g++,await H_(E),E=E*F_}if(f+=m,((a=p?.headers)===null||a===void 0?void 0:a[Wt])!=="active")break;if(d<=f)throw new Error("All content has been uploaded, but the upload status is not finalized.")}return p}async function ak(t){return{size:t.size,type:t.type}}function H_(t){return new Promise(e=>setTimeout(e,t))}var Gu=class{async stat(e){let n={size:0,type:void 0};if(typeof e=="string"){let r=await Io.stat(e);return n.size=r.size,n.type=this.inferMimeType(e),n}else return await ak(e)}async upload(e,n,r,i){return typeof e=="string"?await this.uploadFileFromPath(e,n,r,i):ok(e,n,r,i)}async uploadToFileSearchStore(e,n,r,i){return typeof e=="string"?await this.uploadFileToFileSearchStoreFromPath(e,n,r,i):sk(e,n,r,i)}inferMimeType(e){let n=e.slice(e.lastIndexOf(".")+1);return{aac:"audio/aac",abw:"application/x-abiword",arc:"application/x-freearc",avi:"video/x-msvideo",azw:"application/vnd.amazon.ebook",bin:"application/octet-stream",bmp:"image/bmp",bz:"application/x-bzip",bz2:"application/x-bzip2",csh:"application/x-csh",css:"text/css",csv:"text/csv",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",eot:"application/vnd.ms-fontobject",epub:"application/epub+zip",gz:"application/gzip",gif:"image/gif",htm:"text/html",html:"text/html",ico:"image/vnd.microsoft.icon",ics:"text/calendar",jar:"application/java-archive",jpeg:"image/jpeg",jpg:"image/jpeg",js:"text/javascript",json:"application/json",jsonld:"application/ld+json",kml:"application/vnd.google-earth.kml+xml",kmz:"application/vnd.google-earth.kmz+xml",mjs:"text/javascript",mp3:"audio/mpeg",mp4:"video/mp4",mpeg:"video/mpeg",mpkg:"application/vnd.apple.installer+xml",odt:"application/vnd.oasis.opendocument.text",oga:"audio/ogg",ogv:"video/ogg",ogx:"application/ogg",opus:"audio/opus",otf:"font/otf",png:"image/png",pdf:"application/pdf",php:"application/x-httpd-php",ppt:"application/vnd.ms-powerpoint",pptx:"application/vnd.openxmlformats-officedocument.presentationml.presentation",rar:"application/vnd.rar",rtf:"application/rtf",sh:"application/x-sh",svg:"image/svg+xml",swf:"application/x-shockwave-flash",tar:"application/x-tar",tif:"image/tiff",tiff:"image/tiff",ts:"video/mp2t",ttf:"font/ttf",txt:"text/plain",vsd:"application/vnd.visio",wav:"audio/wav",weba:"audio/webm",webm:"video/webm",webp:"image/webp",woff:"font/woff",woff2:"font/woff2",xhtml:"application/xhtml+xml",xls:"application/vnd.ms-excel",xlsx:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",xml:"application/xml",xul:"application/vnd.mozilla.xul+xml",zip:"application/zip","3gp":"video/3gpp","3g2":"video/3gpp2","7z":"application/x-7z-compressed"}[n.toLowerCase()]}async uploadFileFromPath(e,n,r,i){var o;let a=await this.uploadFileFromPathInternal(e,n,r,i),u=await a?.json();if(((o=a?.headers)===null||o===void 0?void 0:o[Wt])!=="final")throw new Error("Failed to upload file: Upload status is not finalized.");return u.file}async uploadFileToFileSearchStoreFromPath(e,n,r,i){var o;let a=await this.uploadFileFromPathInternal(e,n,r,i),u=await a?.json();if(((o=a?.headers)===null||o===void 0?void 0:o[Wt])!=="final")throw new Error("Failed to upload file: Upload status is not finalized.");let c=qu(u),d=new mo;return Object.assign(d,c),d}async uploadFileFromPathInternal(e,n,r,i){var o,a,u;let c=n,d=i?.baseUrl||((o=r.clientOptions.httpOptions)===null||o===void 0?void 0:o.baseUrl);if(d){let E=new URL(d),y=new URL(n);y.protocol=E.protocol,y.host=E.host,y.port=E.port,c=y.toString()}let f=0,p=0,h=new Kt(new Response),m="upload",_,g=mg.basename(e);try{if(_=await Io.open(e,"r"),!_)throw new Error("Failed to open file");for(f=(await _.stat()).size;p<f;){let E=Math.min(L_,f-p);p+E>=f&&(m+=", finalize");let y=new Uint8Array(E),{bytesRead:C}=await _.read(y,0,E,p);if(C!==E)throw new Error(`Failed to read ${E} bytes from file at offset ${p}. bytes actually read: ${C}`);let A=new Blob([y]),I=0,P=q_;for(;I<O_;){let G=Object.assign(Object.assign({},i?.headers||{}),{"X-Goog-Upload-Command":m,"X-Goog-Upload-Offset":String(p),"Content-Length":String(C),"X-Goog-Upload-File-Name":g});if(h=await r.request({path:"",body:A,httpMethod:"POST",httpOptions:Object.assign(Object.assign({},i),{apiVersion:"",baseUrl:c,headers:G})}),!((a=h?.headers)===null||a===void 0)&&a[Wt])break;I++,await H_(P),P=P*F_}if(p+=C,((u=h?.headers)===null||u===void 0?void 0:u[Wt])!=="active")break;if(f<=p)throw new Error("All content has been uploaded, but the upload status is not finalized.")}return h}finally{_&&await _.close()}}};var Lu=class extends Gl{async registerFiles(e){if(typeof process>"u"||!process.versions||!process.versions.node)throw new Error("registerFiles is only supported in Node.js environments.");let r=await e.auth.getRequestHeaders(),i=e.config||{},o=i.httpOptions||{},a=Object.assign({},o.headers||{});if(r)if(typeof r[Symbol.iterator]=="function")for(let[u,c]of r)a[u]=c;else for(let[u,c]of Object.entries(r))a[u]=c;return this._registerFiles({uris:e.uris,config:Object.assign(Object.assign({},i),{httpOptions:Object.assign(Object.assign({},o),{headers:a})})})}};var lk="gl-node/";function uk(t){var e;if(t.enterprise!==void 0||t.vertexai!==void 0){if(t.enterprise!==void 0&&t.vertexai!==void 0&&t.enterprise!==t.vertexai)throw new Error("enterprise and vertexAI flags have conflicting values, please set enterprise value only.");return(e=t.enterprise)!==null&&e!==void 0?e:t.vertexai}let n=Xt("GOOGLE_GENAI_USE_ENTERPRISE"),r=Xt("GOOGLE_GENAI_USE_VERTEXAI"),i=fg(n),o=fg(r);return n!==void 0&&r!==void 0&&i!==o&&console.warn("Warning: Both GOOGLE_GENAI_USE_ENTERPRISE and GOOGLE_GENAI_USE_VERTEXAI are set with conflicting values. The value of GOOGLE_GENAI_USE_ENTERPRISE will be used."),n!==void 0?i:r!==void 0?o:!1}var dg=class{getNextGenClient(){let e=this.httpOptions;return this._nextGenClient===void 0&&(this._nextGenClient=Ct(this.apiClient,{timeout_ms:e?.timeout})),e?.extraBody&&console.warn("GoogleGenAI: Client level httpOptions.extraBody is not supported by the Gemini NextGen client and will be ignored."),this._nextGenClient}get interactions(){return this._interactions!==void 0?this._interactions:(this._interactions=new Su(this.apiClient),this._interactions)}get webhooks(){return this._webhooks!==void 0?this._webhooks:(this._webhooks=new wu(this.apiClient),this._webhooks)}get agents(){return this._agents!==void 0?this._agents:(console.warn("GoogleGenAI.agents: Agents usage is experimental and may change in future versions."),this._agents=new Iu(this.apiClient),this._agents)}get triggers(){return this._triggers!==void 0?this._triggers:(console.warn("GoogleGenAI.triggers: Triggers usage is experimental and may change in future versions."),this._triggers=new Pu(this.apiClient),this._triggers)}get environments(){return this._environments!==void 0?this._environments:(console.warn("GoogleGenAI.environments: Environments usage is experimental and may change in future versions."),this._environments=new Ru(this.apiClient),this._environments)}constructor(e){var n,r,i,o;if(this.vertexai=uk(e),(e.project||e.location)&&!this.vertexai)throw new Error("Project and location are not supported for Gemini API backend.");let a=ck(),u=Xt("GOOGLE_CLOUD_PROJECT"),c=Xt("GOOGLE_CLOUD_LOCATION");this.apiKey=(n=e.apiKey)!==null&&n!==void 0?n:a,this.project=(r=e.project)!==null&&r!==void 0?r:u,this.location=(i=e.location)!==null&&i!==void 0?i:c,!this.vertexai&&!this.apiKey&&console.warn("API key should be set when using the Gemini API."),this.vertexai&&(!((o=e.googleAuthOptions)===null||o===void 0)&&o.credentials&&(console.debug("The user provided Google Cloud credentials will take precedence over the API key from the environment variable."),this.apiKey=void 0),!e.project&&!e.location&&(u||c)&&e.apiKey?(console.debug("The user provided Vertex AI API key will take precedence over the project/location from the environment variables."),this.project=void 0,this.location=void 0):(e.project||e.location)&&!e.apiKey&&a?(console.debug("The user provided project/location will take precedence over the API key from the environment variables."),this.apiKey=void 0):!e.project&&!e.location&&!e.apiKey&&(u||c)&&a&&(console.debug("The project/location from the environment variables will take precedence over the API key from the environment variables."),this.apiKey=void 0),!this.location&&!this.apiKey&&(this.location="global"));let d=zC(e.httpOptions,this.vertexai,Xt("GOOGLE_VERTEX_BASE_URL"),Xt("GOOGLE_GEMINI_BASE_URL"));d&&(e.httpOptions?e.httpOptions.baseUrl=d:e.httpOptions={baseUrl:d}),this.apiVersion=e.apiVersion,this.httpOptions=e.httpOptions;let f=new Nu({apiKey:this.apiKey,googleAuthOptions:e.googleAuthOptions});this.apiClient=new Fl({auth:f,project:this.project,location:this.location,apiVersion:this.apiVersion,apiKey:this.apiKey,vertexai:this.vertexai,httpOptions:this.httpOptions,userAgentExtra:lk+process.version,uploader:new Gu,downloader:new xu}),this.models=new Yn(this.apiClient),this.live=new Vl(this.apiClient,f,new ku),this.batches=new Dl(this.apiClient),this.chats=new Ul(this.models,this.apiClient),this.caches=new Ml(this.apiClient),this.files=new Lu(this.apiClient),this.operations=new Jl(this.apiClient),this.authTokens=new Wl(this.apiClient),this.tunings=new bu(this.apiClient),this.fileSearchStores=new Kl(this.apiClient)}};function Xt(t){var e,n,r;return(r=(n=(e=process==null?void 0:process.env)===null||e===void 0?void 0:e[t])===null||n===void 0?void 0:n.trim())!==null&&r!==void 0?r:void 0}function fg(t){return t===void 0?!1:t.toLowerCase()==="true"}function ck(){let t=Xt("GOOGLE_API_KEY"),e=Xt("GEMINI_API_KEY");return t&&e&&console.warn("Both GOOGLE_API_KEY and GEMINI_API_KEY are set. Using GOOGLE_API_KEY."),t||e||void 0}export{Qh as ActivityHandling,_h as AdapterSize,Ah as AggregationMetric,_o as ApiError,Jp as ApiSpec,hh as AspectRatio,cm as AudioResponseFormat,Vp as AuthType,Dl as Batches,Yp as Behavior,lh as BlockedReason,Ml as Caches,co as CancelTuningJobResponse,bl as Chat,Ul as Chats,_l as ComputeTokensResponse,Nm as ContentReferenceImage,wm as ControlReferenceImage,bh as ControlReferenceType,lo as CountTokensResponse,Il as CreateFileResponse,fo as DeleteCachedContentResponse,wl as DeleteFileResponse,ao as DeleteModelResponse,ph as Delivery,Ph as DocumentState,zp as DynamicRetrievalConfigMode,pl as EditImageResponse,Lh as EditMode,io as EmbedContentResponse,ro as EmbeddingApiType,zh as EndSensitivity,Wp as Environment,ym as EvaluateDatasetResponse,kh as FeatureSelectionPreference,Jh as FileSource,$h as FileState,Gl as Files,ih as FinishReason,rh as FunctionCallingConfigMode,om as FunctionResponse,rm as FunctionResponseBlob,nm as FunctionResponseFileData,im as FunctionResponsePart,Hp as FunctionResponseScheduling,pn as GenerateContentResponse,lm as GenerateContentResponsePromptFeedback,um as GenerateContentResponseUsageMetadata,oo as GenerateImagesResponse,uo as GenerateVideosOperation,mm as GenerateVideosResponse,dg as GoogleGenAI,th as HarmBlockMethod,nh as HarmBlockThreshold,eh as HarmCategory,oh as HarmProbability,sh as HarmSeverity,$p as HttpElementLocation,Kt as HttpResponse,Mh as ImagePromptLanguage,Hh as ImageResizeMode,dm as ImageResponseFormat,mh as ImageSize,Cl as ImportFileOperation,Em as ImportFileResponse,Am as InlinedEmbedContentResponse,vm as InlinedResponse,dl as JobState,Bp as Language,ho as ListBatchJobsResponse,po as ListCachedContentsResponse,vl as ListDocumentsResponse,Tl as ListFileSearchStoresResponse,Sl as ListFilesResponse,so as ListModelsResponse,yl as ListTuningJobsResponse,Vl as Live,xm as LiveClientToolResponse,Vn as LiveMusicPlaybackControl,Nl as LiveMusicServerMessage,km as LiveSendToolResponseParameters,Rl as LiveServerMessage,Im as MaskReferenceImage,Uh as MaskReferenceMode,Eh as MatchOperation,ch as MediaModality,fh as MediaResolution,no as Modality,dh as ModelStage,Yn as Models,em as MusicGenerationMode,Jl as Operations,Fp as Outcome,Mt as PagedItem,Ut as Pager,Ch as PairwiseChoice,Nh as PartMediaResolutionLevel,Zp as PersonGeneration,Kp as PhishBlockThreshold,jp as ProminentPeople,Sm as RawReferenceImage,ml as RecontextImageResponse,Pl as RegisterFilesResponse,_m as ReinforcementTuningAutoraterScorerParsedResponseConversionScorer,gm as ReinforcementTuningParseResponseConfig,vh as ReinforcementTuningThinkingLevel,Cm as ReplayResponse,fl as ResourceScope,hm as ResponseFormat,yh as ResponseParseType,Dh as SafetyFilterLevel,Xp as SafetyPolicy,jh as Scale,gl as SegmentImageResponse,Oh as SegmentMode,Rh as ServiceTier,$l as Session,Tm as SingleEmbedContentResponse,Yh as StartSensitivity,Pm as StyleReferenceImage,Rm as SubjectReferenceImage,Gh as SubjectReferenceType,fm as TextResponseFormat,Qp as ThinkingLevel,Wl as Tokens,tm as ToolResponse,xh as ToolType,uh as TrafficType,Th as TuningJobState,Vh as TuningMethod,gh as TuningMode,Ih as TuningSpeed,wh as TuningTask,Wh as TurnCompleteReason,Zh as TurnCoverage,Jt as Type,mo as UploadToFileSearchStoreOperation,Dm as UploadToFileSearchStoreResponse,Al as UploadToFileSearchStoreResumableResponse,hl as UpscaleImageResponse,ah as UrlRetrievalStatus,Xh as VadSignalType,El as ValidateRewardResponse,Bh as VideoCompressionQuality,Fh as VideoGenerationMaskMode,qh as VideoGenerationReferenceType,Sh as VideoOrientation,pm as VideoResponseFormat,Kh as VoiceActivityType,tM as createFunctionResponsePartFromBase64,nM as createFunctionResponsePartFromUri,cM as createModelContent,sM as createPartFromBase64,aM as createPartFromCodeExecutionResult,lM as createPartFromExecutableCode,iM as createPartFromFunctionCall,oM as createPartFromFunctionResponse,sm as createPartFromText,rM as createPartFromUri,uM as createUserContent,dM as mcpToTool,eM as setDefaultBaseUrls};
43
- /*! Bundled license information:
44
-
45
- safe-buffer/index.js:
46
- (*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> *)
47
-
48
- @google/genai/dist/node/index.mjs:
49
- (**
50
- * @license
51
- * Copyright 2025 Google LLC
52
- * SPDX-License-Identifier: Apache-2.0
53
- *)
54
-
55
- @google/genai/dist/node/index.mjs:
56
- (**
57
- * @license
58
- * Copyright 2025 Google LLC
59
- * SPDX-License-Identifier: Apache-2.0
60
- *)
61
- (**
62
- * @license
63
- * Copyright 2026 Google LLC
64
- * SPDX-License-Identifier: Apache-2.0
65
- *
66
- * g3-prettier-ignore-file
67
- *)
68
- */