@cline/core 0.0.95 → 0.2.0
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.
- package/dist/ClineCore.d.ts +6 -1
- package/dist/account/rpc.d.ts +3 -1
- package/dist/cline-core/runtime-services.d.ts +4 -2
- package/dist/cloud/controller.d.ts +5 -2
- package/dist/cloud/hub-client.d.ts +51 -0
- package/dist/cloud/hub-protocol.d.ts +18 -0
- package/dist/cloud/index.d.ts +2 -0
- package/dist/cloud/index.js +16 -16
- package/dist/cloud/types.d.ts +4 -1
- package/dist/extensions/context/compaction-shared.d.ts +1 -0
- package/dist/extensions/context/compaction.d.ts +7 -0
- package/dist/extensions/context/summarize-conversation.d.ts +7 -0
- package/dist/extensions/context/summary-generation.d.ts +14 -0
- package/dist/extensions/mcp/apps.d.ts +16 -0
- package/dist/extensions/mcp/client.d.ts +1 -0
- package/dist/extensions/mcp/index.d.ts +5 -1
- package/dist/extensions/mcp/manager.d.ts +2 -1
- package/dist/extensions/mcp/session-apps.d.ts +28 -0
- package/dist/extensions/mcp/types.d.ts +22 -0
- package/dist/extensions/plugin/plugin-command-origin.d.ts +8 -0
- package/dist/extensions/plugin/plugin-registry.d.ts +1 -0
- package/dist/extensions/plugin/plugin-runtime.d.ts +7 -0
- package/dist/hub/client/index.d.ts +6 -0
- package/dist/hub/client/managed-hub-build-watcher.d.ts +2 -0
- package/dist/hub/client/plugin-commands.d.ts +4 -0
- package/dist/hub/client/session-client.d.ts +2 -0
- package/dist/hub/daemon/entry.js +241 -228
- package/dist/hub/index.d.ts +1 -0
- package/dist/hub/index.js +231 -218
- package/dist/hub/runtime-host/hub-runtime-host.d.ts +6 -0
- package/dist/hub/server/cloud-session-service.d.ts +50 -0
- package/dist/hub/server/handlers/capability-handlers.d.ts +18 -1
- package/dist/hub/server/handlers/context.d.ts +13 -2
- package/dist/hub/server/handlers/mcp-apps-handlers.d.ts +5 -0
- package/dist/hub/server/hub-server-options.d.ts +3 -0
- package/dist/hub/server/hub-server-transport.d.ts +2 -0
- package/dist/index.d.ts +8 -4
- package/dist/index.js +278 -258
- package/dist/plugin-runtime/node_modules/@cline/agents/dist/index.js +76 -0
- package/dist/plugin-runtime/node_modules/@cline/agents/package.json +1 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/ai-sdk-b1d8eb67.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/anthropic-33qvrctr.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/bedrock-paabhz8w.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/cline-yhsfqcy1.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/cloud/index.js +21 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/community-gqgs7446.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/foundation-models-embedding-model-strategy-SAVQFBF4-822304b0.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/foundation-models-language-model-strategy-BPQO66W7-hky2m2yx.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/getMachineId-bsd-sqf1kd37.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/getMachineId-bsd-tx1kp6xn.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/getMachineId-darwin-6cpgjxme.js +2 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/getMachineId-darwin-fxchqbze.js +2 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/getMachineId-linux-m3bzwmzc.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/getMachineId-linux-pr9sb5fr.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/getMachineId-unsupported-nckraycx.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/getMachineId-unsupported-w91yq3tm.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/getMachineId-win-xdyxc2tf.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/getMachineId-win-yxsvs11a.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/google-pgdk2dm9.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/hub/daemon/entry.js +1160 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/hub/index.js +1147 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-02jpyn9y.js +85 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-0cb4390m.js +137 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-0f8xrhgt.js +209 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-1f8vb421.js +2 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-28c7m0fv.js +16 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-2em3jg4q.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-4n1zpzbe.js +2 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-54eea0ex.js +2 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-5j92dtg5.js +16 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-6akf3a5d.js +2 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-6k6ep10s.js +136 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-71ym4q6s.js +2 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-91p1ghfk.js +14 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-9qkpjy7x.js +2 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-9swk4nej.js +3 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-aa2s5myc.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-ae0ajw38.js +13 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-bxvyzjhc.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-bzy863k0.js +6 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-d96n0s70.js +20 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-dsd6vt8c.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-e2q4azd9.js +119 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-egd18jj2.js +4 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-eh83hr16.js +2 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-ev9r2dy3.js +1204 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-f2mvvryf.js +190 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-h7gn5v3f.js +2 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-h7s1a560.js +12 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-hkhq3jtz.js +21 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-j8r18nfg.js +15 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-jhny555h.js +6 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-m1gpa2eg.js +146 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-m2ad6tgj.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-m7mks2jq.js +4 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-mcnngj50.js +62 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-n2srkkh0.js +39 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-nbs1tsny.js +142 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-nqjnz7m4.js +9 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-rmhzyxr8.js +3 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-rtzf3vvk.js +6 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-sw74pcm3.js +2 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-t3eanyjj.js +3 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-tseksj1v.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-v0ctpcdr.js +12 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-v4-dx8bd4wq.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-v695918t.js +14 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-v96yy1pw.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-vfm7r9wk.js +65 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-xecthgrg.js +9 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-xn1xhp06.js +9 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-yfdscfdx.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-yrnwqsdt.js +2 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/jiti-static-3mgy2y9y.js +473 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/jiti-w1xrs0vd.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/langfuse-stream-telemetry-9tppg77c.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/langfuse-telemetry-y658kpzy.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/mistral-cmhqd91b.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/multipart-parser-qkjjf8mm.js +2 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/ollama-8z6y9d1h.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/openai-cfmja1ez.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/openai-compatible-1t7n5sxj.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/orchestration-embedding-model-strategy-GT27AFII-k6yqgnyd.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/orchestration-language-model-strategy-YEQPUCOT-6rdyebbq.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/services/feature-flags/posthog.js +2 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/services/telemetry/index.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/token-1h068py9.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/token-util-7jchft51.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/vertex-qfxfsrn4.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/core/package.json +1 -0
- package/dist/plugin-runtime/node_modules/@cline/llms/dist/index.browser.js +16 -0
- package/dist/plugin-runtime/node_modules/@cline/llms/dist/index.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/llms/package.json +1 -0
- package/dist/plugin-runtime/node_modules/@cline/sdk/dist/index.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/sdk/package.json +1 -0
- package/dist/plugin-runtime/node_modules/@cline/shared/dist/automation/index.js +57 -0
- package/dist/plugin-runtime/node_modules/@cline/shared/dist/db/index.js +127 -0
- package/dist/plugin-runtime/node_modules/@cline/shared/dist/index.browser.js +110 -0
- package/dist/plugin-runtime/node_modules/@cline/shared/dist/index.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/shared/dist/node.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/shared/dist/remote-config/index.js +68 -0
- package/dist/plugin-runtime/node_modules/@cline/shared/dist/storage/index.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/shared/dist/types/index.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/shared/package.json +1 -0
- package/dist/plugin-runtime/package.json +1 -0
- package/dist/{extensions → plugin-runtime}/plugin-sandbox-bootstrap.js +129 -129
- package/dist/remote/remote-environments.d.ts +1 -0
- package/dist/runtime/config/agent-runtime-config-builder.d.ts +2 -0
- package/dist/runtime/host/local-runtime-host.d.ts +10 -0
- package/dist/runtime/host/runtime-host.d.ts +6 -0
- package/dist/runtime/orchestration/runtime-oauth-token-manager.d.ts +3 -0
- package/dist/runtime/orchestration/session-runtime-orchestrator.d.ts +10 -1
- package/dist/runtime/orchestration/session-runtime.d.ts +2 -0
- package/dist/runtime/tools/subprocess-sandbox.d.ts +22 -0
- package/dist/services/llms/cline-recommended-models.d.ts +2 -0
- package/dist/services/local-runtime-bootstrap.d.ts +1 -0
- package/dist/services/plugin-command-api.d.ts +47 -0
- package/dist/services/plugin-commands.d.ts +25 -27
- package/dist/services/skills-cli.d.ts +2 -0
- package/dist/services/telemetry/core-events.d.ts +26 -0
- package/dist/services/telemetry/index.js +1 -1
- package/dist/services/telemetry/run-health.d.ts +40 -0
- package/dist/services/telemetry/stall-signals.d.ts +12 -0
- package/dist/types/config.d.ts +1 -0
- package/dist/types/session.d.ts +7 -0
- package/package.json +6 -5
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import{xy,gc}from"./index-m7mks2jq.js";import{Lw,Ri}from"./index-rmhzyxr8.js";import{D,F,ve,lt,b,H,Q,I,Oi,xn,Xn,Te,tt,j,dp,Ct,Kt,Ht,Ai,Me,Ci,Se,it,ge,Ae,Ao,C,De,Wr,Ms,ut,io,Ee,ft,en,Ke,u,l,yt,k,A,G,W,ee,$e,oe,qe,E,te,He}from"./index-6k6ep10s.js";import{v,i,c,e,n,r,m,le,o,t,ae,p,d,s,a,Fe}from"./index-mcnngj50.js";var rr=i(function(Nm,Bs){var An=Object.prototype.hasOwnProperty,Hs=Object.prototype.toString,{defineProperty:Ds,getOwnPropertyDescriptor:qs}=Object,Ls=function(f){if(typeof Array.isArray==="function")return Array.isArray(f);return Hs.call(f)==="[object Array]"},Fs=function(f){if(!f||Hs.call(f)!=="[object Object]")return!1;var g=An.call(f,"constructor"),y=f.constructor&&f.constructor.prototype&&An.call(f.constructor.prototype,"isPrototypeOf");if(f.constructor&&!g&&!y)return!1;var _;for(_ in f);return typeof _>"u"||An.call(f,_)},Gs=function(f,g){if(Ds&&g.name==="__proto__")Ds(f,g.name,{enumerable:!0,configurable:!0,value:g.newValue,writable:!0});else f[g.name]=g.newValue},$s=function(f,g){if(g==="__proto__"){if(!An.call(f,g))return;else if(qs)return qs(f,g).value}return f[g]};Bs.exports=function h(){var f,g,y,_,T,S,w=arguments[0],x=1,B=arguments.length,P=!1;if(typeof w==="boolean")P=w,w=arguments[1]||{},x=2;if(w==null||typeof w!=="object"&&typeof w!=="function")w={};for(;x<B;++x)if(f=arguments[x],f!=null){for(g in f)if(y=$s(w,g),_=$s(f,g),w!==_){if(P&&_&&(Fs(_)||(T=Ls(_)))){if(T)T=!1,S=y&&Ls(y)?y:[];else S=y&&Fs(y)?y:{};Gs(w,{name:g,newValue:h(P,S,_)})}else if(typeof _<"u")Gs(w,{name:g,newValue:_})}}return w}});var Vs=i(function(Pm,Kl){Kl.exports={name:"gaxios",version:"7.3.1",description:"A simple common HTTP client specifically for Google APIs and services.",main:"build/cjs/src/index.js",types:"build/cjs/src/index.d.ts",files:["build/"],exports:{".":{import:{types:"./build/esm/src/index.d.ts",default:"./build/esm/src/index.js"},require:{types:"./build/cjs/src/index.d.ts",default:"./build/cjs/src/index.js"}}},scripts:{lint:"gts check --no-inline-config",test:"c8 mocha build/esm/test","presystem-test":"npm run compile","system-test":"mocha build/esm/system-test --timeout 80000",compile:"tsc -b ./tsconfig.json ./tsconfig.cjs.json && node utils/enable-esm.mjs",fix:"gts fix",prepare:"npm run compile",pretest:"npm run compile",webpack:"webpack","prebrowser-test":"npm run compile","browser-test":"node build/browser-test/browser-test-runner.js",docs:"jsdoc -c .jsdoc.js","samples-test":"cd samples/ && npm link ../ && npm test && cd ../",prelint:"cd samples; npm link ../; npm install",clean:"gts clean"},repository:{type:"git",directory:"core/packages/gaxios",url:"https://github.com/googleapis/google-cloud-node.git"},keywords:["google"],engines:{node:">=18"},author:"Google, LLC",license:"Apache-2.0",devDependencies:{"@babel/plugin-proposal-private-methods":"^7.18.6","@types/cors":"^2.8.6","@types/express":"^5.0.0","@types/extend":"^3.0.1","@types/mocha":"^10.0.10","@types/multiparty":"4.2.1","@types/mv":"^2.1.0","@types/ncp":"^2.0.8","@types/node":"^24.0.0","@types/sinon":"^21.0.0","@types/tmp":"^0.2.6",assert:"^2.0.0",browserify:"^17.0.0",c8:"^10.1.3",cors:"^2.8.5",express:"^5.0.0",gts:"^6.0.2","is-docker":"^3.0.0",jsdoc:"^4.0.4","jsdoc-fresh":"^5.0.0","jsdoc-region-tag":"^4.0.0",karma:"^6.0.0","karma-chrome-launcher":"^3.0.0","karma-coverage":"^2.0.0","karma-firefox-launcher":"^2.0.0","karma-mocha":"^2.0.0","karma-remap-coverage":"^0.1.5","karma-sourcemap-loader":"^0.4.0","karma-webpack":"^5.0.0",mocha:"^11.1.0",multiparty:"^4.2.1",mv:"^2.1.1",ncp:"^2.0.0",nock:"14.0.5","null-loader":"^4.0.1","pack-n-play":"^4.0.0",puppeteer:"^24.0.0",sinon:"21.0.3","stream-browserify":"^3.0.0",tmp:"0.2.7","ts-loader":"^9.5.2",typescript:"5.8.3","undici-types":"^7.24.1",webpack:"^5.97.1","webpack-cli":"^6.0.1"},dependencies:{extend:"^3.0.2","https-proxy-agent":"^7.0.1","node-fetch":"^3.3.2"},homepage:"https://github.com/googleapis/google-cloud-node/tree/main/core/packages/gaxios"}});var Ks=i(function(jm,Ws){var Jl=Vs();Ws.exports={pkg:Jl}});var or=i(function(At){var Ys=At&&At.__importDefault||function(h){return h&&h.__esModule?h:{default:h}};Object.defineProperty(At,"__esModule",{value:!0});At.GaxiosError=At.GAXIOS_ERROR_SYMBOL=void 0;At.defaultErrorRedactor=zs;var Js=Ys(rr()),Yl=Ys(Ks()),sr=Yl.default.pkg;At.GAXIOS_ERROR_SYMBOL=Symbol.for(`${sr.name}-gaxios-error`);class ir extends Error{config;response;code;status;error;[At.GAXIOS_ERROR_SYMBOL]=sr.version;static[Symbol.hasInstance](h){if(h&&typeof h==="object"&&At.GAXIOS_ERROR_SYMBOL in h&&h[At.GAXIOS_ERROR_SYMBOL]===sr.version)return!0;return Function.prototype[Symbol.hasInstance].call(ir,h)}constructor(h,f,g,y){super(h,{cause:y});if(this.config=f,this.response=g,this.error=y instanceof Error?y:void 0,this.config=(0,Js.default)(!0,{},f),this.response)this.response.config=(0,Js.default)(!0,{},this.response.config);if(this.response){try{this.response.data=zl(this.config.responseType,this.response?.bodyUsed?this.response?.data:void 0)}catch{}this.status=this.response.status}if(y instanceof DOMException)this.code=y.name;else if(y&&typeof y==="object"&&"code"in y&&(typeof y.code==="string"||typeof y.code==="number"))this.code=y.code}static extractAPIErrorFromResponse(h,f="The request failed"){let g=f;if(typeof h.data==="string")g=h.data;if(h.data&&typeof h.data==="object"&&"error"in h.data&&h.data.error&&!h.ok){if(typeof h.data.error==="string")return{message:h.data.error,code:h.status,status:h.statusText};if(typeof h.data.error==="object"){g="message"in h.data.error&&typeof h.data.error.message==="string"?h.data.error.message:g;let y="status"in h.data.error&&typeof h.data.error.status==="string"?h.data.error.status:h.statusText,_="code"in h.data.error&&typeof h.data.error.code==="number"?h.data.error.code:h.status;if("errors"in h.data.error&&Array.isArray(h.data.error.errors)){let T=[];for(let S of h.data.error.errors)if(typeof S==="object"&&"message"in S&&typeof S.message==="string")T.push(S.message);return Object.assign({message:T.join(`
|
|
2
|
+
`)||g,code:_,status:y},h.data.error)}return Object.assign({message:g,code:_,status:y},h.data.error)}}return{message:g,code:h.status,status:h.statusText}}}At.GaxiosError=ir;function zl(h,f){switch(h){case"stream":return f;case"json":return JSON.parse(JSON.stringify(f));case"arraybuffer":return JSON.parse(Buffer.from(f).toString("utf8"));case"blob":return JSON.parse(f.text());default:return f}}function zs(h){function g(T){if(!T)return;T.forEach((S,w)=>{if(/^authentication$/i.test(w)||/^authorization$/i.test(w)||/secret/i.test(w))T.set(w,"<<REDACTED> - See `errorRedactor` option in `gaxios` for configuration>.")})}function y(T,S){if(typeof T==="object"&&T!==null&&typeof T[S]==="string"){let w=T[S];if(/grant_type=/i.test(w)||/assertion=/i.test(w)||/secret/i.test(w))T[S]="<<REDACTED> - See `errorRedactor` option in `gaxios` for configuration>."}}function _(T){if(!T||typeof T!=="object")return;else if(T instanceof FormData||T instanceof URLSearchParams||"forEach"in T&&"set"in T)T.forEach((S,w)=>{if(["grant_type","assertion"].includes(w)||/secret/.test(w))T.set(w,"<<REDACTED> - See `errorRedactor` option in `gaxios` for configuration>.")});else{if("grant_type"in T)T.grant_type="<<REDACTED> - See `errorRedactor` option in `gaxios` for configuration>.";if("assertion"in T)T.assertion="<<REDACTED> - See `errorRedactor` option in `gaxios` for configuration>.";if("client_secret"in T)T.client_secret="<<REDACTED> - See `errorRedactor` option in `gaxios` for configuration>."}}if(h.config){if(g(h.config.headers),y(h.config,"data"),_(h.config.data),y(h.config,"body"),_(h.config.body),h.config.url.searchParams.has("token"))h.config.url.searchParams.set("token","<<REDACTED> - See `errorRedactor` option in `gaxios` for configuration>.");if(h.config.url.searchParams.has("client_secret"))h.config.url.searchParams.set("client_secret","<<REDACTED> - See `errorRedactor` option in `gaxios` for configuration>.")}if(h.response){if(zs({config:h.response.config}),g(h.response.headers),h.response.bodyUsed)y(h.response,"data"),_(h.response.data)}return h}});var Zs=i(function(Qs){Object.defineProperty(Qs,"__esModule",{value:!0});Qs.getRetryConfig=Xl;async function Xl(h){let f=Xs(h);if(!h||!h.config||!f&&!h.config.retry)return{shouldRetry:!1};f=f||{},f.currentRetryAttempt=f.currentRetryAttempt||0,f.retry=f.retry===void 0||f.retry===null?3:f.retry,f.httpMethodsToRetry=f.httpMethodsToRetry||["GET","HEAD","PUT","OPTIONS","DELETE"],f.noResponseRetries=f.noResponseRetries===void 0||f.noResponseRetries===null?2:f.noResponseRetries,f.retryDelayMultiplier=f.retryDelayMultiplier?f.retryDelayMultiplier:2,f.timeOfFirstRequest=f.timeOfFirstRequest?f.timeOfFirstRequest:Date.now(),f.totalTimeout=f.totalTimeout?f.totalTimeout:Number.MAX_SAFE_INTEGER,f.maxRetryDelay=f.maxRetryDelay?f.maxRetryDelay:Number.MAX_SAFE_INTEGER;let g=[[100,199],[408,408],[429,429],[500,599]];if(f.statusCodesToRetry=f.statusCodesToRetry||g,h.config.retryConfig=f,!await(f.shouldRetry||Ql)(h))return{shouldRetry:!1,config:h.config};let _=Zl(f);h.config.retryConfig.currentRetryAttempt+=1;let T=f.retryBackoff?f.retryBackoff(h,_):new Promise((S)=>{setTimeout(S,_)});if(f.onRetryAttempt)await f.onRetryAttempt(h);return await T,{shouldRetry:!0,config:h.config}}function Ql(h){let f=Xs(h);if(h.config.signal?.aborted&&h.code!=="TimeoutError"||h.code==="AbortError")return!1;if(!f||f.retry===0)return!1;if(!h.response&&(f.currentRetryAttempt||0)>=f.noResponseRetries)return!1;if(!f.httpMethodsToRetry||!f.httpMethodsToRetry.includes(h.config.method?.toUpperCase()||"GET"))return!1;if(h.response&&h.response.status){let g=!1;for(let[y,_]of f.statusCodesToRetry){let T=h.response.status;if(T>=y&&T<=_){g=!0;break}}if(!g)return!1}if(f.currentRetryAttempt=f.currentRetryAttempt||0,f.currentRetryAttempt>=f.retry)return!1;return!0}function Xs(h){if(h&&h.config&&h.config.retryConfig)return h.config.retryConfig;return}function Zl(h){let g=(h.currentRetryAttempt?0:h.retryDelay??100)+(Math.pow(h.retryDelayMultiplier,h.currentRetryAttempt)-1)/2*1000,y=h.totalTimeout-(Date.now()-h.timeOfFirstRequest);return Math.min(g,y,h.maxRetryDelay)}});var ar=i(function(ti){Object.defineProperty(ti,"__esModule",{value:!0});ti.GaxiosInterceptorManager=void 0;class ei extends Set{}ti.GaxiosInterceptorManager=ei});var ii=i(function(Qt){var tu=Qt&&Qt.__importDefault||function(h){return h&&h.__esModule?h:{default:h}},Xt;Object.defineProperty(Qt,"__esModule",{value:!0});Qt.Gaxios=void 0;var nu=tu(rr()),ru=c("https"),Wt=or(),su=Zs(),ri=c("stream"),si=ar(),iu=async()=>globalThis.crypto?.randomUUID()||(await import("crypto")).randomUUID(),ou=204;class cr{agentCache=new Map;defaults;interceptors;constructor(h){this.defaults=h||{},this.interceptors={request:new si.GaxiosInterceptorManager,response:new si.GaxiosInterceptorManager}}fetch(...h){let f=h[0],g=h[1],y=void 0,_=new Headers;if(typeof f==="string")y=new URL(f);else if(f instanceof URL)y=f;else if(f&&f.url)y=new URL(f.url);if(f&&typeof f==="object"&&"headers"in f)Xt.mergeHeaders(_,f.headers);if(g)Xt.mergeHeaders(_,new Headers(g.headers));if(typeof f==="object"&&!(f instanceof URL))return this.request({...g,...f,headers:_,url:y});else return this.request({...g,headers:_,url:y})}async request(h={}){let f=await this.#r(h);return f=await this.#t(f),this.#n(this._request(f))}async _defaultAdapter(h){let f=h.fetchImplementation||this.defaults.fetchImplementation||await Xt.#c(),g={...h};delete g.data;let y=await f(h.url,g),_=await this.getResponseData(h,y);if(!Object.getOwnPropertyDescriptor(y,"data")?.configurable)Object.defineProperties(y,{data:{configurable:!0,writable:!0,enumerable:!0,value:_}});return Object.assign(y,{config:h,data:_})}async _request(h){try{let f;if(h.adapter)f=await h.adapter(h,this._defaultAdapter.bind(this));else f=await this._defaultAdapter(h);if(!h.validateStatus(f.status)){if(h.responseType==="stream"){let y=[];for await(let _ of f.data)y.push(_);f.data=Buffer.concat(y.map((_)=>typeof _==="string"?Buffer.from(_):_)).toString("utf8")}let g=Wt.GaxiosError.extractAPIErrorFromResponse(f,`Request failed with status code ${f.status}`);throw new Wt.GaxiosError(g?.message,h,f,g)}return f}catch(f){let g;if(f instanceof Wt.GaxiosError)g=f;else if(f instanceof Error)g=new Wt.GaxiosError(f.message,h,void 0,f);else g=new Wt.GaxiosError("Unexpected Gaxios Error",h,void 0,f);let{shouldRetry:y,config:_}=await su.getRetryConfig(g);if(y&&_)return g.config.retryConfig.currentRetryAttempt=_.retryConfig.currentRetryAttempt,h.retryConfig=g.config?.retryConfig,this.#s(h),this._request(h);if(h.errorRedactor)h.errorRedactor(g);throw g}}async getResponseData(h,f){if(f.status===ou)return"";if(h.maxContentLength&&f.headers.has("content-length")&&h.maxContentLength<Number.parseInt(f.headers?.get("content-length")||""))throw new Wt.GaxiosError("Response's `Content-Length` is over the limit.",h,Object.assign(f,{config:h}));switch(h.responseType){case"stream":return f.body;case"json":{let g=await f.text();try{return JSON.parse(g)}catch{return g}}case"arraybuffer":return f.arrayBuffer();case"blob":return f.blob();case"text":return f.text();default:return this.getResponseDataFromContentType(f)}}#e(h,f=[]){let g=new URL(h),y=[...f],_=(process.env.NO_PROXY??process.env.no_proxy)?.split(",")||[];for(let T of _)y.push(T.trim());for(let T of y)if(T instanceof RegExp){if(T.test(g.toString()))return!1}else if(T instanceof URL){if(T.origin===g.origin)return!1}else if(T.startsWith("*.")||T.startsWith(".")){let S=T.replace(/^\*\./,".");if(g.hostname.endsWith(S))return!1}else if(T===g.origin||T===g.hostname||T===g.href)return!1;return!0}async#t(h){let f=Promise.resolve(h);for(let g of this.interceptors.request.values())if(g)f=f.then(g.resolved,g.rejected);return f}async#n(h){let f=Promise.resolve(h);for(let g of this.interceptors.response.values())if(g)f=f.then(g.resolved,g.rejected);return f}async#r(h){let f=new Headers(this.defaults.headers);Xt.mergeHeaders(f,h.headers);let g=(0,nu.default)(!0,{},this.defaults,h);if(!g.url)throw Error("URL is required.");if(g.baseURL)g.url=new URL(g.url,g.baseURL);if(g.url=new URL(g.url),g.params)if(g.paramsSerializer){let T=g.paramsSerializer(g.params);if(T.startsWith("?"))T=T.slice(1);let S=g.url.toString().includes("?")?"&":"?";g.url=g.url+S+T}else{let T=g.url instanceof URL?g.url:new URL(g.url);for(let[S,w]of new URLSearchParams(g.params))T.searchParams.append(S,w);g.url=T}if(typeof h.maxContentLength==="number")g.size=h.maxContentLength;if(typeof h.maxRedirects==="number")g.follow=h.maxRedirects;let y=typeof g.data==="string"||g.data instanceof ArrayBuffer||g.data instanceof Blob||globalThis.File&&g.data instanceof File||g.data instanceof FormData||g.data instanceof ri.Readable||g.data instanceof ReadableStream||g.data instanceof String||g.data instanceof URLSearchParams||ArrayBuffer.isView(g.data)||["Blob","File","FormData"].includes(g.data?.constructor?.name||"");if(g.multipart?.length){let T=await iu();f.set("content-type",`multipart/related; boundary=${T}`),g.body=ri.Readable.from(this.getMultipartRequest(g.multipart,T))}else if(y)g.body=g.data;else if(typeof g.data==="object")if(f.get("Content-Type")==="application/x-www-form-urlencoded")g.body=g.paramsSerializer?g.paramsSerializer(g.data):new URLSearchParams(g.data);else{if(!f.has("content-type"))f.set("content-type","application/json");g.body=JSON.stringify(g.data)}else if(g.data)g.body=g.data;if(g.validateStatus=g.validateStatus||this.validateStatus,g.responseType=g.responseType||"unknown",!f.has("accept")&&g.responseType==="json")f.set("accept","application/json");let _=g.proxy||process?.env?.HTTPS_PROXY||process?.env?.https_proxy||process?.env?.HTTP_PROXY||process?.env?.http_proxy;if(g.agent);else if(_&&this.#e(g.url,g.noProxy)){let T=await Xt.#a();if(this.agentCache.has(_))g.agent=this.agentCache.get(_);else g.agent=new T(_,{cert:g.cert,key:g.key}),this.agentCache.set(_,g.agent)}else if(g.cert&&g.key)if(this.agentCache.has(g.key))g.agent=this.agentCache.get(g.key);else g.agent=new ru.Agent({cert:g.cert,key:g.key}),this.agentCache.set(g.key,g.agent);if(typeof g.errorRedactor!=="function"&&g.errorRedactor!==!1)g.errorRedactor=Wt.defaultErrorRedactor;if(g.body&&!("duplex"in g))g.duplex="half";return this.#s(g),Object.assign(g,{headers:f,url:g.url instanceof URL?g.url:new URL(g.url)})}#s(h){if(h.timeout){let f=AbortSignal.timeout(h.timeout);if(h.signal&&!h.signal.aborted)h.signal=AbortSignal.any([h.signal,f]);else h.signal=f}}validateStatus(h){return h>=200&&h<300}async getResponseDataFromContentType(h){let f=h.headers.get("Content-Type");if(f===null)return h.text();if(f=f.toLowerCase(),f.includes("application/json")){let g=await h.text();try{g=JSON.parse(g)}catch{}return g}else if(f.match(/^text\//))return h.text();else return h.blob()}async*getMultipartRequest(h,f){let g=`--${f}--`;for(let y of h){let _=y.headers.get("Content-Type")||"application/octet-stream";if(yield`--${f}\r
|
|
3
|
+
Content-Type: ${_}\r
|
|
4
|
+
\r
|
|
5
|
+
`,typeof y.content==="string")yield y.content;else yield*y.content;yield`\r
|
|
6
|
+
`}yield g}static#i;static#o;static async#a(){return this.#i||=(await import("./index-yfdscfdx.js").then((m)=>v(m.default))).HttpsProxyAgent,this.#i}static async#c(){let h=typeof window<"u"&&!!window;return this.#o||=h?window.fetch:(await import("./index-t3eanyjj.js")).default,this.#o}static mergeHeaders(h,...f){h=h instanceof Headers?h:new Headers(h);for(let g of f)(g instanceof Headers?g:new Headers(g)).forEach((_,T)=>{T==="set-cookie"?h.append(T,_):h.set(T,_)});return h}}Qt.Gaxios=cr;Xt=cr});var ct=i(function(gt){var au=gt&>.__createBinding||(Object.create?function(h,f,g,y){if(y===void 0)y=g;var _=Object.getOwnPropertyDescriptor(f,g);if(!_||("get"in _?!f.__esModule:_.writable||_.configurable))_={enumerable:!0,get:function(){return f[g]}};Object.defineProperty(h,y,_)}:function(h,f,g,y){if(y===void 0)y=g;h[y]=f[g]}),cu=gt&>.__exportStar||function(h,f){for(var g in h)if(g!=="default"&&!Object.prototype.hasOwnProperty.call(f,g))au(f,h,g)};Object.defineProperty(gt,"__esModule",{value:!0});gt.instance=gt.Gaxios=gt.GaxiosError=void 0;gt.request=uu;var oi=ii();Object.defineProperty(gt,"Gaxios",{enumerable:!0,get:function(){return oi.Gaxios}});var lu=or();Object.defineProperty(gt,"GaxiosError",{enumerable:!0,get:function(){return lu.GaxiosError}});cu(ar(),gt);gt.instance=new oi.Gaxios;async function uu(h){return gt.instance.request(h)}});var lr=i(function(ai,bn){(function(h){var f,g=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,{ceil:y,floor:_}=Math,T="[BigNumber Error] ",S=T+"Number primitive has more than 15 significant digits: ",w=100000000000000,x=14,B=9007199254740991,P=[1,10,100,1000,1e4,1e5,1e6,1e7,1e8,1e9,10000000000,100000000000,1000000000000,10000000000000],ne=1e7,se=1e9;function X(U){var de,ye,Ce,_e=fe.prototype={constructor:fe,toString:null,valueOf:null},Pe=new fe(1),Re=20,Ne=4,Je=-7,je=21,Ye=-1e7,Ue=1e7,ze=!1,Ze=1,nt=0,ot={prefix:"",groupSize:3,secondaryGroupSize:0,groupSeparator:",",decimalSeparator:".",fractionGroupSize:0,fractionGroupSeparator:" ",suffix:""},et="0123456789abcdefghijklmnopqrstuvwxyz",mt=!0;function fe(O,N){var R,K,J,re,pe,V,Y,ce,ie=this;if(!(ie instanceof fe))return new fe(O,N);if(N==null){if(O&&O._isBigNumber===!0){if(ie.s=O.s,!O.c||O.e>Ue)ie.c=ie.e=null;else if(O.e<Ye)ie.c=[ie.e=0];else ie.e=O.e,ie.c=O.c.slice();return}if((V=typeof O=="number")&&O*0==0){if(ie.s=1/O<0?(O=-O,-1):1,O===~~O){for(re=0,pe=O;pe>=10;pe/=10,re++);if(re>Ue)ie.c=ie.e=null;else ie.e=re,ie.c=[O];return}ce=String(O)}else{if(!g.test(ce=String(O)))return Ce(ie,ce,V);ie.s=ce.charCodeAt(0)==45?(ce=ce.slice(1),-1):1}if((re=ce.indexOf("."))>-1)ce=ce.replace(".","");if((pe=ce.search(/e/i))>0){if(re<0)re=pe;re+=+ce.slice(pe+1),ce=ce.substring(0,pe)}else if(re<0)re=ce.length}else{if(M(N,2,et.length,"Base"),N==10&&mt)return ie=new fe(O),Le(ie,Re+ie.e+1,Ne);if(ce=String(O),V=typeof O=="number"){if(O*0!=0)return Ce(ie,ce,V,N);if(ie.s=1/O<0?(ce=ce.slice(1),-1):1,fe.DEBUG&&ce.replace(/^0\.0*|\./,"").length>15)throw Error(S+O)}else ie.s=ce.charCodeAt(0)===45?(ce=ce.slice(1),-1):1;R=et.slice(0,N),re=pe=0;for(Y=ce.length;pe<Y;pe++)if(R.indexOf(K=ce.charAt(pe))<0){if(K=="."){if(pe>re){re=Y;continue}}else if(!J){if(ce==ce.toUpperCase()&&(ce=ce.toLowerCase())||ce==ce.toLowerCase()&&(ce=ce.toUpperCase())){J=!0,pe=-1,re=0;continue}}return Ce(ie,String(O),V,N)}if(V=!1,ce=ye(ce,N,10,ie.s),(re=ce.indexOf("."))>-1)ce=ce.replace(".","");else re=ce.length}for(pe=0;ce.charCodeAt(pe)===48;pe++);for(Y=ce.length;ce.charCodeAt(--Y)===48;);if(ce=ce.slice(pe,++Y)){if(Y-=pe,V&&fe.DEBUG&&Y>15&&(O>B||O!==_(O)))throw Error(S+ie.s*O);if((re=re-pe-1)>Ue)ie.c=ie.e=null;else if(re<Ye)ie.c=[ie.e=0];else{if(ie.e=re,ie.c=[],pe=(re+1)%x,re<0)pe+=x;if(pe<Y){if(pe)ie.c.push(+ce.slice(0,pe));for(Y-=x;pe<Y;)ie.c.push(+ce.slice(pe,pe+=x));pe=x-(ce=ce.slice(pe)).length}else pe-=Y;for(;pe--;ce+="0");ie.c.push(+ce)}}else ie.c=[ie.e=0]}fe.clone=X,fe.ROUND_UP=0,fe.ROUND_DOWN=1,fe.ROUND_CEIL=2,fe.ROUND_FLOOR=3,fe.ROUND_HALF_UP=4,fe.ROUND_HALF_DOWN=5,fe.ROUND_HALF_EVEN=6,fe.ROUND_HALF_CEIL=7,fe.ROUND_HALF_FLOOR=8,fe.EUCLID=9,fe.config=fe.set=function(O){var N,R;if(O!=null)if(typeof O=="object"){if(O.hasOwnProperty(N="DECIMAL_PLACES"))R=O[N],M(R,0,se,N),Re=R;if(O.hasOwnProperty(N="ROUNDING_MODE"))R=O[N],M(R,0,8,N),Ne=R;if(O.hasOwnProperty(N="EXPONENTIAL_AT"))if(R=O[N],R&&R.pop)M(R[0],-se,0,N),M(R[1],0,se,N),Je=R[0],je=R[1];else M(R,-se,se,N),Je=-(je=R<0?-R:R);if(O.hasOwnProperty(N="RANGE"))if(R=O[N],R&&R.pop)M(R[0],-se,-1,N),M(R[1],1,se,N),Ye=R[0],Ue=R[1];else if(M(R,-se,se,N),R)Ye=-(Ue=R<0?-R:R);else throw Error(T+N+" cannot be zero: "+R);if(O.hasOwnProperty(N="CRYPTO"))if(R=O[N],R===!!R)if(R)if(typeof crypto<"u"&&crypto&&(crypto.getRandomValues||crypto.randomBytes))ze=R;else throw ze=!R,Error(T+"crypto unavailable");else ze=R;else throw Error(T+N+" not true or false: "+R);if(O.hasOwnProperty(N="MODULO_MODE"))R=O[N],M(R,0,9,N),Ze=R;if(O.hasOwnProperty(N="POW_PRECISION"))R=O[N],M(R,0,se,N),nt=R;if(O.hasOwnProperty(N="FORMAT"))if(R=O[N],typeof R=="object")ot=R;else throw Error(T+N+" not an object: "+R);if(O.hasOwnProperty(N="ALPHABET"))if(R=O[N],typeof R=="string"&&!/^.?$|[+\-.\s]|(.).*\1/.test(R))mt=R.slice(0,10)=="0123456789",et=R;else throw Error(T+N+" invalid: "+R)}else throw Error(T+"Object expected: "+O);return{DECIMAL_PLACES:Re,ROUNDING_MODE:Ne,EXPONENTIAL_AT:[Je,je],RANGE:[Ye,Ue],CRYPTO:ze,MODULO_MODE:Ze,POW_PRECISION:nt,FORMAT:ot,ALPHABET:et}},fe.isBigNumber=function(O){if(!O||O._isBigNumber!==!0)return!1;if(!fe.DEBUG)return!0;var N,R,{c:K,e:J,s:re}=O;e:if({}.toString.call(K)=="[object Array]"){if((re===1||re===-1)&&J>=-se&&J<=se&&J===_(J)){if(K[0]===0){if(J===0&&K.length===1)return!0;break e}if(N=(J+1)%x,N<1)N+=x;if(String(K[0]).length==N){for(N=0;N<K.length;N++)if(R=K[N],R<0||R>=w||R!==_(R))break e;if(R!==0)return!0}}}else if(K===null&&J===null&&(re===null||re===1||re===-1))return!0;throw Error(T+"Invalid BigNumber: "+O)},fe.maximum=fe.max=function(){return at(arguments,-1)},fe.minimum=fe.min=function(){return at(arguments,1)},fe.random=function(){var O=9007199254740992,N=Math.random()*O&2097151?function(){return _(Math.random()*O)}:function(){return(Math.random()*1073741824|0)*8388608+(Math.random()*8388608|0)};return function(R){var K,J,re,pe,V,Y=0,ce=[],ie=new fe(Pe);if(R==null)R=Re;else M(R,0,se);if(pe=y(R/x),ze)if(crypto.getRandomValues){K=crypto.getRandomValues(new Uint32Array(pe*=2));for(;Y<pe;)if(V=K[Y]*131072+(K[Y+1]>>>11),V>=9000000000000000)J=crypto.getRandomValues(new Uint32Array(2)),K[Y]=J[0],K[Y+1]=J[1];else ce.push(V%100000000000000),Y+=2;Y=pe/2}else if(crypto.randomBytes){K=crypto.randomBytes(pe*=7);for(;Y<pe;)if(V=(K[Y]&31)*281474976710656+K[Y+1]*1099511627776+K[Y+2]*4294967296+K[Y+3]*16777216+(K[Y+4]<<16)+(K[Y+5]<<8)+K[Y+6],V>=9000000000000000)crypto.randomBytes(7).copy(K,Y);else ce.push(V%100000000000000),Y+=7;Y=pe/7}else throw ze=!1,Error(T+"crypto unavailable");if(!ze){for(;Y<pe;)if(V=N(),V<9000000000000000)ce[Y++]=V%100000000000000}if(pe=ce[--Y],R%=x,pe&&R)V=P[x-R],ce[Y]=_(pe/V)*V;for(;ce[Y]===0;ce.pop(),Y--);if(Y<0)ce=[re=0];else{for(re=-1;ce[0]===0;ce.splice(0,1),re-=x);for(Y=1,V=ce[0];V>=10;V/=10,Y++);if(Y<x)re-=x-Y}return ie.e=re,ie.c=ce,ie}}(),fe.sum=function(){var O=1,N=arguments,R=new fe(N[0]);for(;O<N.length;)R=R.plus(N[O++]);return R},ye=function(){var O="0123456789";function N(R,K,J,re){var pe,V=[0],Y,ce=0,ie=R.length;for(;ce<ie;){for(Y=V.length;Y--;V[Y]*=K);V[0]+=re.indexOf(R.charAt(ce++));for(pe=0;pe<V.length;pe++)if(V[pe]>J-1){if(V[pe+1]==null)V[pe+1]=0;V[pe+1]+=V[pe]/J|0,V[pe]%=J}}return V.reverse()}return function(R,K,J,re,pe){var V,Y,ce,ie,me,ke,xe,Be,Xe=R.indexOf("."),st=Re,Ge=Ne;if(Xe>=0)ie=nt,nt=0,R=R.replace(".",""),Be=new fe(K),ke=Be.pow(R.length-Xe),nt=ie,Be.c=N(q(Z(ke.c),ke.e,"0"),10,J,O),Be.e=Be.c.length;xe=N(R,K,J,pe?(V=et,O):(V=O,et)),ce=ie=xe.length;for(;xe[--ie]==0;xe.pop());if(!xe[0])return V.charAt(0);if(Xe<0)--ce;else ke.c=xe,ke.e=ce,ke.s=re,ke=de(ke,Be,st,Ge,J),xe=ke.c,me=ke.r,ce=ke.e;if(Y=ce+st+1,Xe=xe[Y],ie=J/2,me=me||Y<0||xe[Y+1]!=null,me=Ge<4?(Xe!=null||me)&&(Ge==0||Ge==(ke.s<0?3:2)):Xe>ie||Xe==ie&&(Ge==4||me||Ge==6&&xe[Y-1]&1||Ge==(ke.s<0?8:7)),Y<1||!xe[0])R=me?q(V.charAt(1),-st,V.charAt(0)):V.charAt(0);else{if(xe.length=Y,me){for(--J;++xe[--Y]>J;)if(xe[Y]=0,!Y)++ce,xe=[1].concat(xe)}for(ie=xe.length;!xe[--ie];);for(Xe=0,R="";Xe<=ie;R+=V.charAt(xe[Xe++]));R=q(R,ce,V.charAt(0))}return R}}(),de=function(){function O(K,J,re){var pe,V,Y,ce,ie=0,me=K.length,ke=J%ne,xe=J/ne|0;for(K=K.slice();me--;)Y=K[me]%ne,ce=K[me]/ne|0,pe=xe*Y+ce*ke,V=ke*Y+pe%ne*ne+ie,ie=(V/re|0)+(pe/ne|0)+xe*ce,K[me]=V%re;if(ie)K=[ie].concat(K);return K}function N(K,J,re,pe){var V,Y;if(re!=pe)Y=re>pe?1:-1;else for(V=Y=0;V<re;V++)if(K[V]!=J[V]){Y=K[V]>J[V]?1:-1;break}return Y}function R(K,J,re,pe){var V=0;for(;re--;)K[re]-=V,V=K[re]<J[re]?1:0,K[re]=V*pe+K[re]-J[re];for(;!K[0]&&K.length>1;K.splice(0,1));}return function(K,J,re,pe,V){var Y,ce,ie,me,ke,xe,Be,Xe,st,Ge,Ve,ht,Cn,tr,nr,Rt,un,Et=K.s==J.s?1:-1,pt=K.c,Qe=J.c;if(!pt||!pt[0]||!Qe||!Qe[0])return new fe(!K.s||!J.s||(pt?Qe&&pt[0]==Qe[0]:!Qe)?NaN:pt&&pt[0]==0||!Qe?Et*0:Et/0);if(Xe=new fe(Et),st=Xe.c=[],ce=K.e-J.e,Et=re+ce+1,!V)V=w,ce=z(K.e/x)-z(J.e/x),Et=Et/x|0;for(ie=0;Qe[ie]==(pt[ie]||0);ie++);if(Qe[ie]>(pt[ie]||0))ce--;if(Et<0)st.push(1),me=!0;else{if(tr=pt.length,Rt=Qe.length,ie=0,Et+=2,ke=_(V/(Qe[0]+1)),ke>1)Qe=O(Qe,ke,V),pt=O(pt,ke,V),Rt=Qe.length,tr=pt.length;Cn=Rt,Ge=pt.slice(0,Rt),Ve=Ge.length;for(;Ve<Rt;Ge[Ve++]=0);if(un=Qe.slice(),un=[0].concat(un),nr=Qe[0],Qe[1]>=V/2)nr++;do{if(ke=0,Y=N(Qe,Ge,Rt,Ve),Y<0){if(ht=Ge[0],Rt!=Ve)ht=ht*V+(Ge[1]||0);if(ke=_(ht/nr),ke>1){if(ke>=V)ke=V-1;xe=O(Qe,ke,V),Be=xe.length,Ve=Ge.length;while(N(xe,Ge,Be,Ve)==1)ke--,R(xe,Rt<Be?un:Qe,Be,V),Be=xe.length,Y=1}else{if(ke==0)Y=ke=1;xe=Qe.slice(),Be=xe.length}if(Be<Ve)xe=[0].concat(xe);if(R(Ge,xe,Ve,V),Ve=Ge.length,Y==-1)while(N(Qe,Ge,Rt,Ve)<1)ke++,R(Ge,Rt<Ve?un:Qe,Ve,V),Ve=Ge.length}else if(Y===0)ke++,Ge=[0];if(st[ie++]=ke,Ge[0])Ge[Ve++]=pt[Cn]||0;else Ge=[pt[Cn]],Ve=1}while((Cn++<tr||Ge[0]!=null)&&Et--);if(me=Ge[0]!=null,!st[0])st.splice(0,1)}if(V==w){for(ie=1,Et=st[0];Et>=10;Et/=10,ie++);Le(Xe,re+(Xe.e=ie+ce*x-1)+1,pe,me)}else Xe.e=ce,Xe.r=+me;return Xe}}();function be(O,N,R,K){var J,re,pe,V,Y;if(R==null)R=Ne;else M(R,0,8);if(!O.c)return O.toString();if(J=O.c[0],pe=O.e,N==null)Y=Z(O.c),Y=K==1||K==2&&(pe<=Je||pe>=je)?he(Y,pe):q(Y,pe,"0");else if(O=Le(new fe(O),N,R),re=O.e,Y=Z(O.c),V=Y.length,K==1||K==2&&(N<=re||re<=Je)){for(;V<N;Y+="0",V++);Y=he(Y,re)}else if(N-=pe+(K===2&&re>pe),Y=q(Y,re,"0"),re+1>V){if(--N>0)for(Y+=".";N--;Y+="0");}else if(N+=re-V,N>0){if(re+1==V)Y+=".";for(;N--;Y+="0");}return O.s<0&&J?"-"+Y:Y}function at(O,N){var R,K,J=1,re=new fe(O[0]);for(;J<O.length;J++)if(K=new fe(O[J]),!K.s||(R=ue(re,K))===N||R===0&&re.s===N)re=K;return re}function rt(O,N,R){var K=1,J=N.length;for(;!N[--J];N.pop());for(J=N[0];J>=10;J/=10,K++);if((R=K+R*x-1)>Ue)O.c=O.e=null;else if(R<Ye)O.c=[O.e=0];else O.e=R,O.c=N;return O}Ce=function(){var O=/^(-?)0([xbo])(?=\w[\w.]*$)/i,N=/^([^.]+)\.$/,R=/^\.([^.]+)$/,K=/^-?(Infinity|NaN)$/,J=/^\s*\+(?=[\w.])|^\s+|\s+$/g;return function(re,pe,V,Y){var ce,ie=V?pe:pe.replace(J,"");if(K.test(ie))re.s=isNaN(ie)?null:ie<0?-1:1;else{if(!V){if(ie=ie.replace(O,function(me,ke,xe){return ce=(xe=xe.toLowerCase())=="x"?16:xe=="b"?2:8,!Y||Y==ce?ke:me}),Y)ce=Y,ie=ie.replace(N,"$1").replace(R,"0.$1");if(pe!=ie)return new fe(ie,ce)}if(fe.DEBUG)throw Error(T+"Not a"+(Y?" base "+Y:"")+" number: "+pe);re.s=null}re.c=re.e=null}}();function Le(O,N,R,K){var J,re,pe,V,Y,ce,ie,me=O.c,ke=P;if(me){e:{for(J=1,V=me[0];V>=10;V/=10,J++);if(re=N-J,re<0)re+=x,pe=N,Y=me[ce=0],ie=_(Y/ke[J-pe-1]%10);else if(ce=y((re+1)/x),ce>=me.length)if(K){for(;me.length<=ce;me.push(0));Y=ie=0,J=1,re%=x,pe=re-x+1}else break e;else{Y=V=me[ce];for(J=1;V>=10;V/=10,J++);re%=x,pe=re-x+J,ie=pe<0?0:_(Y/ke[J-pe-1]%10)}if(K=K||N<0||me[ce+1]!=null||(pe<0?Y:Y%ke[J-pe-1]),K=R<4?(ie||K)&&(R==0||R==(O.s<0?3:2)):ie>5||ie==5&&(R==4||K||R==6&&(re>0?pe>0?Y/ke[J-pe]:0:me[ce-1])%10&1||R==(O.s<0?8:7)),N<1||!me[0]){if(me.length=0,K)N-=O.e+1,me[0]=ke[(x-N%x)%x],O.e=-N||0;else me[0]=O.e=0;return O}if(re==0)me.length=ce,V=1,ce--;else me.length=ce+1,V=ke[x-re],me[ce]=pe>0?_(Y/ke[J-pe]%ke[pe])*V:0;if(K)for(;;)if(ce==0){for(re=1,pe=me[0];pe>=10;pe/=10,re++);pe=me[0]+=V;for(V=1;pe>=10;pe/=10,V++);if(re!=V){if(O.e++,me[0]==w)me[0]=1}break}else{if(me[ce]+=V,me[ce]!=w)break;me[ce--]=0,V=1}for(re=me.length;me[--re]===0;me.pop());}if(O.e>Ue)O.c=O.e=null;else if(O.e<Ye)O.c=[O.e=0]}return O}function _t(O){var N,R=O.e;if(R===null)return O.toString();return N=Z(O.c),N=R<=Je||R>=je?he(N,R):q(N,R,"0"),O.s<0?"-"+N:N}if(_e.absoluteValue=_e.abs=function(){var O=new fe(this);if(O.s<0)O.s=1;return O},_e.comparedTo=function(O,N){return ue(this,new fe(O,N))},_e.decimalPlaces=_e.dp=function(O,N){var R,K,J,re=this;if(O!=null){if(M(O,0,se),N==null)N=Ne;else M(N,0,8);return Le(new fe(re),O+re.e+1,N)}if(!(R=re.c))return null;if(K=((J=R.length-1)-z(this.e/x))*x,J=R[J])for(;J%10==0;J/=10,K--);if(K<0)K=0;return K},_e.dividedBy=_e.div=function(O,N){return de(this,new fe(O,N),Re,Ne)},_e.dividedToIntegerBy=_e.idiv=function(O,N){return de(this,new fe(O,N),0,1)},_e.exponentiatedBy=_e.pow=function(O,N){var R,K,J,re,pe,V,Y,ce,ie,me=this;if(O=new fe(O),O.c&&!O.isInteger())throw Error(T+"Exponent not an integer: "+_t(O));if(N!=null)N=new fe(N);if(V=O.e>14,!me.c||!me.c[0]||me.c[0]==1&&!me.e&&me.c.length==1||!O.c||!O.c[0])return ie=new fe(Math.pow(+_t(me),V?O.s*(2-L(O)):+_t(O))),N?ie.mod(N):ie;if(Y=O.s<0,N){if(N.c?!N.c[0]:!N.s)return new fe(NaN);if(K=!Y&&me.isInteger()&&N.isInteger(),K)me=me.mod(N)}else if(O.e>9&&(me.e>0||me.e<-1||(me.e==0?me.c[0]>1||V&&me.c[1]>=240000000:me.c[0]<80000000000000||V&&me.c[0]<=99999750000000))){if(re=me.s<0&&L(O)?-0:0,me.e>-1)re=1/re;return new fe(Y?1/re:re)}else if(nt)re=y(nt/x+2);if(V){if(R=new fe(0.5),Y)O.s=1;ce=L(O)}else J=Math.abs(+_t(O)),ce=J%2;ie=new fe(Pe);for(;;){if(ce){if(ie=ie.times(me),!ie.c)break;if(re){if(ie.c.length>re)ie.c.length=re}else if(K)ie=ie.mod(N)}if(J){if(J=_(J/2),J===0)break;ce=J%2}else if(O=O.times(R),Le(O,O.e+1,1),O.e>14)ce=L(O);else{if(J=+_t(O),J===0)break;ce=J%2}if(me=me.times(me),re){if(me.c&&me.c.length>re)me.c.length=re}else if(K)me=me.mod(N)}if(K)return ie;if(Y)ie=Pe.div(ie);return N?ie.mod(N):re?Le(ie,nt,Ne,pe):ie},_e.integerValue=function(O){var N=new fe(this);if(O==null)O=Ne;else M(O,0,8);return Le(N,N.e+1,O)},_e.isEqualTo=_e.eq=function(O,N){return ue(this,new fe(O,N))===0},_e.isFinite=function(){return!!this.c},_e.isGreaterThan=_e.gt=function(O,N){return ue(this,new fe(O,N))>0},_e.isGreaterThanOrEqualTo=_e.gte=function(O,N){return(N=ue(this,new fe(O,N)))===1||N===0},_e.isInteger=function(){return!!this.c&&z(this.e/x)>this.c.length-2},_e.isLessThan=_e.lt=function(O,N){return ue(this,new fe(O,N))<0},_e.isLessThanOrEqualTo=_e.lte=function(O,N){return(N=ue(this,new fe(O,N)))===-1||N===0},_e.isNaN=function(){return!this.s},_e.isNegative=function(){return this.s<0},_e.isPositive=function(){return this.s>0},_e.isZero=function(){return!!this.c&&this.c[0]==0},_e.minus=function(O,N){var R,K,J,re,pe=this,V=pe.s;if(O=new fe(O,N),N=O.s,!V||!N)return new fe(NaN);if(V!=N)return O.s=-N,pe.plus(O);var Y=pe.e/x,ce=O.e/x,ie=pe.c,me=O.c;if(!Y||!ce){if(!ie||!me)return ie?(O.s=-N,O):new fe(me?pe:NaN);if(!ie[0]||!me[0])return me[0]?(O.s=-N,O):new fe(ie[0]?pe:Ne==3?-0:0)}if(Y=z(Y),ce=z(ce),ie=ie.slice(),V=Y-ce){if(re=V<0)V=-V,J=ie;else ce=Y,J=me;J.reverse();for(N=V;N--;J.push(0));J.reverse()}else{K=(re=(V=ie.length)<(N=me.length))?V:N;for(V=N=0;N<K;N++)if(ie[N]!=me[N]){re=ie[N]<me[N];break}}if(re)J=ie,ie=me,me=J,O.s=-O.s;if(N=(K=me.length)-(R=ie.length),N>0)for(;N--;ie[R++]=0);N=w-1;for(;K>V;){if(ie[--K]<me[K]){for(R=K;R&&!ie[--R];ie[R]=N);--ie[R],ie[K]+=w}ie[K]-=me[K]}for(;ie[0]==0;ie.splice(0,1),--ce);if(!ie[0])return O.s=Ne==3?-1:1,O.c=[O.e=0],O;return rt(O,ie,ce)},_e.modulo=_e.mod=function(O,N){var R,K,J=this;if(O=new fe(O,N),!J.c||!O.s||O.c&&!O.c[0])return new fe(NaN);else if(!O.c||J.c&&!J.c[0])return new fe(J);if(Ze==9)K=O.s,O.s=1,R=de(J,O,0,3),O.s=K,R.s*=K;else R=de(J,O,0,Ze);if(O=J.minus(R.times(O)),!O.c[0]&&Ze==1)O.s=J.s;return O},_e.multipliedBy=_e.times=function(O,N){var R,K,J,re,pe,V,Y,ce,ie,me,ke,xe,Be,Xe,st,Ge=this,Ve=Ge.c,ht=(O=new fe(O,N)).c;if(!Ve||!ht||!Ve[0]||!ht[0]){if(!Ge.s||!O.s||Ve&&!Ve[0]&&!ht||ht&&!ht[0]&&!Ve)O.c=O.e=O.s=null;else if(O.s*=Ge.s,!Ve||!ht)O.c=O.e=null;else O.c=[0],O.e=0;return O}if(K=z(Ge.e/x)+z(O.e/x),O.s*=Ge.s,Y=Ve.length,me=ht.length,Y<me)Be=Ve,Ve=ht,ht=Be,J=Y,Y=me,me=J;for(J=Y+me,Be=[];J--;Be.push(0));Xe=w,st=ne;for(J=me;--J>=0;){R=0,ke=ht[J]%st,xe=ht[J]/st|0;for(pe=Y,re=J+pe;re>J;)ce=Ve[--pe]%st,ie=Ve[pe]/st|0,V=xe*ce+ie*ke,ce=ke*ce+V%st*st+Be[re]+R,R=(ce/Xe|0)+(V/st|0)+xe*ie,Be[re--]=ce%Xe;Be[re]=R}if(R)++K;else Be.splice(0,1);return rt(O,Be,K)},_e.negated=function(){var O=new fe(this);return O.s=-O.s||null,O},_e.plus=function(O,N){var R,K=this,J=K.s;if(O=new fe(O,N),N=O.s,!J||!N)return new fe(NaN);if(J!=N)return O.s=-N,K.minus(O);var re=K.e/x,pe=O.e/x,V=K.c,Y=O.c;if(!re||!pe){if(!V||!Y)return new fe(J/0);if(!V[0]||!Y[0])return Y[0]?O:new fe(V[0]?K:J*0)}if(re=z(re),pe=z(pe),V=V.slice(),J=re-pe){if(J>0)pe=re,R=Y;else J=-J,R=V;R.reverse();for(;J--;R.push(0));R.reverse()}if(J=V.length,N=Y.length,J-N<0)R=Y,Y=V,V=R,N=J;for(J=0;N;)J=(V[--N]=V[N]+Y[N]+J)/w|0,V[N]=w===V[N]?0:V[N]%w;if(J)V=[J].concat(V),++pe;return rt(O,V,pe)},_e.precision=_e.sd=function(O,N){var R,K,J,re=this;if(O!=null&&O!==!!O){if(M(O,1,se),N==null)N=Ne;else M(N,0,8);return Le(new fe(re),O,N)}if(!(R=re.c))return null;if(J=R.length-1,K=J*x+1,J=R[J]){for(;J%10==0;J/=10,K--);for(J=R[0];J>=10;J/=10,K++);}if(O&&re.e+1>K)K=re.e+1;return K},_e.shiftedBy=function(O){return M(O,-B,B),this.times("1e"+O)},_e.squareRoot=_e.sqrt=function(){var O,N,R,K,J,re=this,{c:pe,s:V,e:Y}=re,ce=Re+4,ie=new fe("0.5");if(V!==1||!pe||!pe[0])return new fe(!V||V<0&&(!pe||pe[0])?NaN:pe?re:1/0);if(V=Math.sqrt(+_t(re)),V==0||V==1/0){if(N=Z(pe),(N.length+Y)%2==0)N+="0";if(V=Math.sqrt(+N),Y=z((Y+1)/2)-(Y<0||Y%2),V==1/0)N="5e"+Y;else N=V.toExponential(),N=N.slice(0,N.indexOf("e")+1)+Y;R=new fe(N)}else R=new fe(V+"");if(R.c[0]){if(Y=R.e,V=Y+ce,V<3)V=0;for(;;)if(J=R,R=ie.times(J.plus(de(re,J,ce,1))),Z(J.c).slice(0,V)===(N=Z(R.c)).slice(0,V)){if(R.e<Y)--V;if(N=N.slice(V-3,V+1),N=="9999"||!K&&N=="4999"){if(!K){if(Le(J,J.e+Re+2,0),J.times(J).eq(re)){R=J;break}}ce+=4,V+=4,K=1}else{if(!+N||!+N.slice(1)&&N.charAt(0)=="5")Le(R,R.e+Re+2,1),O=!R.times(R).eq(re);break}}}return Le(R,R.e+Re+1,Ne,O)},_e.toExponential=function(O,N){if(O!=null)M(O,0,se),O++;return be(this,O,N,1)},_e.toFixed=function(O,N){if(O!=null)M(O,0,se),O=O+this.e+1;return be(this,O,N)},_e.toFormat=function(O,N,R){var K,J=this;if(R==null)if(O!=null&&N&&typeof N=="object")R=N,N=null;else if(O&&typeof O=="object")R=O,O=N=null;else R=ot;else if(typeof R!="object")throw Error(T+"Argument not an object: "+R);if(K=J.toFixed(O,N),J.c){var re,pe=K.split("."),V=+R.groupSize,Y=+R.secondaryGroupSize,ce=R.groupSeparator||"",ie=pe[0],me=pe[1],ke=J.s<0,xe=ke?ie.slice(1):ie,Be=xe.length;if(Y)re=V,V=Y,Y=re,Be-=re;if(V>0&&Be>0){re=Be%V||V,ie=xe.substr(0,re);for(;re<Be;re+=V)ie+=ce+xe.substr(re,V);if(Y>0)ie+=ce+xe.slice(re);if(ke)ie="-"+ie}K=me?ie+(R.decimalSeparator||"")+((Y=+R.fractionGroupSize)?me.replace(new RegExp("\\d{"+Y+"}\\B","g"),"$&"+(R.fractionGroupSeparator||"")):me):ie}return(R.prefix||"")+K+(R.suffix||"")},_e.toFraction=function(O){var N,R,K,J,re,pe,V,Y,ce,ie,me,ke,xe=this,Be=xe.c;if(O!=null){if(V=new fe(O),!V.isInteger()&&(V.c||V.s!==1)||V.lt(Pe))throw Error(T+"Argument "+(V.isInteger()?"out of range: ":"not an integer: ")+_t(V))}if(!Be)return new fe(xe);N=new fe(Pe),ce=R=new fe(Pe),K=Y=new fe(Pe),ke=Z(Be),re=N.e=ke.length-xe.e-1,N.c[0]=P[(pe=re%x)<0?x+pe:pe],O=!O||V.comparedTo(N)>0?re>0?N:ce:V,pe=Ue,Ue=1/0,V=new fe(ke),Y.c[0]=0;for(;;){if(ie=de(V,N,0,1),J=R.plus(ie.times(K)),J.comparedTo(O)==1)break;R=K,K=J,ce=Y.plus(ie.times(J=ce)),Y=J,N=V.minus(ie.times(J=N)),V=J}return J=de(O.minus(R),K,0,1),Y=Y.plus(J.times(ce)),R=R.plus(J.times(K)),Y.s=ce.s=xe.s,re=re*2,me=de(ce,K,re,Ne).minus(xe).abs().comparedTo(de(Y,R,re,Ne).minus(xe).abs())<1?[ce,K]:[Y,R],Ue=pe,me},_e.toNumber=function(){return+_t(this)},_e.toPrecision=function(O,N){if(O!=null)M(O,1,se);return be(this,O,N,2)},_e.toString=function(O){var N,R=this,K=R.s,J=R.e;if(J===null)if(K){if(N="Infinity",K<0)N="-"+N}else N="NaN";else{if(O==null)N=J<=Je||J>=je?he(Z(R.c),J):q(Z(R.c),J,"0");else if(O===10&&mt)R=Le(new fe(R),Re+J+1,Ne),N=q(Z(R.c),R.e,"0");else M(O,2,et.length,"Base"),N=ye(q(Z(R.c),J,"0"),10,O,K,!0);if(K<0&&R.c[0])N="-"+N}return N},_e.valueOf=_e.toJSON=function(){return _t(this)},_e._isBigNumber=!0,U!=null)fe.set(U);return fe}function z(U){var de=U|0;return U>0||U===de?de:de-1}function Z(U){var de,ye,Ce=1,_e=U.length,Pe=U[0]+"";for(;Ce<_e;){de=U[Ce++]+"",ye=x-de.length;for(;ye--;de="0"+de);Pe+=de}for(_e=Pe.length;Pe.charCodeAt(--_e)===48;);return Pe.slice(0,_e+1||1)}function ue(U,de){var ye,Ce,_e=U.c,Pe=de.c,Re=U.s,Ne=de.s,Je=U.e,je=de.e;if(!Re||!Ne)return null;if(ye=_e&&!_e[0],Ce=Pe&&!Pe[0],ye||Ce)return ye?Ce?0:-Ne:Re;if(Re!=Ne)return Re;if(ye=Re<0,Ce=Je==je,!_e||!Pe)return Ce?0:!_e^ye?1:-1;if(!Ce)return Je>je^ye?1:-1;Ne=(Je=_e.length)<(je=Pe.length)?Je:je;for(Re=0;Re<Ne;Re++)if(_e[Re]!=Pe[Re])return _e[Re]>Pe[Re]^ye?1:-1;return Je==je?0:Je>je^ye?1:-1}function M(U,de,ye,Ce){if(U<de||U>ye||U!==_(U))throw Error(T+(Ce||"Argument")+(typeof U=="number"?U<de||U>ye?" out of range: ":" not an integer: ":" not a primitive number: ")+String(U))}function L(U){var de=U.c.length-1;return z(U.e/x)==de&&U.c[de]%2!=0}function he(U,de){return(U.length>1?U.charAt(0)+"."+U.slice(1):U)+(de<0?"e":"e+")+de}function q(U,de,ye){var Ce,_e;if(de<0){for(_e=ye+".";++de;_e+=ye);U=_e+U}else if(Ce=U.length,++de>Ce){for(_e=ye,de-=Ce;--de;_e+=ye);U+=_e}else if(de<Ce)U=U.slice(0,de)+"."+U.slice(de);return U}if(f=X(),f.default=f.BigNumber=f,typeof define=="function"&&define.amd)define(function(){return f});else if(typeof bn<"u"&&bn.exports)bn.exports=f;else{if(!h)h=typeof self<"u"&&self?self:window;h.BigNumber=f}})(ai)});var di=i(function(Fm,ui){var ci=lr(),li=Fm;(function(){function h(B){return B<10?"0"+B:B}var f=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,g=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,y,_,T={"\b":"\\b","\t":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':"\\\"","\\":"\\\\"},S;function w(B){return g.lastIndex=0,g.test(B)?'"'+B.replace(g,function(P){var ne=T[P];return typeof ne==="string"?ne:"\\u"+("0000"+P.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+B+'"'}function x(B,P){var ne,se,X,z,Z=y,ue,M=P[B],L=M!=null&&(M instanceof ci||ci.isBigNumber(M));if(M&&typeof M==="object"&&typeof M.toJSON==="function")M=M.toJSON(B);if(typeof S==="function")M=S.call(P,B,M);switch(typeof M){case"string":if(L)return M;else return w(M);case"number":return isFinite(M)?String(M):"null";case"boolean":case"null":case"bigint":return String(M);case"object":if(!M)return"null";if(y+=_,ue=[],Object.prototype.toString.apply(M)==="[object Array]"){z=M.length;for(ne=0;ne<z;ne+=1)ue[ne]=x(ne,M)||"null";return X=ue.length===0?"[]":y?`[
|
|
7
|
+
`+y+ue.join(`,
|
|
8
|
+
`+y)+`
|
|
9
|
+
`+Z+"]":"["+ue.join(",")+"]",y=Z,X}if(S&&typeof S==="object"){z=S.length;for(ne=0;ne<z;ne+=1)if(typeof S[ne]==="string"){if(se=S[ne],X=x(se,M),X)ue.push(w(se)+(y?": ":":")+X)}}else Object.keys(M).forEach(function(he){var q=x(he,M);if(q)ue.push(w(he)+(y?": ":":")+q)});return X=ue.length===0?"{}":y?`{
|
|
10
|
+
`+y+ue.join(`,
|
|
11
|
+
`+y)+`
|
|
12
|
+
`+Z+"}":"{"+ue.join(",")+"}",y=Z,X}}if(typeof li.stringify!=="function")li.stringify=function(B,P,ne){var se;if(y="",_="",typeof ne==="number")for(se=0;se<ne;se+=1)_+=" ";else if(typeof ne==="string")_=ne;if(S=P,P&&typeof P!=="function"&&(typeof P!=="object"||typeof P.length!=="number"))throw Error("JSON.stringify");return x("",{"":B})}})()});var pi=i(function(Gm,hi){var Sn=null,du=/(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])/,hu=/(?: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)/,pu=function(h){var f={strict:!1,storeAsString:!1,alwaysParseAsBig:!1,useNativeBigInt:!1,protoAction:"error",constructorAction:"error"};if(h!==void 0&&h!==null){if(h.strict===!0)f.strict=!0;if(h.storeAsString===!0)f.storeAsString=!0;if(f.alwaysParseAsBig=h.alwaysParseAsBig===!0?h.alwaysParseAsBig:!1,f.useNativeBigInt=h.useNativeBigInt===!0?h.useNativeBigInt:!1,typeof h.constructorAction<"u")if(h.constructorAction==="error"||h.constructorAction==="ignore"||h.constructorAction==="preserve")f.constructorAction=h.constructorAction;else throw Error(`Incorrect value for constructorAction option, must be "error", "ignore" or undefined but passed ${h.constructorAction}`);if(typeof h.protoAction<"u")if(h.protoAction==="error"||h.protoAction==="ignore"||h.protoAction==="preserve")f.protoAction=h.protoAction;else throw Error(`Incorrect value for protoAction option, must be "error", "ignore" or undefined but passed ${h.protoAction}`)}var g,y,_={'"':'"',"\\":"\\","/":"/",b:"\b",f:"\f",n:`
|
|
13
|
+
`,r:"\r",t:"\t"},T,S=function(Z){throw{name:"SyntaxError",message:Z,at:g,text:T}},w=function(Z){if(Z&&Z!==y)S("Expected '"+Z+"' instead of '"+y+"'");return y=T.charAt(g),g+=1,y},x=function(){var Z,ue="";if(y==="-")ue="-",w("-");while(y>="0"&&y<="9")ue+=y,w();if(y==="."){ue+=".";while(w()&&y>="0"&&y<="9")ue+=y}if(y==="e"||y==="E"){if(ue+=y,w(),y==="-"||y==="+")ue+=y,w();while(y>="0"&&y<="9")ue+=y,w()}if(Z=+ue,!isFinite(Z))S("Bad number");else{if(Sn==null)Sn=lr();if(ue.length>15)return f.storeAsString?ue:f.useNativeBigInt?BigInt(ue):new Sn(ue);else return!f.alwaysParseAsBig?Z:f.useNativeBigInt?BigInt(Z):new Sn(Z)}},B=function(){var Z,ue,M="",L;if(y==='"'){var he=g;while(w()){if(y==='"'){if(g-1>he)M+=T.substring(he,g-1);return w(),M}if(y==="\\"){if(g-1>he)M+=T.substring(he,g-1);if(w(),y==="u"){L=0;for(ue=0;ue<4;ue+=1){if(Z=parseInt(w(),16),!isFinite(Z))break;L=L*16+Z}M+=String.fromCharCode(L)}else if(typeof _[y]==="string")M+=_[y];else break;he=g}}}S("Bad string")},P=function(){while(y&&y<=" ")w()},ne=function(){switch(y){case"t":return w("t"),w("r"),w("u"),w("e"),!0;case"f":return w("f"),w("a"),w("l"),w("s"),w("e"),!1;case"n":return w("n"),w("u"),w("l"),w("l"),null}S("Unexpected '"+y+"'")},se,X=function(){var Z=[];if(y==="["){if(w("["),P(),y==="]")return w("]"),Z;while(y){if(Z.push(se()),P(),y==="]")return w("]"),Z;w(","),P()}}S("Bad array")},z=function(){var Z,ue=Object.create(null);if(y==="{"){if(w("{"),P(),y==="}")return w("}"),ue;while(y){if(Z=B(),P(),w(":"),f.strict===!0&&Object.hasOwnProperty.call(ue,Z))S('Duplicate key "'+Z+'"');if(du.test(Z)===!0)if(f.protoAction==="error")S("Object contains forbidden prototype property");else if(f.protoAction==="ignore")se();else ue[Z]=se();else if(hu.test(Z)===!0)if(f.constructorAction==="error")S("Object contains forbidden constructor property");else if(f.constructorAction==="ignore")se();else ue[Z]=se();else ue[Z]=se();if(P(),y==="}")return w("}"),ue;w(","),P()}}S("Bad object")};return se=function(){switch(P(),y){case"{":return z();case"[":return X();case'"':return B();case"-":return x();default:return y>="0"&&y<="9"?x():ne()}},function(Z,ue){var M;if(T=Z+"",g=0,y=" ",M=se(),P(),y)S("Syntax error");return typeof ue==="function"?function L(he,q){var U,de,ye=he[q];if(ye&&typeof ye==="object")Object.keys(ye).forEach(function(Ce){if(de=L(ye,Ce),de!==void 0)ye[Ce]=de;else delete ye[Ce]});return ue.call(he,q,ye)}({"":M},""):M}};hi.exports=pu});var mi=i(function($m,kn){var fi=di().stringify,gi=pi();kn.exports=function(h){return{parse:gi(h),stringify:fi}};kn.exports.parse=gi();kn.exports.stringify=fi});var ur=i(function(bi){Object.defineProperty(bi,"__esModule",{value:!0});bi.GCE_LINUX_BIOS_PATHS=void 0;bi.isGoogleCloudServerless=Ti;bi.isGoogleComputeEngineLinux=vi;bi.isGoogleComputeEngineMACAddress=wi;bi.isGoogleComputeEngine=Ei;bi.detectGCPResidency=gu;var yi=c("fs"),_i=c("os");bi.GCE_LINUX_BIOS_PATHS={BIOS_DATE:"/sys/class/dmi/id/bios_date",BIOS_VENDOR:"/sys/class/dmi/id/bios_vendor"};var fu=/^42:01/;function Ti(){return!!(process.env.CLOUD_RUN_JOB||process.env.FUNCTION_NAME||process.env.K_SERVICE)}function vi(){if(_i.platform()!=="linux")return!1;try{yi.statSync(bi.GCE_LINUX_BIOS_PATHS.BIOS_DATE);let h=yi.readFileSync(bi.GCE_LINUX_BIOS_PATHS.BIOS_VENDOR,"utf8");return/Google/.test(h)}catch{return!1}}function wi(){let h=_i.networkInterfaces();for(let f of Object.values(h)){if(!f)continue;for(let{mac:g}of f)if(fu.test(g))return!0}return!1}function Ei(){return vi()||wi()}function gu(){return Ti()||Ei()}});var xi=i(function(Si){Object.defineProperty(Si,"__esModule",{value:!0});Si.Colours=void 0;class Ie{static isEnabled(h){return h&&h.isTTY&&(typeof h.getColorDepth==="function"?h.getColorDepth()>2:!0)}static refresh(){if(Ie.enabled=Ie.isEnabled(process===null||process===void 0?void 0:process.stderr),!this.enabled)Ie.reset="",Ie.bright="",Ie.dim="",Ie.red="",Ie.green="",Ie.yellow="",Ie.blue="",Ie.magenta="",Ie.cyan="",Ie.white="",Ie.grey="";else Ie.reset="\x1B[0m",Ie.bright="\x1B[1m",Ie.dim="\x1B[2m",Ie.red="\x1B[31m",Ie.green="\x1B[32m",Ie.yellow="\x1B[33m",Ie.blue="\x1B[34m",Ie.magenta="\x1B[35m",Ie.cyan="\x1B[36m",Ie.white="\x1B[37m",Ie.grey="\x1B[90m"}}Si.Colours=Ie;Ie.enabled=!1;Ie.reset="";Ie.bright="";Ie.dim="";Ie.red="";Ie.green="";Ie.yellow="";Ie.blue="";Ie.magenta="";Ie.cyan="";Ie.white="";Ie.grey="";Ie.refresh()});var Di=i(function(We){var wu=We&&We.__createBinding||(Object.create?function(h,f,g,y){if(y===void 0)y=g;var _=Object.getOwnPropertyDescriptor(f,g);if(!_||("get"in _?!f.__esModule:_.writable||_.configurable))_={enumerable:!0,get:function(){return f[g]}};Object.defineProperty(h,y,_)}:function(h,f,g,y){if(y===void 0)y=g;h[y]=f[g]}),Eu=We&&We.__setModuleDefault||(Object.create?function(h,f){Object.defineProperty(h,"default",{enumerable:!0,value:f})}:function(h,f){h.default=f}),Ii=We&&We.__importStar||function(){var h=function(f){return h=Object.getOwnPropertyNames||function(g){var y=[];for(var _ in g)if(Object.prototype.hasOwnProperty.call(g,_))y[y.length]=_;return y},h(f)};return function(f){if(f&&f.__esModule)return f;var g={};if(f!=null){for(var y=h(f),_=0;_<y.length;_++)if(y[_]!=="default")wu(g,f,y[_])}return Eu(g,f),g}}();Object.defineProperty(We,"__esModule",{value:!0});We.env=We.DebugLogBackendBase=We.placeholder=We.AdhocDebugLogger=We.LogSeverity=void 0;We.getNodeBackend=dr;We.getDebugBackend=Au;We.getStructuredBackend=bu;We.setBackend=Su;We.log=Mi;var Cu=c("events"),dn=Ii(c("process")),Ni=Ii(c("util")),Tt=xi(),kt;(function(h){h.DEFAULT="DEFAULT",h.DEBUG="DEBUG",h.INFO="INFO",h.WARNING="WARNING",h.ERROR="ERROR"})(kt||(We.LogSeverity=kt={}));class Rn extends Cu.EventEmitter{constructor(h,f){super();this.namespace=h,this.upstream=f,this.func=Object.assign(this.invoke.bind(this),{instance:this,on:(g,y)=>this.on(g,y)}),this.func.debug=(...g)=>this.invokeSeverity(kt.DEBUG,...g),this.func.info=(...g)=>this.invokeSeverity(kt.INFO,...g),this.func.warn=(...g)=>this.invokeSeverity(kt.WARNING,...g),this.func.error=(...g)=>this.invokeSeverity(kt.ERROR,...g),this.func.sublog=(g)=>Mi(g,this.func)}invoke(h,...f){if(this.upstream)try{this.upstream(h,...f)}catch(g){}try{this.emit("log",h,f)}catch(g){}}invokeSeverity(h,...f){this.invoke({severity:h},...f)}}We.AdhocDebugLogger=Rn;We.placeholder=new Rn("",()=>{}).func;class hn{constructor(){var h;this.cached=new Map,this.filters=[],this.filtersSet=!1;let f=(h=dn.env[We.env.nodeEnables])!==null&&h!==void 0?h:"*";if(f==="all")f="*";this.filters=f.split(",")}log(h,f,...g){try{if(!this.filtersSet)this.setFilters(),this.filtersSet=!0;let y=this.cached.get(h);if(!y)y=this.makeLogger(h),this.cached.set(h,y);y(f,...g)}catch(y){console.error(y)}}}We.DebugLogBackendBase=hn;class Pi extends hn{constructor(){super(...arguments);this.enabledRegexp=/.*/g}isEnabled(h){return this.enabledRegexp.test(h)}makeLogger(h){if(!this.enabledRegexp.test(h))return()=>{};return(f,...g)=>{var y;let _=`${Tt.Colours.green}${h}${Tt.Colours.reset}`,T=`${Tt.Colours.yellow}${dn.pid}${Tt.Colours.reset}`,S;switch(f.severity){case kt.ERROR:S=`${Tt.Colours.red}${f.severity}${Tt.Colours.reset}`;break;case kt.INFO:S=`${Tt.Colours.magenta}${f.severity}${Tt.Colours.reset}`;break;case kt.WARNING:S=`${Tt.Colours.yellow}${f.severity}${Tt.Colours.reset}`;break;default:S=(y=f.severity)!==null&&y!==void 0?y:kt.DEFAULT;break}let w=Ni.formatWithOptions({colors:Tt.Colours.enabled},...g),x=Object.assign({},f);delete x.severity;let B=Object.getOwnPropertyNames(x).length?JSON.stringify(x):"",P=B?`${Tt.Colours.grey}${B}${Tt.Colours.reset}`:"";console.error("%s [%s|%s] %s%s",T,_,S,w,B?` ${P}`:"")}}setFilters(){let f=this.filters.join(",").replace(/[|\\{}()[\]^$+?.]/g,"\\$&").replace(/\*/g,".*").replace(/,/g,"$|^");this.enabledRegexp=new RegExp(`^${f}$`,"i")}}function dr(){return new Pi}class ji extends hn{constructor(h){super();this.debugPkg=h}makeLogger(h){let f=this.debugPkg(h);return(g,...y)=>{f(y[0],...y.slice(1))}}setFilters(){var h;let f=(h=dn.env.NODE_DEBUG)!==null&&h!==void 0?h:"";dn.env.NODE_DEBUG=`${f}${f?",":""}${this.filters.join(",")}`}}function Au(h){return new ji(h)}class Ui extends hn{constructor(h){var f;super();this.upstream=(f=h)!==null&&f!==void 0?f:void 0}makeLogger(h){var f;let g=(f=this.upstream)===null||f===void 0?void 0:f.makeLogger(h);return(y,..._)=>{var T;let S=(T=y.severity)!==null&&T!==void 0?T:kt.INFO,w=Object.assign({severity:S,message:Ni.format(..._)},y),x=JSON.stringify(w);if(g)g(y,x);else console.log("%s",x)}}setFilters(){var h;(h=this.upstream)===null||h===void 0||h.setFilters()}}function bu(h){return new Ui(h)}We.env={nodeEnables:"GOOGLE_SDK_NODE_LOGGING"};var hr=new Map,vt=void 0;function Su(h){vt=h,hr.clear()}function Mi(h,f){if(!vt){if(!dn.env[We.env.nodeEnables])return We.placeholder}if(!h)return We.placeholder;if(f)h=`${f.instance.namespace}:${h}`;let g=hr.get(h);if(g)return g.func;if(vt===null)return We.placeholder;else if(vt===void 0)vt=dr();let y=(()=>{let _=void 0;return new Rn(h,(S,...w)=>{if(_!==vt){if(vt===null)return;else if(vt===void 0)vt=dr();_=vt}vt===null||vt===void 0||vt.log(h,S,...w)})})();return hr.set(h,y),y.func}});var pr=i(function(Jt){var ku=Jt&&Jt.__createBinding||(Object.create?function(h,f,g,y){if(y===void 0)y=g;var _=Object.getOwnPropertyDescriptor(f,g);if(!_||("get"in _?!f.__esModule:_.writable||_.configurable))_={enumerable:!0,get:function(){return f[g]}};Object.defineProperty(h,y,_)}:function(h,f,g,y){if(y===void 0)y=g;h[y]=f[g]}),xu=Jt&&Jt.__exportStar||function(h,f){for(var g in h)if(g!=="default"&&!Object.prototype.hasOwnProperty.call(f,g))ku(f,h,g)};Object.defineProperty(Jt,"__esModule",{value:!0});xu(Di(),Jt)});var fn=i(function(Oe){var Li=Oe&&Oe.__createBinding||(Object.create?function(h,f,g,y){if(y===void 0)y=g;var _=Object.getOwnPropertyDescriptor(f,g);if(!_||("get"in _?!f.__esModule:_.writable||_.configurable))_={enumerable:!0,get:function(){return f[g]}};Object.defineProperty(h,y,_)}:function(h,f,g,y){if(y===void 0)y=g;h[y]=f[g]}),Ou=Oe&&Oe.__setModuleDefault||(Object.create?function(h,f){Object.defineProperty(h,"default",{enumerable:!0,value:f})}:function(h,f){h.default=f}),Ru=Oe&&Oe.__importStar||function(){var h=function(f){return h=Object.getOwnPropertyNames||function(g){var y=[];for(var _ in g)if(Object.prototype.hasOwnProperty.call(g,_))y[y.length]=_;return y},h(f)};return function(f){if(f&&f.__esModule)return f;var g={};if(f!=null){for(var y=h(f),_=0;_<y.length;_++)if(y[_]!=="default")Li(g,f,y[_])}return Ou(g,f),g}}(),Iu=Oe&&Oe.__exportStar||function(h,f){for(var g in h)if(g!=="default"&&!Object.prototype.hasOwnProperty.call(f,g))Li(f,h,g)};Object.defineProperty(Oe,"__esModule",{value:!0});Oe.gcpResidencyCache=Oe.METADATA_SERVER_DETECTION=Oe.HEADERS=Oe.HEADER_VALUE=Oe.HEADER_NAME=Oe.SECONDARY_HOST_ADDRESS=Oe.HOST_ADDRESS=Oe.BASE_PATH=void 0;Oe.instance=Du;Oe.project=qu;Oe.universe=Lu;Oe.bulk=Fu;Oe.isAvailable=$u;Oe.resetIsAvailableCache=Hu;Oe.getGCPResidency=mr;Oe.setGCPResidency=Fi;Oe.requestTimeout=Gi;var fr=ct(),Nu=mi(),Pu=ur(),ju=Ru(pr());Oe.BASE_PATH="/computeMetadata/v1";Oe.HOST_ADDRESS="http://169.254.169.254";Oe.SECONDARY_HOST_ADDRESS="http://metadata.google.internal.";Oe.HEADER_NAME="Metadata-Flavor";Oe.HEADER_VALUE="Google";Oe.HEADERS=Object.freeze({[Oe.HEADER_NAME]:Oe.HEADER_VALUE});var qi=ju.log("gcp-metadata");Oe.METADATA_SERVER_DETECTION=Object.freeze({"assume-present":"don't try to ping the metadata server, but assume it's present",none:"don't try to ping the metadata server, but don't try to use it either","bios-only":"treat the result of a BIOS probe as canonical (don't fall back to pinging)","ping-only":"skip the BIOS probe, and go straight to pinging"});function gr(h){if(!h)h=process.env.GCE_METADATA_IP||process.env.GCE_METADATA_HOST||Oe.HOST_ADDRESS;if(!/^https?:\/\//.test(h))h=`http://${h}`;return new URL(Oe.BASE_PATH,h).href}function Uu(h){Object.keys(h).forEach((f)=>{switch(f){case"params":case"property":case"headers":break;case"qs":throw Error("'qs' is not a valid configuration option. Please use 'params' instead.");default:throw Error(`'${f}' is not a valid configuration option.`)}})}async function pn(h,f={},g=3,y=!1){let _=new Headers(Oe.HEADERS),T="",S={};if(typeof h==="object"){let ne=h;new Headers(ne.headers).forEach((se,X)=>_.set(X,se)),T=ne.metadataKey,S=ne.params||S,g=ne.noResponseRetries||g,y=ne.fastFail||y}else T=h;if(typeof f==="string")T+=`/${f}`;else{if(Uu(f),f.property)T+=`/${f.property}`;new Headers(f.headers).forEach((ne,se)=>_.set(se,ne)),S=f.params||S}let w=y?Mu:fr.request,x={url:`${gr()}/${T}`,headers:_,retryConfig:{noResponseRetries:g},params:S,responseType:"text",timeout:Gi()};qi.info("instance request %j",x);let B=await w(x);qi.info("instance metadata is %s",B.data);let P=B.headers.get(Oe.HEADER_NAME);if(P!==Oe.HEADER_VALUE)throw RangeError(`Invalid response from metadata service: incorrect ${Oe.HEADER_NAME} header. Expected '${Oe.HEADER_VALUE}', got ${P?`'${P}'`:"no header"}`);if(typeof B.data==="string")try{return Nu.parse(B.data)}catch{}return B.data}async function Mu(h){let f={...h,url:h.url?.toString().replace(gr(),gr(Oe.SECONDARY_HOST_ADDRESS))},g=fr.request(h),y=fr.request(f);return Promise.any([g,y])}function Du(h){return pn("instance",h)}function qu(h){return pn("project",h)}function Lu(h){return pn("universe",h)}async function Fu(h){let f={};return await Promise.all(h.map((g)=>(async()=>{let y=await pn(g),_=g.metadataKey;f[_]=y})())),f}function Gu(){return process.env.DETECT_GCP_RETRIES?Number(process.env.DETECT_GCP_RETRIES):0}var In;async function $u(){if(process.env.METADATA_SERVER_DETECTION){let h=process.env.METADATA_SERVER_DETECTION.trim().toLocaleLowerCase();if(!(h in Oe.METADATA_SERVER_DETECTION))throw RangeError(`Unknown \`METADATA_SERVER_DETECTION\` env variable. Got \`${h}\`, but it should be \`${Object.keys(Oe.METADATA_SERVER_DETECTION).join("`, `")}\`, or unset`);switch(h){case"assume-present":return!0;case"none":return!1;case"bios-only":return mr();case"ping-only":}}try{if(In===void 0)In=pn("instance",void 0,Gu(),!(process.env.GCE_METADATA_IP||process.env.GCE_METADATA_HOST));return await In,!0}catch(h){let f=h;if(process.env.DEBUG_AUTH)console.info(f);if(f.type==="request-timeout")return!1;if(f.response&&f.response.status===404)return!1;else{if(!(f.response&&f.response.status===404)&&(!f.code||!["EHOSTDOWN","EHOSTUNREACH","ENETUNREACH","ENOENT","ENOTFOUND","ECONNREFUSED"].includes(f.code.toString()))){let g="UNKNOWN";if(f.code)g=f.code.toString();process.emitWarning(`received unexpected error = ${f.message} code = ${g}`,"MetadataLookupWarning")}return!1}}}function Hu(){In=void 0}Oe.gcpResidencyCache=null;function mr(){if(Oe.gcpResidencyCache===null)Fi();return Oe.gcpResidencyCache}function Fi(h=null){Oe.gcpResidencyCache=h!==null?h:Pu.detectGCPResidency()}function Gi(){return mr()?0:3000}Iu(ur(),Oe)});var Hi=i(function(Xu){Xu.byteLength=Vu;Xu.toByteArray=Ku;Xu.fromByteArray=zu;var It=[],bt=[],Bu=typeof Uint8Array<"u"?Uint8Array:Array,yr="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(Lt=0,_r=yr.length;Lt<_r;++Lt)It[Lt]=yr[Lt],bt[yr.charCodeAt(Lt)]=Lt;var Lt,_r;bt[45]=62;bt[95]=63;function $i(h){var f=h.length;if(f%4>0)throw Error("Invalid string. Length must be a multiple of 4");var g=h.indexOf("=");if(g===-1)g=f;var y=g===f?0:4-g%4;return[g,y]}function Vu(h){var f=$i(h),g=f[0],y=f[1];return(g+y)*3/4-y}function Wu(h,f,g){return(f+g)*3/4-g}function Ku(h){var f,g=$i(h),y=g[0],_=g[1],T=new Bu(Wu(h,y,_)),S=0,w=_>0?y-4:y,x;for(x=0;x<w;x+=4)f=bt[h.charCodeAt(x)]<<18|bt[h.charCodeAt(x+1)]<<12|bt[h.charCodeAt(x+2)]<<6|bt[h.charCodeAt(x+3)],T[S++]=f>>16&255,T[S++]=f>>8&255,T[S++]=f&255;if(_===2)f=bt[h.charCodeAt(x)]<<2|bt[h.charCodeAt(x+1)]>>4,T[S++]=f&255;if(_===1)f=bt[h.charCodeAt(x)]<<10|bt[h.charCodeAt(x+1)]<<4|bt[h.charCodeAt(x+2)]>>2,T[S++]=f>>8&255,T[S++]=f&255;return T}function Ju(h){return It[h>>18&63]+It[h>>12&63]+It[h>>6&63]+It[h&63]}function Yu(h,f,g){var y,_=[];for(var T=f;T<g;T+=3)y=(h[T]<<16&16711680)+(h[T+1]<<8&65280)+(h[T+2]&255),_.push(Ju(y));return _.join("")}function zu(h){var f,g=h.length,y=g%3,_=[],T=16383;for(var S=0,w=g-y;S<w;S+=T)_.push(Yu(h,S,S+T>w?w:S+T));if(y===1)f=h[g-1],_.push(It[f>>2]+It[f<<4&63]+"==");else if(y===2)f=(h[g-2]<<8)+h[g-1],_.push(It[f>>10]+It[f>>4&63]+It[f<<2&63]+"=");return _.join("")}});var Tr=i(function(Bi){Object.defineProperty(Bi,"__esModule",{value:!0});Bi.fromArrayBufferToHex=td;function td(h){return Array.from(new Uint8Array(h)).map((g)=>g.toString(16).padStart(2,"0")).join("")}});var Ki=i(function(Vi){Object.defineProperty(Vi,"__esModule",{value:!0});Vi.BrowserCrypto=void 0;var Zt=Hi(),rd=Tr();class Nn{constructor(){if(typeof window>"u"||window.crypto===void 0||window.crypto.subtle===void 0)throw Error("SubtleCrypto not found. Make sure it's an https:// website.")}async sha256DigestBase64(h){let f=new TextEncoder().encode(h),g=await window.crypto.subtle.digest("SHA-256",f);return Zt.fromByteArray(new Uint8Array(g))}randomBytesBase64(h){let f=new Uint8Array(h);return window.crypto.getRandomValues(f),Zt.fromByteArray(f)}static padBase64(h){while(h.length%4!==0)h+="=";return h}async verify(h,f,g){let y={name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},_=new TextEncoder().encode(f),T=Zt.toByteArray(Nn.padBase64(g)),S=await window.crypto.subtle.importKey("jwk",h,y,!0,["verify"]);return await window.crypto.subtle.verify(y,S,Buffer.from(T),_)}async sign(h,f){let g={name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},y=new TextEncoder().encode(f),_=await window.crypto.subtle.importKey("jwk",h,g,!0,["sign"]),T=await window.crypto.subtle.sign(g,_,y);return Zt.fromByteArray(new Uint8Array(T))}decodeBase64StringUtf8(h){let f=Zt.toByteArray(Nn.padBase64(h));return new TextDecoder().decode(f)}encodeBase64StringUtf8(h){let f=new TextEncoder().encode(h);return Zt.fromByteArray(f)}async sha256DigestHex(h){let f=new TextEncoder().encode(h),g=await window.crypto.subtle.digest("SHA-256",f);return rd.fromArrayBufferToHex(g)}async signWithHmacSha256(h,f){let g=typeof h==="string"?h:String.fromCharCode(...new Uint16Array(h)),y=new TextEncoder,_=await window.crypto.subtle.importKey("raw",y.encode(g),{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return window.crypto.subtle.sign("HMAC",_,y.encode(f))}}Vi.BrowserCrypto=Nn});var Xi=i(function(Yi){Object.defineProperty(Yi,"__esModule",{value:!0});Yi.NodeCrypto=void 0;var tn=c("crypto");class Ji{async sha256DigestBase64(h){return tn.createHash("sha256").update(h).digest("base64")}randomBytesBase64(h){return tn.randomBytes(h).toString("base64")}async verify(h,f,g){let y=tn.createVerify("RSA-SHA256");return y.update(f),y.end(),y.verify(h,g,"base64")}async sign(h,f){let g=tn.createSign("RSA-SHA256");return g.update(f),g.end(),g.sign(h,"base64")}decodeBase64StringUtf8(h){return Buffer.from(h,"base64").toString("utf-8")}encodeBase64StringUtf8(h){return Buffer.from(h,"utf-8").toString("base64")}async sha256DigestHex(h){return tn.createHash("sha256").update(h).digest("hex")}async signWithHmacSha256(h,f){let g=typeof h==="string"?h:id(h);return sd(tn.createHmac("sha256",g).update(f).digest())}}Yi.NodeCrypto=Ji;function sd(h){let f=new ArrayBuffer(h.length),g=new Uint8Array(f);for(let y=0;y<h.length;++y)g[y]=h[y];return f}function id(h){return Buffer.from(h)}});var gn=i(function(jt){var od=jt&&jt.__createBinding||(Object.create?function(h,f,g,y){if(y===void 0)y=g;var _=Object.getOwnPropertyDescriptor(f,g);if(!_||("get"in _?!f.__esModule:_.writable||_.configurable))_={enumerable:!0,get:function(){return f[g]}};Object.defineProperty(h,y,_)}:function(h,f,g,y){if(y===void 0)y=g;h[y]=f[g]}),ad=jt&&jt.__exportStar||function(h,f){for(var g in h)if(g!=="default"&&!Object.prototype.hasOwnProperty.call(f,g))od(f,h,g)};Object.defineProperty(jt,"__esModule",{value:!0});jt.createCrypto=ud;jt.hasBrowserCrypto=Qi;var cd=Ki(),ld=Xi();ad(Tr(),jt);function ud(){if(Qi())return new cd.BrowserCrypto;return new ld.NodeCrypto}function Qi(){return typeof window<"u"&&typeof window.crypto<"u"&&typeof window.crypto.subtle<"u"}});var xt=i(function(no){Object.defineProperty(no,"__esModule",{value:!0});no.LRUCache=void 0;no.snakeToCamel=eo;no.originalOrCamelOptions=fd;no.removeUndefinedValuesInObject=gd;no.isValidFile=md;no.getWellKnownCertificateConfigFileLocation=yd;var dd=c("fs"),hd=c("os"),vr=c("path"),pd="certificate_config.json",Zi="gcloud";function eo(h){return h.replace(/([_][^_])/g,(f)=>f.slice(1).toUpperCase())}function fd(h){function f(g){let y=h||{};return y[g]??y[eo(g)]}return{get:f}}class to{capacity;#e=new Map;maxAge;constructor(h){this.capacity=h.capacity,this.maxAge=h.maxAge}#t(h,f){this.#e.delete(h),this.#e.set(h,{value:f,lastAccessed:Date.now()})}set(h,f){this.#t(h,f),this.#n()}get(h){let f=this.#e.get(h);if(!f)return;return this.#t(h,f.value),this.#n(),f.value}#n(){let h=this.maxAge?Date.now()-this.maxAge:0,f=this.#e.entries().next();while(!f.done&&(this.#e.size>this.capacity||f.value[1].lastAccessed<h))this.#e.delete(f.value[0]),f=this.#e.entries().next()}}no.LRUCache=to;function gd(h){return Object.entries(h).forEach(([f,g])=>{if(g===void 0||g==="undefined")delete h[f]}),h}async function md(h){try{return(await dd.promises.lstat(h)).isFile()}catch(f){return!1}}function yd(){let h=process.env.CLOUDSDK_CONFIG||(_d()?vr.join(process.env.APPDATA||"",Zi):vr.join(process.env.HOME||"",".config",Zi));return vr.join(h,pd)}function _d(){return hd.platform().startsWith("win")}});var so=i(function(ey,Ad){Ad.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 wr=i(function(co){Object.defineProperty(co,"__esModule",{value:!0});co.USER_AGENT=co.PRODUCT_NAME=co.pkg=void 0;var oo=so();co.pkg=oo;var ao="google-api-nodejs-client";co.PRODUCT_NAME=ao;var bd=`${ao}/${oo.version}`;co.USER_AGENT=bd});var wt=i(function(uo){Object.defineProperty(uo,"__esModule",{value:!0});uo.AuthClient=uo.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS=uo.DEFAULT_UNIVERSE=void 0;var xd=c("events"),Er=ct(),Od=xt(),Rd=pr(),Cr=wr();uo.DEFAULT_UNIVERSE="googleapis.com";uo.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS=300000;class dt extends xd.EventEmitter{apiKey;projectId;quotaProjectId;transporter;credentials={};eagerRefreshThresholdMillis=uo.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS;forceRefreshOnFailure=!1;universeDomain=uo.DEFAULT_UNIVERSE;static RequestMethodNameSymbol=Symbol("request method name");static RequestLogIdSymbol=Symbol("request log id");constructor(h={}){super();let f=Od.originalOrCamelOptions(h);if(this.apiKey=h.apiKey,this.projectId=f.get("project_id")??null,this.quotaProjectId=f.get("quota_project_id"),this.credentials=f.get("credentials")??{},this.universeDomain=f.get("universe_domain")??uo.DEFAULT_UNIVERSE,this.transporter=h.transporter??new Er.Gaxios(h.transporterOptions),f.get("useAuthRequestParameters")!==!1)this.transporter.interceptors.request.add(dt.DEFAULT_REQUEST_INTERCEPTOR),this.transporter.interceptors.response.add(dt.DEFAULT_RESPONSE_INTERCEPTOR);if(h.eagerRefreshThresholdMillis)this.eagerRefreshThresholdMillis=h.eagerRefreshThresholdMillis;this.forceRefreshOnFailure=h.forceRefreshOnFailure??!1}fetch(...h){let f=h[0],g=h[1],y=void 0,_=new Headers;if(typeof f==="string")y=new URL(f);else if(f instanceof URL)y=f;else if(f&&f.url)y=new URL(f.url);if(f&&typeof f==="object"&&"headers"in f)Er.Gaxios.mergeHeaders(_,f.headers);if(g)Er.Gaxios.mergeHeaders(_,new Headers(g.headers));if(typeof f==="object"&&!(f instanceof URL))return this.request({...g,...f,headers:_,url:y});else return this.request({...g,headers:_,url:y})}setCredentials(h){this.credentials=h}addSharedMetadataHeaders(h){if(!h.has("x-goog-user-project")&&this.quotaProjectId)h.set("x-goog-user-project",this.quotaProjectId);return h}addUserProjectAndAuthHeaders(h,f){let g=f.get("x-goog-user-project"),y=f.get("authorization");if(g)h.set("x-goog-user-project",g);if(y)h.set("authorization",y);return h}static log=Rd.log("auth");static DEFAULT_REQUEST_INTERCEPTOR={resolved:async(h)=>{if(!h.headers.has("x-goog-api-client")){let g=process.version.replace(/^v/,"");h.headers.set("x-goog-api-client",`gl-node/${g}`)}let f=h.headers.get("User-Agent");if(!f)h.headers.set("User-Agent",Cr.USER_AGENT);else if(!f.includes(`${Cr.PRODUCT_NAME}/`))h.headers.set("User-Agent",`${f} ${Cr.USER_AGENT}`);try{let g=h,y=g[dt.RequestMethodNameSymbol],_=`${Math.floor(Math.random()*1000)}`;g[dt.RequestLogIdSymbol]=_;let T={url:h.url,headers:h.headers};if(y)dt.log.info("%s [%s] request %j",y,_,T);else dt.log.info("[%s] request %j",_,T)}catch(g){}return h}};static DEFAULT_RESPONSE_INTERCEPTOR={resolved:async(h)=>{try{let f=h.config,g=f[dt.RequestMethodNameSymbol],y=f[dt.RequestLogIdSymbol];if(g)dt.log.info("%s [%s] response %j",g,y,h.data);else dt.log.info("[%s] response %j",y,h.data)}catch(f){}return h},rejected:async(h)=>{try{let f=h.config,g=f[dt.RequestMethodNameSymbol],y=f[dt.RequestLogIdSymbol];if(g)dt.log.info("%s [%s] error %j",g,y,h.response?.data);else dt.log.error("[%s] error %j",y,h.response?.data)}catch(f){}throw h}};static setMethodName(h,f){try{let g=h;g[dt.RequestMethodNameSymbol]=f}catch(g){}}static get RETRY_CONFIG(){return{retry:!0,retryConfig:{httpMethodsToRetry:["GET","PUT","POST","HEAD","OPTIONS","DELETE"]}}}}uo.AuthClient=dt});var br=i(function(go){Object.defineProperty(go,"__esModule",{value:!0});go.LoginTicket=void 0;class fo{envelope;payload;constructor(h,f){this.envelope=h,this.payload=f}getEnvelope(){return this.envelope}getPayload(){return this.payload}getUserId(){let h=this.getPayload();if(h&&h.sub)return h.sub;return null}getAttributes(){return{envelope:this.getEnvelope(),payload:this.getPayload()}}}go.LoginTicket=fo});var Ft=i(function(vo){Object.defineProperty(vo,"__esModule",{value:!0});vo.OAuth2Client=vo.ClientAuthentication=vo.CertificateFormat=vo.CodeChallengeMethod=void 0;var To=ct(),Id=c("querystring"),Nd=c("stream"),Pd=xy(),yo=xt(),Sr=gn(),nn=wt(),jd=br(),_o;(function(h){h.Plain="plain",h.S256="S256"})(_o||(vo.CodeChallengeMethod=_o={}));var Ut;(function(h){h.PEM="PEM",h.JWK="JWK"})(Ut||(vo.CertificateFormat=Ut={}));var mn;(function(h){h.ClientSecretPost="ClientSecretPost",h.ClientSecretBasic="ClientSecretBasic",h.None="None"})(mn||(vo.ClientAuthentication=mn={}));class St extends nn.AuthClient{redirectUri;certificateCache={};certificateExpiry=null;certificateCacheFormat=Ut.PEM;refreshTokenPromises=new Map;endpoints;issuers;clientAuthentication;_clientId;_clientSecret;refreshHandler;constructor(h={},f,g){super(typeof h==="object"?h:{});if(typeof h!=="object")h={clientId:h,clientSecret:f,redirectUri:g};this._clientId=h.clientId||h.client_id,this._clientSecret=h.clientSecret||h.client_secret,this.redirectUri=h.redirectUri||h.redirect_uris?.[0],this.endpoints={tokenInfoUrl:"https://oauth2.googleapis.com/tokeninfo",oauth2AuthBaseUrl:"https://accounts.google.com/o/oauth2/v2/auth",oauth2TokenUrl:"https://oauth2.googleapis.com/token",oauth2RevokeUrl:"https://oauth2.googleapis.com/revoke",oauth2FederatedSignonPemCertsUrl:"https://www.googleapis.com/oauth2/v1/certs",oauth2FederatedSignonJwkCertsUrl:"https://www.googleapis.com/oauth2/v3/certs",oauth2IapPublicKeyUrl:"https://www.gstatic.com/iap/verify/public_key",...h.endpoints},this.clientAuthentication=h.clientAuthentication||mn.ClientSecretPost,this.issuers=h.issuers||["accounts.google.com","https://accounts.google.com",this.universeDomain]}static GOOGLE_TOKEN_INFO_URL="https://oauth2.googleapis.com/tokeninfo";static CLOCK_SKEW_SECS_=300;static DEFAULT_MAX_TOKEN_LIFETIME_SECS_=86400;generateAuthUrl(h={}){if(h.code_challenge_method&&!h.code_challenge)throw Error("If a code_challenge_method is provided, code_challenge must be included.");if(h.response_type=h.response_type||"code",h.client_id=h.client_id||this._clientId,h.redirect_uri=h.redirect_uri||this.redirectUri,Array.isArray(h.scope))h.scope=h.scope.join(" ");return this.endpoints.oauth2AuthBaseUrl.toString()+"?"+Id.stringify(h)}generateCodeVerifier(){throw Error("generateCodeVerifier is removed, please use generateCodeVerifierAsync instead.")}async generateCodeVerifierAsync(){let h=Sr.createCrypto(),g=h.randomBytesBase64(96).replace(/\+/g,"~").replace(/=/g,"_").replace(/\//g,"-"),_=(await h.sha256DigestBase64(g)).split("=")[0].replace(/\+/g,"-").replace(/\//g,"_");return{codeVerifier:g,codeChallenge:_}}getToken(h,f){let g=typeof h==="string"?{code:h}:h;if(f)this.getTokenAsync(g).then((y)=>f(null,y.tokens,y.res),(y)=>f(y,null,y.response));else return this.getTokenAsync(g)}async getTokenAsync(h){let f=this.endpoints.oauth2TokenUrl.toString(),g=new Headers,y={client_id:h.client_id||this._clientId,code_verifier:h.codeVerifier,code:h.code,grant_type:"authorization_code",redirect_uri:h.redirect_uri||this.redirectUri};if(this.clientAuthentication===mn.ClientSecretBasic){let w=Buffer.from(`${this._clientId}:${this._clientSecret}`);g.set("authorization",`Basic ${w.toString("base64")}`)}if(this.clientAuthentication===mn.ClientSecretPost)y.client_secret=this._clientSecret;let _={...St.RETRY_CONFIG,method:"POST",url:f,data:new URLSearchParams(yo.removeUndefinedValuesInObject(y)),headers:g};nn.AuthClient.setMethodName(_,"getTokenAsync");let T=await this.transporter.request(_),S=T.data;if(T.data&&T.data.expires_in)S.expiry_date=new Date().getTime()+T.data.expires_in*1000,delete S.expires_in;return this.emit("tokens",S),{tokens:S,res:T}}async refreshToken(h){if(!h)return this.refreshTokenNoCache(h);if(this.refreshTokenPromises.has(h))return this.refreshTokenPromises.get(h);let f=this.refreshTokenNoCache(h).then((g)=>(this.refreshTokenPromises.delete(h),g),(g)=>{throw this.refreshTokenPromises.delete(h),g});return this.refreshTokenPromises.set(h,f),f}async refreshTokenNoCache(h){if(!h)throw Error("No refresh token is set.");let f=this.endpoints.oauth2TokenUrl.toString(),g={refresh_token:h,client_id:this._clientId,client_secret:this._clientSecret,grant_type:"refresh_token"},y;try{let T={...St.RETRY_CONFIG,method:"POST",url:f,data:new URLSearchParams(yo.removeUndefinedValuesInObject(g))};nn.AuthClient.setMethodName(T,"refreshTokenNoCache"),y=await this.transporter.request(T)}catch(T){if(T instanceof To.GaxiosError&&T.message==="invalid_grant"&&T.response?.data&&/ReAuth/i.test(T.response.data.error_description))T.message=JSON.stringify(T.response.data);throw T}let _=y.data;if(y.data&&y.data.expires_in)_.expiry_date=new Date().getTime()+y.data.expires_in*1000,delete _.expires_in;return this.emit("tokens",_),{tokens:_,res:y}}refreshAccessToken(h){if(h)this.refreshAccessTokenAsync().then((f)=>h(null,f.credentials,f.res),h);else return this.refreshAccessTokenAsync()}async refreshAccessTokenAsync(){let h=await this.refreshToken(this.credentials.refresh_token),f=h.tokens;return f.refresh_token=this.credentials.refresh_token,this.credentials=f,{credentials:this.credentials,res:h.res}}getAccessToken(h){if(h)this.getAccessTokenAsync().then((f)=>h(null,f.token,f.res),h);else return this.getAccessTokenAsync()}async getAccessTokenAsync(){if(!this.credentials.access_token||this.isTokenExpiring()){if(!this.credentials.refresh_token)if(this.refreshHandler){let g=await this.processAndValidateRefreshHandler();if(g?.access_token)return this.setCredentials(g),{token:this.credentials.access_token}}else throw Error("No refresh token or refresh handler callback is set.");let f=await this.refreshAccessTokenAsync();if(!f.credentials||f.credentials&&!f.credentials.access_token)throw Error("Could not refresh access token.");return{token:f.credentials.access_token,res:f.res}}else return{token:this.credentials.access_token}}async getRequestHeaders(h){return(await this.getRequestMetadataAsync(h)).headers}async getRequestMetadataAsync(h){let f=this.credentials;if(!f.access_token&&!f.refresh_token&&!this.apiKey&&!this.refreshHandler)throw Error("No access, refresh token, API key or refresh handler callback is set.");if(f.access_token&&!this.isTokenExpiring()){f.token_type=f.token_type||"Bearer";let S=new Headers({authorization:f.token_type+" "+f.access_token});return{headers:this.addSharedMetadataHeaders(S)}}if(this.refreshHandler){let S=await this.processAndValidateRefreshHandler();if(S?.access_token){this.setCredentials(S);let w=new Headers({authorization:"Bearer "+this.credentials.access_token});return{headers:this.addSharedMetadataHeaders(w)}}}if(this.apiKey)return{headers:new Headers({"X-Goog-Api-Key":this.apiKey})};let g=null,y=null;try{g=await this.refreshToken(f.refresh_token),y=g.tokens}catch(S){let w=S;if(w.response&&(w.response.status===403||w.response.status===404))w.message=`Could not refresh access token: ${w.message}`;throw w}let _=this.credentials;_.token_type=_.token_type||"Bearer",y.refresh_token=_.refresh_token,this.credentials=y;let T=new Headers({authorization:_.token_type+" "+y.access_token});return{headers:this.addSharedMetadataHeaders(T),res:g.res}}static getRevokeTokenUrl(h){return new St().getRevokeTokenURL(h).toString()}getRevokeTokenURL(h){let f=new URL(this.endpoints.oauth2RevokeUrl);return f.searchParams.append("token",h),f}revokeToken(h,f){let g={...St.RETRY_CONFIG,url:this.getRevokeTokenURL(h).toString(),method:"POST"};if(nn.AuthClient.setMethodName(g,"revokeToken"),f)this.transporter.request(g).then((y)=>f(null,y),f);else return this.transporter.request(g)}revokeCredentials(h){if(h)this.revokeCredentialsAsync().then((f)=>h(null,f),h);else return this.revokeCredentialsAsync()}async revokeCredentialsAsync(){let h=this.credentials.access_token;if(this.credentials={},h)return this.revokeToken(h);else throw Error("No access token to revoke.")}request(h,f){if(f)this.requestAsync(h).then((g)=>f(null,g),(g)=>f(g,g.response));else return this.requestAsync(h)}async requestAsync(h,f=!1){try{let g=await this.getRequestMetadataAsync();if(h.headers=To.Gaxios.mergeHeaders(h.headers),this.addUserProjectAndAuthHeaders(h.headers,g.headers),this.apiKey)h.headers.set("X-Goog-Api-Key",this.apiKey);return await this.transporter.request(h)}catch(g){let y=g.response;if(y){let _=y.status,T=this.credentials&&this.credentials.access_token&&this.credentials.refresh_token&&(!this.credentials.expiry_date||this.forceRefreshOnFailure),S=this.credentials&&this.credentials.access_token&&!this.credentials.refresh_token&&(!this.credentials.expiry_date||this.forceRefreshOnFailure)&&this.refreshHandler,w=y.config.data instanceof Nd.Readable,x=_===401||_===403;if(!f&&x&&!w&&T)return await this.refreshAccessTokenAsync(),this.requestAsync(h,!0);else if(!f&&x&&!w&&S){let B=await this.processAndValidateRefreshHandler();if(B?.access_token)this.setCredentials(B);return this.requestAsync(h,!0)}}throw g}}verifyIdToken(h,f){if(f&&typeof f!=="function")throw Error("This method accepts an options object as the first parameter, which includes the idToken, audience, and maxExpiry.");if(f)this.verifyIdTokenAsync(h).then((g)=>f(null,g),f);else return this.verifyIdTokenAsync(h)}async verifyIdTokenAsync(h){if(!h.idToken)throw Error("The verifyIdToken method requires an ID Token");let f=await this.getFederatedSignonCertsAsync();return await this.verifySignedJwtWithCertsAsync(h.idToken,f.certs,h.audience,this.issuers,h.maxExpiry)}async getTokenInfo(h){let{data:f}=await this.transporter.request({...St.RETRY_CONFIG,method:"POST",headers:{"content-type":"application/x-www-form-urlencoded;charset=UTF-8",authorization:`Bearer ${h}`},url:this.endpoints.tokenInfoUrl.toString()}),g=Object.assign({expiry_date:new Date().getTime()+f.expires_in*1000,scopes:f.scope.split(" ")},f);return delete g.expires_in,delete g.scope,g}getFederatedSignonCerts(h){if(h)this.getFederatedSignonCertsAsync().then((f)=>h(null,f.certs,f.res),h);else return this.getFederatedSignonCertsAsync()}async getFederatedSignonCertsAsync(){let h=new Date().getTime(),f=Sr.hasBrowserCrypto()?Ut.JWK:Ut.PEM;if(this.certificateExpiry&&h<this.certificateExpiry.getTime()&&this.certificateCacheFormat===f)return{certs:this.certificateCache,format:f};let g,y;switch(f){case Ut.PEM:y=this.endpoints.oauth2FederatedSignonPemCertsUrl.toString();break;case Ut.JWK:y=this.endpoints.oauth2FederatedSignonJwkCertsUrl.toString();break;default:throw Error(`Unsupported certificate format ${f}`)}try{let x={...St.RETRY_CONFIG,url:y};nn.AuthClient.setMethodName(x,"getFederatedSignonCertsAsync"),g=await this.transporter.request(x)}catch(x){if(x instanceof Error)x.message=`Failed to retrieve verification certificates: ${x.message}`;throw x}let _=g?.headers.get("cache-control"),T=-1;if(_){let x=/max-age=(?<maxAge>[0-9]+)/.exec(_)?.groups?.maxAge;if(x)T=Number(x)*1000}let S={};switch(f){case Ut.PEM:S=g.data;break;case Ut.JWK:for(let x of g.data.keys)S[x.kid]=x;break;default:throw Error(`Unsupported certificate format ${f}`)}let w=new Date;return this.certificateExpiry=T===-1?null:new Date(w.getTime()+T),this.certificateCache=S,this.certificateCacheFormat=f,{certs:S,format:f,res:g}}getIapPublicKeys(h){if(h)this.getIapPublicKeysAsync().then((f)=>h(null,f.pubkeys,f.res),h);else return this.getIapPublicKeysAsync()}async getIapPublicKeysAsync(){let h,f=this.endpoints.oauth2IapPublicKeyUrl.toString();try{let g={...St.RETRY_CONFIG,url:f};nn.AuthClient.setMethodName(g,"getIapPublicKeysAsync"),h=await this.transporter.request(g)}catch(g){if(g instanceof Error)g.message=`Failed to retrieve verification certificates: ${g.message}`;throw g}return{pubkeys:h.data,res:h}}verifySignedJwtWithCerts(){throw Error("verifySignedJwtWithCerts is removed, please use verifySignedJwtWithCertsAsync instead.")}async verifySignedJwtWithCertsAsync(h,f,g,y,_){let T=Sr.createCrypto();if(!_)_=St.DEFAULT_MAX_TOKEN_LIFETIME_SECS_;let S=h.split(".");if(S.length!==3)throw Error("Wrong number of segments in token: "+h);let w=S[0]+"."+S[1],x=S[2],B,P;try{B=JSON.parse(T.decodeBase64StringUtf8(S[0]))}catch(L){if(L instanceof Error)L.message=`Can't parse token envelope: ${S[0]}': ${L.message}`;throw L}if(!B)throw Error("Can't parse token envelope: "+S[0]);try{P=JSON.parse(T.decodeBase64StringUtf8(S[1]))}catch(L){if(L instanceof Error)L.message=`Can't parse token payload '${S[0]}`;throw L}if(!P)throw Error("Can't parse token payload: "+S[1]);if(!Object.prototype.hasOwnProperty.call(f,B.kid))throw Error("No pem found for envelope: "+JSON.stringify(B));let ne=f[B.kid];if(B.alg==="ES256")x=Pd.joseToDer(x,"ES256").toString("base64");if(!await T.verify(ne,w,x))throw Error("Invalid token signature: "+h);if(!P.iat)throw Error("No issue time in token: "+JSON.stringify(P));if(!P.exp)throw Error("No expiration time in token: "+JSON.stringify(P));let X=Number(P.iat);if(isNaN(X))throw Error("iat field using invalid format");let z=Number(P.exp);if(isNaN(z))throw Error("exp field using invalid format");let Z=new Date().getTime()/1000;if(z>=Z+_)throw Error("Expiration time too far in future: "+JSON.stringify(P));let ue=X-St.CLOCK_SKEW_SECS_,M=z+St.CLOCK_SKEW_SECS_;if(Z<ue)throw Error("Token used too early, "+Z+" < "+ue+": "+JSON.stringify(P));if(Z>M)throw Error("Token used too late, "+Z+" > "+M+": "+JSON.stringify(P));if(y&&y.indexOf(P.iss)<0)throw Error("Invalid issuer, expected one of ["+y+"], but got "+P.iss);if(typeof g<"u"&&g!==null){let L=P.aud,he=!1;if(g.constructor===Array)he=g.indexOf(L)>-1;else he=L===g;if(!he)throw Error("Wrong recipient, payload audience != requiredAudience")}return new jd.LoginTicket(B,P)}async processAndValidateRefreshHandler(){if(this.refreshHandler){let h=await this.refreshHandler();if(!h.access_token)throw Error("No access token is returned by the refreshHandler callback.");return h}return}isTokenExpiring(){let h=this.credentials.expiry_date;return h?h<=new Date().getTime()+this.eagerRefreshThresholdMillis:!1}}vo.OAuth2Client=St});var kr=i(function(bo){Object.defineProperty(bo,"__esModule",{value:!0});bo.Compute=void 0;var qd=ct(),Eo=fn(),Ld=Ft();class Co extends Ld.OAuth2Client{serviceAccountEmail;scopes;constructor(h={}){super(h);this.credentials={expiry_date:1,refresh_token:"compute-placeholder"},this.serviceAccountEmail=h.serviceAccountEmail||"default",this.scopes=Array.isArray(h.scopes)?h.scopes:h.scopes?[h.scopes]:[]}async refreshTokenNoCache(){let h=`service-accounts/${this.serviceAccountEmail}/token`,f;try{let y={property:h};if(this.scopes.length>0)y.params={scopes:this.scopes.join(",")};f=await Eo.instance(y)}catch(y){if(y instanceof qd.GaxiosError)y.message=`Could not refresh access token: ${y.message}`,this.wrapError(y);throw y}let g=f;if(f&&f.expires_in)g.expiry_date=new Date().getTime()+f.expires_in*1000,delete g.expires_in;return this.emit("tokens",g),{tokens:g,res:null}}async fetchIdToken(h){let f=`service-accounts/${this.serviceAccountEmail}/identity?format=full&audience=${h}`,g;try{g=await Eo.instance({property:f})}catch(y){if(y instanceof Error)y.message=`Could not fetch ID token: ${y.message}`;throw y}return g}wrapError(h){let f=h.response;if(f&&f.status){if(h.status=f.status,f.status===403)h.message="A Forbidden error was returned while attempting to retrieve an access token for the Compute Engine built-in service account. This may be because the Compute Engine instance does not have the correct permission scopes specified: "+h.message;else if(f.status===404)h.message="A Not Found error was returned while attempting to retrieve an accesstoken for the Compute Engine built-in service account. This may be because the Compute Engine instance does not have any permission scopes specified: "+h.message}}}bo.Compute=Co});var xr=i(function(xo){Object.defineProperty(xo,"__esModule",{value:!0});xo.IdTokenClient=void 0;var Fd=Ft();class ko extends Fd.OAuth2Client{targetAudience;idTokenProvider;constructor(h){super(h);this.targetAudience=h.targetAudience,this.idTokenProvider=h.idTokenProvider}async getRequestMetadataAsync(){if(!this.credentials.id_token||!this.credentials.expiry_date||this.isTokenExpiring()){let f=await this.idTokenProvider.fetchIdToken(this.targetAudience);this.credentials={id_token:f,expiry_date:this.getIdTokenExpiryDate(f)}}return{headers:new Headers({authorization:"Bearer "+this.credentials.id_token})}}getIdTokenExpiryDate(h){let f=h.split(".")[1];if(f)return JSON.parse(Buffer.from(f,"base64").toString("ascii")).exp*1000}}xo.IdTokenClient=ko});var Or=i(function(Io){Object.defineProperty(Io,"__esModule",{value:!0});Io.GCPEnv=void 0;Io.clear=Gd;Io.getEnv=$d;var Ro=fn(),Nt;(function(h){h.APP_ENGINE="APP_ENGINE",h.KUBERNETES_ENGINE="KUBERNETES_ENGINE",h.CLOUD_FUNCTIONS="CLOUD_FUNCTIONS",h.COMPUTE_ENGINE="COMPUTE_ENGINE",h.CLOUD_RUN="CLOUD_RUN",h.CLOUD_RUN_JOBS="CLOUD_RUN_JOBS",h.NONE="NONE"})(Nt||(Io.GCPEnv=Nt={}));var yn;function Gd(){yn=void 0}async function $d(){if(yn)return yn;return yn=Hd(),yn}async function Hd(){let h=Nt.NONE;if(Bd())h=Nt.APP_ENGINE;else if(Vd())h=Nt.CLOUD_FUNCTIONS;else if(await Yd())if(await Jd())h=Nt.KUBERNETES_ENGINE;else if(Wd())h=Nt.CLOUD_RUN;else if(Kd())h=Nt.CLOUD_RUN_JOBS;else h=Nt.COMPUTE_ENGINE;else h=Nt.NONE;return h}function Bd(){return!!(process.env.GAE_SERVICE||process.env.GAE_MODULE_NAME)}function Vd(){return!!(process.env.FUNCTION_NAME||process.env.FUNCTION_TARGET)}function Wd(){return!!process.env.K_CONFIGURATION}function Kd(){return!!process.env.CLOUD_RUN_JOB}async function Jd(){try{return await Ro.instance("attributes/cluster-name"),!0}catch(h){return!1}}async function Yd(){return Ro.isAvailable()}});var Uo=i(function(jo){Object.defineProperty(jo,"__esModule",{value:!0});jo.buildPayloadForJwsSign=Po;jo.getJwsSign=th;var Qd=gc(),Zd="RS256",eh="https://oauth2.googleapis.com/token";function Po(h){let f=Math.floor(new Date().getTime()/1000);return{iss:h.iss,scope:h.scope,aud:eh,exp:f+3600,iat:f,sub:h.sub,...h.additionalClaims}}function th(h){let f=Po(h);return Qd.sign({header:{alg:Zd},payload:f,secret:h.key})}});var Do=i(function(Mo){Object.defineProperty(Mo,"__esModule",{value:!0});Mo.getToken=ch;var sh=Uo(),ih="https://oauth2.googleapis.com/token",oh="urn:ietf:params:oauth:grant-type:jwt-bearer",ah=(h)=>({method:"POST",url:ih,data:new URLSearchParams({grant_type:oh,assertion:sh.getJwsSign(h)}),responseType:"json",retryConfig:{httpMethodsToRetry:["POST"]}});async function ch(h){if(!h.transporter)throw Error("No transporter set.");try{let f=ah(h);return(await h.transporter.request(f)).data}catch(f){let g=f,y=g.response?.data;if(y?.error)g.message=`${y.error}: ${y.error_description}`;throw g}}});var Go=i(function(Lo){Object.defineProperty(Lo,"__esModule",{value:!0});Lo.ErrorWithCode=void 0;class qo extends Error{code;constructor(h,f){super(h);this.code=f}}Lo.ErrorWithCode=qo});var Rr=i(function(Jo){Object.defineProperty(Jo,"__esModule",{value:!0});Jo.getCredentials=hh;var uh=c("path"),$o=c("fs"),dh=c("util"),Pn=Go(),Ho=$o.readFile?dh.promisify($o.readFile):async()=>{throw new Pn.ErrorWithCode("use key rather than keyFile.","MISSING_CREDENTIALS")},Gt;(function(h){h.JSON=".json",h.DER=".der",h.CRT=".crt",h.PEM=".pem",h.P12=".p12",h.PFX=".pfx"})(Gt||(Gt={}));class Bo{keyFilePath;constructor(h){this.keyFilePath=h}async getCredentials(){let h=await Ho(this.keyFilePath,"utf8"),f;try{f=JSON.parse(h)}catch(_){throw Error(`Invalid JSON key file: ${_.message}`)}let g=f.private_key,y=f.client_email;if(!g||!y)throw new Pn.ErrorWithCode("private_key and client_email are required.","MISSING_CREDENTIALS");return{privateKey:g,clientEmail:y}}}class Vo{keyFilePath;constructor(h){this.keyFilePath=h}async getCredentials(){return{privateKey:await Ho(this.keyFilePath,"utf8")}}}class Wo{async getCredentials(){throw new Pn.ErrorWithCode("*.p12 certificates are not supported after v6.1.2. Consider utilizing *.json format or converting *.p12 to *.pem using the OpenSSL CLI.","UNKNOWN_CERTIFICATE_TYPE")}}class Ko{static create(h){switch(uh.extname(h)){case Gt.JSON:return new Bo(h);case Gt.DER:case Gt.CRT:case Gt.PEM:return new Vo(h);case Gt.P12:case Gt.PFX:return new Wo;default:throw new Pn.ErrorWithCode("Unknown certificate type. Type is determined based on file extension. Current supported extensions are *.json, and *.pem.","UNKNOWN_CERTIFICATE_TYPE")}}}async function hh(h){return Ko.create(h).getCredentials()}});var Qo=i(function(zo){Object.defineProperty(zo,"__esModule",{value:!0});zo.TokenHandler=void 0;var fh=Do(),gh=Rr();class Yo{token;tokenExpiresAt;inFlightRequest;tokenOptions;constructor(h){this.tokenOptions=h}async processCredentials(){if(!this.tokenOptions.key&&!this.tokenOptions.keyFile)throw Error("No key or keyFile set.");if(!this.tokenOptions.key&&this.tokenOptions.keyFile){let h=await gh.getCredentials(this.tokenOptions.keyFile);this.tokenOptions.key=h.privateKey,this.tokenOptions.email=h.clientEmail}}isTokenExpiring(){if(!this.token||!this.tokenExpiresAt)return!0;let h=new Date().getTime(),f=this.tokenOptions.eagerRefreshThresholdMillis??0;return this.tokenExpiresAt<=h+f}hasExpired(){let h=new Date().getTime();if(this.token&&this.tokenExpiresAt)return new Date().getTime()>=this.tokenExpiresAt;return!0}async getToken(h){if(await this.processCredentials(),this.inFlightRequest&&!h)return this.inFlightRequest;if(this.token&&!this.isTokenExpiring()&&!h)return this.token;try{this.inFlightRequest=fh.getToken(this.tokenOptions);let f=await this.inFlightRequest;return this.token=f,this.tokenExpiresAt=new Date().getTime()+(f.expires_in??0)*1000,f}finally{this.inFlightRequest=void 0}}}zo.TokenHandler=Yo});var ea=i(function(Zo){Object.defineProperty(Zo,"__esModule",{value:!0});Zo.revokeToken=_h;var mh="https://oauth2.googleapis.com/revoke?token=",yh=!0;async function _h(h,f){let g=mh+h;return await f.request({url:g,retry:yh})}});var Ir=i(function(ra){Object.defineProperty(ra,"__esModule",{value:!0});ra.GoogleToken=void 0;var vh=ct(),ta=Qo(),wh=ea();class na{tokenOptions;tokenHandler;constructor(h){if(this.tokenOptions=h||{},this.tokenOptions.transporter=this.tokenOptions.transporter||{request:(f)=>vh.request(f)},!this.tokenOptions.iss)this.tokenOptions.iss=this.tokenOptions.email;if(typeof this.tokenOptions.scope==="object")this.tokenOptions.scope=this.tokenOptions.scope.join(" ");this.tokenHandler=new ta.TokenHandler(this.tokenOptions)}get expiresAt(){return this.tokenHandler.tokenExpiresAt}get accessToken(){return this.tokenHandler.token?.access_token}get idToken(){return this.tokenHandler.token?.id_token}get tokenType(){return this.tokenHandler.token?.token_type}get refreshToken(){return this.tokenHandler.token?.refresh_token}hasExpired(){return this.tokenHandler.hasExpired()}isTokenExpiring(){return this.tokenHandler.isTokenExpiring()}getToken(h,f={forceRefresh:!1}){let g;if(typeof h==="function")g=h;else if(typeof h==="object")f=h;let y=this.tokenHandler.getToken(f.forceRefresh??!1);if(g)y.then((_)=>g(null,_),g);return y}revokeToken(h){if(!this.accessToken)return Promise.reject(Error("No token to revoke."));let f=wh.revokeToken(this.accessToken,this.tokenOptions.transporter);if(h)f.then(()=>h(),h);this.tokenHandler=new ta.TokenHandler(this.tokenOptions)}get googleTokenOptions(){return this.tokenOptions}}ra.GoogleToken=na});var Pr=i(function(oa){Object.defineProperty(oa,"__esModule",{value:!0});oa.JWTAccess=void 0;var Eh=gc(),Ch=xt(),ia={alg:"RS256",typ:"JWT"};class Nr{email;key;keyId;projectId;eagerRefreshThresholdMillis;cache=new Ch.LRUCache({capacity:500,maxAge:3600000});constructor(h,f,g,y){this.email=h,this.key=f,this.keyId=g,this.eagerRefreshThresholdMillis=y??300000}getCachedKey(h,f){let g=h;if(f&&Array.isArray(f)&&f.length)g=h?`${h}_${f.join("_")}`:`${f.join("_")}`;else if(typeof f==="string")g=h?`${h}_${f}`:f;if(!g)throw Error("Scopes or url must be provided");return g}getRequestHeaders(h,f,g){let y=this.getCachedKey(h,g),_=this.cache.get(y),T=Date.now();if(_&&_.expiration-T>this.eagerRefreshThresholdMillis)return new Headers(_.headers);let S=Math.floor(Date.now()/1000),w=Nr.getExpirationTime(S),x;if(Array.isArray(g))g=g.join(" ");if(g)x={iss:this.email,sub:this.email,scope:g,exp:w,iat:S};else x={iss:this.email,sub:this.email,aud:h,exp:w,iat:S};if(f){for(let X in x)if(f[X])throw Error(`The '${X}' property is not allowed when passing additionalClaims. This claim is included in the JWT by default.`)}let B=this.keyId?{...ia,kid:this.keyId}:ia,P=Object.assign(x,f),ne=Eh.sign({header:B,payload:P,secret:this.key}),se=new Headers({authorization:`Bearer ${ne}`});return this.cache.set(y,{expiration:w*1000,headers:se}),se}static getExpirationTime(h){return h+3600}fromJSON(h){if(!h)throw Error("Must pass in a JSON object containing the service account auth settings.");if(!h.client_email)throw Error("The incoming JSON object does not contain a client_email field");if(!h.private_key)throw Error("The incoming JSON object does not contain a private_key field");this.email=h.client_email,this.key=h.private_key,this.keyId=h.private_key_id,this.projectId=h.project_id}fromStream(h,f){if(f)this.fromStreamAsync(h).then(()=>f(),f);else return this.fromStreamAsync(h)}fromStreamAsync(h){return new Promise((f,g)=>{if(!h)g(Error("Must pass in a stream containing the service account auth settings."));let y="";h.setEncoding("utf8").on("data",(_)=>y+=_).on("error",g).on("end",()=>{try{let _=JSON.parse(y);this.fromJSON(_),f()}catch(_){g(_)}})})}}oa.JWTAccess=Nr});var Ur=i(function(la){Object.defineProperty(la,"__esModule",{value:!0});la.JWT=void 0;var ca=Ir(),Ah=Rr(),bh=Pr(),Sh=Ft(),jn=wt();class jr extends Sh.OAuth2Client{email;keyFile;key;keyId;defaultScopes;scopes;scope;subject;gtoken;additionalClaims;useJWTAccessWithScope;defaultServicePath;access;constructor(h={}){super(h);this.email=h.email,this.keyFile=h.keyFile,this.key=h.key,this.keyId=h.keyId,this.scopes=h.scopes,this.subject=h.subject,this.additionalClaims=h.additionalClaims,this.credentials={refresh_token:"jwt-placeholder",expiry_date:1}}createScoped(h){let f=new jr(this);return f.scopes=h,f}async getRequestMetadataAsync(h){h=this.defaultServicePath?`https://${this.defaultServicePath}/`:h;let f=!this.hasUserScopes()&&h||this.useJWTAccessWithScope&&this.hasAnyScopes()||this.universeDomain!==jn.DEFAULT_UNIVERSE;if(this.subject&&this.universeDomain!==jn.DEFAULT_UNIVERSE)throw RangeError(`Service Account user is configured for the credential. Domain-wide delegation is not supported in universes other than ${jn.DEFAULT_UNIVERSE}`);if(!this.apiKey&&f)if(this.additionalClaims&&this.additionalClaims.target_audience){let{tokens:g}=await this.refreshToken();return{headers:this.addSharedMetadataHeaders(new Headers({authorization:`Bearer ${g.id_token}`}))}}else{if(!this.access)this.access=new bh.JWTAccess(this.email,this.key,this.keyId,this.eagerRefreshThresholdMillis);let g;if(this.hasUserScopes())g=this.scopes;else if(!h)g=this.defaultScopes;let y=this.useJWTAccessWithScope||this.universeDomain!==jn.DEFAULT_UNIVERSE,_=await this.access.getRequestHeaders(h??void 0,this.additionalClaims,y?g:void 0);return{headers:this.addSharedMetadataHeaders(_)}}else if(this.hasAnyScopes()||this.apiKey)return super.getRequestMetadataAsync(h);else return{headers:new Headers}}async fetchIdToken(h){let f=new ca.GoogleToken({iss:this.email,sub:this.subject,scope:this.scopes||this.defaultScopes,keyFile:this.keyFile,key:this.key,additionalClaims:{target_audience:h},transporter:this.transporter});if(await f.getToken({forceRefresh:!0}),!f.idToken)throw Error("Unknown error: Failed to fetch ID token");return f.idToken}hasUserScopes(){if(!this.scopes)return!1;return this.scopes.length>0}hasAnyScopes(){if(this.scopes&&this.scopes.length>0)return!0;if(this.defaultScopes&&this.defaultScopes.length>0)return!0;return!1}authorize(h){if(h)this.authorizeAsync().then((f)=>h(null,f),h);else return this.authorizeAsync()}async authorizeAsync(){let h=await this.refreshToken();if(!h)throw Error("No result returned");return this.credentials=h.tokens,this.credentials.refresh_token="jwt-placeholder",this.key=this.gtoken.googleTokenOptions?.key,this.email=this.gtoken.googleTokenOptions?.iss,h.tokens}async refreshTokenNoCache(){let h=this.createGToken(),g={access_token:(await h.getToken({forceRefresh:this.isTokenExpiring()})).access_token,token_type:"Bearer",expiry_date:h.expiresAt,id_token:h.idToken};return this.emit("tokens",g),{res:null,tokens:g}}createGToken(){if(!this.gtoken)this.gtoken=new ca.GoogleToken({iss:this.email,sub:this.subject,scope:this.scopes||this.defaultScopes,keyFile:this.keyFile,key:this.key,additionalClaims:this.additionalClaims,transporter:this.transporter});return this.gtoken}fromJSON(h){if(!h)throw Error("Must pass in a JSON object containing the service account auth settings.");if(!h.client_email)throw Error("The incoming JSON object does not contain a client_email field");if(!h.private_key)throw Error("The incoming JSON object does not contain a private_key field");this.email=h.client_email,this.key=h.private_key,this.keyId=h.private_key_id,this.projectId=h.project_id,this.quotaProjectId=h.quota_project_id,this.universeDomain=h.universe_domain||this.universeDomain}fromStream(h,f){if(f)this.fromStreamAsync(h).then(()=>f(),f);else return this.fromStreamAsync(h)}fromStreamAsync(h){return new Promise((f,g)=>{if(!h)throw Error("Must pass in a stream containing the service account auth settings.");let y="";h.setEncoding("utf8").on("error",g).on("data",(_)=>y+=_).on("end",()=>{try{let _=JSON.parse(y);this.fromJSON(_),f()}catch(_){g(_)}})})}fromAPIKey(h){if(typeof h!=="string")throw Error("Must provide an API Key string.");this.apiKey=h}async getCredentials(){if(this.key)return{private_key:this.key,client_email:this.email};else if(this.keyFile){let h=this.createGToken(),f=await Ah.getCredentials(this.keyFile);return{private_key:f.privateKey,client_email:f.clientEmail}}throw Error("A key or a keyFile must be provided to getCredentials.")}}la.JWT=jr});var Mr=i(function(da){Object.defineProperty(da,"__esModule",{value:!0});da.UserRefreshClient=da.USER_REFRESH_ACCOUNT_TYPE=void 0;var kh=Ft(),xh=wt();da.USER_REFRESH_ACCOUNT_TYPE="authorized_user";class Un extends kh.OAuth2Client{_refreshToken;constructor(h,f,g,y,_){let T=h&&typeof h==="object"?h:{clientId:h,clientSecret:f,refreshToken:g,eagerRefreshThresholdMillis:y,forceRefreshOnFailure:_};super(T);this._refreshToken=T.refreshToken,this.credentials.refresh_token=T.refreshToken}async refreshTokenNoCache(){return super.refreshTokenNoCache(this._refreshToken)}async fetchIdToken(h){let f={...Un.RETRY_CONFIG,url:this.endpoints.oauth2TokenUrl,method:"POST",data:new URLSearchParams({client_id:this._clientId,client_secret:this._clientSecret,grant_type:"refresh_token",refresh_token:this._refreshToken,target_audience:h}),responseType:"json"};return xh.AuthClient.setMethodName(f,"fetchIdToken"),(await this.transporter.request(f)).data.id_token}fromJSON(h){if(!h)throw Error("Must pass in a JSON object containing the user refresh token");if(h.type!=="authorized_user")throw Error('The incoming JSON object does not have the "authorized_user" type');if(!h.client_id)throw Error("The incoming JSON object does not contain a client_id field");if(!h.client_secret)throw Error("The incoming JSON object does not contain a client_secret field");if(!h.refresh_token)throw Error("The incoming JSON object does not contain a refresh_token field");this._clientId=h.client_id,this._clientSecret=h.client_secret,this._refreshToken=h.refresh_token,this.credentials.refresh_token=h.refresh_token,this.quotaProjectId=h.quota_project_id,this.universeDomain=h.universe_domain||this.universeDomain}fromStream(h,f){if(f)this.fromStreamAsync(h).then(()=>f(),f);else return this.fromStreamAsync(h)}async fromStreamAsync(h){return new Promise((f,g)=>{if(!h)return g(Error("Must pass in a stream containing the user refresh token."));let y="";h.setEncoding("utf8").on("error",g).on("data",(_)=>y+=_).on("end",()=>{try{let _=JSON.parse(y);return this.fromJSON(_),f()}catch(_){return g(_)}})})}static fromJSON(h){let f=new Un;return f.fromJSON(h),f}}da.UserRefreshClient=Un});var Dr=i(function(fa){Object.defineProperty(fa,"__esModule",{value:!0});fa.Impersonated=fa.IMPERSONATED_ACCOUNT_TYPE=void 0;var pa=Ft(),Rh=ct(),Ih=xt();fa.IMPERSONATED_ACCOUNT_TYPE="impersonated_service_account";class _n extends pa.OAuth2Client{sourceClient;targetPrincipal;targetScopes;delegates;lifetime;endpoint;constructor(h={}){super(h);if(this.credentials={expiry_date:1,refresh_token:"impersonated-placeholder"},this.sourceClient=h.sourceClient??new pa.OAuth2Client,this.targetPrincipal=h.targetPrincipal??"",this.delegates=h.delegates??[],this.targetScopes=h.targetScopes??[],this.lifetime=h.lifetime??3600,!Ih.originalOrCamelOptions(h).get("universe_domain"))this.universeDomain=this.sourceClient.universeDomain;else if(this.sourceClient.universeDomain!==this.universeDomain)throw RangeError(`Universe domain ${this.sourceClient.universeDomain} in source credentials does not match ${this.universeDomain} universe domain set for impersonated credentials.`);this.endpoint=h.endpoint??`https://iamcredentials.${this.universeDomain}`}async sign(h){await this.sourceClient.getAccessToken();let f=`projects/-/serviceAccounts/${this.targetPrincipal}`,g=`${this.endpoint}/v1/${f}:signBlob`,y={delegates:this.delegates,payload:Buffer.from(h).toString("base64")};return(await this.sourceClient.request({..._n.RETRY_CONFIG,url:g,data:y,method:"POST"})).data}getTargetPrincipal(){return this.targetPrincipal}async refreshToken(){try{await this.sourceClient.getAccessToken();let h="projects/-/serviceAccounts/"+this.targetPrincipal,f=`${this.endpoint}/v1/${h}:generateAccessToken`,g={delegates:this.delegates,scope:this.targetScopes,lifetime:this.lifetime+"s"},y=await this.sourceClient.request({..._n.RETRY_CONFIG,url:f,data:g,method:"POST"}),_=y.data;return this.credentials.access_token=_.accessToken,this.credentials.expiry_date=Date.parse(_.expireTime),{tokens:this.credentials,res:y}}catch(h){if(!(h instanceof Error))throw h;let f=0,g="";if(h instanceof Rh.GaxiosError)f=h?.response?.data?.error?.status,g=h?.response?.data?.error?.message;if(f&&g)throw h.message=`${f}: unable to impersonate: ${g}`,h;else throw h.message=`unable to impersonate: ${h}`,h}}async fetchIdToken(h,f){await this.sourceClient.getAccessToken();let g=`projects/-/serviceAccounts/${this.targetPrincipal}`,y=`${this.endpoint}/v1/${g}:generateIdToken`,_={delegates:this.delegates,audience:h,includeEmail:f?.includeEmail??!0,useEmailAzp:f?.includeEmail??!0};return(await this.sourceClient.request({..._n.RETRY_CONFIG,url:y,data:_,method:"POST"})).data.token}}fa.Impersonated=_n});var qr=i(function(ya){Object.defineProperty(ya,"__esModule",{value:!0});ya.OAuthClientAuthHandler=void 0;ya.getErrorFromOAuthErrorResponse=Uh;var rn=ct(),Ph=gn(),jh=["PUT","POST","PATCH"];class ma{#e=Ph.createCrypto();#t;transporter;constructor(h){if(h&&"clientId"in h)this.#t=h,this.transporter=new rn.Gaxios;else this.#t=h?.clientAuthentication,this.transporter=h?.transporter||new rn.Gaxios}applyClientAuthenticationOptions(h,f){if(h.headers=rn.Gaxios.mergeHeaders(h.headers),this.injectAuthenticatedHeaders(h,f),!f)this.injectAuthenticatedRequestBody(h)}injectAuthenticatedHeaders(h,f){if(f)h.headers=rn.Gaxios.mergeHeaders(h.headers,{authorization:`Bearer ${f}`});else if(this.#t?.confidentialClientType==="basic"){h.headers=rn.Gaxios.mergeHeaders(h.headers);let g=this.#t.clientId,y=this.#t.clientSecret||"",_=this.#e.encodeBase64StringUtf8(`${g}:${y}`);rn.Gaxios.mergeHeaders(h.headers,{authorization:`Basic ${_}`})}}injectAuthenticatedRequestBody(h){if(this.#t?.confidentialClientType==="request-body"){let f=(h.method||"GET").toUpperCase();if(!jh.includes(f))throw Error(`${f} HTTP method does not support ${this.#t.confidentialClientType} client authentication`);let y=new Headers(h.headers).get("content-type");if(y?.startsWith("application/x-www-form-urlencoded")||h.data instanceof URLSearchParams){let _=new URLSearchParams(h.data??"");_.append("client_id",this.#t.clientId),_.append("client_secret",this.#t.clientSecret||""),h.data=_}else if(y?.startsWith("application/json"))h.data=h.data||{},Object.assign(h.data,{client_id:this.#t.clientId,client_secret:this.#t.clientSecret||""});else throw Error(`${y} content-types are not supported with ${this.#t.confidentialClientType} client authentication`)}}static get RETRY_CONFIG(){return{retry:!0,retryConfig:{httpMethodsToRetry:["GET","PUT","POST","HEAD","OPTIONS","DELETE"]}}}}ya.OAuthClientAuthHandler=ma;function Uh(h,f){let{error:g,error_description:y,error_uri:_}=h,T=`Error code ${g}`;if(typeof y<"u")T+=`: ${y}`;if(typeof _<"u")T+=` - ${_}`;let S=Error(T);if(f){let w=Object.keys(f);if(f.stack)w.push("stack");w.forEach((x)=>{if(x!=="message")Object.defineProperty(S,x,{value:f[x],writable:!1,enumerable:!0})})}return S}});var Mn=i(function(va){Object.defineProperty(va,"__esModule",{value:!0});va.StsCredentials=void 0;var Dh=ct(),qh=wt(),Ta=qr(),Lh=xt();class Lr extends Ta.OAuthClientAuthHandler{#e;constructor(h={tokenExchangeEndpoint:""},f){if(typeof h!=="object"||h instanceof URL)h={tokenExchangeEndpoint:h,clientAuthentication:f};super(h);this.#e=h.tokenExchangeEndpoint}async exchangeToken(h,f,g){let y={grant_type:h.grantType,resource:h.resource,audience:h.audience,scope:h.scope?.join(" "),requested_token_type:h.requestedTokenType,subject_token:h.subjectToken,subject_token_type:h.subjectTokenType,actor_token:h.actingParty?.actorToken,actor_token_type:h.actingParty?.actorTokenType,options:g&&JSON.stringify(g)},_={...Lr.RETRY_CONFIG,url:this.#e.toString(),method:"POST",headers:f,data:new URLSearchParams(Lh.removeUndefinedValuesInObject(y)),responseType:"json"};qh.AuthClient.setMethodName(_,"exchangeToken"),this.applyClientAuthenticationOptions(_);try{let T=await this.transporter.request(_),S=T.data;return S.res=T,S}catch(T){if(T instanceof Dh.GaxiosError&&T.response)throw Ta.getErrorFromOAuthErrorResponse(T.response.data,T);throw T}}}va.StsCredentials=Lr});var $t=i(function(Ca){Object.defineProperty(Ca,"__esModule",{value:!0});Ca.BaseExternalAccountClient=Ca.CLOUD_RESOURCE_MANAGER=Ca.EXTERNAL_ACCOUNT_TYPE=Ca.EXPIRATION_TIME_OFFSET=void 0;var Fh=ct(),Gh=c("stream"),Fr=wt(),$h=Mn(),Ea=xt(),Hh=wr(),Bh="urn:ietf:params:oauth:grant-type:token-exchange",Vh="urn:ietf:params:oauth:token-type:access_token",Gr="https://www.googleapis.com/auth/cloud-platform",Wh=3600;Ca.EXPIRATION_TIME_OFFSET=300000;Ca.EXTERNAL_ACCOUNT_TYPE="external_account";Ca.CLOUD_RESOURCE_MANAGER="https://cloudresourcemanager.googleapis.com/v1/projects/";var Kh="//iam\\.googleapis\\.com/locations/[^/]+/workforcePools/[^/]+/providers/.+",Jh="https://sts.{universeDomain}/v1/token";class Dn extends Fr.AuthClient{scopes;projectNumber;audience;subjectTokenType;stsCredential;clientAuth;credentialSourceType;cachedAccessToken;serviceAccountImpersonationUrl;serviceAccountImpersonationLifetime;workforcePoolUserProject;configLifetimeRequested;tokenUrl;cloudResourceManagerURL;supplierContext;#e=null;constructor(h){super(h);let f=Ea.originalOrCamelOptions(h),g=f.get("type");if(g&&g!==Ca.EXTERNAL_ACCOUNT_TYPE)throw Error(`Expected "${Ca.EXTERNAL_ACCOUNT_TYPE}" type but received "${h.type}"`);let y=f.get("client_id"),_=f.get("client_secret");this.tokenUrl=f.get("token_url")??Jh.replace("{universeDomain}",this.universeDomain);let T=f.get("subject_token_type"),S=f.get("workforce_pool_user_project"),w=f.get("service_account_impersonation_url"),x=f.get("service_account_impersonation"),B=Ea.originalOrCamelOptions(x).get("token_lifetime_seconds");if(this.cloudResourceManagerURL=new URL(f.get("cloud_resource_manager_url")||`https://cloudresourcemanager.${this.universeDomain}/v1/projects/`),y)this.clientAuth={confidentialClientType:"basic",clientId:y,clientSecret:_};this.stsCredential=new $h.StsCredentials({tokenExchangeEndpoint:this.tokenUrl,clientAuthentication:this.clientAuth}),this.scopes=f.get("scopes")||[Gr],this.cachedAccessToken=null,this.audience=f.get("audience"),this.subjectTokenType=T,this.workforcePoolUserProject=S;let P=new RegExp(Kh);if(this.workforcePoolUserProject&&!this.audience.match(P))throw Error("workforcePoolUserProject should not be set for non-workforce pool credentials.");if(this.serviceAccountImpersonationUrl=w,this.serviceAccountImpersonationLifetime=B,this.serviceAccountImpersonationLifetime)this.configLifetimeRequested=!0;else this.configLifetimeRequested=!1,this.serviceAccountImpersonationLifetime=Wh;this.projectNumber=this.getProjectNumber(this.audience),this.supplierContext={audience:this.audience,subjectTokenType:this.subjectTokenType,transporter:this.transporter}}getServiceAccountEmail(){if(this.serviceAccountImpersonationUrl){if(this.serviceAccountImpersonationUrl.length>256)throw RangeError(`URL is too long: ${this.serviceAccountImpersonationUrl}`);return/serviceAccounts\/(?<email>[^:]+):generateAccessToken$/.exec(this.serviceAccountImpersonationUrl)?.groups?.email||null}return null}setCredentials(h){super.setCredentials(h),this.cachedAccessToken=h}async getAccessToken(){if(!this.cachedAccessToken||this.isExpired(this.cachedAccessToken))await this.refreshAccessTokenAsync();return{token:this.cachedAccessToken.access_token,res:this.cachedAccessToken.res}}async getRequestHeaders(){let h=await this.getAccessToken(),f=new Headers({authorization:`Bearer ${h.token}`});return this.addSharedMetadataHeaders(f)}request(h,f){if(f)this.requestAsync(h).then((g)=>f(null,g),(g)=>f(g,g.response));else return this.requestAsync(h)}async getProjectId(){let h=this.projectNumber||this.workforcePoolUserProject;if(this.projectId)return this.projectId;else if(h){let f=await this.getRequestHeaders(),g={...Dn.RETRY_CONFIG,headers:f,url:`${this.cloudResourceManagerURL.toString()}${h}`,responseType:"json"};Fr.AuthClient.setMethodName(g,"getProjectId");let y=await this.transporter.request(g);return this.projectId=y.data.projectId,this.projectId}return null}async requestAsync(h,f=!1){let g;try{let y=await this.getRequestHeaders();h.headers=Fh.Gaxios.mergeHeaders(h.headers),this.addUserProjectAndAuthHeaders(h.headers,y),g=await this.transporter.request(h)}catch(y){let _=y.response;if(_){let T=_.status,S=_.config.data instanceof Gh.Readable;if(!f&&(T===401||T===403)&&!S&&this.forceRefreshOnFailure)return await this.refreshAccessTokenAsync(),await this.requestAsync(h,!0)}throw y}return g}async refreshAccessTokenAsync(){this.#e=this.#e||this.#t();try{return await this.#e}finally{this.#e=null}}async#t(){let h=await this.retrieveSubjectToken(),f={grantType:Bh,audience:this.audience,requestedTokenType:Vh,subjectToken:h,subjectTokenType:this.subjectTokenType,scope:this.serviceAccountImpersonationUrl?[Gr]:this.getScopesArray()},g=!this.clientAuth&&this.workforcePoolUserProject?{userProject:this.workforcePoolUserProject}:void 0,y=new Headers({"x-goog-api-client":this.getMetricsHeaderValue()}),_=await this.stsCredential.exchangeToken(f,y,g);if(this.serviceAccountImpersonationUrl)this.cachedAccessToken=await this.getImpersonatedAccessToken(_.access_token);else if(_.expires_in)this.cachedAccessToken={access_token:_.access_token,expiry_date:new Date().getTime()+_.expires_in*1000,res:_.res};else this.cachedAccessToken={access_token:_.access_token,res:_.res};return this.credentials={},Object.assign(this.credentials,this.cachedAccessToken),delete this.credentials.res,this.emit("tokens",{refresh_token:null,expiry_date:this.cachedAccessToken.expiry_date,access_token:this.cachedAccessToken.access_token,token_type:"Bearer",id_token:null}),this.cachedAccessToken}getProjectNumber(h){let f=h.match(/\/projects\/([^/]+)/);if(!f)return null;return f[1]}async getImpersonatedAccessToken(h){let f={...Dn.RETRY_CONFIG,url:this.serviceAccountImpersonationUrl,method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${h}`},data:{scope:this.getScopesArray(),lifetime:this.serviceAccountImpersonationLifetime+"s"},responseType:"json"};Fr.AuthClient.setMethodName(f,"getImpersonatedAccessToken");let g=await this.transporter.request(f),y=g.data;return{access_token:y.accessToken,expiry_date:new Date(y.expireTime).getTime(),res:g}}isExpired(h){let f=new Date().getTime();return h.expiry_date?f>=h.expiry_date-this.eagerRefreshThresholdMillis:!1}getScopesArray(){if(typeof this.scopes==="string")return[this.scopes];return this.scopes||[Gr]}getMetricsHeaderValue(){let h=process.version.replace(/^v/,""),f=this.serviceAccountImpersonationUrl!==void 0,g=this.credentialSourceType?this.credentialSourceType:"unknown";return`gl-node/${h} auth/${Hh.pkg.version} google-byoid-sdk source/${g} sa-impersonation/${f} config-lifetime/${this.configLifetimeRequested}`}getTokenUrl(){return this.tokenUrl}}Ca.BaseExternalAccountClient=Dn});var xa=i(function(Sa){Object.defineProperty(Sa,"__esModule",{value:!0});Sa.FileSubjectTokenSupplier=void 0;var Hr=c("util"),Br=c("fs"),Xh=Hr.promisify(Br.readFile??(()=>{})),Qh=Hr.promisify(Br.realpath??(()=>{})),Zh=Hr.promisify(Br.lstat??(()=>{}));class ba{filePath;formatType;subjectTokenFieldName;constructor(h){this.filePath=h.filePath,this.formatType=h.formatType,this.subjectTokenFieldName=h.subjectTokenFieldName}async getSubjectToken(){let h=this.filePath;try{if(h=await Qh(h),!(await Zh(h)).isFile())throw Error()}catch(y){if(y instanceof Error)y.message=`The file at ${h} does not exist, or it is not a file. ${y.message}`;throw y}let f,g=await Xh(h,{encoding:"utf8"});if(this.formatType==="text")f=g;else if(this.formatType==="json"&&this.subjectTokenFieldName)f=JSON.parse(g)[this.subjectTokenFieldName];if(!f)throw Error("Unable to parse the subject_token from the credential_source file");return f}}Sa.FileSubjectTokenSupplier=ba});var Na=i(function(Ra){Object.defineProperty(Ra,"__esModule",{value:!0});Ra.UrlSubjectTokenSupplier=void 0;var ep=wt();class Oa{url;headers;formatType;subjectTokenFieldName;additionalGaxiosOptions;constructor(h){this.url=h.url,this.formatType=h.formatType,this.subjectTokenFieldName=h.subjectTokenFieldName,this.headers=h.headers,this.additionalGaxiosOptions=h.additionalGaxiosOptions}async getSubjectToken(h){let f={...this.additionalGaxiosOptions,url:this.url,method:"GET",headers:this.headers,responseType:this.formatType};ep.AuthClient.setMethodName(f,"getSubjectToken");let g;if(this.formatType==="text")g=(await h.transporter.request(f)).data;else if(this.formatType==="json"&&this.subjectTokenFieldName)g=(await h.transporter.request(f)).data[this.subjectTokenFieldName];if(!g)throw Error("Unable to parse the subject_token from the credential_source URL");return g}}Ra.UrlSubjectTokenSupplier=Oa});var Ma=i(function(ja){Object.defineProperty(ja,"__esModule",{value:!0});ja.CertificateSubjectTokenSupplier=ja.InvalidConfigurationError=ja.CertificateSourceUnavailableError=ja.CERTIFICATE_CONFIGURATION_ENV_VARIABLE=void 0;var Ln=xt(),qn=c("fs"),Fn=c("crypto"),tp=c("https");ja.CERTIFICATE_CONFIGURATION_ENV_VARIABLE="GOOGLE_API_CERTIFICATE_CONFIG";class Mt extends Error{constructor(h){super(h);this.name="CertificateSourceUnavailableError"}}ja.CertificateSourceUnavailableError=Mt;class Ot extends Error{constructor(h){super(h);this.name="InvalidConfigurationError"}}ja.InvalidConfigurationError=Ot;class Pa{certificateConfigPath;trustChainPath;cert;key;constructor(h){if(!h.useDefaultCertificateConfig&&!h.certificateConfigLocation)throw new Ot("Either `useDefaultCertificateConfig` must be true or a `certificateConfigLocation` must be provided.");if(h.useDefaultCertificateConfig&&h.certificateConfigLocation)throw new Ot("Both `useDefaultCertificateConfig` and `certificateConfigLocation` cannot be provided.");this.trustChainPath=h.trustChainPath,this.certificateConfigPath=h.certificateConfigLocation??""}async createMtlsHttpsAgent(){if(!this.key||!this.cert)throw new Ot("Cannot create mTLS Agent with missing certificate or key");return new tp.Agent({key:this.key,cert:this.cert})}async getSubjectToken(){this.certificateConfigPath=await this.#e();let{certPath:h,keyPath:f}=await this.#t();return{cert:this.cert,key:this.key}=await this.#n(h,f),await this.#r(this.cert)}async#e(){let h=this.certificateConfigPath;if(h){if(await Ln.isValidFile(h))return h;throw new Mt(`Provided certificate config path is invalid: ${h}`)}let f=process.env[ja.CERTIFICATE_CONFIGURATION_ENV_VARIABLE];if(f){if(await Ln.isValidFile(f))return f;throw new Mt(`Path from environment variable "${ja.CERTIFICATE_CONFIGURATION_ENV_VARIABLE}" is invalid: ${f}`)}let g=Ln.getWellKnownCertificateConfigFileLocation();if(await Ln.isValidFile(g))return g;throw new Mt(`Could not find certificate configuration file. Searched override path, the "${ja.CERTIFICATE_CONFIGURATION_ENV_VARIABLE}" env var, and the gcloud path (${g}).`)}async#t(){let h=this.certificateConfigPath,f;try{f=await qn.promises.readFile(h,"utf8")}catch(g){throw new Mt(`Failed to read certificate config file at: ${h}`)}try{let g=JSON.parse(f),y=g?.cert_configs?.workload?.cert_path,_=g?.cert_configs?.workload?.key_path;if(!y||!_)throw new Ot(`Certificate config file (${h}) is missing required "cert_path" or "key_path" in the workload config.`);return{certPath:y,keyPath:_}}catch(g){if(g instanceof Ot)throw g;throw new Ot(`Failed to parse certificate config from ${h}: ${g.message}`)}}async#n(h,f){let g,y;try{g=await qn.promises.readFile(h),new Fn.X509Certificate(g)}catch(_){let T=_ instanceof Error?_.message:String(_);throw new Mt(`Failed to read certificate file at ${h}: ${T}`)}try{y=await qn.promises.readFile(f),Fn.createPrivateKey(y)}catch(_){let T=_ instanceof Error?_.message:String(_);throw new Mt(`Failed to read private key file at ${f}: ${T}`)}return{cert:g,key:y}}async#r(h){let f=new Fn.X509Certificate(h);if(!this.trustChainPath)return JSON.stringify([f.raw.toString("base64")]);try{let _=((await qn.promises.readFile(this.trustChainPath,"utf8")).match(/-----BEGIN CERTIFICATE-----[^-]+-----END CERTIFICATE-----/g)??[]).map((w,x)=>{try{return new Fn.X509Certificate(w)}catch(B){let P=B instanceof Error?B.message:String(B);throw new Ot(`Failed to parse certificate at index ${x} in trust chain file ${this.trustChainPath}: ${P}`)}}),T=_.findIndex((w)=>f.raw.equals(w.raw)),S;if(T===-1)S=[f,..._];else if(T===0)S=_;else throw new Ot(`Leaf certificate exists in the trust chain but is not the first entry (found at index ${T}).`);return JSON.stringify(S.map((w)=>w.raw.toString("base64")))}catch(g){if(g instanceof Ot)throw g;let y=g instanceof Error?g.message:String(g);throw new Mt(`Failed to process certificate chain from ${this.trustChainPath}: ${y}`)}}}ja.CertificateSubjectTokenSupplier=Pa});var Jr=i(function(La){Object.defineProperty(La,"__esModule",{value:!0});La.IdentityPoolClient=void 0;var sp=$t(),Vr=xt(),ip=xa(),op=Na(),Da=Ma(),ap=Mn(),qa=ct();class Kr extends sp.BaseExternalAccountClient{subjectTokenSupplier;constructor(h){super(h);let f=Vr.originalOrCamelOptions(h),g=f.get("credential_source"),y=f.get("subject_token_supplier");if(!g&&!y)throw Error("A credential source or subject token supplier must be specified.");if(g&&y)throw Error("Only one of credential source or subject token supplier can be specified.");if(y)this.subjectTokenSupplier=y,this.credentialSourceType="programmatic";else{let _=Vr.originalOrCamelOptions(g),T=Vr.originalOrCamelOptions(_.get("format")),S=T.get("type")||"text",w=T.get("subject_token_field_name");if(S!=="json"&&S!=="text")throw Error(`Invalid credential_source format "${S}"`);if(S==="json"&&!w)throw Error("Missing subject_token_field_name for JSON credential_source format");let x=_.get("file"),B=_.get("url"),P=_.get("certificate"),ne=_.get("headers");if(x&&B||B&&P||x&&P)throw Error('No valid Identity Pool "credential_source" provided, must be either file, url, or certificate.');else if(x)this.credentialSourceType="file",this.subjectTokenSupplier=new ip.FileSubjectTokenSupplier({filePath:x,formatType:S,subjectTokenFieldName:w});else if(B)this.credentialSourceType="url",this.subjectTokenSupplier=new op.UrlSubjectTokenSupplier({url:B,formatType:S,subjectTokenFieldName:w,headers:ne,additionalGaxiosOptions:Kr.RETRY_CONFIG});else if(P){this.credentialSourceType="certificate";let se=new Da.CertificateSubjectTokenSupplier({useDefaultCertificateConfig:P.use_default_certificate_config,certificateConfigLocation:P.certificate_config_location,trustChainPath:P.trust_chain_path});this.subjectTokenSupplier=se}else throw Error('No valid Identity Pool "credential_source" provided, must be either file, url, or certificate.')}}async retrieveSubjectToken(){let h=await this.subjectTokenSupplier.getSubjectToken(this.supplierContext);if(this.subjectTokenSupplier instanceof Da.CertificateSubjectTokenSupplier){let f=await this.subjectTokenSupplier.createMtlsHttpsAgent();this.stsCredential=new ap.StsCredentials({tokenExchangeEndpoint:this.getTokenUrl(),clientAuthentication:this.clientAuth,transporter:new qa.Gaxios({agent:f})}),this.transporter=new qa.Gaxios({...this.transporter.defaults||{},agent:f})}return h}}La.IdentityPoolClient=Kr});var Yr=i(function(Ba){Object.defineProperty(Ba,"__esModule",{value:!0});Ba.AwsRequestSigner=void 0;var $n=ct(),$a=gn(),Ga="AWS4-HMAC-SHA256",cp="aws4_request";class Ha{getCredentials;region;crypto;constructor(h,f){this.getCredentials=h,this.region=f,this.crypto=$a.createCrypto()}async getRequestOptions(h){if(!h.url)throw RangeError('"url" is required in "amzOptions"');let f=typeof h.data==="object"?JSON.stringify(h.data):h.data,g=h.url,y=h.method||"GET",_=h.body||f,T=h.headers,S=await this.getCredentials(),w=new URL(g);if(typeof _!=="string"&&_!==void 0)throw TypeError(`'requestPayload' is expected to be a string if provided. Got: ${_}`);let x=await up({crypto:this.crypto,host:w.host,canonicalUri:w.pathname,canonicalQuerystring:w.search.slice(1),method:y,region:this.region,securityCredentials:S,requestPayload:_,additionalAmzHeaders:T}),B=$n.Gaxios.mergeHeaders(x.amzDate?{"x-amz-date":x.amzDate}:{},{authorization:x.authorizationHeader,host:w.host},T||{});if(S.token)$n.Gaxios.mergeHeaders(B,{"x-amz-security-token":S.token});let P={url:g,method:y,headers:B};if(_!==void 0)P.body=_;return P}}Ba.AwsRequestSigner=Ha;async function Tn(h,f,g){return await h.signWithHmacSha256(f,g)}async function lp(h,f,g,y,_){let T=await Tn(h,`AWS4${f}`,g),S=await Tn(h,T,y),w=await Tn(h,S,_);return await Tn(h,w,"aws4_request")}async function up(h){let f=$n.Gaxios.mergeHeaders(h.additionalAmzHeaders),g=h.requestPayload||"",y=h.host.split(".")[0],_=new Date,T=_.toISOString().replace(/[-:]/g,"").replace(/\.[0-9]+/,""),S=_.toISOString().replace(/[-]/g,"").replace(/T.*/,"");if(h.securityCredentials.token)f.set("x-amz-security-token",h.securityCredentials.token);let w=$n.Gaxios.mergeHeaders({host:h.host},f.has("date")?{}:{"x-amz-date":T},f),x="",B=[...w.keys()].sort();B.forEach((L)=>{x+=`${L}:${w.get(L)}
|
|
14
|
+
`});let P=B.join(";"),ne=await h.crypto.sha256DigestHex(g),se=`${h.method.toUpperCase()}
|
|
15
|
+
${h.canonicalUri}
|
|
16
|
+
${h.canonicalQuerystring}
|
|
17
|
+
${x}
|
|
18
|
+
${P}
|
|
19
|
+
${ne}`,X=`${S}/${h.region}/${y}/${cp}`,z=`${Ga}
|
|
20
|
+
${T}
|
|
21
|
+
${X}
|
|
22
|
+
`+await h.crypto.sha256DigestHex(se),Z=await lp(h.crypto,h.securityCredentials.secretAccessKey,S,h.region,y),ue=await Tn(h.crypto,Z,z),M=`${Ga} Credential=${h.securityCredentials.accessKeyId}/${X}, SignedHeaders=${P}, Signature=${$a.fromArrayBufferToHex(ue)}`;return{amzDate:f.has("date")?void 0:T,authorizationHeader:M,canonicalQuerystring:h.canonicalQuerystring}}});var Ya=i(function(Ka){Object.defineProperty(Ka,"__esModule",{value:!0});Ka.DefaultAwsSecurityCredentialsSupplier=void 0;var Hn=wt();class Wa{regionUrl;securityCredentialsUrl;imdsV2SessionTokenUrl;additionalGaxiosOptions;constructor(h){this.regionUrl=h.regionUrl,this.securityCredentialsUrl=h.securityCredentialsUrl,this.imdsV2SessionTokenUrl=h.imdsV2SessionTokenUrl,this.additionalGaxiosOptions=h.additionalGaxiosOptions}async getAwsRegion(h){if(this.#r)return this.#r;let f=new Headers;if(!this.#r&&this.imdsV2SessionTokenUrl)f.set("x-aws-ec2-metadata-token",await this.#e(h.transporter));if(!this.regionUrl)throw RangeError('Unable to determine AWS region due to missing "options.credential_source.region_url"');let g={...this.additionalGaxiosOptions,url:this.regionUrl,method:"GET",responseType:"text",headers:f};Hn.AuthClient.setMethodName(g,"getAwsRegion");let y=await h.transporter.request(g);return y.data.substr(0,y.data.length-1)}async getAwsSecurityCredentials(h){if(this.#s)return this.#s;let f=new Headers;if(this.imdsV2SessionTokenUrl)f.set("x-aws-ec2-metadata-token",await this.#e(h.transporter));let g=await this.#t(f,h.transporter),y=await this.#n(g,f,h.transporter);return{accessKeyId:y.AccessKeyId,secretAccessKey:y.SecretAccessKey,token:y.Token}}async#e(h){let f={...this.additionalGaxiosOptions,url:this.imdsV2SessionTokenUrl,method:"PUT",responseType:"text",headers:{"x-aws-ec2-metadata-token-ttl-seconds":"300"}};return Hn.AuthClient.setMethodName(f,"#getImdsV2SessionToken"),(await h.request(f)).data}async#t(h,f){if(!this.securityCredentialsUrl)throw Error('Unable to determine AWS role name due to missing "options.credential_source.url"');let g={...this.additionalGaxiosOptions,url:this.securityCredentialsUrl,method:"GET",responseType:"text",headers:h};return Hn.AuthClient.setMethodName(g,"#getAwsRoleName"),(await f.request(g)).data}async#n(h,f,g){let y={...this.additionalGaxiosOptions,url:`${this.securityCredentialsUrl}/${h}`,headers:f,responseType:"json"};return Hn.AuthClient.setMethodName(y,"#retrieveAwsSecurityCredentials"),(await g.request(y)).data}get#r(){return process.env.AWS_REGION||process.env.AWS_DEFAULT_REGION||null}get#s(){if(process.env.AWS_ACCESS_KEY_ID&&process.env.AWS_SECRET_ACCESS_KEY)return{accessKeyId:process.env.AWS_ACCESS_KEY_ID,secretAccessKey:process.env.AWS_SECRET_ACCESS_KEY,token:process.env.AWS_SESSION_TOKEN};return null}}Ka.DefaultAwsSecurityCredentialsSupplier=Wa});var zr=i(function(Xa){Object.defineProperty(Xa,"__esModule",{value:!0});Xa.AwsClient=void 0;var hp=Yr(),pp=$t(),fp=Ya(),za=xt(),gp=ct();class Bn extends pp.BaseExternalAccountClient{environmentId;awsSecurityCredentialsSupplier;regionalCredVerificationUrl;awsRequestSigner;region;static#e="https://sts.{region}.amazonaws.com?Action=GetCallerIdentity&Version=2011-06-15";static AWS_EC2_METADATA_IPV4_ADDRESS="169.254.169.254";static AWS_EC2_METADATA_IPV6_ADDRESS="fd00:ec2::254";constructor(h){super(h);let f=za.originalOrCamelOptions(h),g=f.get("credential_source"),y=f.get("aws_security_credentials_supplier");if(!g&&!y)throw Error("A credential source or AWS security credentials supplier must be specified.");if(g&&y)throw Error("Only one of credential source or AWS security credentials supplier can be specified.");if(y)this.awsSecurityCredentialsSupplier=y,this.regionalCredVerificationUrl=Bn.#e,this.credentialSourceType="programmatic";else{let _=za.originalOrCamelOptions(g);this.environmentId=_.get("environment_id");let T=_.get("region_url"),S=_.get("url"),w=_.get("imdsv2_session_token_url");this.awsSecurityCredentialsSupplier=new fp.DefaultAwsSecurityCredentialsSupplier({regionUrl:T,securityCredentialsUrl:S,imdsV2SessionTokenUrl:w}),this.regionalCredVerificationUrl=_.get("regional_cred_verification_url"),this.credentialSourceType="aws",this.validateEnvironmentId()}this.awsRequestSigner=null,this.region=""}validateEnvironmentId(){let h=this.environmentId?.match(/^(aws)(\d+)$/);if(!h||!this.regionalCredVerificationUrl)throw Error('No valid AWS "credential_source" provided');else if(parseInt(h[2],10)!==1)throw Error(`aws version "${h[2]}" is not supported in the current build.`)}async retrieveSubjectToken(){if(!this.awsRequestSigner)this.region=await this.awsSecurityCredentialsSupplier.getAwsRegion(this.supplierContext),this.awsRequestSigner=new hp.AwsRequestSigner(async()=>this.awsSecurityCredentialsSupplier.getAwsSecurityCredentials(this.supplierContext),this.region);let h=await this.awsRequestSigner.getRequestOptions({...Bn.RETRY_CONFIG,url:this.regionalCredVerificationUrl.replace("{region}",this.region),method:"POST"}),f=[];return gp.Gaxios.mergeHeaders({"x-goog-cloud-target-resource":this.audience},h.headers).forEach((y,_)=>f.push({key:_,value:y})),encodeURIComponent(JSON.stringify({url:h.url,method:h.method,headers:f}))}}Xa.AwsClient=Bn});var ss=i(function(tc){Object.defineProperty(tc,"__esModule",{value:!0});tc.InvalidSubjectTokenError=tc.InvalidMessageFieldError=tc.InvalidCodeFieldError=tc.InvalidTokenTypeFieldError=tc.InvalidExpirationTimeFieldError=tc.InvalidSuccessFieldError=tc.InvalidVersionFieldError=tc.ExecutableResponseError=tc.ExecutableResponse=void 0;var Vn="urn:ietf:params:oauth:token-type:saml2",Xr="urn:ietf:params:oauth:token-type:id_token",Qr="urn:ietf:params:oauth:token-type:jwt";class Za{version;success;expirationTime;tokenType;errorCode;errorMessage;subjectToken;constructor(h){if(!h.version)throw new Zr("Executable response must contain a 'version' field.");if(h.success===void 0)throw new es("Executable response must contain a 'success' field.");if(this.version=h.version,this.success=h.success,this.success){if(this.expirationTime=h.expiration_time,this.tokenType=h.token_type,this.tokenType!==Vn&&this.tokenType!==Xr&&this.tokenType!==Qr)throw new ts(`Executable response must contain a 'token_type' field when successful and it must be one of ${Xr}, ${Qr}, or ${Vn}.`);if(this.tokenType===Vn){if(!h.saml_response)throw new Wn(`Executable response must contain a 'saml_response' field when token_type=${Vn}.`);this.subjectToken=h.saml_response}else{if(!h.id_token)throw new Wn(`Executable response must contain a 'id_token' field when token_type=${Xr} or ${Qr}.`);this.subjectToken=h.id_token}}else{if(!h.code)throw new ns("Executable response must contain a 'code' field when unsuccessful.");if(!h.message)throw new rs("Executable response must contain a 'message' field when unsuccessful.");this.errorCode=h.code,this.errorMessage=h.message}}isValid(){return!this.isExpired()&&this.success}isExpired(){return this.expirationTime!==void 0&&this.expirationTime<Math.round(Date.now()/1000)}}tc.ExecutableResponse=Za;class Dt extends Error{constructor(h){super(h);Object.setPrototypeOf(this,new.target.prototype)}}tc.ExecutableResponseError=Dt;class Zr extends Dt{}tc.InvalidVersionFieldError=Zr;class es extends Dt{}tc.InvalidSuccessFieldError=es;class ec extends Dt{}tc.InvalidExpirationTimeFieldError=ec;class ts extends Dt{}tc.InvalidTokenTypeFieldError=ts;class ns extends Dt{}tc.InvalidCodeFieldError=ns;class rs extends Dt{}tc.InvalidMessageFieldError=rs;class Wn extends Dt{}tc.InvalidSubjectTokenError=Wn});var cs=i(function(rc){Object.defineProperty(rc,"__esModule",{value:!0});rc.PluggableAuthHandler=rc.ExecutableError=void 0;var Yt=ss(),Ap=c("child_process"),is=c("fs");class os extends Error{code;constructor(h,f){super(`The executable failed with exit code: ${f} and error message: ${h}.`);this.code=f,Object.setPrototypeOf(this,new.target.prototype)}}rc.ExecutableError=os;class as{commandComponents;timeoutMillis;outputFile;constructor(h){if(!h.command)throw Error("No command provided.");if(this.commandComponents=as.parseCommand(h.command),this.timeoutMillis=h.timeoutMillis,!this.timeoutMillis)throw Error("No timeoutMillis provided.");this.outputFile=h.outputFile}retrieveResponseFromExecutable(h){return new Promise((f,g)=>{let y=Ap.spawn(this.commandComponents[0],this.commandComponents.slice(1),{env:{...process.env,...Object.fromEntries(h)}}),_="";y.stdout.on("data",(S)=>{_+=S}),y.stderr.on("data",(S)=>{_+=S});let T=setTimeout(()=>(y.removeAllListeners(),y.kill(),g(Error("The executable failed to finish within the timeout specified."))),this.timeoutMillis);y.on("close",(S)=>{if(clearTimeout(T),S===0)try{let w=JSON.parse(_),x=new Yt.ExecutableResponse(w);return f(x)}catch(w){if(w instanceof Yt.ExecutableResponseError)return g(w);return g(new Yt.ExecutableResponseError(`The executable returned an invalid response: ${_}`))}else return g(new os(_,S.toString()))})})}async retrieveCachedResponse(){if(!this.outputFile||this.outputFile.length===0)return;let h;try{h=await is.promises.realpath(this.outputFile)}catch{return}if(!(await is.promises.lstat(h)).isFile())return;let f=await is.promises.readFile(h,{encoding:"utf8"});if(f==="")return;try{let g=JSON.parse(f);if(new Yt.ExecutableResponse(g).isValid())return new Yt.ExecutableResponse(g);return}catch(g){if(g instanceof Yt.ExecutableResponseError)throw g;throw new Yt.ExecutableResponseError(`The output file contained an invalid response: ${f}`)}}static parseCommand(h){let f=h.match(/(?:[^\s"]+|"[^"]*")+/g);if(!f)throw Error(`Provided command: "${h}" could not be parsed.`);for(let g=0;g<f.length;g++)if(f[g][0]==='"'&&f[g].slice(-1)==='"')f[g]=f[g].slice(1,-1);return f}}rc.PluggableAuthHandler=as});var us=i(function(ls){Object.defineProperty(ls,"__esModule",{value:!0});ls.PluggableAuthClient=ls.ExecutableError=void 0;var Sp=$t(),kp=ss(),cc=cs(),xp=cs();Object.defineProperty(ls,"ExecutableError",{enumerable:!0,get:function(){return xp.ExecutableError}});var Op=30000,ic=5000,oc=120000,Rp="GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES",ac=1;class lc extends Sp.BaseExternalAccountClient{command;timeoutMillis;outputFile;handler;constructor(h){super(h);if(!h.credential_source.executable)throw Error('No valid Pluggable Auth "credential_source" provided.');if(this.command=h.credential_source.executable.command,!this.command)throw Error('No valid Pluggable Auth "credential_source" provided.');if(h.credential_source.executable.timeout_millis===void 0)this.timeoutMillis=Op;else if(this.timeoutMillis=h.credential_source.executable.timeout_millis,this.timeoutMillis<ic||this.timeoutMillis>oc)throw Error(`Timeout must be between ${ic} and ${oc} milliseconds.`);this.outputFile=h.credential_source.executable.output_file,this.handler=new cc.PluggableAuthHandler({command:this.command,timeoutMillis:this.timeoutMillis,outputFile:this.outputFile}),this.credentialSourceType="executable"}async retrieveSubjectToken(){if(process.env[Rp]!=="1")throw Error("Pluggable Auth executables need to be explicitly allowed to run by setting the GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES environment Variable to 1.");let h=void 0;if(this.outputFile)h=await this.handler.retrieveCachedResponse();if(!h){let f=new Map;if(f.set("GOOGLE_EXTERNAL_ACCOUNT_AUDIENCE",this.audience),f.set("GOOGLE_EXTERNAL_ACCOUNT_TOKEN_TYPE",this.subjectTokenType),f.set("GOOGLE_EXTERNAL_ACCOUNT_INTERACTIVE","0"),this.outputFile)f.set("GOOGLE_EXTERNAL_ACCOUNT_OUTPUT_FILE",this.outputFile);let g=this.getServiceAccountEmail();if(g)f.set("GOOGLE_EXTERNAL_ACCOUNT_IMPERSONATED_EMAIL",g);h=await this.handler.retrieveResponseFromExecutable(f)}if(h.version>ac)throw Error(`Version of executable is not currently supported, maximum supported version is ${ac}.`);if(!h.success)throw new cc.ExecutableError(h.errorMessage,h.errorCode);if(this.outputFile){if(!h.expirationTime)throw new kp.InvalidExpirationTimeFieldError("The executable response must contain the `expiration_time` field for successful responses when an output_file has been specified in the configuration.")}if(h.isExpired())throw Error("Executable response is expired.");return h.subjectToken}}ls.PluggableAuthClient=lc});var ds=i(function(hc){Object.defineProperty(hc,"__esModule",{value:!0});hc.ExternalAccountClient=void 0;var Ip=$t(),Np=Jr(),Pp=zr(),jp=us();class dc{constructor(){throw Error("ExternalAccountClients should be initialized via: ExternalAccountClient.fromJSON(), directly via explicit constructors, eg. new AwsClient(options), new IdentityPoolClient(options), newPluggableAuthClientOptions, or via new GoogleAuth(options).getClient()")}static fromJSON(h){if(h&&h.type===Ip.EXTERNAL_ACCOUNT_TYPE)if(h.credential_source?.environment_id)return new Pp.AwsClient(h);else if(h.credential_source?.executable)return new jp.PluggableAuthClient(h);else return new Np.IdentityPoolClient(h);else return null}}hc.ExternalAccountClient=dc});var ps=i(function(Tc){Object.defineProperty(Tc,"__esModule",{value:!0});Tc.ExternalAccountAuthorizedUserClient=Tc.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE=void 0;var fc=wt(),mc=qr(),yc=ct(),Up=c("stream"),Mp=$t();Tc.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE="external_account_authorized_user";var Dp="https://sts.{universeDomain}/v1/oauthtoken";class hs extends mc.OAuthClientAuthHandler{#e;constructor(h){super(h);this.#e=h.tokenRefreshEndpoint}async refreshToken(h,f){let g={...hs.RETRY_CONFIG,url:this.#e,method:"POST",headers:f,data:new URLSearchParams({grant_type:"refresh_token",refresh_token:h}),responseType:"json"};fc.AuthClient.setMethodName(g,"refreshToken"),this.applyClientAuthenticationOptions(g);try{let y=await this.transporter.request(g),_=y.data;return _.res=y,_}catch(y){if(y instanceof yc.GaxiosError&&y.response)throw mc.getErrorFromOAuthErrorResponse(y.response.data,y);throw y}}}class _c extends fc.AuthClient{cachedAccessToken;externalAccountAuthorizedUserHandler;refreshToken;constructor(h){super(h);if(h.universe_domain)this.universeDomain=h.universe_domain;this.refreshToken=h.refresh_token;let f={confidentialClientType:"basic",clientId:h.client_id,clientSecret:h.client_secret};if(this.externalAccountAuthorizedUserHandler=new hs({tokenRefreshEndpoint:h.token_url??Dp.replace("{universeDomain}",this.universeDomain),transporter:this.transporter,clientAuthentication:f}),this.cachedAccessToken=null,this.quotaProjectId=h.quota_project_id,typeof h?.eagerRefreshThresholdMillis!=="number")this.eagerRefreshThresholdMillis=Mp.EXPIRATION_TIME_OFFSET;else this.eagerRefreshThresholdMillis=h.eagerRefreshThresholdMillis;this.forceRefreshOnFailure=!!h?.forceRefreshOnFailure}async getAccessToken(){if(!this.cachedAccessToken||this.isExpired(this.cachedAccessToken))await this.refreshAccessTokenAsync();return{token:this.cachedAccessToken.access_token,res:this.cachedAccessToken.res}}async getRequestHeaders(){let h=await this.getAccessToken(),f=new Headers({authorization:`Bearer ${h.token}`});return this.addSharedMetadataHeaders(f)}request(h,f){if(f)this.requestAsync(h).then((g)=>f(null,g),(g)=>f(g,g.response));else return this.requestAsync(h)}async requestAsync(h,f=!1){let g;try{let y=await this.getRequestHeaders();h.headers=yc.Gaxios.mergeHeaders(h.headers),this.addUserProjectAndAuthHeaders(h.headers,y),g=await this.transporter.request(h)}catch(y){let _=y.response;if(_){let T=_.status,S=_.config.data instanceof Up.Readable;if(!f&&(T===401||T===403)&&!S&&this.forceRefreshOnFailure)return await this.refreshAccessTokenAsync(),await this.requestAsync(h,!0)}throw y}return g}async refreshAccessTokenAsync(){let h=await this.externalAccountAuthorizedUserHandler.refreshToken(this.refreshToken);if(this.cachedAccessToken={access_token:h.access_token,expiry_date:new Date().getTime()+h.expires_in*1000,res:h.res},h.refresh_token!==void 0)this.refreshToken=h.refresh_token;return this.cachedAccessToken}isExpired(h){let f=new Date().getTime();return h.expiry_date?f>=h.expiry_date-this.eagerRefreshThresholdMillis:!1}}Tc.ExternalAccountAuthorizedUserClient=_c});var ms=i(function(wc){Object.defineProperty(wc,"__esModule",{value:!0});wc.GdchClient=wc.GDCH_SERVICE_ACCOUNT_TYPE=void 0;var Lp=c("crypto"),Fp=c("fs"),Gp=c("https"),$p=Ft(),Hp=3600;wc.GDCH_SERVICE_ACCOUNT_TYPE="gdch_service_account";class gs extends $p.OAuth2Client{projectId;privateKeyId;privateKey;serviceIdentityName;tokenServerUri;caCertPath;apiAudience;lifetime;gdchOptions;caAgentPromise;cachedCaCertPath;lastCaCertReadTime=0;CA_CERT_TTL_MS=300000;constructor(h={}){super(h);this.gdchOptions=h,this.projectId=h.projectId||void 0,this.privateKeyId=h.privateKeyId,this.privateKey=h.privateKey,this.serviceIdentityName=h.serviceIdentityName,this.tokenServerUri=h.tokenServerUri,this.caCertPath=h.caCertPath,this.apiAudience=h.apiAudience,this.lifetime=h.lifetime||Hp,this.credentials={refresh_token:"gdch-placeholder",expiry_date:1}}createWithGdchAudience(h){if(!h)throw Error("Audience cannot be null or empty for GDCH service account credentials.");return new gs({...this.gdchOptions,projectId:this.projectId,privateKeyId:this.privateKeyId,privateKey:this.privateKey,serviceIdentityName:this.serviceIdentityName,tokenServerUri:this.tokenServerUri,caCertPath:this.caCertPath,lifetime:this.lifetime,apiAudience:h})}fromJSON(h){if(!h)throw Error("Must pass in a JSON object containing the GDCH credentials settings.");if(h.type!==wc.GDCH_SERVICE_ACCOUNT_TYPE)throw Error(`The incoming JSON object does not have the "${wc.GDCH_SERVICE_ACCOUNT_TYPE}" type`);if(h.format_version!=="1")throw Error("Only format version 1 is supported.");if(!h.project)throw Error("The incoming JSON object does not contain a project field");if(!h.private_key_id)throw Error("The incoming JSON object does not contain a private_key_id field");if(!h.private_key)throw Error("The incoming JSON object does not contain a private_key field");if(!h.name)throw Error("The incoming JSON object does not contain a name field");if(!h.token_uri)throw Error("The incoming JSON object does not contain a token_uri field");this.projectId=h.project,this.privateKeyId=h.private_key_id,this.privateKey=h.private_key,this.serviceIdentityName=h.name,this.tokenServerUri=h.token_uri,this.caCertPath=h.ca_cert_path,this.gdchOptions={...this.gdchOptions,projectId:h.project,privateKeyId:h.private_key_id,privateKey:h.private_key,serviceIdentityName:h.name,tokenServerUri:h.token_uri,caCertPath:h.ca_cert_path}}async refreshTokenNoCache(){if(!this.apiAudience)throw Error("Audience cannot be null or empty for GDCH service account credentials. Specify the audience by calling createWithGdchAudience.");if(!this.privateKey)throw Error("Private key is not configured for GDCH credentials.");if(!this.privateKeyId)throw Error("Private key ID is not configured for GDCH credentials.");if(!this.projectId)throw Error("Project is not configured for GDCH credentials.");if(!this.serviceIdentityName)throw Error("Service identity name is not configured for GDCH credentials.");if(!this.tokenServerUri)throw Error("Token server URI is not configured for GDCH credentials.");let h=this.createAssertion(),f={audience:this.apiAudience,grant_type:"urn:ietf:params:oauth:token-type:token-exchange",requested_token_type:"urn:ietf:params:oauth:token-type:access_token",subject_token:h,subject_token_type:"urn:k8s:params:oauth:token-type:serviceaccount"},g={url:this.tokenServerUri,method:"POST",headers:{"Content-Type":"application/json"},data:f,responseType:"json",timeout:1e4,retry:!0,retryConfig:{httpMethodsToRetry:["POST"],statusCodesToRetry:[[500,599]],noResponseRetries:3}};if(this.caCertPath)g.agent=await this.getCaAgent();try{let y=await this.transporter.request(g),_=y.data;if(!_.access_token)throw Error("Token response did not contain an access_token.");if(!_.expires_in)throw Error("Token response did not contain an expires_in field.");let T={access_token:_.access_token,token_type:"STS-Bearer",expiry_date:Date.now()+_.expires_in*1000};return this.emit("tokens",T),{res:y,tokens:T}}catch(y){if(y&&y.config&&y.config.data)try{if(typeof y.config.data==="string"){let _=JSON.parse(y.config.data);if(_.subject_token)_.subject_token="***REDACTED***",y.config.data=JSON.stringify(_)}else if(typeof y.config.data==="object"&&y.config.data.subject_token)y.config.data.subject_token="***REDACTED***"}catch{}if(y instanceof Error)y.message=`Error getting access token for GDCH service account: ${y.message}, iss: ${this.serviceIdentityName}`;throw y}}createAssertion(){let h={alg:"ES256",typ:"JWT",kid:this.privateKeyId},f=`system:serviceaccount:${this.projectId}:${this.serviceIdentityName}`,g=Math.floor(Date.now()/1000),y={iss:f,sub:f,iat:g,exp:g+this.lifetime,aud:this.tokenServerUri},_=this.base64UrlEncode(JSON.stringify(h)),T=this.base64UrlEncode(JSON.stringify(y)),S=`${_}.${T}`,w=Lp.sign("sha256",Buffer.from(S),{key:this.privateKey,dsaEncoding:"ieee-p1363"}),x=this.base64UrlEncode(w);return`${S}.${x}`}async requestAsync(h,f=!1){if(this.caCertPath&&!h.agent){let g=(h.url||"").toString();if(!g.includes("googleapis.com")&&!g.includes("google.com"))h.agent=await this.getCaAgent()}return super.requestAsync(h,f)}getCaAgent(){if(!this.caCertPath){this.caAgentPromise=void 0,this.cachedCaCertPath=void 0,this.lastCaCertReadTime=0;return}let h=Date.now(),f=h-this.lastCaCertReadTime>this.CA_CERT_TTL_MS;if(this.caAgentPromise&&this.caCertPath===this.cachedCaCertPath&&!f)return this.caAgentPromise;this.cachedCaCertPath=this.caCertPath,this.lastCaCertReadTime=h;let g=this.caCertPath;return this.caAgentPromise=(async()=>{try{let y=await Fp.promises.readFile(g);return new Gp.Agent({ca:y})}catch(y){if(this.cachedCaCertPath===g)this.caAgentPromise=void 0,this.cachedCaCertPath=void 0,this.lastCaCertReadTime=0;if(y instanceof Error)y.message=`Error reading certificate file from CA cert path, value '${g}': ${y.message}`;throw y}})(),this.caAgentPromise}toJSON(){return{...this,privateKey:this.privateKey?"***REDACTED***":void 0,_clientSecret:this._clientSecret?"***REDACTED***":void 0,apiKey:this.apiKey?"***REDACTED***":void 0,gdchOptions:this.gdchOptions?{...this.gdchOptions,privateKey:this.gdchOptions.privateKey?"***REDACTED***":void 0,clientSecret:this.gdchOptions.clientSecret?"***REDACTED***":void 0,client_secret:this.gdchOptions.client_secret?"***REDACTED***":void 0,apiKey:this.gdchOptions.apiKey?"***REDACTED***":void 0,credentials:this.gdchOptions.credentials?{...this.gdchOptions.credentials,access_token:this.gdchOptions.credentials.access_token?"***REDACTED***":void 0,refresh_token:this.gdchOptions.credentials.refresh_token?"***REDACTED***":void 0}:void 0}:void 0,credentials:{...this.credentials,access_token:this.credentials?.access_token?"***REDACTED***":void 0,refresh_token:this.credentials?.refresh_token?"***REDACTED***":void 0}}}[Symbol.for("nodejs.util.inspect.custom")](){return this.toJSON()}base64UrlEncode(h){return(typeof h==="string"?Buffer.from(h):h).toString("base64url")}}wc.GdchClient=gs});var Oc=i(function(kc){Object.defineProperty(kc,"__esModule",{value:!0});kc.GoogleAuth=kc.GoogleAuthExceptionMessages=void 0;var Bp=c("child_process"),wn=c("fs"),Vp=ct(),En=fn(),Wp=c("os"),Kn=c("path"),Kp=gn(),Jp=kr(),Yp=xr(),zp=Or(),sn=Ur(),Ac=Mr(),an=Dr(),Xp=ds(),vn=$t(),ys=wt(),bc=ps(),_s=ms(),Cc=xt();kc.GoogleAuthExceptionMessages={API_KEY_WITH_CREDENTIALS:"API Keys and Credentials are mutually exclusive authentication methods and cannot be used together.",NO_PROJECT_ID_FOUND:`Unable to detect a Project Id in the current environment.
|
|
23
|
+
To learn more about authentication and Google APIs, visit:
|
|
24
|
+
https://cloud.google.com/docs/authentication/getting-started`,NO_CREDENTIALS_FOUND:`Unable to find credentials in current environment.
|
|
25
|
+
To learn more about authentication and Google APIs, visit:
|
|
26
|
+
https://cloud.google.com/docs/authentication/getting-started`,NO_ADC_FOUND:"Could not load the default credentials. Browse to https://cloud.google.com/docs/authentication/getting-started for more information.",NO_UNIVERSE_DOMAIN_FOUND:`Unable to detect a Universe Domain in the current environment.
|
|
27
|
+
To learn more about Universe Domain retrieval, visit:
|
|
28
|
+
https://cloud.google.com/compute/docs/metadata/predefined-metadata-keys`};class Sc{checkIsGCE=void 0;useJWTAccessWithScope;defaultServicePath;get isGCE(){return this.checkIsGCE}_findProjectIdPromise;_cachedProjectId;jsonContent=null;apiKey;cachedCredential=null;#e=null;defaultScopes;keyFilename;scopes;clientOptions={};constructor(h={}){if(this._cachedProjectId=h.projectId||null,this.cachedCredential=h.authClient||null,this.keyFilename=h.keyFilename||h.keyFile,this.scopes=h.scopes,this.clientOptions=h.clientOptions||{},this.jsonContent=h.credentials||null,this.apiKey=h.apiKey||this.clientOptions.apiKey||null,this.apiKey&&(this.jsonContent||this.clientOptions.credentials))throw RangeError(kc.GoogleAuthExceptionMessages.API_KEY_WITH_CREDENTIALS);if(h.universeDomain)this.clientOptions.universeDomain=h.universeDomain}setGapicJWTValues(h){h.defaultServicePath=this.defaultServicePath,h.useJWTAccessWithScope=this.useJWTAccessWithScope,h.defaultScopes=this.defaultScopes}getProjectId(h){if(h)this.getProjectIdAsync().then((f)=>h(null,f),h);else return this.getProjectIdAsync()}async getProjectIdOptional(){try{return await this.getProjectId()}catch(h){if(h instanceof Error&&h.message===kc.GoogleAuthExceptionMessages.NO_PROJECT_ID_FOUND)return null;else throw h}}async findAndCacheProjectId(){let h=null;if(h||=await this.getProductionProjectId(),h||=await this.getFileProjectId(),h||=await this.getDefaultServiceProjectId(),h||=await this.getGCEProjectId(),h||=await this.getExternalAccountClientProjectId(),h)return this._cachedProjectId=h,h;else throw Error(kc.GoogleAuthExceptionMessages.NO_PROJECT_ID_FOUND)}async getProjectIdAsync(){if(this._cachedProjectId)return this._cachedProjectId;if(!this._findProjectIdPromise)this._findProjectIdPromise=this.findAndCacheProjectId();return this._findProjectIdPromise}async getUniverseDomainFromMetadataServer(){let h;try{h=await En.universe("universe-domain"),h||=ys.DEFAULT_UNIVERSE}catch(f){if(f&&f?.response?.status===404)h=ys.DEFAULT_UNIVERSE;else throw f}return h}async getUniverseDomain(){let h=Cc.originalOrCamelOptions(this.clientOptions).get("universe_domain");try{h??=(await this.getClient()).universeDomain}catch{h??=ys.DEFAULT_UNIVERSE}return h}getAnyScopes(){return this.scopes||this.defaultScopes}getApplicationDefault(h={},f){let g;if(typeof h==="function")f=h;else g=h;if(f)this.getApplicationDefaultAsync(g).then((y)=>f(null,y.credential,y.projectId),f);else return this.getApplicationDefaultAsync(g)}async getApplicationDefaultAsync(h={}){if(this.cachedCredential)return await this.#t(this.cachedCredential,null);let f;if(f=await this._tryGetApplicationCredentialsFromEnvironmentVariable(h),f){if(f instanceof sn.JWT)f.scopes=this.scopes;else if(f instanceof vn.BaseExternalAccountClient)f.scopes=this.getAnyScopes();return await this.#t(f)}if(f=await this._tryGetApplicationCredentialsFromWellKnownFile(h),f){if(f instanceof sn.JWT)f.scopes=this.scopes;else if(f instanceof vn.BaseExternalAccountClient)f.scopes=this.getAnyScopes();return await this.#t(f)}if(await this._checkIsGCE())return h.scopes=this.getAnyScopes(),await this.#t(new Jp.Compute(h));throw Error(kc.GoogleAuthExceptionMessages.NO_ADC_FOUND)}async#t(h,f=process.env.GOOGLE_CLOUD_QUOTA_PROJECT||null){let g=await this.getProjectIdOptional();if(f)h.quotaProjectId=f;return this.cachedCredential=h,{credential:h,projectId:g}}async _checkIsGCE(){if(this.checkIsGCE===void 0)this.checkIsGCE=En.getGCPResidency()||await En.isAvailable();return this.checkIsGCE}async _tryGetApplicationCredentialsFromEnvironmentVariable(h){let f=process.env.GOOGLE_APPLICATION_CREDENTIALS||process.env.google_application_credentials;if(!f||f.length===0)return null;try{return await this._getApplicationCredentialsFromFilePath(f,h)}catch(g){if(g instanceof Error)g.message=`Unable to read the credential file specified by the GOOGLE_APPLICATION_CREDENTIALS environment variable: ${g.message}`;throw g}}async _tryGetApplicationCredentialsFromWellKnownFile(h){let f=process.env.CLOUDSDK_CONFIG;if(!f)if(this._isWindows()){if(process.env.APPDATA)f=Kn.join(process.env.APPDATA,"gcloud")}else{let _=process.env.HOME;if(_)f=Kn.join(_,".config","gcloud")}if(!f)return null;let g=Kn.join(f,"application_default_credentials.json");if(!wn.existsSync(g))return null;return await this._getApplicationCredentialsFromFilePath(g,h)}async _getApplicationCredentialsFromFilePath(h,f={}){if(!h||h.length===0)throw Error("The file path is invalid.");try{if(h=wn.realpathSync(h),!wn.lstatSync(h).isFile())throw Error()}catch(y){if(y instanceof Error)y.message=`The file at ${h} does not exist, or it is not a file. ${y.message}`;throw y}let g=wn.createReadStream(h);return this.fromStream(g,f)}fromImpersonatedJSON(h){if(!h)throw Error("Must pass in a JSON object containing an impersonated refresh token");if(h.type!==an.IMPERSONATED_ACCOUNT_TYPE)throw Error(`The incoming JSON object does not have the "${an.IMPERSONATED_ACCOUNT_TYPE}" type`);if(!h.source_credentials)throw Error("The incoming JSON object does not contain a source_credentials field");if(!h.service_account_impersonation_url)throw Error("The incoming JSON object does not contain a service_account_impersonation_url field");let f=this.fromJSON(h.source_credentials);if(h.service_account_impersonation_url?.length>256)throw RangeError(`Target principal is too long: ${h.service_account_impersonation_url}`);let g=/(?<target>[^/]+):(generateAccessToken|generateIdToken)$/.exec(h.service_account_impersonation_url)?.groups?.target;if(!g)throw RangeError(`Cannot extract target principal from ${h.service_account_impersonation_url}`);let y=(this.scopes||h.scopes||this.defaultScopes)??[];return new an.Impersonated({...h,sourceClient:f,targetPrincipal:g,targetScopes:Array.isArray(y)?y:[y]})}fromJSON(h,f={}){let g,y=Cc.originalOrCamelOptions(f).get("universe_domain");if(h.type===Ac.USER_REFRESH_ACCOUNT_TYPE)g=new Ac.UserRefreshClient(f),g.fromJSON(h);else if(h.type===an.IMPERSONATED_ACCOUNT_TYPE)g=this.fromImpersonatedJSON(h);else if(h.type===vn.EXTERNAL_ACCOUNT_TYPE)g=Xp.ExternalAccountClient.fromJSON({...h,...f}),g.scopes=this.getAnyScopes();else if(h.type===bc.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE)g=new bc.ExternalAccountAuthorizedUserClient({...h,...f});else if(h.type===_s.GDCH_SERVICE_ACCOUNT_TYPE)g=new _s.GdchClient(f),g.fromJSON(h);else f.scopes=this.scopes,g=new sn.JWT(f),this.setGapicJWTValues(g),g.fromJSON(h);if(y)g.universeDomain=y;return g}_cacheClientFromJSON(h,f){let g=this.fromJSON(h,f);return this.jsonContent=h,this.cachedCredential=g,g}fromStream(h,f={},g){let y={};if(typeof f==="function")g=f;else y=f;if(g)this.fromStreamAsync(h,y).then((_)=>g(null,_),g);else return this.fromStreamAsync(h,y)}fromStreamAsync(h,f){return new Promise((g,y)=>{if(!h)throw Error("Must pass in a stream containing the Google auth settings.");let _=[];h.setEncoding("utf8").on("error",y).on("data",(T)=>_.push(T)).on("end",()=>{try{try{let T=JSON.parse(_.join("")),S=this._cacheClientFromJSON(T,f);return g(S)}catch(T){if(!this.keyFilename)throw T;let S=new sn.JWT({...this.clientOptions,keyFile:this.keyFilename});return this.cachedCredential=S,this.setGapicJWTValues(S),g(S)}}catch(T){return y(T)}})})}fromAPIKey(h,f={}){return new sn.JWT({...f,apiKey:h})}_isWindows(){let h=Wp.platform();if(h&&h.length>=3){if(h.substring(0,3).toLowerCase()==="win")return!0}return!1}async getDefaultServiceProjectId(){return new Promise((h)=>{Bp.exec("gcloud config config-helper --format json",(f,g)=>{if(!f&&g)try{let y=JSON.parse(g).configuration.properties.core.project;h(y);return}catch(y){}h(null)})})}getProductionProjectId(){return process.env.GCLOUD_PROJECT||process.env.GOOGLE_CLOUD_PROJECT||process.env.gcloud_project||process.env.google_cloud_project}async getFileProjectId(){if(this.cachedCredential)return this.cachedCredential.projectId;if(this.keyFilename){let f=await this.getClient();if(f&&f.projectId)return f.projectId}let h=await this._tryGetApplicationCredentialsFromEnvironmentVariable();if(h)return h.projectId;else return null}async getExternalAccountClientProjectId(){if(!this.jsonContent||this.jsonContent.type!==vn.EXTERNAL_ACCOUNT_TYPE)return null;return await(await this.getClient()).getProjectId()}async getGCEProjectId(){try{return await En.project("project-id")}catch(h){return null}}getCredentials(h){if(h)this.getCredentialsAsync().then((f)=>h(null,f),h);else return this.getCredentialsAsync()}async getCredentialsAsync(){let h=await this.getClient();if(h instanceof an.Impersonated)return{client_email:h.getTargetPrincipal()};if(h instanceof vn.BaseExternalAccountClient){let f=h.getServiceAccountEmail();if(f)return{client_email:f,universe_domain:h.universeDomain}}if(this.jsonContent)return{client_email:this.jsonContent.client_email,private_key:this.jsonContent.private_key,universe_domain:this.jsonContent.universe_domain};if(await this._checkIsGCE()){let[f,g]=await Promise.all([En.instance("service-accounts/default/email"),this.getUniverseDomain()]);return{client_email:f,universe_domain:g}}throw Error(kc.GoogleAuthExceptionMessages.NO_CREDENTIALS_FOUND)}async getClient(){if(this.cachedCredential)return this.cachedCredential;this.#e=this.#e||this.#n();try{let h=await this.#e;if(h instanceof _s.GdchClient&&!h.apiAudience){let f=this.clientOptions,g=f.apiEndpoint||f.servicePath;if(g){let _=`${g.startsWith("http")?"":"https://"}${g}`.replace(/\/+$/,""),T=h.createWithGdchAudience(_);return this.cachedCredential=T,T}}return h}finally{this.#e=null}}async#n(){if(this.jsonContent)return this._cacheClientFromJSON(this.jsonContent,this.clientOptions);else if(this.keyFilename){let h=Kn.resolve(this.keyFilename),f=wn.createReadStream(h);return await this.fromStreamAsync(f,this.clientOptions)}else if(this.apiKey){let h=await this.fromAPIKey(this.apiKey,this.clientOptions);h.scopes=this.scopes;let{credential:f}=await this.#t(h);return f}else{let{credential:h}=await this.getApplicationDefaultAsync(this.clientOptions);return h}}async getIdTokenClient(h){let f=await this.getClient();if(!("fetchIdToken"in f))throw Error("Cannot fetch ID token in this environment, use GCE or set the GOOGLE_APPLICATION_CREDENTIALS environment variable to a service account credentials JSON file.");return new Yp.IdTokenClient({targetAudience:h,idTokenProvider:f})}async getAccessToken(){return(await(await this.getClient()).getAccessToken()).token}async getRequestHeaders(h){return(await this.getClient()).getRequestHeaders(h)}async authorizeRequest(h={}){let f=h.url,y=await(await this.getClient()).getRequestHeaders(f);return h.headers=Vp.Gaxios.mergeHeaders(h.headers,y),h}async fetch(...h){return(await this.getClient()).fetch(...h)}async request(h){return(await this.getClient()).request(h)}getEnv(){return zp.getEnv()}async sign(h,f){let g=await this.getClient(),y=await this.getUniverseDomain();if(f=f||`https://iamcredentials.${y}/v1/projects/-/serviceAccounts/`,g instanceof an.Impersonated)return(await g.sign(h)).signedBlob;let _=Kp.createCrypto();if(g instanceof sn.JWT&&g.key)return await _.sign(g.key,h);let T=await this.getCredentials();if(!T.client_email)throw Error("Cannot sign data without `client_email`.");return this.signBlob(_,T.client_email,h,f)}async signBlob(h,f,g,y){let _=new URL(y+`${f}:signBlob`);return(await this.request({method:"POST",url:_.href,data:{payload:h.encodeBase64StringUtf8(g)},retry:!0,retryConfig:{httpMethodsToRetry:["POST"]}})).data.signedBlob}}kc.GoogleAuth=Sc});var Pc=i(function(Ic){Object.defineProperty(Ic,"__esModule",{value:!0});Ic.IAMAuth=void 0;class Rc{selector;token;constructor(h,f){this.selector=h,this.token=f,this.selector=h,this.token=f}getRequestHeaders(){return{"x-goog-iam-authority-selector":this.selector,"x-goog-iam-authorization-token":this.token}}}Ic.IAMAuth=Rc});var Dc=i(function(Uc){Object.defineProperty(Uc,"__esModule",{value:!0});Uc.DownscopedClient=Uc.EXPIRATION_TIME_OFFSET=Uc.MAX_ACCESS_BOUNDARY_RULES_COUNT=void 0;var Qp=ct(),Zp=c("stream"),Ts=wt(),ef=Mn(),tf="urn:ietf:params:oauth:grant-type:token-exchange",nf="urn:ietf:params:oauth:token-type:access_token",rf="urn:ietf:params:oauth:token-type:access_token";Uc.MAX_ACCESS_BOUNDARY_RULES_COUNT=10;Uc.EXPIRATION_TIME_OFFSET=300000;class jc extends Ts.AuthClient{authClient;credentialAccessBoundary;cachedDownscopedAccessToken;stsCredential;constructor(h,f={accessBoundary:{accessBoundaryRules:[]}}){super(h instanceof Ts.AuthClient?{}:h);if(h instanceof Ts.AuthClient)this.authClient=h,this.credentialAccessBoundary=f;else this.authClient=h.authClient,this.credentialAccessBoundary=h.credentialAccessBoundary;if(this.credentialAccessBoundary.accessBoundary.accessBoundaryRules.length===0)throw Error("At least one access boundary rule needs to be defined.");else if(this.credentialAccessBoundary.accessBoundary.accessBoundaryRules.length>Uc.MAX_ACCESS_BOUNDARY_RULES_COUNT)throw Error(`The provided access boundary has more than ${Uc.MAX_ACCESS_BOUNDARY_RULES_COUNT} access boundary rules.`);for(let g of this.credentialAccessBoundary.accessBoundary.accessBoundaryRules)if(g.availablePermissions.length===0)throw Error("At least one permission should be defined in access boundary rules.");this.stsCredential=new ef.StsCredentials({tokenExchangeEndpoint:`https://sts.${this.universeDomain}/v1/token`}),this.cachedDownscopedAccessToken=null}setCredentials(h){if(!h.expiry_date)throw Error("The access token expiry_date field is missing in the provided credentials.");super.setCredentials(h),this.cachedDownscopedAccessToken=h}async getAccessToken(){if(!this.cachedDownscopedAccessToken||this.isExpired(this.cachedDownscopedAccessToken))await this.refreshAccessTokenAsync();return{token:this.cachedDownscopedAccessToken.access_token,expirationTime:this.cachedDownscopedAccessToken.expiry_date,res:this.cachedDownscopedAccessToken.res}}async getRequestHeaders(){let h=await this.getAccessToken(),f=new Headers({authorization:`Bearer ${h.token}`});return this.addSharedMetadataHeaders(f)}request(h,f){if(f)this.requestAsync(h).then((g)=>f(null,g),(g)=>f(g,g.response));else return this.requestAsync(h)}async requestAsync(h,f=!1){let g;try{let y=await this.getRequestHeaders();h.headers=Qp.Gaxios.mergeHeaders(h.headers),this.addUserProjectAndAuthHeaders(h.headers,y),g=await this.transporter.request(h)}catch(y){let _=y.response;if(_){let T=_.status,S=_.config.data instanceof Zp.Readable;if(!f&&(T===401||T===403)&&!S&&this.forceRefreshOnFailure)return await this.refreshAccessTokenAsync(),await this.requestAsync(h,!0)}throw y}return g}async refreshAccessTokenAsync(){let h=(await this.authClient.getAccessToken()).token,f={grantType:tf,requestedTokenType:nf,subjectToken:h,subjectTokenType:rf},g=await this.stsCredential.exchangeToken(f,void 0,this.credentialAccessBoundary),y=this.authClient.credentials?.expiry_date||null,_=g.expires_in?new Date().getTime()+g.expires_in*1000:y;return this.cachedDownscopedAccessToken={access_token:g.access_token,expiry_date:_,res:g.res},this.credentials={},Object.assign(this.credentials,this.cachedDownscopedAccessToken),delete this.credentials.res,this.emit("tokens",{refresh_token:null,expiry_date:this.cachedDownscopedAccessToken.expiry_date,access_token:this.cachedDownscopedAccessToken.access_token,token_type:"Bearer",id_token:null}),this.cachedDownscopedAccessToken}isExpired(h){let f=new Date().getTime();return h.expiry_date?f>=h.expiry_date-this.eagerRefreshThresholdMillis:!1}}Uc.DownscopedClient=jc});var Gc=i(function(Lc){Object.defineProperty(Lc,"__esModule",{value:!0});Lc.PassThroughClient=void 0;var of=wt();class qc extends of.AuthClient{async request(h){return this.transporter.request(h)}async getAccessToken(){return{}}async getRequestHeaders(){return new Headers}}Lc.PassThroughClient=qc});var Es=i(function(we){var af=we&&we.__createBinding||(Object.create?function(h,f,g,y){if(y===void 0)y=g;var _=Object.getOwnPropertyDescriptor(f,g);if(!_||("get"in _?!f.__esModule:_.writable||_.configurable))_={enumerable:!0,get:function(){return f[g]}};Object.defineProperty(h,y,_)}:function(h,f,g,y){if(y===void 0)y=g;h[y]=f[g]}),cf=we&&we.__exportStar||function(h,f){for(var g in h)if(g!=="default"&&!Object.prototype.hasOwnProperty.call(f,g))af(f,h,g)};Object.defineProperty(we,"__esModule",{value:!0});we.GoogleAuth=we.auth=we.GDCH_SERVICE_ACCOUNT_TYPE=we.GdchClient=we.PassThroughClient=we.ExternalAccountAuthorizedUserClient=we.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE=we.ExecutableError=we.PluggableAuthClient=we.DownscopedClient=we.BaseExternalAccountClient=we.ExternalAccountClient=we.IdentityPoolClient=we.AwsRequestSigner=we.AwsClient=we.UserRefreshClient=we.LoginTicket=we.ClientAuthentication=we.OAuth2Client=we.CodeChallengeMethod=we.Impersonated=we.JWT=we.JWTAccess=we.IdTokenClient=we.IAMAuth=we.GCPEnv=we.Compute=we.DEFAULT_UNIVERSE=we.AuthClient=we.gaxios=we.gcpMetadata=void 0;var $c=Oc();Object.defineProperty(we,"GoogleAuth",{enumerable:!0,get:function(){return $c.GoogleAuth}});we.gcpMetadata=fn();we.gaxios=ct();var Hc=wt();Object.defineProperty(we,"AuthClient",{enumerable:!0,get:function(){return Hc.AuthClient}});Object.defineProperty(we,"DEFAULT_UNIVERSE",{enumerable:!0,get:function(){return Hc.DEFAULT_UNIVERSE}});var lf=kr();Object.defineProperty(we,"Compute",{enumerable:!0,get:function(){return lf.Compute}});var uf=Or();Object.defineProperty(we,"GCPEnv",{enumerable:!0,get:function(){return uf.GCPEnv}});var df=Pc();Object.defineProperty(we,"IAMAuth",{enumerable:!0,get:function(){return df.IAMAuth}});var hf=xr();Object.defineProperty(we,"IdTokenClient",{enumerable:!0,get:function(){return hf.IdTokenClient}});var pf=Pr();Object.defineProperty(we,"JWTAccess",{enumerable:!0,get:function(){return pf.JWTAccess}});var ff=Ur();Object.defineProperty(we,"JWT",{enumerable:!0,get:function(){return ff.JWT}});var gf=Dr();Object.defineProperty(we,"Impersonated",{enumerable:!0,get:function(){return gf.Impersonated}});var ws=Ft();Object.defineProperty(we,"CodeChallengeMethod",{enumerable:!0,get:function(){return ws.CodeChallengeMethod}});Object.defineProperty(we,"OAuth2Client",{enumerable:!0,get:function(){return ws.OAuth2Client}});Object.defineProperty(we,"ClientAuthentication",{enumerable:!0,get:function(){return ws.ClientAuthentication}});var mf=br();Object.defineProperty(we,"LoginTicket",{enumerable:!0,get:function(){return mf.LoginTicket}});var yf=Mr();Object.defineProperty(we,"UserRefreshClient",{enumerable:!0,get:function(){return yf.UserRefreshClient}});var _f=zr();Object.defineProperty(we,"AwsClient",{enumerable:!0,get:function(){return _f.AwsClient}});var Tf=Yr();Object.defineProperty(we,"AwsRequestSigner",{enumerable:!0,get:function(){return Tf.AwsRequestSigner}});var vf=Jr();Object.defineProperty(we,"IdentityPoolClient",{enumerable:!0,get:function(){return vf.IdentityPoolClient}});var wf=ds();Object.defineProperty(we,"ExternalAccountClient",{enumerable:!0,get:function(){return wf.ExternalAccountClient}});var Ef=$t();Object.defineProperty(we,"BaseExternalAccountClient",{enumerable:!0,get:function(){return Ef.BaseExternalAccountClient}});var Cf=Dc();Object.defineProperty(we,"DownscopedClient",{enumerable:!0,get:function(){return Cf.DownscopedClient}});var Bc=us();Object.defineProperty(we,"PluggableAuthClient",{enumerable:!0,get:function(){return Bc.PluggableAuthClient}});Object.defineProperty(we,"ExecutableError",{enumerable:!0,get:function(){return Bc.ExecutableError}});var Vc=ps();Object.defineProperty(we,"EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE",{enumerable:!0,get:function(){return Vc.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE}});Object.defineProperty(we,"ExternalAccountAuthorizedUserClient",{enumerable:!0,get:function(){return Vc.ExternalAccountAuthorizedUserClient}});var Af=Gc();Object.defineProperty(we,"PassThroughClient",{enumerable:!0,get:function(){return Af.PassThroughClient}});var Wc=ms();Object.defineProperty(we,"GdchClient",{enumerable:!0,get:function(){return Wc.GdchClient}});Object.defineProperty(we,"GDCH_SERVICE_ACCOUNT_TYPE",{enumerable:!0,get:function(){return Wc.GDCH_SERVICE_ACCOUNT_TYPE}});cf(Ir(),we);var bf=new $c.GoogleAuth;we.auth=bf});var Vl=v(Es(),1);function Sf({stream:h,getContinuationToken:f,continueStream:g}){let y=h.getReader(),_;return new ReadableStream({async pull(T){while(!0){let{done:S,value:w}=await y.read();if(!S){if(w.success){let B=f(w.value);if(B!=null)_=B}T.enqueue(w);return}if(_==null){T.close();return}let x=_;_=void 0;try{y=(await g(x)).getReader(),T.enqueue({type:"continuation-start"});return}catch(B){T.enqueue({success:!1,error:B,rawValue:void 0}),T.close();return}}},async cancel(T){await y.cancel(T)}})}function Kc(h){if(h==null)return Ct();let f=h.promptTokenCount??0,g=h.candidatesTokenCount??0,y=h.toolUsePromptTokenCount??0,_=h.cachedContentTokenCount??0,T=h.thoughtsTokenCount??0,S=f+y;return{inputTokens:{total:S,noCache:S-_,cacheRead:_,cacheWrite:void 0},outputTokens:{total:g+T,text:g,reasoning:T},raw:h}}function Cs(h,f){if(h==null||f==null)return f??h;return{...h,...f,promptTokenCount:cn(h.promptTokenCount,f.promptTokenCount),candidatesTokenCount:cn(h.candidatesTokenCount,f.candidatesTokenCount),toolUsePromptTokenCount:cn(h.toolUsePromptTokenCount,f.toolUsePromptTokenCount),totalTokenCount:cn(h.totalTokenCount,f.totalTokenCount),cachedContentTokenCount:cn(h.cachedContentTokenCount,f.cachedContentTokenCount),thoughtsTokenCount:cn(h.thoughtsTokenCount,f.thoughtsTokenCount),promptTokensDetails:Jn(h.promptTokensDetails,f.promptTokensDetails),cacheTokensDetails:Jn(h.cacheTokensDetails,f.cacheTokensDetails),candidatesTokensDetails:Jn(h.candidatesTokensDetails,f.candidatesTokensDetails),toolUsePromptTokensDetails:Jn(h.toolUsePromptTokensDetails,f.toolUsePromptTokensDetails)}}function cn(h,f){return h==null&&f==null?f??h:(h??0)+(f??0)}function Jn(h,f){if(h==null||f==null)return f??h;let g=new Map;for(let{modality:y,tokenCount:_}of[...h,...f])g.set(y,(g.get(y)??0)+_);return Array.from(g,([y,_])=>({modality:y,tokenCount:_}))}var ul=t({language:e().describe("The programming language of the code."),code:e().describe("The code to be executed.")}),dl=t({outcome:e().describe('The outcome of the execution (e.g., "OUTCOME_OK").'),output:e().describe("The output from the code execution.")}),kf=G({id:"google.code_execution",inputSchema:ul,outputSchema:dl}),xf="skip_thought_signature_validator",Of=/^data:([^;,]+);base64,(.+)$/s;function Rf(h){let f=Of.exec(h);if(f==null)return;return{mediaType:f[1],data:f[2]}}function If(h){let f=Rf(h);if(f==null)return;return{inlineData:{mimeType:f.mediaType,data:f.data}}}function bs(h){if(Array.isArray(h))return h.some(bs);if(typeof h!=="object"||h===null)return!1;return Object.entries(h).some(([f,g])=>f==="$ref"||bs(g))}function Jc(h){return bs(h)?JSON.stringify(h):h}function Nf(h,f,g,y,_=!0,T={}){let S=[],w=[];for(let x of g)switch(x.type){case"text":w.push(x.text);break;case"file":if(x.data.type==="data")S.push({inlineData:{mimeType:ee({part:x}),data:j(x.data.data)}});else if(x.data.type==="url"){let B=x.data.url.toString(),P=If(B),ne=x.data.url.protocol==="gs:"&&x.data.originalUrl!=null?x.data.originalUrl:B;if(P!=null)S.push(P);else if(Ae(x.mediaType)&&Wr({url:ne,mediaType:x.mediaType,supportedUrls:T}))S.push({fileData:{mimeType:x.mediaType,fileUri:ne}});else w.push(JSON.stringify(x))}else w.push(JSON.stringify(x));break;default:w.push(JSON.stringify(x))}h.push({functionResponse:{..._&&y!=null?{id:y}:{},name:f,response:{name:f,content:w.length>0?w.join(`
|
|
29
|
+
`):"Tool executed successfully."},...S.length>0?{parts:S}:{}}})}function Pf(h,f,g,y,_=!0){for(let T of g)switch(T.type){case"text":h.push({functionResponse:{..._&&y!=null?{id:y}:{},name:f,response:{name:f,content:T.text}}});break;case"file":if(T.data.type==="data"){let S=ge(T.mediaType);h.push({inlineData:{mimeType:ee({part:T}),data:j(T.data.data)}},{text:`Tool executed successfully and returned this ${S==="image"?"image":"file"} as a response`})}else h.push({text:JSON.stringify(T)});break;default:h.push({text:JSON.stringify(T)})}}function jf(h,f){let g=[],y=[],_=!0,T=f?.isGemmaModel??!1,S=f?.isGemini3Model??!1,w=f?.onWarning,x=f?.providerOptionsNames??["google"],B=!x.includes("google"),P=f?.supportsFunctionResponseParts??!0,ne=f?.includeFunctionCallIds??!0,se=f?.supportedFunctionResponseUrls??{},X=!1,z=[],Z=(M)=>(z.push(M),X=!0,xf),ue=(M)=>{for(let L of x){let he=M.providerOptions?.[L];if(he!=null)return he}if(B)return M.providerOptions?.google;return M.providerOptions?.googleVertex??M.providerOptions?.vertex};for(let{role:M,content:L}of h)switch(M){case"system":if(!_)throw new b({functionality:"system messages are only supported at the beginning of the conversation"});g.push({text:L});break;case"user":{_=!1;let he=[];for(let q of L)switch(q.type){case"text":he.push({text:q.text});break;case"file":switch(q.data.type){case"url":he.push({fileData:{mimeType:ee({part:q}),fileUri:q.data.url.protocol==="gs:"&&q.data.originalUrl!=null?q.data.originalUrl:q.data.url.toString()}});break;case"reference":if(B)throw new b({functionality:"file parts with provider references"});he.push({fileData:{mimeType:ee({part:q}),fileUri:$e({reference:q.data.reference,provider:"google"})}});break;case"text":he.push({inlineData:{mimeType:Ae(q.mediaType)?q.mediaType:"text/plain",data:j(new TextEncoder().encode(q.data.text))}});break;case"data":he.push({inlineData:{mimeType:ee({part:q}),data:j(q.data.data)}})}}y.push({role:"user",parts:he});break}case"assistant":{_=!1;let he=!1;y.push({role:"model",parts:L.map((q)=>{let U=ue(q),de=U?.thoughtSignature!=null?String(U.thoughtSignature):void 0;switch(q.type){case"text":return q.text.length===0?void 0:{text:q.text,thoughtSignature:de};case"reasoning":return q.text.length===0?void 0:{text:q.text,thought:!0,thoughtSignature:de};case"reasoning-file":switch(q.data.type){case"url":throw new b({functionality:"File data URLs in assistant messages are not supported"});case"data":return{inlineData:{mimeType:q.mediaType,data:j(q.data.data)},thought:!0,thoughtSignature:de}}break;case"file":switch(q.data.type){case"url":throw new b({functionality:"File data URLs in assistant messages are not supported"});case"reference":if(B)throw new b({functionality:"file parts with provider references"});return{fileData:{mimeType:q.mediaType,fileUri:$e({reference:q.data.reference,provider:"google"})},...U?.thought===!0?{thought:!0}:{},thoughtSignature:de};case"text":return{inlineData:{mimeType:Ae(q.mediaType)?q.mediaType:"text/plain",data:j(new TextEncoder().encode(q.data.text))},...U?.thought===!0?{thought:!0}:{},thoughtSignature:de};case"data":return{inlineData:{mimeType:q.mediaType,data:j(q.data.data)},...U?.thought===!0?{thought:!0}:{},thoughtSignature:de}}break;case"tool-call":{if(q.providerExecuted===!0&&q.toolName==="code_execution")return{executableCode:ul.parse(typeof q.input==="string"?Ke(q.input):q.input)};let ye=U?.serverToolCallId!=null?String(U.serverToolCallId):void 0,Ce=U?.serverToolType!=null?String(U.serverToolType):void 0,_e=ye!=null&&Ce!=null,Pe=de??(S&&!(!_e&&de==null&&he)?Z(q.toolName):void 0);if(!_e&&de!=null)he=!0;if(_e)return{toolCall:{toolType:Ce,args:typeof q.input==="string"?Ke(q.input):q.input,id:ye},thoughtSignature:Pe};return{functionCall:{...ne&&q.toolCallId!=null?{id:q.toolCallId}:{},name:q.toolName,args:q.input},thoughtSignature:Pe}}case"tool-result":{if(q.toolName==="code_execution"&&q.output.type==="json")return{codeExecutionResult:dl.parse(q.output.value)};let ye=U?.serverToolCallId!=null?String(U.serverToolCallId):void 0,Ce=U?.serverToolType!=null?String(U.serverToolType):void 0;if(ye&&Ce)return{toolResponse:{toolType:Ce,response:q.output.type==="json"?q.output.value:{},id:ye},thoughtSignature:de};return}}}).filter((q)=>q!==void 0)});break}case"tool":{_=!1;let he=[];for(let q of L){if(q.type==="tool-approval-response")continue;let U=ue(q),de=U?.serverToolCallId!=null?String(U.serverToolCallId):void 0,ye=U?.serverToolType!=null?String(U.serverToolType):void 0;if(de&&ye){let _e=U?.thoughtSignature!=null?String(U.thoughtSignature):void 0;if(y.length>0){let Pe=y[y.length-1];if(Pe.role==="model"){Pe.parts.push({toolResponse:{toolType:ye,response:q.output.type==="json"?q.output.value:{},id:de},thoughtSignature:_e});continue}}}let Ce=q.output;if(Ce.type==="content")if(P)Nf(he,q.toolName,Ce.value,q.toolCallId,ne,se);else Pf(he,q.toolName,Ce.value,q.toolCallId,ne);else{let _e=Ce.type==="error-text"||Ce.type==="error-json"||Ce.type==="execution-denied";he.push({functionResponse:{...ne&&q.toolCallId!=null?{id:q.toolCallId}:{},name:q.toolName,response:{name:q.toolName,..._e?{error:Ce.type==="execution-denied"?Ce.reason??"Tool call execution denied.":Jc(Ce.value)}:{content:Jc(Ce.value)}}}})}}y.push({role:"user",parts:he});break}}if(T&&g.length>0&&y.length>0&&y[0].role==="user"){let M=g.map((L)=>L.text).join(`
|
|
30
|
+
|
|
31
|
+
`);y[0].parts.unshift({text:M+`
|
|
32
|
+
|
|
33
|
+
`})}if(X&&w!=null){let M=Array.from(new Set(z));w({type:"other",message:`Replayed ${z.length} \`functionCall\` part(s) for a Gemini 3 model without a \`thoughtSignature\` (tools: ${M.map((L)=>`\`${L}\``).join(", ")}). Injected the documented \`skip_thought_signature_validator\` sentinel to keep the request from failing with HTTP 400. The likely cause is application code that drops \`providerOptions.google.thoughtSignature\` when persisting or serializing assistant tool-call messages. See https://ai.google.dev/gemini-api/docs/thought-signatures.`})}return{systemInstruction:g.length>0&&!T?{parts:g}:void 0,contents:y}}async function Uf(h,{abortSignal:f,maxBytes:g,supportedUrls:y={}}){let _=[];for(let T of h){if(T.role==="assistant"){let S=[];for(let w of T.content)S.push(w.type==="tool-result"?{...w,output:await Yc(w.output,{abortSignal:f,maxBytes:g,supportedUrls:y})}:w);_.push({...T,content:S});continue}if(T.role==="tool"){let S=[];for(let w of T.content){if(w.type!=="tool-result"){S.push(w);continue}S.push({...w,output:await Yc(w.output,{abortSignal:f,maxBytes:g,supportedUrls:y})})}_.push({...T,content:S});continue}_.push(T)}return _}async function Yc(h,{abortSignal:f,maxBytes:g,supportedUrls:y}){if(h.type!=="content")return h;let _=[];for(let T of h.value){if(T.type!=="file"||T.data.type!=="url"){_.push(T);continue}if(Wr({url:T.data.url.toString(),mediaType:T.mediaType,supportedUrls:y})){_.push(T);continue}let S=await Ao(T.data.url.toString(),{abortSignal:f,maxBytes:g}),w=new Uint8Array(await S.arrayBuffer()),x=it({data:w,topLevelType:"image"});_.push({...T,data:{type:"data",data:w},mediaType:x??(S.type&&!Ae(T.mediaType)?S.type:T.mediaType)})}return{...h,value:_}}function zc(h){return h.includes("/")?h:`models/${h}`}var hl=()=>t({code:n().nullable(),message:e(),status:e(),details:o(m()).nullish()}),Mf=u(()=>l(t({error:hl()}))),Bt=oe({errorSchema:Mf,errorToMessage:(h)=>h.error.message});function pl(h){let{const:f,properties:g,items:y,additionalProperties:_,anyOf:T,oneOf:S,...w}=h;return{...w,...f!==void 0?{enum:[f]}:{},...g!=null?{properties:Xc(g)}:{},...y!=null?{items:Array.isArray(y)?y.map(ln):ln(y)}:{},..._!=null?{additionalProperties:typeof _==="boolean"?_:ln(_)}:{},...T!=null?{anyOf:T.map(ln)}:{},...S!=null?{oneOf:S.map(ln)}:{},...w.$defs!=null?{$defs:Xc(w.$defs)}:{}}}function Xc(h){return Object.fromEntries(Object.entries(h).map(([f,g])=>[f,ln(g)]))}function ln(h){return typeof h==="boolean"?h:pl(h)}var Qc=u(()=>l(t({responseModalities:o(s(["TEXT","IMAGE","AUDIO"])).optional(),thinkingConfig:t({thinkingBudget:n().optional(),includeThoughts:r().optional(),thinkingLevel:s(["minimal","low","medium","high"]).optional()}).optional(),cachedContent:e().optional(),structuredOutputs:r().optional(),safetySettings:o(t({category:s(["HARM_CATEGORY_UNSPECIFIED","HARM_CATEGORY_HATE_SPEECH","HARM_CATEGORY_DANGEROUS_CONTENT","HARM_CATEGORY_HARASSMENT","HARM_CATEGORY_SEXUALLY_EXPLICIT","HARM_CATEGORY_CIVIC_INTEGRITY"]),threshold:s(["HARM_BLOCK_THRESHOLD_UNSPECIFIED","BLOCK_LOW_AND_ABOVE","BLOCK_MEDIUM_AND_ABOVE","BLOCK_ONLY_HIGH","BLOCK_NONE","OFF"])})).optional(),threshold:s(["HARM_BLOCK_THRESHOLD_UNSPECIFIED","BLOCK_LOW_AND_ABOVE","BLOCK_MEDIUM_AND_ABOVE","BLOCK_ONLY_HIGH","BLOCK_NONE","OFF"]).optional(),audioTimestamp:r().optional(),labels:d(e(),e()).optional(),mediaResolution:s(["MEDIA_RESOLUTION_UNSPECIFIED","MEDIA_RESOLUTION_LOW","MEDIA_RESOLUTION_MEDIUM","MEDIA_RESOLUTION_HIGH"]).optional(),imageConfig:t({aspectRatio:s(["1:1","2:3","3:2","3:4","4:3","4:5","5:4","9:16","16:9","21:9","1:8","8:1","1:4","4:1"]).optional(),imageSize:s(["1K","2K","4K","512"]).optional(),personGeneration:s(["PERSON_GENERATION_UNSPECIFIED","ALLOW_ALL","ALLOW_ADULT","ALLOW_NONE"]).optional(),prominentPeople:s(["PROMINENT_PEOPLE_UNSPECIFIED","ALLOW_PROMINENT_PEOPLE","BLOCK_PROMINENT_PEOPLE"]).optional(),imageOutputOptions:t({mimeType:s(["image/jpeg","image/png"]).optional(),compressionQuality:n().optional()}).optional()}).optional(),retrievalConfig:t({latLng:t({latitude:n(),longitude:n()}).optional()}).optional(),streamFunctionCallArguments:r().optional(),serviceTier:s(["standard","flex","priority"]).optional(),continuationToken:e().optional(),sharedRequestType:s(["priority","flex","standard"]).optional(),requestType:s(["shared"]).optional()}))),Df=/(^|[/.])gemini-1(?:[.-]|$)/i,qf=/(^|[/.])gemini-2(?:[.-]|$)/i,Lf=/(^|[/.])gemini-2\.5(?:[.-]|$)/i,Ff=/(^|[/.])gemini-/i;function Gf(h){return Df.test(h)||/(^|[/.])gemini-pro(?:-vision)?$/i.test(h)||/(^|[/.])gemini-robotics-er-1\.5(?:[.-]|$)/i.test(h)}function Zn(h){let f=Ff.test(h),g=qf.test(h),y=Gf(h),_=f&&!(y||g);return{supportsGemini2Tools:f&&!y||h.toLowerCase().includes("nano-banana"),supportsFileSearch:Lf.test(h)||_,usesGemini3Features:_}}function $f({tools:h,toolChoice:f,modelId:g,isVertexProvider:y=!1}){h=h?.length?h:void 0;let _=[],{supportsGemini2Tools:T,supportsFileSearch:S,usesGemini3Features:w}=Zn(g);if(h==null)return{tools:void 0,toolConfig:void 0,toolWarnings:_};let x=h.some((X)=>X.type==="function"),B=h.some((X)=>X.type==="provider");if(x&&B&&!w)_.push({type:"unsupported",feature:"combination of function and provider-defined tools"});if(B){let X=[];if(h.filter((z)=>z.type==="provider").forEach((z)=>{switch(z.id){case"google.google_search":if(T)X.push({googleSearch:{...z.args}});else _.push({type:"unsupported",feature:`provider-defined tool ${z.id}`,details:"Google Search requires Gemini 2.0 or newer."});break;case"google.enterprise_web_search":if(T)X.push({enterpriseWebSearch:{}});else _.push({type:"unsupported",feature:`provider-defined tool ${z.id}`,details:"Enterprise Web Search requires Gemini 2.0 or newer."});break;case"google.url_context":if(T)X.push({urlContext:{}});else _.push({type:"unsupported",feature:`provider-defined tool ${z.id}`,details:"The URL context tool is not supported with other Gemini models than Gemini 2."});break;case"google.code_execution":if(T)X.push({codeExecution:{}});else _.push({type:"unsupported",feature:`provider-defined tool ${z.id}`,details:"The code execution tool is not supported with other Gemini models than Gemini 2."});break;case"google.file_search":if(S)X.push({fileSearch:{...z.args}});else _.push({type:"unsupported",feature:`provider-defined tool ${z.id}`,details:"The file search tool is only supported with Gemini 2.5 models and Gemini 3 models."});break;case"google.vertex_rag_store":if(T)X.push({retrieval:{vertex_rag_store:{rag_resources:{rag_corpus:z.args.ragCorpus},similarity_top_k:z.args.topK}}});else _.push({type:"unsupported",feature:`provider-defined tool ${z.id}`,details:"The RAG store tool is not supported with other Gemini models than Gemini 2."});break;case"google.google_maps":if(T)X.push({googleMaps:{}});else _.push({type:"unsupported",feature:`provider-defined tool ${z.id}`,details:"The Google Maps grounding tool is not supported with Gemini models other than Gemini 2 or newer."});break;default:_.push({type:"unsupported",feature:`provider-defined tool ${z.id}`})}}),x&&w&&X.length>0){let z=[];for(let ue of h)if(ue.type==="function")z.push(Zc(ue));let Z={functionCallingConfig:{mode:"VALIDATED"},...!y&&{includeServerSideToolInvocations:!0}};if(f!=null)switch(f.type){case"auto":break;case"none":Z.functionCallingConfig={mode:"NONE"};break;case"required":Z.functionCallingConfig={mode:"ANY"};break;case"tool":Z.functionCallingConfig={mode:"ANY",allowedFunctionNames:[f.toolName]}}return{tools:[...X,{functionDeclarations:z}],toolConfig:Z,toolWarnings:_}}return{tools:X.length>0?X:void 0,toolConfig:void 0,toolWarnings:_}}let P=[],ne=!1;for(let X of h)switch(X.type){case"function":if(P.push(Zc(X)),X.strict===!0)ne=!0;break;default:_.push({type:"unsupported",feature:`function tool ${X.name}`})}if(f==null)return{tools:[{functionDeclarations:P}],toolConfig:ne?{functionCallingConfig:{mode:"VALIDATED"}}:void 0,toolWarnings:_};let se=f.type;switch(se){case"auto":return{tools:[{functionDeclarations:P}],toolConfig:{functionCallingConfig:{mode:ne?"VALIDATED":"AUTO"}},toolWarnings:_};case"none":return{tools:[{functionDeclarations:P}],toolConfig:{functionCallingConfig:{mode:"NONE"}},toolWarnings:_};case"required":return{tools:[{functionDeclarations:P}],toolConfig:{functionCallingConfig:{mode:"ANY"}},toolWarnings:_};case"tool":return{tools:[{functionDeclarations:P}],toolConfig:{functionCallingConfig:{mode:"ANY",allowedFunctionNames:[f.toolName]}},toolWarnings:_};default:throw new b({functionality:`tool choice type: ${se}`})}}function Zc(h){return{name:h.name,description:h.description??"",parametersJsonSchema:h.inputSchema}}var Hf=class{constructor(){this.accumulatedArgs={},this.jsonText="",this.pathStack=[],this.stringOpen=!1}processPartialArgs(h){let f="";for(let g of h){let y=g.jsonPath.endsWith("[]"),_=(y?g.jsonPath.slice(0,-2):g.jsonPath).replace(/^\$\./,"");if(!_||_==="$")continue;let T=Bf(_),S=Wf(this.accumulatedArgs,T);if(g.stringValue!=null&&S!==void 0){let x=JSON.stringify(g.stringValue).slice(1,-1);As(this.accumulatedArgs,T,S+g.stringValue),f+=x;continue}let w=Kf(g);if(w==null){if(S!==void 0||g.willContinue===!0)continue;As(this.accumulatedArgs,T,y?[]:{}),f+=this.emitContainer(T,y);continue}As(this.accumulatedArgs,T,w.value),f+=this.emitNavigationTo(T,g,w.json)}return this.jsonText+=f,{currentJSON:this.accumulatedArgs,textDelta:f}}finalize(){let h=JSON.stringify(this.accumulatedArgs);return{finalJSON:h,closingDelta:h.slice(this.jsonText.length)}}ensureRoot(){if(this.pathStack.length===0)return this.pathStack.push({segment:"",isArray:!1,childCount:0}),"{";return""}emitNavigationTo(h,f,g){let y="";if(this.stringOpen)y+='"',this.stringOpen=!1;y+=this.ensureRoot();let _=h.slice(0,-1),T=h[h.length-1],S=this.findCommonStackDepth(_);return y+=this.closeDownTo(S),y+=this.openDownTo(_,T),y+=this.emitLeaf(T,f,g),y}emitContainer(h,f){let g="";if(this.stringOpen)g+='"',this.stringOpen=!1;g+=this.ensureRoot();let y=this.findCommonStackDepth(h);return g+=this.closeDownTo(y),g+=this.openDownTo(h,f?0:""),g}findCommonStackDepth(h){let f=Math.min(this.pathStack.length-1,h.length),g=0;for(let y=0;y<f;y++)if(this.pathStack[y+1].segment===h[y])g++;else break;return g+1}closeDownTo(h){let f="";while(this.pathStack.length>h){let g=this.pathStack.pop();f+=g.isArray?"]":"}"}return f}openDownTo(h,f){let g="",y=this.pathStack.length-1;for(let _=y;_<h.length;_++){let T=h[_],S=this.pathStack[this.pathStack.length-1];if(S.childCount>0)g+=",";if(S.childCount++,typeof T==="string")g+=`${JSON.stringify(T)}:`;let w=typeof(_+1<h.length?h[_+1]:f)==="number";g+=w?"[":"{",this.pathStack.push({segment:T,isArray:w,childCount:0})}return g}emitLeaf(h,f,g){let y="",_=this.pathStack[this.pathStack.length-1];if(_.childCount>0)y+=",";if(_.childCount++,typeof h==="string")y+=`${JSON.stringify(h)}:`;if(f.stringValue!=null&&f.willContinue)y+=g.slice(0,-1),this.stringOpen=!0;else y+=g;return y}};function Bf(h){let f=[];for(let g of h.split(".")){let y=g.indexOf("[");if(y===-1)f.push(g);else{if(y>0)f.push(g.slice(0,y));for(let _ of g.matchAll(/\[(\d+)\]/g))f.push(parseInt(_[1],10))}}return f}var Vf=Object.prototype.hasOwnProperty;function gl(h,f){return Vf.call(h,f)}function el(h,f,g){Object.defineProperty(h,f,{value:g,enumerable:!0,configurable:!0,writable:!0})}function Wf(h,f){let g=h;for(let y of f){if(g==null||typeof g!=="object")return;let _=g;if(!gl(_,y))return;g=_[y]}return g}function As(h,f,g){let y=h;for(let _=0;_<f.length-1;_++){let T=f[_],S=f[_+1];if(!gl(y,T)||y[T]==null)el(y,T,typeof S==="number"?[]:{});y=y[T]}el(y,f[f.length-1],g)}function Kf(h){let f=h.stringValue??h.numberValue??h.boolValue;if(f!=null)return{value:f,json:JSON.stringify(f)};if("nullValue"in h)return{value:null,json:"null"}}function tl({finishReason:h,hasToolCalls:f}){switch(h){case"STOP":return f?"tool-calls":"stop";case"MAX_TOKENS":case"CONTINUATION":return"length";case"IMAGE_SAFETY":case"RECITATION":case"SAFETY":case"BLOCKLIST":case"PROHIBITED_CONTENT":case"SPII":return"content-filter";case"MALFORMED_FUNCTION_CALL":return"error";default:return"other"}}var Jf=["HARM_CATEGORY_HATE_SPEECH","HARM_CATEGORY_DANGEROUS_CONTENT","HARM_CATEGORY_HARASSMENT","HARM_CATEGORY_SEXUALLY_EXPLICIT"],Yf=/(^|[/.])gemini-2\.5(?:[.-]|$)/i,zf={"image/png":[/^gs:\/\/.*$/],"image/jpeg":[/^gs:\/\/.*$/],"image/webp":[/^gs:\/\/.*$/],"application/pdf":[/^gs:\/\/.*$/],"text/plain":[/^gs:\/\/.*$/]},Os=class h{static[H](f){return te({modelId:f.modelId,config:f.config})}static[Q](f){return new h(f.modelId,f.config)}constructor(f,g){this.specificationVersion="v4",this.modelId=f,this.config=g,this.generateId=g.generateId??C}get provider(){return this.config.provider}get supportedUrls(){return this.config.supportedUrls?.()??{}}static async prepareRequest({modelId:f,config:g,options:{prompt:y,maxOutputTokens:_,temperature:T,topP:S,topK:w,frequencyPenalty:x,presencePenalty:B,stopSequences:P,responseFormat:ne,seed:se,tools:X,toolChoice:z,reasoning:Z,providerOptions:ue,abortSignal:M},isStreaming:L=!1}){let he=[],q=g.provider.includes("vertex")?["googleVertex","vertex"]:["google"],U;for(let rt of q)if(U=await k({provider:rt,providerOptions:ue,schema:Qc}),U!=null)break;if(U==null&&!q.includes("google"))U=await k({provider:"google",providerOptions:ue,schema:Qc});let de=g.provider.startsWith("google.vertex.");if(X?.some((rt)=>rt.type==="provider"&&rt.id==="google.vertex_rag_store")&&!de)he.push({type:"other",message:`The 'vertex_rag_store' tool is only supported with the Google Vertex provider and might not be supported or could behave unexpectedly with the current Google provider (${g.provider}).`});if(U?.streamFunctionCallArguments&&!de)he.push({type:"other",message:`'streamFunctionCallArguments' is only supported on the Vertex AI API and will be ignored with the current Google provider (${g.provider}). See https://docs.cloud.google.com/vertex-ai/generative-ai/docs/multimodal/function-calling#streaming-fc`});if(U?.serviceTier&&de)he.push({type:"other",message:"'serviceTier' is a Gemini API option and is not supported on Vertex AI. Use 'sharedRequestType' (and optionally 'requestType') instead. See https://docs.cloud.google.com/vertex-ai/generative-ai/docs/priority-paygo"});if((U?.sharedRequestType||U?.requestType)&&!de)he.push({type:"other",message:`'sharedRequestType' and 'requestType' are Vertex AI options and are ignored with the current Google provider (${g.provider}).`});let ye=de&&(U?.sharedRequestType||U?.requestType)?{...U.sharedRequestType&&{"X-Vertex-AI-LLM-Shared-Request-Type":U.sharedRequestType},...U.requestType&&{"X-Vertex-AI-LLM-Request-Type":U.requestType}}:void 0,Ce=de?void 0:U?.serviceTier,_e=U?.imageConfig;if(_e!=null&&!de){let{personGeneration:rt,prominentPeople:Le,imageOutputOptions:_t,...O}=_e,N=Object.entries({personGeneration:rt,prominentPeople:Le,imageOutputOptions:_t}).filter(([,R])=>R!=null).map(([R])=>`'imageConfig.${R}'`);if(N.length>0)he.push({type:"other",message:`${N.join(", ")} ${N.length===1?"is a Vertex AI option and is":"are Vertex AI options and are"} ignored with the current Google provider (${g.provider}).`}),_e=O}let Pe=f.toLowerCase().startsWith("gemma-"),Re=!de&&Yf.test(f);if(Re&&x!=null)he.push({type:"unsupported",feature:"frequencyPenalty"});if(Re&&B!=null)he.push({type:"unsupported",feature:"presencePenalty"});let{usesGemini3Features:Ne}=Zn(f),Je=Ne&&g.downloadToolResultFiles?.supportsGoogleCloudStorageUrls?zf:void 0,{contents:je,systemInstruction:Ye}=jf(g.downloadToolResultFiles?await Uf(y,{abortSignal:M,maxBytes:g.downloadToolResultFiles.maxBytes,supportedUrls:Je}):y,{isGemmaModel:Pe,isGemini3Model:Ne,onWarning:(rt)=>he.push(rt),providerOptionsNames:q,supportsFunctionResponseParts:Ne,includeFunctionCallIds:!de,supportedFunctionResponseUrls:Je}),{tools:Ue,toolConfig:ze,toolWarnings:Ze}=$f({tools:X,toolChoice:z,modelId:f,isVertexProvider:de}),nt=Kt({tools:X,providerToolNames:{"google.code_execution":"code_execution"}}),ot=U?.thinkingConfig?.thinkingBudget!=null||U?.thinkingConfig?.thinkingLevel!=null?void 0:Zf({reasoning:Z,modelId:f,warnings:he}),et=U?.thinkingConfig||ot?{...ot,...U?.thinkingConfig}:void 0,mt=L&&de?U?.streamFunctionCallArguments??!1:void 0,fe=U?.threshold,be=U?.safetySettings??(fe!=null?Jf.map((rt)=>({category:rt,threshold:fe})):void 0),at=ze||mt||U?.retrievalConfig?{...ze,...mt&&{functionCallingConfig:{...ze?.functionCallingConfig,streamFunctionCallArguments:!0}},...U?.retrievalConfig&&{retrievalConfig:U.retrievalConfig}}:void 0;return{args:{generationConfig:{maxOutputTokens:_,temperature:T,topK:w,topP:S,frequencyPenalty:Re?void 0:x,presencePenalty:Re?void 0:B,stopSequences:P,seed:se,responseMimeType:ne?.type==="json"?"application/json":void 0,responseJsonSchema:ne?.type==="json"&&ne.schema!=null&&(U?.structuredOutputs??!0)?pl(ne.schema):void 0,...U?.audioTimestamp&&{audioTimestamp:U.audioTimestamp},responseModalities:U?.responseModalities,thinkingConfig:et,...U?.mediaResolution&&{mediaResolution:U.mediaResolution},..._e&&{imageConfig:_e}},contents:je,systemInstruction:Pe?void 0:Ye,safetySettings:be,tools:Ue,toolConfig:at,cachedContent:U?.cachedContent,labels:U?.labels,serviceTier:Ce,...U?.continuationToken!=null&&{continuationToken:U.continuationToken}},warnings:[...he,...Ze],providerOptionsNames:q,extraHeaders:ye,toolNameMapping:nt}}async getArgs(f,{isStreaming:g=!1}={}){let{responseFormat:y,tools:_,toolChoice:T}=f,S;if(y?.type==="json"&&y.schema!=null&&_?.some((w)=>w.type==="function")&&/(^|\/)gemini-/i.test(this.modelId)&&(!Zn(this.modelId).usesGemini3Features||T?.type==="required"||T?.type==="tool")){let w="json";for(let x=1;_.some((B)=>B.name===w);x++)w=`json_${x}`;S={type:"function",name:w,description:y.description??"Respond with a JSON object.",inputSchema:y.schema}}return{...await h.prepareRequest({modelId:this.modelId,config:this.config,options:S==null?f:{...f,responseFormat:void 0,tools:[..._??[],S],toolChoice:T?.type==="tool"?T:T?.type==="none"?{type:"tool",toolName:S.name}:{type:"required"}},isStreaming:g}),jsonResponseToolName:S?.name}}static convertGenerateContentResponse({config:f,response:g,warnings:y,providerOptionsNames:_,toolNameMapping:T,jsonResponseToolName:S,initialPromptTokenCount:w,groundingMetadataPerRequest:x}){let B=(U)=>Object.fromEntries(_.map((de)=>[de,U])),P=g.candidates?.[0],ne=g.promptFeedback?.blockReason,se=rl(ne)?ne:void 0,X=P?.finishReason==null&&se!=null,z=P?.finishReason??se,Z=[],ue=P?.content?.parts??[],M=g.usageMetadata,L,he;for(let U of ue)if("executableCode"in U&&U.executableCode?.code){let de=f.generateId();L=de,Z.push({type:"tool-call",toolCallId:de,toolName:T?.toCustomToolName("code_execution")??"code_execution",input:JSON.stringify(U.executableCode),providerExecuted:!0})}else if("codeExecutionResult"in U&&U.codeExecutionResult)Z.push({type:"tool-result",toolCallId:L,toolName:T?.toCustomToolName("code_execution")??"code_execution",result:{outcome:U.codeExecutionResult.outcome,output:U.codeExecutionResult.output??""}});else if("text"in U&&U.text!=null){if(S!=null&&U.thought!==!0)continue;let de=U.thoughtSignature?B({thoughtSignature:U.thoughtSignature}):void 0;if(U.text.length===0){if(de!=null&&Z.length>0){let ye=Z[Z.length-1];ye.providerMetadata=de}}else Z.push({type:U.thought===!0?"reasoning":"text",text:U.text,providerMetadata:de})}else if("functionCall"in U&&U.functionCall.name!=null){if(U.functionCall.name===S){Z.push({type:"text",text:typeof U.functionCall.args==="string"?U.functionCall.args:JSON.stringify(U.functionCall.args??{}),...U.thoughtSignature?{providerMetadata:B({thoughtSignature:U.thoughtSignature})}:{}});continue}Z.push({type:"tool-call",toolCallId:U.functionCall.id||f.generateId(),toolName:U.functionCall.name,input:JSON.stringify(U.functionCall.args??{}),providerMetadata:U.thoughtSignature?B({thoughtSignature:U.thoughtSignature}):void 0})}else if("inlineData"in U){let de=U.thought===!0,ye=!!U.thoughtSignature;Z.push({type:de?"reasoning-file":"file",data:{type:"data",data:U.inlineData.data},mediaType:U.inlineData.mimeType,providerMetadata:ye?B({thoughtSignature:U.thoughtSignature}):void 0})}else if("toolCall"in U&&U.toolCall){let de=U.toolCall.id||f.generateId();he=de,Z.push({type:"tool-call",toolCallId:de,toolName:`server:${U.toolCall.toolType}`,input:JSON.stringify(U.toolCall.args??{}),providerExecuted:!0,dynamic:!0,providerMetadata:U.thoughtSignature?B({thoughtSignature:U.thoughtSignature,serverToolCallId:de,serverToolType:U.toolCall.toolType}):B({serverToolCallId:de,serverToolType:U.toolCall.toolType})})}else if("toolResponse"in U&&U.toolResponse){let de=he||U.toolResponse.id||f.generateId();Z.push({type:"tool-result",toolCallId:de,toolName:`server:${U.toolResponse.toolType}`,result:U.toolResponse.response??{},providerMetadata:U.thoughtSignature?B({thoughtSignature:U.thoughtSignature,serverToolCallId:de,serverToolType:U.toolResponse.toolType}):B({serverToolCallId:de,serverToolType:U.toolResponse.toolType})}),he=void 0}let q=nl({groundingMetadata:P?.groundingMetadata,generateId:f.generateId})??[];for(let U of q)Z.push(U);return{content:Z,finishReason:{unified:X?"content-filter":tl({finishReason:z,hasToolCalls:Z.some((U)=>U.type==="tool-call"&&!U.providerExecuted)}),raw:z},usage:Kc(M),warnings:y,providerMetadata:B({promptFeedback:g.promptFeedback??null,groundingMetadata:P?.groundingMetadata??null,...x!=null?{groundingMetadataPerRequest:x}:{},urlContextMetadata:P?.urlContextMetadata??null,safetyRatings:P?.safetyRatings??null,usageMetadata:M??null,finishMessage:P?.finishMessage??null,serviceTier:M?.serviceTier??null,...P?.continuationToken!=null?{continuationToken:P.continuationToken}:{},...w!=null?{initialPromptTokenCount:w}:{}}),response:{id:g.responseId??void 0}}}async doGenerate(f){let{args:g,warnings:y,providerOptionsNames:_,extraHeaders:T,toolNameMapping:S,jsonResponseToolName:w}=await this.getArgs(f),x=I(this.config.headers?await W(this.config.headers):void 0,f.headers,T),B=(q)=>A({url:`${this.config.baseURL}/${zc(this.modelId)}:generateContent`,headers:x,body:q,failedResponseHandler:Bt,successfulResponseHandler:E(sg),abortSignal:f.abortSignal,fetch:this.config.fetch}),{responseHeaders:P,value:ne,rawValue:se}=await B(g),X=[],z=[],Z,ue=ne.usageMetadata?.promptTokenCount,M=!1;while(!0){let q=ne.candidates?.[0];z.push(q?.groundingMetadata??null);let U=q?.finishReason==="CONTINUATION"?q.continuationToken:void 0;if(Z=Cs(Z,ne.usageMetadata??void 0),U==null)break;X.push(...h.convertGenerateContentResponse({config:this.config,response:ne,warnings:y,providerOptionsNames:_,toolNameMapping:S,jsonResponseToolName:w}).content),M=!0,{responseHeaders:P,value:ne,rawValue:se}=await B({...g,continuationToken:U})}let L=h.convertGenerateContentResponse({config:this.config,response:{...ne,usageMetadata:Z},warnings:y,providerOptionsNames:_,toolNameMapping:S,jsonResponseToolName:w,initialPromptTokenCount:M?ue:void 0,groundingMetadataPerRequest:M?z:void 0}),he={...L,content:[...X,...L.content]};return{...he,request:{body:g},response:{...he.response,headers:P,body:se}}}async doStream(f){let{args:g,warnings:y,providerOptionsNames:_,extraHeaders:T,toolNameMapping:S,jsonResponseToolName:w}=await this.getArgs(f,{isStreaming:!0}),x=(fe)=>Object.fromEntries(_.map((be)=>[be,fe])),B=I(this.config.headers?await W(this.config.headers):void 0,f.headers,T),P=(fe)=>A({url:`${this.config.baseURL}/${zc(this.modelId)}:streamGenerateContent?alt=sse`,headers:B,body:fe,failedResponseHandler:Bt,successfulResponseHandler:qe(ig),abortSignal:f.abortSignal,fetch:this.config.fetch}),{responseHeaders:ne,value:se}=await P(g),X=[],z=null,Z=Sf({stream:se,getContinuationToken:(fe)=>{let be=fe.candidates?.[0];if(be?.groundingMetadata!=null)z=be.groundingMetadata;return be?.finishReason==="CONTINUATION"?be.continuationToken??void 0:void 0},continueStream:async(fe)=>{let{value:be}=await P({...g,continuationToken:fe});return X.push(z),z=null,be}}),ue={unified:"interrupted",raw:void 0},M=void 0,L=void 0,he=void 0,q=null,U=null,de=null,ye=null,Ce=null,_e=null,Pe,Re=this.config.generateId,Ne=!1,Je=!1,je=null,Ye=null,Ue=0,ze=new Set,Ze,nt,ot=[],et=(fe)=>{let be=ot.pop();if(be==null)return;let{finalJSON:at,closingDelta:rt}=be.accumulator.finalize();if(rt.length>0)fe.enqueue({type:"tool-input-delta",id:be.toolCallId,delta:rt,providerMetadata:be.providerMetadata});fe.enqueue({type:"tool-input-end",id:be.toolCallId,providerMetadata:be.providerMetadata}),fe.enqueue({type:"tool-call",toolCallId:be.toolCallId,toolName:be.toolName,input:at,providerMetadata:be.providerMetadata}),Ne=!0},mt={stream:Z.pipeThrough(new TransformStream({start(fe){fe.enqueue({type:"stream-start",warnings:y})},transform(fe,be){if("type"in fe){ue={unified:"interrupted",raw:void 0};return}if(f.includeRawChunks)be.enqueue({type:"raw",rawValue:fe.rawValue});if(!fe.success){if(ue.unified==="interrupted")ue={unified:"error",raw:void 0};be.enqueue({type:"error",error:fe.error});return}let at=fe.value;if(at.error!=null){ue={unified:"error",raw:void 0};let N=at.error;be.enqueue({type:"error",error:Ht({message:N.message,type:N.status,code:N.code??void 0,statusCode:N.code??void 0,isRetryable:N.code!=null&&(N.code===408||N.code===409||N.code===429||N.code>=500),data:N})});return}if(!Je&&at.responseId!=null)Je=!0,be.enqueue({type:"response-metadata",id:at.responseId});let rt=at.usageMetadata;if(rt!=null)M=rt;if(at.promptFeedback!=null&&Pe==null){if(q=at.promptFeedback,rl(at.promptFeedback.blockReason))Pe=at.promptFeedback.blockReason,ue={unified:"content-filter",raw:Pe}}let Le=at.candidates?.[0];if(Le!=null){if(Le.groundingMetadata!=null)U=Le.groundingMetadata;if(Le.urlContextMetadata!=null)de=Le.urlContextMetadata;if(Le.safetyRatings!=null)ye=Le.safetyRatings;if(Le.finishMessage!=null)Ce=Le.finishMessage;if(Le.continuationToken!=null)_e=Le.continuationToken}if(Pe!=null||Le==null)return;let _t=Le.content,O=nl({groundingMetadata:Le.groundingMetadata,generateId:Re});if(O!=null){for(let N of O)if(N.sourceType==="url"&&!ze.has(N.url))ze.add(N.url),be.enqueue(N)}if(_t!=null){let N=_t.parts??[];for(let R of N)if("executableCode"in R&&R.executableCode?.code){let K=Re();Ze=K,be.enqueue({type:"tool-call",toolCallId:K,toolName:S.toCustomToolName("code_execution"),input:JSON.stringify(R.executableCode),providerExecuted:!0})}else if("codeExecutionResult"in R&&R.codeExecutionResult){let K=Ze;if(K)be.enqueue({type:"tool-result",toolCallId:K,toolName:S.toCustomToolName("code_execution"),result:{outcome:R.codeExecutionResult.outcome,output:R.codeExecutionResult.output??""}})}else if("text"in R&&R.text!=null){let K=R.thoughtSignature?x({thoughtSignature:R.thoughtSignature}):void 0;if(R.text.length===0){if(K!=null&&je!==null)be.enqueue({type:"text-delta",id:je,delta:"",providerMetadata:K})}else if(R.thought===!0){if(je!==null)be.enqueue({type:"text-end",id:je}),je=null;if(Ye===null)Ye=String(Ue++),be.enqueue({type:"reasoning-start",id:Ye,providerMetadata:K});be.enqueue({type:"reasoning-delta",id:Ye,delta:R.text,providerMetadata:K})}else{if(Ye!==null)be.enqueue({type:"reasoning-end",id:Ye}),Ye=null;if(je===null)je=String(Ue++),be.enqueue({type:"text-start",id:je,providerMetadata:K});be.enqueue({type:"text-delta",id:je,delta:R.text,providerMetadata:K})}}else if("inlineData"in R){if(je!==null)be.enqueue({type:"text-end",id:je}),je=null;if(Ye!==null)be.enqueue({type:"reasoning-end",id:Ye}),Ye=null;let K=R.thought===!0,J=R.thoughtSignature?x({thoughtSignature:R.thoughtSignature}):void 0;be.enqueue({type:K?"reasoning-file":"file",mediaType:R.inlineData.mimeType,data:{type:"data",data:R.inlineData.data},providerMetadata:J})}else if("toolCall"in R&&R.toolCall){let K=R.toolCall.id||Re();nt=K;let J=x({...R.thoughtSignature?{thoughtSignature:R.thoughtSignature}:{},serverToolCallId:K,serverToolType:R.toolCall.toolType});be.enqueue({type:"tool-call",toolCallId:K,toolName:`server:${R.toolCall.toolType}`,input:JSON.stringify(R.toolCall.args??{}),providerExecuted:!0,dynamic:!0,providerMetadata:J})}else if("toolResponse"in R&&R.toolResponse){let K=nt||R.toolResponse.id||Re(),J=x({...R.thoughtSignature?{thoughtSignature:R.thoughtSignature}:{},serverToolCallId:K,serverToolType:R.toolResponse.toolType});be.enqueue({type:"tool-result",toolCallId:K,toolName:`server:${R.toolResponse.toolType}`,result:R.toolResponse.response??{},providerMetadata:J}),nt=void 0}for(let R of N){if(!("functionCall"in R))continue;let K=R.thoughtSignature?x({thoughtSignature:R.thoughtSignature}):void 0,J=R.functionCall.partialArgs!=null||R.functionCall.name!=null&&R.functionCall.willContinue===!0,re=R.functionCall.name==null&&R.functionCall.args==null&&R.functionCall.partialArgs==null&&R.functionCall.willContinue==null,pe=R.functionCall.name!=null&&R.functionCall.args!=null&&R.functionCall.partialArgs==null,V=R.functionCall.name!=null&&R.functionCall.args==null&&R.functionCall.partialArgs==null&&R.functionCall.willContinue!==!0;if(J){if(R.functionCall.name!=null){let Y=R.functionCall.id||Re(),ce=new Hf;if(ot.push({toolCallId:Y,toolName:R.functionCall.name,accumulator:ce,providerMetadata:K}),be.enqueue({type:"tool-input-start",id:Y,toolName:R.functionCall.name,providerMetadata:K}),R.functionCall.partialArgs!=null){let ie=R.functionCall.partialArgs,{textDelta:me}=ce.processPartialArgs(ie);if(me.length>0)be.enqueue({type:"tool-input-delta",id:Y,delta:me,providerMetadata:K});if(R.functionCall.willContinue!==!0&&ie.every((ke)=>ke.willContinue!==!0))et(be)}}else if(R.functionCall.partialArgs!=null&&ot.length>0){let Y=ot[ot.length-1],ce=R.functionCall.partialArgs,{textDelta:ie}=Y.accumulator.processPartialArgs(ce);if(ie.length>0)be.enqueue({type:"tool-input-delta",id:Y.toolCallId,delta:ie,providerMetadata:K});if(R.functionCall.willContinue!==!0&&ce.every((me)=>me.willContinue!==!0))et(be)}}else if(re&&ot.length>0)et(be);else if(pe){let Y=R.functionCall.id||Re(),ce=R.functionCall.name,ie=typeof R.functionCall.args==="string"?R.functionCall.args:JSON.stringify(R.functionCall.args??{});be.enqueue({type:"tool-input-start",id:Y,toolName:ce,providerMetadata:K}),be.enqueue({type:"tool-input-delta",id:Y,delta:ie,providerMetadata:K}),be.enqueue({type:"tool-input-end",id:Y,providerMetadata:K}),be.enqueue({type:"tool-call",toolCallId:Y,toolName:ce,input:ie,providerMetadata:K}),Ne=!0}else if(V){let Y=R.functionCall.id||Re(),ce=R.functionCall.name;be.enqueue({type:"tool-input-start",id:Y,toolName:ce,providerMetadata:K}),be.enqueue({type:"tool-input-end",id:Y,providerMetadata:K}),be.enqueue({type:"tool-call",toolCallId:Y,toolName:ce,input:"{}",providerMetadata:K}),Ne=!0}}}if(Le.finishReason==="CONTINUATION"){if(L==null)he=M?.promptTokenCount;L=Cs(L,M),M=void 0}if(Le.finishReason!=null)ue={unified:tl({finishReason:Le.finishReason,hasToolCalls:Ne}),raw:Le.finishReason}},flush(fe){if(M=Cs(L,M),je!==null)fe.enqueue({type:"text-end",id:je});if(Ye!==null)fe.enqueue({type:"reasoning-end",id:Ye});fe.enqueue({type:"finish",finishReason:ue,usage:Kc(M),providerMetadata:x({promptFeedback:q,groundingMetadata:U,...X.length>0?{groundingMetadataPerRequest:[...X,z]}:{},urlContextMetadata:de,safetyRatings:ye,usageMetadata:M??null,finishMessage:Ce,serviceTier:M?.serviceTier??null,..._e!=null&&(ue.raw==="MAX_TOKENS"||ue.raw==="CONTINUATION")?{continuationToken:_e}:{},...he!=null?{initialPromptTokenCount:he}:{}})})}})),response:{headers:ne},request:{body:g}};return{...mt,stream:w==null?mt.stream:mt.stream.pipeThrough(dp(w))}}};function Xf(){return 65536}function Qf(h){let f=h.toLowerCase();if(f.includes("2.5-pro")||f.includes("gemini-3-pro-image"))return 32768;return 24576}function Zf({reasoning:h,modelId:f,warnings:g}){if(!Ee(h))return;if(Zn(f).usesGemini3Features&&!f.includes("gemini-3-pro-image"))return eg({reasoning:h,modelId:f,warnings:g});return ng({reasoning:h,modelId:f,warnings:g})}function eg({reasoning:h,modelId:f,warnings:g}){let y=tg(f);if(h==="none")return{thinkingLevel:y};let _=ft({reasoning:h,effortMap:{minimal:y,low:"low",medium:"medium",high:"high",xhigh:"high",max:"high"},warnings:g});if(_==null)return;return{thinkingLevel:_}}function tg(h){let f=/(?:^|[/.])(gemini-[^/]*)$/i.exec(h)?.[1].toLowerCase();if(f==="gemini-flash-latest")return"low";let g=/^gemini-(\d+)(?:\.\d+)?-pro(?:$|-)/.exec(f??"");if(Number(g?.[1])>=3)return"low";let y=/^gemini-(\d+)\.(\d+)-flash(?:$|-(?!lite(?:-|$)))/.exec(f??"");if(y==null)return"minimal";let _=Number(y[1]),T=Number(y[2]);return _>3||_===3&&T>=7?"low":"minimal"}function ng({reasoning:h,modelId:f,warnings:g}){if(h==="none")return{thinkingBudget:0};let y=en({reasoning:h,maxOutputTokens:Xf(),maxReasoningBudget:Qf(f),minReasoningBudget:0,warnings:g});if(y==null)return;return{thinkingBudget:y}}function nl({groundingMetadata:h,generateId:f}){if(!h?.groundingChunks)return;let g=[];for(let y of h.groundingChunks)if(y.web!=null)g.push({type:"source",sourceType:"url",id:f(),url:y.web.uri,title:y.web.title??void 0});else if(y.image!=null)g.push({type:"source",sourceType:"url",id:f(),url:y.image.sourceUri,title:y.image.title??void 0});else if(y.retrievedContext!=null){let _=y.retrievedContext.uri,T=y.retrievedContext.fileSearchStore;if(_&&(_.startsWith("http://")||_.startsWith("https://")))g.push({type:"source",sourceType:"url",id:f(),url:_,title:y.retrievedContext.title??void 0});else if(_){let S=y.retrievedContext.title??"Unknown Document",w="application/octet-stream",x=void 0;if(_.endsWith(".pdf"))w="application/pdf",x=_.split("/").pop();else if(_.endsWith(".txt"))w="text/plain",x=_.split("/").pop();else if(_.endsWith(".docx"))w="application/vnd.openxmlformats-officedocument.wordprocessingml.document",x=_.split("/").pop();else if(_.endsWith(".doc"))w="application/msword",x=_.split("/").pop();else if(_.match(/\.(md|markdown)$/))w="text/markdown",x=_.split("/").pop();else x=_.split("/").pop();g.push({type:"source",sourceType:"document",id:f(),mediaType:w,title:S,filename:x})}else if(T){let S=y.retrievedContext.title??"Unknown Document";g.push({type:"source",sourceType:"document",id:f(),mediaType:"application/octet-stream",title:S,filename:T.split("/").pop()})}}else if(y.maps!=null){if(y.maps.uri)g.push({type:"source",sourceType:"url",id:f(),url:y.maps.uri,title:y.maps.title??void 0})}return g.length>0?g:void 0}var ml=()=>t({webSearchQueries:o(e()).nullish(),imageSearchQueries:o(e()).nullish(),retrievalQueries:o(e()).nullish(),searchEntryPoint:t({renderedContent:e()}).nullish(),groundingChunks:o(t({web:t({uri:e(),title:e().nullish()}).nullish(),image:t({sourceUri:e(),imageUri:e(),title:e().nullish(),domain:e().nullish()}).nullish(),retrievedContext:t({uri:e().nullish(),title:e().nullish(),text:e().nullish(),fileSearchStore:e().nullish(),customMetadata:o(t({key:e(),stringValue:e().nullish(),numericValue:n().nullish(),stringListValue:t({values:o(e()).nullish()}).nullish()})).nullish()}).nullish(),maps:t({uri:e().nullish(),title:e().nullish(),text:e().nullish(),placeId:e().nullish()}).nullish()})).nullish(),groundingSupports:o(t({segment:t({startIndex:n().nullish(),endIndex:n().nullish(),text:e().nullish()}).nullish(),segment_text:e().nullish(),groundingChunkIndices:o(n()).nullish(),supportChunkIndices:o(n()).nullish(),confidenceScores:o(n()).nullish(),confidenceScore:o(n()).nullish()})).nullish(),retrievalMetadata:p([t({webDynamicRetrievalScore:n()}),t({})]).nullish()}),rg=()=>t({jsonPath:e(),stringValue:e().nullish(),numberValue:n().nullish(),boolValue:r().nullish(),nullValue:m().nullish(),willContinue:r().nullish()}),_l=()=>t({parts:o(p([t({functionCall:t({id:e().nullish(),name:e().nullish(),args:m().nullish(),partialArgs:o(rg()).nullish(),willContinue:r().nullish()}),thoughtSignature:e().nullish()}),t({inlineData:t({mimeType:e(),data:e()}),thought:r().nullish(),thoughtSignature:e().nullish()}),t({toolCall:t({toolType:e(),args:m().nullish(),id:e()}),thoughtSignature:e().nullish()}),t({toolResponse:t({toolType:e(),response:m().nullish(),id:e()}),thoughtSignature:e().nullish()}),t({executableCode:t({language:e(),code:e()}).nullish(),codeExecutionResult:t({outcome:e(),output:e().nullish()}).nullish(),text:e().nullish(),thought:r().nullish(),thoughtSignature:e().nullish()})])).nullish()}),er=()=>t({category:e().nullish(),probability:e().nullish(),probabilityScore:n().nullish(),severity:e().nullish(),severityScore:n().nullish(),blocked:r().nullish()}),Yn=()=>o(t({modality:e(),tokenCount:n()}).loose()).nullish(),Tl=()=>t({cachedContentTokenCount:n().nullish(),thoughtsTokenCount:n().nullish(),promptTokenCount:n().nullish(),candidatesTokenCount:n().nullish(),toolUsePromptTokenCount:n().nullish(),totalTokenCount:n().nullish(),trafficType:e().nullish(),serviceTier:e().nullish(),promptTokensDetails:Yn(),cacheTokensDetails:Yn(),candidatesTokensDetails:Yn(),toolUsePromptTokensDetails:Yn()}).loose(),vl=()=>t({urlMetadata:o(t({retrievedUrl:e(),urlRetrievalStatus:e()})).nullish()}),sg=u(()=>l(t({responseId:e().nullish(),candidates:o(t({content:_l().nullish().or(t({}).strict()),finishReason:e().nullish(),finishMessage:e().nullish(),continuationToken:e().nullish(),safetyRatings:o(er()).nullish(),groundingMetadata:ml().nullish(),urlContextMetadata:vl().nullish()})).nullish(),usageMetadata:Tl().nullish(),promptFeedback:t({blockReason:e().nullish(),safetyRatings:o(er()).nullish()}).nullish()}))),ig=u(()=>l(t({error:hl().nullish(),responseId:e().nullish(),candidates:o(t({content:_l().nullish(),finishReason:e().nullish(),finishMessage:e().nullish(),continuationToken:e().nullish(),safetyRatings:o(er()).nullish(),groundingMetadata:ml().nullish(),urlContextMetadata:vl().nullish()})).nullish(),usageMetadata:Tl().nullish(),promptFeedback:t({blockReason:e().nullish(),safetyRatings:o(er()).nullish()}).nullish()})));function rl(h){return h!=null&&h!==""&&h!=="BLOCK_REASON_UNSPECIFIED"&&h!=="BLOCKED_REASON_UNSPECIFIED"}var og=u(()=>l(t({candidates:o(t({content:t({parts:o(t({inlineData:t({mimeType:e().nullish(),data:e().nullish()}).nullish()})).nullish()}).nullish()})).nullish(),usageMetadata:d(e(),Fe()).nullish()})));function ag({text:h,voice:f,providerOptions:g}){let y=g?.google,_=y!=null&&typeof y==="object"?y:void 0,T=_&&"turns"in _?_.turns:void 0,S=[];if(Array.isArray(T)&&T.length>0){for(let B of T){if(B==null||typeof B!=="object"||!("text"in B)||typeof B.text!=="string")break;S.push(B.text)}if(S.length===T.length)h=S.join("")}let w=_&&"multiSpeakerVoiceConfig"in _?_.multiSpeakerVoiceConfig:void 0,x=w!=null&&typeof w==="object"&&"speakerVoiceConfigs"in w&&Array.isArray(w.speakerVoiceConfigs)?w.speakerVoiceConfigs:[];return{text:h,usesCustomVoice:f?.startsWith("voice_")===!0||f?.startsWith("voicekey_")===!0||x.some((B)=>B!=null&&typeof B==="object"&&("voiceConfig"in B)&&B.voiceConfig!=null&&typeof B.voiceConfig==="object"&&("voice"in B.voiceConfig))}}var cg=()=>t({voiceName:e()}),lg=()=>t({prebuiltVoiceConfig:cg(),voice:le().optional()}),sl=()=>t({speaker:e().min(1).optional(),style:e().optional()}),il=u(()=>l(t({speechMetadata:sl().optional(),turns:o(t({text:e(),speechMetadata:sl().optional()})).min(1).optional(),multiSpeakerVoiceConfig:t({speakerVoiceConfigs:o(t({speaker:e(),voiceConfig:lg()}))}).optional()}))),ug="Kore",dg=24000,wl=class h{static[H](f){return te({modelId:f.modelId,config:f.config})}static[Q](f){return new h(f.modelId,f.config)}get provider(){return this.config.provider}constructor(f,g){this.modelId=f,this.config=g,this.specificationVersion="v4"}async getArgs({text:f,voice:g=ug,outputFormat:y,instructions:_,speed:T,language:S,providerOptions:w}){let x=[],B=this.config.provider.includes("vertex")?["googleVertex","vertex"]:["google"],P;for(let he of B)if(P=await k({provider:he,providerOptions:w,schema:il}),P!=null)break;if(P==null&&!B.includes("google"))P=await k({provider:"google",providerOptions:w,schema:il});let ne=!this.modelId.startsWith("gemini-2.5-")&&!this.modelId.startsWith("gemini-3.1-"),se=ag({text:f,voice:g,providerOptions:{google:P}});if(se.usesCustomVoice)throw new F({argument:"voice",message:"Custom voices are not supported. Use a prebuilt voice instead."});let X=P?.multiSpeakerVoiceConfig,z=X?{multiSpeakerVoiceConfig:X}:{voiceConfig:{prebuiltVoiceConfig:{voiceName:g}}},Z=f;if(_!=null&&!ne)if(X)x.push({type:"unsupported",feature:"instructions",details:"Google Gemini TTS ignores `instructions` when `multiSpeakerVoiceConfig` is set, because prepending them would break multi-speaker transcript parsing."});else Z=`${_}: ${f}`;let ue=[{text:Z}];if(ne){if(P?.turns&&P.speechMetadata)throw new F({argument:"providerOptions",message:"Set speechMetadata on each turn when using turns."});if(P?.turns&&f!=="")x.push({type:"unsupported",feature:"text",details:"Google TTS turns replace the top-level text."});ue=(P?.turns??[{text:f,speechMetadata:P?.speechMetadata}]).map((he)=>{let q=he.speechMetadata?.style??_,U=he.speechMetadata?.speaker;if(X&&!X.speakerVoiceConfigs.some((de)=>de.speaker===U))throw new F({argument:"speechMetadata.speaker",message:"Every multi-speaker turn must specify a speechMetadata.speaker matching a configured speaker."});return{text:he.text,...q!=null||U!=null?{speechMetadata:{style:q,speaker:U}}:{}}})}else if(P?.turns||P?.speechMetadata)throw new F({argument:"providerOptions",message:"Structured speech metadata and turns require Gemini 3.8 TTS."});if(se.text.length===0)throw new F({argument:"text",message:"Speech input must contain a non-empty transcript."});if(T!=null)x.push({type:"unsupported",feature:"speed",details:"Google Gemini TTS models do not support the `speed` option. It was ignored."});if(S!=null)x.push({type:"unsupported",feature:"language",details:"Google Gemini TTS models do not support the `language` option. Language is detected automatically from the input text."});let M=ne?{wav:"AUDIO_WAV","audio/wav":"AUDIO_WAV",pcm:"AUDIO_L16","audio/l16":"AUDIO_L16",mulaw:"AUDIO_MULAW","audio/mulaw":"AUDIO_MULAW",alaw:"AUDIO_ALAW","audio/alaw":"AUDIO_ALAW"}:{wav:"AUDIO_WAV",pcm:"AUDIO_L16"},L="wav";if(y!=null&&Object.prototype.hasOwnProperty.call(M,y))L=y;else if(y!=null)x.push({type:"unsupported",feature:"outputFormat",details:`Unsupported output format: ${y}. Using wav instead.`});return{requestBody:{contents:[{role:"user",parts:ue}],generationConfig:{responseModalities:["AUDIO"],speechConfig:z,...ne&&y!=null?{responseFormat:{audio:{mimeType:M[L]}}}:{}}},warnings:x,outputFormat:M[L],usesStructuredSpeech:ne}}async doGenerate(f){let g=this.config._internal?.currentDate?.()??new Date,{requestBody:y,warnings:_,outputFormat:T,usesStructuredSpeech:S}=await this.getArgs(f),{value:w,responseHeaders:x,rawValue:B}=await A({url:`${this.config.baseURL}/models/${this.modelId}:generateContent`,headers:I(this.config.headers?await W(this.config.headers):void 0,f.headers),body:y,failedResponseHandler:Bt,successfulResponseHandler:E(og),abortSignal:f.abortSignal,fetch:this.config.fetch}),P,ne;for(let ue of w.candidates??[]){for(let M of ue.content?.parts??[])if(M.inlineData?.data){P=M.inlineData.data,ne=M.inlineData.mimeType??void 0;break}if(P!=null)break}let se=hg(ne)??dg,X=P!=null?Te(P):new Uint8Array(0),z=/^audio\/(?:l16|pcm)(?:;|$)/i.test(ne??"")||ne==null&&!S,Z=T==="AUDIO_WAV"&&z&&X.length>0?pg(X,se):X;if(T==="AUDIO_L16"&&X.length>0&&!S)_.push({type:"unsupported",feature:"outputFormat",details:`Returning raw PCM audio (signed 16-bit little-endian, mono, ${se} Hz). These bytes have no container header and are not directly playable; see providerMetadata.google for the sample rate and mime type.`});return{audio:Z,warnings:_,...w.usageMetadata!=null&&{usage:w.usageMetadata},request:{body:JSON.stringify(y)},response:{timestamp:g,modelId:this.modelId,headers:x,body:B},providerMetadata:{google:{sampleRate:se,mimeType:ne??null}}}}};function hg(h){if(h==null)return;let f=/rate=(\d+)/.exec(h);return f?Number.parseInt(f[1],10):void 0}function pg(h,f){let T=f*2,S=h.length,w=new ArrayBuffer(44+S),x=new DataView(w);zn(x,0,"RIFF"),x.setUint32(4,36+S,!0),zn(x,8,"WAVE"),zn(x,12,"fmt "),x.setUint32(16,16,!0),x.setUint16(20,1,!0),x.setUint16(22,1,!0),x.setUint32(24,f,!0),x.setUint32(28,T,!0),x.setUint16(32,2,!0),x.setUint16(34,16,!0),zn(x,36,"data"),x.setUint32(40,S,!0);let B=new Uint8Array(w);return B.set(h,44),B}function zn(h,f,g){for(let y=0;y<g.length;y++)h.setUint8(f+y,g.charCodeAt(y))}var fg=G({id:"google.enterprise_web_search",inputSchema:u(()=>l(t({}))),outputSchema:u(()=>l(t({})))});u(()=>l(ae({fileSearchStoreNames:o(e()).describe("The names of the file_search_stores to retrieve from. Example: `fileSearchStores/my-file-search-store-123`"),topK:n().int().positive().describe("The number of file search retrieval chunks to retrieve.").optional(),metadataFilter:e().describe("Metadata filter to apply to the file search retrieval documents. See https://google.aip.dev/160 for the syntax of the filter expression.").optional()})));var gg=G({id:"google.file_search",inputSchema:u(()=>l(t({}))),outputSchema:u(()=>l(t({})))}),mg=G({id:"google.google_maps",inputSchema:u(()=>l(t({}))),outputSchema:u(()=>l(t({})))}),Vt={googleSearch:G({id:"google.google_search",inputSchema:u(()=>l(t({}))),outputSchema:u(()=>l(t({})))}),enterpriseWebSearch:fg,googleMaps:mg,urlContext:G({id:"google.url_context",inputSchema:u(()=>l(t({}))),outputSchema:u(()=>l(t({})))}),fileSearch:gg,codeExecution:kf,vertexRagStore:G({id:"google.vertex_rag_store",inputSchema:u(()=>l(t({}))),outputSchema:u(()=>l(t({})))})};function Rs(h){if(h==null)return Ct();let f=h.total_input_tokens??0,g=h.total_output_tokens??0,y=h.total_thought_tokens??0,_=h.total_cached_tokens??0;return{inputTokens:{total:h.total_input_tokens??void 0,noCache:h.total_input_tokens==null?void 0:f-_,cacheRead:h.total_cached_tokens??void 0,cacheWrite:void 0},outputTokens:{total:h.total_output_tokens==null&&h.total_thought_tokens==null?void 0:g+y,text:h.total_output_tokens??void 0,reasoning:h.total_thought_tokens??void 0},raw:h}}function El(h){let f=h?.output_tokens_by_modality;if(f==null)return;let g={};for(let y of f)if(y?.modality!=null&&y.tokens!=null)g[y.modality]=y.tokens;return Object.keys(g).length>0?g:void 0}var yg={pdf:"application/pdf",txt:"text/plain",md:"text/markdown",markdown:"text/markdown",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"};function Cl(h){let f=h.toLowerCase();for(let[g,y]of Object.entries(yg))if(f.endsWith(`.${g}`))return y;return"application/octet-stream"}function Al(h){let f=h.split("/"),g=f[f.length-1];return g&&g.length>0?g:void 0}function _g({annotation:h,generateId:f}){switch(h.type){case"url_citation":{let g=h;if(g.url==null||g.url.length===0)return;return{type:"source",sourceType:"url",id:f(),url:g.url,...g.title!=null?{title:g.title}:{}}}case"file_citation":{let g=h,y=g.url??g.document_uri??g.file_name;if(y==null||y.length===0)return;if(y.startsWith("http://")||y.startsWith("https://"))return{type:"source",sourceType:"url",id:f(),url:y,...g.file_name!=null?{title:g.file_name}:{}};let _=g.file_name??Al(y),T=Cl(y);return{type:"source",sourceType:"document",id:f(),mediaType:T,title:g.file_name??_??y,..._!=null?{filename:_}:{}}}case"place_citation":{let g=h;if(g.url==null||g.url.length===0)return;return{type:"source",sourceType:"url",id:f(),url:g.url,...g.name!=null?{title:g.name}:{}}}default:return}}function bl({block:h,generateId:f}){let g=[];switch(h.type){case"url_context_result":{let y=h.result??[];for(let _ of y){if(_?.url==null||_.url.length===0)continue;if(_.status!=null&&_.status!=="success")continue;g.push({type:"source",sourceType:"url",id:f(),url:_.url})}break}case"google_search_result":{let y=h.result??[];for(let _ of y){let T=_?.url;if(T==null||T.length===0)continue;g.push({type:"source",sourceType:"url",id:f(),url:T,..._.title!=null?{title:_.title}:{}})}break}case"google_maps_result":{let y=h.result??[];for(let _ of y)for(let T of _.places??[]){if(T.url==null||T.url.length===0)continue;g.push({type:"source",sourceType:"url",id:f(),url:T.url,...T.name!=null?{title:T.name}:{}})}break}case"file_search_result":{let y=h.result??[];for(let _ of y){if(_==null||typeof _!=="object")continue;let T=_,S=T.url??T.document_uri??T.file_name;if(S==null||S.length===0)continue;if(S.startsWith("http://")||S.startsWith("https://")){g.push({type:"source",sourceType:"url",id:f(),url:S,...T.title!=null?{title:T.title}:{}});continue}let w=T.file_name??Al(S),x=Cl(S);g.push({type:"source",sourceType:"document",id:f(),mediaType:x,title:T.title??T.file_name??w??S,...w!=null?{filename:w}:{}})}break}}return g}function Ss({annotations:h,generateId:f}){if(h==null)return[];let g=new Set,y=[];for(let _ of h){let T=_g({annotation:_,generateId:f});if(T==null)continue;let S=T.sourceType==="url"?`url:${T.url}`:`doc:${T.filename??T.title}`;if(g.has(S))continue;g.add(S),y.push(T)}return y}function Is({status:h,hasFunctionCall:f}){switch(h){case"completed":return f?"tool-calls":"stop";case"requires_action":return"tool-calls";case"failed":return"error";case"incomplete":return"length";case"cancelled":return"other";default:return"other"}}var Tg=new Set(["google_search_call","code_execution_call","url_context_call","file_search_call","google_maps_call","mcp_server_tool_call"]),vg=new Set(["google_search_result","code_execution_result","url_context_result","file_search_result","google_maps_result","mcp_server_tool_result"]);function wg(h){return h.replace(/_call$/,"")}function Eg(h){return h.replace(/_result$/,"")}function ol({warnings:h,generateId:f,includeRawChunks:g,serviceTier:y}){let _,T,S=y,w,x=!1,B=!1,P=new Map,ne=new Set;function se(X){return X.sourceType==="url"?`url:${X.url}`:`doc:${X.filename??X.title}`}return new TransformStream({start(X){X.enqueue({type:"stream-start",warnings:h})},transform(X,z){if(g)z.enqueue({type:"raw",rawValue:X.rawValue});if(!X.success){w="failed",z.enqueue({type:"error",error:X.error});return}let Z=X.value,ue=Z.event_type;switch(ue){case"interaction.created":{let M=Z.interaction;_=M?.id!=null&&M.id.length>0?M.id:void 0;let L=M?.created,he;if(typeof L==="string"){let q=new Date(L);if(!Number.isNaN(q.getTime()))he=q}z.enqueue({type:"response-metadata",..._!=null?{id:_}:{},modelId:M?.model,...he?{timestamp:he}:{}});break}case"step.start":{let M=Z,{step:L,index:he}=M,q=`${_??"interaction"}:${he}`,U=L?.type;if(U==="model_output"){let de=L?.content?.[0];if(de?.type==="text"){P.set(he,{kind:"text",id:q,emittedSourceKeys:new Set}),z.enqueue({type:"text-start",id:q});let ye=Ss({annotations:de.annotations,generateId:f});for(let Ce of ye){let _e=se(Ce);if(ne.has(_e))continue;ne.add(_e),z.enqueue(Ce)}}else if(de?.type==="image")P.set(he,{kind:"image",id:q,...de.data!=null?{data:de.data}:{},...de.mime_type!=null?{mimeType:de.mime_type}:{},...de.uri!=null?{uri:de.uri}:{}});else P.set(he,{kind:"pending_model_output",id:q})}else if(U==="thought"){let de=L?.signature;if(P.set(he,{kind:"reasoning",id:q,...de!=null?{signature:de}:{}}),z.enqueue({type:"reasoning-start",id:q}),Array.isArray(L?.summary)){for(let ye of L.summary)if(ye?.type==="text"&&typeof ye.text==="string")z.enqueue({type:"reasoning-delta",id:q,delta:ye.text})}}else if(U==="processing_call"||U==="processing_result"){let de={};if(L?.signature!=null)de.signature=L.signature;if(_!=null)de.interactionId=_;if(U==="processing_call")de.processingId=L?.id||q;else de.processingCallId=L?.call_id||q;P.set(he,{kind:"custom",id:q,customKind:`google.${U}`,google:de})}else if(U==="function_call"){let de=L?.id||q,ye=L?.name??"unknown";x=!0;let Ce={kind:"function_call",id:q,toolCallId:de,toolName:ye,argumentsAccum:"",...L?.signature!=null?{signature:L.signature}:{}};P.set(he,Ce),z.enqueue({type:"tool-input-start",id:de,toolName:ye})}else if(U!=null&&Tg.has(U)){let de=U==="mcp_server_tool_call"?L?.name??"mcp_server_tool":wg(U),ye={kind:"builtin_tool_call",id:q,blockType:U,toolCallId:L?.id||q,toolName:de,arguments:L?.arguments??{},callEmitted:!1};P.set(he,ye)}else if(U!=null&&vg.has(U)){let de=U==="mcp_server_tool_result"?L?.name??"mcp_server_tool":Eg(U),ye={kind:"builtin_tool_result",id:q,blockType:U,callId:L?.call_id||q,toolName:de,result:L?.result??null,...L?.is_error!=null?{isError:L.is_error}:{},resultEmitted:!1};P.set(he,ye)}else P.set(he,{kind:"unknown",id:q});break}case"step.delta":{let M=Z,L=P.get(M.index);if(L==null)break;let he=M.delta?.type;if(L.kind==="pending_model_output"){if(he==="text"||he==="text_annotation"||he==="text_annotation_delta"){let U={kind:"text",id:L.id,emittedSourceKeys:new Set};P.set(M.index,U),L=U,z.enqueue({type:"text-start",id:U.id})}}if(he==="image"&&(L.kind==="pending_model_output"||L.kind==="text"||L.kind==="image")){let U=M.delta,de={};if(_!=null)de.interactionId=_;let ye=Object.keys(de).length>0?{google:de}:void 0;if(U?.data!=null&&U.data.length>0)z.enqueue({type:"file",mediaType:U.mime_type??"image/png",data:{type:"data",data:U.data},...ye?{providerMetadata:ye}:{}});else if(U?.uri!=null&&U.uri.length>0)z.enqueue({type:"file",mediaType:U.mime_type??"image/png",data:{type:"url",url:new URL(U.uri)},...ye?{providerMetadata:ye}:{}});if(L.kind==="image")L.data=void 0,L.uri=void 0;break}if(he==="video"&&(L.kind==="pending_model_output"||L.kind==="text")){let U=M.delta,de={};if(_!=null)de.interactionId=_;let ye=Object.keys(de).length>0?{google:de}:void 0;if(U?.data!=null&&U.data.length>0)z.enqueue({type:"file",mediaType:U.mime_type??"video/mp4",data:{type:"data",data:U.data},...ye?{providerMetadata:ye}:{}});else if(U?.uri!=null&&U.uri.length>0)z.enqueue({type:"file",mediaType:U.mime_type??"video/mp4",data:{type:"url",url:new URL(U.uri)},...ye?{providerMetadata:ye}:{}});break}let q=M.delta;if(L.kind==="custom"&&(q?.type==="processing_call"||q?.type==="processing_result")){if(q.signature!=null)L.google.signature=q.signature;if(q.type==="processing_call"&&q.id!=null&&q.id.length>0)L.google.processingId=q.id;if(q.type==="processing_result"&&q.call_id!=null&&q.call_id.length>0)L.google.processingCallId=q.call_id}else if(L.kind==="text"&&q?.type==="text"){let U=q.text??"";if(U.length>0)z.enqueue({type:"text-delta",id:L.id,delta:U})}else if(L.kind==="text"&&(q?.type==="text_annotation"||q?.type==="text_annotation_delta")){let U=Ss({annotations:q.annotations,generateId:f});for(let de of U){let ye=se(de);if(ne.has(ye))continue;ne.add(ye),L.emittedSourceKeys.add(ye),z.enqueue(de)}}else if(L.kind==="image"&&q?.type==="image"){if(q.data!=null)L.data=q.data;if(q.mime_type!=null)L.mimeType=q.mime_type;if(q.uri!=null)L.uri=q.uri}else if(L.kind==="reasoning"){if(q?.type==="thought_summary"){let U=q.content;if(U?.type==="text"&&typeof U.text==="string")z.enqueue({type:"reasoning-delta",id:L.id,delta:U.text})}else if(q?.type==="thought_signature"){let U=q.signature;if(U!=null)L.signature=U}}else if(L.kind==="function_call"&&q?.type==="arguments_delta"){let U=typeof q.arguments==="string"?q.arguments:"";if(U.length>0)L.argumentsAccum+=U,z.enqueue({type:"tool-input-delta",id:L.toolCallId,delta:U});if(q.id!=null&&q.id.length>0)L.toolCallId=q.id;if(q.signature!=null)L.signature=q.signature;x=!0}else if(L.kind==="builtin_tool_call"&&q?.type===L.blockType){if(q.id!=null&&q.id.length>0)L.toolCallId=q.id;if(q.arguments!=null&&typeof q.arguments==="object")L.arguments=q.arguments;if(q.name!=null&&L.blockType==="mcp_server_tool_call")L.toolName=q.name}else if(L.kind==="builtin_tool_result"&&q?.type===L.blockType){if(q.call_id!=null&&q.call_id.length>0)L.callId=q.call_id;if(q.result!==void 0)L.result=q.result;if(q.is_error!=null)L.isError=q.is_error;if(q.name!=null&&L.blockType==="mcp_server_tool_result")L.toolName=q.name}break}case"step.stop":{let M=Z,L=P.get(M.index);if(L==null)break;if(L.kind==="text"){let he=_!=null?{google:{interactionId:_}}:void 0;z.enqueue({type:"text-end",id:L.id,...he?{providerMetadata:he}:{}})}else if(L.kind==="reasoning"){let he={};if(L.signature!=null)he.signature=L.signature;if(_!=null)he.interactionId=_;let q=Object.keys(he).length>0?{google:he}:void 0;z.enqueue({type:"reasoning-end",id:L.id,...q?{providerMetadata:q}:{}})}else if(L.kind==="image"){let he={};if(_!=null)he.interactionId=_;let q=Object.keys(he).length>0?{google:he}:void 0;if(L.data!=null&&L.data.length>0)z.enqueue({type:"file",mediaType:L.mimeType??"image/png",data:{type:"data",data:L.data},...q?{providerMetadata:q}:{}});else if(L.uri!=null&&L.uri.length>0)z.enqueue({type:"file",mediaType:L.mimeType??"image/png",data:{type:"url",url:new URL(L.uri)},...q?{providerMetadata:q}:{}})}else if(L.kind==="function_call"){let he=L.argumentsAccum.length>0?L.argumentsAccum:"{}";z.enqueue({type:"tool-input-end",id:L.toolCallId});let q={};if(L.signature!=null)q.signature=L.signature;if(_!=null)q.interactionId=_;let U=Object.keys(q).length>0?{google:q}:void 0;z.enqueue({type:"tool-call",toolCallId:L.toolCallId,toolName:L.toolName,input:he,...U?{providerMetadata:U}:{}})}else if(L.kind==="custom")z.enqueue({type:"custom",kind:L.customKind,providerMetadata:{google:L.google}});else if(L.kind==="builtin_tool_call"&&!L.callEmitted)z.enqueue({type:"tool-call",toolCallId:L.toolCallId,toolName:L.toolName,input:JSON.stringify(L.arguments??{}),providerExecuted:!0}),L.callEmitted=!0;else if(L.kind==="builtin_tool_result"&&!L.resultEmitted){z.enqueue({type:"tool-result",toolCallId:L.callId,toolName:L.toolName,result:L.result??null}),L.resultEmitted=!0;let he=bl({block:{type:L.blockType,call_id:L.callId,result:L.result},generateId:f});for(let q of he){let U=se(q);if(ne.has(U))continue;ne.add(U),z.enqueue(q)}}P.delete(M.index);break}case"interaction.status_update":case"interaction.in_progress":case"interaction.requires_action":{let M=Z;if(M.status!=null)w=M.status;else if(ue==="interaction.requires_action")w="requires_action";else w="in_progress";break}case"interaction.completed":{B=!0;let M=Z.interaction;if(M?.id!=null&&M.id.length>0)_=M.id;if(M?.status!=null)w=M.status;if(M?.usage!=null)T=M.usage;if(M?.service_tier!=null)S=M.service_tier;break}case"error":{let M=Z;w="failed",z.enqueue({type:"error",error:Ht({message:M.error?.message??"Unknown interaction error",type:M.event_type,code:M.error?.code??void 0,data:M})});break}}},flush(X){let z=!B&&(w==null||w==="in_progress"),Z={unified:z?"interrupted":Is({status:w,hasFunctionCall:x}),raw:z?void 0:w},ue=El(T),M={google:{..._!=null?{interactionId:_}:{},...S!=null?{serviceTier:S}:{},...ue!=null?{outputTokensByModality:ue}:{}}};X.enqueue({type:"finish",finishReason:Z,usage:Rs(T),providerMetadata:M})}})}function Cg({prompt:h,previousInteractionId:f,store:g,mediaResolution:y}){let _=[],T=f!=null&&g===!1,S=f!=null&&g!==!1;if(T)_.push({type:"other",message:"google.interactions: providerOptions.google.previousInteractionId was set together with store: false. These are incoherent (the prior interaction cannot be referenced when nothing was stored on the server); the full history will be sent and previous_interaction_id will still be emitted."});let w=S?bg({prompt:h,previousInteractionId:f}):h,x=[],B=[];for(let P of w)switch(P.role){case"system":x.push(P.content);break;case"user":{let ne=[];for(let X of P.content)if(X.type==="text")ne.push({type:"text",text:X.text});else if(X.type==="file"){let z=al({part:X,warnings:_,mediaResolution:y});if(z!=null)ne.push(z)}let se=Og(ne);if(se.length>0)B.push({type:"user_input",content:se});break}case"assistant":{let ne=[],se=()=>{if(ne.length>0)B.push({type:"model_output",content:ne}),ne=[]};for(let X of P.content)if(X.type==="text")ne.push({type:"text",text:X.text});else if(X.type==="reasoning"){se();let z=X.providerOptions?.google?.signature;B.push({type:"thought",...z!=null?{signature:z}:{},summary:X.text.length>0?[{type:"text",text:X.text}]:void 0})}else if(X.type==="file"){let z=al({part:X,warnings:_,mediaResolution:y});if(z!=null)ne.push(z)}else if(X.type==="custom"){se();let z=X.providerOptions?.google,Z=typeof z?.signature==="string"?z.signature:void 0;if(X.kind==="google.processing_call"&&typeof z?.processingId==="string")B.push({type:"processing_call",id:z.processingId,...Z!=null?{signature:Z}:{}});else if(X.kind==="google.processing_result"&&typeof z?.processingCallId==="string")B.push({type:"processing_result",call_id:z.processingCallId,...Z!=null?{signature:Z}:{}});else _.push({type:"other",message:`google.interactions: unsupported or invalid custom assistant content part "${X.kind}"; part dropped.`})}else if(X.type==="tool-call"){se();let z=X.providerOptions?.google?.signature,Z=typeof X.input==="string"?Sg(X.input):X.input??{};B.push({type:"function_call",id:X.toolCallId,name:X.toolName,arguments:Z,...z!=null?{signature:z}:{}})}else _.push({type:"other",message:`google.interactions: unsupported assistant content part type "${X.type}"; part dropped.`});se();break}case"tool":{let ne=[];for(let se of P.content){if(se.type!=="tool-result"){_.push({type:"other",message:`google.interactions: unsupported tool message part type "${se.type}"; part dropped.`});continue}let X=kg({toolCallId:se.toolCallId,toolName:se.toolName,output:se.output,signature:se.providerOptions?.google?.signature,warnings:_});ne.push(X)}if(ne.length>0)B.push({type:"user_input",content:ne});break}}return{input:B,systemInstruction:x.length>0?x.join(`
|
|
34
|
+
|
|
35
|
+
`):void 0,warnings:_}}function al({part:h,warnings:f,mediaResolution:g}){if(h.data.type==="text")return{type:"text",text:h.data.text};let y=ge(h.mediaType),_;switch(y){case"image":_="image";break;case"audio":_="audio";break;case"video":_="video";break;case"application":case"text":_="document";break;default:_=void 0}if(_==null){f.push({type:"other",message:`google.interactions: unsupported file media type "${h.mediaType}"; part dropped.`});return}let T=g!=null&&(_==="image"||_==="video")?{resolution:g}:{},S=_==="video"?Ag({part:h,warnings:f}):{};switch(h.data.type){case"data":{let w=ee({part:h});return{type:_,data:j(h.data.data),mime_type:w,...T,...S}}case"url":return{type:_,uri:h.data.url.toString(),...Ae(h.mediaType)?{mime_type:h.mediaType}:{},...T,...S};case"reference":{let w=$e({reference:h.data.reference,provider:"google"});return{type:_,uri:w,...Ae(h.mediaType)?{mime_type:h.mediaType}:{},...T,...S}}}}function Ag({part:h,warnings:f}){let g=h.providerOptions?.google?.processing;if(g==null)return{};if(g==="agentic"||g==="static")return{processing:g};if(typeof g==="object"&&!Array.isArray(g)&&g.type==="static"){let y=g;return{processing:{type:"static",...typeof y.startOffset==="number"?{start_offset:`${y.startOffset}s`}:{},...typeof y.endOffset==="number"?{end_offset:`${y.endOffset}s`}:{},...typeof y.fps==="number"?{fps:y.fps}:{}}}}return f.push({type:"other",message:'google.interactions: invalid providerOptions.google.processing on video file part; expected "agentic", "static", or a static processing configuration. Option dropped.'}),{}}function bg({prompt:h,previousInteractionId:f}){let g=[],y=new Set;for(let _ of h){if(_.role==="assistant"){if(_.content.some((T)=>T.providerOptions?.google?.interactionId===f)){for(let T of _.content)if(T.type==="tool-call")y.add(T.toolCallId);continue}g.push(_);continue}if(_.role==="tool"){let T=_.content.filter((S)=>{if(S.type!=="tool-result")return!0;return!y.has(S.toolCallId)});if(T.length===0)continue;g.push({..._,content:T});continue}g.push(_)}return g}function Sg(h){try{let f=Ke(h);if(f!=null&&typeof f==="object"&&!Array.isArray(f))return f;return{value:f}}catch{return{value:h}}}function kg({toolCallId:h,toolName:f,output:g,signature:y,warnings:_}){let T={type:"function_result",call_id:h,name:f,...y!=null?{signature:y}:{}};switch(g.type){case"text":return{...T,result:g.value};case"json":return{...T,result:JSON.stringify(g.value)};case"error-text":return{...T,is_error:!0,result:g.value};case"error-json":return{...T,is_error:!0,result:JSON.stringify(g.value)};case"execution-denied":return{...T,is_error:!0,result:g.reason??"Tool execution denied by user."};case"content":{let S=[];for(let w of g.value)if(w.type==="text")S.push({type:"text",text:w.text});else if(w.type==="file"){if(ge(w.mediaType)!=="image"){_.push({type:"other",message:`google.interactions: tool-result file with mediaType "${w.mediaType}" is not supported (Interactions \`function_result.result\` accepts only text and image content); part dropped.`});continue}let x=xg({part:w,warnings:_});if(x!=null)S.push(x)}else _.push({type:"other",message:`google.interactions: tool-result content part type "${w.type}" is not supported; part dropped.`});return{...T,result:S}}}}function xg({part:h,warnings:f}){switch(h.data.type){case"data":{let g=Ae(h.mediaType)?h.mediaType:ee({part:{type:"file",mediaType:h.mediaType,data:h.data}});return{type:"image",data:j(h.data.data),mime_type:g}}case"url":return{type:"image",uri:h.data.url.toString(),...Ae(h.mediaType)?{mime_type:h.mediaType}:{}};case"reference":return{type:"image",uri:$e({reference:h.data.reference,provider:"google"}),...Ae(h.mediaType)?{mime_type:h.mediaType}:{}};case"text":f.push({type:"other",message:'google.interactions: tool-result image part with `data.type === "text"` is not representable as an image; part dropped.'});return}}function Og(h){if(h.length<2)return h;let f=[];for(let g of h){let y=f[f.length-1];if(g.type==="text"&&y!=null&&y.type==="text"&&y.annotations==null&&g.annotations==null){let _={type:"text",text:`${y.text}
|
|
36
|
+
|
|
37
|
+
${g.text}`};f[f.length-1]=_;continue}f.push(g)}return f}var Qn=()=>t({modality:e().nullish(),tokens:n().nullish()}).loose(),Sl=()=>t({total_input_tokens:n().nullish(),total_output_tokens:n().nullish(),total_thought_tokens:n().nullish(),total_cached_tokens:n().nullish(),total_tool_use_tokens:n().nullish(),total_tokens:n().nullish(),input_tokens_by_modality:o(Qn()).nullish(),output_tokens_by_modality:o(Qn()).nullish(),cached_tokens_by_modality:o(Qn()).nullish(),tool_use_tokens_by_modality:o(Qn()).nullish(),grounding_tool_count:o(t({type:e().nullish(),count:n().nullish()}).loose()).nullish()}).loose(),kl=()=>s(["in_progress","requires_action","completed","failed","cancelled","incomplete"]),xl=()=>{let h=t({type:a("url_citation"),url:e().nullish(),title:e().nullish(),start_index:n().nullish(),end_index:n().nullish()}).loose(),f=t({type:a("file_citation"),file_name:e().nullish(),document_uri:e().nullish(),url:e().nullish(),page_number:n().nullish(),media_id:e().nullish(),start_index:n().nullish(),end_index:n().nullish(),custom_metadata:d(e(),m()).nullish()}).loose(),g=t({type:a("place_citation"),name:e().nullish(),url:e().nullish(),place_id:e().nullish(),start_index:n().nullish(),end_index:n().nullish()}).loose();return p([h,f,g,t({type:e()}).loose()])},Ol=()=>t({type:e(),text:e().nullish(),data:e().nullish(),mime_type:e().nullish()}).loose(),cl=()=>{let h=t({type:a("text"),text:e(),annotations:o(xl()).nullish()}).loose(),f=t({type:a("image"),data:e().nullish(),mime_type:e().nullish(),resolution:s(["low","medium","high","ultra_high"]).nullish(),uri:e().nullish()}).loose(),g=t({type:a("video"),data:e().nullish(),mime_type:e().nullish(),uri:e().nullish()}).loose();return p([h,f,g,t({type:e()}).loose()])},Rl=["google_search_call","code_execution_call","url_context_call","file_search_call","google_maps_call","mcp_server_tool_call"],Il=["google_search_result","code_execution_result","url_context_result","file_search_result","google_maps_result","mcp_server_tool_result"],Nl=()=>{let h=t({type:a("user_input"),content:o(cl()).nullish()}).loose(),f=t({type:a("model_output"),content:o(cl()).nullish()}).loose(),g=t({type:a("function_call"),id:e(),name:e(),arguments:d(e(),m()).nullish(),signature:e().nullish()}).loose(),y=t({type:a("thought"),signature:e().nullish(),summary:o(Ol()).nullish()}).loose(),_=t({type:a("processing_call"),id:e(),signature:e().nullish()}).loose(),T=t({type:a("processing_result"),call_id:e(),signature:e().nullish()}).loose(),S=t({type:s(Rl),id:e(),arguments:d(e(),m()).nullish(),name:e().nullish(),server_name:e().nullish(),search_type:e().nullish(),signature:e().nullish()}).loose(),w=t({type:s(Il),call_id:e(),result:m().nullish(),is_error:r().nullish(),name:e().nullish(),server_name:e().nullish(),signature:e().nullish()}).loose();return p([h,f,g,y,_,T,S,w,t({type:e()}).loose()])},ks=u(()=>l(t({id:e().nullish(),created:e().nullish(),updated:e().nullish(),status:kl(),model:e().nullish(),agent:e().nullish(),steps:o(Nl()).nullish(),usage:Sl().nullish(),service_tier:e().nullish(),previous_interaction_id:e().nullish(),response_modalities:o(e()).nullish()}).loose())),Pl=u(()=>l((()=>{let h=kl(),f=xl(),g=Ol(),y=t({event_type:a("interaction.created"),event_id:e().nullish(),interaction:t({id:e().nullish(),created:e().nullish(),model:e().nullish(),agent:e().nullish(),status:h.nullish()}).loose()}).loose(),_=t({event_type:a("step.start"),event_id:e().nullish(),index:n(),step:Nl()}).loose(),T=t({type:a("text"),text:e()}).loose(),S=t({type:a("thought_summary"),content:g.nullish()}).loose(),w=t({type:a("thought_signature"),signature:e().nullish()}).loose(),x=t({type:a("arguments_delta"),arguments:e().nullish(),id:e().nullish(),signature:e().nullish()}).loose(),B=t({type:s(["text_annotation_delta","text_annotation"]),annotations:o(f).nullish()}).loose(),P=t({type:a("image"),data:e().nullish(),mime_type:e().nullish(),resolution:s(["low","medium","high","ultra_high"]).nullish(),uri:e().nullish()}).loose(),ne=t({type:a("video"),data:e().nullish(),mime_type:e().nullish(),uri:e().nullish()}).loose(),se=t({type:s(Rl),id:e().nullish(),arguments:d(e(),m()).nullish(),name:e().nullish(),server_name:e().nullish(),search_type:e().nullish(),signature:e().nullish()}).loose(),X=t({type:s(Il),call_id:e().nullish(),result:m().nullish(),is_error:r().nullish(),name:e().nullish(),server_name:e().nullish(),signature:e().nullish()}).loose(),z=t({type:e()}).loose(),Z=p([T,P,ne,S,w,x,B,se,X,z]),ue=t({event_type:a("step.delta"),event_id:e().nullish(),index:n(),delta:Z}).loose(),M=t({event_type:a("step.stop"),event_id:e().nullish(),index:n()}).loose(),L=t({event_type:a("interaction.status_update"),event_id:e().nullish(),interaction_id:e().nullish(),status:h.nullish()}).loose(),he=t({event_type:a("interaction.in_progress"),event_id:e().nullish(),interaction_id:e().nullish(),status:h.nullish()}).loose(),q=t({event_type:a("interaction.requires_action"),event_id:e().nullish(),interaction_id:e().nullish(),status:h.nullish()}).loose(),U=t({event_type:a("interaction.completed"),event_id:e().nullish(),interaction:t({id:e().nullish(),status:h.nullish(),usage:Sl().nullish(),service_tier:e().nullish()}).loose()}).loose(),de=t({event_type:a("error"),event_id:e().nullish(),error:t({code:e().nullish(),message:e().nullish()}).loose().nullish()}).loose(),ye=t({event_type:e()}).loose();return p([y,_,ue,M,L,he,q,U,de,ye])})())),Rg=u(()=>l(t({previousInteractionId:e().nullish(),store:r().nullish(),agent:e().nullish(),agentConfig:p([t({type:a("dynamic")}).loose(),t({type:a("deep-research"),thinkingSummaries:s(["auto","none"]).nullish(),visualization:s(["off","auto"]).nullish(),collaborativePlanning:r().nullish()})]).nullish(),thinkingLevel:s(["minimal","low","medium","high"]).nullish(),thinkingSummaries:s(["auto","none"]).nullish(),responseFormat:o(p([t({type:a("text"),mimeType:e().nullish(),schema:m().nullish()}).loose(),t({type:a("image"),mimeType:e().nullish(),aspectRatio:s(["1:1","2:3","3:2","3:4","4:3","4:5","5:4","9:16","16:9","21:9","1:8","8:1","1:4","4:1"]).nullish(),imageSize:s(["1K","2K","4K","512"]).nullish()}).loose(),t({type:a("audio"),mimeType:e().nullish()}).loose(),t({type:a("video"),aspectRatio:s(["16:9","9:16"]).nullish(),resolution:s(["360p","720p","1080p","4k"]).nullish(),duration:e().nullish(),delivery:s(["inline","uri"]).nullish(),gcsUri:e().nullish()}).loose()])).nullish(),imageConfig:t({aspectRatio:s(["1:1","2:3","3:2","3:4","4:3","4:5","5:4","9:16","16:9","21:9","1:8","8:1","1:4","4:1"]).nullish(),imageSize:s(["1K","2K","4K","512"]).nullish()}).nullish(),mediaResolution:s(["low","medium","high","ultra_high"]).nullish(),responseModalities:o(s(["text","image","audio","video","document"])).nullish(),serviceTier:s(["flex","standard","priority"]).nullish(),systemInstruction:e().nullish(),signature:e().nullish(),interactionId:e().nullish(),pollingTimeoutMs:n().int().positive().nullish(),background:r().nullish(),environment:p([e(),t({type:a("remote"),sources:o(p([t({type:a("gcs"),source:e(),target:e().nullish()}),t({type:a("repository"),source:e(),target:e().nullish()}),t({type:a("inline"),content:e(),target:e()})])).nullish(),network:p([a("disabled"),t({allowlist:o(t({domain:e(),transform:o(d(e(),e())).nullish()}))})]).nullish()})]).nullish()})));function qt({signature:h,interactionId:f,processingId:g,processingCallId:y}){let _={};if(h!=null)_.signature=h;if(f!=null)_.interactionId=f;if(g!=null)_.processingId=g;if(y!=null)_.processingCallId=y;return Object.keys(_).length>0?{providerMetadata:{google:_}}:{}}var Ig=new Set(["google_search_call","code_execution_call","url_context_call","file_search_call","google_maps_call","mcp_server_tool_call"]),Ng=new Set(["google_search_result","code_execution_result","url_context_result","file_search_result","google_maps_result","mcp_server_tool_result"]);function Pg(h){return h.replace(/_call$/,"")}function jg(h){return h.replace(/_result$/,"")}function jl({steps:h,generateId:f,interactionId:g}){let y=[],_=!1;if(h==null)return{content:y,hasFunctionCall:_};for(let T of h){if(T==null||typeof T!=="object")continue;let S=T.type;if(typeof S!=="string")continue;switch(S){case"user_input":break;case"model_output":{let w=T.content??[];for(let x of w){if(x==null||typeof x!=="object")continue;let B=x.type;if(B==="text"){let P=x.text??"",ne=x.annotations;y.push({type:"text",text:P,...qt({interactionId:g})});let se=Ss({annotations:ne,generateId:f});for(let X of se)y.push(X)}else if(B==="image"){let P=x;if(P.data!=null&&P.data.length>0)y.push({type:"file",mediaType:P.mime_type??"image/png",data:{type:"data",data:P.data},...qt({interactionId:g})});else if(P.uri!=null&&P.uri.length>0)y.push({type:"file",mediaType:P.mime_type??"image/png",data:{type:"url",url:new URL(P.uri)},...qt({interactionId:g})})}else if(B==="video"){let P=x;if(P.data!=null&&P.data.length>0)y.push({type:"file",mediaType:P.mime_type??"video/mp4",data:{type:"data",data:P.data},...qt({interactionId:g})});else if(P.uri!=null&&P.uri.length>0)y.push({type:"file",mediaType:P.mime_type??"video/mp4",data:{type:"url",url:new URL(P.uri)},...qt({interactionId:g})})}}break}case"thought":{let w=T,x=(Array.isArray(w.summary)?w.summary:[]).filter((B)=>B?.type==="text"&&typeof B.text==="string").map((B)=>B.text).join(`
|
|
38
|
+
`);y.push({type:"reasoning",text:x,...qt({signature:w.signature,interactionId:g})});break}case"processing_call":{let w=T,x=w.id||f();y.push({type:"custom",kind:"google.processing_call",...qt({signature:w.signature,interactionId:g,processingId:x})});break}case"processing_result":{let w=T,x=w.call_id||f();y.push({type:"custom",kind:"google.processing_result",...qt({signature:w.signature,interactionId:g,processingCallId:x})});break}case"function_call":{_=!0;let w=T;y.push({type:"tool-call",toolCallId:w.id,toolName:w.name,input:JSON.stringify(w.arguments??{}),...qt({signature:w.signature,interactionId:g})});break}default:if(Ig.has(S)){let w=T,x=S==="mcp_server_tool_call"?w.name??"mcp_server_tool":Pg(S),B=JSON.stringify(w.arguments??{});y.push({type:"tool-call",toolCallId:w.id||f(),toolName:x,input:B,providerExecuted:!0})}else if(Ng.has(S)){let w=T,x=S==="mcp_server_tool_result"?w.name??"mcp_server_tool":jg(S);y.push({type:"tool-result",toolCallId:w.call_id||f(),toolName:x,result:w.result??null});let B=bl({block:T,generateId:f});for(let P of B)y.push(P)}}}return{content:y,hasFunctionCall:_}}var Ug=()=>globalThis.fetch;async function Ul({baseURL:h,interactionId:f,headers:g,fetch:y=Ug()}){if(f==null||f.length===0)return;let _=`${h}/interactions/${encodeURIComponent(f)}/cancel`;try{let T=await y(_,{method:"POST",headers:Se(I({"Content-Type":"application/json"},g),Ai()),body:"{}"});try{await T.text()}catch{}}catch{}}var Mg=new Set(["completed","failed","cancelled","incomplete"]);function xs(h){return h!=null&&Mg.has(h)}var Dg=1000,qg=1e4,Lg=1800000;async function Fg({baseURL:h,interactionId:f,headers:g,fetch:y,abortSignal:_,initialDelayMs:T=Dg,maxDelayMs:S=qg,timeoutMs:w=Lg}){if(f==null||f.length===0)throw Error("google.interactions: cannot poll a background interaction without an id. The POST response did not include an interaction id.");let x=Date.now(),B=T,P=`${h}/interactions/${encodeURIComponent(f)}`,ne=()=>Ul({baseURL:h,interactionId:f,headers:g,fetch:y});try{while(!0){if(_?.aborted)throw await ne(),new DOMException("Polling was aborted","AbortError");if(Date.now()-x>w)throw Error(`google.interactions: timed out polling interaction ${f} after ${w}ms.`);await Oi(B,{abortSignal:_});let{value:se,rawValue:X,responseHeaders:z}=await De({url:P,validateUrl:!1,headers:g,failedResponseHandler:Bt,successfulResponseHandler:E(ks),abortSignal:_,fetch:y});if(xs(se.status))return{response:se,rawResponse:X,responseHeaders:z};B=Math.min(B*2,S)}}catch(se){if(Me(se))await ne();throw se}}function Gg({tools:h,toolChoice:f}){let g=[],y=h?.length?h:void 0;if(y==null)return{tools:void 0,toolChoice:void 0,toolWarnings:g};let _=[];for(let w of y){if(w.type==="function"){_.push({type:"function",name:w.name,description:w.description??"",parameters:w.inputSchema});continue}if(w.type==="provider"){let x=w.args??{};switch(w.id){case"google.google_search":{let B=x.searchTypes,P;if(B!=null&&typeof B==="object"){let ne=[];if(B.webSearch!=null)ne.push("web_search");if(B.imageSearch!=null)ne.push("image_search");if(ne.length>0)P=ne}_.push({type:"google_search",...P!=null?{search_types:P}:{}});break}case"google.code_execution":_.push({type:"code_execution"});break;case"google.url_context":_.push({type:"url_context"});break;case"google.file_search":_.push({type:"file_search",...x.fileSearchStoreNames!=null?{file_search_store_names:x.fileSearchStoreNames}:{},...x.topK!=null?{top_k:x.topK}:{},...x.metadataFilter!=null?{metadata_filter:x.metadataFilter}:{}});break;case"google.google_maps":_.push({type:"google_maps",...x.latitude!=null?{latitude:x.latitude}:{},...x.longitude!=null?{longitude:x.longitude}:{},...x.enableWidget!=null?{enable_widget:x.enableWidget}:{}});break;case"google.computer_use":_.push({type:"computer_use",environment:x.environment??"browser",...x.excludedPredefinedFunctions!=null?{excludedPredefinedFunctions:x.excludedPredefinedFunctions}:{}});break;case"google.mcp_server":_.push({type:"mcp_server",...x.name!=null?{name:x.name}:{},...x.url!=null?{url:x.url}:{},...x.headers!=null?{headers:x.headers}:{},...x.allowedTools!=null?{allowed_tools:x.allowedTools}:{}});break;case"google.retrieval":{let B=x.vertexAiSearchConfig??void 0;_.push({type:"retrieval",...x.retrievalTypes!=null?{retrieval_types:x.retrievalTypes}:{retrieval_types:["vertex_ai_search"]},...B!=null?{vertex_ai_search_config:B}:{}});break}default:g.push({type:"unsupported",feature:`provider-defined tool ${w.id}`,details:`provider-defined tool ${w.id} is not supported by google.interactions; tool dropped.`})}continue}g.push({type:"unsupported",feature:`tool of type ${w.type}`,details:"Only function tools and google.* provider-defined tools are supported by google.interactions; tool dropped."})}let T=_.some((w)=>w.type==="function"),S;if(f!=null&&T)switch(f.type){case"auto":S="auto";break;case"required":S="any";break;case"none":S="none";break;case"tool":S={allowed_tools:{mode:"validated",tools:[f.toolName]}}}return{tools:_.length>0?_:void 0,toolChoice:S,toolWarnings:g}}var $g=3,Hg=500;function Bg({baseURL:h,interactionId:f,headers:g,fetch:y,abortSignal:_,maxRetries:T=$g,retryDelayMs:S=Hg}){if(f.length===0)throw Error("google.interactions: cannot stream a background interaction without an id.");let w={...g,accept:"text/event-stream"},x,B=!1,P=0,ne=!1,se,X=new AbortController,z=()=>X.abort();if(_!=null)if(_.aborted)X.abort();else _.addEventListener("abort",z,{once:!0});let Z=X.signal;function ue(){let L=`${h}/interactions/${encodeURIComponent(f)}`,he=new URLSearchParams({stream:"true"});if(x!=null)he.set("last_event_id",x);return`${L}?${he.toString()}`}async function M(){let{value:L}=await De({url:ue(),validateUrl:!1,headers:w,failedResponseHandler:Bt,successfulResponseHandler:qe(Pl),abortSignal:Z,fetch:y});return L.getReader()}return new ReadableStream({async start(L){try{while(!B&&!Z.aborted){if(se==null)try{se=await M(),ne=!1}catch(he){if(Me(he)||Z.aborted){L.error(he);return}if(P++,P>=T){L.error(he);return}await Oi(S*P,{abortSignal:Z});continue}try{let{done:he,value:q}=await se.read();if(he){if(se=void 0,B)break;if(!ne){if(P++,P>=T){L.error(Error("google.interactions: SSE stream closed without producing any events."));return}await Oi(S*P,{abortSignal:Z})}else P=0;continue}if(ne=!0,q.success){let U=q.value;if(typeof U.event_id==="string"&&U.event_id.length>0)x=U.event_id;if(U.event_type==="interaction.completed"||U.event_type==="error")B=!0}L.enqueue(q)}catch(he){if(Me(he)||Z.aborted){L.error(he);return}if(se=void 0,P++,P>=T){L.error(he);return}await Oi(S*P,{abortSignal:Z})}}L.close()}catch(he){L.error(he)}finally{if(_!=null)_.removeEventListener("abort",z);if(se?.cancel().catch(()=>{}),se=void 0,Z.aborted&&!B)await Ul({baseURL:h,interactionId:f,headers:g,fetch:y})}},cancel(){X.abort(),se?.cancel().catch(()=>{}),se=void 0}})}function Vg({response:h,warnings:f,generateId:g,includeRawChunks:y,headerServiceTier:_}){return new ReadableStream({start(T){T.enqueue({type:"stream-start",warnings:f});let S=typeof h.id==="string"&&h.id.length>0?h.id:void 0,w,x=h.created;if(typeof x==="string"){let ue=new Date(x);if(!Number.isNaN(ue.getTime()))w=ue}if(T.enqueue({type:"response-metadata",...S!=null?{id:S}:{},modelId:h.model??void 0,...w?{timestamp:w}:{}}),y)T.enqueue({type:"raw",rawValue:h});let{content:B,hasFunctionCall:P}=jl({steps:h.steps??null,generateId:g,interactionId:S}),ne=0,se=()=>`${S??"agent"}:${ne++}`;for(let ue of B)switch(ue.type){case"text":{let M=se(),L=ue.providerMetadata;if(T.enqueue({type:"text-start",id:M}),ue.text.length>0)T.enqueue({type:"text-delta",id:M,delta:ue.text});T.enqueue({type:"text-end",id:M,...L?{providerMetadata:L}:{}});break}case"reasoning":{let M=se(),L=ue.providerMetadata;if(T.enqueue({type:"reasoning-start",id:M}),ue.text.length>0)T.enqueue({type:"reasoning-delta",id:M,delta:ue.text});T.enqueue({type:"reasoning-end",id:M,...L?{providerMetadata:L}:{}});break}case"tool-call":{let M=ue.providerMetadata;T.enqueue({type:"tool-input-start",id:ue.toolCallId,toolName:ue.toolName,...ue.providerExecuted?{providerExecuted:ue.providerExecuted}:{}}),T.enqueue({type:"tool-input-delta",id:ue.toolCallId,delta:ue.input}),T.enqueue({type:"tool-input-end",id:ue.toolCallId}),T.enqueue({type:"tool-call",toolCallId:ue.toolCallId,toolName:ue.toolName,input:ue.input,...ue.providerExecuted?{providerExecuted:ue.providerExecuted}:{},...M?{providerMetadata:M}:{}});break}case"tool-result":T.enqueue({type:"tool-result",toolCallId:ue.toolCallId,toolName:ue.toolName,result:ue.result});break;case"source":case"file":T.enqueue(ue)}let X=h.service_tier??_,z={unified:Is({status:h.status,hasFunctionCall:P}),raw:h.status},Z={google:{...S!=null?{interactionId:S}:{},...X!=null?{serviceTier:X}:{}}};T.enqueue({type:"finish",finishReason:z,usage:Rs(h.usage),providerMetadata:Z}),T.close()}})}var Ml=class h{static[H](f){return{...te({modelId:f.modelId,config:f.config}),agent:f.agent}}static[Q](f){return new h(f.agent!=null?{agent:f.agent}:f.modelId,f.config)}constructor(f,g){if(this.specificationVersion="v4",typeof f==="string")this.modelId=f,this.agent=void 0;else if("managedAgent"in f)this.modelId=f.managedAgent,this.agent=f.managedAgent;else this.modelId=f.agent,this.agent=f.agent;this.config=g}get provider(){return this.config.provider}get supportedUrls(){if(this.config.supportedUrls)return this.config.supportedUrls();return{"image/*":[/^https?:\/\/.+/],"application/pdf":[/^https?:\/\/.+/],"audio/*":[/^https?:\/\/.+/],"video/*":[/^https?:\/\/(www\.)?youtube\.com\/watch\?v=.+/,/^https?:\/\/youtu\.be\/.+/,/^gs:\/\/.+/]}}async getArgs(f){let g=[],y=await k({provider:"google",providerOptions:f.providerOptions,schema:Rg}),_=this.agent!=null;if(!_){if(f.frequencyPenalty!=null)g.push({type:"unsupported",feature:"frequencyPenalty"});if(f.presencePenalty!=null)g.push({type:"unsupported",feature:"presencePenalty"})}let T=f.tools!=null&&f.tools.length>0,S,w;if(T){let M=Gg({tools:f.tools,toolChoice:f.toolChoice});S=M.tools,w=M.toolChoice,g.push(...M.toolWarnings)}let x=[];if(f.responseFormat?.type==="json")if(_)g.push({type:"other",message:"google.interactions: structured output (responseFormat) is not supported when an agent is set; responseFormat will be ignored."});else{let M={type:"text",mime_type:"application/json",...f.responseFormat.schema!=null?{schema:f.responseFormat.schema}:{}};x.push(M)}if(y?.responseFormat!=null){for(let M of y.responseFormat)if(M.type==="text")x.push(Pt({type:"text",mime_type:M.mimeType??void 0,schema:M.schema??void 0}));else if(M.type==="image")x.push(Pt({type:"image",mime_type:M.mimeType??void 0,aspect_ratio:M.aspectRatio??void 0,image_size:M.imageSize??void 0}));else if(M.type==="audio")x.push(Pt({type:"audio",mime_type:M.mimeType??void 0}));else if(M.type==="video")x.push(Pt({type:"video",aspect_ratio:M.aspectRatio??void 0,resolution:M.resolution??void 0,duration:M.duration??void 0,delivery:M.delivery??void 0,gcs_uri:M.gcsUri??void 0}))}let{input:B,systemInstruction:P,warnings:ne}=Cg({prompt:f.prompt,previousInteractionId:y?.previousInteractionId??void 0,store:y?.store??void 0,mediaResolution:y?.mediaResolution??void 0});g.push(...ne);let se=P,X=y?.systemInstruction??void 0;if(se!=null&&X!=null)g.push({type:"other",message:"google.interactions: both AI SDK system message and providerOptions.google.systemInstruction were set; using the AI SDK system message."});else if(se==null&&X!=null)se=X;let z;if(_){let M=[];if(f.temperature!=null)M.push("temperature");if(f.topP!=null)M.push("topP");if(f.topK!=null)M.push("topK");if(f.frequencyPenalty!=null)M.push("frequencyPenalty");if(f.presencePenalty!=null)M.push("presencePenalty");if(f.seed!=null)M.push("seed");if(f.stopSequences!=null&&f.stopSequences.length>0)M.push("stopSequences");if(f.maxOutputTokens!=null)M.push("maxOutputTokens");if(y?.thinkingLevel!=null)M.push("thinkingLevel");if(y?.thinkingSummaries!=null)M.push("thinkingSummaries");if(y?.imageConfig!=null)M.push("imageConfig");if(M.length>0)g.push({type:"other",message:`google.interactions: ${M.join(", ")} ${M.length===1?"is":"are"} not supported when an agent is set; use providerOptions.google.agentConfig instead. Dropped from the request body.`});z=void 0}else if(z=Pt({temperature:f.temperature??void 0,top_p:f.topP??void 0,top_k:f.topK??void 0,seed:f.seed??void 0,stop_sequences:f.stopSequences!=null&&f.stopSequences.length>0?f.stopSequences:void 0,max_output_tokens:f.maxOutputTokens??void 0,thinking_level:y?.thinkingLevel??void 0,thinking_summaries:y?.thinkingSummaries??void 0,tool_choice:w}),y?.imageConfig!=null){let M=x.some((L)=>L.type==="image");if(g.push({type:"other",message:M?"google.interactions: providerOptions.google.imageConfig is deprecated and was ignored because providerOptions.google.responseFormat already supplies an image entry. Use responseFormat exclusively.":'google.interactions: providerOptions.google.imageConfig is deprecated. Use providerOptions.google.responseFormat with a { type: "image", ... } entry instead.'}),!M)x.push({type:"image",mime_type:"image/png",...y.imageConfig.aspectRatio!=null?{aspect_ratio:y.imageConfig.aspectRatio}:{},...y.imageConfig.imageSize!=null?{image_size:y.imageConfig.imageSize}:{}})}let Z;if(_&&y?.agentConfig!=null){let M=y.agentConfig;if(M.type==="deep-research")Z=Pt({type:"deep-research",thinking_summaries:M.thinkingSummaries??void 0,visualization:M.visualization??void 0,collaborative_planning:M.collaborativePlanning??void 0});else if(M.type==="dynamic")Z={type:"dynamic"}}let ue;if(y?.environment!=null)if(!_)g.push({type:"other",message:"google.interactions: environment is only supported when an agent is set; environment will be omitted from the request body."});else if(typeof y.environment==="string")ue=y.environment;else{let M=y.environment,L=M.sources?.map((q)=>{if(q.type==="inline")return{type:"inline",content:q.content,target:q.target};return Pt({type:q.type,source:q.source,target:q.target??void 0})}),he;if(M.network==="disabled")he="disabled";else if(M.network!=null)he={allowlist:M.network.allowlist.map((q)=>Pt({domain:q.domain,transform:q.transform??void 0}))};ue=Pt({type:"remote",sources:L!=null&&L.length>0?L:void 0,network:he})}return{args:Pt({..._?{agent:this.agent}:{model:this.modelId},input:B,system_instruction:se,tools:S,response_format:x.length>0?x:void 0,response_modalities:y?.responseModalities!=null?y.responseModalities:void 0,previous_interaction_id:y?.previousInteractionId??void 0,service_tier:y?.serviceTier??void 0,store:y?.store??void 0,generation_config:z!=null&&Object.keys(z).length>0?z:void 0,agent_config:Z,environment:ue,background:y?.background??void 0}),warnings:g,isAgent:_,isBackground:y?.background===!0,pollingTimeoutMs:y?.pollingTimeoutMs??void 0}}async doGenerate(f){let{args:g,warnings:y,isAgent:_,isBackground:T,pollingTimeoutMs:S}=await this.getArgs(f),w=`${this.config.baseURL}/interactions`,x=I(this.config.headers?await W(this.config.headers):void 0,f.headers),{responseHeaders:B,value:P,rawValue:ne}=await A({url:w,headers:x,body:g,failedResponseHandler:Bt,successfulResponseHandler:E(ks),abortSignal:f.abortSignal,fetch:this.config.fetch});if((_||T)&&!xs(P.status)){let q=await Fg({baseURL:this.config.baseURL,interactionId:P.id,headers:x,fetch:this.config.fetch,abortSignal:f.abortSignal,timeoutMs:S});P=q.response,ne=q.rawResponse,B=q.responseHeaders??B}let se=typeof P.id==="string"&&P.id.length>0?P.id:void 0,{content:X,hasFunctionCall:z}=jl({steps:P.steps??null,generateId:this.config.generateId??C,interactionId:se}),Z={unified:Is({status:P.status,hasFunctionCall:z}),raw:P.status},ue=P.service_tier??B?.["x-gemini-service-tier"]??void 0,M=El(P.usage),L={google:{...se!=null?{interactionId:se}:{},...ue!=null?{serviceTier:ue}:{},...M!=null?{outputTokensByModality:M}:{}}},he;if(typeof P.created==="string"){let q=new Date(P.created);if(!Number.isNaN(q.getTime()))he=q}return{content:X,finishReason:Z,usage:Rs(P.usage),warnings:y,providerMetadata:L,request:{body:g},response:{headers:B,body:ne,...se!=null?{id:se}:{},...he?{timestamp:he}:{},modelId:P.model??void 0}}}async doStream(f){let{args:g,warnings:y,isBackground:_,pollingTimeoutMs:T}=await this.getArgs(f),S=`${this.config.baseURL}/interactions`,w=I(this.config.headers?await W(this.config.headers):void 0,f.headers);if(_)return this.doStreamBackground({args:g,warnings:y,url:S,mergedHeaders:w,options:f,pollingTimeoutMs:T});let x={...g,stream:!0},{responseHeaders:B,value:P}=await A({url:S,headers:w,body:x,failedResponseHandler:Bt,successfulResponseHandler:qe(Pl),abortSignal:f.abortSignal,fetch:this.config.fetch}),ne=B?.["x-gemini-service-tier"],se=ol({warnings:y,generateId:this.config.generateId??C,includeRawChunks:f.includeRawChunks,serviceTier:ne});return{stream:P.pipeThrough(se),request:{body:x},response:{headers:B}}}async doStreamBackground({args:f,warnings:g,url:y,mergedHeaders:_,options:T,pollingTimeoutMs:S}){let{responseHeaders:w,value:x}=await A({url:y,headers:_,body:f,failedResponseHandler:Bt,successfulResponseHandler:E(ks),abortSignal:T.abortSignal,fetch:this.config.fetch}),B=x.id;if(B==null||B.length===0)throw Error("google.interactions: background POST response did not include an interaction id; cannot stream the result.");let P=w?.["x-gemini-service-tier"];if(xs(x.status))return{stream:Vg({response:x,warnings:g,generateId:this.config.generateId??C,includeRawChunks:T.includeRawChunks,headerServiceTier:P}),request:{body:f},response:{headers:w}};let ne=Bg({baseURL:this.config.baseURL,interactionId:B,headers:_,fetch:this.config.fetch,abortSignal:T.abortSignal}),se=ol({warnings:g,generateId:this.config.generateId??C,includeRawChunks:T.includeRawChunks,serviceTier:P});return{stream:ne.pipeThrough(se),request:{body:f},response:{headers:w}}}};function Pt(h){let f={};for(let[g,y]of Object.entries(h)){if(y===void 0)continue;f[g]=y}return f}function Wg(h){let f=new Vl.GoogleAuth({scopes:["https://www.googleapis.com/auth/cloud-platform"],...h});return async function(){return(await(await f.getClient()).getAccessToken())?.token??null}}var Kg="5.0.122",Jg=u(()=>l(t({error:t({code:n().nullable(),message:e(),status:e()})}))),zt=oe({errorSchema:Jg,errorToMessage:(h)=>h.error.message}),Ns=u(()=>l(t({outputDimensionality:n().optional(),taskType:s(["SEMANTIC_SIMILARITY","CLASSIFICATION","CLUSTERING","RETRIEVAL_DOCUMENT","RETRIEVAL_QUERY","QUESTION_ANSWERING","FACT_VERIFICATION","CODE_RETRIEVAL_QUERY"]).optional(),title:e().optional(),autoTruncate:r().optional()}))),Yg=class h{static[H](f){return te({modelId:f.modelId,config:f.config})}static[Q](f){return new h(f.modelId,f.config)}get provider(){return this.config.provider}get maxEmbeddingsPerCall(){return Dl(this.modelId)?1:250}constructor(f,g){this.specificationVersion="v4",this.supportsParallelCalls=!0,this.modelId=f,this.config=g}async doEmbed({values:f,dimensions:g,headers:y,abortSignal:_,providerOptions:T}){let S=await k({provider:"googleVertex",providerOptions:T,schema:Ns});if(S==null)S=await k({provider:"vertex",providerOptions:T,schema:Ns});if(S==null)S=await k({provider:"google",providerOptions:T,schema:Ns});if(S=S??{},f.length>this.maxEmbeddingsPerCall)throw new lt({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:f});let w=I(this.config.headers?await W(this.config.headers):void 0,y);if(Dl(this.modelId)){let{responseHeaders:se,value:X,rawValue:z}=await A({url:`${this.config.baseURL}/models/${this.modelId}:embedContent`,headers:w,body:{content:{parts:[{text:f[0]}]},embedContentConfig:{outputDimensionality:S.outputDimensionality??g,taskType:S.taskType,title:S.title,autoTruncate:S.autoTruncate}},failedResponseHandler:zt,successfulResponseHandler:E(Xg),abortSignal:_,fetch:this.config.fetch});return{warnings:[],embeddings:[X.embedding.values],usage:X.usageMetadata?.promptTokenCount==null?void 0:{tokens:X.usageMetadata.promptTokenCount},response:{headers:se,body:z}}}let x=`${this.config.baseURL}/models/${this.modelId}:predict`,{responseHeaders:B,value:P,rawValue:ne}=await A({url:x,headers:w,body:{instances:f.map((se)=>({content:se,task_type:S.taskType,title:S.title})),parameters:{outputDimensionality:S.outputDimensionality??g,autoTruncate:S.autoTruncate}},failedResponseHandler:zt,successfulResponseHandler:E(zg),abortSignal:_,fetch:this.config.fetch});return{warnings:[],embeddings:P.predictions.map((se)=>se.embeddings.values),usage:{tokens:P.predictions.reduce((se,X)=>se+X.embeddings.statistics.token_count,0)},response:{headers:B,body:ne}}}},zg=u(()=>l(t({predictions:o(t({embeddings:t({values:o(n()),statistics:t({token_count:n()})})}))}))),Xg=u(()=>l(t({embedding:t({values:o(n())}),usageMetadata:t({promptTokenCount:n().nullish()}).nullish()})));function Dl(h){return h==="gemini-embedding-2"||h==="gemini-embedding-2-preview"}var Qg=new Set(["gemini-2.5-flash-image","gemini-3-pro-image-preview","gemini-3.1-flash-image-preview","gemini-nano-banana-2.1"]),Zg=class h{static[H](f){return te({modelId:f.modelId,config:f.config})}static[Q](f){return new h(f.modelId,f.config)}get supportsFileInputs(){return Qg.has(this.modelId)?!0:void 0}get supportsMaskInputs(){return this.supportsFileInputs===!0?!1:void 0}get provider(){return this.config.provider}constructor(f,g){this.modelId=f,this.config=g,this.specificationVersion="v4",this.maxImagesPerCall=1}async doGenerate(f){if(!this.modelId.startsWith("gemini-"))throw Error("Google image models other than Gemini are no longer supported. Use a model ID that starts with `gemini-`.");let{prompt:g,size:y,aspectRatio:_,seed:T,providerOptions:S,headers:w,abortSignal:x,files:B,mask:P}=f,ne=[];if(P!=null)throw Error("Gemini image models do not support mask-based image editing.");if(y!=null)ne.push({type:"unsupported",feature:"size",details:"This model does not support the `size` option. Use `aspectRatio` instead."});let se=[];if(g!=null)se.push({type:"text",text:g});if(B!=null&&B.length>0)for(let ye of B)if(ye.type==="url")se.push({type:"file",data:{type:"url",url:new URL(ye.url)},mediaType:"image/*"});else se.push({type:"file",data:{type:"data",data:typeof ye.data==="string"?ye.data:new Uint8Array(ye.data)},mediaType:ye.mediaType});let X=[{role:"user",content:se}],z=new Os(this.modelId,{provider:this.config.provider,baseURL:this.config.baseURL,headers:this.config.headers??{},fetch:this.config.fetch,generateId:this.config.generateId??C,supportedUrls:()=>({"*":[/^https?:\/\/.*$/,/^gs:\/\/.*$/]})}),{responseModalities:Z,imageConfig:ue,...M}=S?.googleVertex??S?.vertex??{},L={...M,responseModalities:["IMAGE"],imageConfig:_!=null||ue!=null?{...ue,..._!=null?{aspectRatio:_}:{}}:void 0},he=await z.doGenerate({prompt:X,seed:T,providerOptions:{googleVertex:L,vertex:L},headers:w,abortSignal:x}),q=this.config._internal?.currentDate?.()??new Date,U=[];for(let ye of he.content)if(ye.type==="file"&&ye.mediaType.startsWith("image/")&&ye.data.type==="data")U.push(j(ye.data.data));let de={images:U.map(()=>({}))};return{images:U,...he.finishReason.unified==="content-filter"?{isRetryable:!1}:{},warnings:ne,providerMetadata:{googleVertex:de,vertex:de},response:{timestamp:q,modelId:this.modelId,headers:he.response?.headers},usage:he.usage?{inputTokens:he.usage.inputTokens.total,outputTokens:he.usage.outputTokens.total,totalTokens:(he.usage.inputTokens.total??0)+(he.usage.outputTokens.total??0)}:void 0}}},em="Kore",ql="en-US",Ps="Chirp3-HD",tm="https://texttospeech.googleapis.com/v1/text:synthesize",nm=class h{static[H](f){return te({modelId:f.modelId,config:f.config})}static[Q](f){return new h(f.modelId,f.config)}get provider(){return this.config.provider}constructor(f,g){this.modelId=f,this.config=g,this.specificationVersion="v4"}async doGenerate(f){let g=this.config._internal?.currentDate?.()??new Date,y=[],{text:_,voice:T=em,outputFormat:S,instructions:w,speed:x,language:B}=f,P,ne;if(T.includes(Ps)){P=T;let ue=T.split(Ps)[0].replace(/-$/,"");ne=B??(ue||ql)}else ne=B??ql,P=`${ne}-${Ps}-${T}`;if(w!=null)y.push({type:"unsupported",feature:"instructions",details:"Google Cloud Text-to-Speech Chirp 3: HD voices do not support the `instructions` option. It was ignored."});if(S!=null&&S!=="wav")y.push({type:"unsupported",feature:"outputFormat",details:`Unsupported output format: ${S}. Using wav instead.`});let se={input:{text:_},voice:{languageCode:ne,name:P},audioConfig:{audioEncoding:"LINEAR16",...x!=null?{speakingRate:x}:{}}},{value:X,responseHeaders:z,rawValue:Z}=await A({url:tm,headers:I(this.config.headers?await W(this.config.headers):void 0,f.headers),body:se,failedResponseHandler:zt,successfulResponseHandler:E(rm),abortSignal:f.abortSignal,fetch:this.config.fetch});return{audio:X.audioContent!=null?Te(X.audioContent):new Uint8Array(0),warnings:y,request:{body:JSON.stringify(se)},response:{timestamp:g,modelId:this.modelId,headers:z,body:Z},providerMetadata:{google:{mimeType:"audio/wav"}}}}},rm=u(()=>l(t({audioContent:e().nullish()}))),sm={googleSearch:Vt.googleSearch,enterpriseWebSearch:Vt.enterpriseWebSearch,googleMaps:Vt.googleMaps,urlContext:Vt.urlContext,fileSearch:Vt.fileSearch,codeExecution:Vt.codeExecution,vertexRagStore:Vt.vertexRagStore},im=u(()=>l(t({languageCodes:o(e()).optional(),enableAutomaticPunctuation:r().optional(),enableWordTimeOffsets:r().optional(),region:e().optional()})));function js(h){if(h==null)return;let f=Number.parseFloat(h);return Number.isFinite(f)?f:void 0}function om(h){if(h==null)return;try{let f=new Intl.Locale(h).language;return f.length===2?f:void 0}catch{return}}var am=class h{static[H](f){return te({modelId:f.modelId,config:f.config})}static[Q](f){return new h(f.modelId,f.config)}get provider(){return this.config.provider}constructor(f,g){this.modelId=f,this.config=g,this.specificationVersion="v4"}async doGenerate(f){let g=this.config._internal?.currentDate?.()??new Date,y=[],_;for(let z of["googleVertex","vertex","google"])if(_=await k({provider:z,providerOptions:f.providerOptions,schema:im}),_!=null)break;let T=_?.region??this.config.location;if(!Ms(T))throw new F({argument:_?.region!=null?"region":"location",message:"Invalid Google Cloud Speech-to-Text region. Expected a single DNS label (letters, digits, and hyphens)."});let S=_?.languageCodes??["auto"],w=typeof f.audio==="string"?f.audio:tt(f.audio),x={config:{model:this.modelId,languageCodes:S,autoDecodingConfig:{},features:{enableWordTimeOffsets:_?.enableWordTimeOffsets??!0,enableAutomaticPunctuation:_?.enableAutomaticPunctuation??!0}},content:w},B=`https://${T==="global"?"speech.googleapis.com":`${T}-speech.googleapis.com`}/v2/projects/${this.config.project}/locations/${T}/recognizers/_:recognize`,{value:P,responseHeaders:ne,rawValue:se}=await A({url:B,headers:I(this.config.headers?await W(this.config.headers):void 0,f.headers),body:x,failedResponseHandler:zt,successfulResponseHandler:E(cm),abortSignal:f.abortSignal,fetch:this.config.fetch}),X=P.results??[];return{text:X.map((z)=>z.alternatives?.[0]?.transcript??"").join(" ").trim(),segments:X.flatMap((z)=>z.alternatives?.[0]?.words?.flatMap((Z)=>{let ue=js(Z.startOffset),M=js(Z.endOffset);return Z.word==null||ue==null||M==null?[]:[{text:Z.word,startSecond:ue,endSecond:M}]})??[]),language:om(X[0]?.languageCode),durationInSeconds:js(P.metadata?.totalBilledDuration),warnings:y,response:{timestamp:g,modelId:this.modelId,headers:ne,body:se}}}},cm=u(()=>l(t({results:o(t({alternatives:o(t({transcript:e().nullish(),words:o(t({word:e().nullish(),startOffset:e().nullish(),endOffset:e().nullish()})).nullish()})).nullish(),languageCode:e().nullish()})).nullish(),metadata:t({totalBilledDuration:e().nullish()}).nullish()}))),lm=u(()=>l(t({languageCodes:o(e()).optional(),customVocabulary:o(e()).optional(),wordTimestamp:r().optional(),diarization:r().optional(),mode:s(["SMART","VERBATIM"]).optional()}))),um="google.cloud.aiplatform.v1.LlmBidiService/BidiGenerateContent",dm=3000;function Ll(h){return h.includes("-live")}function hm(h){if(h==="global")return"aiplatform.googleapis.com";if(h==="eu"||h==="us")return`aiplatform.${h}.rep.googleapis.com`;return`${h}-aiplatform.googleapis.com`}var pm=class h{static[H](f){return te({modelId:f.modelId,config:f.config})}static[Q](f){return new h(f.modelId,f.config)}get provider(){return this.config.provider}constructor(f,g){this.modelId=f,this.config=g,this.specificationVersion="v4"}async parseOptions(f){for(let g of["googleVertex","vertex","google"]){let y=await k({provider:g,providerOptions:f,schema:lm});if(y!=null)return y}}async doGenerate(f){if(Ll(this.modelId))throw new F({argument:"modelId",message:`Model '${this.modelId}' only supports streaming transcription. Use experimental_streamTranscribe, or a unary model such as 'gemini-3.5-transcribe'.`});let g=this.config._internal?.currentDate?.()??new Date,y=[],_=Fl(await this.parseOptions(f.providerOptions)),T={contents:[{role:"user",parts:[{inlineData:{mimeType:f.mediaType,data:j(f.audio)}}]}],..._!=null?{generationConfig:{audioTranscriptionConfig:_}}:{}},{value:S,responseHeaders:w,rawValue:x}=await A({url:`${this.config.baseURL}/models/${this.modelId}:generateContent`,headers:I(this.config.headers?await W(this.config.headers):void 0,f.headers),body:T,failedResponseHandler:zt,successfulResponseHandler:E(ym),abortSignal:f.abortSignal,fetch:this.config.fetch}),B=S.candidates?.[0]?.content?.parts??[],P=B.map((Z)=>Z.text??"").join(""),ne=B.map((Z)=>Z.audioTranscription?.text??"").join(""),se=P!==""?P:ne,X,z=[];for(let Z of B){let ue=Z.audioTranscription;if(ue==null)continue;X??=ue.languageCode??void 0;for(let M of ue.words??[]){let L=Gl(M.startOffset),he=Gl(M.endOffset);if(M.word==null||L==null||he==null)continue;z.push({text:M.word,startSecond:L,endSecond:he})}}return{text:se,segments:z,language:X,durationInSeconds:void 0,warnings:y,response:{timestamp:g,modelId:this.modelId,headers:w,body:x},...S.usageMetadata!=null?{usage:S.usageMetadata,providerMetadata:{google:{usageMetadata:S.usageMetadata}}}:{}}}async doStream(f){if(!Ll(this.modelId))throw new F({argument:"modelId",message:`Model '${this.modelId}' does not support streaming transcription. Use a live model such as 'gemini-3.5-transcribe-live'.`});let g=this.config._internal?.currentDate?.()??new Date,y=[],_=await this.parseOptions(f.providerOptions);gm(f.inputAudioFormat);let T=I(this.config.headers?await W(this.config.headers):void 0,f.headers),{project:S,location:w}=this.config,x=`projects/${S}/locations/${w}/publishers/google/models/${this.modelId}`,B=new URL(`wss://${hm(w)}/ws/${um}`),P={model:x,inputAudioTranscription:Fl(_)??{}};return{request:{body:P},response:{timestamp:g,modelId:this.modelId},stream:fm({webSocket:this.config.webSocket,url:B,headers:T,setup:P,inputAudioRate:f.inputAudioFormat.rate??16000,finishGraceMs:this.config._internal?.finishGraceMs??dm,warnings:y,audio:f.audio,abortSignal:f.abortSignal,includeRawChunks:f.includeRawChunks})}}};function fm({webSocket:h,url:f,headers:g,setup:y,inputAudioRate:_,finishGraceMs:T,warnings:S,audio:w,abortSignal:x,includeRawChunks:B}){let P=!1,ne=()=>{};return new ReadableStream({start:(se)=>{let X,z,Z,ue=new Promise((Ue)=>{Z=Ue}),M=0,L="",he="",q="",U,de=!1,ye,Ce,_e=()=>`google-segment-${M}`,Pe=()=>{if(Ce!=null)clearTimeout(Ce),Ce=void 0},Re=()=>{if(P||!de)return;Pe(),Ce=setTimeout(()=>{Ce=void 0,je()},T)};ne=(Ue)=>{if(Pe(),X!=null)X.cancel().catch(()=>{});else w.cancel().catch(()=>{});z?.close(Ue)};let Ne=(Ue)=>{if(P)return;P=!0,ne(),se.error(Ue)},Je=()=>{if(L===""){if(q==="")return;L=q}q="",se.enqueue({type:"transcript-final",id:_e(),text:L}),he+=he===""?L:` ${L}`,L="",M++},je=()=>{if(P)return;Je(),P=!0,se.enqueue({type:"finish",text:he,segments:[],language:U,durationInSeconds:void 0,...ye!=null?{usage:ye,providerMetadata:{google:{usageMetadata:ye}}}:{}}),se.close(),ne(1000)},Ye=async(Ue)=>{X=w.getReader();try{while(!0){let{done:ze,value:Ze}=await X.read();if(ze||P)break;Ue.send(JSON.stringify({realtimeInput:{audio:{data:j(Ze),mimeType:`audio/pcm;rate=${_}`}}})),await xn(Ue)}}finally{X.releaseLock(),X=void 0}if(!P)Ue.send(JSON.stringify({realtimeInput:{audioStreamEnd:!0}})),de=!0,Re()};z=Xn({url:f,headers:g,webSocket:h,abortSignal:x,onAbort:Ne,onProcessingError:Ne,onOpen:(Ue)=>{se.enqueue({type:"stream-start",warnings:S}),Ue.send(JSON.stringify({setup:y})),ue.then(()=>P?void 0:Ye(Ue)).catch(Ne)},onMessageText:async(Ue)=>{if(P)return;let ze=await yt({text:Ue});if(!ze.success)return;let Ze=ze.value;if(B)se.enqueue({type:"raw",rawValue:Ze});if(Ze.setupComplete!=null)Z();if(Ze.usageMetadata!=null)ye=Ze.usageMetadata;if(Ze.error!=null){Ne(Error(Ze.error.message??"Vertex Live API error"));return}let nt=Ze.serverContent,ot=nt?.interimInputTranscription;if(ot?.text)Re(),q=ot.text,se.enqueue({type:"transcript-partial",id:_e(),text:ot.text});let et=nt?.inputTranscription??Ze.inputTranscription;if(et!=null){if(et.languageCode!=null)U=et.languageCode;if(et.text)Re(),q="",L+=et.text,se.enqueue({type:"transcript-delta",id:_e(),delta:et.text});if(et.finished===!0)Je()}if(nt?.turnComplete)Je();let mt=nt?.interactionStatus;if(de&&(mt==="IDLE"||mt==="REQUIRES_ACTION"||nt?.turnComplete===!0&&mt==null))je()},onSocketError:()=>{Ne(Error("Vertex Live transcription error."+(h==null?" Note: the native WebSocket implementation cannot send the Authorization header required by Vertex. Pass a header-capable WebSocket implementation (e.g. the 'ws' package) via createVertex({ webSocket }).":"")))},onClose:({code:Ue,reason:ze})=>{if(P)return;if(de){je();return}Ne(Error(`Vertex Live transcription WebSocket closed unexpectedly before finishing (code ${Ue??"unknown"}${ze?`, reason: ${ze}`:""}).`))}})},cancel:()=>{if(P)return;P=!0,ne()}})}function Fl(h){if(h==null)return;let f={};if(h.languageCodes!=null)f.languageCodes=h.languageCodes;if(h.customVocabulary!=null)f.customVocabulary=h.customVocabulary;if(h.wordTimestamp!=null)f.wordTimestamp=h.wordTimestamp;if(h.diarization!=null)f.diarization=h.diarization;if(h.mode!=null)f.mode=h.mode;return Object.keys(f).length>0?f:void 0}function gm(h){if(h.type!=="audio/pcm"||h.rate!=null&&h.rate!==16000)throw new F({argument:"inputAudioFormat",message:"The Gemini Live transcription API only supports 16kHz 16-bit PCM input audio."})}function Gl(h){if(h==null)return;let f=Number.parseFloat(h);return Number.isFinite(f)?f:void 0}var mm=()=>t({word:e().nullish(),startOffset:e().nullish(),endOffset:e().nullish()}),ym=u(()=>l(t({candidates:o(t({content:t({parts:o(t({text:e().nullish(),audioTranscription:t({text:e().nullish(),languageCode:e().nullish(),speakerLabel:e().nullish(),words:o(mm()).nullish()}).nullish()})).nullish()}).nullish()})).nullish(),usageMetadata:d(e(),m()).nullish()}))),$l=u(()=>l(ae({pollIntervalMs:n().positive().nullish(),pollTimeoutMs:n().positive().nullish(),personGeneration:s(["dont_allow","allow_adult","allow_all"]).nullish(),negativePrompt:e().nullish(),generateAudio:r().nullish(),gcsOutputDirectory:e().nullish(),referenceImages:o(t({bytesBase64Encoded:e().nullish(),gcsUri:e().nullish()})).nullish()})));function _m(h){return h.frameImages?.find((f)=>f.frameType==="first_frame")?.image}function Tm(h){return _m(h)??h.image}function vm(h){return h.frameImages?.find((f)=>f.frameType==="last_frame")?.image}function wm(h){if(h.frameImages!=null&&h.frameImages.length>0)return;return h.inputReferences!=null&&h.inputReferences.length>0?h.inputReferences:void 0}function Us(h,f){if(h.type==="url"){if(h.url.startsWith("gs://"))return{gcsUri:h.url,mimeType:"image/png"};f.push({type:"unsupported",feature:"URL-based image input",details:"Vertex AI video models require base64-encoded images or GCS URIs. URL will be ignored."});return}return{bytesBase64Encoded:typeof h.data==="string"?h.data:tt(h.data),mimeType:h.mediaType||"image/png"}}function Em(h,f){let g=Us(h,f);return g!=null?{image:g,referenceType:"asset"}:void 0}var Cm=class{get provider(){return this.config.provider}get maxVideosPerCall(){return 4}constructor(h,f){this.modelId=h,this.config=f,this.specificationVersion="v4"}async buildRequest(h){let f=[],g=await k({provider:"googleVertex",providerOptions:h.providerOptions,schema:$l})??await k({provider:"vertex",providerOptions:h.providerOptions,schema:$l}),y=[{}],_=y[0];if(h.prompt!=null)_.prompt=h.prompt;let T=Tm(h);if(T!=null){let P=Us(T,f);if(P!=null)_.image=P}let S=vm(h);if(S!=null){let P=Us(S,f);if(P!=null)_.lastFrame=P}let w=wm(h);if(w!=null)_.referenceImages=w.flatMap((P)=>{let ne=Em(P,f);return ne!=null?[ne]:[]});else if(g?.referenceImages!=null)_.referenceImages=g.referenceImages;let x={sampleCount:h.n};if(h.aspectRatio)x.aspectRatio=h.aspectRatio;if(h.resolution)x.resolution={"1280x720":"720p","1920x1080":"1080p","3840x2160":"4k"}[h.resolution]||h.resolution;if(h.duration)x.durationSeconds=h.duration;if(h.seed)x.seed=h.seed;let B=h.generateAudio??g?.generateAudio;if(B!=null)x.generateAudio=B;if(g!=null){let P=g;if(P.personGeneration!==void 0&&P.personGeneration!==null)x.personGeneration=P.personGeneration;if(P.negativePrompt!==void 0&&P.negativePrompt!==null)x.negativePrompt=P.negativePrompt;if(P.gcsOutputDirectory!==void 0&&P.gcsOutputDirectory!==null)x.gcsOutputDirectory=P.gcsOutputDirectory;for(let[ne,se]of Object.entries(P))if(!["pollIntervalMs","pollTimeoutMs","personGeneration","negativePrompt","generateAudio","gcsOutputDirectory","referenceImages"].includes(ne))x[ne]=se}return{instances:y,parameters:x,warnings:f,googleVertexOptions:g}}buildCompletedResult({finalOperation:h,responseHeaders:f,warnings:g,currentDate:y}){let _=h.response;if(!_?.videos||_.videos.length===0)throw new D({name:"VERTEX_VIDEO_GENERATION_ERROR",message:`No videos in response. Response: ${JSON.stringify(h)}`});let T=[],S=[];for(let w of _.videos)if(w.bytesBase64Encoded)T.push({type:"base64",data:w.bytesBase64Encoded,mediaType:w.mimeType||"video/mp4"}),S.push({mimeType:w.mimeType});else if(w.gcsUri)T.push({type:"url",url:w.gcsUri,mediaType:w.mimeType||"video/mp4"}),S.push({gcsUri:w.gcsUri,mimeType:w.mimeType});if(T.length===0)throw new D({name:"VERTEX_VIDEO_GENERATION_ERROR",message:"No valid videos in response"});return{status:"completed",videos:T,warnings:g,response:{timestamp:y,modelId:this.modelId,headers:f},providerMetadata:(()=>{let w={videos:S};return{googleVertex:w,"google-vertex":w,vertex:w}})()}}async doStart(h){let f=this.config._internal?.currentDate?.()??new Date,{instances:g,parameters:y,warnings:_}=await this.buildRequest(h),{value:T,responseHeaders:S}=await A({url:`${this.config.baseURL}/models/${this.modelId}:predictLongRunning`,headers:I(await W(this.config.headers),h.headers),body:{instances:g,parameters:y},successfulResponseHandler:E(Hl),failedResponseHandler:zt,abortSignal:h.abortSignal,fetch:this.config.fetch}),w=T.name;if(!w)throw new D({name:"VERTEX_VIDEO_GENERATION_ERROR",message:"No operation name returned from API"});return{operation:{operationName:w},warnings:_,response:{timestamp:f,modelId:this.modelId,headers:S}}}async doStatus(h){let f=this.config._internal?.currentDate?.()??new Date,{operationName:g}=h.operation,{value:y,responseHeaders:_}=await A({url:`${this.config.baseURL}/models/${this.modelId}:fetchPredictOperation`,headers:I(await W(this.config.headers),h.headers),body:{operationName:g},successfulResponseHandler:E(Hl),failedResponseHandler:zt,abortSignal:h.abortSignal,fetch:this.config.fetch});if(!y.done)return{status:"pending",response:{timestamp:f,modelId:this.modelId,headers:_}};if(y.error)return{status:"error",error:`Video generation failed: ${y.error.message}`,response:{timestamp:f,modelId:this.modelId,headers:_}};return this.buildCompletedResult({finalOperation:y,responseHeaders:_,warnings:[],currentDate:f})}},Hl=u(()=>l(t({name:e().nullish(),done:r().nullish(),error:t({code:n().nullish(),message:e(),status:e().nullish()}).nullish(),response:t({videos:o(t({bytesBase64Encoded:e().nullish(),gcsUri:e().nullish(),mimeType:e().nullish()})).nullish(),raiMediaFilteredCount:n().nullish()}).nullish()}))),Am="https://aiplatform.googleapis.com/v1/publishers/google",bm="endpoints/";function Sm(h){return h.startsWith(bm)}function km(h,f){return async(g,y)=>{let _={...y,headers:{...y?.headers?Ci(y.headers):{},"x-goog-api-key":h}};return(f??fetch)(g.toString(),_)}}function Bl(h={}){let f=ut({settingValue:h.apiKey,environmentVariableName:"GOOGLE_VERTEX_API_KEY"}),g=()=>io({settingValue:h.project,settingName:"project",environmentVariableName:"GOOGLE_VERTEX_PROJECT",description:"Google Vertex project"}),y=()=>{let z=io({settingValue:h.location,settingName:"location",environmentVariableName:"GOOGLE_VERTEX_LOCATION",description:"Google Vertex location"});if(!Ms(z))throw new F({argument:"location",message:"Invalid Google Vertex location. Expected a single DNS label (letters, digits, and hyphens). Use `baseURL` for custom endpoints."});return z},_=({endpoint:z=!1}={})=>{if(f)return He(h.baseURL)??Am;let Z=He(h.baseURL);if(Z!=null)return Z;let ue=y(),M=g();return`https://${(()=>{if(ue==="global")return"aiplatform.googleapis.com";else if(ue==="eu"||ue==="us")return`aiplatform.${ue}.rep.googleapis.com`;else return`${ue}-aiplatform.googleapis.com`})()}/v1beta1/projects/${M}/locations/${ue}${z?"":"/publishers/google"}`},T=(z,{endpoint:Z=!1}={})=>{let ue=async()=>{let M=await W(h.headers??{});return Se(M,`ai-sdk-google-vertex/${Kg}`)};return{provider:`google.vertex.${z}`,headers:ue,fetch:f?km(f,h.fetch):h.fetch,baseURL:_({endpoint:Z})}},S=(z)=>{let Z=Sm(z);if(Z&&f)throw Error("Google Vertex tuned models do not support Express Mode API keys. Use standard Google Cloud credentials instead.");return new Os(z,{...T("chat",{endpoint:Z}),generateId:h.generateId??C,supportedUrls:()=>({"*":[/^https?:\/\/.*$/,/^gs:\/\/.*$/]}),downloadToolResultFiles:{maxBytes:h.toolResultDownloads?.maxBytes??7340032,supportsGoogleCloudStorageUrls:!0}})},w=(z)=>{if(f)throw Error("Google Vertex Interactions models do not support Express Mode API keys. Use standard Google Cloud credentials instead.");return new Ml(z,{...T("interactions",{endpoint:!0}),generateId:h.generateId??C})},x=(z)=>new Yg(z,T("embedding")),B=(z)=>new Zg(z,{...T("image"),generateId:h.generateId??C}),P=(z)=>new Cm(z,{...T("video"),generateId:h.generateId??C}),ne=(z)=>{if(z.startsWith("chirp")){if(f)throw Error("Google Vertex Chirp speech models do not support Express Mode API keys. Use standard Google Cloud credentials instead.");let Z=T("speech");return new nm(z,{provider:Z.provider,headers:Z.headers,fetch:Z.fetch})}return new wl(z,T("speech"))},se=(z)=>{if(f)throw Error("Google Vertex transcription models do not support Express Mode API keys. Use standard Google Cloud credentials instead.");let Z=T("transcription");if(z.startsWith("gemini"))return new pm(z,{provider:Z.provider,baseURL:_(),headers:Z.headers,fetch:Z.fetch,webSocket:h.webSocket,project:g(),location:y()});return new am(z,{provider:Z.provider,headers:Z.headers,fetch:Z.fetch,project:g(),location:y()})},X=function(z){if(new.target)throw Error("The Google Vertex AI model function cannot be called with the new keyword.");return S(z)};return X.specificationVersion="v4",X.languageModel=S,X.interactions=w,X.embeddingModel=x,X.textEmbeddingModel=x,X.image=B,X.imageModel=B,X.video=P,X.videoModel=P,X.speech=ne,X.speechModel=ne,X.transcription=se,X.transcriptionModel=se,X.tools=sm,X}function fl(h={}){if(ut({settingValue:h.apiKey,environmentVariableName:"GOOGLE_VERTEX_API_KEY"}))return Bl(h);let f=Wg(h.project==null?h.googleAuthOptions:{projectId:h.project,...h.googleAuthOptions});return Bl({...h,headers:async()=>({Authorization:`Bearer ${await f()}`,...await W(h.headers)})})}var Xy=fl();var Wl=v(Es(),1);function xm(h){let f=new Wl.GoogleAuth({scopes:["https://www.googleapis.com/auth/cloud-platform"],...h});return async function(){return(await(await f.getClient()).getAccessToken())?.token??null}}var Om=u(()=>l(t({labels:d(e(),e()).optional()}))),Rm={bash_20241022:Ri.bash_20241022,bash_20250124:Ri.bash_20250124,textEditor_20241022:Ri.textEditor_20241022,textEditor_20250124:Ri.textEditor_20250124,textEditor_20250429:Ri.textEditor_20250429,textEditor_20250728:Ri.textEditor_20250728,computer_20241022:Ri.computer_20241022,webSearch_20250305:Ri.webSearch_20250305,toolSearchRegex_20251119:Ri.toolSearchRegex_20251119,toolSearchBm25_20251119:Ri.toolSearchBm25_20251119};function Im(h={}){let f=()=>{let _=He(h.baseURL);if(_!=null)return _;let T=ut({settingValue:h.location,environmentVariableName:"GOOGLE_VERTEX_LOCATION"});if(T!=null&&!Ms(T))throw new F({argument:"location",message:"Invalid Google Vertex location. Expected a single DNS label (letters, digits, and hyphens). Use `baseURL` for custom endpoints."});let S=ut({settingValue:h.project,environmentVariableName:"GOOGLE_VERTEX_PROJECT"});return`https://${(()=>{if(T==="global")return"aiplatform.googleapis.com";else if(T==="eu"||T==="us")return`aiplatform.${T}.rep.googleapis.com`;else return`${T}-aiplatform.googleapis.com`})()}/v1/projects/${S}/locations/${T}/publishers/anthropic/models`},g=(_)=>new Lw(_,{provider:"googleVertex.anthropic.messages",baseURL:f(),headers:h.headers??{},fetch:h.fetch,buildRequestUrl:(T,S)=>`${T}/${_}:${S?"streamRawPredict":"rawPredict"}`,transformRequestBody:(T)=>{let{model:S,...w}=T;return{...w,anthropic_version:"vertex-2023-10-16"}},transformRequestHeaders:async(T,S)=>{let w=await k({provider:"vertex",providerOptions:S,schema:Om});if(w?.labels==null||Object.keys(T).some((x)=>x.toLowerCase()==="x-vertex-ai-labels"&&T[x]!=null))return T;return{...T,"x-vertex-ai-labels":tt(new TextEncoder().encode(JSON.stringify(w.labels)))}},supportedUrls:()=>({}),supportsNativeStructuredOutput:!1,supportsStrictTools:!1}),y=function(_){if(new.target)throw Error("The Anthropic model function cannot be called with the new keyword.");return g(_)};return y.specificationVersion="v4",y.languageModel=g,y.chat=g,y.messages=g,y.embeddingModel=(_)=>{throw new ve({modelId:_,modelType:"embeddingModel"})},y.textEmbeddingModel=y.embeddingModel,y.imageModel=(_)=>{throw new ve({modelId:_,modelType:"imageModel"})},y.tools=Rm,y}function yl(h={}){let f=h.generateAuthToken??xm(h.googleAuthOptions);return Im({...h,headers:async()=>({Authorization:`Bearer ${await f()}`,...await W(h.headers)})})}var s_=yl();
|
|
39
|
+
export{fl,yl};
|