@asaidimu/utils-workspace 6.2.5 → 6.2.6
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/index.js +1 -288
- package/index.mjs +1 -287
- package/package.json +5 -2
package/index.js
CHANGED
|
@@ -1,288 +1 @@
|
|
|
1
|
-
"use strict";var e=require("fs"),t=require("path"),r=require("stream"),n=require("util"),s=require("buffer"),o=require("http"),i=require("net"),a=require("url"),c=require("https"),l=require("zlib"),u=require("@asaidimu/utils-events"),d=require("uuid");function h(e){return e&&e.__esModule?e:{default:e}}var f,p=h(r),m=h(o),_=h(c),y=h(l),g=Object.create,E=Object.defineProperty,b=Object.getOwnPropertyDescriptor,w=Object.getOwnPropertyNames,T=Object.getPrototypeOf,v=Object.prototype.hasOwnProperty,S=(e=>"undefined"!=typeof require?require:"undefined"!=typeof Proxy?new Proxy(e,{get:(e,t)=>("undefined"!=typeof require?require:e)[t]}):e)((function(e){if("undefined"!=typeof require)return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')})),A=(e,t)=>function(){return e&&(t=(0,e[w(e)[0]])(e=0)),t},O=(e,t)=>function(){return t||(0,e[w(e)[0]])((t={exports:{}}).exports,t),t.exports},R=(e,t)=>{for(var r in t)E(e,r,{get:t[r],enumerable:!0})},C=(e,t,r)=>(r=null!=e?g(T(e)):{},((e,t,r,n)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let s of w(t))v.call(e,s)||s===r||E(e,s,{get:()=>t[s],enumerable:!(n=b(t,s))||n.enumerable});return e})(!t&&e&&e.__esModule?r:E(r,"default",{value:e,enumerable:!0}),e)),I=O({"node_modules/retry/lib/retry_operation.js"(e,t){function r(e,t){"boolean"==typeof t&&(t={forever:t}),this._originalTimeouts=JSON.parse(JSON.stringify(e)),this._timeouts=e,this._options=t||{},this._maxRetryTime=t&&t.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._timer=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}t.exports=r,r.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)},r.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null},r.prototype.retry=function(e){if(this._timeout&&clearTimeout(this._timeout),!e)return!1;var t=(new Date).getTime();if(e&&t-this._operationStart>=this._maxRetryTime)return this._errors.push(e),this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(e);var r=this._timeouts.shift();if(void 0===r){if(!this._cachedTimeouts)return!1;this._errors.splice(0,this._errors.length-1),r=this._cachedTimeouts.slice(-1)}var n=this;return this._timer=setTimeout((function(){n._attempts++,n._operationTimeoutCb&&(n._timeout=setTimeout((function(){n._operationTimeoutCb(n._attempts)}),n._operationTimeout),n._options.unref&&n._timeout.unref()),n._fn(n._attempts)}),r),this._options.unref&&this._timer.unref(),!0},r.prototype.attempt=function(e,t){this._fn=e,t&&(t.timeout&&(this._operationTimeout=t.timeout),t.cb&&(this._operationTimeoutCb=t.cb));var r=this;this._operationTimeoutCb&&(this._timeout=setTimeout((function(){r._operationTimeoutCb()}),r._operationTimeout)),this._operationStart=(new Date).getTime(),this._fn(this._attempts)},r.prototype.try=function(e){console.log("Using RetryOperation.try() is deprecated"),this.attempt(e)},r.prototype.start=function(e){console.log("Using RetryOperation.start() is deprecated"),this.attempt(e)},r.prototype.start=r.prototype.try,r.prototype.errors=function(){return this._errors},r.prototype.attempts=function(){return this._attempts},r.prototype.mainError=function(){if(0===this._errors.length)return null;for(var e={},t=null,r=0,n=0;n<this._errors.length;n++){var s=this._errors[n],o=s.message,i=(e[o]||0)+1;e[o]=i,i>=r&&(t=s,r=i)}return t}}}),k=O({"node_modules/retry/lib/retry.js"(e){var t=I();e.operation=function(r){var n=e.timeouts(r);return new t(n,{forever:r&&(r.forever||r.retries===1/0),unref:r&&r.unref,maxRetryTime:r&&r.maxRetryTime})},e.timeouts=function(e){if(e instanceof Array)return[].concat(e);var t={retries:10,factor:2,minTimeout:1e3,maxTimeout:1/0,randomize:!1};for(var r in e)t[r]=e[r];if(t.minTimeout>t.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var n=[],s=0;s<t.retries;s++)n.push(this.createTimeout(s,t));return e&&e.forever&&!n.length&&n.push(this.createTimeout(s,t)),n.sort((function(e,t){return e-t})),n},e.createTimeout=function(e,t){var r=t.randomize?Math.random()+1:1,n=Math.round(r*Math.max(t.minTimeout,1)*Math.pow(t.factor,e));return n=Math.min(n,t.maxTimeout)},e.wrap=function(t,r,n){if(r instanceof Array&&(n=r,r=null),!n)for(var s in n=[],t)"function"==typeof t[s]&&n.push(s);for(var o=0;o<n.length;o++){var i=n[o],a=t[i];t[i]=function(n){var s=e.operation(r),o=Array.prototype.slice.call(arguments,1),i=o.pop();o.push((function(e){s.retry(e)||(e&&(arguments[0]=s.mainError()),i.apply(this,arguments))})),s.attempt((function(){n.apply(t,o)}))}.bind(t,a),t[i].options=r}}}}),N=O({"node_modules/retry/index.js"(e,t){t.exports=k()}}),P=O({"node_modules/p-retry/index.js"(e,t){var r=N(),n=["Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed"],s=class extends Error{constructor(e){super(),e instanceof Error?(this.originalError=e,({message:e}=e)):(this.originalError=new Error(e),this.originalError.stack=this.stack),this.name="AbortError",this.message=e}},o=(e,t)=>new Promise(((o,i)=>{t={onFailedAttempt:()=>{},retries:10,...t};const a=r.operation(t);a.attempt((async r=>{try{o(await e(r))}catch(e){if(!(e instanceof Error))return void i(new TypeError(`Non-error was thrown: "${e}". You should only throw errors.`));if(e instanceof s)a.stop(),i(e.originalError);else if(e instanceof TypeError&&(c=e.message,!n.includes(c)))a.stop(),i(e);else{((e,t,r)=>{const n=r.retries-(t-1);e.attemptNumber=t,e.retriesLeft=n})(e,r,t);try{await t.onFailedAttempt(e)}catch(e){return void i(e)}a.retry(e)||i(a.mainError())}}var c}))}));t.exports=o,t.exports.default=o,t.exports.AbortError=s}}),x=O({"node_modules/extend/index.js"(e,t){var r=Object.prototype.hasOwnProperty,n=Object.prototype.toString,s=Object.defineProperty,o=Object.getOwnPropertyDescriptor,i=function(e){return"function"==typeof Array.isArray?Array.isArray(e):"[object Array]"===n.call(e)},a=function(e){if(!e||"[object Object]"!==n.call(e))return!1;var t,s=r.call(e,"constructor"),o=e.constructor&&e.constructor.prototype&&r.call(e.constructor.prototype,"isPrototypeOf");if(e.constructor&&!s&&!o)return!1;for(t in e);return void 0===t||r.call(e,t)},c=function(e,t){s&&"__proto__"===t.name?s(e,t.name,{enumerable:!0,configurable:!0,value:t.newValue,writable:!0}):e[t.name]=t.newValue},l=function(e,t){if("__proto__"===t){if(!r.call(e,t))return;if(o)return o(e,t).value}return e[t]};t.exports=function e(){var t,r,n,s,o,u,d=arguments[0],h=1,f=arguments.length,p=!1;for("boolean"==typeof d&&(p=d,d=arguments[1]||{},h=2),(null==d||"object"!=typeof d&&"function"!=typeof d)&&(d={});h<f;++h)if(null!=(t=arguments[h]))for(r in t)n=l(d,r),d!==(s=l(t,r))&&(p&&s&&(a(s)||(o=i(s)))?(o?(o=!1,u=n&&i(n)?n:[]):u=n&&a(n)?n:{},c(d,{name:r,newValue:e(p,u,s)})):void 0!==s&&c(d,{name:r,newValue:s}));return d}}}),D=O({"node_modules/gaxios/package.json"(e,t){t.exports={name:"gaxios",version:"7.1.4",description:"A simple common HTTP client specifically for Google APIs and services.",main:"build/cjs/src/index.js",types:"build/cjs/src/index.d.ts",files:["build/"],exports:{".":{import:{types:"./build/esm/src/index.d.ts",default:"./build/esm/src/index.js"},require:{types:"./build/cjs/src/index.d.ts",default:"./build/cjs/src/index.js"}}},scripts:{lint:"gts check --no-inline-config",test:"c8 mocha build/esm/test","presystem-test":"npm run compile","system-test":"mocha build/esm/system-test --timeout 80000",compile:"tsc -b ./tsconfig.json ./tsconfig.cjs.json && node utils/enable-esm.mjs",fix:"gts fix",prepare:"npm run compile",pretest:"npm run compile",webpack:"webpack","prebrowser-test":"npm run compile","browser-test":"node build/browser-test/browser-test-runner.js",docs:"jsdoc -c .jsdoc.js","docs-test":"linkinator docs","predocs-test":"npm run docs","samples-test":"cd samples/ && npm link ../ && npm test && cd ../",prelint:"cd samples; npm link ../; npm install",clean:"gts clean"},repository:{type:"git",directory:"packages/gaxios",url:"https://github.com/googleapis/google-cloud-node-core.git"},keywords:["google"],engines:{node:">=18"},author:"Google, LLC",license:"Apache-2.0",devDependencies:{"@babel/plugin-proposal-private-methods":"^7.18.6","@types/cors":"^2.8.6","@types/express":"^5.0.0","@types/extend":"^3.0.1","@types/mocha":"^10.0.10","@types/multiparty":"4.2.1","@types/mv":"^2.1.0","@types/ncp":"^2.0.8","@types/node":"^22.13.1","@types/sinon":"^17.0.3","@types/tmp":"^0.2.6",assert:"^2.0.0",browserify:"^17.0.0",c8:"^10.1.3",cors:"^2.8.5",express:"^5.0.0",gts:"^6.0.2","is-docker":"^3.0.0",jsdoc:"^4.0.4","jsdoc-fresh":"^5.0.0","jsdoc-region-tag":"^4.0.0",karma:"^6.0.0","karma-chrome-launcher":"^3.0.0","karma-coverage":"^2.0.0","karma-firefox-launcher":"^2.0.0","karma-mocha":"^2.0.0","karma-remap-coverage":"^0.1.5","karma-sourcemap-loader":"^0.4.0","karma-webpack":"^5.0.1",linkinator:"^6.1.2",mocha:"^11.1.0",multiparty:"^4.2.1",mv:"^2.1.1",ncp:"^2.0.0",nock:"^14.0.5","null-loader":"^4.0.1","pack-n-play":"^4.0.0",puppeteer:"^24.0.0",sinon:"^21.0.0","stream-browserify":"^3.0.0",tmp:"0.2.5","ts-loader":"^9.5.2",typescript:"5.8.3",webpack:"^5.97.1","webpack-cli":"^6.0.1"},dependencies:{extend:"^3.0.2","https-proxy-agent":"^7.0.1","node-fetch":"^3.3.2"},homepage:"https://github.com/googleapis/google-cloud-node-core/tree/main/packages/gaxios"}}}),U=O({"node_modules/gaxios/build/cjs/src/util.cjs"(e,t){var r=D();t.exports={pkg:r}}}),L=O({"node_modules/gaxios/build/cjs/src/common.js"(e){var t=e&&e.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(e,"__esModule",{value:!0}),e.GaxiosError=e.GAXIOS_ERROR_SYMBOL=void 0,e.defaultErrorRedactor=function e(t){const r="<<REDACTED> - See `errorRedactor` option in `gaxios` for configuration>.";function n(e){e&&e.forEach(((t,n)=>{(/^authentication$/i.test(n)||/^authorization$/i.test(n)||/secret/i.test(n))&&e.set(n,r)}))}function s(e,t){if("object"==typeof e&&null!==e&&"string"==typeof e[t]){const n=e[t];(/grant_type=/i.test(n)||/assertion=/i.test(n)||/secret/i.test(n))&&(e[t]=r)}}function o(e){e&&"object"==typeof e&&(e instanceof FormData||e instanceof URLSearchParams||"forEach"in e&&"set"in e?e.forEach(((t,n)=>{(["grant_type","assertion"].includes(n)||/secret/.test(n))&&e.set(n,r)})):("grant_type"in e&&(e.grant_type=r),"assertion"in e&&(e.assertion=r),"client_secret"in e&&(e.client_secret=r)))}t.config&&(n(t.config.headers),s(t.config,"data"),o(t.config.data),s(t.config,"body"),o(t.config.body),t.config.url.searchParams.has("token")&&t.config.url.searchParams.set("token",r),t.config.url.searchParams.has("client_secret")&&t.config.url.searchParams.set("client_secret",r));t.response&&(e({config:t.response.config}),n(t.response.headers),t.response.bodyUsed&&(s(t.response,"data"),o(t.response.data)));return t};var r=t(x()),n=t(U()).default.pkg;e.GAXIOS_ERROR_SYMBOL=Symbol.for(`${n.name}-gaxios-error`);var s=class t extends Error{config;response;code;status;error;[e.GAXIOS_ERROR_SYMBOL]=n.version;static[Symbol.hasInstance](r){return!(!r||"object"!=typeof r||!(e.GAXIOS_ERROR_SYMBOL in r)||r[e.GAXIOS_ERROR_SYMBOL]!==n.version)||Function.prototype[Symbol.hasInstance].call(t,r)}constructor(e,t,n,s){if(super(e,{cause:s}),this.config=t,this.response=n,this.error=s instanceof Error?s:void 0,this.config=(0,r.default)(!0,{},t),this.response&&(this.response.config=(0,r.default)(!0,{},this.response.config)),this.response){try{this.response.data=function(e,t){switch(e){case"stream":default:return t;case"json":return JSON.parse(JSON.stringify(t));case"arraybuffer":return JSON.parse(Buffer.from(t).toString("utf8"));case"blob":return JSON.parse(t.text())}}(this.config.responseType,this.response?.bodyUsed?this.response?.data:void 0)}catch{}this.status=this.response.status}s instanceof DOMException?this.code=s.name:s&&"object"==typeof s&&"code"in s&&("string"==typeof s.code||"number"==typeof s.code)&&(this.code=s.code)}static extractAPIErrorFromResponse(e,t="The request failed"){let r=t;if("string"==typeof e.data&&(r=e.data),e.data&&"object"==typeof e.data&&"error"in e.data&&e.data.error&&!e.ok){if("string"==typeof e.data.error)return{message:e.data.error,code:e.status,status:e.statusText};if("object"==typeof e.data.error){r="message"in e.data.error&&"string"==typeof e.data.error.message?e.data.error.message:r;const t="status"in e.data.error&&"string"==typeof e.data.error.status?e.data.error.status:e.statusText,n="code"in e.data.error&&"number"==typeof e.data.error.code?e.data.error.code:e.status;if("errors"in e.data.error&&Array.isArray(e.data.error.errors)){const s=[];for(const t of e.data.error.errors)"object"==typeof t&&"message"in t&&"string"==typeof t.message&&s.push(t.message);return Object.assign({message:s.join("\n")||r,code:n,status:t},e.data.error)}return Object.assign({message:r,code:n,status:t},e.data.error)}}return{message:r,code:e.status,status:e.statusText}}};e.GaxiosError=s}}),j=O({"node_modules/gaxios/build/cjs/src/retry.js"(e){function t(e){const t=r(e);if(e.config.signal?.aborted&&"TimeoutError"!==e.code||"AbortError"===e.code)return!1;if(!t||0===t.retry)return!1;if(!e.response&&(t.currentRetryAttempt||0)>=t.noResponseRetries)return!1;if(!t.httpMethodsToRetry||!t.httpMethodsToRetry.includes(e.config.method?.toUpperCase()||"GET"))return!1;if(e.response&&e.response.status){let r=!1;for(const[n,s]of t.statusCodesToRetry){const t=e.response.status;if(t>=n&&t<=s){r=!0;break}}if(!r)return!1}return t.currentRetryAttempt=t.currentRetryAttempt||0,!(t.currentRetryAttempt>=t.retry)}function r(e){if(e&&e.config&&e.config.retryConfig)return e.config.retryConfig}Object.defineProperty(e,"__esModule",{value:!0}),e.getRetryConfig=async function(e){let n=r(e);if(!e||!e.config||!n&&!e.config.retry)return{shouldRetry:!1};n=n||{},n.currentRetryAttempt=n.currentRetryAttempt||0,n.retry=void 0===n.retry||null===n.retry?3:n.retry,n.httpMethodsToRetry=n.httpMethodsToRetry||["GET","HEAD","PUT","OPTIONS","DELETE"],n.noResponseRetries=void 0===n.noResponseRetries||null===n.noResponseRetries?2:n.noResponseRetries,n.retryDelayMultiplier=n.retryDelayMultiplier?n.retryDelayMultiplier:2,n.timeOfFirstRequest=n.timeOfFirstRequest?n.timeOfFirstRequest:Date.now(),n.totalTimeout=n.totalTimeout?n.totalTimeout:Number.MAX_SAFE_INTEGER,n.maxRetryDelay=n.maxRetryDelay?n.maxRetryDelay:Number.MAX_SAFE_INTEGER;n.statusCodesToRetry=n.statusCodesToRetry||[[100,199],[408,408],[429,429],[500,599]],e.config.retryConfig=n;const s=n.shouldRetry||t;if(!await s(e))return{shouldRetry:!1,config:e.config};const o=function(e){const t=e.currentRetryAttempt?0:e.retryDelay??100,r=t+(Math.pow(e.retryDelayMultiplier,e.currentRetryAttempt)-1)/2*1e3,n=e.totalTimeout-(Date.now()-e.timeOfFirstRequest);return Math.min(r,n,e.maxRetryDelay)}(n);e.config.retryConfig.currentRetryAttempt+=1;const i=n.retryBackoff?n.retryBackoff(e,o):new Promise((e=>{setTimeout(e,o)}));n.onRetryAttempt&&await n.onRetryAttempt(e);return await i,{shouldRetry:!0,config:e.config}}}}),M=O({"node_modules/gaxios/build/cjs/src/interceptor.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.GaxiosInterceptorManager=void 0;var t=class extends Set{};e.GaxiosInterceptorManager=t}}),F=O({"node_modules/ms/index.js"(e,t){var r=1e3,n=6e4,s=60*n,o=24*s,i=7*o,a=365.25*o;function c(e,t,r,n){var s=t>=1.5*r;return Math.round(e/r)+" "+n+(s?"s":"")}t.exports=function(e,t){t=t||{};var l=typeof e;if("string"===l&&e.length>0)return function(e){if((e=String(e)).length>100)return;var t=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(!t)return;var c=parseFloat(t[1]);switch((t[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return c*a;case"weeks":case"week":case"w":return c*i;case"days":case"day":case"d":return c*o;case"hours":case"hour":case"hrs":case"hr":case"h":return c*s;case"minutes":case"minute":case"mins":case"min":case"m":return c*n;case"seconds":case"second":case"secs":case"sec":case"s":return c*r;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return c;default:return}}(e);if("number"===l&&isFinite(e))return t.long?function(e){var t=Math.abs(e);if(t>=o)return c(e,t,o,"day");if(t>=s)return c(e,t,s,"hour");if(t>=n)return c(e,t,n,"minute");if(t>=r)return c(e,t,r,"second");return e+" ms"}(e):function(e){var t=Math.abs(e);if(t>=o)return Math.round(e/o)+"d";if(t>=s)return Math.round(e/s)+"h";if(t>=n)return Math.round(e/n)+"m";if(t>=r)return Math.round(e/r)+"s";return e+"ms"}(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))}}}),B=O({"node_modules/debug/src/common.js"(e,t){t.exports=function(e){function t(e){let n,s,o,i=null;function a(...e){if(!a.enabled)return;const r=a,s=Number(new Date),o=s-(n||s);r.diff=o,r.prev=n,r.curr=s,n=s,e[0]=t.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let i=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,((n,s)=>{if("%%"===n)return"%";i++;const o=t.formatters[s];if("function"==typeof o){const t=e[i];n=o.call(r,t),e.splice(i,1),i--}return n})),t.formatArgs.call(r,e);(r.log||t.log).apply(r,e)}return a.namespace=e,a.useColors=t.useColors(),a.color=t.selectColor(e),a.extend=r,a.destroy=t.destroy,Object.defineProperty(a,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==i?i:(s!==t.namespaces&&(s=t.namespaces,o=t.enabled(e)),o),set:e=>{i=e}}),"function"==typeof t.init&&t.init(a),a}function r(e,r){const n=t(this.namespace+(void 0===r?":":r)+e);return n.log=this.log,n}function n(e,t){let r=0,n=0,s=-1,o=0;for(;r<e.length;)if(n<t.length&&(t[n]===e[r]||"*"===t[n]))"*"===t[n]?(s=n,o=r,n++):(r++,n++);else{if(-1===s)return!1;n=s+1,o++,r=o}for(;n<t.length&&"*"===t[n];)n++;return n===t.length}return t.debug=t,t.default=t,t.coerce=function(e){if(e instanceof Error)return e.stack||e.message;return e},t.disable=function(){const e=[...t.names,...t.skips.map((e=>"-"+e))].join(",");return t.enable(""),e},t.enable=function(e){t.save(e),t.namespaces=e,t.names=[],t.skips=[];const r=("string"==typeof e?e:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(const e of r)"-"===e[0]?t.skips.push(e.slice(1)):t.names.push(e)},t.enabled=function(e){for(const r of t.skips)if(n(e,r))return!1;for(const r of t.names)if(n(e,r))return!0;return!1},t.humanize=F(),t.destroy=function(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")},Object.keys(e).forEach((r=>{t[r]=e[r]})),t.names=[],t.skips=[],t.formatters={},t.selectColor=function(e){let r=0;for(let t=0;t<e.length;t++)r=(r<<5)-r+e.charCodeAt(t),r|=0;return t.colors[Math.abs(r)%t.colors.length]},t.enable(t.load()),t}}}),G=O({"node_modules/debug/src/browser.js"(e,t){e.formatArgs=function(e){if(e[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+e[0]+(this.useColors?"%c ":" ")+"+"+t.exports.humanize(this.diff),!this.useColors)return;const r="color: "+this.color;e.splice(1,0,r,"color: inherit");let n=0,s=0;e[0].replace(/%[a-zA-Z%]/g,(e=>{"%%"!==e&&(n++,"%c"===e&&(s=n))})),e.splice(s,0,r)},e.save=function(t){try{t?e.storage.setItem("debug",t):e.storage.removeItem("debug")}catch(e){}},e.load=function(){let t;try{t=e.storage.getItem("debug")||e.storage.getItem("DEBUG")}catch(e){}!t&&"undefined"!=typeof process&&"env"in process&&(t=process.env.DEBUG);return t},e.useColors=function(){if("undefined"!=typeof window&&window.process&&("renderer"===window.process.type||window.process.__nwjs))return!0;if("undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let e;return"undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&(e=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(e[1],10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)},e.storage=function(){try{return localStorage}catch(e){}}(),e.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),e.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],e.log=console.debug||console.log||(()=>{}),t.exports=B()(e);var{formatters:r}=t.exports;r.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}}),H=O({"node_modules/has-flag/index.js"(e,t){t.exports=(e,t=process.argv)=>{const r=e.startsWith("-")?"":1===e.length?"-":"--",n=t.indexOf(r+e),s=t.indexOf("--");return-1!==n&&(-1===s||n<s)}}}),q=O({"node_modules/supports-color/index.js"(e,t){var r,n=S("os"),s=S("tty"),o=H(),{env:i}=process;function a(e){return 0!==e&&{level:e,hasBasic:!0,has256:e>=2,has16m:e>=3}}function c(e,t){if(0===r)return 0;if(o("color=16m")||o("color=full")||o("color=truecolor"))return 3;if(o("color=256"))return 2;if(e&&!t&&void 0===r)return 0;const s=r||0;if("dumb"===i.TERM)return s;if("win32"===process.platform){const e=n.release().split(".");return Number(e[0])>=10&&Number(e[2])>=10586?Number(e[2])>=14931?3:2:1}if("CI"in i)return["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE"].some((e=>e in i))||"codeship"===i.CI_NAME?1:s;if("TEAMCITY_VERSION"in i)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(i.TEAMCITY_VERSION)?1:0;if("truecolor"===i.COLORTERM)return 3;if("TERM_PROGRAM"in i){const e=parseInt((i.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(i.TERM_PROGRAM){case"iTerm.app":return e>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(i.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(i.TERM)||"COLORTERM"in i?1:s}o("no-color")||o("no-colors")||o("color=false")||o("color=never")?r=0:(o("color")||o("colors")||o("color=true")||o("color=always"))&&(r=1),"FORCE_COLOR"in i&&(r="true"===i.FORCE_COLOR?1:"false"===i.FORCE_COLOR?0:0===i.FORCE_COLOR.length?1:Math.min(parseInt(i.FORCE_COLOR,10),3)),t.exports={supportsColor:function(e){return a(c(e,e&&e.isTTY))},stdout:a(c(!0,s.isatty(1))),stderr:a(c(!0,s.isatty(2)))}}}),$=O({"node_modules/debug/src/node.js"(e,t){var r=S("tty"),n=S("util");e.init=function(t){t.inspectOpts={};const r=Object.keys(e.inspectOpts);for(let n=0;n<r.length;n++)t.inspectOpts[r[n]]=e.inspectOpts[r[n]]},e.log=function(...t){return process.stderr.write(n.formatWithOptions(e.inspectOpts,...t)+"\n")},e.formatArgs=function(r){const{namespace:n,useColors:s}=this;if(s){const e=this.color,s="[3"+(e<8?e:"8;5;"+e),o=` ${s};1m${n} [0m`;r[0]=o+r[0].split("\n").join("\n"+o),r.push(s+"m+"+t.exports.humanize(this.diff)+"[0m")}else r[0]=function(){if(e.inspectOpts.hideDate)return"";return(new Date).toISOString()+" "}()+n+" "+r[0]},e.save=function(e){e?process.env.DEBUG=e:delete process.env.DEBUG},e.load=function(){return process.env.DEBUG},e.useColors=function(){return"colors"in e.inspectOpts?Boolean(e.inspectOpts.colors):r.isatty(process.stderr.fd)},e.destroy=n.deprecate((()=>{}),"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."),e.colors=[6,2,3,4,5,1];try{const t=q();t&&(t.stderr||t).level>=2&&(e.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221])}catch(e){}e.inspectOpts=Object.keys(process.env).filter((e=>/^debug_/i.test(e))).reduce(((e,t)=>{const r=t.substring(6).toLowerCase().replace(/_([a-z])/g,((e,t)=>t.toUpperCase()));let n=process.env[t];return n=!!/^(yes|on|true|enabled)$/i.test(n)||!/^(no|off|false|disabled)$/i.test(n)&&("null"===n?null:Number(n)),e[r]=n,e}),{}),t.exports=B()(e);var{formatters:s}=t.exports;s.o=function(e){return this.inspectOpts.colors=this.useColors,n.inspect(e,this.inspectOpts).split("\n").map((e=>e.trim())).join(" ")},s.O=function(e){return this.inspectOpts.colors=this.useColors,n.inspect(e,this.inspectOpts)}}}),W=O({"node_modules/debug/src/index.js"(e,t){"undefined"==typeof process||"renderer"===process.type||!0===process.browser||process.__nwjs?t.exports=G():t.exports=$()}}),V=O({"node_modules/agent-base/dist/helpers.js"(e){var t=e&&e.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var s=Object.getOwnPropertyDescriptor(t,r);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,s)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),r=e&&e.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=e&&e.__importStar||function(e){if(e&&e.__esModule)return e;var n={};if(null!=e)for(var s in e)"default"!==s&&Object.prototype.hasOwnProperty.call(e,s)&&t(n,e,s);return r(n,e),n};Object.defineProperty(e,"__esModule",{value:!0}),e.req=e.json=e.toBuffer=void 0;var s=n(S("http")),o=n(S("https"));async function i(e){let t=0;const r=[];for await(const n of e)t+=n.length,r.push(n);return Buffer.concat(r,t)}e.toBuffer=i,e.json=async function(e){const t=(await i(e)).toString("utf8");try{return JSON.parse(t)}catch(e){const r=e;throw r.message+=` (input: ${t})`,r}},e.req=function(e,t={}){const r=(("string"==typeof e?e:e.href).startsWith("https:")?o:s).request(e,t),n=new Promise(((e,t)=>{r.once("response",e).once("error",t).end()}));return r.then=n.then.bind(n),r}}}),Y=O({"node_modules/agent-base/dist/index.js"(e){var t=e&&e.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var s=Object.getOwnPropertyDescriptor(t,r);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,s)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),r=e&&e.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=e&&e.__importStar||function(e){if(e&&e.__esModule)return e;var n={};if(null!=e)for(var s in e)"default"!==s&&Object.prototype.hasOwnProperty.call(e,s)&&t(n,e,s);return r(n,e),n},s=e&&e.__exportStar||function(e,r){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(r,n)||t(r,e,n)};Object.defineProperty(e,"__esModule",{value:!0}),e.Agent=void 0;var o=n(S("net")),i=n(S("http")),a=S("https");s(V(),e);var c=Symbol("AgentBaseInternalState"),l=class extends i.Agent{constructor(e){super(e),this[c]={}}isSecureEndpoint(e){if(e){if("boolean"==typeof e.secureEndpoint)return e.secureEndpoint;if("string"==typeof e.protocol)return"https:"===e.protocol}const{stack:t}=new Error;return"string"==typeof t&&t.split("\n").some((e=>-1!==e.indexOf("(https.js:")||-1!==e.indexOf("node:https:")))}incrementSockets(e){if(this.maxSockets===1/0&&this.maxTotalSockets===1/0)return null;this.sockets[e]||(this.sockets[e]=[]);const t=new o.Socket({writable:!1});return this.sockets[e].push(t),this.totalSocketCount++,t}decrementSockets(e,t){if(!this.sockets[e]||null===t)return;const r=this.sockets[e],n=r.indexOf(t);-1!==n&&(r.splice(n,1),this.totalSocketCount--,0===r.length&&delete this.sockets[e])}getName(e){return("boolean"==typeof e.secureEndpoint?e.secureEndpoint:this.isSecureEndpoint(e))?a.Agent.prototype.getName.call(this,e):super.getName(e)}createSocket(e,t,r){const n={...t,secureEndpoint:this.isSecureEndpoint(t)},s=this.getName(n),o=this.incrementSockets(s);Promise.resolve().then((()=>this.connect(e,n))).then((a=>{if(this.decrementSockets(s,o),a instanceof i.Agent)try{return a.addRequest(e,n)}catch(e){return r(e)}this[c].currentSocket=a,super.createSocket(e,t,r)}),(e=>{this.decrementSockets(s,o),r(e)}))}createConnection(){const e=this[c].currentSocket;if(this[c].currentSocket=void 0,!e)throw new Error("No socket was returned in the `connect()` function");return e}get defaultPort(){return this[c].defaultPort??("https:"===this.protocol?443:80)}set defaultPort(e){this[c]&&(this[c].defaultPort=e)}get protocol(){return this[c].protocol??(this.isSecureEndpoint()?"https:":"http:")}set protocol(e){this[c]&&(this[c].protocol=e)}};e.Agent=l}}),z=O({"node_modules/https-proxy-agent/dist/parse-proxy-response.js"(e){var t=e&&e.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(e,"__esModule",{value:!0}),e.parseProxyResponse=void 0;var r=(0,t(W()).default)("https-proxy-agent:parse-proxy-response");e.parseProxyResponse=function(e){return new Promise(((t,n)=>{let s=0;const o=[];function i(){const c=e.read();c?function(c){o.push(c),s+=c.length;const l=Buffer.concat(o,s),u=l.indexOf("\r\n\r\n");if(-1===u)return r("have not received end of HTTP headers yet..."),void i();const d=l.slice(0,u).toString("ascii").split("\r\n"),h=d.shift();if(!h)return e.destroy(),n(new Error("No header received from proxy CONNECT response"));const f=h.split(" "),p=+f[1],m=f.slice(2).join(" "),_={};for(const t of d){if(!t)continue;const r=t.indexOf(":");if(-1===r)return e.destroy(),n(new Error(`Invalid header from proxy CONNECT response: "${t}"`));const s=t.slice(0,r).toLowerCase(),o=t.slice(r+1).trimStart(),i=_[s];"string"==typeof i?_[s]=[i,o]:Array.isArray(i)?i.push(o):_[s]=o}r("got proxy server response: %o %o",h,_),a(),t({connect:{statusCode:p,statusText:m,headers:_},buffered:l})}(c):e.once("readable",i)}function a(){e.removeListener("end",c),e.removeListener("error",l),e.removeListener("readable",i)}function c(){a(),r("onend"),n(new Error("Proxy connection ended before receiving CONNECT response"))}function l(e){a(),r("onerror %o",e),n(e)}e.on("error",l),e.on("end",c),i()}))}}}),J=O({"node_modules/https-proxy-agent/dist/index.js"(e){var t=e&&e.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var s=Object.getOwnPropertyDescriptor(t,r);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,s)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),r=e&&e.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=e&&e.__importStar||function(e){if(e&&e.__esModule)return e;var n={};if(null!=e)for(var s in e)"default"!==s&&Object.prototype.hasOwnProperty.call(e,s)&&t(n,e,s);return r(n,e),n},s=e&&e.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(e,"__esModule",{value:!0}),e.HttpsProxyAgent=void 0;var o=n(S("net")),i=n(S("tls")),a=s(S("assert")),c=s(W()),l=Y(),u=S("url"),d=z(),h=(0,c.default)("https-proxy-agent"),f=e=>void 0===e.servername&&e.host&&!o.isIP(e.host)?{...e,servername:e.host}:e,p=class extends l.Agent{constructor(e,t){super(t),this.options={path:void 0},this.proxy="string"==typeof e?new u.URL(e):e,this.proxyHeaders=t?.headers??{},h("Creating new HttpsProxyAgent instance: %o",this.proxy.href);const r=(this.proxy.hostname||this.proxy.host).replace(/^\[|\]$/g,""),n=this.proxy.port?parseInt(this.proxy.port,10):"https:"===this.proxy.protocol?443:80;this.connectOpts={ALPNProtocols:["http/1.1"],...t?_(t,"headers"):null,host:r,port:n}}async connect(e,t){const{proxy:r}=this;if(!t.host)throw new TypeError('No "host" provided');let n;"https:"===r.protocol?(h("Creating `tls.Socket`: %o",this.connectOpts),n=i.connect(f(this.connectOpts))):(h("Creating `net.Socket`: %o",this.connectOpts),n=o.connect(this.connectOpts));const s="function"==typeof this.proxyHeaders?this.proxyHeaders():{...this.proxyHeaders},c=o.isIPv6(t.host)?`[${t.host}]`:t.host;let l=`CONNECT ${c}:${t.port} HTTP/1.1\r\n`;if(r.username||r.password){const e=`${decodeURIComponent(r.username)}:${decodeURIComponent(r.password)}`;s["Proxy-Authorization"]=`Basic ${Buffer.from(e).toString("base64")}`}s.Host=`${c}:${t.port}`,s["Proxy-Connection"]||(s["Proxy-Connection"]=this.keepAlive?"Keep-Alive":"close");for(const e of Object.keys(s))l+=`${e}: ${s[e]}\r\n`;const u=(0,d.parseProxyResponse)(n);n.write(`${l}\r\n`);const{connect:p,buffered:y}=await u;if(e.emit("proxyConnect",p),this.emit("proxyConnect",p,e),200===p.statusCode)return e.once("socket",m),t.secureEndpoint?(h("Upgrading socket connection to TLS"),i.connect({..._(f(t),"host","path","port"),socket:n})):n;n.destroy();const g=new o.Socket({writable:!1});return g.readable=!0,e.once("socket",(e=>{h("Replaying proxy buffer for failed request"),(0,a.default)(e.listenerCount("data")>0),e.push(y),e.push(null)})),g}};function m(e){e.resume()}function _(e,...t){const r={};let n;for(n in e)t.includes(n)||(r[n]=e[n]);return r}p.protocols=["http","https"],e.HttpsProxyAgent=p}});function K(e){if(!/^data:/i.test(e))throw new TypeError('`uri` does not appear to be a Data URI (must begin with "data:")');const t=(e=e.replace(/\r?\n/g,"")).indexOf(",");if(-1===t||t<=4)throw new TypeError("malformed data: URI");const r=e.substring(5,t).split(";");let n="",s=!1;const o=r[0]||"text/plain";let i=o;for(let e=1;e<r.length;e++)"base64"===r[e]?s=!0:r[e]&&(i+=`;${r[e]}`,0===r[e].indexOf("charset=")&&(n=r[e].substring(8)));r[0]||n.length||(i+=";charset=US-ASCII",n="US-ASCII");const a=s?"base64":"ascii",c=unescape(e.substring(t+1)),l=Buffer.from(c,a);return l.type=o,l.typeFull=i,l.charset=n,l}var X,Z,Q,ee=A({"node_modules/data-uri-to-buffer/dist/index.js"(){f=K}}),te=O({"node_modules/web-streams-polyfill/dist/ponyfill.es2018.js"(e,t){var r,n;r=e,n=function(e){function t(){}function r(e){return"object"==typeof e&&null!==e||"function"==typeof e}const n=t;function s(e,t){try{Object.defineProperty(e,"name",{value:t,configurable:!0})}catch(e){}}const o=Promise,i=Promise.prototype.then,a=Promise.reject.bind(o);function c(e){return new o(e)}function l(e){return c((t=>t(e)))}function u(e){return a(e)}function d(e,t,r){return i.call(e,t,r)}function h(e,t,r){d(d(e,t,r),void 0,n)}function f(e,t){h(e,t)}function p(e,t){h(e,void 0,t)}function m(e,t,r){return d(e,t,r)}function _(e){d(e,void 0,n)}let y=e=>{if("function"==typeof queueMicrotask)y=queueMicrotask;else{const e=l(void 0);y=t=>d(e,t)}return y(e)};function g(e,t,r){if("function"!=typeof e)throw new TypeError("Argument is not a function");return Function.prototype.apply.call(e,t,r)}function E(e,t,r){try{return l(g(e,t,r))}catch(e){return u(e)}}class b{constructor(){this._cursor=0,this._size=0,this._front={_elements:[],_next:void 0},this._back=this._front,this._cursor=0,this._size=0}get length(){return this._size}push(e){const t=this._back;let r=t;16383===t._elements.length&&(r={_elements:[],_next:void 0}),t._elements.push(e),r!==t&&(this._back=r,t._next=r),++this._size}shift(){const e=this._front;let t=e;const r=this._cursor;let n=r+1;const s=e._elements,o=s[r];return 16384===n&&(t=e._next,n=0),--this._size,this._cursor=n,e!==t&&(this._front=t),s[r]=void 0,o}forEach(e){let t=this._cursor,r=this._front,n=r._elements;for(;!(t===n.length&&void 0===r._next||t===n.length&&(r=r._next,n=r._elements,t=0,0===n.length));)e(n[t]),++t}peek(){const e=this._front,t=this._cursor;return e._elements[t]}}const w=Symbol("[[AbortSteps]]"),T=Symbol("[[ErrorSteps]]"),v=Symbol("[[CancelSteps]]"),S=Symbol("[[PullSteps]]"),A=Symbol("[[ReleaseSteps]]");function O(e,t){e._ownerReadableStream=t,t._reader=e,"readable"===t._state?k(e):"closed"===t._state?function(e){k(e),x(e)}(e):N(e,t._storedError)}function R(e,t){return jr(e._ownerReadableStream,t)}function C(e){const t=e._ownerReadableStream;"readable"===t._state?P(e,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")):function(e,t){N(e,t)}(e,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")),t._readableStreamController[A](),t._reader=void 0,e._ownerReadableStream=void 0}function I(e){return new TypeError("Cannot "+e+" a stream using a released reader")}function k(e){e._closedPromise=c(((t,r)=>{e._closedPromise_resolve=t,e._closedPromise_reject=r}))}function N(e,t){k(e),P(e,t)}function P(e,t){void 0!==e._closedPromise_reject&&(_(e._closedPromise),e._closedPromise_reject(t),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0)}function x(e){void 0!==e._closedPromise_resolve&&(e._closedPromise_resolve(void 0),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0)}const D=Number.isFinite||function(e){return"number"==typeof e&&isFinite(e)},U=Math.trunc||function(e){return e<0?Math.ceil(e):Math.floor(e)};function L(e,t){if(void 0!==e&&"object"!=typeof(r=e)&&"function"!=typeof r)throw new TypeError(`${t} is not an object.`);var r}function j(e,t){if("function"!=typeof e)throw new TypeError(`${t} is not a function.`)}function M(e,t){if(!function(e){return"object"==typeof e&&null!==e||"function"==typeof e}(e))throw new TypeError(`${t} is not an object.`)}function F(e,t,r){if(void 0===e)throw new TypeError(`Parameter ${t} is required in '${r}'.`)}function B(e,t,r){if(void 0===e)throw new TypeError(`${t} is required in '${r}'.`)}function G(e){return Number(e)}function H(e){return 0===e?0:e}function q(e,t){const r=Number.MAX_SAFE_INTEGER;let n=Number(e);if(n=H(n),!D(n))throw new TypeError(`${t} is not a finite number`);if(n=function(e){return H(U(e))}(n),n<0||n>r)throw new TypeError(`${t} is outside the accepted range of 0 to ${r}, inclusive`);return D(n)&&0!==n?n:0}function $(e,t){if(!Ur(e))throw new TypeError(`${t} is not a ReadableStream.`)}function W(e){return new K(e)}function V(e,t){e._reader._readRequests.push(t)}function Y(e,t,r){const n=e._reader._readRequests.shift();r?n._closeSteps():n._chunkSteps(t)}function z(e){return e._reader._readRequests.length}function J(e){const t=e._reader;return void 0!==t&&!!X(t)}class K{constructor(e){if(F(e,1,"ReadableStreamDefaultReader"),$(e,"First parameter"),Lr(e))throw new TypeError("This stream has already been locked for exclusive reading by another reader");O(this,e),this._readRequests=new b}get closed(){return X(this)?this._closedPromise:u(ee("closed"))}cancel(e=void 0){return X(this)?void 0===this._ownerReadableStream?u(I("cancel")):R(this,e):u(ee("cancel"))}read(){if(!X(this))return u(ee("read"));if(void 0===this._ownerReadableStream)return u(I("read from"));let e,t;const r=c(((r,n)=>{e=r,t=n}));return Z(this,{_chunkSteps:t=>e({value:t,done:!1}),_closeSteps:()=>e({value:void 0,done:!0}),_errorSteps:e=>t(e)}),r}releaseLock(){if(!X(this))throw ee("releaseLock");void 0!==this._ownerReadableStream&&function(e){C(e);const t=new TypeError("Reader was released");Q(e,t)}(this)}}function X(e){return!!r(e)&&!!Object.prototype.hasOwnProperty.call(e,"_readRequests")&&e instanceof K}function Z(e,t){const r=e._ownerReadableStream;r._disturbed=!0,"closed"===r._state?t._closeSteps():"errored"===r._state?t._errorSteps(r._storedError):r._readableStreamController[S](t)}function Q(e,t){const r=e._readRequests;e._readRequests=new b,r.forEach((e=>{e._errorSteps(t)}))}function ee(e){return new TypeError(`ReadableStreamDefaultReader.prototype.${e} can only be used on a ReadableStreamDefaultReader`)}Object.defineProperties(K.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),s(K.prototype.cancel,"cancel"),s(K.prototype.read,"read"),s(K.prototype.releaseLock,"releaseLock"),"symbol"==typeof Symbol.toStringTag&&Object.defineProperty(K.prototype,Symbol.toStringTag,{value:"ReadableStreamDefaultReader",configurable:!0});const te=Object.getPrototypeOf(Object.getPrototypeOf((async function*(){})).prototype);class re{constructor(e,t){this._ongoingPromise=void 0,this._isFinished=!1,this._reader=e,this._preventCancel=t}next(){const e=()=>this._nextSteps();return this._ongoingPromise=this._ongoingPromise?m(this._ongoingPromise,e,e):e(),this._ongoingPromise}return(e){const t=()=>this._returnSteps(e);return this._ongoingPromise?m(this._ongoingPromise,t,t):t()}_nextSteps(){if(this._isFinished)return Promise.resolve({value:void 0,done:!0});const e=this._reader;let t,r;const n=c(((e,n)=>{t=e,r=n}));return Z(e,{_chunkSteps:e=>{this._ongoingPromise=void 0,y((()=>t({value:e,done:!1})))},_closeSteps:()=>{this._ongoingPromise=void 0,this._isFinished=!0,C(e),t({value:void 0,done:!0})},_errorSteps:t=>{this._ongoingPromise=void 0,this._isFinished=!0,C(e),r(t)}}),n}_returnSteps(e){if(this._isFinished)return Promise.resolve({value:e,done:!0});this._isFinished=!0;const t=this._reader;if(!this._preventCancel){const r=R(t,e);return C(t),m(r,(()=>({value:e,done:!0})))}return C(t),l({value:e,done:!0})}}const ne={next(){return se(this)?this._asyncIteratorImpl.next():u(oe("next"))},return(e){return se(this)?this._asyncIteratorImpl.return(e):u(oe("return"))}};function se(e){if(!r(e))return!1;if(!Object.prototype.hasOwnProperty.call(e,"_asyncIteratorImpl"))return!1;try{return e._asyncIteratorImpl instanceof re}catch(e){return!1}}function oe(e){return new TypeError(`ReadableStreamAsyncIterator.${e} can only be used on a ReadableSteamAsyncIterator`)}Object.setPrototypeOf(ne,te);const ie=Number.isNaN||function(e){return e!=e};var ae,ce,le;function ue(e){return e.slice()}function de(e,t,r,n,s){new Uint8Array(e).set(new Uint8Array(r,n,s),t)}let he=e=>(he="function"==typeof e.transfer?e=>e.transfer():"function"==typeof structuredClone?e=>structuredClone(e,{transfer:[e]}):e=>e,he(e)),fe=e=>(fe="boolean"==typeof e.detached?e=>e.detached:e=>0===e.byteLength,fe(e));function pe(e,t,r){if(e.slice)return e.slice(t,r);const n=r-t,s=new ArrayBuffer(n);return de(s,0,e,t,n),s}function me(e,t){const r=e[t];if(null!=r){if("function"!=typeof r)throw new TypeError(`${String(t)} is not a function`);return r}}const _e=null!==(le=null!==(ae=Symbol.asyncIterator)&&void 0!==ae?ae:null===(ce=Symbol.for)||void 0===ce?void 0:ce.call(Symbol,"Symbol.asyncIterator"))&&void 0!==le?le:"@@asyncIterator";function ye(e,t="sync",n){if(void 0===n)if("async"===t){if(void 0===(n=me(e,_e)))return function(e){const t={[Symbol.iterator]:()=>e.iterator},r=async function*(){return yield*t}();return{iterator:r,nextMethod:r.next,done:!1}}(ye(e,"sync",me(e,Symbol.iterator)))}else n=me(e,Symbol.iterator);if(void 0===n)throw new TypeError("The object is not iterable");const s=g(n,e,[]);if(!r(s))throw new TypeError("The iterator method must return an object");return{iterator:s,nextMethod:s.next,done:!1}}function ge(e){const t=pe(e.buffer,e.byteOffset,e.byteOffset+e.byteLength);return new Uint8Array(t)}function Ee(e){const t=e._queue.shift();return e._queueTotalSize-=t.size,e._queueTotalSize<0&&(e._queueTotalSize=0),t.value}function be(e,t,r){if("number"!=typeof(n=r)||ie(n)||n<0||r===1/0)throw new RangeError("Size must be a finite, non-NaN, non-negative number.");var n;e._queue.push({value:t,size:r}),e._queueTotalSize+=r}function we(e){e._queue=new b,e._queueTotalSize=0}function Te(e){return e===DataView}class ve{constructor(){throw new TypeError("Illegal constructor")}get view(){if(!Oe(this))throw Ze("view");return this._view}respond(e){if(!Oe(this))throw Ze("respond");if(F(e,1,"respond"),e=q(e,"First parameter"),void 0===this._associatedReadableByteStreamController)throw new TypeError("This BYOB request has been invalidated");if(fe(this._view.buffer))throw new TypeError("The BYOB request's buffer has been detached and so cannot be used as a response");Je(this._associatedReadableByteStreamController,e)}respondWithNewView(e){if(!Oe(this))throw Ze("respondWithNewView");if(F(e,1,"respondWithNewView"),!ArrayBuffer.isView(e))throw new TypeError("You can only respond with array buffer views");if(void 0===this._associatedReadableByteStreamController)throw new TypeError("This BYOB request has been invalidated");if(fe(e.buffer))throw new TypeError("The given view's buffer has been detached and so cannot be used as a response");Ke(this._associatedReadableByteStreamController,e)}}Object.defineProperties(ve.prototype,{respond:{enumerable:!0},respondWithNewView:{enumerable:!0},view:{enumerable:!0}}),s(ve.prototype.respond,"respond"),s(ve.prototype.respondWithNewView,"respondWithNewView"),"symbol"==typeof Symbol.toStringTag&&Object.defineProperty(ve.prototype,Symbol.toStringTag,{value:"ReadableStreamBYOBRequest",configurable:!0});class Se{constructor(){throw new TypeError("Illegal constructor")}get byobRequest(){if(!Ae(this))throw Qe("byobRequest");return Ye(this)}get desiredSize(){if(!Ae(this))throw Qe("desiredSize");return ze(this)}close(){if(!Ae(this))throw Qe("close");if(this._closeRequested)throw new TypeError("The stream has already been closed; do not close it again!");const e=this._controlledReadableByteStream._state;if("readable"!==e)throw new TypeError(`The stream (in ${e} state) is not in the readable state and cannot be closed`);qe(this)}enqueue(e){if(!Ae(this))throw Qe("enqueue");if(F(e,1,"enqueue"),!ArrayBuffer.isView(e))throw new TypeError("chunk must be an array buffer view");if(0===e.byteLength)throw new TypeError("chunk must have non-zero byteLength");if(0===e.buffer.byteLength)throw new TypeError("chunk's buffer must have non-zero byteLength");if(this._closeRequested)throw new TypeError("stream is closed or draining");const t=this._controlledReadableByteStream._state;if("readable"!==t)throw new TypeError(`The stream (in ${t} state) is not in the readable state and cannot be enqueued to`);$e(this,e)}error(e=void 0){if(!Ae(this))throw Qe("error");We(this,e)}[v](e){Ce(this),we(this);const t=this._cancelAlgorithm(e);return He(this),t}[S](e){const t=this._controlledReadableByteStream;if(this._queueTotalSize>0)return void Ve(this,e);const r=this._autoAllocateChunkSize;if(void 0!==r){let t;try{t=new ArrayBuffer(r)}catch(t){return void e._errorSteps(t)}const n={buffer:t,bufferByteLength:r,byteOffset:0,byteLength:r,bytesFilled:0,minimumFill:1,elementSize:1,viewConstructor:Uint8Array,readerType:"default"};this._pendingPullIntos.push(n)}V(t,e),Re(this)}[A](){if(this._pendingPullIntos.length>0){const e=this._pendingPullIntos.peek();e.readerType="none",this._pendingPullIntos=new b,this._pendingPullIntos.push(e)}}}function Ae(e){return!!r(e)&&!!Object.prototype.hasOwnProperty.call(e,"_controlledReadableByteStream")&&e instanceof Se}function Oe(e){return!!r(e)&&!!Object.prototype.hasOwnProperty.call(e,"_associatedReadableByteStreamController")&&e instanceof ve}function Re(e){const t=function(e){const t=e._controlledReadableByteStream;if("readable"!==t._state)return!1;if(e._closeRequested)return!1;if(!e._started)return!1;if(J(t)&&z(t)>0)return!0;if(st(t)&&nt(t)>0)return!0;const r=ze(e);return r>0}(e);t&&(e._pulling?e._pullAgain=!0:(e._pulling=!0,h(e._pullAlgorithm(),(()=>(e._pulling=!1,e._pullAgain&&(e._pullAgain=!1,Re(e)),null)),(t=>(We(e,t),null)))))}function Ce(e){je(e),e._pendingPullIntos=new b}function Ie(e,t){let r=!1;"closed"===e._state&&(r=!0);const n=ke(t);"default"===t.readerType?Y(e,n,r):function(e,t,r){const n=e._reader,s=n._readIntoRequests.shift();r?s._closeSteps(t):s._chunkSteps(t)}(e,n,r)}function ke(e){const t=e.bytesFilled,r=e.elementSize;return new e.viewConstructor(e.buffer,e.byteOffset,t/r)}function Ne(e,t,r,n){e._queue.push({buffer:t,byteOffset:r,byteLength:n}),e._queueTotalSize+=n}function Pe(e,t,r,n){let s;try{s=pe(t,r,r+n)}catch(t){throw We(e,t),t}Ne(e,s,0,n)}function xe(e,t){t.bytesFilled>0&&Pe(e,t.buffer,t.byteOffset,t.bytesFilled),Ge(e)}function De(e,t){const r=Math.min(e._queueTotalSize,t.byteLength-t.bytesFilled),n=t.bytesFilled+r;let s=r,o=!1;const i=n-n%t.elementSize;i>=t.minimumFill&&(s=i-t.bytesFilled,o=!0);const a=e._queue;for(;s>0;){const r=a.peek(),n=Math.min(s,r.byteLength),o=t.byteOffset+t.bytesFilled;de(t.buffer,o,r.buffer,r.byteOffset,n),r.byteLength===n?a.shift():(r.byteOffset+=n,r.byteLength-=n),e._queueTotalSize-=n,Ue(0,n,t),s-=n}return o}function Ue(e,t,r){r.bytesFilled+=t}function Le(e){0===e._queueTotalSize&&e._closeRequested?(He(e),Mr(e._controlledReadableByteStream)):Re(e)}function je(e){null!==e._byobRequest&&(e._byobRequest._associatedReadableByteStreamController=void 0,e._byobRequest._view=null,e._byobRequest=null)}function Me(e){for(;e._pendingPullIntos.length>0;){if(0===e._queueTotalSize)return;const t=e._pendingPullIntos.peek();De(e,t)&&(Ge(e),Ie(e._controlledReadableByteStream,t))}}function Fe(e,t,r,n){const s=e._controlledReadableByteStream,o=t.constructor,i=function(e){return Te(e)?1:e.BYTES_PER_ELEMENT}(o),{byteOffset:a,byteLength:c}=t,l=r*i;let u;try{u=he(t.buffer)}catch(e){return void n._errorSteps(e)}const d={buffer:u,bufferByteLength:u.byteLength,byteOffset:a,byteLength:c,bytesFilled:0,minimumFill:l,elementSize:i,viewConstructor:o,readerType:"byob"};if(e._pendingPullIntos.length>0)return e._pendingPullIntos.push(d),void rt(s,n);if("closed"!==s._state){if(e._queueTotalSize>0){if(De(e,d)){const t=ke(d);return Le(e),void n._chunkSteps(t)}if(e._closeRequested){const t=new TypeError("Insufficient bytes to fill elements in the given buffer");return We(e,t),void n._errorSteps(t)}}e._pendingPullIntos.push(d),rt(s,n),Re(e)}else{const e=new o(d.buffer,d.byteOffset,0);n._closeSteps(e)}}function Be(e,t){const r=e._pendingPullIntos.peek();je(e),"closed"===e._controlledReadableByteStream._state?function(e,t){"none"===t.readerType&&Ge(e);const r=e._controlledReadableByteStream;if(st(r))for(;nt(r)>0;)Ie(r,Ge(e))}(e,r):function(e,t,r){if(Ue(0,t,r),"none"===r.readerType)return xe(e,r),void Me(e);if(r.bytesFilled<r.minimumFill)return;Ge(e);const n=r.bytesFilled%r.elementSize;if(n>0){const t=r.byteOffset+r.bytesFilled;Pe(e,r.buffer,t-n,n)}r.bytesFilled-=n,Ie(e._controlledReadableByteStream,r),Me(e)}(e,t,r),Re(e)}function Ge(e){return e._pendingPullIntos.shift()}function He(e){e._pullAlgorithm=void 0,e._cancelAlgorithm=void 0}function qe(e){const t=e._controlledReadableByteStream;if(!e._closeRequested&&"readable"===t._state)if(e._queueTotalSize>0)e._closeRequested=!0;else{if(e._pendingPullIntos.length>0){const t=e._pendingPullIntos.peek();if(t.bytesFilled%t.elementSize!==0){const t=new TypeError("Insufficient bytes to fill elements in the given buffer");throw We(e,t),t}}He(e),Mr(t)}}function $e(e,t){const r=e._controlledReadableByteStream;if(e._closeRequested||"readable"!==r._state)return;const{buffer:n,byteOffset:s,byteLength:o}=t;if(fe(n))throw new TypeError("chunk's buffer is detached and so cannot be enqueued");const i=he(n);if(e._pendingPullIntos.length>0){const t=e._pendingPullIntos.peek();if(fe(t.buffer))throw new TypeError("The BYOB request's buffer has been detached and so cannot be filled with an enqueued chunk");je(e),t.buffer=he(t.buffer),"none"===t.readerType&&xe(e,t)}J(r)?(function(e){const t=e._controlledReadableByteStream._reader;for(;t._readRequests.length>0;){if(0===e._queueTotalSize)return;Ve(e,t._readRequests.shift())}}(e),0===z(r)?Ne(e,i,s,o):(e._pendingPullIntos.length>0&&Ge(e),Y(r,new Uint8Array(i,s,o),!1))):st(r)?(Ne(e,i,s,o),Me(e)):Ne(e,i,s,o),Re(e)}function We(e,t){const r=e._controlledReadableByteStream;"readable"===r._state&&(Ce(e),we(e),He(e),Fr(r,t))}function Ve(e,t){const r=e._queue.shift();e._queueTotalSize-=r.byteLength,Le(e);const n=new Uint8Array(r.buffer,r.byteOffset,r.byteLength);t._chunkSteps(n)}function Ye(e){if(null===e._byobRequest&&e._pendingPullIntos.length>0){const t=e._pendingPullIntos.peek(),r=new Uint8Array(t.buffer,t.byteOffset+t.bytesFilled,t.byteLength-t.bytesFilled),n=Object.create(ve.prototype);!function(e,t,r){e._associatedReadableByteStreamController=t,e._view=r}(n,e,r),e._byobRequest=n}return e._byobRequest}function ze(e){const t=e._controlledReadableByteStream._state;return"errored"===t?null:"closed"===t?0:e._strategyHWM-e._queueTotalSize}function Je(e,t){const r=e._pendingPullIntos.peek();if("closed"===e._controlledReadableByteStream._state){if(0!==t)throw new TypeError("bytesWritten must be 0 when calling respond() on a closed stream")}else{if(0===t)throw new TypeError("bytesWritten must be greater than 0 when calling respond() on a readable stream");if(r.bytesFilled+t>r.byteLength)throw new RangeError("bytesWritten out of range")}r.buffer=he(r.buffer),Be(e,t)}function Ke(e,t){const r=e._pendingPullIntos.peek();if("closed"===e._controlledReadableByteStream._state){if(0!==t.byteLength)throw new TypeError("The view's length must be 0 when calling respondWithNewView() on a closed stream")}else if(0===t.byteLength)throw new TypeError("The view's length must be greater than 0 when calling respondWithNewView() on a readable stream");if(r.byteOffset+r.bytesFilled!==t.byteOffset)throw new RangeError("The region specified by view does not match byobRequest");if(r.bufferByteLength!==t.buffer.byteLength)throw new RangeError("The buffer of view has different capacity than byobRequest");if(r.bytesFilled+t.byteLength>r.byteLength)throw new RangeError("The region specified by view is larger than byobRequest");const n=t.byteLength;r.buffer=he(t.buffer),Be(e,n)}function Xe(e,t,r,n,s,o,i){t._controlledReadableByteStream=e,t._pullAgain=!1,t._pulling=!1,t._byobRequest=null,t._queue=t._queueTotalSize=void 0,we(t),t._closeRequested=!1,t._started=!1,t._strategyHWM=o,t._pullAlgorithm=n,t._cancelAlgorithm=s,t._autoAllocateChunkSize=i,t._pendingPullIntos=new b,e._readableStreamController=t,h(l(r()),(()=>(t._started=!0,Re(t),null)),(e=>(We(t,e),null)))}function Ze(e){return new TypeError(`ReadableStreamBYOBRequest.prototype.${e} can only be used on a ReadableStreamBYOBRequest`)}function Qe(e){return new TypeError(`ReadableByteStreamController.prototype.${e} can only be used on a ReadableByteStreamController`)}function et(e,t){if("byob"!=(e=`${e}`))throw new TypeError(`${t} '${e}' is not a valid enumeration value for ReadableStreamReaderMode`);return e}function tt(e){return new ot(e)}function rt(e,t){e._reader._readIntoRequests.push(t)}function nt(e){return e._reader._readIntoRequests.length}function st(e){const t=e._reader;return void 0!==t&&!!it(t)}Object.defineProperties(Se.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},byobRequest:{enumerable:!0},desiredSize:{enumerable:!0}}),s(Se.prototype.close,"close"),s(Se.prototype.enqueue,"enqueue"),s(Se.prototype.error,"error"),"symbol"==typeof Symbol.toStringTag&&Object.defineProperty(Se.prototype,Symbol.toStringTag,{value:"ReadableByteStreamController",configurable:!0});class ot{constructor(e){if(F(e,1,"ReadableStreamBYOBReader"),$(e,"First parameter"),Lr(e))throw new TypeError("This stream has already been locked for exclusive reading by another reader");if(!Ae(e._readableStreamController))throw new TypeError("Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte source");O(this,e),this._readIntoRequests=new b}get closed(){return it(this)?this._closedPromise:u(lt("closed"))}cancel(e=void 0){return it(this)?void 0===this._ownerReadableStream?u(I("cancel")):R(this,e):u(lt("cancel"))}read(e,t={}){if(!it(this))return u(lt("read"));if(!ArrayBuffer.isView(e))return u(new TypeError("view must be an array buffer view"));if(0===e.byteLength)return u(new TypeError("view must have non-zero byteLength"));if(0===e.buffer.byteLength)return u(new TypeError("view's buffer must have non-zero byteLength"));if(fe(e.buffer))return u(new TypeError("view's buffer has been detached"));let r;try{r=function(e,t){var r;return L(e,t),{min:q(null!==(r=null==e?void 0:e.min)&&void 0!==r?r:1,`${t} has member 'min' that`)}}(t,"options")}catch(e){return u(e)}const n=r.min;if(0===n)return u(new TypeError("options.min must be greater than 0"));if(function(e){return Te(e.constructor)}(e)){if(n>e.byteLength)return u(new RangeError("options.min must be less than or equal to view's byteLength"))}else if(n>e.length)return u(new RangeError("options.min must be less than or equal to view's length"));if(void 0===this._ownerReadableStream)return u(I("read from"));let s,o;const i=c(((e,t)=>{s=e,o=t}));return at(this,e,n,{_chunkSteps:e=>s({value:e,done:!1}),_closeSteps:e=>s({value:e,done:!0}),_errorSteps:e=>o(e)}),i}releaseLock(){if(!it(this))throw lt("releaseLock");void 0!==this._ownerReadableStream&&function(e){C(e);const t=new TypeError("Reader was released");ct(e,t)}(this)}}function it(e){return!!r(e)&&!!Object.prototype.hasOwnProperty.call(e,"_readIntoRequests")&&e instanceof ot}function at(e,t,r,n){const s=e._ownerReadableStream;s._disturbed=!0,"errored"===s._state?n._errorSteps(s._storedError):Fe(s._readableStreamController,t,r,n)}function ct(e,t){const r=e._readIntoRequests;e._readIntoRequests=new b,r.forEach((e=>{e._errorSteps(t)}))}function lt(e){return new TypeError(`ReadableStreamBYOBReader.prototype.${e} can only be used on a ReadableStreamBYOBReader`)}function ut(e,t){const{highWaterMark:r}=e;if(void 0===r)return t;if(ie(r)||r<0)throw new RangeError("Invalid highWaterMark");return r}function dt(e){const{size:t}=e;return t||(()=>1)}function ht(e,t){L(e,t);const r=null==e?void 0:e.highWaterMark,n=null==e?void 0:e.size;return{highWaterMark:void 0===r?void 0:G(r),size:void 0===n?void 0:ft(n,`${t} has member 'size' that`)}}function ft(e,t){return j(e,t),t=>G(e(t))}function pt(e,t,r){return j(e,r),r=>E(e,t,[r])}function mt(e,t,r){return j(e,r),()=>E(e,t,[])}function _t(e,t,r){return j(e,r),r=>g(e,t,[r])}function yt(e,t,r){return j(e,r),(r,n)=>E(e,t,[r,n])}function gt(e,t){if(!vt(e))throw new TypeError(`${t} is not a WritableStream.`)}Object.defineProperties(ot.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),s(ot.prototype.cancel,"cancel"),s(ot.prototype.read,"read"),s(ot.prototype.releaseLock,"releaseLock"),"symbol"==typeof Symbol.toStringTag&&Object.defineProperty(ot.prototype,Symbol.toStringTag,{value:"ReadableStreamBYOBReader",configurable:!0});const Et="function"==typeof AbortController;class bt{constructor(e={},t={}){void 0===e?e=null:M(e,"First parameter");const r=ht(t,"Second parameter"),n=function(e,t){L(e,t);const r=null==e?void 0:e.abort,n=null==e?void 0:e.close,s=null==e?void 0:e.start,o=null==e?void 0:e.type,i=null==e?void 0:e.write;return{abort:void 0===r?void 0:pt(r,e,`${t} has member 'abort' that`),close:void 0===n?void 0:mt(n,e,`${t} has member 'close' that`),start:void 0===s?void 0:_t(s,e,`${t} has member 'start' that`),write:void 0===i?void 0:yt(i,e,`${t} has member 'write' that`),type:o}}(e,"First parameter");if(Tt(this),void 0!==n.type)throw new RangeError("Invalid type is specified");const s=dt(r);!function(e,t,r,n){const s=Object.create(Gt.prototype);let o,i,a,c;o=void 0!==t.start?()=>t.start(s):()=>{},i=void 0!==t.write?e=>t.write(e,s):()=>l(void 0),a=void 0!==t.close?()=>t.close():()=>l(void 0),c=void 0!==t.abort?e=>t.abort(e):()=>l(void 0),qt(e,s,o,i,a,c,r,n)}(this,n,ut(r,1),s)}get locked(){if(!vt(this))throw Kt("locked");return St(this)}abort(e=void 0){return vt(this)?St(this)?u(new TypeError("Cannot abort a stream that already has a writer")):At(this,e):u(Kt("abort"))}close(){return vt(this)?St(this)?u(new TypeError("Cannot close a stream that already has a writer")):kt(this)?u(new TypeError("Cannot close an already-closing stream")):Ot(this):u(Kt("close"))}getWriter(){if(!vt(this))throw Kt("getWriter");return wt(this)}}function wt(e){return new xt(e)}function Tt(e){e._state="writable",e._storedError=void 0,e._writer=void 0,e._writableStreamController=void 0,e._writeRequests=new b,e._inFlightWriteRequest=void 0,e._closeRequest=void 0,e._inFlightCloseRequest=void 0,e._pendingAbortRequest=void 0,e._backpressure=!1}function vt(e){return!!r(e)&&!!Object.prototype.hasOwnProperty.call(e,"_writableStreamController")&&e instanceof bt}function St(e){return void 0!==e._writer}function At(e,t){var r;if("closed"===e._state||"errored"===e._state)return l(void 0);e._writableStreamController._abortReason=t,null===(r=e._writableStreamController._abortController)||void 0===r||r.abort(t);const n=e._state;if("closed"===n||"errored"===n)return l(void 0);if(void 0!==e._pendingAbortRequest)return e._pendingAbortRequest._promise;let s=!1;"erroring"===n&&(s=!0,t=void 0);const o=c(((r,n)=>{e._pendingAbortRequest={_promise:void 0,_resolve:r,_reject:n,_reason:t,_wasAlreadyErroring:s}}));return e._pendingAbortRequest._promise=o,s||Ct(e,t),o}function Ot(e){const t=e._state;if("closed"===t||"errored"===t)return u(new TypeError(`The stream (in ${t} state) is not in the writable state and cannot be closed`));const r=c(((t,r)=>{const n={_resolve:t,_reject:r};e._closeRequest=n})),n=e._writer;var s;return void 0!==n&&e._backpressure&&"writable"===t&&cr(n),be(s=e._writableStreamController,Bt,0),Vt(s),r}function Rt(e,t){"writable"!==e._state?It(e):Ct(e,t)}function Ct(e,t){const r=e._writableStreamController;e._state="erroring",e._storedError=t;const n=e._writer;void 0!==n&&jt(n,t),!function(e){return void 0!==e._inFlightWriteRequest||void 0!==e._inFlightCloseRequest}(e)&&r._started&&It(e)}function It(e){e._state="errored",e._writableStreamController[T]();const t=e._storedError;if(e._writeRequests.forEach((e=>{e._reject(t)})),e._writeRequests=new b,void 0===e._pendingAbortRequest)return void Nt(e);const r=e._pendingAbortRequest;if(e._pendingAbortRequest=void 0,r._wasAlreadyErroring)return r._reject(t),void Nt(e);h(e._writableStreamController[w](r._reason),(()=>(r._resolve(),Nt(e),null)),(t=>(r._reject(t),Nt(e),null)))}function kt(e){return void 0!==e._closeRequest||void 0!==e._inFlightCloseRequest}function Nt(e){void 0!==e._closeRequest&&(e._closeRequest._reject(e._storedError),e._closeRequest=void 0);const t=e._writer;void 0!==t&&rr(t,e._storedError)}function Pt(e,t){const r=e._writer;void 0!==r&&t!==e._backpressure&&(t?function(e){sr(e)}(r):cr(r)),e._backpressure=t}Object.defineProperties(bt.prototype,{abort:{enumerable:!0},close:{enumerable:!0},getWriter:{enumerable:!0},locked:{enumerable:!0}}),s(bt.prototype.abort,"abort"),s(bt.prototype.close,"close"),s(bt.prototype.getWriter,"getWriter"),"symbol"==typeof Symbol.toStringTag&&Object.defineProperty(bt.prototype,Symbol.toStringTag,{value:"WritableStream",configurable:!0});class xt{constructor(e){if(F(e,1,"WritableStreamDefaultWriter"),gt(e,"First parameter"),St(e))throw new TypeError("This stream has already been locked for exclusive writing by another writer");this._ownerWritableStream=e,e._writer=this;const t=e._state;if("writable"===t)!kt(e)&&e._backpressure?sr(this):ir(this),er(this);else if("erroring"===t)or(this,e._storedError),er(this);else if("closed"===t)ir(this),er(r=this),nr(r);else{const t=e._storedError;or(this,t),tr(this,t)}var r}get closed(){return Dt(this)?this._closedPromise:u(Zt("closed"))}get desiredSize(){if(!Dt(this))throw Zt("desiredSize");if(void 0===this._ownerWritableStream)throw Qt("desiredSize");return function(e){const t=e._ownerWritableStream,r=t._state;return"errored"===r||"erroring"===r?null:"closed"===r?0:Wt(t._writableStreamController)}(this)}get ready(){return Dt(this)?this._readyPromise:u(Zt("ready"))}abort(e=void 0){return Dt(this)?void 0===this._ownerWritableStream?u(Qt("abort")):function(e,t){return At(e._ownerWritableStream,t)}(this,e):u(Zt("abort"))}close(){if(!Dt(this))return u(Zt("close"));const e=this._ownerWritableStream;return void 0===e?u(Qt("close")):kt(e)?u(new TypeError("Cannot close an already-closing stream")):Ut(this)}releaseLock(){if(!Dt(this))throw Zt("releaseLock");void 0!==this._ownerWritableStream&&Mt(this)}write(e=void 0){return Dt(this)?void 0===this._ownerWritableStream?u(Qt("write to")):Ft(this,e):u(Zt("write"))}}function Dt(e){return!!r(e)&&!!Object.prototype.hasOwnProperty.call(e,"_ownerWritableStream")&&e instanceof xt}function Ut(e){return Ot(e._ownerWritableStream)}function Lt(e,t){"pending"===e._closedPromiseState?rr(e,t):function(e,t){tr(e,t)}(e,t)}function jt(e,t){"pending"===e._readyPromiseState?ar(e,t):function(e,t){or(e,t)}(e,t)}function Mt(e){const t=e._ownerWritableStream,r=new TypeError("Writer was released and can no longer be used to monitor the stream's closedness");jt(e,r),Lt(e,r),t._writer=void 0,e._ownerWritableStream=void 0}function Ft(e,t){const r=e._ownerWritableStream,n=r._writableStreamController,s=function(e,t){try{return e._strategySizeAlgorithm(t)}catch(t){return Yt(e,t),1}}(n,t);if(r!==e._ownerWritableStream)return u(Qt("write to"));const o=r._state;if("errored"===o)return u(r._storedError);if(kt(r)||"closed"===o)return u(new TypeError("The stream is closing or closed and cannot be written to"));if("erroring"===o)return u(r._storedError);const i=function(e){return c(((t,r)=>{const n={_resolve:t,_reject:r};e._writeRequests.push(n)}))}(r);return function(e,t,r){try{be(e,t,r)}catch(t){return void Yt(e,t)}const n=e._controlledWritableStream;kt(n)||"writable"!==n._state||Pt(n,zt(e)),Vt(e)}(n,t,s),i}Object.defineProperties(xt.prototype,{abort:{enumerable:!0},close:{enumerable:!0},releaseLock:{enumerable:!0},write:{enumerable:!0},closed:{enumerable:!0},desiredSize:{enumerable:!0},ready:{enumerable:!0}}),s(xt.prototype.abort,"abort"),s(xt.prototype.close,"close"),s(xt.prototype.releaseLock,"releaseLock"),s(xt.prototype.write,"write"),"symbol"==typeof Symbol.toStringTag&&Object.defineProperty(xt.prototype,Symbol.toStringTag,{value:"WritableStreamDefaultWriter",configurable:!0});const Bt={};class Gt{constructor(){throw new TypeError("Illegal constructor")}get abortReason(){if(!Ht(this))throw Xt("abortReason");return this._abortReason}get signal(){if(!Ht(this))throw Xt("signal");if(void 0===this._abortController)throw new TypeError("WritableStreamDefaultController.prototype.signal is not supported");return this._abortController.signal}error(e=void 0){if(!Ht(this))throw Xt("error");"writable"===this._controlledWritableStream._state&&Jt(this,e)}[w](e){const t=this._abortAlgorithm(e);return $t(this),t}[T](){we(this)}}function Ht(e){return!!r(e)&&!!Object.prototype.hasOwnProperty.call(e,"_controlledWritableStream")&&e instanceof Gt}function qt(e,t,r,n,s,o,i,a){t._controlledWritableStream=e,e._writableStreamController=t,t._queue=void 0,t._queueTotalSize=void 0,we(t),t._abortReason=void 0,t._abortController=function(){if(Et)return new AbortController}(),t._started=!1,t._strategySizeAlgorithm=a,t._strategyHWM=i,t._writeAlgorithm=n,t._closeAlgorithm=s,t._abortAlgorithm=o;const c=zt(t);Pt(e,c),h(l(r()),(()=>(t._started=!0,Vt(t),null)),(r=>(t._started=!0,Rt(e,r),null)))}function $t(e){e._writeAlgorithm=void 0,e._closeAlgorithm=void 0,e._abortAlgorithm=void 0,e._strategySizeAlgorithm=void 0}function Wt(e){return e._strategyHWM-e._queueTotalSize}function Vt(e){const t=e._controlledWritableStream;if(!e._started)return;if(void 0!==t._inFlightWriteRequest)return;if("erroring"===t._state)return void It(t);if(0===e._queue.length)return;const r=e._queue.peek().value;r===Bt?function(e){const t=e._controlledWritableStream;(function(e){e._inFlightCloseRequest=e._closeRequest,e._closeRequest=void 0})(t),Ee(e);const r=e._closeAlgorithm();$t(e),h(r,(()=>(function(e){e._inFlightCloseRequest._resolve(void 0),e._inFlightCloseRequest=void 0,"erroring"===e._state&&(e._storedError=void 0,void 0!==e._pendingAbortRequest&&(e._pendingAbortRequest._resolve(),e._pendingAbortRequest=void 0)),e._state="closed";const t=e._writer;void 0!==t&&nr(t)}(t),null)),(e=>(function(e,t){e._inFlightCloseRequest._reject(t),e._inFlightCloseRequest=void 0,void 0!==e._pendingAbortRequest&&(e._pendingAbortRequest._reject(t),e._pendingAbortRequest=void 0),Rt(e,t)}(t,e),null)))}(e):function(e,t){const r=e._controlledWritableStream;!function(e){e._inFlightWriteRequest=e._writeRequests.shift()}(r);const n=e._writeAlgorithm(t);h(n,(()=>{!function(e){e._inFlightWriteRequest._resolve(void 0),e._inFlightWriteRequest=void 0}(r);const t=r._state;if(Ee(e),!kt(r)&&"writable"===t){const t=zt(e);Pt(r,t)}return Vt(e),null}),(t=>("writable"===r._state&&$t(e),function(e,t){e._inFlightWriteRequest._reject(t),e._inFlightWriteRequest=void 0,Rt(e,t)}(r,t),null)))}(e,r)}function Yt(e,t){"writable"===e._controlledWritableStream._state&&Jt(e,t)}function zt(e){return Wt(e)<=0}function Jt(e,t){const r=e._controlledWritableStream;$t(e),Ct(r,t)}function Kt(e){return new TypeError(`WritableStream.prototype.${e} can only be used on a WritableStream`)}function Xt(e){return new TypeError(`WritableStreamDefaultController.prototype.${e} can only be used on a WritableStreamDefaultController`)}function Zt(e){return new TypeError(`WritableStreamDefaultWriter.prototype.${e} can only be used on a WritableStreamDefaultWriter`)}function Qt(e){return new TypeError("Cannot "+e+" a stream using a released writer")}function er(e){e._closedPromise=c(((t,r)=>{e._closedPromise_resolve=t,e._closedPromise_reject=r,e._closedPromiseState="pending"}))}function tr(e,t){er(e),rr(e,t)}function rr(e,t){void 0!==e._closedPromise_reject&&(_(e._closedPromise),e._closedPromise_reject(t),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0,e._closedPromiseState="rejected")}function nr(e){void 0!==e._closedPromise_resolve&&(e._closedPromise_resolve(void 0),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0,e._closedPromiseState="resolved")}function sr(e){e._readyPromise=c(((t,r)=>{e._readyPromise_resolve=t,e._readyPromise_reject=r})),e._readyPromiseState="pending"}function or(e,t){sr(e),ar(e,t)}function ir(e){sr(e),cr(e)}function ar(e,t){void 0!==e._readyPromise_reject&&(_(e._readyPromise),e._readyPromise_reject(t),e._readyPromise_resolve=void 0,e._readyPromise_reject=void 0,e._readyPromiseState="rejected")}function cr(e){void 0!==e._readyPromise_resolve&&(e._readyPromise_resolve(void 0),e._readyPromise_resolve=void 0,e._readyPromise_reject=void 0,e._readyPromiseState="fulfilled")}Object.defineProperties(Gt.prototype,{abortReason:{enumerable:!0},signal:{enumerable:!0},error:{enumerable:!0}}),"symbol"==typeof Symbol.toStringTag&&Object.defineProperty(Gt.prototype,Symbol.toStringTag,{value:"WritableStreamDefaultController",configurable:!0});const lr="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof global?global:void 0,ur=function(){const e=null==lr?void 0:lr.DOMException;return function(e){if("function"!=typeof e&&"object"!=typeof e)return!1;if("DOMException"!==e.name)return!1;try{return new e,!0}catch(e){return!1}}(e)?e:void 0}()||function(){const e=function(e,t){this.message=e||"",this.name=t||"Error",Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)};return s(e,"DOMException"),e.prototype=Object.create(Error.prototype),Object.defineProperty(e.prototype,"constructor",{value:e,writable:!0,configurable:!0}),e}();function dr(e,r,n,s,o,i){const a=W(e),m=wt(r);e._disturbed=!0;let y=!1,g=l(void 0);return c(((E,b)=>{let w;if(void 0!==i){if(w=()=>{const t=void 0!==i.reason?i.reason:new ur("Aborted","AbortError"),n=[];s||n.push((()=>"writable"===r._state?At(r,t):l(void 0))),o||n.push((()=>"readable"===e._state?jr(e,t):l(void 0))),R((()=>Promise.all(n.map((e=>e())))),!0,t)},i.aborted)return void w();i.addEventListener("abort",w)}var T,v,S;if(O(e,a._closedPromise,(e=>(s?I(!0,e):R((()=>At(r,e)),!0,e),null))),O(r,m._closedPromise,(t=>(o?I(!0,t):R((()=>jr(e,t)),!0,t),null))),T=e,v=a._closedPromise,S=()=>(n?I():R((()=>function(e){const t=e._ownerWritableStream,r=t._state;return kt(t)||"closed"===r?l(void 0):"errored"===r?u(t._storedError):Ut(e)}(m))),null),"closed"===T._state?S():f(v,S),kt(r)||"closed"===r._state){const t=new TypeError("the destination writable stream closed before all data could be piped to it");o?I(!0,t):R((()=>jr(e,t)),!0,t)}function A(){const e=g;return d(g,(()=>e!==g?A():void 0))}function O(e,t,r){"errored"===e._state?r(e._storedError):p(t,r)}function R(e,t,n){function s(){return h(e(),(()=>k(t,n)),(e=>k(!0,e))),null}y||(y=!0,"writable"!==r._state||kt(r)?s():f(A(),s))}function I(e,t){y||(y=!0,"writable"!==r._state||kt(r)?k(e,t):f(A(),(()=>k(e,t))))}function k(e,t){return Mt(m),C(a),void 0!==i&&i.removeEventListener("abort",w),e?b(t):E(void 0),null}_(c(((e,r)=>{!function n(s){s?e():d(y?l(!0):d(m._readyPromise,(()=>c(((e,r)=>{Z(a,{_chunkSteps:r=>{g=d(Ft(m,r),void 0,t),e(!1)},_closeSteps:()=>e(!0),_errorSteps:r})})))),n,r)}(!1)})))}))}class hr{constructor(){throw new TypeError("Illegal constructor")}get desiredSize(){if(!fr(this))throw vr("desiredSize");return br(this)}close(){if(!fr(this))throw vr("close");if(!wr(this))throw new TypeError("The stream is not in a state that permits close");yr(this)}enqueue(e=void 0){if(!fr(this))throw vr("enqueue");if(!wr(this))throw new TypeError("The stream is not in a state that permits enqueue");return gr(this,e)}error(e=void 0){if(!fr(this))throw vr("error");Er(this,e)}[v](e){we(this);const t=this._cancelAlgorithm(e);return _r(this),t}[S](e){const t=this._controlledReadableStream;if(this._queue.length>0){const r=Ee(this);this._closeRequested&&0===this._queue.length?(_r(this),Mr(t)):pr(this),e._chunkSteps(r)}else V(t,e),pr(this)}[A](){}}function fr(e){return!!r(e)&&!!Object.prototype.hasOwnProperty.call(e,"_controlledReadableStream")&&e instanceof hr}function pr(e){mr(e)&&(e._pulling?e._pullAgain=!0:(e._pulling=!0,h(e._pullAlgorithm(),(()=>(e._pulling=!1,e._pullAgain&&(e._pullAgain=!1,pr(e)),null)),(t=>(Er(e,t),null)))))}function mr(e){const t=e._controlledReadableStream;return!!wr(e)&&(!!e._started&&(!!(Lr(t)&&z(t)>0)||br(e)>0))}function _r(e){e._pullAlgorithm=void 0,e._cancelAlgorithm=void 0,e._strategySizeAlgorithm=void 0}function yr(e){if(!wr(e))return;const t=e._controlledReadableStream;e._closeRequested=!0,0===e._queue.length&&(_r(e),Mr(t))}function gr(e,t){if(!wr(e))return;const r=e._controlledReadableStream;if(Lr(r)&&z(r)>0)Y(r,t,!1);else{let r;try{r=e._strategySizeAlgorithm(t)}catch(t){throw Er(e,t),t}try{be(e,t,r)}catch(t){throw Er(e,t),t}}pr(e)}function Er(e,t){const r=e._controlledReadableStream;"readable"===r._state&&(we(e),_r(e),Fr(r,t))}function br(e){const t=e._controlledReadableStream._state;return"errored"===t?null:"closed"===t?0:e._strategyHWM-e._queueTotalSize}function wr(e){const t=e._controlledReadableStream._state;return!e._closeRequested&&"readable"===t}function Tr(e,t,r,n,s,o,i){t._controlledReadableStream=e,t._queue=void 0,t._queueTotalSize=void 0,we(t),t._started=!1,t._closeRequested=!1,t._pullAgain=!1,t._pulling=!1,t._strategySizeAlgorithm=i,t._strategyHWM=o,t._pullAlgorithm=n,t._cancelAlgorithm=s,e._readableStreamController=t,h(l(r()),(()=>(t._started=!0,pr(t),null)),(e=>(Er(t,e),null)))}function vr(e){return new TypeError(`ReadableStreamDefaultController.prototype.${e} can only be used on a ReadableStreamDefaultController`)}function Sr(e,t){return Ae(e._readableStreamController)?function(e){let t,r,n,s,o,i=W(e),a=!1,u=!1,d=!1,h=!1,f=!1;const m=c((e=>{o=e}));function _(e){p(e._closedPromise,(t=>(e!==i||(We(n._readableStreamController,t),We(s._readableStreamController,t),h&&f||o(void 0)),null)))}function g(){it(i)&&(C(i),i=W(e),_(i)),Z(i,{_chunkSteps:t=>{y((()=>{u=!1,d=!1;const r=t;let i=t;if(!h&&!f)try{i=ge(t)}catch(t){return We(n._readableStreamController,t),We(s._readableStreamController,t),void o(jr(e,t))}h||$e(n._readableStreamController,r),f||$e(s._readableStreamController,i),a=!1,u?b():d&&w()}))},_closeSteps:()=>{a=!1,h||qe(n._readableStreamController),f||qe(s._readableStreamController),n._readableStreamController._pendingPullIntos.length>0&&Je(n._readableStreamController,0),s._readableStreamController._pendingPullIntos.length>0&&Je(s._readableStreamController,0),h&&f||o(void 0)},_errorSteps:()=>{a=!1}})}function E(t,r){X(i)&&(C(i),i=tt(e),_(i));const c=r?s:n,l=r?n:s;at(i,t,1,{_chunkSteps:t=>{y((()=>{u=!1,d=!1;const n=r?f:h;if(r?h:f)n||Ke(c._readableStreamController,t);else{let r;try{r=ge(t)}catch(t){return We(c._readableStreamController,t),We(l._readableStreamController,t),void o(jr(e,t))}n||Ke(c._readableStreamController,t),$e(l._readableStreamController,r)}a=!1,u?b():d&&w()}))},_closeSteps:e=>{a=!1;const t=r?f:h,n=r?h:f;t||qe(c._readableStreamController),n||qe(l._readableStreamController),void 0!==e&&(t||Ke(c._readableStreamController,e),!n&&l._readableStreamController._pendingPullIntos.length>0&&Je(l._readableStreamController,0)),t&&n||o(void 0)},_errorSteps:()=>{a=!1}})}function b(){if(a)return u=!0,l(void 0);a=!0;const e=Ye(n._readableStreamController);return null===e?g():E(e._view,!1),l(void 0)}function w(){if(a)return d=!0,l(void 0);a=!0;const e=Ye(s._readableStreamController);return null===e?g():E(e._view,!0),l(void 0)}function T(n){if(h=!0,t=n,f){const n=ue([t,r]),s=jr(e,n);o(s)}return m}function v(n){if(f=!0,r=n,h){const n=ue([t,r]),s=jr(e,n);o(s)}return m}function S(){}return n=xr(S,b,T),s=xr(S,w,v),_(i),[n,s]}(e):function(e){const t=W(e);let r,n,s,o,i,a=!1,u=!1,d=!1,h=!1;const f=c((e=>{i=e}));function m(){return a?(u=!0,l(void 0)):(a=!0,Z(t,{_chunkSteps:e=>{y((()=>{u=!1;const t=e,r=e;d||gr(s._readableStreamController,t),h||gr(o._readableStreamController,r),a=!1,u&&m()}))},_closeSteps:()=>{a=!1,d||yr(s._readableStreamController),h||yr(o._readableStreamController),d&&h||i(void 0)},_errorSteps:()=>{a=!1}}),l(void 0))}function _(t){if(d=!0,r=t,h){const t=ue([r,n]),s=jr(e,t);i(s)}return f}function g(t){if(h=!0,n=t,d){const t=ue([r,n]),s=jr(e,t);i(s)}return f}function E(){}return s=Pr(E,m,_),o=Pr(E,m,g),p(t._closedPromise,(e=>(Er(s._readableStreamController,e),Er(o._readableStreamController,e),d&&h||i(void 0),null))),[s,o]}(e)}function Ar(e){return r(n=e)&&void 0!==n.getReader?function(e){let n;function s(){let t;try{t=e.read()}catch(e){return u(e)}return m(t,(e=>{if(!r(e))throw new TypeError("The promise returned by the reader.read() method must fulfill with an object");if(e.done)yr(n._readableStreamController);else{const t=e.value;gr(n._readableStreamController,t)}}))}function o(t){try{return l(e.cancel(t))}catch(e){return u(e)}}return n=Pr(t,s,o,0),n}(e.getReader()):function(e){let n;const s=ye(e,"async");function o(){let e;try{e=function(e){const t=g(e.nextMethod,e.iterator,[]);if(!r(t))throw new TypeError("The iterator.next() method must return an object");return t}(s)}catch(e){return u(e)}return m(l(e),(e=>{if(!r(e))throw new TypeError("The promise returned by the iterator.next() method must fulfill with an object");const t=function(e){return Boolean(e.done)}(e);if(t)yr(n._readableStreamController);else{const t=function(e){return e.value}(e);gr(n._readableStreamController,t)}}))}function i(e){const t=s.iterator;let n,o;try{n=me(t,"return")}catch(e){return u(e)}if(void 0===n)return l(void 0);try{o=g(n,t,[e])}catch(e){return u(e)}return m(l(o),(e=>{if(!r(e))throw new TypeError("The promise returned by the iterator.return() method must fulfill with an object")}))}return n=Pr(t,o,i,0),n}(e);var n}function Or(e,t,r){return j(e,r),r=>E(e,t,[r])}function Rr(e,t,r){return j(e,r),r=>E(e,t,[r])}function Cr(e,t,r){return j(e,r),r=>g(e,t,[r])}function Ir(e,t){if("bytes"!=(e=`${e}`))throw new TypeError(`${t} '${e}' is not a valid enumeration value for ReadableStreamType`);return e}function kr(e,t){L(e,t);const r=null==e?void 0:e.preventAbort,n=null==e?void 0:e.preventCancel,s=null==e?void 0:e.preventClose,o=null==e?void 0:e.signal;return void 0!==o&&function(e,t){if(!function(e){if("object"!=typeof e||null===e)return!1;try{return"boolean"==typeof e.aborted}catch(e){return!1}}(e))throw new TypeError(`${t} is not an AbortSignal.`)}(o,`${t} has member 'signal' that`),{preventAbort:Boolean(r),preventCancel:Boolean(n),preventClose:Boolean(s),signal:o}}Object.defineProperties(hr.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},desiredSize:{enumerable:!0}}),s(hr.prototype.close,"close"),s(hr.prototype.enqueue,"enqueue"),s(hr.prototype.error,"error"),"symbol"==typeof Symbol.toStringTag&&Object.defineProperty(hr.prototype,Symbol.toStringTag,{value:"ReadableStreamDefaultController",configurable:!0});class Nr{constructor(e={},t={}){void 0===e?e=null:M(e,"First parameter");const r=ht(t,"Second parameter"),n=function(e,t){L(e,t);const r=e,n=null==r?void 0:r.autoAllocateChunkSize,s=null==r?void 0:r.cancel,o=null==r?void 0:r.pull,i=null==r?void 0:r.start,a=null==r?void 0:r.type;return{autoAllocateChunkSize:void 0===n?void 0:q(n,`${t} has member 'autoAllocateChunkSize' that`),cancel:void 0===s?void 0:Or(s,r,`${t} has member 'cancel' that`),pull:void 0===o?void 0:Rr(o,r,`${t} has member 'pull' that`),start:void 0===i?void 0:Cr(i,r,`${t} has member 'start' that`),type:void 0===a?void 0:Ir(a,`${t} has member 'type' that`)}}(e,"First parameter");if(Dr(this),"bytes"===n.type){if(void 0!==r.size)throw new RangeError("The strategy for a byte stream cannot have a size function");!function(e,t,r){const n=Object.create(Se.prototype);let s,o,i;s=void 0!==t.start?()=>t.start(n):()=>{},o=void 0!==t.pull?()=>t.pull(n):()=>l(void 0),i=void 0!==t.cancel?e=>t.cancel(e):()=>l(void 0);const a=t.autoAllocateChunkSize;if(0===a)throw new TypeError("autoAllocateChunkSize must be greater than 0");Xe(e,n,s,o,i,r,a)}(this,n,ut(r,0))}else{const e=dt(r);!function(e,t,r,n){const s=Object.create(hr.prototype);let o,i,a;o=void 0!==t.start?()=>t.start(s):()=>{},i=void 0!==t.pull?()=>t.pull(s):()=>l(void 0),a=void 0!==t.cancel?e=>t.cancel(e):()=>l(void 0),Tr(e,s,o,i,a,r,n)}(this,n,ut(r,1),e)}}get locked(){if(!Ur(this))throw Br("locked");return Lr(this)}cancel(e=void 0){return Ur(this)?Lr(this)?u(new TypeError("Cannot cancel a stream that already has a reader")):jr(this,e):u(Br("cancel"))}getReader(e=void 0){if(!Ur(this))throw Br("getReader");return void 0===function(e,t){L(e,t);const r=null==e?void 0:e.mode;return{mode:void 0===r?void 0:et(r,`${t} has member 'mode' that`)}}(e,"First parameter").mode?W(this):tt(this)}pipeThrough(e,t={}){if(!Ur(this))throw Br("pipeThrough");F(e,1,"pipeThrough");const r=function(e,t){L(e,t);const r=null==e?void 0:e.readable;B(r,"readable","ReadableWritablePair"),$(r,`${t} has member 'readable' that`);const n=null==e?void 0:e.writable;return B(n,"writable","ReadableWritablePair"),gt(n,`${t} has member 'writable' that`),{readable:r,writable:n}}(e,"First parameter"),n=kr(t,"Second parameter");if(Lr(this))throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream");if(St(r.writable))throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream");return _(dr(this,r.writable,n.preventClose,n.preventAbort,n.preventCancel,n.signal)),r.readable}pipeTo(e,t={}){if(!Ur(this))return u(Br("pipeTo"));if(void 0===e)return u("Parameter 1 is required in 'pipeTo'.");if(!vt(e))return u(new TypeError("ReadableStream.prototype.pipeTo's first argument must be a WritableStream"));let r;try{r=kr(t,"Second parameter")}catch(e){return u(e)}return Lr(this)?u(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream")):St(e)?u(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream")):dr(this,e,r.preventClose,r.preventAbort,r.preventCancel,r.signal)}tee(){if(!Ur(this))throw Br("tee");return ue(Sr(this))}values(e=void 0){if(!Ur(this))throw Br("values");return function(e,t){const r=W(e),n=new re(r,t),s=Object.create(ne);return s._asyncIteratorImpl=n,s}(this,function(e,t){L(e,t);const r=null==e?void 0:e.preventCancel;return{preventCancel:Boolean(r)}}(e,"First parameter").preventCancel)}[_e](e){return this.values(e)}static from(e){return Ar(e)}}function Pr(e,t,r,n=1,s=()=>1){const o=Object.create(Nr.prototype);return Dr(o),Tr(o,Object.create(hr.prototype),e,t,r,n,s),o}function xr(e,t,r){const n=Object.create(Nr.prototype);return Dr(n),Xe(n,Object.create(Se.prototype),e,t,r,0,void 0),n}function Dr(e){e._state="readable",e._reader=void 0,e._storedError=void 0,e._disturbed=!1}function Ur(e){return!!r(e)&&!!Object.prototype.hasOwnProperty.call(e,"_readableStreamController")&&e instanceof Nr}function Lr(e){return void 0!==e._reader}function jr(e,r){if(e._disturbed=!0,"closed"===e._state)return l(void 0);if("errored"===e._state)return u(e._storedError);Mr(e);const n=e._reader;if(void 0!==n&&it(n)){const e=n._readIntoRequests;n._readIntoRequests=new b,e.forEach((e=>{e._closeSteps(void 0)}))}return m(e._readableStreamController[v](r),t)}function Mr(e){e._state="closed";const t=e._reader;if(void 0!==t&&(x(t),X(t))){const e=t._readRequests;t._readRequests=new b,e.forEach((e=>{e._closeSteps()}))}}function Fr(e,t){e._state="errored",e._storedError=t;const r=e._reader;void 0!==r&&(P(r,t),X(r)?Q(r,t):ct(r,t))}function Br(e){return new TypeError(`ReadableStream.prototype.${e} can only be used on a ReadableStream`)}function Gr(e,t){L(e,t);const r=null==e?void 0:e.highWaterMark;return B(r,"highWaterMark","QueuingStrategyInit"),{highWaterMark:G(r)}}Object.defineProperties(Nr,{from:{enumerable:!0}}),Object.defineProperties(Nr.prototype,{cancel:{enumerable:!0},getReader:{enumerable:!0},pipeThrough:{enumerable:!0},pipeTo:{enumerable:!0},tee:{enumerable:!0},values:{enumerable:!0},locked:{enumerable:!0}}),s(Nr.from,"from"),s(Nr.prototype.cancel,"cancel"),s(Nr.prototype.getReader,"getReader"),s(Nr.prototype.pipeThrough,"pipeThrough"),s(Nr.prototype.pipeTo,"pipeTo"),s(Nr.prototype.tee,"tee"),s(Nr.prototype.values,"values"),"symbol"==typeof Symbol.toStringTag&&Object.defineProperty(Nr.prototype,Symbol.toStringTag,{value:"ReadableStream",configurable:!0}),Object.defineProperty(Nr.prototype,_e,{value:Nr.prototype.values,writable:!0,configurable:!0});const Hr=e=>e.byteLength;s(Hr,"size");class qr{constructor(e){F(e,1,"ByteLengthQueuingStrategy"),e=Gr(e,"First parameter"),this._byteLengthQueuingStrategyHighWaterMark=e.highWaterMark}get highWaterMark(){if(!Wr(this))throw $r("highWaterMark");return this._byteLengthQueuingStrategyHighWaterMark}get size(){if(!Wr(this))throw $r("size");return Hr}}function $r(e){return new TypeError(`ByteLengthQueuingStrategy.prototype.${e} can only be used on a ByteLengthQueuingStrategy`)}function Wr(e){return!!r(e)&&!!Object.prototype.hasOwnProperty.call(e,"_byteLengthQueuingStrategyHighWaterMark")&&e instanceof qr}Object.defineProperties(qr.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),"symbol"==typeof Symbol.toStringTag&&Object.defineProperty(qr.prototype,Symbol.toStringTag,{value:"ByteLengthQueuingStrategy",configurable:!0});const Vr=()=>1;s(Vr,"size");class Yr{constructor(e){F(e,1,"CountQueuingStrategy"),e=Gr(e,"First parameter"),this._countQueuingStrategyHighWaterMark=e.highWaterMark}get highWaterMark(){if(!Jr(this))throw zr("highWaterMark");return this._countQueuingStrategyHighWaterMark}get size(){if(!Jr(this))throw zr("size");return Vr}}function zr(e){return new TypeError(`CountQueuingStrategy.prototype.${e} can only be used on a CountQueuingStrategy`)}function Jr(e){return!!r(e)&&!!Object.prototype.hasOwnProperty.call(e,"_countQueuingStrategyHighWaterMark")&&e instanceof Yr}function Kr(e,t,r){return j(e,r),r=>E(e,t,[r])}function Xr(e,t,r){return j(e,r),r=>g(e,t,[r])}function Zr(e,t,r){return j(e,r),(r,n)=>E(e,t,[r,n])}function Qr(e,t,r){return j(e,r),r=>E(e,t,[r])}Object.defineProperties(Yr.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),"symbol"==typeof Symbol.toStringTag&&Object.defineProperty(Yr.prototype,Symbol.toStringTag,{value:"CountQueuingStrategy",configurable:!0});class en{constructor(e={},t={},r={}){void 0===e&&(e=null);const n=ht(t,"Second parameter"),s=ht(r,"Third parameter"),o=function(e,t){L(e,t);const r=null==e?void 0:e.cancel,n=null==e?void 0:e.flush,s=null==e?void 0:e.readableType,o=null==e?void 0:e.start,i=null==e?void 0:e.transform,a=null==e?void 0:e.writableType;return{cancel:void 0===r?void 0:Qr(r,e,`${t} has member 'cancel' that`),flush:void 0===n?void 0:Kr(n,e,`${t} has member 'flush' that`),readableType:s,start:void 0===o?void 0:Xr(o,e,`${t} has member 'start' that`),transform:void 0===i?void 0:Zr(i,e,`${t} has member 'transform' that`),writableType:a}}(e,"First parameter");if(void 0!==o.readableType)throw new RangeError("Invalid readableType specified");if(void 0!==o.writableType)throw new RangeError("Invalid writableType specified");const i=ut(s,0),a=dt(s),d=ut(n,1),f=dt(n);let p;!function(e,t,r,n,s,o){function i(){return t}function a(t){return function(e,t){const r=e._transformStreamController;return e._backpressure?m(e._backpressureChangePromise,(()=>{const n=e._writable;if("erroring"===n._state)throw n._storedError;return dn(r,t)})):dn(r,t)}(e,t)}function l(t){return function(e,t){const r=e._transformStreamController;if(void 0!==r._finishPromise)return r._finishPromise;const n=e._readable;r._finishPromise=c(((e,t)=>{r._finishPromise_resolve=e,r._finishPromise_reject=t}));const s=r._cancelAlgorithm(t);return ln(r),h(s,(()=>("errored"===n._state?pn(r,n._storedError):(Er(n._readableStreamController,t),fn(r)),null)),(e=>(Er(n._readableStreamController,e),pn(r,e),null))),r._finishPromise}(e,t)}function u(){return function(e){const t=e._transformStreamController;if(void 0!==t._finishPromise)return t._finishPromise;const r=e._readable;t._finishPromise=c(((e,r)=>{t._finishPromise_resolve=e,t._finishPromise_reject=r}));const n=t._flushAlgorithm();return ln(t),h(n,(()=>("errored"===r._state?pn(t,r._storedError):(yr(r._readableStreamController),fn(t)),null)),(e=>(Er(r._readableStreamController,e),pn(t,e),null))),t._finishPromise}(e)}function d(){return function(e){return on(e,!1),e._backpressureChangePromise}(e)}function f(t){return function(e,t){const r=e._transformStreamController;if(void 0!==r._finishPromise)return r._finishPromise;const n=e._writable;r._finishPromise=c(((e,t)=>{r._finishPromise_resolve=e,r._finishPromise_reject=t}));const s=r._cancelAlgorithm(t);return ln(r),h(s,(()=>("errored"===n._state?pn(r,n._storedError):(Yt(n._writableStreamController,t),sn(e),fn(r)),null)),(t=>(Yt(n._writableStreamController,t),sn(e),pn(r,t),null))),r._finishPromise}(e,t)}e._writable=function(e,t,r,n,s=1,o=()=>1){const i=Object.create(bt.prototype);return Tt(i),qt(i,Object.create(Gt.prototype),e,t,r,n,s,o),i}(i,a,u,l,r,n),e._readable=Pr(i,d,f,s,o),e._backpressure=void 0,e._backpressureChangePromise=void 0,e._backpressureChangePromise_resolve=void 0,on(e,!0),e._transformStreamController=void 0}(this,c((e=>{p=e})),d,f,i,a),function(e,t){const r=Object.create(an.prototype);let n,s,o;n=void 0!==t.transform?e=>t.transform(e,r):e=>{try{return un(r,e),l(void 0)}catch(e){return u(e)}},s=void 0!==t.flush?()=>t.flush(r):()=>l(void 0),o=void 0!==t.cancel?e=>t.cancel(e):()=>l(void 0),function(e,t,r,n,s){t._controlledTransformStream=e,e._transformStreamController=t,t._transformAlgorithm=r,t._flushAlgorithm=n,t._cancelAlgorithm=s,t._finishPromise=void 0,t._finishPromise_resolve=void 0,t._finishPromise_reject=void 0}(e,r,n,s,o)}(this,o),void 0!==o.start?p(o.start(this._transformStreamController)):p(void 0)}get readable(){if(!tn(this))throw mn("readable");return this._readable}get writable(){if(!tn(this))throw mn("writable");return this._writable}}function tn(e){return!!r(e)&&!!Object.prototype.hasOwnProperty.call(e,"_transformStreamController")&&e instanceof en}function rn(e,t){Er(e._readable._readableStreamController,t),nn(e,t)}function nn(e,t){ln(e._transformStreamController),Yt(e._writable._writableStreamController,t),sn(e)}function sn(e){e._backpressure&&on(e,!1)}function on(e,t){void 0!==e._backpressureChangePromise&&e._backpressureChangePromise_resolve(),e._backpressureChangePromise=c((t=>{e._backpressureChangePromise_resolve=t})),e._backpressure=t}Object.defineProperties(en.prototype,{readable:{enumerable:!0},writable:{enumerable:!0}}),"symbol"==typeof Symbol.toStringTag&&Object.defineProperty(en.prototype,Symbol.toStringTag,{value:"TransformStream",configurable:!0});class an{constructor(){throw new TypeError("Illegal constructor")}get desiredSize(){if(!cn(this))throw hn("desiredSize");return br(this._controlledTransformStream._readable._readableStreamController)}enqueue(e=void 0){if(!cn(this))throw hn("enqueue");un(this,e)}error(e=void 0){if(!cn(this))throw hn("error");var t;t=e,rn(this._controlledTransformStream,t)}terminate(){if(!cn(this))throw hn("terminate");!function(e){const t=e._controlledTransformStream;yr(t._readable._readableStreamController);const r=new TypeError("TransformStream terminated");nn(t,r)}(this)}}function cn(e){return!!r(e)&&!!Object.prototype.hasOwnProperty.call(e,"_controlledTransformStream")&&e instanceof an}function ln(e){e._transformAlgorithm=void 0,e._flushAlgorithm=void 0,e._cancelAlgorithm=void 0}function un(e,t){const r=e._controlledTransformStream,n=r._readable._readableStreamController;if(!wr(n))throw new TypeError("Readable side is not in a state that permits enqueue");try{gr(n,t)}catch(e){throw nn(r,e),r._readable._storedError}const s=function(e){return!mr(e)}(n);s!==r._backpressure&&on(r,!0)}function dn(e,t){return m(e._transformAlgorithm(t),void 0,(t=>{throw rn(e._controlledTransformStream,t),t}))}function hn(e){return new TypeError(`TransformStreamDefaultController.prototype.${e} can only be used on a TransformStreamDefaultController`)}function fn(e){void 0!==e._finishPromise_resolve&&(e._finishPromise_resolve(),e._finishPromise_resolve=void 0,e._finishPromise_reject=void 0)}function pn(e,t){void 0!==e._finishPromise_reject&&(_(e._finishPromise),e._finishPromise_reject(t),e._finishPromise_resolve=void 0,e._finishPromise_reject=void 0)}function mn(e){return new TypeError(`TransformStream.prototype.${e} can only be used on a TransformStream`)}Object.defineProperties(an.prototype,{enqueue:{enumerable:!0},error:{enumerable:!0},terminate:{enumerable:!0},desiredSize:{enumerable:!0}}),s(an.prototype.enqueue,"enqueue"),s(an.prototype.error,"error"),s(an.prototype.terminate,"terminate"),"symbol"==typeof Symbol.toStringTag&&Object.defineProperty(an.prototype,Symbol.toStringTag,{value:"TransformStreamDefaultController",configurable:!0}),e.ByteLengthQueuingStrategy=qr,e.CountQueuingStrategy=Yr,e.ReadableByteStreamController=Se,e.ReadableStream=Nr,e.ReadableStreamBYOBReader=ot,e.ReadableStreamBYOBRequest=ve,e.ReadableStreamDefaultController=hr,e.ReadableStreamDefaultReader=K,e.TransformStream=en,e.TransformStreamDefaultController=an,e.WritableStream=bt,e.WritableStreamDefaultController=Gt,e.WritableStreamDefaultWriter=xt},"object"==typeof e&&void 0!==t?n(e):"function"==typeof define&&define.amd?define(["exports"],n):n((r="undefined"!=typeof globalThis?globalThis:r||self).WebStreamsPolyfill={})}}),re=O({"node_modules/fetch-blob/streams.cjs"(){if(!globalThis.ReadableStream)try{const e=S("process"),{emitWarning:t}=e;try{e.emitWarning=()=>{},Object.assign(globalThis,S("stream/web")),e.emitWarning=t}catch(r){throw e.emitWarning=t,r}}catch(e){Object.assign(globalThis,te())}try{const{Blob:e}=S("buffer");e&&!e.prototype.stream&&(e.prototype.stream=function(e){let t=0;const r=this;return new ReadableStream({type:"bytes",async pull(e){const n=r.slice(t,Math.min(r.size,t+65536)),s=await n.arrayBuffer();t+=s.byteLength,e.enqueue(new Uint8Array(s)),t===r.size&&e.close()}})})}catch(e){}}});async function*ne(e,t=!0){for(const r of e)if("stream"in r)yield*r.stream();else if(ArrayBuffer.isView(r))if(t){let e=r.byteOffset;const t=r.byteOffset+r.byteLength;for(;e!==t;){const n=Math.min(t-e,X),s=r.buffer.slice(e,e+n);e+=s.byteLength,yield new Uint8Array(s)}}else yield r;else{let e=0,t=r;for(;e!==t.size;){const r=t.slice(e,Math.min(t.size,e+X)),n=await r.arrayBuffer();e+=n.byteLength,yield new Uint8Array(n)}}}var se,oe,ie,ae,ce,le,ue,de,he,fe,pe,me=A({"node_modules/fetch-blob/index.js"(){C(re(),1),X=65536,Z=class e{#e=[];#t="";#r=0;#n="transparent";constructor(t=[],r={}){if("object"!=typeof t||null===t)throw new TypeError("Failed to construct 'Blob': The provided value cannot be converted to a sequence.");if("function"!=typeof t[Symbol.iterator])throw new TypeError("Failed to construct 'Blob': The object must have a callable @@iterator property.");if("object"!=typeof r&&"function"!=typeof r)throw new TypeError("Failed to construct 'Blob': parameter 2 cannot convert to dictionary.");null===r&&(r={});const n=new TextEncoder;for(const r of t){let t;t=ArrayBuffer.isView(r)?new Uint8Array(r.buffer.slice(r.byteOffset,r.byteOffset+r.byteLength)):r instanceof ArrayBuffer?new Uint8Array(r.slice(0)):r instanceof e?r:n.encode(`${r}`),this.#r+=ArrayBuffer.isView(t)?t.byteLength:t.size,this.#e.push(t)}this.#n=`${void 0===r.endings?"transparent":r.endings}`;const s=void 0===r.type?"":String(r.type);this.#t=/^[\x20-\x7E]*$/.test(s)?s:""}get size(){return this.#r}get type(){return this.#t}async text(){const e=new TextDecoder;let t="";for await(const r of ne(this.#e,!1))t+=e.decode(r,{stream:!0});return t+=e.decode(),t}async arrayBuffer(){const e=new Uint8Array(this.size);let t=0;for await(const r of ne(this.#e,!1))e.set(r,t),t+=r.length;return e.buffer}stream(){const e=ne(this.#e,!0);return new globalThis.ReadableStream({type:"bytes",async pull(t){const r=await e.next();r.done?t.close():t.enqueue(r.value)},async cancel(){await e.return()}})}slice(t=0,r=this.size,n=""){const{size:s}=this;let o=t<0?Math.max(s+t,0):Math.min(t,s),i=r<0?Math.max(s+r,0):Math.min(r,s);const a=Math.max(i-o,0),c=this.#e,l=[];let u=0;for(const e of c){if(u>=a)break;const t=ArrayBuffer.isView(e)?e.byteLength:e.size;if(o&&t<=o)o-=t,i-=t;else{let r;ArrayBuffer.isView(e)?(r=e.subarray(o,Math.min(t,i)),u+=r.byteLength):(r=e.slice(o,Math.min(t,i)),u+=r.size),i-=t,l.push(r),o=0}}const d=new e([],{type:String(n).toLowerCase()});return d.#r=a,d.#e=l,d}get[Symbol.toStringTag](){return"Blob"}static[Symbol.hasInstance](e){return e&&"object"==typeof e&&"function"==typeof e.constructor&&("function"==typeof e.stream||"function"==typeof e.arrayBuffer)&&/^(Blob|File)$/.test(e[Symbol.toStringTag])}},Object.defineProperties(Z.prototype,{size:{enumerable:!0},type:{enumerable:!0},slice:{enumerable:!0}}),Q=Z}}),_e=A({"node_modules/fetch-blob/file.js"(){me(),se=class extends Q{#s=0;#o="";constructor(e,t,r={}){if(arguments.length<2)throw new TypeError(`Failed to construct 'File': 2 arguments required, but only ${arguments.length} present.`);super(e,r),null===r&&(r={});const n=void 0===r.lastModified?Date.now():Number(r.lastModified);Number.isNaN(n)||(this.#s=n),this.#o=String(t)}get name(){return this.#o}get lastModified(){return this.#s}get[Symbol.toStringTag](){return"File"}static[Symbol.hasInstance](e){return!!e&&e instanceof Q&&/^(File)$/.test(e[Symbol.toStringTag])}},oe=se}});var ye,ge,Ee,be,we,Te,ve,Se,Ae,Oe,Re,Ce,Ie,ke,Ne,Pe,xe,De,Ue,Le,je,Me,Fe,Be,Ge=A({"node_modules/formdata-polyfill/esm.min.js"(){me(),_e(),({toStringTag:ie,iterator:ae,hasInstance:ce}=Symbol),le=Math.random,ue="append,set,get,getAll,delete,keys,values,entries,forEach,constructor".split(","),de=(e,t,r)=>(e+="",/^(Blob|File)$/.test(t&&t[ie])?[(r=void 0!==r?r+"":"File"==t[ie]?t.name:"blob",e),t.name!==r||"blob"==t[ie]?new oe([t],r,t):t]:[e,t+""]),he=(e,t)=>(t?e:e.replace(/\r?\n|\r/g,"\r\n")).replace(/\n/g,"%0A").replace(/\r/g,"%0D").replace(/"/g,"%22"),fe=(e,t,r)=>{if(t.length<r)throw new TypeError(`Failed to execute '${e}' on 'FormData': ${r} arguments required, but only ${t.length} present.`)},pe=class{#i=[];constructor(...e){if(e.length)throw new TypeError("Failed to construct 'FormData': parameter 1 is not of type 'HTMLFormElement'.")}get[ie](){return"FormData"}[ae](){return this.entries()}static[ce](e){return e&&"object"==typeof e&&"FormData"===e[ie]&&!ue.some((t=>"function"!=typeof e[t]))}append(...e){fe("append",arguments,2),this.#i.push(de(...e))}delete(e){fe("delete",arguments,1),e+="",this.#i=this.#i.filter((([t])=>t!==e))}get(e){fe("get",arguments,1),e+="";for(var t=this.#i,r=t.length,n=0;n<r;n++)if(t[n][0]===e)return t[n][1];return null}getAll(e,t){return fe("getAll",arguments,1),t=[],e+="",this.#i.forEach((r=>r[0]===e&&t.push(r[1]))),t}has(e){return fe("has",arguments,1),e+="",this.#i.some((t=>t[0]===e))}forEach(e,t){for(var[r,n]of(fe("forEach",arguments,1),this))e.call(t,n,r,this)}set(...e){fe("set",arguments,2);var t=[],r=!0;e=de(...e),this.#i.forEach((n=>{n[0]===e[0]?r&&(r=!t.push(e)):t.push(n)})),r&&t.push(e),this.#i=t}*entries(){yield*this.#i}*keys(){for(var[e]of this)yield e}*values(){for(var[,e]of this)yield e}}}}),He=A({"node_modules/node-fetch/src/errors/base.js"(){ye=class extends Error{constructor(e,t){super(e),Error.captureStackTrace(this,this.constructor),this.type=t}get name(){return this.constructor.name}get[Symbol.toStringTag](){return this.constructor.name}}}}),qe=A({"node_modules/node-fetch/src/errors/fetch-error.js"(){He(),ge=class extends ye{constructor(e,t,r){super(e,t),r&&(this.code=this.errno=r.code,this.erroredSysCall=r.syscall)}}}}),$e=A({"node_modules/node-fetch/src/utils/is.js"(){Ee=Symbol.toStringTag,be=e=>"object"==typeof e&&"function"==typeof e.append&&"function"==typeof e.delete&&"function"==typeof e.get&&"function"==typeof e.getAll&&"function"==typeof e.has&&"function"==typeof e.set&&"function"==typeof e.sort&&"URLSearchParams"===e[Ee],we=e=>e&&"object"==typeof e&&"function"==typeof e.arrayBuffer&&"string"==typeof e.type&&"function"==typeof e.stream&&"function"==typeof e.constructor&&/^(Blob|File)$/.test(e[Ee]),Te=e=>"object"==typeof e&&("AbortSignal"===e[Ee]||"EventTarget"===e[Ee]),ve=(e,t)=>{const r=new URL(t).hostname,n=new URL(e).hostname;return r===n||r.endsWith(`.${n}`)},Se=(e,t)=>new URL(t).protocol===new URL(e).protocol}}),We=O({"node_modules/node-domexception/index.js"(e,t){if(!globalThis.DOMException)try{const{MessageChannel:e}=S("worker_threads"),t=(new e).port1,r=new ArrayBuffer;t.postMessage(r,[r,r])}catch(e){"DOMException"===e.constructor.name&&(globalThis.DOMException=e.constructor)}t.exports=globalThis.DOMException}}),Ve=A({"node_modules/fetch-blob/from.js"(){Ae=C(We(),1),_e(),me(),({stat:Oe}=e.promises),Re=(t,r)=>Ne(e.statSync(t),t,r),Ce=(e,t)=>Oe(e).then((r=>Ne(r,e,t))),Ie=(e,t)=>Oe(e).then((r=>Pe(r,e,t))),ke=(t,r)=>Pe(e.statSync(t),t,r),Ne=(e,t,r="")=>new Q([new xe({path:t,size:e.size,lastModified:e.mtimeMs,start:0})],{type:r}),Pe=(e,r,n="")=>new oe([new xe({path:r,size:e.size,lastModified:e.mtimeMs,start:0})],t.basename(r),{type:n,lastModified:e.mtimeMs}),xe=class t{#a;#c;constructor(e){this.#a=e.path,this.#c=e.start,this.size=e.size,this.lastModified=e.lastModified}slice(e,r){return new t({path:this.#a,lastModified:this.lastModified,size:r-e,start:this.#c+e})}async*stream(){const{mtimeMs:t}=await Oe(this.#a);if(t>this.lastModified)throw new Ae.default("The requested file could not be read, typically due to permission problems that have occurred after a reference to a file was acquired.","NotReadableError");yield*e.createReadStream(this.#a,{start:this.#c,end:this.#c+this.size-1})}get[Symbol.toStringTag](){return"Blob"}}}}),Ye={};async function ze(e,t){if(!/multipart/i.test(t))throw new TypeError("Failed to fetch");const r=t.match(/boundary=(?:"([^"]+)"|([^;]+))/i);if(!r)throw new TypeError("no or bad content-type header, no multipart boundary");const n=new Be(r[1]||r[2]);let s,o,i,a,c,l;const u=[],d=new pe,h=e=>{i+=_.decode(e,{stream:!0})},f=e=>{u.push(e)},p=()=>{const e=new oe(u,l,{type:c});d.append(a,e)},m=()=>{d.append(a,i)},_=new TextDecoder("utf-8");_.decode(),n.onPartBegin=function(){n.onPartData=h,n.onPartEnd=m,s="",o="",i="",a="",c="",l=null,u.length=0},n.onHeaderField=function(e){s+=_.decode(e,{stream:!0})},n.onHeaderValue=function(e){o+=_.decode(e,{stream:!0})},n.onHeaderEnd=function(){if(o+=_.decode(),s=s.toLowerCase(),"content-disposition"===s){const e=o.match(/\bname=("([^"]*)"|([^()<>@,;:\\"/[\]?={}\s\t]+))/i);e&&(a=e[2]||e[3]||""),l=function(e){const t=e.match(/\bfilename=("(.*?)"|([^()<>@,;:\\"/[\]?={}\s\t]+))($|;\s)/i);if(!t)return;const r=t[2]||t[3]||"";let n=r.slice(r.lastIndexOf("\\")+1);return n=n.replace(/%22/g,'"'),n=n.replace(/&#(\d{4});/g,((e,t)=>String.fromCharCode(t))),n}(o),l&&(n.onPartData=f,n.onPartEnd=p)}else"content-type"===s&&(c=o);o="",s=""};for await(const t of e)n.write(t);return n.end(),d}R(Ye,{toFormData:()=>ze});var Je,Ke,Xe,Ze,Qe,et,tt,rt,nt=A({"node_modules/node-fetch/src/utils/multipart-parser.js"(){Ve(),Ge(),De=0,Ue={START_BOUNDARY:De++,HEADER_FIELD_START:De++,HEADER_FIELD:De++,HEADER_VALUE_START:De++,HEADER_VALUE:De++,HEADER_VALUE_ALMOST_DONE:De++,HEADERS_ALMOST_DONE:De++,PART_DATA_START:De++,PART_DATA:De++,END:De++},je={PART_BOUNDARY:Le=1,LAST_BOUNDARY:Le*=2},Me=e=>32|e,Fe=()=>{},Be=class{constructor(e){this.index=0,this.flags=0,this.onHeaderEnd=Fe,this.onHeaderField=Fe,this.onHeadersEnd=Fe,this.onHeaderValue=Fe,this.onPartBegin=Fe,this.onPartData=Fe,this.onPartEnd=Fe,this.boundaryChars={},e="\r\n--"+e;const t=new Uint8Array(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r),this.boundaryChars[t[r]]=!0;this.boundary=t,this.lookbehind=new Uint8Array(this.boundary.length+8),this.state=Ue.START_BOUNDARY}write(e){let t=0;const r=e.length;let n=this.index,{lookbehind:s,boundary:o,boundaryChars:i,index:a,state:c,flags:l}=this;const u=this.boundary.length,d=u-1,h=e.length;let f,p;const m=e=>{this[e+"Mark"]=t},_=e=>{delete this[e+"Mark"]},y=(e,t,r,n)=>{void 0!==t&&t===r||this[e](n&&n.subarray(t,r))},g=(r,n)=>{const s=r+"Mark";s in this&&(n?(y(r,this[s],t,e),delete this[s]):(y(r,this[s],e.length,e),this[s]=0))};for(t=0;t<r;t++)switch(f=e[t],c){case Ue.START_BOUNDARY:if(a===o.length-2){if(45===f)l|=je.LAST_BOUNDARY;else if(13!==f)return;a++;break}if(a-1==o.length-2){if(l&je.LAST_BOUNDARY&&45===f)c=Ue.END,l=0;else{if(l&je.LAST_BOUNDARY||10!==f)return;a=0,y("onPartBegin"),c=Ue.HEADER_FIELD_START}break}f!==o[a+2]&&(a=-2),f===o[a+2]&&a++;break;case Ue.HEADER_FIELD_START:c=Ue.HEADER_FIELD,m("onHeaderField"),a=0;case Ue.HEADER_FIELD:if(13===f){_("onHeaderField"),c=Ue.HEADERS_ALMOST_DONE;break}if(a++,45===f)break;if(58===f){if(1===a)return;g("onHeaderField",!0),c=Ue.HEADER_VALUE_START;break}if(p=Me(f),p<97||p>122)return;break;case Ue.HEADER_VALUE_START:if(32===f)break;m("onHeaderValue"),c=Ue.HEADER_VALUE;case Ue.HEADER_VALUE:13===f&&(g("onHeaderValue",!0),y("onHeaderEnd"),c=Ue.HEADER_VALUE_ALMOST_DONE);break;case Ue.HEADER_VALUE_ALMOST_DONE:if(10!==f)return;c=Ue.HEADER_FIELD_START;break;case Ue.HEADERS_ALMOST_DONE:if(10!==f)return;y("onHeadersEnd"),c=Ue.PART_DATA_START;break;case Ue.PART_DATA_START:c=Ue.PART_DATA,m("onPartData");case Ue.PART_DATA:if(n=a,0===a){for(t+=d;t<h&&!(e[t]in i);)t+=u;t-=d,f=e[t]}if(a<o.length)o[a]===f?(0===a&&g("onPartData",!0),a++):a=0;else if(a===o.length)a++,13===f?l|=je.PART_BOUNDARY:45===f?l|=je.LAST_BOUNDARY:a=0;else if(a-1===o.length)if(l&je.PART_BOUNDARY){if(a=0,10===f){l&=~je.PART_BOUNDARY,y("onPartEnd"),y("onPartBegin"),c=Ue.HEADER_FIELD_START;break}}else l&je.LAST_BOUNDARY&&45===f?(y("onPartEnd"),c=Ue.END,l=0):a=0;if(a>0)s[a-1]=f;else if(n>0){const e=new Uint8Array(s.buffer,s.byteOffset,s.byteLength);y("onPartData",0,n,e),n=0,m("onPartData"),t--}break;case Ue.END:break;default:throw new Error(`Unexpected state entered: ${c}`)}g("onHeaderField"),g("onHeaderValue"),g("onPartData"),this.index=a,this.state=c,this.flags=l}end(){if(this.state===Ue.HEADER_FIELD_START&&0===this.index||this.state===Ue.PART_DATA&&this.index===this.boundary.length)this.onPartEnd();else if(this.state!==Ue.END)throw new Error("MultipartParser.end(): stream ended unexpectedly")}}}});async function st(e){if(e[Ke].disturbed)throw new TypeError(`body used already for: ${e.url}`);if(e[Ke].disturbed=!0,e[Ke].error)throw e[Ke].error;const{body:t}=e;if(null===t)return s.Buffer.alloc(0);if(!(t instanceof p.default))return s.Buffer.alloc(0);const r=[];let n=0;try{for await(const s of t){if(e.size>0&&n+s.length>e.size){const r=new ge(`content size at ${e.url} over limit: ${e.size}`,"max-size");throw t.destroy(r),r}n+=s.length,r.push(s)}}catch(t){throw t instanceof ye?t:new ge(`Invalid response body while trying to fetch ${e.url}: ${t.message}`,"system",t)}if(!0!==t.readableEnded&&!0!==t._readableState.ended)throw new ge(`Premature close of server response while trying to fetch ${e.url}`);try{return r.every((e=>"string"==typeof e))?s.Buffer.from(r.join("")):s.Buffer.concat(r,n)}catch(t){throw new ge(`Could not create Buffer from response body for ${e.url}: ${t.message}`,"system",t)}}var ot,it,at,ct=A({"node_modules/node-fetch/src/body.js"(){me(),Ge(),qe(),He(),$e(),Je=n.promisify(p.default.pipeline),Ke=Symbol("Body internals"),(Xe=class{constructor(e,{size:t=0}={}){let r=null;null===e?e=null:be(e)?e=s.Buffer.from(e.toString()):we(e)||s.Buffer.isBuffer(e)||(n.types.isAnyArrayBuffer(e)?e=s.Buffer.from(e):ArrayBuffer.isView(e)?e=s.Buffer.from(e.buffer,e.byteOffset,e.byteLength):e instanceof p.default||(e instanceof pe?r=(e=function(e,t=Q){var r=`${le()}${le()}`.replace(/\./g,"").slice(-28).padStart(32,"-"),n=[],s=`--${r}\r\nContent-Disposition: form-data; name="`;return e.forEach(((e,t)=>"string"==typeof e?n.push(s+he(t)+`"\r\n\r\n${e.replace(/\r(?!\n)|(?<!\r)\n/g,"\r\n")}\r\n`):n.push(s+he(t)+`"; filename="${he(e.name,1)}"\r\nContent-Type: ${e.type||"application/octet-stream"}\r\n\r\n`,e,"\r\n"))),n.push(`--${r}--`),new t(n,{type:"multipart/form-data; boundary="+r})}(e)).type.split("=")[1]:e=s.Buffer.from(String(e))));let o=e;s.Buffer.isBuffer(e)?o=p.default.Readable.from(e):we(e)&&(o=p.default.Readable.from(e.stream())),this[Ke]={body:e,stream:o,boundary:r,disturbed:!1,error:null},this.size=t,e instanceof p.default&&e.on("error",(e=>{const t=e instanceof ye?e:new ge(`Invalid response body while trying to fetch ${this.url}: ${e.message}`,"system",e);this[Ke].error=t}))}get body(){return this[Ke].stream}get bodyUsed(){return this[Ke].disturbed}async arrayBuffer(){const{buffer:e,byteOffset:t,byteLength:r}=await st(this);return e.slice(t,t+r)}async formData(){const e=this.headers.get("content-type");if(e.startsWith("application/x-www-form-urlencoded")){const e=new pe,t=new URLSearchParams(await this.text());for(const[r,n]of t)e.append(r,n);return e}const{toFormData:t}=await Promise.resolve().then((()=>(nt(),Ye)));return t(this.body,e)}async blob(){const e=this.headers&&this.headers.get("content-type")||this[Ke].body&&this[Ke].body.type||"",t=await this.arrayBuffer();return new Q([t],{type:e})}async json(){const e=await this.text();return JSON.parse(e)}async text(){const e=await st(this);return(new TextDecoder).decode(e)}buffer(){return st(this)}}).prototype.buffer=n.deprecate(Xe.prototype.buffer,"Please use 'response.arrayBuffer()' instead of 'response.buffer()'","node-fetch#buffer"),Object.defineProperties(Xe.prototype,{body:{enumerable:!0},bodyUsed:{enumerable:!0},arrayBuffer:{enumerable:!0},blob:{enumerable:!0},json:{enumerable:!0},text:{enumerable:!0},data:{get:n.deprecate((()=>{}),"data doesn't exist, use json(), text(), arrayBuffer(), or body instead","https://github.com/node-fetch/node-fetch/issues/1000 (response)")}}),Ze=(e,t)=>{let n,s,{body:o}=e[Ke];if(e.bodyUsed)throw new Error("cannot clone body after it is used");return o instanceof p.default&&"function"!=typeof o.getBoundary&&(n=new r.PassThrough({highWaterMark:t}),s=new r.PassThrough({highWaterMark:t}),o.pipe(n),o.pipe(s),e[Ke].stream=n,o=s),o},Qe=n.deprecate((e=>e.getBoundary()),"form-data doesn't follow the spec and requires special treatment. Use alternative package","https://github.com/node-fetch/node-fetch/issues/1167"),et=(e,t)=>null===e?null:"string"==typeof e?"text/plain;charset=UTF-8":be(e)?"application/x-www-form-urlencoded;charset=UTF-8":we(e)?e.type||null:s.Buffer.isBuffer(e)||n.types.isAnyArrayBuffer(e)||ArrayBuffer.isView(e)?null:e instanceof pe?`multipart/form-data; boundary=${t[Ke].boundary}`:e&&"function"==typeof e.getBoundary?`multipart/form-data;boundary=${Qe(e)}`:e instanceof p.default?null:"text/plain;charset=UTF-8",tt=e=>{const{body:t}=e[Ke];return null===t?0:we(t)?t.size:s.Buffer.isBuffer(t)?t.length:t&&"function"==typeof t.getLengthSync&&t.hasKnownLength&&t.hasKnownLength()?t.getLengthSync():null},rt=async(e,{body:t})=>{null===t?e.end():await Je(t,e)}}});var lt,ut,dt,ht,ft,pt,mt,_t=A({"node_modules/node-fetch/src/headers.js"(){ot="function"==typeof m.default.validateHeaderName?m.default.validateHeaderName:e=>{if(!/^[\^`\-\w!#$%&'*+.|~]+$/.test(e)){const t=new TypeError(`Header name must be a valid HTTP token [${e}]`);throw Object.defineProperty(t,"code",{value:"ERR_INVALID_HTTP_TOKEN"}),t}},it="function"==typeof m.default.validateHeaderValue?m.default.validateHeaderValue:(e,t)=>{if(/[^\t\u0020-\u007E\u0080-\u00FF]/.test(t)){const t=new TypeError(`Invalid character in header content ["${e}"]`);throw Object.defineProperty(t,"code",{value:"ERR_INVALID_CHAR"}),t}},at=class e extends URLSearchParams{constructor(t){let r=[];if(t instanceof e){const e=t.raw();for(const[t,n]of Object.entries(e))r.push(...n.map((e=>[t,e])))}else if(null==t);else{if("object"!=typeof t||n.types.isBoxedPrimitive(t))throw new TypeError("Failed to construct 'Headers': The provided value is not of type '(sequence<sequence<ByteString>> or record<ByteString, ByteString>)");{const e=t[Symbol.iterator];if(null==e)r.push(...Object.entries(t));else{if("function"!=typeof e)throw new TypeError("Header pairs must be iterable");r=[...t].map((e=>{if("object"!=typeof e||n.types.isBoxedPrimitive(e))throw new TypeError("Each header pair must be an iterable object");return[...e]})).map((e=>{if(2!==e.length)throw new TypeError("Each header pair must be a name/value tuple");return[...e]}))}}}return r=r.length>0?r.map((([e,t])=>(ot(e),it(e,String(t)),[String(e).toLowerCase(),String(t)]))):void 0,super(r),new Proxy(this,{get(e,t,r){switch(t){case"append":case"set":return(r,n)=>(ot(r),it(r,String(n)),URLSearchParams.prototype[t].call(e,String(r).toLowerCase(),String(n)));case"delete":case"has":case"getAll":return r=>(ot(r),URLSearchParams.prototype[t].call(e,String(r).toLowerCase()));case"keys":return()=>(e.sort(),new Set(URLSearchParams.prototype.keys.call(e)).keys());default:return Reflect.get(e,t,r)}}})}get[Symbol.toStringTag](){return this.constructor.name}toString(){return Object.prototype.toString.call(this)}get(e){const t=this.getAll(e);if(0===t.length)return null;let r=t.join(", ");return/^content-encoding$/i.test(e)&&(r=r.toLowerCase()),r}forEach(e,t=void 0){for(const r of this.keys())Reflect.apply(e,t,[this.get(r),r,this])}*values(){for(const e of this.keys())yield this.get(e)}*entries(){for(const e of this.keys())yield[e,this.get(e)]}[Symbol.iterator](){return this.entries()}raw(){return[...this.keys()].reduce(((e,t)=>(e[t]=this.getAll(t),e)),{})}[Symbol.for("nodejs.util.inspect.custom")](){return[...this.keys()].reduce(((e,t)=>{const r=this.getAll(t);return e[t]="host"===t?r[0]:r.length>1?r:r[0],e}),{})}},Object.defineProperties(at.prototype,["get","entries","forEach","values"].reduce(((e,t)=>(e[t]={enumerable:!0},e)),{}))}}),yt=A({"node_modules/node-fetch/src/utils/is-redirect.js"(){lt=new Set([301,302,303,307,308]),ut=e=>lt.has(e)}}),gt=A({"node_modules/node-fetch/src/response.js"(){_t(),ct(),yt(),dt=Symbol("Response internals"),ht=class e extends Xe{constructor(e=null,t={}){super(e,t);const r=null!=t.status?t.status:200,n=new at(t.headers);if(null!==e&&!n.has("Content-Type")){const t=et(e,this);t&&n.append("Content-Type",t)}this[dt]={type:"default",url:t.url,status:r,statusText:t.statusText||"",headers:n,counter:t.counter,highWaterMark:t.highWaterMark}}get type(){return this[dt].type}get url(){return this[dt].url||""}get status(){return this[dt].status}get ok(){return this[dt].status>=200&&this[dt].status<300}get redirected(){return this[dt].counter>0}get statusText(){return this[dt].statusText}get headers(){return this[dt].headers}get highWaterMark(){return this[dt].highWaterMark}clone(){return new e(Ze(this,this.highWaterMark),{type:this.type,url:this.url,status:this.status,statusText:this.statusText,headers:this.headers,ok:this.ok,redirected:this.redirected,size:this.size,highWaterMark:this.highWaterMark})}static redirect(t,r=302){if(!ut(r))throw new RangeError('Failed to execute "redirect" on "response": Invalid status code');return new e(null,{headers:{location:new URL(t).toString()},status:r})}static error(){const t=new e(null,{status:0,statusText:""});return t[dt].type="error",t}static json(t=void 0,r={}){const n=JSON.stringify(t);if(void 0===n)throw new TypeError("data is not JSON serializable");const s=new at(r&&r.headers);return s.has("content-type")||s.set("content-type","application/json"),new e(n,{...r,headers:s})}get[Symbol.toStringTag](){return"Response"}},Object.defineProperties(ht.prototype,{type:{enumerable:!0},url:{enumerable:!0},status:{enumerable:!0},ok:{enumerable:!0},redirected:{enumerable:!0},statusText:{enumerable:!0},headers:{enumerable:!0},clone:{enumerable:!0}})}}),Et=A({"node_modules/node-fetch/src/utils/get-search.js"(){ft=e=>{if(e.search)return e.search;const t=e.href.length-1,r=e.hash||("#"===e.href[t]?"#":"");return"?"===e.href[t-r.length]?"?":""}}});function bt(e,t=!1){return null==e?"no-referrer":(e=new URL(e),/^(about|blob|data):$/.test(e.protocol)?"no-referrer":(e.username="",e.password="",e.hash="",t&&(e.pathname="",e.search=""),e))}function wt(e){return!!/^about:(blank|srcdoc)$/.test(e)||("data:"===e.protocol||(!!/^(blob|filesystem):$/.test(e.protocol)||function(e){if(/^(http|ws)s:$/.test(e.protocol))return!0;const t=e.host.replace(/(^\[)|(]$)/g,""),r=i.isIP(t);return!(4!==r||!/^127\./.test(t))||!(6!==r||!/^(((0+:){7})|(::(0+:){0,6}))0*1$/.test(t))||"localhost"!==e.host&&!e.host.endsWith(".localhost")&&"file:"===e.protocol}(e)))}var Tt,vt,St,At,Ot,Rt,Ct,It=A({"node_modules/node-fetch/src/utils/referrer.js"(){pt=new Set(["","no-referrer","no-referrer-when-downgrade","same-origin","origin","strict-origin","origin-when-cross-origin","strict-origin-when-cross-origin","unsafe-url"]),mt="strict-origin-when-cross-origin"}}),kt=A({"node_modules/node-fetch/src/request.js"(){_t(),ct(),$e(),Et(),It(),Tt=Symbol("Request internals"),vt=e=>"object"==typeof e&&"object"==typeof e[Tt],St=n.deprecate((()=>{}),".data is not a valid RequestInit property, use .body instead","https://github.com/node-fetch/node-fetch/issues/1000 (request)"),At=class e extends Xe{constructor(e,t={}){let r;if(vt(e)?r=new URL(e.url):(r=new URL(e),e={}),""!==r.username||""!==r.password)throw new TypeError(`${r} is an url with embedded credentials.`);let n=t.method||e.method||"GET";if(/^(delete|get|head|options|post|put)$/i.test(n)&&(n=n.toUpperCase()),!vt(t)&&"data"in t&&St(),(null!=t.body||vt(e)&&null!==e.body)&&("GET"===n||"HEAD"===n))throw new TypeError("Request with GET/HEAD method cannot have body");const s=t.body?t.body:vt(e)&&null!==e.body?Ze(e):null;super(s,{size:t.size||e.size||0});const o=new at(t.headers||e.headers||{});if(null!==s&&!o.has("Content-Type")){const e=et(s,this);e&&o.set("Content-Type",e)}let i=vt(e)?e.signal:null;if("signal"in t&&(i=t.signal),null!=i&&!Te(i))throw new TypeError("Expected signal to be an instanceof AbortSignal or EventTarget");let a=null==t.referrer?e.referrer:t.referrer;if(""===a)a="no-referrer";else if(a){const e=new URL(a);a=/^about:(\/\/)?client$/.test(e)?"client":e}else a=void 0;this[Tt]={method:n,redirect:t.redirect||e.redirect||"follow",headers:o,parsedURL:r,signal:i,referrer:a},this.follow=void 0===t.follow?void 0===e.follow?20:e.follow:t.follow,this.compress=void 0===t.compress?void 0===e.compress||e.compress:t.compress,this.counter=t.counter||e.counter||0,this.agent=t.agent||e.agent,this.highWaterMark=t.highWaterMark||e.highWaterMark||16384,this.insecureHTTPParser=t.insecureHTTPParser||e.insecureHTTPParser||!1,this.referrerPolicy=t.referrerPolicy||e.referrerPolicy||""}get method(){return this[Tt].method}get url(){return a.format(this[Tt].parsedURL)}get headers(){return this[Tt].headers}get redirect(){return this[Tt].redirect}get signal(){return this[Tt].signal}get referrer(){return"no-referrer"===this[Tt].referrer?"":"client"===this[Tt].referrer?"about:client":this[Tt].referrer?this[Tt].referrer.toString():void 0}get referrerPolicy(){return this[Tt].referrerPolicy}set referrerPolicy(e){this[Tt].referrerPolicy=function(e){if(!pt.has(e))throw new TypeError(`Invalid referrerPolicy: ${e}`);return e}(e)}clone(){return new e(this)}get[Symbol.toStringTag](){return"Request"}},Object.defineProperties(At.prototype,{method:{enumerable:!0},url:{enumerable:!0},headers:{enumerable:!0},redirect:{enumerable:!0},clone:{enumerable:!0},signal:{enumerable:!0},referrer:{enumerable:!0},referrerPolicy:{enumerable:!0}}),Ot=e=>{const{parsedURL:t}=e[Tt],r=new at(e[Tt].headers);r.has("Accept")||r.set("Accept","*/*");let n=null;if(null===e.body&&/^(post|put)$/i.test(e.method)&&(n="0"),null!==e.body){const t=tt(e);"number"!=typeof t||Number.isNaN(t)||(n=String(t))}n&&r.set("Content-Length",n),""===e.referrerPolicy&&(e.referrerPolicy=mt),e.referrer&&"no-referrer"!==e.referrer?e[Tt].referrer=function(e,{referrerURLCallback:t,referrerOriginCallback:r}={}){if("no-referrer"===e.referrer||""===e.referrerPolicy)return null;const n=e.referrerPolicy;if("about:client"===e.referrer)return"no-referrer";const s=e.referrer;let o=bt(s),i=bt(s,!0);o.toString().length>4096&&(o=i),t&&(o=t(o)),r&&(i=r(i));const a=new URL(e.url);switch(n){case"no-referrer":return"no-referrer";case"origin":return i;case"unsafe-url":return o;case"strict-origin":return wt(o)&&!wt(a)?"no-referrer":i.toString();case"strict-origin-when-cross-origin":return o.origin===a.origin?o:wt(o)&&!wt(a)?"no-referrer":i;case"same-origin":return o.origin===a.origin?o:"no-referrer";case"origin-when-cross-origin":return o.origin===a.origin?o:i;case"no-referrer-when-downgrade":return wt(o)&&!wt(a)?"no-referrer":o;default:throw new TypeError(`Invalid referrerPolicy: ${n}`)}}(e):e[Tt].referrer="no-referrer",e[Tt].referrer instanceof URL&&r.set("Referer",e.referrer),r.has("User-Agent")||r.set("User-Agent","node-fetch"),e.compress&&!r.has("Accept-Encoding")&&r.set("Accept-Encoding","gzip, deflate, br");let{agent:s}=e;"function"==typeof s&&(s=s(t));const o=ft(t);return{parsedURL:t,options:{path:t.pathname+o,method:e.method,headers:r[Symbol.for("nodejs.util.inspect.custom")](),insecureHTTPParser:e.insecureHTTPParser,agent:s}}}}}),Nt=A({"node_modules/node-fetch/src/errors/abort-error.js"(){He(),Rt=class extends ye{constructor(e,t="aborted"){super(e,t)}}}}),Pt={};async function xt(e,t){return new Promise(((n,o)=>{const i=new At(e,t),{parsedURL:a,options:c}=Ot(i);if(!Ct.has(a.protocol))throw new TypeError(`node-fetch cannot load ${e}. URL scheme "${a.protocol.replace(/:$/,"")}" is not supported.`);if("data:"===a.protocol){const e=f(i.url),t=new ht(e,{headers:{"Content-Type":e.typeFull}});return void n(t)}const l=("https:"===a.protocol?_.default:m.default).request,{signal:u}=i;let d=null;const h=()=>{const e=new Rt("The operation was aborted.");o(e),i.body&&i.body instanceof p.default.Readable&&i.body.destroy(e),d&&d.body&&d.body.emit("error",e)};if(u&&u.aborted)return void h();const g=()=>{h(),b()},E=l(a.toString(),c);u&&u.addEventListener("abort",g);const b=()=>{E.abort(),u&&u.removeEventListener("abort",g)};E.on("error",(e=>{o(new ge(`request to ${i.url} failed, reason: ${e.message}`,"system",e)),b()})),function(e,t){const r=s.Buffer.from("0\r\n\r\n");let n,o=!1,i=!1;e.on("response",(e=>{const{headers:t}=e;o="chunked"===t["transfer-encoding"]&&!t["content-length"]})),e.on("socket",(a=>{const c=()=>{if(o&&!i){const e=new Error("Premature close");e.code="ERR_STREAM_PREMATURE_CLOSE",t(e)}},l=e=>{i=0===s.Buffer.compare(e.slice(-5),r),!i&&n&&(i=0===s.Buffer.compare(n.slice(-3),r.slice(0,3))&&0===s.Buffer.compare(e.slice(-2),r.slice(3))),n=e};a.prependListener("close",c),a.on("data",l),e.on("close",(()=>{a.removeListener("close",c),a.removeListener("data",l)}))}))}(E,(e=>{d&&d.body&&d.body.destroy(e)})),process.version<"v14"&&E.on("socket",(e=>{let t;e.prependListener("end",(()=>{t=e._eventsCount})),e.prependListener("close",(r=>{if(d&&t<e._eventsCount&&!r){const e=new Error("Premature close");e.code="ERR_STREAM_PREMATURE_CLOSE",d.body.emit("error",e)}}))})),E.on("response",(e=>{E.setTimeout(0);const s=function(e=[]){return new at(e.reduce(((e,t,r,n)=>(r%2==0&&e.push(n.slice(r,r+2)),e)),[]).filter((([e,t])=>{try{return ot(e),it(e,String(t)),!0}catch{return!1}})))}(e.rawHeaders);if(ut(e.statusCode)){const r=s.get("Location");let a=null;try{a=null===r?null:new URL(r,i.url)}catch{if("manual"!==i.redirect)return o(new ge(`uri requested responds with an invalid redirect URL: ${r}`,"invalid-redirect")),void b()}switch(i.redirect){case"error":return o(new ge(`uri requested responds with a redirect, redirect mode is set to error: ${i.url}`,"no-redirect")),void b();case"manual":break;case"follow":{if(null===a)break;if(i.counter>=i.follow)return o(new ge(`maximum redirect reached at: ${i.url}`,"max-redirect")),void b();const r={headers:new at(i.headers),follow:i.follow,counter:i.counter+1,agent:i.agent,compress:i.compress,method:i.method,body:Ze(i),signal:i.signal,size:i.size,referrer:i.referrer,referrerPolicy:i.referrerPolicy};if(!ve(i.url,a)||!Se(i.url,a))for(const e of["authorization","www-authenticate","cookie","cookie2"])r.headers.delete(e);if(303!==e.statusCode&&i.body&&t.body instanceof p.default.Readable)return o(new ge("Cannot follow redirect with body being a readable stream","unsupported-redirect")),void b();303!==e.statusCode&&(301!==e.statusCode&&302!==e.statusCode||"POST"!==i.method)||(r.method="GET",r.body=void 0,r.headers.delete("content-length"));const c=function(e){const t=(e.get("referrer-policy")||"").split(/[,\s]+/);let r="";for(const e of t)e&&pt.has(e)&&(r=e);return r}(s);return c&&(r.referrerPolicy=c),n(xt(new At(a,r))),void b()}default:return o(new TypeError(`Redirect option '${i.redirect}' is not a valid value of RequestRedirect`))}}u&&e.once("end",(()=>{u.removeEventListener("abort",g)}));let a=r.pipeline(e,new r.PassThrough,(e=>{e&&o(e)}));process.version<"v12.10"&&e.on("aborted",g);const c={url:i.url,status:e.statusCode,statusText:e.statusMessage,headers:s,size:i.size,counter:i.counter,highWaterMark:i.highWaterMark},l=s.get("Content-Encoding");if(!i.compress||"HEAD"===i.method||null===l||204===e.statusCode||304===e.statusCode)return d=new ht(a,c),void n(d);const h={flush:y.default.Z_SYNC_FLUSH,finishFlush:y.default.Z_SYNC_FLUSH};if("gzip"===l||"x-gzip"===l)return a=r.pipeline(a,y.default.createGunzip(h),(e=>{e&&o(e)})),d=new ht(a,c),void n(d);if("deflate"===l||"x-deflate"===l){const t=r.pipeline(e,new r.PassThrough,(e=>{e&&o(e)}));return t.once("data",(e=>{a=8==(15&e[0])?r.pipeline(a,y.default.createInflate(),(e=>{e&&o(e)})):r.pipeline(a,y.default.createInflateRaw(),(e=>{e&&o(e)})),d=new ht(a,c),n(d)})),void t.once("end",(()=>{d||(d=new ht(a,c),n(d))}))}if("br"===l)return a=r.pipeline(a,y.default.createBrotliDecompress(),(e=>{e&&o(e)})),d=new ht(a,c),void n(d);d=new ht(a,c),n(d)})),rt(E,i).catch(o)}))}R(Pt,{AbortError:()=>Rt,Blob:()=>Q,FetchError:()=>ge,File:()=>oe,FormData:()=>pe,Headers:()=>at,Request:()=>At,Response:()=>ht,blobFrom:()=>Ce,blobFromSync:()=>Re,default:()=>xt,fileFrom:()=>Ie,fileFromSync:()=>ke,isRedirect:()=>ut});var Dt=A({"node_modules/node-fetch/src/index.js"(){ee(),ct(),gt(),_t(),kt(),qe(),Nt(),yt(),Ge(),$e(),It(),Ve(),Ct=new Set(["data:","http:","https:"])}}),Ut=O({"node_modules/gaxios/build/cjs/src/gaxios.js"(e){var t,r=e&&e.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(e,"__esModule",{value:!0}),e.Gaxios=void 0;var n=r(x()),s=S("https"),o=L(),i=j(),a=S("stream"),c=M(),l=class{agentCache=new Map;defaults;interceptors;constructor(e){this.defaults=e||{},this.interceptors={request:new c.GaxiosInterceptorManager,response:new c.GaxiosInterceptorManager}}fetch(...e){const r=e[0],n=e[1];let s;const o=new Headers;return"string"==typeof r?s=new URL(r):r instanceof URL?s=r:r&&r.url&&(s=new URL(r.url)),r&&"object"==typeof r&&"headers"in r&&t.mergeHeaders(o,r.headers),n&&t.mergeHeaders(o,new Headers(n.headers)),"object"!=typeof r||r instanceof URL?this.request({...n,headers:o,url:s}):this.request({...n,...r,headers:o,url:s})}async request(e={}){let t=await this.#l(e);return t=await this.#u(t),this.#d(this._request(t))}async _defaultAdapter(e){const r=e.fetchImplementation||this.defaults.fetchImplementation||await t.#h(),n={...e};delete n.data;const s=await r(e.url,n),o=await this.getResponseData(e,s);return Object.getOwnPropertyDescriptor(s,"data")?.configurable||Object.defineProperties(s,{data:{configurable:!0,writable:!0,enumerable:!0,value:o}}),Object.assign(s,{config:e,data:o})}async _request(e){try{let t;if(t=e.adapter?await e.adapter(e,this._defaultAdapter.bind(this)):await this._defaultAdapter(e),!e.validateStatus(t.status)){if("stream"===e.responseType){const e=[];for await(const r of t.data)e.push(r);t.data=e.toString()}const r=o.GaxiosError.extractAPIErrorFromResponse(t,`Request failed with status code ${t.status}`);throw new o.GaxiosError(r?.message,e,t,r)}return t}catch(t){let r;r=t instanceof o.GaxiosError?t:t instanceof Error?new o.GaxiosError(t.message,e,void 0,t):new o.GaxiosError("Unexpected Gaxios Error",e,void 0,t);const{shouldRetry:n,config:s}=await(0,i.getRetryConfig)(r);if(n&&s)return r.config.retryConfig.currentRetryAttempt=s.retryConfig.currentRetryAttempt,e.retryConfig=r.config?.retryConfig,this.#f(e),this._request(e);throw e.errorRedactor&&e.errorRedactor(r),r}}async getResponseData(e,t){if(204===t.status)return"";if(e.maxContentLength&&t.headers.has("content-length")&&e.maxContentLength<Number.parseInt(t.headers?.get("content-length")||""))throw new o.GaxiosError("Response's `Content-Length` is over the limit.",e,Object.assign(t,{config:e}));switch(e.responseType){case"stream":return t.body;case"json":{const e=await t.text();try{return JSON.parse(e)}catch{return e}}case"arraybuffer":return t.arrayBuffer();case"blob":return t.blob();case"text":return t.text();default:return this.getResponseDataFromContentType(t)}}#p(e,t=[]){const r=new URL(e),n=[...t],s=(process.env.NO_PROXY??process.env.no_proxy)?.split(",")||[];for(const e of s)n.push(e.trim());for(const e of n)if(e instanceof RegExp){if(e.test(r.toString()))return!1}else if(e instanceof URL){if(e.origin===r.origin)return!1}else if(e.startsWith("*.")||e.startsWith(".")){const t=e.replace(/^\*\./,".");if(r.hostname.endsWith(t))return!1}else if(e===r.origin||e===r.hostname||e===r.href)return!1;return!0}async#u(e){let t=Promise.resolve(e);for(const e of this.interceptors.request.values())e&&(t=t.then(e.resolved,e.rejected));return t}async#d(e){let t=Promise.resolve(e);for(const e of this.interceptors.response.values())e&&(t=t.then(e.resolved,e.rejected));return t}async#l(e){const r=new Headers(this.defaults.headers);t.mergeHeaders(r,e.headers);const i=(0,n.default)(!0,{},this.defaults,e);if(!i.url)throw new Error("URL is required.");if(i.baseURL&&(i.url=new URL(i.url,i.baseURL)),i.url=new URL(i.url),i.params)if(i.paramsSerializer){let e=i.paramsSerializer(i.params);e.startsWith("?")&&(e=e.slice(1));const t=i.url.toString().includes("?")?"&":"?";i.url=i.url+t+e}else{const e=i.url instanceof URL?i.url:new URL(i.url);for(const[t,r]of new URLSearchParams(i.params))e.searchParams.append(t,r);i.url=e}"number"==typeof e.maxContentLength&&(i.size=e.maxContentLength),"number"==typeof e.maxRedirects&&(i.follow=e.maxRedirects);const c="string"==typeof i.data||i.data instanceof ArrayBuffer||i.data instanceof Blob||globalThis.File&&i.data instanceof File||i.data instanceof FormData||i.data instanceof a.Readable||i.data instanceof ReadableStream||i.data instanceof String||i.data instanceof URLSearchParams||ArrayBuffer.isView(i.data)||["Blob","File","FormData"].includes(i.data?.constructor?.name||"");if(i.multipart?.length){const e=await(async()=>globalThis.crypto?.randomUUID()||(await import("crypto")).randomUUID())();r.set("content-type",`multipart/related; boundary=${e}`),i.body=a.Readable.from(this.getMultipartRequest(i.multipart,e))}else c?i.body=i.data:"object"==typeof i.data?"application/x-www-form-urlencoded"===r.get("Content-Type")?i.body=i.paramsSerializer?i.paramsSerializer(i.data):new URLSearchParams(i.data):(r.has("content-type")||r.set("content-type","application/json"),i.body=JSON.stringify(i.data)):i.data&&(i.body=i.data);i.validateStatus=i.validateStatus||this.validateStatus,i.responseType=i.responseType||"unknown",r.has("accept")||"json"!==i.responseType||r.set("accept","application/json");const l=i.proxy||process?.env?.HTTPS_PROXY||process?.env?.https_proxy||process?.env?.HTTP_PROXY||process?.env?.http_proxy;if(i.agent);else if(l&&this.#p(i.url,i.noProxy)){const e=await t.#m();this.agentCache.has(l)?i.agent=this.agentCache.get(l):(i.agent=new e(l,{cert:i.cert,key:i.key}),this.agentCache.set(l,i.agent))}else i.cert&&i.key&&(this.agentCache.has(i.key)?i.agent=this.agentCache.get(i.key):(i.agent=new s.Agent({cert:i.cert,key:i.key}),this.agentCache.set(i.key,i.agent)));return"function"!=typeof i.errorRedactor&&!1!==i.errorRedactor&&(i.errorRedactor=o.defaultErrorRedactor),i.body&&!("duplex"in i)&&(i.duplex="half"),this.#f(i),Object.assign(i,{headers:r,url:i.url instanceof URL?i.url:new URL(i.url)})}#f(e){if(e.timeout){const t=AbortSignal.timeout(e.timeout);e.signal&&!e.signal.aborted?e.signal=AbortSignal.any([e.signal,t]):e.signal=t}}validateStatus(e){return e>=200&&e<300}async getResponseDataFromContentType(e){let t=e.headers.get("Content-Type");if(null===t)return e.text();if(t=t.toLowerCase(),t.includes("application/json")){let t=await e.text();try{t=JSON.parse(t)}catch{}return t}return t.match(/^text\//)?e.text():e.blob()}async*getMultipartRequest(e,t){const r=`--${t}--`;for(const r of e){const e=`--${t}\r\nContent-Type: ${r.headers.get("Content-Type")||"application/octet-stream"}\r\n\r\n`;yield e,"string"==typeof r.content?yield r.content:yield*r.content,yield"\r\n"}yield r}static#_;static#y;static async#m(){return this.#_||=(await Promise.resolve().then((()=>C(J())))).HttpsProxyAgent,this.#_}static async#h(){const e="undefined"!=typeof window&&!!window;return this.#y||=e?window.fetch:(await Promise.resolve().then((()=>(Dt(),Pt)))).default,this.#y}static mergeHeaders(e,...t){e=e instanceof Headers?e:new Headers(e);for(const r of t){(r instanceof Headers?r:new Headers(r)).forEach(((t,r)=>{"set-cookie"===r?e.append(r,t):e.set(r,t)}))}return e}};e.Gaxios=l,t=l}}),Lt=O({"node_modules/gaxios/build/cjs/src/index.js"(e){var t=e&&e.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var s=Object.getOwnPropertyDescriptor(t,r);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,s)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),r=e&&e.__exportStar||function(e,r){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(r,n)||t(r,e,n)};Object.defineProperty(e,"__esModule",{value:!0}),e.instance=e.Gaxios=e.GaxiosError=void 0,e.request=async function(t){return e.instance.request(t)};var n=Ut();Object.defineProperty(e,"Gaxios",{enumerable:!0,get:function(){return n.Gaxios}});var s=L();Object.defineProperty(e,"GaxiosError",{enumerable:!0,get:function(){return s.GaxiosError}}),r(M(),e),e.instance=new n.Gaxios}}),jt=O({"node_modules/bignumber.js/bignumber.js"(e,t){!function(e){var r,n=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,s=Math.ceil,o=Math.floor,i="[BigNumber Error] ",a=i+"Number primitive has more than 15 significant digits: ",c=1e14,l=14,u=9007199254740991,d=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],h=1e7,f=1e9;function p(e){var t=0|e;return e>0||e===t?t:t-1}function m(e){for(var t,r,n=1,s=e.length,o=e[0]+"";n<s;){for(t=e[n++]+"",r=l-t.length;r--;t="0"+t);o+=t}for(s=o.length;48===o.charCodeAt(--s););return o.slice(0,s+1||1)}function _(e,t){var r,n,s=e.c,o=t.c,i=e.s,a=t.s,c=e.e,l=t.e;if(!i||!a)return null;if(r=s&&!s[0],n=o&&!o[0],r||n)return r?n?0:-a:i;if(i!=a)return i;if(r=i<0,n=c==l,!s||!o)return n?0:!s^r?1:-1;if(!n)return c>l^r?1:-1;for(a=(c=s.length)<(l=o.length)?c:l,i=0;i<a;i++)if(s[i]!=o[i])return s[i]>o[i]^r?1:-1;return c==l?0:c>l^r?1:-1}function y(e,t,r,n){if(e<t||e>r||e!==o(e))throw Error(i+(n||"Argument")+("number"==typeof e?e<t||e>r?" out of range: ":" not an integer: ":" not a primitive number: ")+String(e))}function g(e){var t=e.c.length-1;return p(e.e/l)==t&&e.c[t]%2!=0}function E(e,t){return(e.length>1?e.charAt(0)+"."+e.slice(1):e)+(t<0?"e":"e+")+t}function b(e,t,r){var n,s;if(t<0){for(s=r+".";++t;s+=r);e=s+e}else if(++t>(n=e.length)){for(s=r,t-=n;--t;s+=r);e+=s}else t<n&&(e=e.slice(0,t)+"."+e.slice(t));return e}r=function e(t){var r,w,T,v,S,A=F.prototype={constructor:F,toString:null,valueOf:null},O=new F(1),R=20,C=4,I=-7,k=21,N=-1e7,P=1e7,x=!1,D=1,U=0,L={prefix:"",groupSize:3,secondaryGroupSize:0,groupSeparator:",",decimalSeparator:".",fractionGroupSize:0,fractionGroupSeparator:" ",suffix:""},j="0123456789abcdefghijklmnopqrstuvwxyz",M=!0;function F(e,t){var r,s,i,c,d,h,f,p,m=this;if(!(m instanceof F))return new F(e,t);if(null==t){if(e&&!0===e._isBigNumber)return m.s=e.s,void(!e.c||e.e>P?m.c=m.e=null:e.e<N?m.c=[m.e=0]:(m.e=e.e,m.c=e.c.slice()));if((h="number"==typeof e)&&0*e==0){if(m.s=1/e<0?(e=-e,-1):1,e===~~e){for(c=0,d=e;d>=10;d/=10,c++);return void(c>P?m.c=m.e=null:(m.e=c,m.c=[e]))}p=String(e)}else{if(!n.test(p=String(e)))return T(m,p,h);m.s=45==p.charCodeAt(0)?(p=p.slice(1),-1):1}(c=p.indexOf("."))>-1&&(p=p.replace(".","")),(d=p.search(/e/i))>0?(c<0&&(c=d),c+=+p.slice(d+1),p=p.substring(0,d)):c<0&&(c=p.length)}else{if(y(t,2,j.length,"Base"),10==t&&M)return q(m=new F(e),R+m.e+1,C);if(p=String(e),h="number"==typeof e){if(0*e!=0)return T(m,p,h,t);if(m.s=1/e<0?(p=p.slice(1),-1):1,F.DEBUG&&p.replace(/^0\.0*|\./,"").length>15)throw Error(a+e)}else m.s=45===p.charCodeAt(0)?(p=p.slice(1),-1):1;for(r=j.slice(0,t),c=d=0,f=p.length;d<f;d++)if(r.indexOf(s=p.charAt(d))<0){if("."==s){if(d>c){c=f;continue}}else if(!i&&(p==p.toUpperCase()&&(p=p.toLowerCase())||p==p.toLowerCase()&&(p=p.toUpperCase()))){i=!0,d=-1,c=0;continue}return T(m,String(e),h,t)}h=!1,(c=(p=w(p,t,10,m.s)).indexOf("."))>-1?p=p.replace(".",""):c=p.length}for(d=0;48===p.charCodeAt(d);d++);for(f=p.length;48===p.charCodeAt(--f););if(p=p.slice(d,++f)){if(f-=d,h&&F.DEBUG&&f>15&&(e>u||e!==o(e)))throw Error(a+m.s*e);if((c=c-d-1)>P)m.c=m.e=null;else if(c<N)m.c=[m.e=0];else{if(m.e=c,m.c=[],d=(c+1)%l,c<0&&(d+=l),d<f){for(d&&m.c.push(+p.slice(0,d)),f-=l;d<f;)m.c.push(+p.slice(d,d+=l));d=l-(p=p.slice(d)).length}else d-=f;for(;d--;p+="0");m.c.push(+p)}}else m.c=[m.e=0]}function B(e,t,r,n){var s,o,i,a,c;if(null==r?r=C:y(r,0,8),!e.c)return e.toString();if(s=e.c[0],i=e.e,null==t)c=m(e.c),c=1==n||2==n&&(i<=I||i>=k)?E(c,i):b(c,i,"0");else if(o=(e=q(new F(e),t,r)).e,a=(c=m(e.c)).length,1==n||2==n&&(t<=o||o<=I)){for(;a<t;c+="0",a++);c=E(c,o)}else if(t-=i+(2===n&&o>i),c=b(c,o,"0"),o+1>a){if(--t>0)for(c+=".";t--;c+="0");}else if((t+=o-a)>0)for(o+1==a&&(c+=".");t--;c+="0");return e.s<0&&s?"-"+c:c}function G(e,t){for(var r,n,s=1,o=new F(e[0]);s<e.length;s++)(!(n=new F(e[s])).s||(r=_(o,n))===t||0===r&&o.s===t)&&(o=n);return o}function H(e,t,r){for(var n=1,s=t.length;!t[--s];t.pop());for(s=t[0];s>=10;s/=10,n++);return(r=n+r*l-1)>P?e.c=e.e=null:r<N?e.c=[e.e=0]:(e.e=r,e.c=t),e}function q(e,t,r,n){var i,a,u,h,f,p,m,_=e.c,y=d;if(_){e:{for(i=1,h=_[0];h>=10;h/=10,i++);if((a=t-i)<0)a+=l,u=t,f=_[p=0],m=o(f/y[i-u-1]%10);else if((p=s((a+1)/l))>=_.length){if(!n)break e;for(;_.length<=p;_.push(0));f=m=0,i=1,u=(a%=l)-l+1}else{for(f=h=_[p],i=1;h>=10;h/=10,i++);m=(u=(a%=l)-l+i)<0?0:o(f/y[i-u-1]%10)}if(n=n||t<0||null!=_[p+1]||(u<0?f:f%y[i-u-1]),n=r<4?(m||n)&&(0==r||r==(e.s<0?3:2)):m>5||5==m&&(4==r||n||6==r&&(a>0?u>0?f/y[i-u]:0:_[p-1])%10&1||r==(e.s<0?8:7)),t<1||!_[0])return _.length=0,n?(t-=e.e+1,_[0]=y[(l-t%l)%l],e.e=-t||0):_[0]=e.e=0,e;if(0==a?(_.length=p,h=1,p--):(_.length=p+1,h=y[l-a],_[p]=u>0?o(f/y[i-u]%y[u])*h:0),n)for(;;){if(0==p){for(a=1,u=_[0];u>=10;u/=10,a++);for(u=_[0]+=h,h=1;u>=10;u/=10,h++);a!=h&&(e.e++,_[0]==c&&(_[0]=1));break}if(_[p]+=h,_[p]!=c)break;_[p--]=0,h=1}for(a=_.length;0===_[--a];_.pop());}e.e>P?e.c=e.e=null:e.e<N&&(e.c=[e.e=0])}return e}function $(e){var t,r=e.e;return null===r?e.toString():(t=m(e.c),t=r<=I||r>=k?E(t,r):b(t,r,"0"),e.s<0?"-"+t:t)}return F.clone=e,F.ROUND_UP=0,F.ROUND_DOWN=1,F.ROUND_CEIL=2,F.ROUND_FLOOR=3,F.ROUND_HALF_UP=4,F.ROUND_HALF_DOWN=5,F.ROUND_HALF_EVEN=6,F.ROUND_HALF_CEIL=7,F.ROUND_HALF_FLOOR=8,F.EUCLID=9,F.config=F.set=function(e){var t,r;if(null!=e){if("object"!=typeof e)throw Error(i+"Object expected: "+e);if(e.hasOwnProperty(t="DECIMAL_PLACES")&&(y(r=e[t],0,f,t),R=r),e.hasOwnProperty(t="ROUNDING_MODE")&&(y(r=e[t],0,8,t),C=r),e.hasOwnProperty(t="EXPONENTIAL_AT")&&((r=e[t])&&r.pop?(y(r[0],-f,0,t),y(r[1],0,f,t),I=r[0],k=r[1]):(y(r,-f,f,t),I=-(k=r<0?-r:r))),e.hasOwnProperty(t="RANGE"))if((r=e[t])&&r.pop)y(r[0],-f,-1,t),y(r[1],1,f,t),N=r[0],P=r[1];else{if(y(r,-f,f,t),!r)throw Error(i+t+" cannot be zero: "+r);N=-(P=r<0?-r:r)}if(e.hasOwnProperty(t="CRYPTO")){if((r=e[t])!==!!r)throw Error(i+t+" not true or false: "+r);if(r){if("undefined"==typeof crypto||!crypto||!crypto.getRandomValues&&!crypto.randomBytes)throw x=!r,Error(i+"crypto unavailable");x=r}else x=r}if(e.hasOwnProperty(t="MODULO_MODE")&&(y(r=e[t],0,9,t),D=r),e.hasOwnProperty(t="POW_PRECISION")&&(y(r=e[t],0,f,t),U=r),e.hasOwnProperty(t="FORMAT")){if("object"!=typeof(r=e[t]))throw Error(i+t+" not an object: "+r);L=r}if(e.hasOwnProperty(t="ALPHABET")){if("string"!=typeof(r=e[t])||/^.?$|[+\-.\s]|(.).*\1/.test(r))throw Error(i+t+" invalid: "+r);M="0123456789"==r.slice(0,10),j=r}}return{DECIMAL_PLACES:R,ROUNDING_MODE:C,EXPONENTIAL_AT:[I,k],RANGE:[N,P],CRYPTO:x,MODULO_MODE:D,POW_PRECISION:U,FORMAT:L,ALPHABET:j}},F.isBigNumber=function(e){if(!e||!0!==e._isBigNumber)return!1;if(!F.DEBUG)return!0;var t,r,n=e.c,s=e.e,a=e.s;e:if("[object Array]"=={}.toString.call(n)){if((1===a||-1===a)&&s>=-f&&s<=f&&s===o(s)){if(0===n[0]){if(0===s&&1===n.length)return!0;break e}if((t=(s+1)%l)<1&&(t+=l),String(n[0]).length==t){for(t=0;t<n.length;t++)if((r=n[t])<0||r>=c||r!==o(r))break e;if(0!==r)return!0}}}else if(null===n&&null===s&&(null===a||1===a||-1===a))return!0;throw Error(i+"Invalid BigNumber: "+e)},F.maximum=F.max=function(){return G(arguments,-1)},F.minimum=F.min=function(){return G(arguments,1)},F.random=(v=9007199254740992,S=Math.random()*v&2097151?function(){return o(Math.random()*v)}:function(){return 8388608*(1073741824*Math.random()|0)+(8388608*Math.random()|0)},function(e){var t,r,n,a,c,u=0,h=[],p=new F(O);if(null==e?e=R:y(e,0,f),a=s(e/l),x)if(crypto.getRandomValues){for(t=crypto.getRandomValues(new Uint32Array(a*=2));u<a;)(c=131072*t[u]+(t[u+1]>>>11))>=9e15?(r=crypto.getRandomValues(new Uint32Array(2)),t[u]=r[0],t[u+1]=r[1]):(h.push(c%1e14),u+=2);u=a/2}else{if(!crypto.randomBytes)throw x=!1,Error(i+"crypto unavailable");for(t=crypto.randomBytes(a*=7);u<a;)(c=281474976710656*(31&t[u])+1099511627776*t[u+1]+4294967296*t[u+2]+16777216*t[u+3]+(t[u+4]<<16)+(t[u+5]<<8)+t[u+6])>=9e15?crypto.randomBytes(7).copy(t,u):(h.push(c%1e14),u+=7);u=a/7}if(!x)for(;u<a;)(c=S())<9e15&&(h[u++]=c%1e14);for(a=h[--u],e%=l,a&&e&&(c=d[l-e],h[u]=o(a/c)*c);0===h[u];h.pop(),u--);if(u<0)h=[n=0];else{for(n=-1;0===h[0];h.splice(0,1),n-=l);for(u=1,c=h[0];c>=10;c/=10,u++);u<l&&(n-=l-u)}return p.e=n,p.c=h,p}),F.sum=function(){for(var e=1,t=arguments,r=new F(t[0]);e<t.length;)r=r.plus(t[e++]);return r},w=function(){var e="0123456789";function t(e,t,r,n){for(var s,o,i=[0],a=0,c=e.length;a<c;){for(o=i.length;o--;i[o]*=t);for(i[0]+=n.indexOf(e.charAt(a++)),s=0;s<i.length;s++)i[s]>r-1&&(null==i[s+1]&&(i[s+1]=0),i[s+1]+=i[s]/r|0,i[s]%=r)}return i.reverse()}return function(n,s,o,i,a){var c,l,u,d,h,f,p,_,y=n.indexOf("."),g=R,E=C;for(y>=0&&(d=U,U=0,n=n.replace(".",""),f=(_=new F(s)).pow(n.length-y),U=d,_.c=t(b(m(f.c),f.e,"0"),10,o,e),_.e=_.c.length),u=d=(p=t(n,s,o,a?(c=j,e):(c=e,j))).length;0==p[--d];p.pop());if(!p[0])return c.charAt(0);if(y<0?--u:(f.c=p,f.e=u,f.s=i,p=(f=r(f,_,g,E,o)).c,h=f.r,u=f.e),y=p[l=u+g+1],d=o/2,h=h||l<0||null!=p[l+1],h=E<4?(null!=y||h)&&(0==E||E==(f.s<0?3:2)):y>d||y==d&&(4==E||h||6==E&&1&p[l-1]||E==(f.s<0?8:7)),l<1||!p[0])n=h?b(c.charAt(1),-g,c.charAt(0)):c.charAt(0);else{if(p.length=l,h)for(--o;++p[--l]>o;)p[l]=0,l||(++u,p=[1].concat(p));for(d=p.length;!p[--d];);for(y=0,n="";y<=d;n+=c.charAt(p[y++]));n=b(n,u,c.charAt(0))}return n}}(),r=function(){function e(e,t,r){var n,s,o,i,a=0,c=e.length,l=t%h,u=t/h|0;for(e=e.slice();c--;)a=((s=l*(o=e[c]%h)+(n=u*o+(i=e[c]/h|0)*l)%h*h+a)/r|0)+(n/h|0)+u*i,e[c]=s%r;return a&&(e=[a].concat(e)),e}function t(e,t,r,n){var s,o;if(r!=n)o=r>n?1:-1;else for(s=o=0;s<r;s++)if(e[s]!=t[s]){o=e[s]>t[s]?1:-1;break}return o}function r(e,t,r,n){for(var s=0;r--;)e[r]-=s,s=e[r]<t[r]?1:0,e[r]=s*n+e[r]-t[r];for(;!e[0]&&e.length>1;e.splice(0,1));}return function(n,s,i,a,u){var d,h,f,m,_,y,g,E,b,w,T,v,S,A,O,R,C,I=n.s==s.s?1:-1,k=n.c,N=s.c;if(!(k&&k[0]&&N&&N[0]))return new F(n.s&&s.s&&(k?!N||k[0]!=N[0]:N)?k&&0==k[0]||!N?0*I:I/0:NaN);for(b=(E=new F(I)).c=[],I=i+(h=n.e-s.e)+1,u||(u=c,h=p(n.e/l)-p(s.e/l),I=I/l|0),f=0;N[f]==(k[f]||0);f++);if(N[f]>(k[f]||0)&&h--,I<0)b.push(1),m=!0;else{for(A=k.length,R=N.length,f=0,I+=2,(_=o(u/(N[0]+1)))>1&&(N=e(N,_,u),k=e(k,_,u),R=N.length,A=k.length),S=R,T=(w=k.slice(0,R)).length;T<R;w[T++]=0);C=N.slice(),C=[0].concat(C),O=N[0],N[1]>=u/2&&O++;do{if(_=0,(d=t(N,w,R,T))<0){if(v=w[0],R!=T&&(v=v*u+(w[1]||0)),(_=o(v/O))>1)for(_>=u&&(_=u-1),g=(y=e(N,_,u)).length,T=w.length;1==t(y,w,g,T);)_--,r(y,R<g?C:N,g,u),g=y.length,d=1;else 0==_&&(d=_=1),g=(y=N.slice()).length;if(g<T&&(y=[0].concat(y)),r(w,y,T,u),T=w.length,-1==d)for(;t(N,w,R,T)<1;)_++,r(w,R<T?C:N,T,u),T=w.length}else 0===d&&(_++,w=[0]);b[f++]=_,w[0]?w[T++]=k[S]||0:(w=[k[S]],T=1)}while((S++<A||null!=w[0])&&I--);m=null!=w[0],b[0]||b.splice(0,1)}if(u==c){for(f=1,I=b[0];I>=10;I/=10,f++);q(E,i+(E.e=f+h*l-1)+1,a,m)}else E.e=h,E.r=+m;return E}}(),T=function(){var e=/^(-?)0([xbo])(?=\w[\w.]*$)/i,t=/^([^.]+)\.$/,r=/^\.([^.]+)$/,n=/^-?(Infinity|NaN)$/,s=/^\s*\+(?=[\w.])|^\s+|\s+$/g;return function(o,a,c,l){var u,d=c?a:a.replace(s,"");if(n.test(d))o.s=isNaN(d)?null:d<0?-1:1;else{if(!c&&(d=d.replace(e,(function(e,t,r){return u="x"==(r=r.toLowerCase())?16:"b"==r?2:8,l&&l!=u?e:t})),l&&(u=l,d=d.replace(t,"$1").replace(r,"0.$1")),a!=d))return new F(d,u);if(F.DEBUG)throw Error(i+"Not a"+(l?" base "+l:"")+" number: "+a);o.s=null}o.c=o.e=null}}(),A.absoluteValue=A.abs=function(){var e=new F(this);return e.s<0&&(e.s=1),e},A.comparedTo=function(e,t){return _(this,new F(e,t))},A.decimalPlaces=A.dp=function(e,t){var r,n,s,o=this;if(null!=e)return y(e,0,f),null==t?t=C:y(t,0,8),q(new F(o),e+o.e+1,t);if(!(r=o.c))return null;if(n=((s=r.length-1)-p(this.e/l))*l,s=r[s])for(;s%10==0;s/=10,n--);return n<0&&(n=0),n},A.dividedBy=A.div=function(e,t){return r(this,new F(e,t),R,C)},A.dividedToIntegerBy=A.idiv=function(e,t){return r(this,new F(e,t),0,1)},A.exponentiatedBy=A.pow=function(e,t){var r,n,a,c,u,d,h,f,p=this;if((e=new F(e)).c&&!e.isInteger())throw Error(i+"Exponent not an integer: "+$(e));if(null!=t&&(t=new F(t)),u=e.e>14,!p.c||!p.c[0]||1==p.c[0]&&!p.e&&1==p.c.length||!e.c||!e.c[0])return f=new F(Math.pow(+$(p),u?e.s*(2-g(e)):+$(e))),t?f.mod(t):f;if(d=e.s<0,t){if(t.c?!t.c[0]:!t.s)return new F(NaN);(n=!d&&p.isInteger()&&t.isInteger())&&(p=p.mod(t))}else{if(e.e>9&&(p.e>0||p.e<-1||(0==p.e?p.c[0]>1||u&&p.c[1]>=24e7:p.c[0]<8e13||u&&p.c[0]<=9999975e7)))return c=p.s<0&&g(e)?-0:0,p.e>-1&&(c=1/c),new F(d?1/c:c);U&&(c=s(U/l+2))}for(u?(r=new F(.5),d&&(e.s=1),h=g(e)):h=(a=Math.abs(+$(e)))%2,f=new F(O);;){if(h){if(!(f=f.times(p)).c)break;c?f.c.length>c&&(f.c.length=c):n&&(f=f.mod(t))}if(a){if(0===(a=o(a/2)))break;h=a%2}else if(q(e=e.times(r),e.e+1,1),e.e>14)h=g(e);else{if(0===(a=+$(e)))break;h=a%2}p=p.times(p),c?p.c&&p.c.length>c&&(p.c.length=c):n&&(p=p.mod(t))}return n?f:(d&&(f=O.div(f)),t?f.mod(t):c?q(f,U,C,undefined):f)},A.integerValue=function(e){var t=new F(this);return null==e?e=C:y(e,0,8),q(t,t.e+1,e)},A.isEqualTo=A.eq=function(e,t){return 0===_(this,new F(e,t))},A.isFinite=function(){return!!this.c},A.isGreaterThan=A.gt=function(e,t){return _(this,new F(e,t))>0},A.isGreaterThanOrEqualTo=A.gte=function(e,t){return 1===(t=_(this,new F(e,t)))||0===t},A.isInteger=function(){return!!this.c&&p(this.e/l)>this.c.length-2},A.isLessThan=A.lt=function(e,t){return _(this,new F(e,t))<0},A.isLessThanOrEqualTo=A.lte=function(e,t){return-1===(t=_(this,new F(e,t)))||0===t},A.isNaN=function(){return!this.s},A.isNegative=function(){return this.s<0},A.isPositive=function(){return this.s>0},A.isZero=function(){return!!this.c&&0==this.c[0]},A.minus=function(e,t){var r,n,s,o,i=this,a=i.s;if(t=(e=new F(e,t)).s,!a||!t)return new F(NaN);if(a!=t)return e.s=-t,i.plus(e);var u=i.e/l,d=e.e/l,h=i.c,f=e.c;if(!u||!d){if(!h||!f)return h?(e.s=-t,e):new F(f?i:NaN);if(!h[0]||!f[0])return f[0]?(e.s=-t,e):new F(h[0]?i:3==C?-0:0)}if(u=p(u),d=p(d),h=h.slice(),a=u-d){for((o=a<0)?(a=-a,s=h):(d=u,s=f),s.reverse(),t=a;t--;s.push(0));s.reverse()}else for(n=(o=(a=h.length)<(t=f.length))?a:t,a=t=0;t<n;t++)if(h[t]!=f[t]){o=h[t]<f[t];break}if(o&&(s=h,h=f,f=s,e.s=-e.s),(t=(n=f.length)-(r=h.length))>0)for(;t--;h[r++]=0);for(t=c-1;n>a;){if(h[--n]<f[n]){for(r=n;r&&!h[--r];h[r]=t);--h[r],h[n]+=c}h[n]-=f[n]}for(;0==h[0];h.splice(0,1),--d);return h[0]?H(e,h,d):(e.s=3==C?-1:1,e.c=[e.e=0],e)},A.modulo=A.mod=function(e,t){var n,s,o=this;return e=new F(e,t),!o.c||!e.s||e.c&&!e.c[0]?new F(NaN):!e.c||o.c&&!o.c[0]?new F(o):(9==D?(s=e.s,e.s=1,n=r(o,e,0,3),e.s=s,n.s*=s):n=r(o,e,0,D),(e=o.minus(n.times(e))).c[0]||1!=D||(e.s=o.s),e)},A.multipliedBy=A.times=function(e,t){var r,n,s,o,i,a,u,d,f,m,_,y,g,E,b,w=this,T=w.c,v=(e=new F(e,t)).c;if(!(T&&v&&T[0]&&v[0]))return!w.s||!e.s||T&&!T[0]&&!v||v&&!v[0]&&!T?e.c=e.e=e.s=null:(e.s*=w.s,T&&v?(e.c=[0],e.e=0):e.c=e.e=null),e;for(n=p(w.e/l)+p(e.e/l),e.s*=w.s,(u=T.length)<(m=v.length)&&(g=T,T=v,v=g,s=u,u=m,m=s),s=u+m,g=[];s--;g.push(0));for(E=c,b=h,s=m;--s>=0;){for(r=0,_=v[s]%b,y=v[s]/b|0,o=s+(i=u);o>s;)r=((d=_*(d=T[--i]%b)+(a=y*d+(f=T[i]/b|0)*_)%b*b+g[o]+r)/E|0)+(a/b|0)+y*f,g[o--]=d%E;g[o]=r}return r?++n:g.splice(0,1),H(e,g,n)},A.negated=function(){var e=new F(this);return e.s=-e.s||null,e},A.plus=function(e,t){var r,n=this,s=n.s;if(t=(e=new F(e,t)).s,!s||!t)return new F(NaN);if(s!=t)return e.s=-t,n.minus(e);var o=n.e/l,i=e.e/l,a=n.c,u=e.c;if(!o||!i){if(!a||!u)return new F(s/0);if(!a[0]||!u[0])return u[0]?e:new F(a[0]?n:0*s)}if(o=p(o),i=p(i),a=a.slice(),s=o-i){for(s>0?(i=o,r=u):(s=-s,r=a),r.reverse();s--;r.push(0));r.reverse()}for((s=a.length)-(t=u.length)<0&&(r=u,u=a,a=r,t=s),s=0;t;)s=(a[--t]=a[t]+u[t]+s)/c|0,a[t]=c===a[t]?0:a[t]%c;return s&&(a=[s].concat(a),++i),H(e,a,i)},A.precision=A.sd=function(e,t){var r,n,s,o=this;if(null!=e&&e!==!!e)return y(e,1,f),null==t?t=C:y(t,0,8),q(new F(o),e,t);if(!(r=o.c))return null;if(n=(s=r.length-1)*l+1,s=r[s]){for(;s%10==0;s/=10,n--);for(s=r[0];s>=10;s/=10,n++);}return e&&o.e+1>n&&(n=o.e+1),n},A.shiftedBy=function(e){return y(e,-9007199254740991,u),this.times("1e"+e)},A.squareRoot=A.sqrt=function(){var e,t,n,s,o,i=this,a=i.c,c=i.s,l=i.e,u=R+4,d=new F("0.5");if(1!==c||!a||!a[0])return new F(!c||c<0&&(!a||a[0])?NaN:a?i:1/0);if(0==(c=Math.sqrt(+$(i)))||c==1/0?(((t=m(a)).length+l)%2==0&&(t+="0"),c=Math.sqrt(+t),l=p((l+1)/2)-(l<0||l%2),n=new F(t=c==1/0?"5e"+l:(t=c.toExponential()).slice(0,t.indexOf("e")+1)+l)):n=new F(c+""),n.c[0])for((c=(l=n.e)+u)<3&&(c=0);;)if(o=n,n=d.times(o.plus(r(i,o,u,1))),m(o.c).slice(0,c)===(t=m(n.c)).slice(0,c)){if(n.e<l&&--c,"9999"!=(t=t.slice(c-3,c+1))&&(s||"4999"!=t)){+t&&(+t.slice(1)||"5"!=t.charAt(0))||(q(n,n.e+R+2,1),e=!n.times(n).eq(i));break}if(!s&&(q(o,o.e+R+2,0),o.times(o).eq(i))){n=o;break}u+=4,c+=4,s=1}return q(n,n.e+R+1,C,e)},A.toExponential=function(e,t){return null!=e&&(y(e,0,f),e++),B(this,e,t,1)},A.toFixed=function(e,t){return null!=e&&(y(e,0,f),e=e+this.e+1),B(this,e,t)},A.toFormat=function(e,t,r){var n,s=this;if(null==r)null!=e&&t&&"object"==typeof t?(r=t,t=null):e&&"object"==typeof e?(r=e,e=t=null):r=L;else if("object"!=typeof r)throw Error(i+"Argument not an object: "+r);if(n=s.toFixed(e,t),s.c){var o,a=n.split("."),c=+r.groupSize,l=+r.secondaryGroupSize,u=r.groupSeparator||"",d=a[0],h=a[1],f=s.s<0,p=f?d.slice(1):d,m=p.length;if(l&&(o=c,c=l,l=o,m-=o),c>0&&m>0){for(o=m%c||c,d=p.substr(0,o);o<m;o+=c)d+=u+p.substr(o,c);l>0&&(d+=u+p.slice(o)),f&&(d="-"+d)}n=h?d+(r.decimalSeparator||"")+((l=+r.fractionGroupSize)?h.replace(new RegExp("\\d{"+l+"}\\B","g"),"$&"+(r.fractionGroupSeparator||"")):h):d}return(r.prefix||"")+n+(r.suffix||"")},A.toFraction=function(e){var t,n,s,o,a,c,u,h,f,p,_,y,g=this,E=g.c;if(null!=e&&(!(u=new F(e)).isInteger()&&(u.c||1!==u.s)||u.lt(O)))throw Error(i+"Argument "+(u.isInteger()?"out of range: ":"not an integer: ")+$(u));if(!E)return new F(g);for(t=new F(O),f=n=new F(O),s=h=new F(O),y=m(E),a=t.e=y.length-g.e-1,t.c[0]=d[(c=a%l)<0?l+c:c],e=!e||u.comparedTo(t)>0?a>0?t:f:u,c=P,P=1/0,u=new F(y),h.c[0]=0;p=r(u,t,0,1),1!=(o=n.plus(p.times(s))).comparedTo(e);)n=s,s=o,f=h.plus(p.times(o=f)),h=o,t=u.minus(p.times(o=t)),u=o;return o=r(e.minus(n),s,0,1),h=h.plus(o.times(f)),n=n.plus(o.times(s)),h.s=f.s=g.s,_=r(f,s,a*=2,C).minus(g).abs().comparedTo(r(h,n,a,C).minus(g).abs())<1?[f,s]:[h,n],P=c,_},A.toNumber=function(){return+$(this)},A.toPrecision=function(e,t){return null!=e&&y(e,1,f),B(this,e,t,2)},A.toString=function(e){var t,r=this,n=r.s,s=r.e;return null===s?n?(t="Infinity",n<0&&(t="-"+t)):t="NaN":(null==e?t=s<=I||s>=k?E(m(r.c),s):b(m(r.c),s,"0"):10===e&&M?t=b(m((r=q(new F(r),R+s+1,C)).c),r.e,"0"):(y(e,2,j.length,"Base"),t=w(b(m(r.c),s,"0"),10,e,n,!0)),n<0&&r.c[0]&&(t="-"+t)),t},A.valueOf=A.toJSON=function(){return $(this)},A._isBigNumber=!0,null!=t&&F.set(t),F}(),r.default=r.BigNumber=r,"function"==typeof define&&define.amd?define((function(){return r})):void 0!==t&&t.exports?t.exports=r:(e||(e="undefined"!=typeof self&&self?self:window),e.BigNumber=r)}(e)}}),Mt=O({"node_modules/json-bigint/lib/stringify.js"(e,t){var r=jt(),n=t.exports;!function(){var e,t,s,o=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,i={"\b":"\\b","\t":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"};function a(e){return o.lastIndex=0,o.test(e)?'"'+e.replace(o,(function(e){var t=i[e];return"string"==typeof t?t:"\\u"+("0000"+e.charCodeAt(0).toString(16)).slice(-4)}))+'"':'"'+e+'"'}function c(n,o){var i,l,u,d,h,f=e,p=o[n],m=null!=p&&(p instanceof r||r.isBigNumber(p));switch(p&&"object"==typeof p&&"function"==typeof p.toJSON&&(p=p.toJSON(n)),"function"==typeof s&&(p=s.call(o,n,p)),typeof p){case"string":return m?p:a(p);case"number":return isFinite(p)?String(p):"null";case"boolean":case"null":case"bigint":return String(p);case"object":if(!p)return"null";if(e+=t,h=[],"[object Array]"===Object.prototype.toString.apply(p)){for(d=p.length,i=0;i<d;i+=1)h[i]=c(i,p)||"null";return u=0===h.length?"[]":e?"[\n"+e+h.join(",\n"+e)+"\n"+f+"]":"["+h.join(",")+"]",e=f,u}if(s&&"object"==typeof s)for(d=s.length,i=0;i<d;i+=1)"string"==typeof s[i]&&(u=c(l=s[i],p))&&h.push(a(l)+(e?": ":":")+u);else Object.keys(p).forEach((function(t){var r=c(t,p);r&&h.push(a(t)+(e?": ":":")+r)}));return u=0===h.length?"{}":e?"{\n"+e+h.join(",\n"+e)+"\n"+f+"}":"{"+h.join(",")+"}",e=f,u}}"function"!=typeof n.stringify&&(n.stringify=function(r,n,o){var i;if(e="",t="","number"==typeof o)for(i=0;i<o;i+=1)t+=" ";else"string"==typeof o&&(t=o);if(s=n,n&&"function"!=typeof n&&("object"!=typeof n||"number"!=typeof n.length))throw new Error("JSON.stringify");return c("",{"":r})})}()}}),Ft=O({"node_modules/json-bigint/lib/parse.js"(e,t){var r=null,n=/(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])/,s=/(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)/;t.exports=function(e){var t={strict:!1,storeAsString:!1,alwaysParseAsBig:!1,useNativeBigInt:!1,protoAction:"error",constructorAction:"error"};if(null!=e){if(!0===e.strict&&(t.strict=!0),!0===e.storeAsString&&(t.storeAsString=!0),t.alwaysParseAsBig=!0===e.alwaysParseAsBig&&e.alwaysParseAsBig,t.useNativeBigInt=!0===e.useNativeBigInt&&e.useNativeBigInt,void 0!==e.constructorAction){if("error"!==e.constructorAction&&"ignore"!==e.constructorAction&&"preserve"!==e.constructorAction)throw new Error(`Incorrect value for constructorAction option, must be "error", "ignore" or undefined but passed ${e.constructorAction}`);t.constructorAction=e.constructorAction}if(void 0!==e.protoAction){if("error"!==e.protoAction&&"ignore"!==e.protoAction&&"preserve"!==e.protoAction)throw new Error(`Incorrect value for protoAction option, must be "error", "ignore" or undefined but passed ${e.protoAction}`);t.protoAction=e.protoAction}}var o,i,a,c,l={'"':'"',"\\":"\\","/":"/",b:"\b",f:"\f",n:"\n",r:"\r",t:"\t"},u=function(e){throw{name:"SyntaxError",message:e,at:o,text:a}},d=function(e){return e&&e!==i&&u("Expected '"+e+"' instead of '"+i+"'"),i=a.charAt(o),o+=1,i},h=function(){var e,n="";for("-"===i&&(n="-",d("-"));i>="0"&&i<="9";)n+=i,d();if("."===i)for(n+=".";d()&&i>="0"&&i<="9";)n+=i;if("e"===i||"E"===i)for(n+=i,d(),"-"!==i&&"+"!==i||(n+=i,d());i>="0"&&i<="9";)n+=i,d();if(e=+n,isFinite(e))return null==r&&(r=jt()),n.length>15?t.storeAsString?n:t.useNativeBigInt?BigInt(n):new r(n):t.alwaysParseAsBig?t.useNativeBigInt?BigInt(e):new r(e):e;u("Bad number")},f=function(){var e,t,r,n="";if('"'===i)for(var s=o;d();){if('"'===i)return o-1>s&&(n+=a.substring(s,o-1)),d(),n;if("\\"===i){if(o-1>s&&(n+=a.substring(s,o-1)),d(),"u"===i){for(r=0,t=0;t<4&&(e=parseInt(d(),16),isFinite(e));t+=1)r=16*r+e;n+=String.fromCharCode(r)}else{if("string"!=typeof l[i])break;n+=l[i]}s=o}}u("Bad string")},p=function(){for(;i&&i<=" ";)d()};return c=function(){switch(p(),i){case"{":return function(){var e,r=Object.create(null);if("{"===i){if(d("{"),p(),"}"===i)return d("}"),r;for(;i;){if(e=f(),p(),d(":"),!0===t.strict&&Object.hasOwnProperty.call(r,e)&&u('Duplicate key "'+e+'"'),!0===n.test(e)?"error"===t.protoAction?u("Object contains forbidden prototype property"):"ignore"===t.protoAction?c():r[e]=c():!0===s.test(e)?"error"===t.constructorAction?u("Object contains forbidden constructor property"):"ignore"===t.constructorAction?c():r[e]=c():r[e]=c(),p(),"}"===i)return d("}"),r;d(","),p()}}u("Bad object")}();case"[":return function(){var e=[];if("["===i){if(d("["),p(),"]"===i)return d("]"),e;for(;i;){if(e.push(c()),p(),"]"===i)return d("]"),e;d(","),p()}}u("Bad array")}();case'"':return f();case"-":return h();default:return i>="0"&&i<="9"?h():function(){switch(i){case"t":return d("t"),d("r"),d("u"),d("e"),!0;case"f":return d("f"),d("a"),d("l"),d("s"),d("e"),!1;case"n":return d("n"),d("u"),d("l"),d("l"),null}u("Unexpected '"+i+"'")}()}},function(e,t){var r;return a=e+"",o=0,i=" ",r=c(),p(),i&&u("Syntax error"),"function"==typeof t?function e(r,n){var s,o=r[n];return o&&"object"==typeof o&&Object.keys(o).forEach((function(t){void 0!==(s=e(o,t))?o[t]=s:delete o[t]})),t.call(r,n,o)}({"":r},""):r}}}}),Bt=O({"node_modules/json-bigint/index.js"(e,t){var r=Mt().stringify,n=Ft();t.exports=function(e){return{parse:n(e),stringify:r}},t.exports.parse=n(),t.exports.stringify=r}}),Gt=O({"node_modules/gcp-metadata/build/src/gcp-residency.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.GCE_LINUX_BIOS_PATHS=void 0,e.isGoogleCloudServerless=s,e.isGoogleComputeEngineLinux=o,e.isGoogleComputeEngineMACAddress=i,e.isGoogleComputeEngine=a,e.detectGCPResidency=function(){return s()||a()};var t=S("fs"),r=S("os");e.GCE_LINUX_BIOS_PATHS={BIOS_DATE:"/sys/class/dmi/id/bios_date",BIOS_VENDOR:"/sys/class/dmi/id/bios_vendor"};var n=/^42:01/;function s(){return!!(process.env.CLOUD_RUN_JOB||process.env.FUNCTION_NAME||process.env.K_SERVICE)}function o(){if("linux"!==(0,r.platform)())return!1;try{(0,t.statSync)(e.GCE_LINUX_BIOS_PATHS.BIOS_DATE);const r=(0,t.readFileSync)(e.GCE_LINUX_BIOS_PATHS.BIOS_VENDOR,"utf8");return/Google/.test(r)}catch{return!1}}function i(){const e=(0,r.networkInterfaces)();for(const t of Object.values(e))if(t)for(const{mac:e}of t)if(n.test(e))return!0;return!1}function a(){return o()||i()}}}),Ht=O({"node_modules/google-logging-utils/build/src/colours.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.Colours=void 0;var t=class e{static isEnabled(e){return e&&e.isTTY&&("function"!=typeof e.getColorDepth||e.getColorDepth()>2)}static refresh(){e.enabled=e.isEnabled(null===process||void 0===process?void 0:process.stderr),this.enabled?(e.reset="[0m",e.bright="[1m",e.dim="[2m",e.red="[31m",e.green="[32m",e.yellow="[33m",e.blue="[34m",e.magenta="[35m",e.cyan="[36m",e.white="[37m",e.grey="[90m"):(e.reset="",e.bright="",e.dim="",e.red="",e.green="",e.yellow="",e.blue="",e.magenta="",e.cyan="",e.white="",e.grey="")}};e.Colours=t,t.enabled=!1,t.reset="",t.bright="",t.dim="",t.red="",t.green="",t.yellow="",t.blue="",t.magenta="",t.cyan="",t.white="",t.grey="",t.refresh()}}),qt=O({"node_modules/google-logging-utils/build/src/logging-utils.js"(e){var t=e&&e.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var s=Object.getOwnPropertyDescriptor(t,r);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,s)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),r=e&&e.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=e&&e.__importStar||function(){var e=function(t){return(e=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t})(t)};return function(n){if(n&&n.__esModule)return n;var s={};if(null!=n)for(var o=e(n),i=0;i<o.length;i++)"default"!==o[i]&&t(s,n,o[i]);return r(s,n),s}}();Object.defineProperty(e,"__esModule",{value:!0}),e.env=e.DebugLogBackendBase=e.placeholder=e.AdhocDebugLogger=e.LogSeverity=void 0,e.getNodeBackend=f,e.getDebugBackend=function(e){return new p(e)},e.getStructuredBackend=function(e){return new m(e)},e.setBackend=function(e){y=e,_.clear()},e.log=g;var s,o,i=S("events"),a=n(S("process")),c=n(S("util")),l=Ht();(o=s||(e.LogSeverity=s={})).DEFAULT="DEFAULT",o.DEBUG="DEBUG",o.INFO="INFO",o.WARNING="WARNING",o.ERROR="ERROR";var u=class extends i.EventEmitter{constructor(e,t){super(),this.namespace=e,this.upstream=t,this.func=Object.assign(this.invoke.bind(this),{instance:this,on:(e,t)=>this.on(e,t)}),this.func.debug=(...e)=>this.invokeSeverity(s.DEBUG,...e),this.func.info=(...e)=>this.invokeSeverity(s.INFO,...e),this.func.warn=(...e)=>this.invokeSeverity(s.WARNING,...e),this.func.error=(...e)=>this.invokeSeverity(s.ERROR,...e),this.func.sublog=e=>g(e,this.func)}invoke(e,...t){if(this.upstream)try{this.upstream(e,...t)}catch(e){}try{this.emit("log",e,t)}catch(e){}}invokeSeverity(e,...t){this.invoke({severity:e},...t)}};e.AdhocDebugLogger=u,e.placeholder=new u("",(()=>{})).func;var d=class{constructor(){var t;this.cached=new Map,this.filters=[],this.filtersSet=!1;let r=null!==(t=a.env[e.env.nodeEnables])&&void 0!==t?t:"*";"all"===r&&(r="*"),this.filters=r.split(",")}log(e,t,...r){try{this.filtersSet||(this.setFilters(),this.filtersSet=!0);let n=this.cached.get(e);n||(n=this.makeLogger(e),this.cached.set(e,n)),n(t,...r)}catch(e){console.error(e)}}};e.DebugLogBackendBase=d;var h=class extends d{constructor(){super(...arguments),this.enabledRegexp=/.*/g}isEnabled(e){return this.enabledRegexp.test(e)}makeLogger(e){return this.enabledRegexp.test(e)?(t,...r)=>{var n;const o=`${l.Colours.green}${e}${l.Colours.reset}`,i=`${l.Colours.yellow}${a.pid}${l.Colours.reset}`;let u;switch(t.severity){case s.ERROR:u=`${l.Colours.red}${t.severity}${l.Colours.reset}`;break;case s.INFO:u=`${l.Colours.magenta}${t.severity}${l.Colours.reset}`;break;case s.WARNING:u=`${l.Colours.yellow}${t.severity}${l.Colours.reset}`;break;default:u=null!==(n=t.severity)&&void 0!==n?n:s.DEFAULT}const d=c.formatWithOptions({colors:l.Colours.enabled},...r),h=Object.assign({},t);delete h.severity;const f=Object.getOwnPropertyNames(h).length?JSON.stringify(h):"",p=f?`${l.Colours.grey}${f}${l.Colours.reset}`:"";console.error("%s [%s|%s] %s%s",i,o,u,d,f?` ${p}`:"")}:()=>{}}setFilters(){const e=this.filters.join(",").replace(/[|\\{}()[\]^$+?.]/g,"\\$&").replace(/\*/g,".*").replace(/,/g,"$|^");this.enabledRegexp=new RegExp(`^${e}$`,"i")}};function f(){return new h}var p=class extends d{constructor(e){super(),this.debugPkg=e}makeLogger(e){const t=this.debugPkg(e);return(e,...r)=>{t(r[0],...r.slice(1))}}setFilters(){var e;const t=null!==(e=a.env.NODE_DEBUG)&&void 0!==e?e:"";a.env.NODE_DEBUG=`${t}${t?",":""}${this.filters.join(",")}`}};var m=class extends d{constructor(e){var t;super(),this.upstream=null!==(t=e)&&void 0!==t?t:void 0}makeLogger(e){var t;const r=null===(t=this.upstream)||void 0===t?void 0:t.makeLogger(e);return(e,...t)=>{var n;const o=null!==(n=e.severity)&&void 0!==n?n:s.INFO,i=Object.assign({severity:o,message:c.format(...t)},e),a=JSON.stringify(i);r?r(e,a):console.log("%s",a)}}setFilters(){var e;null===(e=this.upstream)||void 0===e||e.setFilters()}};e.env={nodeEnables:"GOOGLE_SDK_NODE_LOGGING"};var _=new Map,y=void 0;function g(t,r){if(!y){if(!a.env[e.env.nodeEnables])return e.placeholder}if(!t)return e.placeholder;r&&(t=`${r.instance.namespace}:${t}`);const n=_.get(t);if(n)return n.func;if(null===y)return e.placeholder;void 0===y&&(y=f());const s=(()=>{let e;return new u(t,((r,...n)=>{if(e!==y){if(null===y)return;void 0===y&&(y=f()),e=y}null==y||y.log(t,r,...n)}))})();return _.set(t,s),s.func}}}),$t=O({"node_modules/google-logging-utils/build/src/index.js"(e){var t=e&&e.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var s=Object.getOwnPropertyDescriptor(t,r);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,s)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),r=e&&e.__exportStar||function(e,r){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(r,n)||t(r,e,n)};Object.defineProperty(e,"__esModule",{value:!0}),r(qt(),e)}}),Wt=O({"node_modules/gcp-metadata/build/src/index.js"(e){var t=e&&e.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var s=Object.getOwnPropertyDescriptor(t,r);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,s)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),r=e&&e.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=e&&e.__importStar||function(){var e=function(t){return(e=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t})(t)};return function(n){if(n&&n.__esModule)return n;var s={};if(null!=n)for(var o=e(n),i=0;i<o.length;i++)"default"!==o[i]&&t(s,n,o[i]);return r(s,n),s}}(),s=e&&e.__exportStar||function(e,r){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(r,n)||t(r,e,n)};Object.defineProperty(e,"__esModule",{value:!0}),e.gcpResidencyCache=e.METADATA_SERVER_DETECTION=e.HEADERS=e.HEADER_VALUE=e.HEADER_NAME=e.SECONDARY_HOST_ADDRESS=e.HOST_ADDRESS=e.BASE_PATH=void 0,e.instance=function(e){return h("instance",e)},e.project=function(e){return h("project",e)},e.universe=function(e){return h("universe",e)},e.bulk=async function(e){const t={};return await Promise.all(e.map((e=>(async()=>{const r=await h(e),n=e.metadataKey;t[n]=r})()))),t},e.isAvailable=async function(){if(process.env.METADATA_SERVER_DETECTION){const t=process.env.METADATA_SERVER_DETECTION.trim().toLocaleLowerCase();if(!(t in e.METADATA_SERVER_DETECTION))throw new RangeError(`Unknown \`METADATA_SERVER_DETECTION\` env variable. Got \`${t}\`, but it should be \`${Object.keys(e.METADATA_SERVER_DETECTION).join("`, `")}\`, or unset`);switch(t){case"assume-present":return!0;case"none":return!1;case"bios-only":return p()}}try{return void 0===l&&(l=h("instance",void 0,process.env.DETECT_GCP_RETRIES?Number(process.env.DETECT_GCP_RETRIES):0,!(process.env.GCE_METADATA_IP||process.env.GCE_METADATA_HOST))),await l,!0}catch(e){const t=e;if(process.env.DEBUG_AUTH&&console.info(t),"request-timeout"===t.type)return!1;if(t.response&&404===t.response.status)return!1;if(!(t.response&&404===t.response.status||t.code&&["EHOSTDOWN","EHOSTUNREACH","ENETUNREACH","ENOENT","ENOTFOUND","ECONNREFUSED"].includes(t.code.toString()))){let e="UNKNOWN";t.code&&(e=t.code.toString()),process.emitWarning(`received unexpected error = ${t.message} code = ${e}`,"MetadataLookupWarning")}return!1}},e.resetIsAvailableCache=function(){l=void 0},e.getGCPResidency=p,e.setGCPResidency=m,e.requestTimeout=_;var o=Lt(),i=Bt(),a=Gt(),c=n($t());e.BASE_PATH="/computeMetadata/v1",e.HOST_ADDRESS="http://169.254.169.254",e.SECONDARY_HOST_ADDRESS="http://metadata.google.internal.",e.HEADER_NAME="Metadata-Flavor",e.HEADER_VALUE="Google",e.HEADERS=Object.freeze({[e.HEADER_NAME]:e.HEADER_VALUE});var l,u=c.log("gcp-metadata");function d(t){return t||(t=process.env.GCE_METADATA_IP||process.env.GCE_METADATA_HOST||e.HOST_ADDRESS),/^https?:\/\//.test(t)||(t=`http://${t}`),new URL(e.BASE_PATH,t).href}async function h(t,r={},n=3,s=!1){const a=new Headers(e.HEADERS);let c="",l={};if("object"==typeof t){const e=t;new Headers(e.headers).forEach(((e,t)=>a.set(t,e))),c=e.metadataKey,l=e.params||l,n=e.noResponseRetries||n,s=e.fastFail||s}else c=t;"string"==typeof r?c+=`/${r}`:(!function(e){Object.keys(e).forEach((e=>{switch(e){case"params":case"property":case"headers":break;case"qs":throw new Error("'qs' is not a valid configuration option. Please use 'params' instead.");default:throw new Error(`'${e}' is not a valid configuration option.`)}}))}(r),r.property&&(c+=`/${r.property}`),new Headers(r.headers).forEach(((e,t)=>a.set(t,e))),l=r.params||l);const h=s?f:o.request,p={url:`${d()}/${c}`,headers:a,retryConfig:{noResponseRetries:n},params:l,responseType:"text",timeout:_()};u.info("instance request %j",p);const m=await h(p);u.info("instance metadata is %s",m.data);const y=m.headers.get(e.HEADER_NAME);if(y!==e.HEADER_VALUE)throw new RangeError(`Invalid response from metadata service: incorrect ${e.HEADER_NAME} header. Expected '${e.HEADER_VALUE}', got ${y?`'${y}'`:"no header"}`);if("string"==typeof m.data)try{return i.parse(m.data)}catch{}return m.data}async function f(t){const r={...t,url:t.url?.toString().replace(d(),d(e.SECONDARY_HOST_ADDRESS))},n=(0,o.request)(t),s=(0,o.request)(r);return Promise.any([n,s])}function p(){return null===e.gcpResidencyCache&&m(),e.gcpResidencyCache}function m(t=null){e.gcpResidencyCache=null!==t?t:(0,a.detectGCPResidency)()}function _(){return p()?0:3e3}e.METADATA_SERVER_DETECTION=Object.freeze({"assume-present":"don't try to ping the metadata server, but assume it's present",none:"don't try to ping the metadata server, but don't try to use it either","bios-only":"treat the result of a BIOS probe as canonical (don't fall back to pinging)","ping-only":"skip the BIOS probe, and go straight to pinging"}),e.gcpResidencyCache=null,s(Gt(),e)}}),Vt=O({"node_modules/base64-js/index.js"(e){e.byteLength=function(e){var t=i(e),r=t[0],n=t[1];return 3*(r+n)/4-n},e.toByteArray=function(e){var t,r,o=i(e),a=o[0],c=o[1],l=new s(function(e,t,r){return 3*(t+r)/4-r}(0,a,c)),u=0,d=c>0?a-4:a;for(r=0;r<d;r+=4)t=n[e.charCodeAt(r)]<<18|n[e.charCodeAt(r+1)]<<12|n[e.charCodeAt(r+2)]<<6|n[e.charCodeAt(r+3)],l[u++]=t>>16&255,l[u++]=t>>8&255,l[u++]=255&t;2===c&&(t=n[e.charCodeAt(r)]<<2|n[e.charCodeAt(r+1)]>>4,l[u++]=255&t);1===c&&(t=n[e.charCodeAt(r)]<<10|n[e.charCodeAt(r+1)]<<4|n[e.charCodeAt(r+2)]>>2,l[u++]=t>>8&255,l[u++]=255&t);return l},e.fromByteArray=function(e){for(var t,n=e.length,s=n%3,o=[],i=16383,c=0,l=n-s;c<l;c+=i)o.push(a(e,c,c+i>l?l:c+i));1===s?(t=e[n-1],o.push(r[t>>2]+r[t<<4&63]+"==")):2===s&&(t=(e[n-2]<<8)+e[n-1],o.push(r[t>>10]+r[t>>4&63]+r[t<<2&63]+"="));return o.join("")};var t,r=[],n=[],s="undefined"!=typeof Uint8Array?Uint8Array:Array,o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(t=0,64;t<64;++t)r[t]=o[t],n[o.charCodeAt(t)]=t;function i(e){var t=e.length;if(t%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var r=e.indexOf("=");return-1===r&&(r=t),[r,r===t?0:4-r%4]}function a(e,t,n){for(var s,o,i=[],a=t;a<n;a+=3)s=(e[a]<<16&16711680)+(e[a+1]<<8&65280)+(255&e[a+2]),i.push(r[(o=s)>>18&63]+r[o>>12&63]+r[o>>6&63]+r[63&o]);return i.join("")}n["-".charCodeAt(0)]=62,n["_".charCodeAt(0)]=63}}),Yt=O({"node_modules/google-auth-library/build/src/crypto/shared.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.fromArrayBufferToHex=function(e){return Array.from(new Uint8Array(e)).map((e=>e.toString(16).padStart(2,"0"))).join("")}}}),zt=O({"node_modules/google-auth-library/build/src/crypto/browser/crypto.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.BrowserCrypto=void 0;var t=Vt(),r=Yt();e.BrowserCrypto=class e{constructor(){if("undefined"==typeof window||void 0===window.crypto||void 0===window.crypto.subtle)throw new Error("SubtleCrypto not found. Make sure it's an https:// website.")}async sha256DigestBase64(e){const r=(new TextEncoder).encode(e),n=await window.crypto.subtle.digest("SHA-256",r);return t.fromByteArray(new Uint8Array(n))}randomBytesBase64(e){const r=new Uint8Array(e);return window.crypto.getRandomValues(r),t.fromByteArray(r)}static padBase64(e){for(;e.length%4!=0;)e+="=";return e}async verify(r,n,s){const o={name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},i=(new TextEncoder).encode(n),a=t.toByteArray(e.padBase64(s)),c=await window.crypto.subtle.importKey("jwk",r,o,!0,["verify"]);return await window.crypto.subtle.verify(o,c,Buffer.from(a),i)}async sign(e,r){const n={name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},s=(new TextEncoder).encode(r),o=await window.crypto.subtle.importKey("jwk",e,n,!0,["sign"]),i=await window.crypto.subtle.sign(n,o,s);return t.fromByteArray(new Uint8Array(i))}decodeBase64StringUtf8(r){const n=t.toByteArray(e.padBase64(r));return(new TextDecoder).decode(n)}encodeBase64StringUtf8(e){const r=(new TextEncoder).encode(e);return t.fromByteArray(r)}async sha256DigestHex(e){const t=(new TextEncoder).encode(e),n=await window.crypto.subtle.digest("SHA-256",t);return(0,r.fromArrayBufferToHex)(n)}async signWithHmacSha256(e,t){const r="string"==typeof e?e:String.fromCharCode(...new Uint16Array(e)),n=new TextEncoder,s=await window.crypto.subtle.importKey("raw",n.encode(r),{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return window.crypto.subtle.sign("HMAC",s,n.encode(t))}}}}),Jt=O({"node_modules/google-auth-library/build/src/crypto/node/crypto.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.NodeCrypto=void 0;var t=S("crypto");e.NodeCrypto=class{async sha256DigestBase64(e){return t.createHash("sha256").update(e).digest("base64")}randomBytesBase64(e){return t.randomBytes(e).toString("base64")}async verify(e,r,n){const s=t.createVerify("RSA-SHA256");return s.update(r),s.end(),s.verify(e,n,"base64")}async sign(e,r){const n=t.createSign("RSA-SHA256");return n.update(r),n.end(),n.sign(e,"base64")}decodeBase64StringUtf8(e){return Buffer.from(e,"base64").toString("utf-8")}encodeBase64StringUtf8(e){return Buffer.from(e,"utf-8").toString("base64")}async sha256DigestHex(e){return t.createHash("sha256").update(e).digest("hex")}async signWithHmacSha256(e,r){const n="string"==typeof e?e:(s=e,Buffer.from(s));var s;return function(e){const t=new ArrayBuffer(e.length),r=new Uint8Array(t);for(let t=0;t<e.length;++t)r[t]=e[t];return t}(t.createHmac("sha256",n).update(r).digest())}}}}),Kt=O({"node_modules/google-auth-library/build/src/crypto/crypto.js"(e){var t=e&&e.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var s=Object.getOwnPropertyDescriptor(t,r);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,s)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),r=e&&e.__exportStar||function(e,r){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(r,n)||t(r,e,n)};Object.defineProperty(e,"__esModule",{value:!0}),e.createCrypto=function(){if(o())return new n.BrowserCrypto;return new s.NodeCrypto},e.hasBrowserCrypto=o;var n=zt(),s=Jt();function o(){return"undefined"!=typeof window&&void 0!==window.crypto&&void 0!==window.crypto.subtle}r(Yt(),e)}}),Xt=O({"node_modules/safe-buffer/index.js"(e,t){var r=S("buffer"),n=r.Buffer;function s(e,t){for(var r in e)t[r]=e[r]}function o(e,t,r){return n(e,t,r)}n.from&&n.alloc&&n.allocUnsafe&&n.allocUnsafeSlow?t.exports=r:(s(r,e),e.Buffer=o),s(n,o),o.from=function(e,t,r){if("number"==typeof e)throw new TypeError("Argument must not be a number");return n(e,t,r)},o.alloc=function(e,t,r){if("number"!=typeof e)throw new TypeError("Argument must be a number");var s=n(e);return void 0!==t?"string"==typeof r?s.fill(t,r):s.fill(t):s.fill(0),s},o.allocUnsafe=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return n(e)},o.allocUnsafeSlow=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return r.SlowBuffer(e)}}}),Zt=O({"node_modules/ecdsa-sig-formatter/src/param-bytes-for-alg.js"(e,t){function r(e){return(e/8|0)+(e%8==0?0:1)}var n={ES256:r(256),ES384:r(384),ES512:r(521)};t.exports=function(e){var t=n[e];if(t)return t;throw new Error('Unknown algorithm "'+e+'"')}}}),Qt=O({"node_modules/ecdsa-sig-formatter/src/ecdsa-sig-formatter.js"(e,t){var r=Xt().Buffer,n=Zt(),s=128;function o(e){if(r.isBuffer(e))return e;if("string"==typeof e)return r.from(e,"base64");throw new TypeError("ECDSA signature must be a Base64 string or a Buffer")}function i(e,t,r){for(var n=0;t+n<r&&0===e[t+n];)++n;return e[t+n]>=s&&--n,n}t.exports={derToJose:function(e,t){e=o(e);var s=n(t),i=s+1,a=e.length,c=0;if(48!==e[c++])throw new Error('Could not find expected "seq"');var l=e[c++];if(129===l&&(l=e[c++]),a-c<l)throw new Error('"seq" specified length of "'+l+'", only "'+(a-c)+'" remaining');if(2!==e[c++])throw new Error('Could not find expected "int" for "r"');var u=e[c++];if(a-c-2<u)throw new Error('"r" specified length of "'+u+'", only "'+(a-c-2)+'" available');if(i<u)throw new Error('"r" specified length of "'+u+'", max of "'+i+'" is acceptable');var d=c;if(c+=u,2!==e[c++])throw new Error('Could not find expected "int" for "s"');var h=e[c++];if(a-c!==h)throw new Error('"s" specified length of "'+h+'", expected "'+(a-c)+'"');if(i<h)throw new Error('"s" specified length of "'+h+'", max of "'+i+'" is acceptable');var f=c;if((c+=h)!==a)throw new Error('Expected to consume entire buffer, but "'+(a-c)+'" bytes remain');var p=s-u,m=s-h,_=r.allocUnsafe(p+u+m+h);for(c=0;c<p;++c)_[c]=0;e.copy(_,c,d+Math.max(-p,0),d+u);for(var y=c=s;c<y+m;++c)_[c]=0;return e.copy(_,c,f+Math.max(-m,0),f+h),_=(_=_.toString("base64")).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")},joseToDer:function(e,t){e=o(e);var a=n(t),c=e.length;if(c!==2*a)throw new TypeError('"'+t+'" signatures must be "'+2*a+'" bytes, saw "'+c+'"');var l=i(e,0,a),u=i(e,a,e.length),d=a-l,h=a-u,f=2+d+1+1+h,p=f<s,m=r.allocUnsafe((p?2:3)+f),_=0;return m[_++]=48,p?m[_++]=f:(m[_++]=129,m[_++]=255&f),m[_++]=2,m[_++]=d,l<0?(m[_++]=0,_+=e.copy(m,_,0,a)):_+=e.copy(m,_,l,a),m[_++]=2,m[_++]=h,u<0?(m[_++]=0,e.copy(m,_,a)):e.copy(m,_,a+u),m}}}}),er=O({"node_modules/google-auth-library/build/src/util.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.LRUCache=void 0,e.snakeToCamel=o,e.originalOrCamelOptions=function(e){return{get:function(t){const r=e||{};return r[t]??r[o(t)]}}},e.removeUndefinedValuesInObject=function(e){return Object.entries(e).forEach((([t,r])=>{void 0!==r&&"undefined"!==r||delete e[t]})),e},e.isValidFile=async function(e){try{return(await t.promises.lstat(e)).isFile()}catch(e){return!1}},e.getWellKnownCertificateConfigFileLocation=function(){const e=process.env.CLOUDSDK_CONFIG||(r.platform().startsWith("win")?n.join(process.env.APPDATA||"",s):n.join(process.env.HOME||"",".config",s));return n.join(e,"certificate_config.json")};var t=S("fs"),r=S("os"),n=S("path"),s="gcloud";function o(e){return e.replace(/([_][^_])/g,(e=>e.slice(1).toUpperCase()))}e.LRUCache=class{capacity;#g=new Map;maxAge;constructor(e){this.capacity=e.capacity,this.maxAge=e.maxAge}#E(e,t){this.#g.delete(e),this.#g.set(e,{value:t,lastAccessed:Date.now()})}set(e,t){this.#E(e,t),this.#b()}get(e){const t=this.#g.get(e);if(t)return this.#E(e,t.value),this.#b(),t.value}#b(){const e=this.maxAge?Date.now()-this.maxAge:0;let t=this.#g.entries().next();for(;!t.done&&(this.#g.size>this.capacity||t.value[1].lastAccessed<e);)this.#g.delete(t.value[0]),t=this.#g.entries().next()}}}}),tr=O({"node_modules/google-auth-library/package.json"(e,t){t.exports={name:"google-auth-library",version:"10.6.2",author:"Google Inc.",description:"Google APIs Authentication Client Library for Node.js",engines:{node:">=18"},main:"./build/src/index.js",types:"./build/src/index.d.ts",repository:{type:"git",directory:"packages/google-auth-library-nodejs",url:"https://github.com/googleapis/google-cloud-node-core.git"},keywords:["google","api","google apis","client","client library"],dependencies:{"base64-js":"^1.3.0","ecdsa-sig-formatter":"^1.0.11",gaxios:"^7.1.4","gcp-metadata":"8.1.2","google-logging-utils":"1.1.3",jws:"^4.0.0"},devDependencies:{"@types/base64-js":"^1.2.5","@types/jws":"^3.1.0","@types/mocha":"^10.0.10","@types/mv":"^2.1.0","@types/ncp":"^2.0.8","@types/node":"^24.0.0","@types/sinon":"^21.0.0","assert-rejects":"^1.0.0",c8:"^10.1.3",codecov:"^3.8.3",gts:"^6.0.2","is-docker":"^3.0.0",jsdoc:"^4.0.4","jsdoc-fresh":"^5.0.0","jsdoc-region-tag":"^4.0.0",karma:"^6.0.0","karma-chrome-launcher":"^3.0.0","karma-coverage":"^2.0.0","karma-firefox-launcher":"^2.0.0","karma-mocha":"^2.0.0","karma-sourcemap-loader":"^0.4.0","karma-webpack":"^5.0.1",keypair:"^1.0.4",mocha:"^11.1.0",mv:"^2.1.1",ncp:"^2.0.0",nock:"^14.0.5","null-loader":"^4.0.1",puppeteer:"^24.0.0",sinon:"^21.0.0","ts-loader":"^9.5.2",typescript:"5.8.3",webpack:"^5.97.1","webpack-cli":"^6.0.1"},files:["build/src","!build/src/**/*.map"],scripts:{test:"c8 mocha build/test",clean:"gts clean",prepare:"npm run compile",lint:"gts check --no-inline-config",compile:"tsc -p .",fix:"gts fix",pretest:"npm run compile -- --sourceMap",docs:"jsdoc -c .jsdoc.js","samples-setup":"cd samples/ && npm link ../ && npm run setup && cd ../","samples-test":"cd samples/ && npm link ../ && npm test && cd ../","system-test":"mocha build/system-test --timeout 60000","presystem-test":"npm run compile -- --sourceMap",webpack:"webpack","browser-test":"karma start","docs-test":"echo 'disabled until linkinator is fixed'","predocs-test":"npm run docs",prelint:"cd samples; npm link ../; npm install"},license:"Apache-2.0",homepage:"https://github.com/googleapis/google-cloud-node-core/tree/main/packages/google-auth-library-nodejs"}}}),rr=O({"node_modules/google-auth-library/build/src/shared.cjs"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.USER_AGENT=e.PRODUCT_NAME=e.pkg=void 0;var t=tr();e.pkg=t;var r="google-api-nodejs-client";e.PRODUCT_NAME=r;var n=`${r}/${t.version}`;e.USER_AGENT=n}}),nr=O({"node_modules/google-auth-library/build/src/auth/authclient.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.AuthClient=e.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS=e.DEFAULT_UNIVERSE=void 0;var t=S("events"),r=Lt(),n=er(),s=$t(),o=rr();e.DEFAULT_UNIVERSE="googleapis.com",e.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS=3e5;var i=class i extends t.EventEmitter{apiKey;projectId;quotaProjectId;transporter;credentials={};eagerRefreshThresholdMillis=e.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS;forceRefreshOnFailure=!1;universeDomain=e.DEFAULT_UNIVERSE;static RequestMethodNameSymbol=Symbol("request method name");static RequestLogIdSymbol=Symbol("request log id");constructor(t={}){super();const s=(0,n.originalOrCamelOptions)(t);this.apiKey=t.apiKey,this.projectId=s.get("project_id")??null,this.quotaProjectId=s.get("quota_project_id"),this.credentials=s.get("credentials")??{},this.universeDomain=s.get("universe_domain")??e.DEFAULT_UNIVERSE,this.transporter=t.transporter??new r.Gaxios(t.transporterOptions),!1!==s.get("useAuthRequestParameters")&&(this.transporter.interceptors.request.add(i.DEFAULT_REQUEST_INTERCEPTOR),this.transporter.interceptors.response.add(i.DEFAULT_RESPONSE_INTERCEPTOR)),t.eagerRefreshThresholdMillis&&(this.eagerRefreshThresholdMillis=t.eagerRefreshThresholdMillis),this.forceRefreshOnFailure=t.forceRefreshOnFailure??!1}fetch(...e){const t=e[0],n=e[1];let s;const o=new Headers;return"string"==typeof t?s=new URL(t):t instanceof URL?s=t:t&&t.url&&(s=new URL(t.url)),t&&"object"==typeof t&&"headers"in t&&r.Gaxios.mergeHeaders(o,t.headers),n&&r.Gaxios.mergeHeaders(o,new Headers(n.headers)),"object"!=typeof t||t instanceof URL?this.request({...n,headers:o,url:s}):this.request({...n,...t,headers:o,url:s})}setCredentials(e){this.credentials=e}addSharedMetadataHeaders(e){return!e.has("x-goog-user-project")&&this.quotaProjectId&&e.set("x-goog-user-project",this.quotaProjectId),e}addUserProjectAndAuthHeaders(e,t){const r=t.get("x-goog-user-project"),n=t.get("authorization");return r&&e.set("x-goog-user-project",r),n&&e.set("authorization",n),e}static log=(0,s.log)("auth");static DEFAULT_REQUEST_INTERCEPTOR={resolved:async e=>{if(!e.headers.has("x-goog-api-client")){const t=process.version.replace(/^v/,"");e.headers.set("x-goog-api-client",`gl-node/${t}`)}const t=e.headers.get("User-Agent");t?t.includes(`${o.PRODUCT_NAME}/`)||e.headers.set("User-Agent",`${t} ${o.USER_AGENT}`):e.headers.set("User-Agent",o.USER_AGENT);try{const t=e,r=t[i.RequestMethodNameSymbol],n=`${Math.floor(1e3*Math.random())}`;t[i.RequestLogIdSymbol]=n;const s={url:e.url,headers:e.headers};r?i.log.info("%s [%s] request %j",r,n,s):i.log.info("[%s] request %j",n,s)}catch(e){}return e}};static DEFAULT_RESPONSE_INTERCEPTOR={resolved:async e=>{try{const t=e.config,r=t[i.RequestMethodNameSymbol],n=t[i.RequestLogIdSymbol];r?i.log.info("%s [%s] response %j",r,n,e.data):i.log.info("[%s] response %j",n,e.data)}catch(e){}return e},rejected:async e=>{try{const t=e.config,r=t[i.RequestMethodNameSymbol],n=t[i.RequestLogIdSymbol];r?i.log.info("%s [%s] error %j",r,n,e.response?.data):i.log.error("[%s] error %j",n,e.response?.data)}catch(e){}throw e}};static setMethodName(e,t){try{e[i.RequestMethodNameSymbol]=t}catch(e){}}static get RETRY_CONFIG(){return{retry:!0,retryConfig:{httpMethodsToRetry:["GET","PUT","POST","HEAD","OPTIONS","DELETE"]}}}};e.AuthClient=i}}),sr=O({"node_modules/google-auth-library/build/src/auth/loginticket.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.LoginTicket=void 0;e.LoginTicket=class{envelope;payload;constructor(e,t){this.envelope=e,this.payload=t}getEnvelope(){return this.envelope}getPayload(){return this.payload}getUserId(){const e=this.getPayload();return e&&e.sub?e.sub:null}getAttributes(){return{envelope:this.getEnvelope(),payload:this.getPayload()}}}}}),or=O({"node_modules/google-auth-library/build/src/auth/oauth2client.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.OAuth2Client=e.ClientAuthentication=e.CertificateFormat=e.CodeChallengeMethod=void 0;var t,r,n,s,o,i,a=Lt(),c=S("querystring"),l=S("stream"),u=Qt(),d=er(),h=Kt(),f=nr(),p=sr();(r=t||(e.CodeChallengeMethod=t={})).Plain="plain",r.S256="S256",(s=n||(e.CertificateFormat=n={})).PEM="PEM",s.JWK="JWK",(i=o||(e.ClientAuthentication=o={})).ClientSecretPost="ClientSecretPost",i.ClientSecretBasic="ClientSecretBasic",i.None="None";var m=class e extends f.AuthClient{redirectUri;certificateCache={};certificateExpiry=null;certificateCacheFormat=n.PEM;refreshTokenPromises=new Map;endpoints;issuers;clientAuthentication;_clientId;_clientSecret;refreshHandler;constructor(e={},t,r){super("object"==typeof e?e:{}),"object"!=typeof e&&(e={clientId:e,clientSecret:t,redirectUri:r}),this._clientId=e.clientId||e.client_id,this._clientSecret=e.clientSecret||e.client_secret,this.redirectUri=e.redirectUri||e.redirect_uris?.[0],this.endpoints={tokenInfoUrl:"https://oauth2.googleapis.com/tokeninfo",oauth2AuthBaseUrl:"https://accounts.google.com/o/oauth2/v2/auth",oauth2TokenUrl:"https://oauth2.googleapis.com/token",oauth2RevokeUrl:"https://oauth2.googleapis.com/revoke",oauth2FederatedSignonPemCertsUrl:"https://www.googleapis.com/oauth2/v1/certs",oauth2FederatedSignonJwkCertsUrl:"https://www.googleapis.com/oauth2/v3/certs",oauth2IapPublicKeyUrl:"https://www.gstatic.com/iap/verify/public_key",...e.endpoints},this.clientAuthentication=e.clientAuthentication||o.ClientSecretPost,this.issuers=e.issuers||["accounts.google.com","https://accounts.google.com",this.universeDomain]}static GOOGLE_TOKEN_INFO_URL="https://oauth2.googleapis.com/tokeninfo";static CLOCK_SKEW_SECS_=300;static DEFAULT_MAX_TOKEN_LIFETIME_SECS_=86400;generateAuthUrl(e={}){if(e.code_challenge_method&&!e.code_challenge)throw new Error("If a code_challenge_method is provided, code_challenge must be included.");e.response_type=e.response_type||"code",e.client_id=e.client_id||this._clientId,e.redirect_uri=e.redirect_uri||this.redirectUri,Array.isArray(e.scope)&&(e.scope=e.scope.join(" "));return this.endpoints.oauth2AuthBaseUrl.toString()+"?"+c.stringify(e)}generateCodeVerifier(){throw new Error("generateCodeVerifier is removed, please use generateCodeVerifierAsync instead.")}async generateCodeVerifierAsync(){const e=(0,h.createCrypto)(),t=e.randomBytesBase64(96).replace(/\+/g,"~").replace(/=/g,"_").replace(/\//g,"-");return{codeVerifier:t,codeChallenge:(await e.sha256DigestBase64(t)).split("=")[0].replace(/\+/g,"-").replace(/\//g,"_")}}getToken(e,t){const r="string"==typeof e?{code:e}:e;if(!t)return this.getTokenAsync(r);this.getTokenAsync(r).then((e=>t(null,e.tokens,e.res)),(e=>t(e,null,e.response)))}async getTokenAsync(t){const r=this.endpoints.oauth2TokenUrl.toString(),n=new Headers,s={client_id:t.client_id||this._clientId,code_verifier:t.codeVerifier,code:t.code,grant_type:"authorization_code",redirect_uri:t.redirect_uri||this.redirectUri};if(this.clientAuthentication===o.ClientSecretBasic){const e=Buffer.from(`${this._clientId}:${this._clientSecret}`);n.set("authorization",`Basic ${e.toString("base64")}`)}this.clientAuthentication===o.ClientSecretPost&&(s.client_secret=this._clientSecret);const i={...e.RETRY_CONFIG,method:"POST",url:r,data:new URLSearchParams((0,d.removeUndefinedValuesInObject)(s)),headers:n};f.AuthClient.setMethodName(i,"getTokenAsync");const a=await this.transporter.request(i),c=a.data;return a.data&&a.data.expires_in&&(c.expiry_date=(new Date).getTime()+1e3*a.data.expires_in,delete c.expires_in),this.emit("tokens",c),{tokens:c,res:a}}async refreshToken(e){if(!e)return this.refreshTokenNoCache(e);if(this.refreshTokenPromises.has(e))return this.refreshTokenPromises.get(e);const t=this.refreshTokenNoCache(e).then((t=>(this.refreshTokenPromises.delete(e),t)),(t=>{throw this.refreshTokenPromises.delete(e),t}));return this.refreshTokenPromises.set(e,t),t}async refreshTokenNoCache(t){if(!t)throw new Error("No refresh token is set.");const r=this.endpoints.oauth2TokenUrl.toString(),n={refresh_token:t,client_id:this._clientId,client_secret:this._clientSecret,grant_type:"refresh_token"};let s;try{const t={...e.RETRY_CONFIG,method:"POST",url:r,data:new URLSearchParams((0,d.removeUndefinedValuesInObject)(n))};f.AuthClient.setMethodName(t,"refreshTokenNoCache"),s=await this.transporter.request(t)}catch(e){throw e instanceof a.GaxiosError&&"invalid_grant"===e.message&&e.response?.data&&/ReAuth/i.test(e.response.data.error_description)&&(e.message=JSON.stringify(e.response.data)),e}const o=s.data;return s.data&&s.data.expires_in&&(o.expiry_date=(new Date).getTime()+1e3*s.data.expires_in,delete o.expires_in),this.emit("tokens",o),{tokens:o,res:s}}refreshAccessToken(e){if(!e)return this.refreshAccessTokenAsync();this.refreshAccessTokenAsync().then((t=>e(null,t.credentials,t.res)),e)}async refreshAccessTokenAsync(){const e=await this.refreshToken(this.credentials.refresh_token),t=e.tokens;return t.refresh_token=this.credentials.refresh_token,this.credentials=t,{credentials:this.credentials,res:e.res}}getAccessToken(e){if(!e)return this.getAccessTokenAsync();this.getAccessTokenAsync().then((t=>e(null,t.token,t.res)),e)}async getAccessTokenAsync(){if(!this.credentials.access_token||this.isTokenExpiring()){if(!this.credentials.refresh_token){if(!this.refreshHandler)throw new Error("No refresh token or refresh handler callback is set.");{const e=await this.processAndValidateRefreshHandler();if(e?.access_token)return this.setCredentials(e),{token:this.credentials.access_token}}}const e=await this.refreshAccessTokenAsync();if(!e.credentials||e.credentials&&!e.credentials.access_token)throw new Error("Could not refresh access token.");return{token:e.credentials.access_token,res:e.res}}return{token:this.credentials.access_token}}async getRequestHeaders(e){return(await this.getRequestMetadataAsync(e)).headers}async getRequestMetadataAsync(e){const t=this.credentials;if(!(t.access_token||t.refresh_token||this.apiKey||this.refreshHandler))throw new Error("No access, refresh token, API key or refresh handler callback is set.");if(t.access_token&&!this.isTokenExpiring()){t.token_type=t.token_type||"Bearer";const e=new Headers({authorization:t.token_type+" "+t.access_token});return{headers:this.addSharedMetadataHeaders(e)}}if(this.refreshHandler){const e=await this.processAndValidateRefreshHandler();if(e?.access_token){this.setCredentials(e);const t=new Headers({authorization:"Bearer "+this.credentials.access_token});return{headers:this.addSharedMetadataHeaders(t)}}}if(this.apiKey)return{headers:new Headers({"X-Goog-Api-Key":this.apiKey})};let r=null,n=null;try{r=await this.refreshToken(t.refresh_token),n=r.tokens}catch(e){const t=e;throw!t.response||403!==t.response.status&&404!==t.response.status||(t.message=`Could not refresh access token: ${t.message}`),t}const s=this.credentials;s.token_type=s.token_type||"Bearer",n.refresh_token=s.refresh_token,this.credentials=n;const o=new Headers({authorization:s.token_type+" "+n.access_token});return{headers:this.addSharedMetadataHeaders(o),res:r.res}}static getRevokeTokenUrl(t){return(new e).getRevokeTokenURL(t).toString()}getRevokeTokenURL(e){const t=new URL(this.endpoints.oauth2RevokeUrl);return t.searchParams.append("token",e),t}revokeToken(t,r){const n={...e.RETRY_CONFIG,url:this.getRevokeTokenURL(t).toString(),method:"POST"};if(f.AuthClient.setMethodName(n,"revokeToken"),!r)return this.transporter.request(n);this.transporter.request(n).then((e=>r(null,e)),r)}revokeCredentials(e){if(!e)return this.revokeCredentialsAsync();this.revokeCredentialsAsync().then((t=>e(null,t)),e)}async revokeCredentialsAsync(){const e=this.credentials.access_token;if(this.credentials={},e)return this.revokeToken(e);throw new Error("No access token to revoke.")}request(e,t){if(!t)return this.requestAsync(e);this.requestAsync(e).then((e=>t(null,e)),(e=>t(e,e.response)))}async requestAsync(e,t=!1){try{const t=await this.getRequestMetadataAsync();return e.headers=a.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,t.headers),this.apiKey&&e.headers.set("X-Goog-Api-Key",this.apiKey),await this.transporter.request(e)}catch(r){const n=r.response;if(n){const r=n.status,s=this.credentials&&this.credentials.access_token&&this.credentials.refresh_token&&(!this.credentials.expiry_date||this.forceRefreshOnFailure),o=this.credentials&&this.credentials.access_token&&!this.credentials.refresh_token&&(!this.credentials.expiry_date||this.forceRefreshOnFailure)&&this.refreshHandler,i=n.config.data instanceof l.Readable,a=401===r||403===r;if(!t&&a&&!i&&s)return await this.refreshAccessTokenAsync(),this.requestAsync(e,!0);if(!t&&a&&!i&&o){const t=await this.processAndValidateRefreshHandler();return t?.access_token&&this.setCredentials(t),this.requestAsync(e,!0)}}throw r}}verifyIdToken(e,t){if(t&&"function"!=typeof t)throw new Error("This method accepts an options object as the first parameter, which includes the idToken, audience, and maxExpiry.");if(!t)return this.verifyIdTokenAsync(e);this.verifyIdTokenAsync(e).then((e=>t(null,e)),t)}async verifyIdTokenAsync(e){if(!e.idToken)throw new Error("The verifyIdToken method requires an ID Token");const t=await this.getFederatedSignonCertsAsync();return await this.verifySignedJwtWithCertsAsync(e.idToken,t.certs,e.audience,this.issuers,e.maxExpiry)}async getTokenInfo(t){const{data:r}=await this.transporter.request({...e.RETRY_CONFIG,method:"POST",headers:{"content-type":"application/x-www-form-urlencoded;charset=UTF-8",authorization:`Bearer ${t}`},url:this.endpoints.tokenInfoUrl.toString()}),n=Object.assign({expiry_date:(new Date).getTime()+1e3*r.expires_in,scopes:r.scope.split(" ")},r);return delete n.expires_in,delete n.scope,n}getFederatedSignonCerts(e){if(!e)return this.getFederatedSignonCertsAsync();this.getFederatedSignonCertsAsync().then((t=>e(null,t.certs,t.res)),e)}async getFederatedSignonCertsAsync(){const t=(new Date).getTime(),r=(0,h.hasBrowserCrypto)()?n.JWK:n.PEM;if(this.certificateExpiry&&t<this.certificateExpiry.getTime()&&this.certificateCacheFormat===r)return{certs:this.certificateCache,format:r};let s,o;switch(r){case n.PEM:o=this.endpoints.oauth2FederatedSignonPemCertsUrl.toString();break;case n.JWK:o=this.endpoints.oauth2FederatedSignonJwkCertsUrl.toString();break;default:throw new Error(`Unsupported certificate format ${r}`)}try{const t={...e.RETRY_CONFIG,url:o};f.AuthClient.setMethodName(t,"getFederatedSignonCertsAsync"),s=await this.transporter.request(t)}catch(e){throw e instanceof Error&&(e.message=`Failed to retrieve verification certificates: ${e.message}`),e}const i=s?.headers.get("cache-control");let a=-1;if(i){const e=/max-age=(?<maxAge>[0-9]+)/.exec(i)?.groups?.maxAge;e&&(a=1e3*Number(e))}let c={};switch(r){case n.PEM:c=s.data;break;case n.JWK:for(const e of s.data.keys)c[e.kid]=e;break;default:throw new Error(`Unsupported certificate format ${r}`)}const l=new Date;return this.certificateExpiry=-1===a?null:new Date(l.getTime()+a),this.certificateCache=c,this.certificateCacheFormat=r,{certs:c,format:r,res:s}}getIapPublicKeys(e){if(!e)return this.getIapPublicKeysAsync();this.getIapPublicKeysAsync().then((t=>e(null,t.pubkeys,t.res)),e)}async getIapPublicKeysAsync(){let t;const r=this.endpoints.oauth2IapPublicKeyUrl.toString();try{const n={...e.RETRY_CONFIG,url:r};f.AuthClient.setMethodName(n,"getIapPublicKeysAsync"),t=await this.transporter.request(n)}catch(e){throw e instanceof Error&&(e.message=`Failed to retrieve verification certificates: ${e.message}`),e}return{pubkeys:t.data,res:t}}verifySignedJwtWithCerts(){throw new Error("verifySignedJwtWithCerts is removed, please use verifySignedJwtWithCertsAsync instead.")}async verifySignedJwtWithCertsAsync(t,r,n,s,o){const i=(0,h.createCrypto)();o||(o=e.DEFAULT_MAX_TOKEN_LIFETIME_SECS_);const a=t.split(".");if(3!==a.length)throw new Error("Wrong number of segments in token: "+t);const c=a[0]+"."+a[1];let l,d,f=a[2];try{l=JSON.parse(i.decodeBase64StringUtf8(a[0]))}catch(e){throw e instanceof Error&&(e.message=`Can't parse token envelope: ${a[0]}': ${e.message}`),e}if(!l)throw new Error("Can't parse token envelope: "+a[0]);try{d=JSON.parse(i.decodeBase64StringUtf8(a[1]))}catch(e){throw e instanceof Error&&(e.message=`Can't parse token payload '${a[0]}`),e}if(!d)throw new Error("Can't parse token payload: "+a[1]);if(!Object.prototype.hasOwnProperty.call(r,l.kid))throw new Error("No pem found for envelope: "+JSON.stringify(l));const m=r[l.kid];"ES256"===l.alg&&(f=u.joseToDer(f,"ES256").toString("base64"));if(!await i.verify(m,c,f))throw new Error("Invalid token signature: "+t);if(!d.iat)throw new Error("No issue time in token: "+JSON.stringify(d));if(!d.exp)throw new Error("No expiration time in token: "+JSON.stringify(d));const _=Number(d.iat);if(isNaN(_))throw new Error("iat field using invalid format");const y=Number(d.exp);if(isNaN(y))throw new Error("exp field using invalid format");const g=(new Date).getTime()/1e3;if(y>=g+o)throw new Error("Expiration time too far in future: "+JSON.stringify(d));const E=_-e.CLOCK_SKEW_SECS_,b=y+e.CLOCK_SKEW_SECS_;if(g<E)throw new Error("Token used too early, "+g+" < "+E+": "+JSON.stringify(d));if(g>b)throw new Error("Token used too late, "+g+" > "+b+": "+JSON.stringify(d));if(s&&s.indexOf(d.iss)<0)throw new Error("Invalid issuer, expected one of ["+s+"], but got "+d.iss);if(null!=n){const e=d.aud;let t=!1;if(t=n.constructor===Array?n.indexOf(e)>-1:e===n,!t)throw new Error("Wrong recipient, payload audience != requiredAudience")}return new p.LoginTicket(l,d)}async processAndValidateRefreshHandler(){if(this.refreshHandler){const e=await this.refreshHandler();if(!e.access_token)throw new Error("No access token is returned by the refreshHandler callback.");return e}}isTokenExpiring(){const e=this.credentials.expiry_date;return!!e&&e<=(new Date).getTime()+this.eagerRefreshThresholdMillis}};e.OAuth2Client=m}}),ir=O({"node_modules/google-auth-library/build/src/auth/computeclient.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.Compute=void 0;var t=Lt(),r=Wt(),n=or(),s=class extends n.OAuth2Client{serviceAccountEmail;scopes;constructor(e={}){super(e),this.credentials={expiry_date:1,refresh_token:"compute-placeholder"},this.serviceAccountEmail=e.serviceAccountEmail||"default",this.scopes=Array.isArray(e.scopes)?e.scopes:e.scopes?[e.scopes]:[]}async refreshTokenNoCache(){const e=`service-accounts/${this.serviceAccountEmail}/token`;let n;try{const t={property:e};this.scopes.length>0&&(t.params={scopes:this.scopes.join(",")}),n=await r.instance(t)}catch(e){throw e instanceof t.GaxiosError&&(e.message=`Could not refresh access token: ${e.message}`,this.wrapError(e)),e}const s=n;return n&&n.expires_in&&(s.expiry_date=(new Date).getTime()+1e3*n.expires_in,delete s.expires_in),this.emit("tokens",s),{tokens:s,res:null}}async fetchIdToken(e){const t=`service-accounts/${this.serviceAccountEmail}/identity?format=full&audience=${e}`;let n;try{const e={property:t};n=await r.instance(e)}catch(e){throw e instanceof Error&&(e.message=`Could not fetch ID token: ${e.message}`),e}return n}wrapError(e){const t=e.response;t&&t.status&&(e.status=t.status,403===t.status?e.message="A Forbidden error was returned while attempting to retrieve an access token for the Compute Engine built-in service account. This may be because the Compute Engine instance does not have the correct permission scopes specified: "+e.message:404===t.status&&(e.message="A Not Found error was returned while attempting to retrieve an accesstoken for the Compute Engine built-in service account. This may be because the Compute Engine instance does not have any permission scopes specified: "+e.message))}};e.Compute=s}}),ar=O({"node_modules/google-auth-library/build/src/auth/idtokenclient.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.IdTokenClient=void 0;var t=or(),r=class extends t.OAuth2Client{targetAudience;idTokenProvider;constructor(e){super(e),this.targetAudience=e.targetAudience,this.idTokenProvider=e.idTokenProvider}async getRequestMetadataAsync(){if(!this.credentials.id_token||!this.credentials.expiry_date||this.isTokenExpiring()){const e=await this.idTokenProvider.fetchIdToken(this.targetAudience);this.credentials={id_token:e,expiry_date:this.getIdTokenExpiryDate(e)}}return{headers:new Headers({authorization:"Bearer "+this.credentials.id_token})}}getIdTokenExpiryDate(e){const t=e.split(".")[1];if(t){return 1e3*JSON.parse(Buffer.from(t,"base64").toString("ascii")).exp}}};e.IdTokenClient=r}}),cr=O({"node_modules/google-auth-library/build/src/auth/envDetect.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.GCPEnv=void 0,e.clear=function(){n=void 0},e.getEnv=async function(){if(n)return n;return n=async function(){let e=t.NONE;e=process.env.GAE_SERVICE||process.env.GAE_MODULE_NAME?t.APP_ENGINE:process.env.FUNCTION_NAME||process.env.FUNCTION_TARGET?t.CLOUD_FUNCTIONS:await async function(){return s.isAvailable()}()?await async function(){try{return await s.instance("attributes/cluster-name"),!0}catch(e){return!1}}()?t.KUBERNETES_ENGINE:process.env.K_CONFIGURATION?t.CLOUD_RUN:process.env.CLOUD_RUN_JOB?t.CLOUD_RUN_JOBS:t.COMPUTE_ENGINE:t.NONE;return e}()};var t,r,n,s=Wt();(r=t||(e.GCPEnv=t={})).APP_ENGINE="APP_ENGINE",r.KUBERNETES_ENGINE="KUBERNETES_ENGINE",r.CLOUD_FUNCTIONS="CLOUD_FUNCTIONS",r.COMPUTE_ENGINE="COMPUTE_ENGINE",r.CLOUD_RUN="CLOUD_RUN",r.CLOUD_RUN_JOBS="CLOUD_RUN_JOBS",r.NONE="NONE"}}),lr=O({"node_modules/jws/lib/data-stream.js"(e,t){var r=Xt().Buffer,n=S("stream");function s(e){if(this.buffer=null,this.writable=!0,this.readable=!0,!e)return this.buffer=r.alloc(0),this;if("function"==typeof e.pipe)return this.buffer=r.alloc(0),e.pipe(this),this;if(e.length||"object"==typeof e)return this.buffer=e,this.writable=!1,process.nextTick(function(){this.emit("end",e),this.readable=!1,this.emit("close")}.bind(this)),this;throw new TypeError("Unexpected data type ("+typeof e+")")}S("util").inherits(s,n),s.prototype.write=function(e){this.buffer=r.concat([this.buffer,r.from(e)]),this.emit("data",e)},s.prototype.end=function(e){e&&this.write(e),this.emit("end",e),this.emit("close"),this.writable=!1,this.readable=!1},t.exports=s}}),ur=O({"node_modules/buffer-equal-constant-time/index.js"(e,t){var r=S("buffer").Buffer,n=S("buffer").SlowBuffer;function s(e,t){if(!r.isBuffer(e)||!r.isBuffer(t))return!1;if(e.length!==t.length)return!1;for(var n=0,s=0;s<e.length;s++)n|=e[s]^t[s];return 0===n}t.exports=s,s.install=function(){r.prototype.equal=n.prototype.equal=function(e){return s(this,e)}};var o=r.prototype.equal,i=n.prototype.equal;s.restore=function(){r.prototype.equal=o,n.prototype.equal=i}}}),dr=O({"node_modules/jwa/index.js"(e,t){var r,n=Xt().Buffer,s=S("crypto"),o=Qt(),i=S("util"),a="secret must be a string or buffer",c="key must be a string or a buffer",l="function"==typeof s.createPublicKey;function u(e){if(!n.isBuffer(e)&&"string"!=typeof e){if(!l)throw p(c);if("object"!=typeof e)throw p(c);if("string"!=typeof e.type)throw p(c);if("string"!=typeof e.asymmetricKeyType)throw p(c);if("function"!=typeof e.export)throw p(c)}}function d(e){if(!n.isBuffer(e)&&"string"!=typeof e&&"object"!=typeof e)throw p("key must be a string, a buffer or an object")}function h(e){return e.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function f(e){var t=4-(e=e.toString()).length%4;if(4!==t)for(var r=0;r<t;++r)e+="=";return e.replace(/\-/g,"+").replace(/_/g,"/")}function p(e){var t=[].slice.call(arguments,1),r=i.format.bind(i,e).apply(null,t);return new TypeError(r)}function m(e){var t;return t=e,n.isBuffer(t)||"string"==typeof t||(e=JSON.stringify(e)),e}function _(e){return function(t,r){!function(e){if(!n.isBuffer(e)){if("string"==typeof e)return e;if(!l)throw p(a);if("object"!=typeof e)throw p(a);if("secret"!==e.type)throw p(a);if("function"!=typeof e.export)throw p(a)}}(r),t=m(t);var o=s.createHmac("sha"+e,r);return h((o.update(t),o.digest("base64")))}}l&&(c+=" or a KeyObject",a+="or a KeyObject");var y="timingSafeEqual"in s?function(e,t){return e.byteLength===t.byteLength&&s.timingSafeEqual(e,t)}:function(e,t){return r||(r=ur()),r(e,t)};function g(e){return function(t,r,s){var o=_(e)(t,s);return y(n.from(r),n.from(o))}}function E(e){return function(t,r){d(r),t=m(t);var n=s.createSign("RSA-SHA"+e);return h((n.update(t),n.sign(r,"base64")))}}function b(e){return function(t,r,n){u(n),t=m(t),r=f(r);var o=s.createVerify("RSA-SHA"+e);return o.update(t),o.verify(n,r,"base64")}}function w(e){return function(t,r){d(r),t=m(t);var n=s.createSign("RSA-SHA"+e);return h((n.update(t),n.sign({key:r,padding:s.constants.RSA_PKCS1_PSS_PADDING,saltLength:s.constants.RSA_PSS_SALTLEN_DIGEST},"base64")))}}function T(e){return function(t,r,n){u(n),t=m(t),r=f(r);var o=s.createVerify("RSA-SHA"+e);return o.update(t),o.verify({key:n,padding:s.constants.RSA_PKCS1_PSS_PADDING,saltLength:s.constants.RSA_PSS_SALTLEN_DIGEST},r,"base64")}}function v(e){var t=E(e);return function(){var r=t.apply(null,arguments);return r=o.derToJose(r,"ES"+e)}}function A(e){var t=b(e);return function(r,n,s){return n=o.joseToDer(n,"ES"+e).toString("base64"),t(r,n,s)}}function O(){return function(){return""}}function R(){return function(e,t){return""===t}}t.exports=function(e){var t={hs:_,rs:E,ps:w,es:v,none:O},r={hs:g,rs:b,ps:T,es:A,none:R},n=e.match(/^(RS|PS|ES|HS)(256|384|512)$|^(none)$/);if(!n)throw p('"%s" is not a valid algorithm.\n Supported algorithms are:\n "HS256", "HS384", "HS512", "RS256", "RS384", "RS512", "PS256", "PS384", "PS512", "ES256", "ES384", "ES512" and "none".',e);var s=(n[1]||n[3]).toLowerCase(),o=n[2];return{sign:t[s](o),verify:r[s](o)}}}}),hr=O({"node_modules/jws/lib/tostring.js"(e,t){var r=S("buffer").Buffer;t.exports=function(e){return"string"==typeof e?e:"number"==typeof e||r.isBuffer(e)?e.toString():JSON.stringify(e)}}}),fr=O({"node_modules/jws/lib/sign-stream.js"(e,t){var r=Xt().Buffer,n=lr(),s=dr(),o=S("stream"),i=hr(),a=S("util");function c(e,t){return r.from(e,t).toString("base64").replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function l(e){var t=e.header,r=e.payload,n=e.secret||e.privateKey,o=e.encoding,l=s(t.alg),u=function(e,t,r){r=r||"utf8";var n=c(i(e),"binary"),s=c(i(t),r);return a.format("%s.%s",n,s)}(t,r,o),d=l.sign(u,n);return a.format("%s.%s",u,d)}function u(e){var t=e.secret;if(t=null==(t=null==t?e.privateKey:t)?e.key:t,!0===/^hs/i.test(e.header.alg)&&null==t)throw new TypeError("secret must be a string or buffer or a KeyObject");var r=new n(t);this.readable=!0,this.header=e.header,this.encoding=e.encoding,this.secret=this.privateKey=this.key=r,this.payload=new n(e.payload),this.secret.once("close",function(){!this.payload.writable&&this.readable&&this.sign()}.bind(this)),this.payload.once("close",function(){!this.secret.writable&&this.readable&&this.sign()}.bind(this))}a.inherits(u,o),u.prototype.sign=function(){try{var e=l({header:this.header,payload:this.payload.buffer,secret:this.secret.buffer,encoding:this.encoding});return this.emit("done",e),this.emit("data",e),this.emit("end"),this.readable=!1,e}catch(e){this.readable=!1,this.emit("error",e),this.emit("close")}},u.sign=l,t.exports=u}}),pr=O({"node_modules/jws/lib/verify-stream.js"(e,t){var r=Xt().Buffer,n=lr(),s=dr(),o=S("stream"),i=hr(),a=S("util"),c=/^[a-zA-Z0-9\-_]+?\.[a-zA-Z0-9\-_]+?\.([a-zA-Z0-9\-_]+)?$/;function l(e){if(function(e){return"[object Object]"===Object.prototype.toString.call(e)}(e))return e;try{return JSON.parse(e)}catch(e){return}}function u(e){var t=e.split(".",1)[0];return l(r.from(t,"base64").toString("binary"))}function d(e){return e.split(".")[2]}function h(e){return c.test(e)&&!!u(e)}function f(e,t,r){if(!t){var n=new Error("Missing algorithm parameter for jws.verify");throw n.code="MISSING_ALGORITHM",n}var o=d(e=i(e)),a=function(e){return e.split(".",2).join(".")}(e);return s(t).verify(a,o,r)}function p(e,t){if(t=t||{},!h(e=i(e)))return null;var n=u(e);if(!n)return null;var s=function(e,t){t=t||"utf8";var n=e.split(".")[1];return r.from(n,"base64").toString(t)}(e);return("JWT"===n.typ||t.json)&&(s=JSON.parse(s,t.encoding)),{header:n,payload:s,signature:d(e)}}function m(e){var t=(e=e||{}).secret;if(t=null==(t=null==t?e.publicKey:t)?e.key:t,!0===/^hs/i.test(e.algorithm)&&null==t)throw new TypeError("secret must be a string or buffer or a KeyObject");var r=new n(t);this.readable=!0,this.algorithm=e.algorithm,this.encoding=e.encoding,this.secret=this.publicKey=this.key=r,this.signature=new n(e.signature),this.secret.once("close",function(){!this.signature.writable&&this.readable&&this.verify()}.bind(this)),this.signature.once("close",function(){!this.secret.writable&&this.readable&&this.verify()}.bind(this))}a.inherits(m,o),m.prototype.verify=function(){try{var e=f(this.signature.buffer,this.algorithm,this.key.buffer),t=p(this.signature.buffer,this.encoding);return this.emit("done",e,t),this.emit("data",e),this.emit("end"),this.readable=!1,e}catch(e){this.readable=!1,this.emit("error",e),this.emit("close")}},m.decode=p,m.isValid=h,m.verify=f,t.exports=m}}),mr=O({"node_modules/jws/index.js"(e){var t=fr(),r=pr();e.ALGORITHMS=["HS256","HS384","HS512","RS256","RS384","RS512","PS256","PS384","PS512","ES256","ES384","ES512"],e.sign=t.sign,e.verify=r.verify,e.decode=r.decode,e.isValid=r.isValid,e.createSign=function(e){return new t(e)},e.createVerify=function(e){return new r(e)}}}),_r=O({"node_modules/google-auth-library/build/src/gtoken/jwsSign.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.buildPayloadForJwsSign=r,e.getJwsSign=function(e){const n=r(e);return(0,t.sign)({header:{alg:"RS256"},payload:n,secret:e.key})};var t=mr();function r(e){const t=Math.floor((new Date).getTime()/1e3);return{iss:e.iss,scope:e.scope,aud:"https://oauth2.googleapis.com/token",exp:t+3600,iat:t,sub:e.sub,...e.additionalClaims}}}}),yr=O({"node_modules/google-auth-library/build/src/gtoken/getToken.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.getToken=async function(e){if(!e.transporter)throw new Error("No transporter set.");try{const s=(e=>({method:"POST",url:r,data:new URLSearchParams({grant_type:n,assertion:(0,t.getJwsSign)(e)}),responseType:"json",retryConfig:{httpMethodsToRetry:["POST"]}}))(e);return(await e.transporter.request(s)).data}catch(e){const t=e,r=t.response?.data;throw r?.error&&(t.message=`${r.error}: ${r.error_description}`),t}};var t=_r(),r="https://oauth2.googleapis.com/token",n="urn:ietf:params:oauth:grant-type:jwt-bearer"}}),gr=O({"node_modules/google-auth-library/build/src/gtoken/errorWithCode.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.ErrorWithCode=void 0;var t=class extends Error{code;constructor(e,t){super(e),this.code=t}};e.ErrorWithCode=t}}),Er=O({"node_modules/google-auth-library/build/src/gtoken/getCredentials.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.getCredentials=async function(e){return d.create(e).getCredentials()};var t,r,n=S("path"),s=S("fs"),o=S("util"),i=gr(),a=s.readFile?(0,o.promisify)(s.readFile):async()=>{throw new i.ErrorWithCode("use key rather than keyFile.","MISSING_CREDENTIALS")};(r=t||(t={})).JSON=".json",r.DER=".der",r.CRT=".crt",r.PEM=".pem",r.P12=".p12",r.PFX=".pfx";var c=class{keyFilePath;constructor(e){this.keyFilePath=e}async getCredentials(){const e=await a(this.keyFilePath,"utf8");let t;try{t=JSON.parse(e)}catch(e){throw new Error(`Invalid JSON key file: ${e.message}`)}const r=t.private_key,n=t.client_email;if(!r||!n)throw new i.ErrorWithCode("private_key and client_email are required.","MISSING_CREDENTIALS");return{privateKey:r,clientEmail:n}}},l=class{keyFilePath;constructor(e){this.keyFilePath=e}async getCredentials(){return{privateKey:await a(this.keyFilePath,"utf8")}}},u=class{async getCredentials(){throw new i.ErrorWithCode("*.p12 certificates are not supported after v6.1.2. Consider utilizing *.json format or converting *.p12 to *.pem using the OpenSSL CLI.","UNKNOWN_CERTIFICATE_TYPE")}},d=class{static create(e){switch(n.extname(e)){case t.JSON:return new c(e);case t.DER:case t.CRT:case t.PEM:return new l(e);case t.P12:case t.PFX:return new u;default:throw new i.ErrorWithCode("Unknown certificate type. Type is determined based on file extension. Current supported extensions are *.json, and *.pem.","UNKNOWN_CERTIFICATE_TYPE")}}}}}),br=O({"node_modules/google-auth-library/build/src/gtoken/tokenHandler.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.TokenHandler=void 0;var t=yr(),r=Er();e.TokenHandler=class{token;tokenExpiresAt;inFlightRequest;tokenOptions;constructor(e){this.tokenOptions=e}async processCredentials(){if(!this.tokenOptions.key&&!this.tokenOptions.keyFile)throw new Error("No key or keyFile set.");if(!this.tokenOptions.key&&this.tokenOptions.keyFile){const e=await(0,r.getCredentials)(this.tokenOptions.keyFile);this.tokenOptions.key=e.privateKey,this.tokenOptions.email=e.clientEmail}}isTokenExpiring(){if(!this.token||!this.tokenExpiresAt)return!0;const e=(new Date).getTime(),t=this.tokenOptions.eagerRefreshThresholdMillis??0;return this.tokenExpiresAt<=e+t}hasExpired(){if((new Date).getTime(),this.token&&this.tokenExpiresAt){return(new Date).getTime()>=this.tokenExpiresAt}return!0}async getToken(e){if(await this.processCredentials(),this.inFlightRequest&&!e)return this.inFlightRequest;if(this.token&&!this.isTokenExpiring()&&!e)return this.token;try{this.inFlightRequest=(0,t.getToken)(this.tokenOptions);const e=await this.inFlightRequest;return this.token=e,this.tokenExpiresAt=(new Date).getTime()+1e3*(e.expires_in??0),e}finally{this.inFlightRequest=void 0}}}}}),wr=O({"node_modules/google-auth-library/build/src/gtoken/revokeToken.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.revokeToken=async function(e,t){const r="https://oauth2.googleapis.com/revoke?token="+e;return await t.request({url:r,retry:true})}}}),Tr=O({"node_modules/google-auth-library/build/src/gtoken/googleToken.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.GoogleToken=void 0;var t=Lt(),r=br(),n=wr();e.GoogleToken=class{tokenOptions;tokenHandler;constructor(e){this.tokenOptions=e||{},this.tokenOptions.transporter=this.tokenOptions.transporter||{request:e=>(0,t.request)(e)},this.tokenOptions.iss||(this.tokenOptions.iss=this.tokenOptions.email),"object"==typeof this.tokenOptions.scope&&(this.tokenOptions.scope=this.tokenOptions.scope.join(" ")),this.tokenHandler=new r.TokenHandler(this.tokenOptions)}get expiresAt(){return this.tokenHandler.tokenExpiresAt}get accessToken(){return this.tokenHandler.token?.access_token}get idToken(){return this.tokenHandler.token?.id_token}get tokenType(){return this.tokenHandler.token?.token_type}get refreshToken(){return this.tokenHandler.token?.refresh_token}hasExpired(){return this.tokenHandler.hasExpired()}isTokenExpiring(){return this.tokenHandler.isTokenExpiring()}getToken(e,t={forceRefresh:!1}){let r;"function"==typeof e?r=e:"object"==typeof e&&(t=e);const n=this.tokenHandler.getToken(t.forceRefresh??!1);return r&&n.then((e=>r(null,e)),r),n}revokeToken(e){if(!this.accessToken)return Promise.reject(new Error("No token to revoke."));const t=(0,n.revokeToken)(this.accessToken,this.tokenOptions.transporter);e&&t.then((()=>e()),e),this.tokenHandler=new r.TokenHandler(this.tokenOptions)}get googleTokenOptions(){return this.tokenOptions}}}}),vr=O({"node_modules/google-auth-library/build/src/auth/jwtaccess.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.JWTAccess=void 0;var t=mr(),r=er(),n={alg:"RS256",typ:"JWT"};e.JWTAccess=class e{email;key;keyId;projectId;eagerRefreshThresholdMillis;cache=new r.LRUCache({capacity:500,maxAge:36e5});constructor(e,t,r,n){this.email=e,this.key=t,this.keyId=r,this.eagerRefreshThresholdMillis=n??3e5}getCachedKey(e,t){let r=e;if(t&&Array.isArray(t)&&t.length?r=e?`${e}_${t.join("_")}`:`${t.join("_")}`:"string"==typeof t&&(r=e?`${e}_${t}`:t),!r)throw Error("Scopes or url must be provided");return r}getRequestHeaders(r,s,o){const i=this.getCachedKey(r,o),a=this.cache.get(i),c=Date.now();if(a&&a.expiration-c>this.eagerRefreshThresholdMillis)return new Headers(a.headers);const l=Math.floor(Date.now()/1e3),u=e.getExpirationTime(l);let d;if(Array.isArray(o)&&(o=o.join(" ")),d=o?{iss:this.email,sub:this.email,scope:o,exp:u,iat:l}:{iss:this.email,sub:this.email,aud:r,exp:u,iat:l},s)for(const e in d)if(s[e])throw new Error(`The '${e}' property is not allowed when passing additionalClaims. This claim is included in the JWT by default.`);const h=this.keyId?{...n,kid:this.keyId}:n,f=Object.assign(d,s),p=t.sign({header:h,payload:f,secret:this.key}),m=new Headers({authorization:`Bearer ${p}`});return this.cache.set(i,{expiration:1e3*u,headers:m}),m}static getExpirationTime(e){return e+3600}fromJSON(e){if(!e)throw new Error("Must pass in a JSON object containing the service account auth settings.");if(!e.client_email)throw new Error("The incoming JSON object does not contain a client_email field");if(!e.private_key)throw new Error("The incoming JSON object does not contain a private_key field");this.email=e.client_email,this.key=e.private_key,this.keyId=e.private_key_id,this.projectId=e.project_id}fromStream(e,t){if(!t)return this.fromStreamAsync(e);this.fromStreamAsync(e).then((()=>t()),t)}fromStreamAsync(e){return new Promise(((t,r)=>{e||r(new Error("Must pass in a stream containing the service account auth settings."));let n="";e.setEncoding("utf8").on("data",(e=>n+=e)).on("error",r).on("end",(()=>{try{const e=JSON.parse(n);this.fromJSON(e),t()}catch(e){r(e)}}))}))}}}}),Sr=O({"node_modules/google-auth-library/build/src/auth/jwtclient.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.JWT=void 0;var t=Tr(),r=Er(),n=vr(),s=or(),o=nr(),i=class e extends s.OAuth2Client{email;keyFile;key;keyId;defaultScopes;scopes;scope;subject;gtoken;additionalClaims;useJWTAccessWithScope;defaultServicePath;access;constructor(e={}){super(e),this.email=e.email,this.keyFile=e.keyFile,this.key=e.key,this.keyId=e.keyId,this.scopes=e.scopes,this.subject=e.subject,this.additionalClaims=e.additionalClaims,this.credentials={refresh_token:"jwt-placeholder",expiry_date:1}}createScoped(t){const r=new e(this);return r.scopes=t,r}async getRequestMetadataAsync(e){e=this.defaultServicePath?`https://${this.defaultServicePath}/`:e;const t=!this.hasUserScopes()&&e||this.useJWTAccessWithScope&&this.hasAnyScopes()||this.universeDomain!==o.DEFAULT_UNIVERSE;if(this.subject&&this.universeDomain!==o.DEFAULT_UNIVERSE)throw new RangeError(`Service Account user is configured for the credential. Domain-wide delegation is not supported in universes other than ${o.DEFAULT_UNIVERSE}`);if(!this.apiKey&&t){if(this.additionalClaims&&this.additionalClaims.target_audience){const{tokens:e}=await this.refreshToken();return{headers:this.addSharedMetadataHeaders(new Headers({authorization:`Bearer ${e.id_token}`}))}}{let t;this.access||(this.access=new n.JWTAccess(this.email,this.key,this.keyId,this.eagerRefreshThresholdMillis)),this.hasUserScopes()?t=this.scopes:e||(t=this.defaultScopes);const r=this.useJWTAccessWithScope||this.universeDomain!==o.DEFAULT_UNIVERSE,s=await this.access.getRequestHeaders(e??void 0,this.additionalClaims,r?t:void 0);return{headers:this.addSharedMetadataHeaders(s)}}}return this.hasAnyScopes()||this.apiKey?super.getRequestMetadataAsync(e):{headers:new Headers}}async fetchIdToken(e){const r=new t.GoogleToken({iss:this.email,sub:this.subject,scope:this.scopes||this.defaultScopes,keyFile:this.keyFile,key:this.key,additionalClaims:{target_audience:e},transporter:this.transporter});if(await r.getToken({forceRefresh:!0}),!r.idToken)throw new Error("Unknown error: Failed to fetch ID token");return r.idToken}hasUserScopes(){return!!this.scopes&&this.scopes.length>0}hasAnyScopes(){return!!(this.scopes&&this.scopes.length>0)||!!(this.defaultScopes&&this.defaultScopes.length>0)}authorize(e){if(!e)return this.authorizeAsync();this.authorizeAsync().then((t=>e(null,t)),e)}async authorizeAsync(){const e=await this.refreshToken();if(!e)throw new Error("No result returned");return this.credentials=e.tokens,this.credentials.refresh_token="jwt-placeholder",this.key=this.gtoken.googleTokenOptions?.key,this.email=this.gtoken.googleTokenOptions?.iss,e.tokens}async refreshTokenNoCache(){const e=this.createGToken(),t={access_token:(await e.getToken({forceRefresh:this.isTokenExpiring()})).access_token,token_type:"Bearer",expiry_date:e.expiresAt,id_token:e.idToken};return this.emit("tokens",t),{res:null,tokens:t}}createGToken(){return this.gtoken||(this.gtoken=new t.GoogleToken({iss:this.email,sub:this.subject,scope:this.scopes||this.defaultScopes,keyFile:this.keyFile,key:this.key,additionalClaims:this.additionalClaims,transporter:this.transporter})),this.gtoken}fromJSON(e){if(!e)throw new Error("Must pass in a JSON object containing the service account auth settings.");if(!e.client_email)throw new Error("The incoming JSON object does not contain a client_email field");if(!e.private_key)throw new Error("The incoming JSON object does not contain a private_key field");this.email=e.client_email,this.key=e.private_key,this.keyId=e.private_key_id,this.projectId=e.project_id,this.quotaProjectId=e.quota_project_id,this.universeDomain=e.universe_domain||this.universeDomain}fromStream(e,t){if(!t)return this.fromStreamAsync(e);this.fromStreamAsync(e).then((()=>t()),t)}fromStreamAsync(e){return new Promise(((t,r)=>{if(!e)throw new Error("Must pass in a stream containing the service account auth settings.");let n="";e.setEncoding("utf8").on("error",r).on("data",(e=>n+=e)).on("end",(()=>{try{const e=JSON.parse(n);this.fromJSON(e),t()}catch(e){r(e)}}))}))}fromAPIKey(e){if("string"!=typeof e)throw new Error("Must provide an API Key string.");this.apiKey=e}async getCredentials(){if(this.key)return{private_key:this.key,client_email:this.email};if(this.keyFile){this.createGToken();const e=await(0,r.getCredentials)(this.keyFile);return{private_key:e.privateKey,client_email:e.clientEmail}}throw new Error("A key or a keyFile must be provided to getCredentials.")}};e.JWT=i}}),Ar=O({"node_modules/google-auth-library/build/src/auth/refreshclient.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.UserRefreshClient=e.USER_REFRESH_ACCOUNT_TYPE=void 0;var t=or(),r=nr();e.USER_REFRESH_ACCOUNT_TYPE="authorized_user";var n=class e extends t.OAuth2Client{_refreshToken;constructor(e,t,r,n,s){const o=e&&"object"==typeof e?e:{clientId:e,clientSecret:t,refreshToken:r,eagerRefreshThresholdMillis:n,forceRefreshOnFailure:s};super(o),this._refreshToken=o.refreshToken,this.credentials.refresh_token=o.refreshToken}async refreshTokenNoCache(){return super.refreshTokenNoCache(this._refreshToken)}async fetchIdToken(t){const n={...e.RETRY_CONFIG,url:this.endpoints.oauth2TokenUrl,method:"POST",data:new URLSearchParams({client_id:this._clientId,client_secret:this._clientSecret,grant_type:"refresh_token",refresh_token:this._refreshToken,target_audience:t}),responseType:"json"};r.AuthClient.setMethodName(n,"fetchIdToken");return(await this.transporter.request(n)).data.id_token}fromJSON(e){if(!e)throw new Error("Must pass in a JSON object containing the user refresh token");if("authorized_user"!==e.type)throw new Error('The incoming JSON object does not have the "authorized_user" type');if(!e.client_id)throw new Error("The incoming JSON object does not contain a client_id field");if(!e.client_secret)throw new Error("The incoming JSON object does not contain a client_secret field");if(!e.refresh_token)throw new Error("The incoming JSON object does not contain a refresh_token field");this._clientId=e.client_id,this._clientSecret=e.client_secret,this._refreshToken=e.refresh_token,this.credentials.refresh_token=e.refresh_token,this.quotaProjectId=e.quota_project_id,this.universeDomain=e.universe_domain||this.universeDomain}fromStream(e,t){if(!t)return this.fromStreamAsync(e);this.fromStreamAsync(e).then((()=>t()),t)}async fromStreamAsync(e){return new Promise(((t,r)=>{if(!e)return r(new Error("Must pass in a stream containing the user refresh token."));let n="";e.setEncoding("utf8").on("error",r).on("data",(e=>n+=e)).on("end",(()=>{try{const e=JSON.parse(n);return this.fromJSON(e),t()}catch(e){return r(e)}}))}))}static fromJSON(t){const r=new e;return r.fromJSON(t),r}};e.UserRefreshClient=n}}),Or=O({"node_modules/google-auth-library/build/src/auth/impersonated.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.Impersonated=e.IMPERSONATED_ACCOUNT_TYPE=void 0;var t=or(),r=Lt(),n=er();e.IMPERSONATED_ACCOUNT_TYPE="impersonated_service_account";var s=class e extends t.OAuth2Client{sourceClient;targetPrincipal;targetScopes;delegates;lifetime;endpoint;constructor(e={}){super(e),this.credentials={expiry_date:1,refresh_token:"impersonated-placeholder"},this.sourceClient=e.sourceClient??new t.OAuth2Client,this.targetPrincipal=e.targetPrincipal??"",this.delegates=e.delegates??[],this.targetScopes=e.targetScopes??[],this.lifetime=e.lifetime??3600;if(!!(0,n.originalOrCamelOptions)(e).get("universe_domain")){if(this.sourceClient.universeDomain!==this.universeDomain)throw new RangeError(`Universe domain ${this.sourceClient.universeDomain} in source credentials does not match ${this.universeDomain} universe domain set for impersonated credentials.`)}else this.universeDomain=this.sourceClient.universeDomain;this.endpoint=e.endpoint??`https://iamcredentials.${this.universeDomain}`}async sign(t){await this.sourceClient.getAccessToken();const r=`projects/-/serviceAccounts/${this.targetPrincipal}`,n=`${this.endpoint}/v1/${r}:signBlob`,s={delegates:this.delegates,payload:Buffer.from(t).toString("base64")};return(await this.sourceClient.request({...e.RETRY_CONFIG,url:n,data:s,method:"POST"})).data}getTargetPrincipal(){return this.targetPrincipal}async refreshToken(){try{await this.sourceClient.getAccessToken();const t="projects/-/serviceAccounts/"+this.targetPrincipal,r=`${this.endpoint}/v1/${t}:generateAccessToken`,n={delegates:this.delegates,scope:this.targetScopes,lifetime:this.lifetime+"s"},s=await this.sourceClient.request({...e.RETRY_CONFIG,url:r,data:n,method:"POST"}),o=s.data;return this.credentials.access_token=o.accessToken,this.credentials.expiry_date=Date.parse(o.expireTime),{tokens:this.credentials,res:s}}catch(e){if(!(e instanceof Error))throw e;let t=0,n="";throw e instanceof r.GaxiosError&&(t=e?.response?.data?.error?.status,n=e?.response?.data?.error?.message),t&&n?(e.message=`${t}: unable to impersonate: ${n}`,e):(e.message=`unable to impersonate: ${e}`,e)}}async fetchIdToken(t,r){await this.sourceClient.getAccessToken();const n=`projects/-/serviceAccounts/${this.targetPrincipal}`,s=`${this.endpoint}/v1/${n}:generateIdToken`,o={delegates:this.delegates,audience:t,includeEmail:r?.includeEmail??!0,useEmailAzp:r?.includeEmail??!0};return(await this.sourceClient.request({...e.RETRY_CONFIG,url:s,data:o,method:"POST"})).data.token}};e.Impersonated=s}}),Rr=O({"node_modules/google-auth-library/build/src/auth/oauth2common.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.OAuthClientAuthHandler=void 0,e.getErrorFromOAuthErrorResponse=function(e,t){const r=e.error,n=e.error_description,s=e.error_uri;let o=`Error code ${r}`;void 0!==n&&(o+=`: ${n}`);void 0!==s&&(o+=` - ${s}`);const i=new Error(o);if(t){const e=Object.keys(t);t.stack&&e.push("stack"),e.forEach((e=>{"message"!==e&&Object.defineProperty(i,e,{value:t[e],writable:!1,enumerable:!0})}))}return i};var t=Lt(),r=Kt(),n=["PUT","POST","PATCH"];e.OAuthClientAuthHandler=class{#w=(0,r.createCrypto)();#T;transporter;constructor(e){e&&"clientId"in e?(this.#T=e,this.transporter=new t.Gaxios):(this.#T=e?.clientAuthentication,this.transporter=e?.transporter||new t.Gaxios)}applyClientAuthenticationOptions(e,r){e.headers=t.Gaxios.mergeHeaders(e.headers),this.injectAuthenticatedHeaders(e,r),r||this.injectAuthenticatedRequestBody(e)}injectAuthenticatedHeaders(e,r){if(r)e.headers=t.Gaxios.mergeHeaders(e.headers,{authorization:`Bearer ${r}`});else if("basic"===this.#T?.confidentialClientType){e.headers=t.Gaxios.mergeHeaders(e.headers);const r=this.#T.clientId,n=this.#T.clientSecret||"",s=this.#w.encodeBase64StringUtf8(`${r}:${n}`);t.Gaxios.mergeHeaders(e.headers,{authorization:`Basic ${s}`})}}injectAuthenticatedRequestBody(e){if("request-body"===this.#T?.confidentialClientType){const t=(e.method||"GET").toUpperCase();if(!n.includes(t))throw new Error(`${t} HTTP method does not support ${this.#T.confidentialClientType} client authentication`);const r=new Headers(e.headers).get("content-type");if(r?.startsWith("application/x-www-form-urlencoded")||e.data instanceof URLSearchParams){const t=new URLSearchParams(e.data??"");t.append("client_id",this.#T.clientId),t.append("client_secret",this.#T.clientSecret||""),e.data=t}else{if(!r?.startsWith("application/json"))throw new Error(`${r} content-types are not supported with ${this.#T.confidentialClientType} client authentication`);e.data=e.data||{},Object.assign(e.data,{client_id:this.#T.clientId,client_secret:this.#T.clientSecret||""})}}}static get RETRY_CONFIG(){return{retry:!0,retryConfig:{httpMethodsToRetry:["GET","PUT","POST","HEAD","OPTIONS","DELETE"]}}}}}}),Cr=O({"node_modules/google-auth-library/build/src/auth/stscredentials.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.StsCredentials=void 0;var t=Lt(),r=nr(),n=Rr(),s=er(),o=class e extends n.OAuthClientAuthHandler{#v;constructor(e={tokenExchangeEndpoint:""},t){("object"!=typeof e||e instanceof URL)&&(e={tokenExchangeEndpoint:e,clientAuthentication:t}),super(e),this.#v=e.tokenExchangeEndpoint}async exchangeToken(o,i,a){const c={grant_type:o.grantType,resource:o.resource,audience:o.audience,scope:o.scope?.join(" "),requested_token_type:o.requestedTokenType,subject_token:o.subjectToken,subject_token_type:o.subjectTokenType,actor_token:o.actingParty?.actorToken,actor_token_type:o.actingParty?.actorTokenType,options:a&&JSON.stringify(a)},l={...e.RETRY_CONFIG,url:this.#v.toString(),method:"POST",headers:i,data:new URLSearchParams((0,s.removeUndefinedValuesInObject)(c)),responseType:"json"};r.AuthClient.setMethodName(l,"exchangeToken"),this.applyClientAuthenticationOptions(l);try{const e=await this.transporter.request(l),t=e.data;return t.res=e,t}catch(e){if(e instanceof t.GaxiosError&&e.response)throw(0,n.getErrorFromOAuthErrorResponse)(e.response.data,e);throw e}}};e.StsCredentials=o}}),Ir=O({"node_modules/google-auth-library/build/src/auth/baseexternalclient.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.BaseExternalAccountClient=e.CLOUD_RESOURCE_MANAGER=e.EXTERNAL_ACCOUNT_TYPE=e.EXPIRATION_TIME_OFFSET=void 0;var t=Lt(),r=S("stream"),n=nr(),s=Cr(),o=er(),i=rr(),a="https://www.googleapis.com/auth/cloud-platform";e.EXPIRATION_TIME_OFFSET=3e5,e.EXTERNAL_ACCOUNT_TYPE="external_account",e.CLOUD_RESOURCE_MANAGER="https://cloudresourcemanager.googleapis.com/v1/projects/";var c=class c extends n.AuthClient{scopes;projectNumber;audience;subjectTokenType;stsCredential;clientAuth;credentialSourceType;cachedAccessToken;serviceAccountImpersonationUrl;serviceAccountImpersonationLifetime;workforcePoolUserProject;configLifetimeRequested;tokenUrl;cloudResourceManagerURL;supplierContext;#S=null;constructor(t){super(t);const r=(0,o.originalOrCamelOptions)(t),n=r.get("type");if(n&&n!==e.EXTERNAL_ACCOUNT_TYPE)throw new Error(`Expected "${e.EXTERNAL_ACCOUNT_TYPE}" type but received "${t.type}"`);const i=r.get("client_id"),c=r.get("client_secret");this.tokenUrl=r.get("token_url")??"https://sts.{universeDomain}/v1/token".replace("{universeDomain}",this.universeDomain);const l=r.get("subject_token_type"),u=r.get("workforce_pool_user_project"),d=r.get("service_account_impersonation_url"),h=r.get("service_account_impersonation"),f=(0,o.originalOrCamelOptions)(h).get("token_lifetime_seconds");this.cloudResourceManagerURL=new URL(r.get("cloud_resource_manager_url")||`https://cloudresourcemanager.${this.universeDomain}/v1/projects/`),i&&(this.clientAuth={confidentialClientType:"basic",clientId:i,clientSecret:c}),this.stsCredential=new s.StsCredentials({tokenExchangeEndpoint:this.tokenUrl,clientAuthentication:this.clientAuth}),this.scopes=r.get("scopes")||[a],this.cachedAccessToken=null,this.audience=r.get("audience"),this.subjectTokenType=l,this.workforcePoolUserProject=u;const p=new RegExp("//iam\\.googleapis\\.com/locations/[^/]+/workforcePools/[^/]+/providers/.+");if(this.workforcePoolUserProject&&!this.audience.match(p))throw new Error("workforcePoolUserProject should not be set for non-workforce pool credentials.");this.serviceAccountImpersonationUrl=d,this.serviceAccountImpersonationLifetime=f,this.serviceAccountImpersonationLifetime?this.configLifetimeRequested=!0:(this.configLifetimeRequested=!1,this.serviceAccountImpersonationLifetime=3600),this.projectNumber=this.getProjectNumber(this.audience),this.supplierContext={audience:this.audience,subjectTokenType:this.subjectTokenType,transporter:this.transporter}}getServiceAccountEmail(){if(this.serviceAccountImpersonationUrl){if(this.serviceAccountImpersonationUrl.length>256)throw new RangeError(`URL is too long: ${this.serviceAccountImpersonationUrl}`);const e=/serviceAccounts\/(?<email>[^:]+):generateAccessToken$/.exec(this.serviceAccountImpersonationUrl);return e?.groups?.email||null}return null}setCredentials(e){super.setCredentials(e),this.cachedAccessToken=e}async getAccessToken(){return this.cachedAccessToken&&!this.isExpired(this.cachedAccessToken)||await this.refreshAccessTokenAsync(),{token:this.cachedAccessToken.access_token,res:this.cachedAccessToken.res}}async getRequestHeaders(){const e=await this.getAccessToken(),t=new Headers({authorization:`Bearer ${e.token}`});return this.addSharedMetadataHeaders(t)}request(e,t){if(!t)return this.requestAsync(e);this.requestAsync(e).then((e=>t(null,e)),(e=>t(e,e.response)))}async getProjectId(){const e=this.projectNumber||this.workforcePoolUserProject;if(this.projectId)return this.projectId;if(e){const t=await this.getRequestHeaders(),r={...c.RETRY_CONFIG,headers:t,url:`${this.cloudResourceManagerURL.toString()}${e}`,responseType:"json"};n.AuthClient.setMethodName(r,"getProjectId");const s=await this.transporter.request(r);return this.projectId=s.data.projectId,this.projectId}return null}async requestAsync(e,n=!1){let s;try{const r=await this.getRequestHeaders();e.headers=t.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,r),s=await this.transporter.request(e)}catch(t){const s=t.response;if(s){const t=s.status,o=s.config.data instanceof r.Readable;if(!n&&(401===t||403===t)&&!o&&this.forceRefreshOnFailure)return await this.refreshAccessTokenAsync(),await this.requestAsync(e,!0)}throw t}return s}async refreshAccessTokenAsync(){this.#S=this.#S||this.#A();try{return await this.#S}finally{this.#S=null}}async#A(){const e=await this.retrieveSubjectToken(),t={grantType:"urn:ietf:params:oauth:grant-type:token-exchange",audience:this.audience,requestedTokenType:"urn:ietf:params:oauth:token-type:access_token",subjectToken:e,subjectTokenType:this.subjectTokenType,scope:this.serviceAccountImpersonationUrl?[a]:this.getScopesArray()},r=!this.clientAuth&&this.workforcePoolUserProject?{userProject:this.workforcePoolUserProject}:void 0,n=new Headers({"x-goog-api-client":this.getMetricsHeaderValue()}),s=await this.stsCredential.exchangeToken(t,n,r);return this.serviceAccountImpersonationUrl?this.cachedAccessToken=await this.getImpersonatedAccessToken(s.access_token):s.expires_in?this.cachedAccessToken={access_token:s.access_token,expiry_date:(new Date).getTime()+1e3*s.expires_in,res:s.res}:this.cachedAccessToken={access_token:s.access_token,res:s.res},this.credentials={},Object.assign(this.credentials,this.cachedAccessToken),delete this.credentials.res,this.emit("tokens",{refresh_token:null,expiry_date:this.cachedAccessToken.expiry_date,access_token:this.cachedAccessToken.access_token,token_type:"Bearer",id_token:null}),this.cachedAccessToken}getProjectNumber(e){const t=e.match(/\/projects\/([^/]+)/);return t?t[1]:null}async getImpersonatedAccessToken(e){const t={...c.RETRY_CONFIG,url:this.serviceAccountImpersonationUrl,method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e}`},data:{scope:this.getScopesArray(),lifetime:this.serviceAccountImpersonationLifetime+"s"},responseType:"json"};n.AuthClient.setMethodName(t,"getImpersonatedAccessToken");const r=await this.transporter.request(t),s=r.data;return{access_token:s.accessToken,expiry_date:new Date(s.expireTime).getTime(),res:r}}isExpired(e){const t=(new Date).getTime();return!!e.expiry_date&&t>=e.expiry_date-this.eagerRefreshThresholdMillis}getScopesArray(){return"string"==typeof this.scopes?[this.scopes]:this.scopes||[a]}getMetricsHeaderValue(){const e=process.version.replace(/^v/,""),t=void 0!==this.serviceAccountImpersonationUrl,r=this.credentialSourceType?this.credentialSourceType:"unknown";return`gl-node/${e} auth/${i.pkg.version} google-byoid-sdk source/${r} sa-impersonation/${t} config-lifetime/${this.configLifetimeRequested}`}getTokenUrl(){return this.tokenUrl}};e.BaseExternalAccountClient=c}}),kr=O({"node_modules/google-auth-library/build/src/auth/filesubjecttokensupplier.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.FileSubjectTokenSupplier=void 0;var t=S("util"),r=S("fs"),n=(0,t.promisify)(r.readFile??(()=>{})),s=(0,t.promisify)(r.realpath??(()=>{})),o=(0,t.promisify)(r.lstat??(()=>{}));e.FileSubjectTokenSupplier=class{filePath;formatType;subjectTokenFieldName;constructor(e){this.filePath=e.filePath,this.formatType=e.formatType,this.subjectTokenFieldName=e.subjectTokenFieldName}async getSubjectToken(){let e,t=this.filePath;try{if(t=await s(t),!(await o(t)).isFile())throw new Error}catch(e){throw e instanceof Error&&(e.message=`The file at ${t} does not exist, or it is not a file. ${e.message}`),e}const r=await n(t,{encoding:"utf8"});if("text"===this.formatType)e=r;else if("json"===this.formatType&&this.subjectTokenFieldName){e=JSON.parse(r)[this.subjectTokenFieldName]}if(!e)throw new Error("Unable to parse the subject_token from the credential_source file");return e}}}}),Nr=O({"node_modules/google-auth-library/build/src/auth/urlsubjecttokensupplier.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.UrlSubjectTokenSupplier=void 0;var t=nr();e.UrlSubjectTokenSupplier=class{url;headers;formatType;subjectTokenFieldName;additionalGaxiosOptions;constructor(e){this.url=e.url,this.formatType=e.formatType,this.subjectTokenFieldName=e.subjectTokenFieldName,this.headers=e.headers,this.additionalGaxiosOptions=e.additionalGaxiosOptions}async getSubjectToken(e){const r={...this.additionalGaxiosOptions,url:this.url,method:"GET",headers:this.headers,responseType:this.formatType};let n;if(t.AuthClient.setMethodName(r,"getSubjectToken"),"text"===this.formatType){n=(await e.transporter.request(r)).data}else if("json"===this.formatType&&this.subjectTokenFieldName){n=(await e.transporter.request(r)).data[this.subjectTokenFieldName]}if(!n)throw new Error("Unable to parse the subject_token from the credential_source URL");return n}}}}),Pr=O({"node_modules/google-auth-library/build/src/auth/certificatesubjecttokensupplier.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.CertificateSubjectTokenSupplier=e.InvalidConfigurationError=e.CertificateSourceUnavailableError=e.CERTIFICATE_CONFIGURATION_ENV_VARIABLE=void 0;var t=er(),r=S("fs"),n=S("crypto"),s=S("https");e.CERTIFICATE_CONFIGURATION_ENV_VARIABLE="GOOGLE_API_CERTIFICATE_CONFIG";var o=class extends Error{constructor(e){super(e),this.name="CertificateSourceUnavailableError"}};e.CertificateSourceUnavailableError=o;var i=class extends Error{constructor(e){super(e),this.name="InvalidConfigurationError"}};e.InvalidConfigurationError=i;e.CertificateSubjectTokenSupplier=class{certificateConfigPath;trustChainPath;cert;key;constructor(e){if(!e.useDefaultCertificateConfig&&!e.certificateConfigLocation)throw new i("Either `useDefaultCertificateConfig` must be true or a `certificateConfigLocation` must be provided.");if(e.useDefaultCertificateConfig&&e.certificateConfigLocation)throw new i("Both `useDefaultCertificateConfig` and `certificateConfigLocation` cannot be provided.");this.trustChainPath=e.trustChainPath,this.certificateConfigPath=e.certificateConfigLocation??""}async createMtlsHttpsAgent(){if(!this.key||!this.cert)throw new i("Cannot create mTLS Agent with missing certificate or key");return new s.Agent({key:this.key,cert:this.cert})}async getSubjectToken(){this.certificateConfigPath=await this.#O();const{certPath:e,keyPath:t}=await this.#R();return({cert:this.cert,key:this.key}=await this.#C(e,t)),await this.#I(this.cert)}async#O(){const r=this.certificateConfigPath;if(r){if(await(0,t.isValidFile)(r))return r;throw new o(`Provided certificate config path is invalid: ${r}`)}const n=process.env[e.CERTIFICATE_CONFIGURATION_ENV_VARIABLE];if(n){if(await(0,t.isValidFile)(n))return n;throw new o(`Path from environment variable "${e.CERTIFICATE_CONFIGURATION_ENV_VARIABLE}" is invalid: ${n}`)}const s=(0,t.getWellKnownCertificateConfigFileLocation)();if(await(0,t.isValidFile)(s))return s;throw new o(`Could not find certificate configuration file. Searched override path, the "${e.CERTIFICATE_CONFIGURATION_ENV_VARIABLE}" env var, and the gcloud path (${s}).`)}async#R(){const e=this.certificateConfigPath;let t;try{t=await r.promises.readFile(e,"utf8")}catch(t){throw new o(`Failed to read certificate config file at: ${e}`)}try{const r=JSON.parse(t),n=r?.cert_configs?.workload?.cert_path,s=r?.cert_configs?.workload?.key_path;if(!n||!s)throw new i(`Certificate config file (${e}) is missing required "cert_path" or "key_path" in the workload config.`);return{certPath:n,keyPath:s}}catch(t){if(t instanceof i)throw t;throw new i(`Failed to parse certificate config from ${e}: ${t.message}`)}}async#C(e,t){let s,i;try{s=await r.promises.readFile(e),new n.X509Certificate(s)}catch(t){const r=t instanceof Error?t.message:String(t);throw new o(`Failed to read certificate file at ${e}: ${r}`)}try{i=await r.promises.readFile(t),(0,n.createPrivateKey)(i)}catch(e){const r=e instanceof Error?e.message:String(e);throw new o(`Failed to read private key file at ${t}: ${r}`)}return{cert:s,key:i}}async#I(e){const t=new n.X509Certificate(e);if(!this.trustChainPath)return JSON.stringify([t.raw.toString("base64")]);try{const e=await r.promises.readFile(this.trustChainPath,"utf8"),s=(e.match(/-----BEGIN CERTIFICATE-----[^-]+-----END CERTIFICATE-----/g)??[]).map(((e,t)=>{try{return new n.X509Certificate(e)}catch(e){const r=e instanceof Error?e.message:String(e);throw new i(`Failed to parse certificate at index ${t} in trust chain file ${this.trustChainPath}: ${r}`)}})),o=s.findIndex((e=>t.raw.equals(e.raw)));let a;if(-1===o)a=[t,...s];else{if(0!==o)throw new i(`Leaf certificate exists in the trust chain but is not the first entry (found at index ${o}).`);a=s}return JSON.stringify(a.map((e=>e.raw.toString("base64"))))}catch(e){if(e instanceof i)throw e;const t=e instanceof Error?e.message:String(e);throw new o(`Failed to process certificate chain from ${this.trustChainPath}: ${t}`)}}}}}),xr=O({"node_modules/google-auth-library/build/src/auth/identitypoolclient.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.IdentityPoolClient=void 0;var t=Ir(),r=er(),n=kr(),s=Nr(),o=Pr(),i=Cr(),a=Lt(),c=class e extends t.BaseExternalAccountClient{subjectTokenSupplier;constructor(t){super(t);const i=(0,r.originalOrCamelOptions)(t),a=i.get("credential_source"),c=i.get("subject_token_supplier");if(!a&&!c)throw new Error("A credential source or subject token supplier must be specified.");if(a&&c)throw new Error("Only one of credential source or subject token supplier can be specified.");if(c)this.subjectTokenSupplier=c,this.credentialSourceType="programmatic";else{const t=(0,r.originalOrCamelOptions)(a),i=(0,r.originalOrCamelOptions)(t.get("format")),c=i.get("type")||"text",l=i.get("subject_token_field_name");if("json"!==c&&"text"!==c)throw new Error(`Invalid credential_source format "${c}"`);if("json"===c&&!l)throw new Error("Missing subject_token_field_name for JSON credential_source format");const u=t.get("file"),d=t.get("url"),h=t.get("certificate"),f=t.get("headers");if(u&&d||d&&h||u&&h)throw new Error('No valid Identity Pool "credential_source" provided, must be either file, url, or certificate.');if(u)this.credentialSourceType="file",this.subjectTokenSupplier=new n.FileSubjectTokenSupplier({filePath:u,formatType:c,subjectTokenFieldName:l});else if(d)this.credentialSourceType="url",this.subjectTokenSupplier=new s.UrlSubjectTokenSupplier({url:d,formatType:c,subjectTokenFieldName:l,headers:f,additionalGaxiosOptions:e.RETRY_CONFIG});else{if(!h)throw new Error('No valid Identity Pool "credential_source" provided, must be either file, url, or certificate.');{this.credentialSourceType="certificate";const e=new o.CertificateSubjectTokenSupplier({useDefaultCertificateConfig:h.use_default_certificate_config,certificateConfigLocation:h.certificate_config_location,trustChainPath:h.trust_chain_path});this.subjectTokenSupplier=e}}}}async retrieveSubjectToken(){const e=await this.subjectTokenSupplier.getSubjectToken(this.supplierContext);if(this.subjectTokenSupplier instanceof o.CertificateSubjectTokenSupplier){const e=await this.subjectTokenSupplier.createMtlsHttpsAgent();this.stsCredential=new i.StsCredentials({tokenExchangeEndpoint:this.getTokenUrl(),clientAuthentication:this.clientAuth,transporter:new a.Gaxios({agent:e})}),this.transporter=new a.Gaxios({...this.transporter.defaults||{},agent:e})}return e}};e.IdentityPoolClient=c}}),Dr=O({"node_modules/google-auth-library/build/src/auth/awsrequestsigner.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.AwsRequestSigner=void 0;var t=Lt(),r=Kt(),n="AWS4-HMAC-SHA256",s="aws4_request";async function o(e,t,r){return await e.signWithHmacSha256(t,r)}e.AwsRequestSigner=class{getCredentials;region;crypto;constructor(e,t){this.getCredentials=e,this.region=t,this.crypto=(0,r.createCrypto)()}async getRequestOptions(e){if(!e.url)throw new RangeError('"url" is required in "amzOptions"');const i="object"==typeof e.data?JSON.stringify(e.data):e.data,a=e.url,c=e.method||"GET",l=e.body||i,u=e.headers,d=await this.getCredentials(),h=new URL(a);if("string"!=typeof l&&void 0!==l)throw new TypeError(`'requestPayload' is expected to be a string if provided. Got: ${l}`);const f=await async function(e){const i=t.Gaxios.mergeHeaders(e.additionalAmzHeaders),a=e.requestPayload||"",c=e.host.split(".")[0],l=new Date,u=l.toISOString().replace(/[-:]/g,"").replace(/\.[0-9]+/,""),d=l.toISOString().replace(/[-]/g,"").replace(/T.*/,"");e.securityCredentials.token&&i.set("x-amz-security-token",e.securityCredentials.token);const h=t.Gaxios.mergeHeaders({host:e.host},i.has("date")?{}:{"x-amz-date":u},i);let f="";const p=[...h.keys()].sort();p.forEach((e=>{f+=`${e}:${h.get(e)}\n`}));const m=p.join(";"),_=await e.crypto.sha256DigestHex(a),y=`${e.method.toUpperCase()}\n${e.canonicalUri}\n${e.canonicalQuerystring}\n${f}\n${m}\n${_}`,g=`${d}/${e.region}/${c}/${s}`,E=`${n}\n${u}\n${g}\n`+await e.crypto.sha256DigestHex(y),b=await async function(e,t,r,n,s){const i=await o(e,`AWS4${t}`,r),a=await o(e,i,n),c=await o(e,a,s);return await o(e,c,"aws4_request")}(e.crypto,e.securityCredentials.secretAccessKey,d,e.region,c),w=await o(e.crypto,b,E),T=`${n} Credential=${e.securityCredentials.accessKeyId}/${g}, SignedHeaders=${m}, Signature=${(0,r.fromArrayBufferToHex)(w)}`;return{amzDate:i.has("date")?void 0:u,authorizationHeader:T,canonicalQuerystring:e.canonicalQuerystring}}({crypto:this.crypto,host:h.host,canonicalUri:h.pathname,canonicalQuerystring:h.search.slice(1),method:c,region:this.region,securityCredentials:d,requestPayload:l,additionalAmzHeaders:u}),p=t.Gaxios.mergeHeaders(f.amzDate?{"x-amz-date":f.amzDate}:{},{authorization:f.authorizationHeader,host:h.host},u||{});d.token&&t.Gaxios.mergeHeaders(p,{"x-amz-security-token":d.token});const m={url:a,method:c,headers:p};return void 0!==l&&(m.body=l),m}}}}),Ur=O({"node_modules/google-auth-library/build/src/auth/defaultawssecuritycredentialssupplier.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.DefaultAwsSecurityCredentialsSupplier=void 0;var t=nr();e.DefaultAwsSecurityCredentialsSupplier=class{regionUrl;securityCredentialsUrl;imdsV2SessionTokenUrl;additionalGaxiosOptions;constructor(e){this.regionUrl=e.regionUrl,this.securityCredentialsUrl=e.securityCredentialsUrl,this.imdsV2SessionTokenUrl=e.imdsV2SessionTokenUrl,this.additionalGaxiosOptions=e.additionalGaxiosOptions}async getAwsRegion(e){if(this.#k)return this.#k;const r=new Headers;if(!this.#k&&this.imdsV2SessionTokenUrl&&r.set("x-aws-ec2-metadata-token",await this.#N(e.transporter)),!this.regionUrl)throw new RangeError('Unable to determine AWS region due to missing "options.credential_source.region_url"');const n={...this.additionalGaxiosOptions,url:this.regionUrl,method:"GET",responseType:"text",headers:r};t.AuthClient.setMethodName(n,"getAwsRegion");const s=await e.transporter.request(n);return s.data.substr(0,s.data.length-1)}async getAwsSecurityCredentials(e){if(this.#P)return this.#P;const t=new Headers;this.imdsV2SessionTokenUrl&&t.set("x-aws-ec2-metadata-token",await this.#N(e.transporter));const r=await this.#x(t,e.transporter),n=await this.#D(r,t,e.transporter);return{accessKeyId:n.AccessKeyId,secretAccessKey:n.SecretAccessKey,token:n.Token}}async#N(e){const r={...this.additionalGaxiosOptions,url:this.imdsV2SessionTokenUrl,method:"PUT",responseType:"text",headers:{"x-aws-ec2-metadata-token-ttl-seconds":"300"}};t.AuthClient.setMethodName(r,"#getImdsV2SessionToken");return(await e.request(r)).data}async#x(e,r){if(!this.securityCredentialsUrl)throw new Error('Unable to determine AWS role name due to missing "options.credential_source.url"');const n={...this.additionalGaxiosOptions,url:this.securityCredentialsUrl,method:"GET",responseType:"text",headers:e};t.AuthClient.setMethodName(n,"#getAwsRoleName");return(await r.request(n)).data}async#D(e,r,n){const s={...this.additionalGaxiosOptions,url:`${this.securityCredentialsUrl}/${e}`,headers:r,responseType:"json"};t.AuthClient.setMethodName(s,"#retrieveAwsSecurityCredentials");return(await n.request(s)).data}get#k(){return process.env.AWS_REGION||process.env.AWS_DEFAULT_REGION||null}get#P(){return process.env.AWS_ACCESS_KEY_ID&&process.env.AWS_SECRET_ACCESS_KEY?{accessKeyId:process.env.AWS_ACCESS_KEY_ID,secretAccessKey:process.env.AWS_SECRET_ACCESS_KEY,token:process.env.AWS_SESSION_TOKEN}:null}}}}),Lr=O({"node_modules/google-auth-library/build/src/auth/awsclient.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.AwsClient=void 0;var t=Dr(),r=Ir(),n=Ur(),s=er(),o=Lt(),i=class e extends r.BaseExternalAccountClient{environmentId;awsSecurityCredentialsSupplier;regionalCredVerificationUrl;awsRequestSigner;region;static#U="https://sts.{region}.amazonaws.com?Action=GetCallerIdentity&Version=2011-06-15";static AWS_EC2_METADATA_IPV4_ADDRESS="169.254.169.254";static AWS_EC2_METADATA_IPV6_ADDRESS="fd00:ec2::254";constructor(t){super(t);const r=(0,s.originalOrCamelOptions)(t),o=r.get("credential_source"),i=r.get("aws_security_credentials_supplier");if(!o&&!i)throw new Error("A credential source or AWS security credentials supplier must be specified.");if(o&&i)throw new Error("Only one of credential source or AWS security credentials supplier can be specified.");if(i)this.awsSecurityCredentialsSupplier=i,this.regionalCredVerificationUrl=e.#U,this.credentialSourceType="programmatic";else{const e=(0,s.originalOrCamelOptions)(o);this.environmentId=e.get("environment_id");const t=e.get("region_url"),r=e.get("url"),i=e.get("imdsv2_session_token_url");this.awsSecurityCredentialsSupplier=new n.DefaultAwsSecurityCredentialsSupplier({regionUrl:t,securityCredentialsUrl:r,imdsV2SessionTokenUrl:i}),this.regionalCredVerificationUrl=e.get("regional_cred_verification_url"),this.credentialSourceType="aws",this.validateEnvironmentId()}this.awsRequestSigner=null,this.region=""}validateEnvironmentId(){const e=this.environmentId?.match(/^(aws)(\d+)$/);if(!e||!this.regionalCredVerificationUrl)throw new Error('No valid AWS "credential_source" provided');if(1!==parseInt(e[2],10))throw new Error(`aws version "${e[2]}" is not supported in the current build.`)}async retrieveSubjectToken(){this.awsRequestSigner||(this.region=await this.awsSecurityCredentialsSupplier.getAwsRegion(this.supplierContext),this.awsRequestSigner=new t.AwsRequestSigner((async()=>this.awsSecurityCredentialsSupplier.getAwsSecurityCredentials(this.supplierContext)),this.region));const r=await this.awsRequestSigner.getRequestOptions({...e.RETRY_CONFIG,url:this.regionalCredVerificationUrl.replace("{region}",this.region),method:"POST"}),n=[];return o.Gaxios.mergeHeaders({"x-goog-cloud-target-resource":this.audience},r.headers).forEach(((e,t)=>n.push({key:t,value:e}))),encodeURIComponent(JSON.stringify({url:r.url,method:r.method,headers:n}))}};e.AwsClient=i}}),jr=O({"node_modules/google-auth-library/build/src/auth/executable-response.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.InvalidSubjectTokenError=e.InvalidMessageFieldError=e.InvalidCodeFieldError=e.InvalidTokenTypeFieldError=e.InvalidExpirationTimeFieldError=e.InvalidSuccessFieldError=e.InvalidVersionFieldError=e.ExecutableResponseError=e.ExecutableResponse=void 0;var t="urn:ietf:params:oauth:token-type:saml2",r="urn:ietf:params:oauth:token-type:id_token",n="urn:ietf:params:oauth:token-type:jwt";e.ExecutableResponse=class{version;success;expirationTime;tokenType;errorCode;errorMessage;subjectToken;constructor(e){if(!e.version)throw new o("Executable response must contain a 'version' field.");if(void 0===e.success)throw new i("Executable response must contain a 'success' field.");if(this.version=e.version,this.success=e.success,this.success){if(this.expirationTime=e.expiration_time,this.tokenType=e.token_type,this.tokenType!==t&&this.tokenType!==r&&this.tokenType!==n)throw new a(`Executable response must contain a 'token_type' field when successful and it must be one of ${r}, ${n}, or ${t}.`);if(this.tokenType===t){if(!e.saml_response)throw new u(`Executable response must contain a 'saml_response' field when token_type=${t}.`);this.subjectToken=e.saml_response}else{if(!e.id_token)throw new u(`Executable response must contain a 'id_token' field when token_type=${r} or ${n}.`);this.subjectToken=e.id_token}}else{if(!e.code)throw new c("Executable response must contain a 'code' field when unsuccessful.");if(!e.message)throw new l("Executable response must contain a 'message' field when unsuccessful.");this.errorCode=e.code,this.errorMessage=e.message}}isValid(){return!this.isExpired()&&this.success}isExpired(){return void 0!==this.expirationTime&&this.expirationTime<Math.round(Date.now()/1e3)}};var s=class extends Error{constructor(e){super(e),Object.setPrototypeOf(this,new.target.prototype)}};e.ExecutableResponseError=s;var o=class extends s{};e.InvalidVersionFieldError=o;var i=class extends s{};e.InvalidSuccessFieldError=i;e.InvalidExpirationTimeFieldError=class extends s{};var a=class extends s{};e.InvalidTokenTypeFieldError=a;var c=class extends s{};e.InvalidCodeFieldError=c;var l=class extends s{};e.InvalidMessageFieldError=l;var u=class extends s{};e.InvalidSubjectTokenError=u}}),Mr=O({"node_modules/google-auth-library/build/src/auth/pluggable-auth-handler.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.PluggableAuthHandler=e.ExecutableError=void 0;var t=jr(),r=S("child_process"),n=S("fs"),s=class extends Error{code;constructor(e,t){super(`The executable failed with exit code: ${t} and error message: ${e}.`),this.code=t,Object.setPrototypeOf(this,new.target.prototype)}};e.ExecutableError=s;e.PluggableAuthHandler=class e{commandComponents;timeoutMillis;outputFile;constructor(t){if(!t.command)throw new Error("No command provided.");if(this.commandComponents=e.parseCommand(t.command),this.timeoutMillis=t.timeoutMillis,!this.timeoutMillis)throw new Error("No timeoutMillis provided.");this.outputFile=t.outputFile}retrieveResponseFromExecutable(e){return new Promise(((n,o)=>{const i=r.spawn(this.commandComponents[0],this.commandComponents.slice(1),{env:{...process.env,...Object.fromEntries(e)}});let a="";i.stdout.on("data",(e=>{a+=e})),i.stderr.on("data",(e=>{a+=e}));const c=setTimeout((()=>(i.removeAllListeners(),i.kill(),o(new Error("The executable failed to finish within the timeout specified.")))),this.timeoutMillis);i.on("close",(e=>{if(clearTimeout(c),0!==e)return o(new s(a,e.toString()));try{const e=JSON.parse(a),r=new t.ExecutableResponse(e);return n(r)}catch(e){return e instanceof t.ExecutableResponseError?o(e):o(new t.ExecutableResponseError(`The executable returned an invalid response: ${a}`))}}))}))}async retrieveCachedResponse(){if(!this.outputFile||0===this.outputFile.length)return;let e;try{e=await n.promises.realpath(this.outputFile)}catch{return}if(!(await n.promises.lstat(e)).isFile())return;const r=await n.promises.readFile(e,{encoding:"utf8"});if(""!==r)try{const e=JSON.parse(r);return new t.ExecutableResponse(e).isValid()?new t.ExecutableResponse(e):void 0}catch(e){if(e instanceof t.ExecutableResponseError)throw e;throw new t.ExecutableResponseError(`The output file contained an invalid response: ${r}`)}}static parseCommand(e){const t=e.match(/(?:[^\s"]+|"[^"]*")+/g);if(!t)throw new Error(`Provided command: "${e}" could not be parsed.`);for(let e=0;e<t.length;e++)'"'===t[e][0]&&'"'===t[e].slice(-1)&&(t[e]=t[e].slice(1,-1));return t}}}}),Fr=O({"node_modules/google-auth-library/build/src/auth/pluggable-auth-client.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.PluggableAuthClient=e.ExecutableError=void 0;var t=Ir(),r=jr(),n=Mr(),s=Mr();Object.defineProperty(e,"ExecutableError",{enumerable:!0,get:function(){return s.ExecutableError}});var o=12e4,i=class extends t.BaseExternalAccountClient{command;timeoutMillis;outputFile;handler;constructor(e){if(super(e),!e.credential_source.executable)throw new Error('No valid Pluggable Auth "credential_source" provided.');if(this.command=e.credential_source.executable.command,!this.command)throw new Error('No valid Pluggable Auth "credential_source" provided.');if(void 0===e.credential_source.executable.timeout_millis)this.timeoutMillis=3e4;else if(this.timeoutMillis=e.credential_source.executable.timeout_millis,this.timeoutMillis<5e3||this.timeoutMillis>o)throw new Error("Timeout must be between 5000 and 120000 milliseconds.");this.outputFile=e.credential_source.executable.output_file,this.handler=new n.PluggableAuthHandler({command:this.command,timeoutMillis:this.timeoutMillis,outputFile:this.outputFile}),this.credentialSourceType="executable"}async retrieveSubjectToken(){if("1"!==process.env.GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES)throw new Error("Pluggable Auth executables need to be explicitly allowed to run by setting the GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES environment Variable to 1.");let e;if(this.outputFile&&(e=await this.handler.retrieveCachedResponse()),!e){const t=new Map;t.set("GOOGLE_EXTERNAL_ACCOUNT_AUDIENCE",this.audience),t.set("GOOGLE_EXTERNAL_ACCOUNT_TOKEN_TYPE",this.subjectTokenType),t.set("GOOGLE_EXTERNAL_ACCOUNT_INTERACTIVE","0"),this.outputFile&&t.set("GOOGLE_EXTERNAL_ACCOUNT_OUTPUT_FILE",this.outputFile);const r=this.getServiceAccountEmail();r&&t.set("GOOGLE_EXTERNAL_ACCOUNT_IMPERSONATED_EMAIL",r),e=await this.handler.retrieveResponseFromExecutable(t)}if(e.version>1)throw new Error("Version of executable is not currently supported, maximum supported version is 1.");if(!e.success)throw new n.ExecutableError(e.errorMessage,e.errorCode);if(this.outputFile&&!e.expirationTime)throw new r.InvalidExpirationTimeFieldError("The executable response must contain the `expiration_time` field for successful responses when an output_file has been specified in the configuration.");if(e.isExpired())throw new Error("Executable response is expired.");return e.subjectToken}};e.PluggableAuthClient=i}}),Br=O({"node_modules/google-auth-library/build/src/auth/externalclient.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.ExternalAccountClient=void 0;var t=Ir(),r=xr(),n=Lr(),s=Fr();e.ExternalAccountClient=class{constructor(){throw new Error("ExternalAccountClients should be initialized via: ExternalAccountClient.fromJSON(), directly via explicit constructors, eg. new AwsClient(options), new IdentityPoolClient(options), newPluggableAuthClientOptions, or via new GoogleAuth(options).getClient()")}static fromJSON(e){return e&&e.type===t.EXTERNAL_ACCOUNT_TYPE?e.credential_source?.environment_id?new n.AwsClient(e):e.credential_source?.executable?new s.PluggableAuthClient(e):new r.IdentityPoolClient(e):null}}}}),Gr=O({"node_modules/google-auth-library/build/src/auth/externalAccountAuthorizedUserClient.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.ExternalAccountAuthorizedUserClient=e.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE=void 0;var t=nr(),r=Rr(),n=Lt(),s=S("stream"),o=Ir();e.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE="external_account_authorized_user";var i=class e extends r.OAuthClientAuthHandler{#L;constructor(e){super(e),this.#L=e.tokenRefreshEndpoint}async refreshToken(s,o){const i={...e.RETRY_CONFIG,url:this.#L,method:"POST",headers:o,data:new URLSearchParams({grant_type:"refresh_token",refresh_token:s}),responseType:"json"};t.AuthClient.setMethodName(i,"refreshToken"),this.applyClientAuthenticationOptions(i);try{const e=await this.transporter.request(i),t=e.data;return t.res=e,t}catch(e){if(e instanceof n.GaxiosError&&e.response)throw(0,r.getErrorFromOAuthErrorResponse)(e.response.data,e);throw e}}},a=class extends t.AuthClient{cachedAccessToken;externalAccountAuthorizedUserHandler;refreshToken;constructor(e){super(e),e.universe_domain&&(this.universeDomain=e.universe_domain),this.refreshToken=e.refresh_token;const t={confidentialClientType:"basic",clientId:e.client_id,clientSecret:e.client_secret};this.externalAccountAuthorizedUserHandler=new i({tokenRefreshEndpoint:e.token_url??"https://sts.{universeDomain}/v1/oauthtoken".replace("{universeDomain}",this.universeDomain),transporter:this.transporter,clientAuthentication:t}),this.cachedAccessToken=null,this.quotaProjectId=e.quota_project_id,this.eagerRefreshThresholdMillis="number"!=typeof e?.eagerRefreshThresholdMillis?o.EXPIRATION_TIME_OFFSET:e.eagerRefreshThresholdMillis,this.forceRefreshOnFailure=!!e?.forceRefreshOnFailure}async getAccessToken(){return this.cachedAccessToken&&!this.isExpired(this.cachedAccessToken)||await this.refreshAccessTokenAsync(),{token:this.cachedAccessToken.access_token,res:this.cachedAccessToken.res}}async getRequestHeaders(){const e=await this.getAccessToken(),t=new Headers({authorization:`Bearer ${e.token}`});return this.addSharedMetadataHeaders(t)}request(e,t){if(!t)return this.requestAsync(e);this.requestAsync(e).then((e=>t(null,e)),(e=>t(e,e.response)))}async requestAsync(e,t=!1){let r;try{const t=await this.getRequestHeaders();e.headers=n.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,t),r=await this.transporter.request(e)}catch(r){const n=r.response;if(n){const r=n.status,o=n.config.data instanceof s.Readable;if(!t&&(401===r||403===r)&&!o&&this.forceRefreshOnFailure)return await this.refreshAccessTokenAsync(),await this.requestAsync(e,!0)}throw r}return r}async refreshAccessTokenAsync(){const e=await this.externalAccountAuthorizedUserHandler.refreshToken(this.refreshToken);return this.cachedAccessToken={access_token:e.access_token,expiry_date:(new Date).getTime()+1e3*e.expires_in,res:e.res},void 0!==e.refresh_token&&(this.refreshToken=e.refresh_token),this.cachedAccessToken}isExpired(e){const t=(new Date).getTime();return!!e.expiry_date&&t>=e.expiry_date-this.eagerRefreshThresholdMillis}};e.ExternalAccountAuthorizedUserClient=a}}),Hr=O({"node_modules/google-auth-library/build/src/auth/googleauth.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.GoogleAuth=e.GoogleAuthExceptionMessages=void 0;var t=S("child_process"),r=S("fs"),n=Lt(),s=Wt(),o=S("os"),i=S("path"),a=Kt(),c=ir(),l=ar(),u=cr(),d=Sr(),h=Ar(),f=Or(),p=Br(),m=Ir(),_=nr(),y=Gr(),g=er();e.GoogleAuthExceptionMessages={API_KEY_WITH_CREDENTIALS:"API Keys and Credentials are mutually exclusive authentication methods and cannot be used together.",NO_PROJECT_ID_FOUND:"Unable to detect a Project Id in the current environment. \nTo learn more about authentication and Google APIs, visit: \nhttps://cloud.google.com/docs/authentication/getting-started",NO_CREDENTIALS_FOUND:"Unable to find credentials in current environment. \nTo learn more about authentication and Google APIs, visit: \nhttps://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.\nTo learn more about Universe Domain retrieval, visit: \nhttps://cloud.google.com/compute/docs/metadata/predefined-metadata-keys"};e.GoogleAuth=class{checkIsGCE=void 0;useJWTAccessWithScope;defaultServicePath;get isGCE(){return this.checkIsGCE}_findProjectIdPromise;_cachedProjectId;jsonContent=null;apiKey;cachedCredential=null;#j=null;defaultScopes;keyFilename;scopes;clientOptions={};constructor(t={}){if(this._cachedProjectId=t.projectId||null,this.cachedCredential=t.authClient||null,this.keyFilename=t.keyFilename||t.keyFile,this.scopes=t.scopes,this.clientOptions=t.clientOptions||{},this.jsonContent=t.credentials||null,this.apiKey=t.apiKey||this.clientOptions.apiKey||null,this.apiKey&&(this.jsonContent||this.clientOptions.credentials))throw new RangeError(e.GoogleAuthExceptionMessages.API_KEY_WITH_CREDENTIALS);t.universeDomain&&(this.clientOptions.universeDomain=t.universeDomain)}setGapicJWTValues(e){e.defaultServicePath=this.defaultServicePath,e.useJWTAccessWithScope=this.useJWTAccessWithScope,e.defaultScopes=this.defaultScopes}getProjectId(e){if(!e)return this.getProjectIdAsync();this.getProjectIdAsync().then((t=>e(null,t)),e)}async getProjectIdOptional(){try{return await this.getProjectId()}catch(t){if(t instanceof Error&&t.message===e.GoogleAuthExceptionMessages.NO_PROJECT_ID_FOUND)return null;throw t}}async findAndCacheProjectId(){let t=null;if(t||=await this.getProductionProjectId(),t||=await this.getFileProjectId(),t||=await this.getDefaultServiceProjectId(),t||=await this.getGCEProjectId(),t||=await this.getExternalAccountClientProjectId(),t)return this._cachedProjectId=t,t;throw new Error(e.GoogleAuthExceptionMessages.NO_PROJECT_ID_FOUND)}async getProjectIdAsync(){return this._cachedProjectId?this._cachedProjectId:(this._findProjectIdPromise||(this._findProjectIdPromise=this.findAndCacheProjectId()),this._findProjectIdPromise)}async getUniverseDomainFromMetadataServer(){let e;try{e=await s.universe("universe-domain"),e||=_.DEFAULT_UNIVERSE}catch(t){if(!t||404!==t?.response?.status)throw t;e=_.DEFAULT_UNIVERSE}return e}async getUniverseDomain(){let e=(0,g.originalOrCamelOptions)(this.clientOptions).get("universe_domain");try{e??=(await this.getClient()).universeDomain}catch{e??=_.DEFAULT_UNIVERSE}return e}getAnyScopes(){return this.scopes||this.defaultScopes}getApplicationDefault(e={},t){let r;if("function"==typeof e?t=e:r=e,!t)return this.getApplicationDefaultAsync(r);this.getApplicationDefaultAsync(r).then((e=>t(null,e.credential,e.projectId)),t)}async getApplicationDefaultAsync(t={}){if(this.cachedCredential)return await this.#M(this.cachedCredential,null);let r;if(r=await this._tryGetApplicationCredentialsFromEnvironmentVariable(t),r)return r instanceof d.JWT?r.scopes=this.scopes:r instanceof m.BaseExternalAccountClient&&(r.scopes=this.getAnyScopes()),await this.#M(r);if(r=await this._tryGetApplicationCredentialsFromWellKnownFile(t),r)return r instanceof d.JWT?r.scopes=this.scopes:r instanceof m.BaseExternalAccountClient&&(r.scopes=this.getAnyScopes()),await this.#M(r);if(await this._checkIsGCE())return t.scopes=this.getAnyScopes(),await this.#M(new c.Compute(t));throw new Error(e.GoogleAuthExceptionMessages.NO_ADC_FOUND)}async#M(e,t=process.env.GOOGLE_CLOUD_QUOTA_PROJECT||null){const r=await this.getProjectIdOptional();return t&&(e.quotaProjectId=t),this.cachedCredential=e,{credential:e,projectId:r}}async _checkIsGCE(){return void 0===this.checkIsGCE&&(this.checkIsGCE=s.getGCPResidency()||await s.isAvailable()),this.checkIsGCE}async _tryGetApplicationCredentialsFromEnvironmentVariable(e){const t=process.env.GOOGLE_APPLICATION_CREDENTIALS||process.env.google_application_credentials;if(!t||0===t.length)return null;try{return this._getApplicationCredentialsFromFilePath(t,e)}catch(e){throw e instanceof Error&&(e.message=`Unable to read the credential file specified by the GOOGLE_APPLICATION_CREDENTIALS environment variable: ${e.message}`),e}}async _tryGetApplicationCredentialsFromWellKnownFile(e){let t=null;if(this._isWindows())t=process.env.APPDATA;else{const e=process.env.HOME;e&&(t=i.join(e,".config"))}if(t&&(t=i.join(t,"gcloud","application_default_credentials.json"),r.existsSync(t)||(t=null)),!t)return null;return await this._getApplicationCredentialsFromFilePath(t,e)}async _getApplicationCredentialsFromFilePath(e,t={}){if(!e||0===e.length)throw new Error("The file path is invalid.");try{if(e=r.realpathSync(e),!r.lstatSync(e).isFile())throw new Error}catch(t){throw t instanceof Error&&(t.message=`The file at ${e} does not exist, or it is not a file. ${t.message}`),t}const n=r.createReadStream(e);return this.fromStream(n,t)}fromImpersonatedJSON(e){if(!e)throw new Error("Must pass in a JSON object containing an impersonated refresh token");if(e.type!==f.IMPERSONATED_ACCOUNT_TYPE)throw new Error(`The incoming JSON object does not have the "${f.IMPERSONATED_ACCOUNT_TYPE}" type`);if(!e.source_credentials)throw new Error("The incoming JSON object does not contain a source_credentials field");if(!e.service_account_impersonation_url)throw new Error("The incoming JSON object does not contain a service_account_impersonation_url field");const t=this.fromJSON(e.source_credentials);if(e.service_account_impersonation_url?.length>256)throw new RangeError(`Target principal is too long: ${e.service_account_impersonation_url}`);const r=/(?<target>[^/]+):(generateAccessToken|generateIdToken)$/.exec(e.service_account_impersonation_url)?.groups?.target;if(!r)throw new RangeError(`Cannot extract target principal from ${e.service_account_impersonation_url}`);const n=(this.scopes||e.scopes||this.defaultScopes)??[];return new f.Impersonated({...e,sourceClient:t,targetPrincipal:r,targetScopes:Array.isArray(n)?n:[n]})}fromJSON(e,t={}){let r;const n=(0,g.originalOrCamelOptions)(t).get("universe_domain");return e.type===h.USER_REFRESH_ACCOUNT_TYPE?(r=new h.UserRefreshClient(t),r.fromJSON(e)):e.type===f.IMPERSONATED_ACCOUNT_TYPE?r=this.fromImpersonatedJSON(e):e.type===m.EXTERNAL_ACCOUNT_TYPE?(r=p.ExternalAccountClient.fromJSON({...e,...t}),r.scopes=this.getAnyScopes()):e.type===y.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE?r=new y.ExternalAccountAuthorizedUserClient({...e,...t}):(t.scopes=this.scopes,r=new d.JWT(t),this.setGapicJWTValues(r),r.fromJSON(e)),n&&(r.universeDomain=n),r}_cacheClientFromJSON(e,t){const r=this.fromJSON(e,t);return this.jsonContent=e,this.cachedCredential=r,r}fromStream(e,t={},r){let n={};if("function"==typeof t?r=t:n=t,!r)return this.fromStreamAsync(e,n);this.fromStreamAsync(e,n).then((e=>r(null,e)),r)}fromStreamAsync(e,t){return new Promise(((r,n)=>{if(!e)throw new Error("Must pass in a stream containing the Google auth settings.");const s=[];e.setEncoding("utf8").on("error",n).on("data",(e=>s.push(e))).on("end",(()=>{try{try{const e=JSON.parse(s.join("")),n=this._cacheClientFromJSON(e,t);return r(n)}catch(e){if(!this.keyFilename)throw e;const t=new d.JWT({...this.clientOptions,keyFile:this.keyFilename});return this.cachedCredential=t,this.setGapicJWTValues(t),r(t)}}catch(e){return n(e)}}))}))}fromAPIKey(e,t={}){return new d.JWT({...t,apiKey:e})}_isWindows(){const e=o.platform();return!!(e&&e.length>=3&&"win"===e.substring(0,3).toLowerCase())}async getDefaultServiceProjectId(){return new Promise((e=>{(0,t.exec)("gcloud config config-helper --format json",((t,r)=>{if(!t&&r)try{const t=JSON.parse(r).configuration.properties.core.project;return void e(t)}catch(e){}e(null)}))}))}getProductionProjectId(){return process.env.GCLOUD_PROJECT||process.env.GOOGLE_CLOUD_PROJECT||process.env.gcloud_project||process.env.google_cloud_project}async getFileProjectId(){if(this.cachedCredential)return this.cachedCredential.projectId;if(this.keyFilename){const e=await this.getClient();if(e&&e.projectId)return e.projectId}const e=await this._tryGetApplicationCredentialsFromEnvironmentVariable();return e?e.projectId:null}async getExternalAccountClientProjectId(){if(!this.jsonContent||this.jsonContent.type!==m.EXTERNAL_ACCOUNT_TYPE)return null;const e=await this.getClient();return await e.getProjectId()}async getGCEProjectId(){try{return await s.project("project-id")}catch(e){return null}}getCredentials(e){if(!e)return this.getCredentialsAsync();this.getCredentialsAsync().then((t=>e(null,t)),e)}async getCredentialsAsync(){const t=await this.getClient();if(t instanceof f.Impersonated)return{client_email:t.getTargetPrincipal()};if(t instanceof m.BaseExternalAccountClient){const e=t.getServiceAccountEmail();if(e)return{client_email:e,universe_domain:t.universeDomain}}if(this.jsonContent)return{client_email:this.jsonContent.client_email,private_key:this.jsonContent.private_key,universe_domain:this.jsonContent.universe_domain};if(await this._checkIsGCE()){const[e,t]=await Promise.all([s.instance("service-accounts/default/email"),this.getUniverseDomain()]);return{client_email:e,universe_domain:t}}throw new Error(e.GoogleAuthExceptionMessages.NO_CREDENTIALS_FOUND)}async getClient(){if(this.cachedCredential)return this.cachedCredential;this.#j=this.#j||this.#F();try{return await this.#j}finally{this.#j=null}}async#F(){if(this.jsonContent)return this._cacheClientFromJSON(this.jsonContent,this.clientOptions);if(this.keyFilename){const e=i.resolve(this.keyFilename),t=r.createReadStream(e);return await this.fromStreamAsync(t,this.clientOptions)}if(this.apiKey){const e=await this.fromAPIKey(this.apiKey,this.clientOptions);e.scopes=this.scopes;const{credential:t}=await this.#M(e);return t}{const{credential:e}=await this.getApplicationDefaultAsync(this.clientOptions);return e}}async getIdTokenClient(e){const t=await this.getClient();if(!("fetchIdToken"in t))throw new Error("Cannot fetch ID token in this environment, use GCE or set the GOOGLE_APPLICATION_CREDENTIALS environment variable to a service account credentials JSON file.");return new l.IdTokenClient({targetAudience:e,idTokenProvider:t})}async getAccessToken(){const e=await this.getClient();return(await e.getAccessToken()).token}async getRequestHeaders(e){return(await this.getClient()).getRequestHeaders(e)}async authorizeRequest(e={}){const t=e.url,r=await this.getClient(),s=await r.getRequestHeaders(t);return e.headers=n.Gaxios.mergeHeaders(e.headers,s),e}async fetch(...e){return(await this.getClient()).fetch(...e)}async request(e){return(await this.getClient()).request(e)}getEnv(){return(0,u.getEnv)()}async sign(e,t){const r=await this.getClient(),n=await this.getUniverseDomain();if(t=t||`https://iamcredentials.${n}/v1/projects/-/serviceAccounts/`,r instanceof f.Impersonated){return(await r.sign(e)).signedBlob}const s=(0,a.createCrypto)();if(r instanceof d.JWT&&r.key){return await s.sign(r.key,e)}const o=await this.getCredentials();if(!o.client_email)throw new Error("Cannot sign data without `client_email`.");return this.signBlob(s,o.client_email,e,t)}async signBlob(e,t,r,n){const s=new URL(n+`${t}:signBlob`);return(await this.request({method:"POST",url:s.href,data:{payload:e.encodeBase64StringUtf8(r)},retry:!0,retryConfig:{httpMethodsToRetry:["POST"]}})).data.signedBlob}}}}),qr=O({"node_modules/google-auth-library/build/src/auth/iam.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.IAMAuth=void 0;e.IAMAuth=class{selector;token;constructor(e,t){this.selector=e,this.token=t,this.selector=e,this.token=t}getRequestHeaders(){return{"x-goog-iam-authority-selector":this.selector,"x-goog-iam-authorization-token":this.token}}}}}),$r=O({"node_modules/google-auth-library/build/src/auth/downscopedclient.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.DownscopedClient=e.EXPIRATION_TIME_OFFSET=e.MAX_ACCESS_BOUNDARY_RULES_COUNT=void 0;var t=Lt(),r=S("stream"),n=nr(),s=Cr();e.MAX_ACCESS_BOUNDARY_RULES_COUNT=10,e.EXPIRATION_TIME_OFFSET=3e5;var o=class extends n.AuthClient{authClient;credentialAccessBoundary;cachedDownscopedAccessToken;stsCredential;constructor(t,r={accessBoundary:{accessBoundaryRules:[]}}){if(super(t instanceof n.AuthClient?{}:t),t instanceof n.AuthClient?(this.authClient=t,this.credentialAccessBoundary=r):(this.authClient=t.authClient,this.credentialAccessBoundary=t.credentialAccessBoundary),0===this.credentialAccessBoundary.accessBoundary.accessBoundaryRules.length)throw new Error("At least one access boundary rule needs to be defined.");if(this.credentialAccessBoundary.accessBoundary.accessBoundaryRules.length>e.MAX_ACCESS_BOUNDARY_RULES_COUNT)throw new Error(`The provided access boundary has more than ${e.MAX_ACCESS_BOUNDARY_RULES_COUNT} access boundary rules.`);for(const e of this.credentialAccessBoundary.accessBoundary.accessBoundaryRules)if(0===e.availablePermissions.length)throw new Error("At least one permission should be defined in access boundary rules.");this.stsCredential=new s.StsCredentials({tokenExchangeEndpoint:`https://sts.${this.universeDomain}/v1/token`}),this.cachedDownscopedAccessToken=null}setCredentials(e){if(!e.expiry_date)throw new Error("The access token expiry_date field is missing in the provided credentials.");super.setCredentials(e),this.cachedDownscopedAccessToken=e}async getAccessToken(){return this.cachedDownscopedAccessToken&&!this.isExpired(this.cachedDownscopedAccessToken)||await this.refreshAccessTokenAsync(),{token:this.cachedDownscopedAccessToken.access_token,expirationTime:this.cachedDownscopedAccessToken.expiry_date,res:this.cachedDownscopedAccessToken.res}}async getRequestHeaders(){const e=await this.getAccessToken(),t=new Headers({authorization:`Bearer ${e.token}`});return this.addSharedMetadataHeaders(t)}request(e,t){if(!t)return this.requestAsync(e);this.requestAsync(e).then((e=>t(null,e)),(e=>t(e,e.response)))}async requestAsync(e,n=!1){let s;try{const r=await this.getRequestHeaders();e.headers=t.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,r),s=await this.transporter.request(e)}catch(t){const s=t.response;if(s){const t=s.status,o=s.config.data instanceof r.Readable;if(!n&&(401===t||403===t)&&!o&&this.forceRefreshOnFailure)return await this.refreshAccessTokenAsync(),await this.requestAsync(e,!0)}throw t}return s}async refreshAccessTokenAsync(){const e={grantType:"urn:ietf:params:oauth:grant-type:token-exchange",requestedTokenType:"urn:ietf:params:oauth:token-type:access_token",subjectToken:(await this.authClient.getAccessToken()).token,subjectTokenType:"urn:ietf:params:oauth:token-type:access_token"},t=await this.stsCredential.exchangeToken(e,void 0,this.credentialAccessBoundary),r=this.authClient.credentials?.expiry_date||null,n=t.expires_in?(new Date).getTime()+1e3*t.expires_in:r;return this.cachedDownscopedAccessToken={access_token:t.access_token,expiry_date:n,res:t.res},this.credentials={},Object.assign(this.credentials,this.cachedDownscopedAccessToken),delete this.credentials.res,this.emit("tokens",{refresh_token:null,expiry_date:this.cachedDownscopedAccessToken.expiry_date,access_token:this.cachedDownscopedAccessToken.access_token,token_type:"Bearer",id_token:null}),this.cachedDownscopedAccessToken}isExpired(e){const t=(new Date).getTime();return!!e.expiry_date&&t>=e.expiry_date-this.eagerRefreshThresholdMillis}};e.DownscopedClient=o}}),Wr=O({"node_modules/google-auth-library/build/src/auth/passthrough.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.PassThroughClient=void 0;var t=nr(),r=class extends t.AuthClient{async request(e){return this.transporter.request(e)}async getAccessToken(){return{}}async getRequestHeaders(){return new Headers}};e.PassThroughClient=r}}),Vr=O({"node_modules/google-auth-library/build/src/index.js"(e){var t=e&&e.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var s=Object.getOwnPropertyDescriptor(t,r);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,s)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),r=e&&e.__exportStar||function(e,r){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(r,n)||t(r,e,n)};Object.defineProperty(e,"__esModule",{value:!0}),e.GoogleAuth=e.auth=e.PassThroughClient=e.ExternalAccountAuthorizedUserClient=e.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE=e.ExecutableError=e.PluggableAuthClient=e.DownscopedClient=e.BaseExternalAccountClient=e.ExternalAccountClient=e.IdentityPoolClient=e.AwsRequestSigner=e.AwsClient=e.UserRefreshClient=e.LoginTicket=e.ClientAuthentication=e.OAuth2Client=e.CodeChallengeMethod=e.Impersonated=e.JWT=e.JWTAccess=e.IdTokenClient=e.IAMAuth=e.GCPEnv=e.Compute=e.DEFAULT_UNIVERSE=e.AuthClient=e.gaxios=e.gcpMetadata=void 0;var n=Hr();Object.defineProperty(e,"GoogleAuth",{enumerable:!0,get:function(){return n.GoogleAuth}}),e.gcpMetadata=Wt(),e.gaxios=Lt();var s=nr();Object.defineProperty(e,"AuthClient",{enumerable:!0,get:function(){return s.AuthClient}}),Object.defineProperty(e,"DEFAULT_UNIVERSE",{enumerable:!0,get:function(){return s.DEFAULT_UNIVERSE}});var o=ir();Object.defineProperty(e,"Compute",{enumerable:!0,get:function(){return o.Compute}});var i=cr();Object.defineProperty(e,"GCPEnv",{enumerable:!0,get:function(){return i.GCPEnv}});var a=qr();Object.defineProperty(e,"IAMAuth",{enumerable:!0,get:function(){return a.IAMAuth}});var c=ar();Object.defineProperty(e,"IdTokenClient",{enumerable:!0,get:function(){return c.IdTokenClient}});var l=vr();Object.defineProperty(e,"JWTAccess",{enumerable:!0,get:function(){return l.JWTAccess}});var u=Sr();Object.defineProperty(e,"JWT",{enumerable:!0,get:function(){return u.JWT}});var d=Or();Object.defineProperty(e,"Impersonated",{enumerable:!0,get:function(){return d.Impersonated}});var h=or();Object.defineProperty(e,"CodeChallengeMethod",{enumerable:!0,get:function(){return h.CodeChallengeMethod}}),Object.defineProperty(e,"OAuth2Client",{enumerable:!0,get:function(){return h.OAuth2Client}}),Object.defineProperty(e,"ClientAuthentication",{enumerable:!0,get:function(){return h.ClientAuthentication}});var f=sr();Object.defineProperty(e,"LoginTicket",{enumerable:!0,get:function(){return f.LoginTicket}});var p=Ar();Object.defineProperty(e,"UserRefreshClient",{enumerable:!0,get:function(){return p.UserRefreshClient}});var m=Lr();Object.defineProperty(e,"AwsClient",{enumerable:!0,get:function(){return m.AwsClient}});var _=Dr();Object.defineProperty(e,"AwsRequestSigner",{enumerable:!0,get:function(){return _.AwsRequestSigner}});var y=xr();Object.defineProperty(e,"IdentityPoolClient",{enumerable:!0,get:function(){return y.IdentityPoolClient}});var g=Br();Object.defineProperty(e,"ExternalAccountClient",{enumerable:!0,get:function(){return g.ExternalAccountClient}});var E=Ir();Object.defineProperty(e,"BaseExternalAccountClient",{enumerable:!0,get:function(){return E.BaseExternalAccountClient}});var b=$r();Object.defineProperty(e,"DownscopedClient",{enumerable:!0,get:function(){return b.DownscopedClient}});var w=Fr();Object.defineProperty(e,"PluggableAuthClient",{enumerable:!0,get:function(){return w.PluggableAuthClient}}),Object.defineProperty(e,"ExecutableError",{enumerable:!0,get:function(){return w.ExecutableError}});var T=Gr();Object.defineProperty(e,"EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE",{enumerable:!0,get:function(){return T.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE}}),Object.defineProperty(e,"ExternalAccountAuthorizedUserClient",{enumerable:!0,get:function(){return T.ExternalAccountAuthorizedUserClient}});var v=Wr();Object.defineProperty(e,"PassThroughClient",{enumerable:!0,get:function(){return v.PassThroughClient}}),r(Tr(),e);var S=new n.GoogleAuth;e.auth=S}}),Yr=O({"node_modules/ws/lib/constants.js"(e,t){var r=["nodebuffer","arraybuffer","fragments"],n="undefined"!=typeof Blob;n&&r.push("blob"),t.exports={BINARY_TYPES:r,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:n,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}}}),zr=O({"node_modules/ws/lib/buffer-util.js"(e,t){var{EMPTY_BUFFER:r}=Yr(),n=Buffer[Symbol.species];function s(e,t,r,n,s){for(let o=0;o<s;o++)r[n+o]=e[o]^t[3&o]}function o(e,t){for(let r=0;r<e.length;r++)e[r]^=t[3&r]}if(t.exports={concat:function(e,t){if(0===e.length)return r;if(1===e.length)return e[0];const s=Buffer.allocUnsafe(t);let o=0;for(let t=0;t<e.length;t++){const r=e[t];s.set(r,o),o+=r.length}return o<t?new n(s.buffer,s.byteOffset,o):s},mask:s,toArrayBuffer:function(e){return e.length===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.length)},toBuffer:function e(t){if(e.readOnly=!0,Buffer.isBuffer(t))return t;let r;return t instanceof ArrayBuffer?r=new n(t):ArrayBuffer.isView(t)?r=new n(t.buffer,t.byteOffset,t.byteLength):(r=Buffer.from(t),e.readOnly=!1),r},unmask:o},!process.env.WS_NO_BUFFER_UTIL)try{const e=S("bufferutil");t.exports.mask=function(t,r,n,o,i){i<48?s(t,r,n,o,i):e.mask(t,r,n,o,i)},t.exports.unmask=function(t,r){t.length<32?o(t,r):e.unmask(t,r)}}catch(e){}}}),Jr=O({"node_modules/ws/lib/limiter.js"(e,t){var r=Symbol("kDone"),n=Symbol("kRun");t.exports=class{constructor(e){this[r]=()=>{this.pending--,this[n]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[n]()}[n](){if(this.pending!==this.concurrency&&this.jobs.length){const e=this.jobs.shift();this.pending++,e(this[r])}}}}}),Kr=O({"node_modules/ws/lib/permessage-deflate.js"(e,t){var r,n=S("zlib"),s=zr(),o=Jr(),{kStatusCode:i}=Yr(),a=Buffer[Symbol.species],c=Buffer.from([0,0,255,255]),l=Symbol("permessage-deflate"),u=Symbol("total-length"),d=Symbol("callback"),h=Symbol("buffers"),f=Symbol("error");function p(e){this[h].push(e),this[u]+=e.length}function m(e){this[u]+=e.length,this[l]._maxPayload<1||this[u]<=this[l]._maxPayload?this[h].push(e):(this[f]=new RangeError("Max payload size exceeded"),this[f].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[f][i]=1009,this.removeListener("data",m),this.reset())}function _(e){this[l]._inflate=null,this[f]?this[d](this[f]):(e[i]=1007,this[d](e))}t.exports=class{constructor(e,t,n){if(this._maxPayload=0|n,this._options=e||{},this._threshold=void 0!==this._options.threshold?this._options.threshold:1024,this._isServer=!!t,this._deflate=null,this._inflate=null,this.params=null,!r){const e=void 0!==this._options.concurrencyLimit?this._options.concurrencyLimit:10;r=new o(e)}}static get extensionName(){return"permessage-deflate"}offer(){const e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:null==this._options.clientMaxWindowBits&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){const e=this._deflate[d];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){const t=this._options,r=e.find((e=>!(!1===t.serverNoContextTakeover&&e.server_no_context_takeover||e.server_max_window_bits&&(!1===t.serverMaxWindowBits||"number"==typeof t.serverMaxWindowBits&&t.serverMaxWindowBits>e.server_max_window_bits)||"number"==typeof t.clientMaxWindowBits&&!e.client_max_window_bits)));if(!r)throw new Error("None of the extension offers can be accepted");return t.serverNoContextTakeover&&(r.server_no_context_takeover=!0),t.clientNoContextTakeover&&(r.client_no_context_takeover=!0),"number"==typeof t.serverMaxWindowBits&&(r.server_max_window_bits=t.serverMaxWindowBits),"number"==typeof t.clientMaxWindowBits?r.client_max_window_bits=t.clientMaxWindowBits:!0!==r.client_max_window_bits&&!1!==t.clientMaxWindowBits||delete r.client_max_window_bits,r}acceptAsClient(e){const t=e[0];if(!1===this._options.clientNoContextTakeover&&t.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(t.client_max_window_bits){if(!1===this._options.clientMaxWindowBits||"number"==typeof this._options.clientMaxWindowBits&&t.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"')}else"number"==typeof this._options.clientMaxWindowBits&&(t.client_max_window_bits=this._options.clientMaxWindowBits);return t}normalizeParams(e){return e.forEach((e=>{Object.keys(e).forEach((t=>{let r=e[t];if(r.length>1)throw new Error(`Parameter "${t}" must have only a single value`);if(r=r[0],"client_max_window_bits"===t){if(!0!==r){const e=+r;if(!Number.isInteger(e)||e<8||e>15)throw new TypeError(`Invalid value for parameter "${t}": ${r}`);r=e}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${t}": ${r}`)}else if("server_max_window_bits"===t){const e=+r;if(!Number.isInteger(e)||e<8||e>15)throw new TypeError(`Invalid value for parameter "${t}": ${r}`);r=e}else{if("client_no_context_takeover"!==t&&"server_no_context_takeover"!==t)throw new Error(`Unknown parameter "${t}"`);if(!0!==r)throw new TypeError(`Invalid value for parameter "${t}": ${r}`)}e[t]=r}))})),e}decompress(e,t,n){r.add((r=>{this._decompress(e,t,((e,t)=>{r(),n(e,t)}))}))}compress(e,t,n){r.add((r=>{this._compress(e,t,((e,t)=>{r(),n(e,t)}))}))}_decompress(e,t,r){const o=this._isServer?"client":"server";if(!this._inflate){const e=`${o}_max_window_bits`,t="number"!=typeof this.params[e]?n.Z_DEFAULT_WINDOWBITS:this.params[e];this._inflate=n.createInflateRaw({...this._options.zlibInflateOptions,windowBits:t}),this._inflate[l]=this,this._inflate[u]=0,this._inflate[h]=[],this._inflate.on("error",_),this._inflate.on("data",m)}this._inflate[d]=r,this._inflate.write(e),t&&this._inflate.write(c),this._inflate.flush((()=>{const e=this._inflate[f];if(e)return this._inflate.close(),this._inflate=null,void r(e);const n=s.concat(this._inflate[h],this._inflate[u]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[u]=0,this._inflate[h]=[],t&&this.params[`${o}_no_context_takeover`]&&this._inflate.reset()),r(null,n)}))}_compress(e,t,r){const o=this._isServer?"server":"client";if(!this._deflate){const e=`${o}_max_window_bits`,t="number"!=typeof this.params[e]?n.Z_DEFAULT_WINDOWBITS:this.params[e];this._deflate=n.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:t}),this._deflate[u]=0,this._deflate[h]=[],this._deflate.on("data",p)}this._deflate[d]=r,this._deflate.write(e),this._deflate.flush(n.Z_SYNC_FLUSH,(()=>{if(!this._deflate)return;let e=s.concat(this._deflate[h],this._deflate[u]);t&&(e=new a(e.buffer,e.byteOffset,e.length-4)),this._deflate[d]=null,this._deflate[u]=0,this._deflate[h]=[],t&&this.params[`${o}_no_context_takeover`]&&this._deflate.reset(),r(null,e)}))}}}}),Xr=O({"node_modules/ws/lib/validation.js"(e,t){var{isUtf8:r}=S("buffer"),{hasBlob:n}=Yr();function s(e){const t=e.length;let r=0;for(;r<t;)if(128&e[r])if(192==(224&e[r])){if(r+1===t||128!=(192&e[r+1])||192==(254&e[r]))return!1;r+=2}else if(224==(240&e[r])){if(r+2>=t||128!=(192&e[r+1])||128!=(192&e[r+2])||224===e[r]&&128==(224&e[r+1])||237===e[r]&&160==(224&e[r+1]))return!1;r+=3}else{if(240!=(248&e[r]))return!1;if(r+3>=t||128!=(192&e[r+1])||128!=(192&e[r+2])||128!=(192&e[r+3])||240===e[r]&&128==(240&e[r+1])||244===e[r]&&e[r+1]>143||e[r]>244)return!1;r+=4}else r++;return!0}if(t.exports={isBlob:function(e){return n&&"object"==typeof e&&"function"==typeof e.arrayBuffer&&"string"==typeof e.type&&"function"==typeof e.stream&&("Blob"===e[Symbol.toStringTag]||"File"===e[Symbol.toStringTag])},isValidStatusCode:function(e){return e>=1e3&&e<=1014&&1004!==e&&1005!==e&&1006!==e||e>=3e3&&e<=4999},isValidUTF8:s,tokenChars:[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0]},r)t.exports.isValidUTF8=function(e){return e.length<24?s(e):r(e)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{const e=S("utf-8-validate");t.exports.isValidUTF8=function(t){return t.length<32?s(t):e(t)}}catch(e){}}}),Zr=O({"node_modules/ws/lib/receiver.js"(e,t){var{Writable:r}=S("stream"),n=Kr(),{BINARY_TYPES:s,EMPTY_BUFFER:o,kStatusCode:i,kWebSocket:a}=Yr(),{concat:c,toArrayBuffer:l,unmask:u}=zr(),{isValidStatusCode:d,isValidUTF8:h}=Xr(),f=Buffer[Symbol.species];t.exports=class extends r{constructor(e={}){super(),this._allowSynchronousEvents=void 0===e.allowSynchronousEvents||e.allowSynchronousEvents,this._binaryType=e.binaryType||s[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=0|e.maxPayload,this._skipUTF8Validation=!!e.skipUTF8Validation,this[a]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=0}_write(e,t,r){if(8===this._opcode&&0==this._state)return r();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(r)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){const t=this._buffers[0];return this._buffers[0]=new f(t.buffer,t.byteOffset+e,t.length-e),new f(t.buffer,t.byteOffset,e)}const t=Buffer.allocUnsafe(e);do{const r=this._buffers[0],n=t.length-e;e>=r.length?t.set(this._buffers.shift(),n):(t.set(new Uint8Array(r.buffer,r.byteOffset,e),n),this._buffers[0]=new f(r.buffer,r.byteOffset+e,r.length-e)),e-=r.length}while(e>0);return t}startLoop(e){this._loop=!0;do{switch(this._state){case 0:this.getInfo(e);break;case 1:this.getPayloadLength16(e);break;case 2:this.getPayloadLength64(e);break;case 3:this.getMask();break;case 4:this.getData(e);break;case 5:case 6:return void(this._loop=!1)}}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2)return void(this._loop=!1);const t=this.consume(2);if(48&t[0]){return void e(this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3"))}const r=!(64&~t[0]);if(!r||this._extensions[n.extensionName]){if(this._fin=!(128&~t[0]),this._opcode=15&t[0],this._payloadLength=127&t[1],0===this._opcode){if(r){return void e(this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1"))}if(!this._fragmented){return void e(this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE"))}this._opcode=this._fragmented}else if(1===this._opcode||2===this._opcode){if(this._fragmented){return void e(this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE"))}this._compressed=r}else{if(!(this._opcode>7&&this._opcode<11)){return void e(this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE"))}if(!this._fin){return void e(this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN"))}if(r){return void e(this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1"))}if(this._payloadLength>125||8===this._opcode&&1===this._payloadLength){return void e(this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH"))}}if(this._fin||this._fragmented||(this._fragmented=this._opcode),this._masked=!(128&~t[1]),this._isServer){if(!this._masked){return void e(this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK"))}}else if(this._masked){return void e(this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK"))}126===this._payloadLength?this._state=1:127===this._payloadLength?this._state=2:this.haveLength(e)}else{e(this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1"))}}getPayloadLength16(e){this._bufferedBytes<2?this._loop=!1:(this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e))}getPayloadLength64(e){if(this._bufferedBytes<8)return void(this._loop=!1);const t=this.consume(8),r=t.readUInt32BE(0);if(r>Math.pow(2,21)-1){e(this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH"))}else this._payloadLength=r*Math.pow(2,32)+t.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){e(this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"))}else this._masked?this._state=3:this._state=4}getMask(){this._bufferedBytes<4?this._loop=!1:(this._mask=this.consume(4),this._state=4)}getData(e){let t=o;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength)return void(this._loop=!1);t=this.consume(this._payloadLength),this._masked&&0!==(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])&&u(t,this._mask)}if(this._opcode>7)this.controlMessage(t,e);else{if(this._compressed)return this._state=5,void this.decompress(t,e);t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}}decompress(e,t){this._extensions[n.extensionName].decompress(e,this._fin,((e,r)=>{if(e)return t(e);if(r.length){if(this._messageLength+=r.length,this._messageLength>this._maxPayload&&this._maxPayload>0){const e=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");return void t(e)}this._fragments.push(r)}this.dataMessage(t),0===this._state&&this.startLoop(t)}))}dataMessage(e){if(!this._fin)return void(this._state=0);const t=this._messageLength,r=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],2===this._opcode){let n;n="nodebuffer"===this._binaryType?c(r,t):"arraybuffer"===this._binaryType?l(c(r,t)):"blob"===this._binaryType?new Blob(r):r,this._allowSynchronousEvents?(this.emit("message",n,!0),this._state=0):(this._state=6,setImmediate((()=>{this.emit("message",n,!0),this._state=0,this.startLoop(e)})))}else{const n=c(r,t);if(!this._skipUTF8Validation&&!h(n)){const t=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");return void e(t)}5===this._state||this._allowSynchronousEvents?(this.emit("message",n,!1),this._state=0):(this._state=6,setImmediate((()=>{this.emit("message",n,!1),this._state=0,this.startLoop(e)})))}}controlMessage(e,t){if(8!==this._opcode)this._allowSynchronousEvents?(this.emit(9===this._opcode?"ping":"pong",e),this._state=0):(this._state=6,setImmediate((()=>{this.emit(9===this._opcode?"ping":"pong",e),this._state=0,this.startLoop(t)})));else{if(0===e.length)this._loop=!1,this.emit("conclude",1005,o),this.end();else{const r=e.readUInt16BE(0);if(!d(r)){const e=this.createError(RangeError,`invalid status code ${r}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");return void t(e)}const n=new f(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!h(n)){const e=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");return void t(e)}this._loop=!1,this.emit("conclude",r,n),this.end()}this._state=0}}createError(e,t,r,n,s){this._loop=!1,this._errored=!0;const o=new e(r?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(o,this.createError),o.code=s,o[i]=n,o}}}}),Qr=O({"node_modules/ws/lib/sender.js"(e,t){S("stream");var r,{randomFillSync:n}=S("crypto"),s=Kr(),{EMPTY_BUFFER:o,kWebSocket:i,NOOP:a}=Yr(),{isBlob:c,isValidStatusCode:l}=Xr(),{mask:u,toBuffer:d}=zr(),h=Symbol("kByteLength"),f=Buffer.alloc(4),p=8192,m=p;function _(e,t,r){"function"==typeof r&&r(t);for(let r=0;r<e._queue.length;r++){const n=e._queue[r],s=n[n.length-1];"function"==typeof s&&s(t)}}function y(e,t,r){_(e,t,r),e.onerror(t)}t.exports=class e{constructor(e,t,r){this._extensions=t||{},r&&(this._generateMask=r,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=0,this.onerror=a,this[i]=void 0}static frame(e,t){let s,o,i=!1,a=2,c=!1;t.mask&&(s=t.maskBuffer||f,t.generateMask?t.generateMask(s):(m===p&&(void 0===r&&(r=Buffer.alloc(p)),n(r,0,p),m=0),s[0]=r[m++],s[1]=r[m++],s[2]=r[m++],s[3]=r[m++]),c=0===(s[0]|s[1]|s[2]|s[3]),a=6),"string"==typeof e?o=t.mask&&!c||void 0===t[h]?(e=Buffer.from(e)).length:t[h]:(o=e.length,i=t.mask&&t.readOnly&&!c);let l=o;o>=65536?(a+=8,l=127):o>125&&(a+=2,l=126);const d=Buffer.allocUnsafe(i?o+a:a);return d[0]=t.fin?128|t.opcode:t.opcode,t.rsv1&&(d[0]|=64),d[1]=l,126===l?d.writeUInt16BE(o,2):127===l&&(d[2]=d[3]=0,d.writeUIntBE(o,4,6)),t.mask?(d[1]|=128,d[a-4]=s[0],d[a-3]=s[1],d[a-2]=s[2],d[a-1]=s[3],c?[d,e]:i?(u(e,s,d,a,o),[d]):(u(e,s,e,0,o),[d,e])):[d,e]}close(t,r,n,s){let i;if(void 0===t)i=o;else{if("number"!=typeof t||!l(t))throw new TypeError("First argument must be a valid error code number");if(void 0!==r&&r.length){const e=Buffer.byteLength(r);if(e>123)throw new RangeError("The message must not be greater than 123 bytes");i=Buffer.allocUnsafe(2+e),i.writeUInt16BE(t,0),"string"==typeof r?i.write(r,2):i.set(r,2)}else i=Buffer.allocUnsafe(2),i.writeUInt16BE(t,0)}const a={[h]:i.length,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};0!==this._state?this.enqueue([this.dispatch,i,!1,a,s]):this.sendFrame(e.frame(i,a),s)}ping(t,r,n){let s,o;if("string"==typeof t?(s=Buffer.byteLength(t),o=!1):c(t)?(s=t.size,o=!1):(s=(t=d(t)).length,o=d.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");const i={[h]:s,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:9,readOnly:o,rsv1:!1};c(t)?0!==this._state?this.enqueue([this.getBlobData,t,!1,i,n]):this.getBlobData(t,!1,i,n):0!==this._state?this.enqueue([this.dispatch,t,!1,i,n]):this.sendFrame(e.frame(t,i),n)}pong(t,r,n){let s,o;if("string"==typeof t?(s=Buffer.byteLength(t),o=!1):c(t)?(s=t.size,o=!1):(s=(t=d(t)).length,o=d.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");const i={[h]:s,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:10,readOnly:o,rsv1:!1};c(t)?0!==this._state?this.enqueue([this.getBlobData,t,!1,i,n]):this.getBlobData(t,!1,i,n):0!==this._state?this.enqueue([this.dispatch,t,!1,i,n]):this.sendFrame(e.frame(t,i),n)}send(e,t,r){const n=this._extensions[s.extensionName];let o,i,a=t.binary?2:1,l=t.compress;"string"==typeof e?(o=Buffer.byteLength(e),i=!1):c(e)?(o=e.size,i=!1):(o=(e=d(e)).length,i=d.readOnly),this._firstFragment?(this._firstFragment=!1,l&&n&&n.params[n._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(l=o>=n._threshold),this._compress=l):(l=!1,a=0),t.fin&&(this._firstFragment=!0);const u={[h]:o,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:a,readOnly:i,rsv1:l};c(e)?0!==this._state?this.enqueue([this.getBlobData,e,this._compress,u,r]):this.getBlobData(e,this._compress,u,r):0!==this._state?this.enqueue([this.dispatch,e,this._compress,u,r]):this.dispatch(e,this._compress,u,r)}getBlobData(t,r,n,s){this._bufferedBytes+=n[h],this._state=2,t.arrayBuffer().then((t=>{if(this._socket.destroyed){const e=new Error("The socket was closed while the blob was being read");return void process.nextTick(_,this,e,s)}this._bufferedBytes-=n[h];const o=d(t);r?this.dispatch(o,r,n,s):(this._state=0,this.sendFrame(e.frame(o,n),s),this.dequeue())})).catch((e=>{process.nextTick(y,this,e,s)}))}dispatch(t,r,n,o){if(!r)return void this.sendFrame(e.frame(t,n),o);const i=this._extensions[s.extensionName];this._bufferedBytes+=n[h],this._state=1,i.compress(t,n.fin,((t,r)=>{if(this._socket.destroyed){_(this,new Error("The socket was closed while data was being compressed"),o)}else this._bufferedBytes-=n[h],this._state=0,n.readOnly=!1,this.sendFrame(e.frame(r,n),o),this.dequeue()}))}dequeue(){for(;0===this._state&&this._queue.length;){const e=this._queue.shift();this._bufferedBytes-=e[3][h],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][h],this._queue.push(e)}sendFrame(e,t){2===e.length?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],t),this._socket.uncork()):this._socket.write(e[0],t)}}}}),en=O({"node_modules/ws/lib/event-target.js"(e,t){var{kForOnEventAttribute:r,kListener:n}=Yr(),s=Symbol("kCode"),o=Symbol("kData"),i=Symbol("kError"),a=Symbol("kMessage"),c=Symbol("kReason"),l=Symbol("kTarget"),u=Symbol("kType"),d=Symbol("kWasClean"),h=class{constructor(e){this[l]=null,this[u]=e}get target(){return this[l]}get type(){return this[u]}};Object.defineProperty(h.prototype,"target",{enumerable:!0}),Object.defineProperty(h.prototype,"type",{enumerable:!0});var f=class extends h{constructor(e,t={}){super(e),this[s]=void 0===t.code?0:t.code,this[c]=void 0===t.reason?"":t.reason,this[d]=void 0!==t.wasClean&&t.wasClean}get code(){return this[s]}get reason(){return this[c]}get wasClean(){return this[d]}};Object.defineProperty(f.prototype,"code",{enumerable:!0}),Object.defineProperty(f.prototype,"reason",{enumerable:!0}),Object.defineProperty(f.prototype,"wasClean",{enumerable:!0});var p=class extends h{constructor(e,t={}){super(e),this[i]=void 0===t.error?null:t.error,this[a]=void 0===t.message?"":t.message}get error(){return this[i]}get message(){return this[a]}};Object.defineProperty(p.prototype,"error",{enumerable:!0}),Object.defineProperty(p.prototype,"message",{enumerable:!0});var m=class extends h{constructor(e,t={}){super(e),this[o]=void 0===t.data?null:t.data}get data(){return this[o]}};Object.defineProperty(m.prototype,"data",{enumerable:!0});var _={addEventListener(e,t,s={}){for(const o of this.listeners(e))if(!s[r]&&o[n]===t&&!o[r])return;let o;if("message"===e)o=function(e,r){const n=new m("message",{data:r?e:e.toString()});n[l]=this,y(t,this,n)};else if("close"===e)o=function(e,r){const n=new f("close",{code:e,reason:r.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});n[l]=this,y(t,this,n)};else if("error"===e)o=function(e){const r=new p("error",{error:e,message:e.message});r[l]=this,y(t,this,r)};else{if("open"!==e)return;o=function(){const e=new h("open");e[l]=this,y(t,this,e)}}o[r]=!!s[r],o[n]=t,s.once?this.once(e,o):this.on(e,o)},removeEventListener(e,t){for(const s of this.listeners(e))if(s[n]===t&&!s[r]){this.removeListener(e,s);break}}};function y(e,t,r){"object"==typeof e&&e.handleEvent?e.handleEvent.call(e,r):e.call(t,r)}t.exports={CloseEvent:f,ErrorEvent:p,Event:h,EventTarget:_,MessageEvent:m}}}),tn=O({"node_modules/ws/lib/extension.js"(e,t){var{tokenChars:r}=Xr();function n(e,t,r){void 0===e[t]?e[t]=[r]:e[t].push(r)}t.exports={format:function(e){return Object.keys(e).map((t=>{let r=e[t];return Array.isArray(r)||(r=[r]),r.map((e=>[t].concat(Object.keys(e).map((t=>{let r=e[t];return Array.isArray(r)||(r=[r]),r.map((e=>!0===e?t:`${t}=${e}`)).join("; ")}))).join("; "))).join(", ")})).join(", ")},parse:function(e){const t=Object.create(null);let s,o,i=Object.create(null),a=!1,c=!1,l=!1,u=-1,d=-1,h=-1,f=0;for(;f<e.length;f++)if(d=e.charCodeAt(f),void 0===s)if(-1===h&&1===r[d])-1===u&&(u=f);else if(0===f||32!==d&&9!==d){if(59!==d&&44!==d)throw new SyntaxError(`Unexpected character at index ${f}`);{if(-1===u)throw new SyntaxError(`Unexpected character at index ${f}`);-1===h&&(h=f);const r=e.slice(u,h);44===d?(n(t,r,i),i=Object.create(null)):s=r,u=h=-1}}else-1===h&&-1!==u&&(h=f);else if(void 0===o)if(-1===h&&1===r[d])-1===u&&(u=f);else if(32===d||9===d)-1===h&&-1!==u&&(h=f);else if(59===d||44===d){if(-1===u)throw new SyntaxError(`Unexpected character at index ${f}`);-1===h&&(h=f),n(i,e.slice(u,h),!0),44===d&&(n(t,s,i),i=Object.create(null),s=void 0),u=h=-1}else{if(61!==d||-1===u||-1!==h)throw new SyntaxError(`Unexpected character at index ${f}`);o=e.slice(u,f),u=h=-1}else if(c){if(1!==r[d])throw new SyntaxError(`Unexpected character at index ${f}`);-1===u?u=f:a||(a=!0),c=!1}else if(l)if(1===r[d])-1===u&&(u=f);else if(34===d&&-1!==u)l=!1,h=f;else{if(92!==d)throw new SyntaxError(`Unexpected character at index ${f}`);c=!0}else if(34===d&&61===e.charCodeAt(f-1))l=!0;else if(-1===h&&1===r[d])-1===u&&(u=f);else if(-1===u||32!==d&&9!==d){if(59!==d&&44!==d)throw new SyntaxError(`Unexpected character at index ${f}`);{if(-1===u)throw new SyntaxError(`Unexpected character at index ${f}`);-1===h&&(h=f);let r=e.slice(u,h);a&&(r=r.replace(/\\/g,""),a=!1),n(i,o,r),44===d&&(n(t,s,i),i=Object.create(null),s=void 0),o=void 0,u=h=-1}}else-1===h&&(h=f);if(-1===u||l||32===d||9===d)throw new SyntaxError("Unexpected end of input");-1===h&&(h=f);const p=e.slice(u,h);return void 0===s?n(t,p,i):(void 0===o?n(i,p,!0):n(i,o,a?p.replace(/\\/g,""):p),n(t,s,i)),t}}}}),rn=O({"node_modules/ws/lib/websocket.js"(e,t){var r=S("events"),n=S("https"),s=S("http"),o=S("net"),i=S("tls"),{randomBytes:a,createHash:c}=S("crypto");S("stream");var{URL:l}=S("url"),u=Kr(),d=Zr(),h=Qr(),{isBlob:f}=Xr(),{BINARY_TYPES:p,EMPTY_BUFFER:m,GUID:_,kForOnEventAttribute:y,kListener:g,kStatusCode:E,kWebSocket:b,NOOP:w}=Yr(),{EventTarget:{addEventListener:T,removeEventListener:v}}=en(),{format:A,parse:O}=tn(),{toBuffer:R}=zr(),C=Symbol("kAborted"),I=[8,13],k=["CONNECTING","OPEN","CLOSING","CLOSED"],N=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,P=class e extends r{constructor(t,r,n){super(),this._binaryType=p[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=m,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=e.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,null!==t?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,void 0===r?r=[]:Array.isArray(r)||("object"==typeof r&&null!==r?(n=r,r=[]):r=[r]),x(this,t,r,n)):(this._autoPong=n.autoPong,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){p.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(t,r,n){const s=new d({allowSynchronousEvents:n.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:n.maxPayload,skipUTF8Validation:n.skipUTF8Validation}),o=new h(t,this._extensions,n.generateMask);this._receiver=s,this._sender=o,this._socket=t,s[b]=this,o[b]=this,t[b]=this,s.on("conclude",F),s.on("drain",B),s.on("error",G),s.on("message",q),s.on("ping",$),s.on("pong",W),o.onerror=Y,t.setTimeout&&t.setTimeout(0),t.setNoDelay&&t.setNoDelay(),r.length>0&&t.unshift(r),t.on("close",J),t.on("data",K),t.on("end",X),t.on("error",Z),this._readyState=e.OPEN,this.emit("open")}emitClose(){if(!this._socket)return this._readyState=e.CLOSED,void this.emit("close",this._closeCode,this._closeMessage);this._extensions[u.extensionName]&&this._extensions[u.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=e.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(t,r){if(this.readyState!==e.CLOSED)if(this.readyState!==e.CONNECTING)this.readyState!==e.CLOSING?(this._readyState=e.CLOSING,this._sender.close(t,r,!this._isServer,(e=>{e||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())})),z(this)):this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();else{const e="WebSocket was closed before the connection was established";j(this,this._req,e)}}pause(){this.readyState!==e.CONNECTING&&this.readyState!==e.CLOSED&&(this._paused=!0,this._socket.pause())}ping(t,r,n){if(this.readyState===e.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");"function"==typeof t?(n=t,t=r=void 0):"function"==typeof r&&(n=r,r=void 0),"number"==typeof t&&(t=t.toString()),this.readyState===e.OPEN?(void 0===r&&(r=!this._isServer),this._sender.ping(t||m,r,n)):M(this,t,n)}pong(t,r,n){if(this.readyState===e.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");"function"==typeof t?(n=t,t=r=void 0):"function"==typeof r&&(n=r,r=void 0),"number"==typeof t&&(t=t.toString()),this.readyState===e.OPEN?(void 0===r&&(r=!this._isServer),this._sender.pong(t||m,r,n)):M(this,t,n)}resume(){this.readyState!==e.CONNECTING&&this.readyState!==e.CLOSED&&(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(t,r,n){if(this.readyState===e.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if("function"==typeof r&&(n=r,r={}),"number"==typeof t&&(t=t.toString()),this.readyState!==e.OPEN)return void M(this,t,n);const s={binary:"string"!=typeof t,mask:!this._isServer,compress:!0,fin:!0,...r};this._extensions[u.extensionName]||(s.compress=!1),this._sender.send(t||m,s,n)}terminate(){if(this.readyState!==e.CLOSED)if(this.readyState!==e.CONNECTING)this._socket&&(this._readyState=e.CLOSING,this._socket.destroy());else{const e="WebSocket was closed before the connection was established";j(this,this._req,e)}}};function x(e,t,r,o){const i={allowSynchronousEvents:!0,autoPong:!0,protocolVersion:I[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...o,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(e._autoPong=i.autoPong,!I.includes(i.protocolVersion))throw new RangeError(`Unsupported protocol version: ${i.protocolVersion} (supported versions: ${I.join(", ")})`);let d;if(t instanceof l)d=t;else try{d=new l(t)}catch(e){throw new SyntaxError(`Invalid URL: ${t}`)}"http:"===d.protocol?d.protocol="ws:":"https:"===d.protocol&&(d.protocol="wss:"),e._url=d.href;const h="wss:"===d.protocol,f="ws+unix:"===d.protocol;let p;if("ws:"===d.protocol||h||f?f&&!d.pathname?p="The URL's pathname is empty":d.hash&&(p="The URL contains a fragment identifier"):p='The URL\'s protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"',p){const t=new SyntaxError(p);if(0===e._redirects)throw t;return void D(e,t)}const m=h?443:80,y=a(16).toString("base64"),g=h?n.request:s.request,E=new Set;let b,w;if(i.createConnection=i.createConnection||(h?L:U),i.defaultPort=i.defaultPort||m,i.port=d.port||m,i.host=d.hostname.startsWith("[")?d.hostname.slice(1,-1):d.hostname,i.headers={...i.headers,"Sec-WebSocket-Version":i.protocolVersion,"Sec-WebSocket-Key":y,Connection:"Upgrade",Upgrade:"websocket"},i.path=d.pathname+d.search,i.timeout=i.handshakeTimeout,i.perMessageDeflate&&(b=new u(!0!==i.perMessageDeflate?i.perMessageDeflate:{},!1,i.maxPayload),i.headers["Sec-WebSocket-Extensions"]=A({[u.extensionName]:b.offer()})),r.length){for(const e of r){if("string"!=typeof e||!N.test(e)||E.has(e))throw new SyntaxError("An invalid or duplicated subprotocol was specified");E.add(e)}i.headers["Sec-WebSocket-Protocol"]=r.join(",")}if(i.origin&&(i.protocolVersion<13?i.headers["Sec-WebSocket-Origin"]=i.origin:i.headers.Origin=i.origin),(d.username||d.password)&&(i.auth=`${d.username}:${d.password}`),f){const e=i.path.split(":");i.socketPath=e[0],i.path=e[1]}if(i.followRedirects){if(0===e._redirects){e._originalIpc=f,e._originalSecure=h,e._originalHostOrSocketPath=f?i.socketPath:d.host;const t=o&&o.headers;if(o={...o,headers:{}},t)for(const[e,r]of Object.entries(t))o.headers[e.toLowerCase()]=r}else if(0===e.listenerCount("redirect")){const t=f?!!e._originalIpc&&i.socketPath===e._originalHostOrSocketPath:!e._originalIpc&&d.host===e._originalHostOrSocketPath;(!t||e._originalSecure&&!h)&&(delete i.headers.authorization,delete i.headers.cookie,t||delete i.headers.host,i.auth=void 0)}i.auth&&!o.headers.authorization&&(o.headers.authorization="Basic "+Buffer.from(i.auth).toString("base64")),w=e._req=g(i),e._redirects&&e.emit("redirect",e.url,w)}else w=e._req=g(i);i.timeout&&w.on("timeout",(()=>{j(e,w,"Opening handshake has timed out")})),w.on("error",(t=>{null===w||w[C]||(w=e._req=null,D(e,t))})),w.on("response",(n=>{const s=n.headers.location,a=n.statusCode;if(s&&i.followRedirects&&a>=300&&a<400){if(++e._redirects>i.maxRedirects)return void j(e,w,"Maximum redirects exceeded");let n;w.abort();try{n=new l(s,t)}catch(t){const r=new SyntaxError(`Invalid URL: ${s}`);return void D(e,r)}x(e,n,r,o)}else e.emit("unexpected-response",w,n)||j(e,w,`Unexpected server response: ${n.statusCode}`)})),w.on("upgrade",((t,r,n)=>{if(e.emit("upgrade",t),e.readyState!==P.CONNECTING)return;w=e._req=null;const s=t.headers.upgrade;if(void 0===s||"websocket"!==s.toLowerCase())return void j(e,r,"Invalid Upgrade header");const o=c("sha1").update(y+_).digest("base64");if(t.headers["sec-websocket-accept"]!==o)return void j(e,r,"Invalid Sec-WebSocket-Accept header");const a=t.headers["sec-websocket-protocol"];let l;if(void 0!==a?E.size?E.has(a)||(l="Server sent an invalid subprotocol"):l="Server sent a subprotocol but none was requested":E.size&&(l="Server sent no subprotocol"),l)return void j(e,r,l);a&&(e._protocol=a);const d=t.headers["sec-websocket-extensions"];if(void 0!==d){if(!b){return void j(e,r,"Server sent a Sec-WebSocket-Extensions header but no extension was requested")}let t;try{t=O(d)}catch(t){return void j(e,r,"Invalid Sec-WebSocket-Extensions header")}const n=Object.keys(t);if(1!==n.length||n[0]!==u.extensionName){return void j(e,r,"Server indicated an extension that was not requested")}try{b.accept(t[u.extensionName])}catch(t){return void j(e,r,"Invalid Sec-WebSocket-Extensions header")}e._extensions[u.extensionName]=b}e.setSocket(r,n,{allowSynchronousEvents:i.allowSynchronousEvents,generateMask:i.generateMask,maxPayload:i.maxPayload,skipUTF8Validation:i.skipUTF8Validation})})),i.finishRequest?i.finishRequest(w,e):w.end()}function D(e,t){e._readyState=P.CLOSING,e._errorEmitted=!0,e.emit("error",t),e.emitClose()}function U(e){return e.path=e.socketPath,o.connect(e)}function L(e){return e.path=void 0,e.servername||""===e.servername||(e.servername=o.isIP(e.host)?"":e.host),i.connect(e)}function j(e,t,r){e._readyState=P.CLOSING;const n=new Error(r);Error.captureStackTrace(n,j),t.setHeader?(t[C]=!0,t.abort(),t.socket&&!t.socket.destroyed&&t.socket.destroy(),process.nextTick(D,e,n)):(t.destroy(n),t.once("error",e.emit.bind(e,"error")),t.once("close",e.emitClose.bind(e)))}function M(e,t,r){if(t){const r=f(t)?t.size:R(t).length;e._socket?e._sender._bufferedBytes+=r:e._bufferedAmount+=r}if(r){const t=new Error(`WebSocket is not open: readyState ${e.readyState} (${k[e.readyState]})`);process.nextTick(r,t)}}function F(e,t){const r=this[b];r._closeFrameReceived=!0,r._closeMessage=t,r._closeCode=e,void 0!==r._socket[b]&&(r._socket.removeListener("data",K),process.nextTick(V,r._socket),1005===e?r.close():r.close(e,t))}function B(){const e=this[b];e.isPaused||e._socket.resume()}function G(e){const t=this[b];void 0!==t._socket[b]&&(t._socket.removeListener("data",K),process.nextTick(V,t._socket),t.close(e[E])),t._errorEmitted||(t._errorEmitted=!0,t.emit("error",e))}function H(){this[b].emitClose()}function q(e,t){this[b].emit("message",e,t)}function $(e){const t=this[b];t._autoPong&&t.pong(e,!this._isServer,w),t.emit("ping",e)}function W(e){this[b].emit("pong",e)}function V(e){e.resume()}function Y(e){const t=this[b];t.readyState!==P.CLOSED&&(t.readyState===P.OPEN&&(t._readyState=P.CLOSING,z(t)),this._socket.end(),t._errorEmitted||(t._errorEmitted=!0,t.emit("error",e)))}function z(e){e._closeTimer=setTimeout(e._socket.destroy.bind(e._socket),3e4)}function J(){const e=this[b];let t;this.removeListener("close",J),this.removeListener("data",K),this.removeListener("end",X),e._readyState=P.CLOSING,this._readableState.endEmitted||e._closeFrameReceived||e._receiver._writableState.errorEmitted||null===(t=e._socket.read())||e._receiver.write(t),e._receiver.end(),this[b]=void 0,clearTimeout(e._closeTimer),e._receiver._writableState.finished||e._receiver._writableState.errorEmitted?e.emitClose():(e._receiver.on("error",H),e._receiver.on("finish",H))}function K(e){this[b]._receiver.write(e)||this.pause()}function X(){const e=this[b];e._readyState=P.CLOSING,e._receiver.end(),this.end()}function Z(){const e=this[b];this.removeListener("error",Z),this.on("error",w),e&&(e._readyState=P.CLOSING,this.destroy())}Object.defineProperty(P,"CONNECTING",{enumerable:!0,value:k.indexOf("CONNECTING")}),Object.defineProperty(P.prototype,"CONNECTING",{enumerable:!0,value:k.indexOf("CONNECTING")}),Object.defineProperty(P,"OPEN",{enumerable:!0,value:k.indexOf("OPEN")}),Object.defineProperty(P.prototype,"OPEN",{enumerable:!0,value:k.indexOf("OPEN")}),Object.defineProperty(P,"CLOSING",{enumerable:!0,value:k.indexOf("CLOSING")}),Object.defineProperty(P.prototype,"CLOSING",{enumerable:!0,value:k.indexOf("CLOSING")}),Object.defineProperty(P,"CLOSED",{enumerable:!0,value:k.indexOf("CLOSED")}),Object.defineProperty(P.prototype,"CLOSED",{enumerable:!0,value:k.indexOf("CLOSED")}),["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach((e=>{Object.defineProperty(P.prototype,e,{enumerable:!0})})),["open","error","close","message"].forEach((e=>{Object.defineProperty(P.prototype,`on${e}`,{enumerable:!0,get(){for(const t of this.listeners(e))if(t[y])return t[g];return null},set(t){for(const t of this.listeners(e))if(t[y]){this.removeListener(e,t);break}"function"==typeof t&&this.addEventListener(e,t,{[y]:!0})}})})),P.prototype.addEventListener=T,P.prototype.removeEventListener=v,t.exports=P}}),nn=O({"node_modules/ws/lib/stream.js"(e,t){rn();var{Duplex:r}=S("stream");function n(e){e.emit("close")}function s(){!this.destroyed&&this._writableState.finished&&this.destroy()}function o(e){this.removeListener("error",o),this.destroy(),0===this.listenerCount("error")&&this.emit("error",e)}t.exports=function(e,t){let i=!0;const a=new r({...t,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return e.on("message",(function(t,r){const n=!r&&a._readableState.objectMode?t.toString():t;a.push(n)||e.pause()})),e.once("error",(function(e){a.destroyed||(i=!1,a.destroy(e))})),e.once("close",(function(){a.destroyed||a.push(null)})),a._destroy=function(t,r){if(e.readyState===e.CLOSED)return r(t),void process.nextTick(n,a);let s=!1;e.once("error",(function(e){s=!0,r(e)})),e.once("close",(function(){s||r(t),process.nextTick(n,a)})),i&&e.terminate()},a._final=function(t){e.readyState!==e.CONNECTING?null!==e._socket&&(e._socket._writableState.finished?(t(),a._readableState.endEmitted&&a.destroy()):(e._socket.once("finish",(function(){t()})),e.close())):e.once("open",(function(){a._final(t)}))},a._read=function(){e.isPaused&&e.resume()},a._write=function(t,r,n){e.readyState!==e.CONNECTING?e.send(t,n):e.once("open",(function(){a._write(t,r,n)}))},a.on("end",s),a.on("error",o),a}}}),sn=O({"node_modules/ws/lib/subprotocol.js"(e,t){var{tokenChars:r}=Xr();t.exports={parse:function(e){const t=new Set;let n=-1,s=-1,o=0;for(;o<e.length;o++){const i=e.charCodeAt(o);if(-1===s&&1===r[i])-1===n&&(n=o);else if(0===o||32!==i&&9!==i){if(44!==i)throw new SyntaxError(`Unexpected character at index ${o}`);{if(-1===n)throw new SyntaxError(`Unexpected character at index ${o}`);-1===s&&(s=o);const r=e.slice(n,s);if(t.has(r))throw new SyntaxError(`The "${r}" subprotocol is duplicated`);t.add(r),n=s=-1}}else-1===s&&-1!==n&&(s=o)}if(-1===n||-1!==s)throw new SyntaxError("Unexpected end of input");const i=e.slice(n,o);if(t.has(i))throw new SyntaxError(`The "${i}" subprotocol is duplicated`);return t.add(i),t}}}}),on=O({"node_modules/ws/lib/websocket-server.js"(e,t){var r=S("events"),n=S("http");S("stream");var{createHash:s}=S("crypto"),o=tn(),i=Kr(),a=sn(),c=rn(),{GUID:l,kWebSocket:u}=Yr(),d=/^[+/0-9A-Za-z]{22}==$/;function h(e){e._state=2,e.emit("close")}function f(){this.destroy()}function p(e,t,r,s){r=r||n.STATUS_CODES[t],s={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(r),...s},e.once("finish",e.destroy),e.end(`HTTP/1.1 ${t} ${n.STATUS_CODES[t]}\r\n`+Object.keys(s).map((e=>`${e}: ${s[e]}`)).join("\r\n")+"\r\n\r\n"+r)}function m(e,t,r,n,s){if(e.listenerCount("wsClientError")){const n=new Error(s);Error.captureStackTrace(n,m),e.emit("wsClientError",n,r,t)}else p(r,n,s)}t.exports=class extends r{constructor(e,t){if(super(),null==(e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:c,...e}).port&&!e.server&&!e.noServer||null!=e.port&&(e.server||e.noServer)||e.server&&e.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(null!=e.port?(this._server=n.createServer(((e,t)=>{const r=n.STATUS_CODES[426];t.writeHead(426,{"Content-Length":r.length,"Content-Type":"text/plain"}),t.end(r)})),this._server.listen(e.port,e.host,e.backlog,t)):e.server&&(this._server=e.server),this._server){const e=this.emit.bind(this,"connection");this._removeListeners=function(e,t){for(const r of Object.keys(t))e.on(r,t[r]);return function(){for(const r of Object.keys(t))e.removeListener(r,t[r])}}(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(t,r,n)=>{this.handleUpgrade(t,r,n,e)}})}!0===e.perMessageDeflate&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=0}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(e){if(2===this._state)return e&&this.once("close",(()=>{e(new Error("The server is not running"))})),void process.nextTick(h,this);if(e&&this.once("close",e),1!==this._state)if(this._state=1,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients&&this.clients.size?this._shouldEmitClose=!0:process.nextTick(h,this);else{const e=this._server;this._removeListeners(),this._removeListeners=this._server=null,e.close((()=>{h(this)}))}}shouldHandle(e){if(this.options.path){const t=e.url.indexOf("?");if((-1!==t?e.url.slice(0,t):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,t,r,n){t.on("error",f);const s=e.headers["sec-websocket-key"],c=e.headers.upgrade,l=+e.headers["sec-websocket-version"];if("GET"!==e.method){return void m(this,e,t,405,"Invalid HTTP method")}if(void 0===c||"websocket"!==c.toLowerCase()){return void m(this,e,t,400,"Invalid Upgrade header")}if(void 0===s||!d.test(s)){return void m(this,e,t,400,"Missing or invalid Sec-WebSocket-Key header")}if(8!==l&&13!==l){return void m(this,e,t,400,"Missing or invalid Sec-WebSocket-Version header")}if(!this.shouldHandle(e))return void p(t,400);const u=e.headers["sec-websocket-protocol"];let h=new Set;if(void 0!==u)try{h=a.parse(u)}catch(r){return void m(this,e,t,400,"Invalid Sec-WebSocket-Protocol header")}const _=e.headers["sec-websocket-extensions"],y={};if(this.options.perMessageDeflate&&void 0!==_){const r=new i(this.options.perMessageDeflate,!0,this.options.maxPayload);try{const e=o.parse(_);e[i.extensionName]&&(r.accept(e[i.extensionName]),y[i.extensionName]=r)}catch(r){return void m(this,e,t,400,"Invalid or unacceptable Sec-WebSocket-Extensions header")}}if(this.options.verifyClient){const o={origin:e.headers[""+(8===l?"sec-websocket-origin":"origin")],secure:!(!e.socket.authorized&&!e.socket.encrypted),req:e};if(2===this.options.verifyClient.length)return void this.options.verifyClient(o,((o,i,a,c)=>{if(!o)return p(t,i||401,a,c);this.completeUpgrade(y,s,h,e,t,r,n)}));if(!this.options.verifyClient(o))return p(t,401)}this.completeUpgrade(y,s,h,e,t,r,n)}completeUpgrade(e,t,r,n,a,c,d){if(!a.readable||!a.writable)return a.destroy();if(a[u])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>0)return p(a,503);const m=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${s("sha1").update(t+l).digest("base64")}`],_=new this.options.WebSocket(null,void 0,this.options);if(r.size){const e=this.options.handleProtocols?this.options.handleProtocols(r,n):r.values().next().value;e&&(m.push(`Sec-WebSocket-Protocol: ${e}`),_._protocol=e)}if(e[i.extensionName]){const t=e[i.extensionName].params,r=o.format({[i.extensionName]:[t]});m.push(`Sec-WebSocket-Extensions: ${r}`),_._extensions=e}this.emit("headers",m,n),a.write(m.concat("\r\n").join("\r\n")),a.removeListener("error",f),_.setSocket(a,c,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(_),_.on("close",(()=>{this.clients.delete(_),this._shouldEmitClose&&!this.clients.size&&process.nextTick(h,this)}))),d(_,n)}}}}),an=[async e=>{const t=await e.workspaceStore.list();if(0===t.length)return{};const r=t[0];return{id:r.id,settings:r.settings,project:r.project}},async e=>{const t=await e.roles.list(),r={};for(const n of t)r[n.name]=e.roles.summarize(n);return{index:{roles:r}}},async e=>{const t=await e.preferences.list(),r={};for(const n of t)r[n.id]=e.preferences.summarize(n);return{index:{preferences:r}}},async e=>{const t=await e.context.list(),r={};for(const n of t)r[n.key]=e.context.summarize(n);return{index:{context:r}}},async e=>{const t=await e.sessions.list(),r={};for(const n of t)r[n.id]=e.sessions.summarize(n);return{index:{sessions:r}}},async e=>{const t=await e.topics.list(),r={};for(const n of t)r[n.name]=e.topics.summarize(n);return{index:{topics:r}}},async e=>({index:{blobs:await e.blobs.getAllRecords()}})],cn=[{name:"workspace",version:"1.0.0",description:"Workspace root containing global settings and project metadata.",fields:{id:{name:"id",type:"string",required:!0},settings:{name:"settings",type:"record",required:!0},project:{name:"project",type:"record",required:!0}},indexes:[{name:"by_id",fields:["id"],type:"unique"}],constraints:[],migrations:[]},{name:"role",version:"1.0.0",description:"AI persona with a system prompt and associated preference defaults.",fields:{name:{name:"name",type:"string",required:!0},label:{name:"label",type:"string",required:!0},description:{name:"description",type:"string",required:!1},persona:{name:"persona",type:"string",required:!0},preferences:{name:"preferences",type:"array",required:!1,itemsType:"string"},topics:{name:"topics",type:"array",required:!1},constraints:{name:"constraints",type:"record",required:!1}},indexes:[{name:"by_name",fields:["name"],type:"unique"},{name:"by_label",fields:["label"],type:"normal"}],constraints:[],migrations:[]},{name:"preference",version:"1.0.0",description:"A user behavioural instruction, scoped to zero or more topics.",fields:{id:{name:"id",type:"string",required:!0},content:{name:"content",type:"string",required:!0},topics:{name:"topics",type:"array",required:!1,itemsType:"string"},timestamp:{name:"timestamp",type:"string",required:!0}},indexes:[{name:"by_id",fields:["id"],type:"unique"},{name:"by_topics",fields:["topics"],type:"normal"},{name:"by_timestamp",fields:["timestamp"],type:"btree"}],constraints:[],migrations:[]},{name:"context",version:"1.0.0",description:"Injected background knowledge, scoped to topics. Content is a discriminated union.",fields:{key:{name:"key",type:"string",required:!0},topics:{name:"topics",type:"array",required:!1,itemsType:"string"},content:{name:"content",type:"record",required:!0},timestamp:{name:"timestamp",type:"string",required:!0},metadata:{name:"metadata",type:"record",required:!1}},indexes:[{name:"by_key",fields:["key"],type:"unique"},{name:"by_topics",fields:["topics"],type:"normal"},{name:"by_timestamp",fields:["timestamp"],type:"btree"}],constraints:[],migrations:[]},{name:"session",version:"1.0.0",description:"Session metadata. The head field tracks the current tip of the turn DAG.",fields:{id:{name:"id",type:"string",required:!0},label:{name:"label",type:"string",required:!0},role:{name:"role",type:"string",required:!0},topics:{name:"topics",type:"array",required:!1,itemsType:"string"},preferences:{name:"preferences",type:"array",required:!1,itemsType:"string"},metadata:{name:"metadata",type:"record",required:!1},head:{name:"head",type:"record",required:!1},constraints:{name:"constraints",type:"record",required:!1}},indexes:[{name:"by_id",fields:["id"],type:"unique"},{name:"by_role",fields:["role"],type:"normal"}],constraints:[],migrations:[]},{name:"turn",version:"1.0.0",description:["A single message in a session transcript, stored as a flat document.","The DAG is reconstructed in memory by TurnTree.buildNodeGraph() at session open time."].join(" "),fields:{id:{name:"id",type:"string",required:!0},session:{name:"session",type:"string",required:!0},version:{name:"version",type:"number",required:!0},actor:{name:"actor",type:"enum",required:!0,values:["user","assistant","tool"]},blocks:{name:"blocks",type:"array",required:!0},timestamp:{name:"timestamp",type:"string",required:!0},role:{name:"role",type:"string",required:!1},parent:{name:"parent",type:"record",required:!1},constraints:{name:"constraints",type:"record",required:!1}},indexes:[{name:"by_session",fields:["session"],type:"normal"},{name:"by_session_parent",fields:["session","parent"],type:"composite"},{name:"by_session_id_ver",fields:["session","id","version"],type:"composite",unique:!0}],constraints:[],migrations:[]},{name:"topic",version:"1.0.0",description:"A categorization for context and preferences, used for retrieval.",fields:{name:{name:"name",type:"string",required:!0},label:{name:"label",type:"string",required:!1},description:{name:"description",type:"string",required:!1},metadata:{name:"metadata",type:"record",required:!1},created:{name:"created",type:"string",required:!0},updated:{name:"updated",type:"string",required:!0}},indexes:[{name:"by_name",fields:["name"],type:"unique"}],constraints:[],migrations:[]}],ln=class e extends Error{constructor(t,r){super(t,{cause:r}),this.name="SyncError",Object.setPrototypeOf(this,e.prototype)}},un=class extends ln{constructor(e){super(`[ArtifactContainer] Operation timed out: ${e}`)}},dn=class extends ln{constructor(e){super("[Serializer] The serializer has been marked as done!",e)}},hn=class{_locked=!1;_capacity;_yieldMode;waiters=[];constructor(e){this._capacity=e?.capacity??1/0,this._yieldMode=e?.yieldMode??"macrotask"}async lock(e){if(!this._locked)return void(this._locked=!0);if(this.waiters.length>=this._capacity)throw new Error(`Mutex queue is full (capacity: ${this._capacity})`);let t;const r=new Promise((e=>t=e));if(this.waiters.push(t),null==e)return void await r;let n;await Promise.race([r.then((()=>clearTimeout(n))),new Promise(((r,s)=>{n=setTimeout((()=>{const e=this.waiters.indexOf(t);-1!==e&&this.waiters.splice(e,1),s(new un("Mutex lock timed out"))}),e)}))])}tryLock(){return!this._locked&&(this._locked=!0,!0)}unlock(){if(!this._locked)throw new Error("Mutex is not locked");const e=this.waiters.shift();e?"microtask"===this._yieldMode?queueMicrotask(e):setTimeout(e,0):this._locked=!1}locked(){return this._locked}pending(){return this.waiters.length}},fn=class{mutex=new hn({yieldMode:"microtask"});promise=null;_value=null;_error;_done=!1;retry;throws;constructor({retry:e,throws:t}={}){this.retry=Boolean(e),this.throws=Boolean(t)}async do(e,t){return this._done?this.peek():this.promise?this._awaitWithTimeout(this.promise,t,"Once do() timed out"):(await this.mutex.lock(),this.promise?(this.mutex.unlock(),this._awaitWithTimeout(this.promise,t,"Once do() timed out")):(this.promise=(async()=>{try{this._value=await e(),this._done=!0}catch(e){if(this._error=e,this.retry||(this._done=!0),this.throws)throw e}finally{this.retry&&!this._done&&(this.promise=null)}return this.peek()})(),this.mutex.unlock(),this._awaitWithTimeout(this.promise,t,"Once do() timed out")))}doSync(e){if(this._done){if(this.throws&&this._error)throw this._error;return this.peek()}if(this.promise){const e=new Error("Cannot execute doSync while an async operation is pending.");if(this.throws)throw e;return{value:null,error:e}}if(!this.mutex.tryLock()){const e=new Error("Cannot execute doSync: lock is currently held.");if(this.throws)throw e;return{value:null,error:e}}if(this.promise||this._done){if(this.mutex.unlock(),this._done){if(this.throws&&this._error)throw this._error;return this.peek()}const e=new Error("Cannot execute doSync while an async operation is pending.");if(this.throws)throw e;return{value:null,error:e}}try{const t=e();this._value=t,this._done=!0}catch(e){if(this._error=e,this.retry||(this._done=!0),this.throws)throw e}finally{this.mutex.unlock()}return this.peek()}running(){return null!==this.promise&&!this.done()}peek(){return{value:this._value,error:this._error}}get(){if(!this._done)throw new Error("Once operation is not yet complete");if(this._error)throw this._error;return this._value}reset(){if(this.running())throw new Error("Cannot reset Once while an operation is in progress.");this._done=!1,this.promise=null,this._value=null,this._error=void 0}done(){return this._done}current(){return this.promise}_awaitWithTimeout(e,t,r="Operation timed out"){if(null==t)return e;let n;return Promise.race([e.then((e=>(clearTimeout(n),e))),new Promise(((e,s)=>{n=setTimeout((()=>s(new un(r))),t)}))])}},pn=class{mutex;_done=!1;_lastValue=null;_lastError=void 0;_hasRun=!1;constructor(e){this.mutex=new hn({capacity:e?.capacity??1e3,yieldMode:e?.yieldMode??"macrotask"})}async do(e,t){if(this._done)return{value:null,error:new dn};try{await this.mutex.lock(t)}catch(e){return{value:null,error:e}}let r,n=null;try{if(this._done)throw new dn;n=await e(),this._lastValue=n,this._lastError=void 0,this._hasRun=!0}catch(e){r=e,this._lastError=e,this._hasRun=!0}finally{this.mutex.unlock()}return{value:n,error:r}}peek(){return{value:this._lastValue,error:this._lastError}}hasRun(){return this._hasRun}close(){this._done=!0}pending(){return this.mutex.pending()}running(){return this.mutex.locked()}};function mn(e){const t=new fn({retry:!0,throws:!0}),r=new fn({retry:!0,throws:!0});return{open:async(r=[])=>(await t.do((async()=>{const t=[...cn,...r];await e.setupCollections(t)}))).value,collection:async t=>e.collection(t),close:async()=>(await r.do((()=>{e.close()}))).value,database:()=>e}}var _n={WORKSPACE:"workspace",ROLE:"role",PREFERENCE:"preference",CONTEXT:"context",SESSION:"session",TURN:"turn",BLOB:"blob",TOPIC:"topic"},yn=Symbol.for("delete"),gn=e=>Array.isArray(e)?[...e]:{...e};function En(e){return{ok:!0,value:e}}function bn(e){return{ok:!1,error:e}}var wn=function(e){const t=e?.deleteMarker||yn;function r(e){if(null==e)return e;if(Array.isArray(e))return e.filter((e=>e!==t)).map((e=>"object"!=typeof e||null===e||Array.isArray(e)?e:r(e)));if("object"==typeof e){const n={};for(const[s,o]of Object.entries(e))if(o!==t)if("object"==typeof o&&null!==o){const e=r(o);void 0!==e&&(n[s]=e)}else n[s]=o;return n}return e===t?void 0:e}return function(e,n){if("object"!=typeof e||null===e)return"object"==typeof n&&null!==n?r(n):n===t?{}:n;if("object"!=typeof n||null===n)return e;const s=gn(e),o=[{target:s,source:n}];for(;o.length>0;){const{target:e,source:r}=o.pop();for(const n of Object.keys(r)){const s=r[n];if(s!==t)if(Array.isArray(s))e[n]=s;else if("object"==typeof s&&null!==s){const t=n in e&&"object"==typeof e[n]&&null!==e[n]?e[n]:{};e[n]=gn(t),o.push({target:e[n],source:s})}else e[n]=s;else delete e[n]}}return s}}({deleteMarker:yn});async function Tn(e){const t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t)).map((e=>e.toString(16).padStart(2,"0"))).join("")}function vn(e){if("undefined"!=typeof Buffer)return Buffer.from(e).toString("base64");const t=[];for(let r=0;r<e.length;r+=32768){const n=e.subarray(r,r+32768);t.push(String.fromCharCode.apply(null,Array.from(n)))}return btoa(t.join(""))}var Sn=class{registry=new Map;middlewares=[];serializer=new pn;bus;_getWorkspace;updateWorkspace;guard;_ctx;constructor(e){this._ctx=e.ctx,this._getWorkspace=e.getWorkspace,this.updateWorkspace=e.updateWorkspace,this.guard=e.guard,this.bus=e.bus}register(e,t){return this.registry.set(e,t),this}use(e){return this.middlewares.push(e),this}workspace(){return this._getWorkspace()}async dispatch(e){const t=await this.serializer.do((async()=>{if(this.guard){const t=await this.guard.authenticate({type:"command",payload:e});if(!t.ok)return bn(t.error)}const t=this.registry.get(e.type);if(!t)return bn({code:"INVALID_COMMAND",reason:`No reducer registered for command type: ${e.type}`});const r=this._getWorkspace(),n=await t({workspace:r,...this._ctx},e.payload);if(!n.ok)return n;let s=n.value;for(const t of this.middlewares){const n=await t({workspace:r,command:e,patch:s,...this._ctx});s=wn(s,n)}return await this.updateWorkspace(s),this.bus.emit({name:"workspace:changed",payload:s}),"workspace:sync"===e.type&&this.bus.emit({name:"workspace:synced",payload:void 0}),En(s)}));if(t.error)throw t.error;return t.value}subscribe(e,t){return this.bus.subscribe(e,t)}ctx(){return{workspace:this._getWorkspace(),...this._ctx}}},An=class{constructor(e,t){this.collection=e,this.cache=t}async get(e){const t=this.cache.get(e);if(t)return t;const r=await this.collection.find({field:"name",operator:"eq",value:e});if(!r)return null;const n=r.state();return this.cache.set(e,n),n}async add(e){await this.collection.create(e),this.cache.set(e.name,e)}async update(e,t){const r=await this.collection.find({field:"name",operator:"eq",value:e});if(!r)return null;await r.update(t);const n=r.state();return this.cache.set(e,n),n}async delete(e){const t=await this.collection.find({field:"name",operator:"eq",value:e});if(!t)return!1;const r=await t.delete();return r&&this.cache.delete(e),r}async getMany(e){if(0===e.length)return[];const t=[],r=[];for(const n of e){const e=this.cache.get(n);e?t.push(e):r.push(n)}if(r.length>0){const e=await this.collection.filter({operator:"or",conditions:r.map((e=>({field:"name",operator:"eq",value:e})))});for(const r of e){const e=r.state();this.cache.set(e.name,e),t.push(e)}}return t}async list(){const e=await this.collection.list({limit:1e3,type:"cursor",direction:"forward"});return((await e.next()).value||[]).map((e=>e.state()))}referencedBy(e,t){for(const r in t.roles)if(t.roles[r].topics?.includes(e))return!0;for(const r in t.sessions)if(t.sessions[r].topics?.includes(e))return!0;for(const r in t.context)if(t.context[r].topics?.includes(e))return!0;for(const r in t.preferences)if(t.preferences[r].topics?.includes(e))return!0;return!1}summarize(e){return{topic:e.name,contextKeys:[],preferences:[],metadata:{created:e.created,updated:e.updated,entries:0}}}};function On(e,t,r,n,s,o){const i={};for(const a of t){let t=e[a];if(!t){if("add"!==s||!o)continue;t={topic:a,contextKeys:[],preferences:[],metadata:{created:(new Date).toISOString(),updated:(new Date).toISOString(),entries:0}},o.add({name:a,created:t.metadata.created,updated:t.metadata.updated})}const c=t[n],l=c.includes(r);if("add"!==s||l){if("remove"===s&&l){const e=Math.max(0,(t.metadata.entries||0)-1);i[a]={...t,[n]:c.filter((e=>e!==r)),metadata:{...t.metadata,updated:(new Date).toISOString(),entries:e}}}}else i[a]={...t,[n]:[...c,r],metadata:{...t.metadata,updated:(new Date).toISOString(),entries:(t.metadata.entries||0)+1}}}return{index:{topics:i}}}function Rn(e,t,r,n){return On(e,t,r,"contextKeys","add",n)}function Cn(e,t,r){return On(e,t,r,"contextKeys","remove")}function In(e,t,r,n){return On(e,t,r,"preferences","add",n)}function kn(e,t,r){return On(e,t,r,"preferences","remove")}var Nn=async e=>{if(!e.patch)return;const{workspace:t,patch:r}=e,n=t.index.topics;let s={};const o=e=>{const t=e?.index?.topics;t&&(s=wn(s,t))};if(r.index?.context)for(const[s,i]of Object.entries(r.index.context)){const r=t.index.context[s];if(void 0===i&&r)o(Cn(n,r.topics,r.key));else if(r||!i){if(r&&i){const t=r.topics??[],s=i.topics??t,a=s.filter((e=>!t.includes(e))),c=t.filter((e=>!s.includes(e)));c.length&&o(Cn(n,c,r.key)),a.length&&o(Rn(n,a,r.key,e.topics))}}else o(Rn(n,i.topics??[],i.key,e.topics))}if(r.index?.preferences)for(const[s,i]of Object.entries(r.index.preferences)){const r=t.index.preferences[s];if(void 0===i&&r)o(kn(n,r.topics,r.id));else if(r||!i){if(r&&i){const t=r.topics??[],s=i.topics??t,a=s.filter((e=>!t.includes(e))),c=t.filter((e=>!s.includes(e)));c.length&&o(kn(n,c,r.id)),a.length&&o(In(n,a,r.id,e.topics))}}else o(In(n,i.topics??[],i.id,e.topics))}return Object.keys(s).length?{index:{topics:s}}:{}},Pn="\n# WORKSPACE OPERATING SYSTEM\nYou are operating within a structured workspace. Your output MUST be a JSON object matching the provided schema.\nYour entire response MUST be valid JSON. Nothing else.\n".trim();function xn(e){if(!e||"append"===e)return{placement:"append",label:null};if("prepend"===e)return{placement:"prepend",label:null};const[t,...r]=e.split(":");return("before"===t||"after"===t)&&r.length>0?{placement:t,label:r.join(":")}:(console.warn(`[SystemPromptAssembler] Unrecognised position "${e}", defaulting to "append".`),{placement:"append",label:null})}var Dn=class{build(e,t=[]){const r=[...e.system.extensions||[],...t],n=[];var s,o,i;n.push({label:"operating-system",content:Pn}),e.role.persona&&n.push({label:"persona",content:(s=e.role.persona,`# Persona\n${s}`)}),e.system.preferences.length>0&&n.push({label:"preferences",content:(o=e.system.preferences,`# User Preferences\n${o.map((e=>`- ${e.content}`)).join("\n")}`),metadata:{count:e.system.preferences.length}}),e.system.context.length>0&&n.push({label:"context",content:(i=e.system.context,`# Context\n${i.map((e=>{switch(e.content.kind){case"text":return`[${e.key}] ${e.content.value}`;case"json":return`[${e.key}] JSON: ${JSON.stringify(e.content.value)}`;case"blob":return`[${e.key}] Blob: ${e.content.filename??"unnamed"} (${e.content.mediaType}, ${e.content.sizeBytes} bytes)`;case"remote":return`[${e.key}] Remote: ${e.content.uri}`;default:return`[${e.key}] Unsupported context type`}})).join("\n")}`),metadata:{count:e.system.context.length}}),e.system.instructions&&n.push({label:"instructions",content:`# Instructions\n${e.system.instructions}`});const a=[...n],c=[];for(const e of r){const{position:t,...r}=e,n=xn(t);if("prepend"===n.placement){c.push(r);continue}if("append"===n.placement){a.push(r);continue}const s=a.findIndex((e=>e.label===n.label));if(-1===s){console.warn(`[SystemPromptAssembler] Anchor target "${n.label}" not found in sections. Extension "${e.label}" will be appended.`),a.push(r);continue}const o="before"===n.placement?s:s+1;a.splice(o,0,r)}return[...c,...a]}join(e){return e.map((e=>e.content)).join("\n\n---\n\n")}};var Un={"workspace:create":async function(e,t){const{workspaceStore:r}=e,{id:n,settings:s,project:o}=t;return await r.add({id:n,settings:s,project:o}),En({id:n,settings:s,project:o})},"workspace:sync":async function(e,t){let r={};t&&(t.id&&(r.id=t.id),t.settings&&(r.settings=t.settings),t.project&&(r.project=t.project));for(const t of e.indexers){const n=await t(e);r=wn(r,n)}return En(r)},"role:add":async function(e,t){const{workspace:r,roles:n}=e,s=t;return r.index.roles[s.name]?bn({code:"DUPLICATE_KEY",resource:"Role",key:s.name}):(await n.add(s),En({index:{roles:{[s.name]:n.summarize(s)}}}))},"role:update":async function(e,t){const{workspace:r,roles:n}=e,{name:s,...o}=t;if(!r.index.roles[s])return bn({code:"NOT_FOUND",resource:"Role",id:s});const i=await n.update(s,o);return i?En({index:{roles:{[s]:n.summarize(i)}}}):bn({code:"BACKEND_ERROR",reason:`Failed to update role ${s} in store.`})},"role:delete":async function(e,t){const{workspace:r,roles:n}=e,{name:s}=t;return r.index.roles[s]?await n.delete(s)?En({index:{roles:{[s]:yn}}}):bn({code:"BACKEND_ERROR",reason:`Failed to delete role ${s} from store.`}):bn({code:"NOT_FOUND",resource:"Role",id:s})},"preference:add":async function(e,t){const{workspace:r,preferences:n}=e,s=t;return r.index.preferences[s.id]?bn({code:"DUPLICATE_KEY",resource:"Preference",key:s.id}):(await n.add(s),En({index:{preferences:{[s.id]:n.summarize(s)}}}))},"preference:update":async function(e,t){const{workspace:r,preferences:n}=e,{id:s,...o}=t;if(!r.index.preferences[s])return bn({code:"NOT_FOUND",resource:"Preference",id:s});const i=await n.update(s,o);return i?En({index:{preferences:{[s]:n.summarize(i)}}}):bn({code:"BACKEND_ERROR",reason:`Failed to update preference ${s} in store.`})},"preference:delete":async function(e,t){const{workspace:r,preferences:n}=e,{id:s}=t;return r.index.preferences[s]?await n.delete(s)?En({index:{preferences:{[s]:yn}}}):bn({code:"BACKEND_ERROR",reason:`Failed to delete preference ${s} from store.`}):bn({code:"NOT_FOUND",resource:"Preference",id:s})},"context:add":async function(e,t){const{workspace:r,context:n}=e,s=t;return r.index.context[s.key]?bn({code:"DUPLICATE_KEY",resource:"Context",key:s.key}):(await n.add(s),En({index:{context:{[s.key]:n.summarize(s)}}}))},"context:update":async function(e,t){const{workspace:r,context:n}=e,{key:s,...o}=t,i=r.index.context[s];if(!i)return bn({code:"NOT_FOUND",resource:"Context",id:s});const a=await n.update(s,o,i.kind);return a?En({index:{context:{[s]:n.summarize(a)}}}):bn({code:"BACKEND_ERROR",reason:`Failed to update context ${s} in store.`})},"context:delete":async function(e,t){const{workspace:r,context:n}=e,{key:s}=t,o=r.index.context[s];return o?await n.delete(s,o.kind)?En({index:{context:{[s]:yn}}}):bn({code:"BACKEND_ERROR",reason:`Failed to delete context ${s} from store.`}):bn({code:"NOT_FOUND",resource:"Context",id:s})},"topic:add":async function(e,t){const{workspace:r,topics:n}=e,s=t;return r.index.topics[s.name]?bn({code:"DUPLICATE_KEY",resource:"Topic",key:s.name}):(await n.add(s),En({index:{topics:{[s.name]:n.summarize(s)}}}))},"topic:update":async function(e,t){const{workspace:r,topics:n}=e,{name:s,...o}=t;if(!r.index.topics[s])return bn({code:"NOT_FOUND",resource:"Topic",id:s});const i=await n.update(s,o);return i?En({index:{topics:{[s]:{metadata:{updated:i.updated}}}}}):bn({code:"BACKEND_ERROR",reason:`Failed to update topic ${s} in store.`})},"topic:delete":async function(e,t){const{workspace:r,topics:n,roles:s,sessions:o}=e,{name:i,cascade:a}=t;if(!r.index.topics[i])return bn({code:"NOT_FOUND",resource:"Topic",id:i});if(n.referencedBy(i,r.index)&&!a)return bn({code:"INVALID_COMMAND",reason:`Topic '${i}' is referenced by other entities. Use 'cascade: true' to force deletion.`});if(a){for(const e in r.index.roles){const t=r.index.roles[e];if(t.topics?.includes(i)){const t=await s.get(e);t&&await s.update(e,{topics:t.topics.filter((e=>e!==i))})}}for(const e in r.index.sessions){const t=r.index.sessions[e];t.topics?.includes(i)&&await o.update(e,{topics:t.topics.filter((e=>e!==i))})}}return await n.delete(i)?En({index:{topics:{[i]:yn}}}):bn({code:"BACKEND_ERROR",reason:`Failed to delete topic ${i} from store.`})},"topic:merge":async function(e,t){const{workspace:r,topics:n,roles:s,sessions:o}=e,{source:i,target:a}=t;if(!r.index.topics[i]||!r.index.topics[a])return bn({code:"NOT_FOUND",resource:"Topic",id:r.index.topics[i]?a:i});for(const e in r.index.roles){const t=r.index.roles[e];if(t.topics?.includes(i)){const t=await s.get(e);if(t){const r=t.topics.filter((e=>e!==i));r.includes(a)||r.push(a),await s.update(e,{topics:r})}}}for(const e in r.index.sessions){const t=r.index.sessions[e];if(t.topics?.includes(i)){const r=t.topics.filter((e=>e!==i));r.includes(a)||r.push(a),await o.update(e,{topics:r})}}return await n.delete(i),En({index:{topics:{[i]:yn}}})},"session:create":async function(e,t){const{workspace:r,sessions:n}=e,s=t;return r.index.sessions[s.id]?bn({code:"DUPLICATE_KEY",resource:"Session",key:s.id}):(await n.add(s),En({index:{sessions:{[s.id]:n.summarize(s)}}}))},"session:update":async function(e,t){const{workspace:r,sessions:n}=e,{sessionId:s,...o}=t;if(!r.index.sessions[s])return bn({code:"NOT_FOUND",resource:"Session",id:s});const i=await n.update(s,o);return i?En({index:{sessions:{[s]:n.summarize(i)}}}):bn({code:"BACKEND_ERROR",reason:`Failed to update session ${s} in store.`})},"session:fork":async function(e,t){const{workspace:r,sessions:n}=e,{sessionId:s,newSessionId:o,label:i}=t,a=r.index.sessions[s];if(!a)return bn({code:"NOT_FOUND",resource:"Session",id:s});const c={...a,id:o,label:i||`Fork of ${a.label}`,role:t.role?t.role:a.role,topics:t.topics?t.topics:a.topics};return await n.add(c),En({index:{sessions:{[o]:n.summarize(c)}}})},"session:delete":async function(e,t){const{workspace:r,sessions:n}=e,{sessionId:s}=t;return r.index.sessions[s]?(await n.delete(s),En({index:{sessions:{[s]:yn}}})):bn({code:"NOT_FOUND",resource:"Session",id:s})},"session:role:switch":async function(e,t){const{workspace:r,sessions:n}=e,{sessionId:s,roleName:o}=t;return r.index.sessions[s]?(await n.update(s,{role:o}),En({index:{sessions:{[s]:{role:o}}}})):bn({code:"NOT_FOUND",resource:"Session",id:s})},"session:topics:add":async function(e,t){const{workspace:r,sessions:n}=e,{sessionId:s,topics:o}=t,i=r.index.sessions[s];if(!i)return bn({code:"NOT_FOUND",resource:"Session",id:s});const a=Array.from(new Set([...i.topics,...o]));return await n.update(s,{topics:a}),En({index:{sessions:{[s]:{topics:a}}}})},"session:preferences:override":async function(e,t){const{workspace:r,sessions:n}=e,{sessionId:s,preferences:o}=t;return r.index.sessions[s]?(await n.update(s,{preferences:o}),En({index:{sessions:{[s]:{preferences:o}}}})):bn({code:"NOT_FOUND",resource:"Session",id:s})},"turn:add":async function(e,t){const{workspace:r,sessions:n,turns:s}=e,{sessionId:o,turn:i}=t;if(!r.index.sessions[o])return bn({code:"NOT_FOUND",resource:"Session",id:o});await s.add(i);const a={id:i.id,version:i.version};return await n.update(o,{head:a}),En({index:{sessions:{[o]:{head:a}}}})},"turn:update":async function(e,t){const{workspace:r,sessions:n,turns:s}=e,{sessionId:o,turn:i}=t;if(!r.index.sessions[o])return bn({code:"NOT_FOUND",resource:"Session",id:o});await s.update(i,i);const a={id:i.id,version:i.version};return await n.update(o,{head:a}),En({index:{sessions:{[o]:{head:a}}}})},"turn:edit":async function(e,t){const{workspace:r,sessions:n,turns:s}=e,{sessionId:o,turnId:i,newBlocks:a,newVersion:c,roleSnapshot:l}=t,u=r.index.sessions[o];if(!u)return bn({code:"NOT_FOUND",resource:"Session",id:o});const d=u.head;let h={};if(d&&d.id===i){const e=await s.get({id:d.id,version:d.version,session:o});e&&(h={...e})}const f={...h,id:i,version:c,blocks:a,role:l??h.role,timestamp:(new Date).toISOString(),parent:h.parent,actor:h.actor||"assistant",session:o};if(await s.add(f),u.head?.id===i){const e={id:i,version:c};return await n.update(o,{head:e}),En({index:{sessions:{[o]:{head:e}}}})}return En({})},"turn:branch":async function(e,t){const{workspace:r,sessions:n,turns:s}=e,{sessionId:o,turn:i}=t;if(!r.index.sessions[o])return bn({code:"NOT_FOUND",resource:"Session",id:o});await s.add(i);const a={id:i.id,version:i.version};return await n.update(o,{head:a}),En({index:{sessions:{[o]:{head:a}}}})},"turn:delete":async function(e,t){const{workspace:r,sessions:n,turns:s}=e,{sessionId:o,turnId:i,newHead:a}=t;return r.index.sessions[o]?(await s.delete({session:o,id:i,version:t.version}),a?(await n.update(o,{head:a}),En({index:{sessions:{[o]:{head:a}}}})):En({})):bn({code:"NOT_FOUND",resource:"Session",id:o})},"blob:register":async function(e,t){const{blobs:r}=e,n=await r.register(t.data,t.mediaType,t.filename);if(!n.ok)return n;const s=await r.getRecord(n.value.sha256);return s?En({index:{blobs:{[s.sha256]:s}}}):bn({code:"BACKEND_ERROR",reason:`Failed to retrieve registered blob record for ${n.value.sha256}`})},"blob:retain":async function(e,t){const{blobs:r}=e,n=await r.retain(t.sha256);if(!n.ok)return n;const s=await r.getRecord(t.sha256);return En({index:{blobs:{[t.sha256]:s}}})},"blob:release":async function(e,t){const{blobs:r}=e,n=await r.release(t.sha256);if(!n.ok)return n;const s=await r.getRecord(t.sha256);return En({index:{blobs:{[t.sha256]:s||yn}}})},"blob:purge":async function(e,t){const{blobs:r}=e,n=await r.purge(t.sha256);return n.ok?En({index:{blobs:{[t.sha256]:yn}}}):n},"blob:record_remote_id":async function(e,t){const{blobs:r}=e,{sha256:n,providerId:s,fileId:o,timestamp:i}=t,a=await r.recordRemoteId(n,s,o,i);if(!a.ok)return a;const c=await r.getRecord(n);return En({index:{blobs:{[n]:c}}})},"tool:call":async function(e,t){return En({})}},Ln=class{profiles;constructor(e=[]){this.profiles=new Map;for(const t of e)this.profiles.set(t.name,t)}get(e){return this.profiles.get(e)}list(e){const t=Array.from(this.profiles.values());return e?t.filter((t=>t.provider===e)):t}register(e){this.profiles.set(e.name,e)}},jn=[{type:"text",emittable:!0,description:["## Block: `text`","Primary communication block. Use for all conversational responses, explanations, and prose.","A response may contain multiple `text` blocks interleaved with other block types."].join("\n"),rules:[],schema:{type:"object",properties:{type:{type:"string",enum:["text"]},text:{type:"string",description:"The raw markdown or plain text content of the response."}},required:["type","text"]}},{type:"summary",emittable:!0,description:["## Block: `summary`","Context compression block. Replaces older conversation history with a concise digest."].join("\n"),rules:["Only emit when explicitly instructed by the system to summarise.","Never emit more than one summary block per turn.","Preserve key decisions, outcomes, and unresolved questions.","Do not summarise the current turn — only prior history."],schema:{type:"object",properties:{type:{type:"string",enum:["summary"]},text:{type:"string",description:"A concise summary replacing older conversation context."}},required:["type","text"]}},{type:"thinking",emittable:!1,description:["## Block: `thinking`","Internal chain-of-thought produced by the model before its final response.","Injected by the workspace from provider reasoning tokens — never emit it yourself."].join("\n"),rules:[],schema:{type:"object",properties:{type:{type:"string",enum:["thinking"]},thinking:{type:"string",description:"The internal reasoning text produced before the final response."}},required:["type","thinking"]}},{type:"tool:use",emittable:!1,description:["## Block: `tool:use`","Captures a model request to execute a registered tool.","Constructed by the workspace from the provider native function-call response — never emit it yourself."].join("\n"),rules:[],schema:{type:"object",properties:{type:{type:"string",enum:["tool:use"]},name:{type:"string",description:"The exact registered name of the tool to execute."},input:{type:"object",description:"The parameter arguments for the tool execution.",additionalProperties:!0}},required:["type","name","input"]}},{type:"tool:result",emittable:!1,description:["## Block: `tool:result`","Contains the output of a tool execution, including any errors.","Injected by the workspace after a tool runs — never emit it yourself."].join("\n"),rules:[],schema:{type:"object",properties:{type:{type:"string",enum:["tool:result"]},useId:{type:"string",description:"The UUID of the ToolUseBlock that triggered this execution."},content:{oneOf:[{type:"string"},{type:"object",additionalProperties:!0}],description:"The serialized output of the tool, or a structured JSON response."},isError:{type:"boolean",description:"True if the tool execution resulted in an error."}},required:["type","useId","content"]}},{type:"image",emittable:!1,description:["## Block: `image`","An image asset attached to a turn, resolved from the workspace blob store.","Constructed by the workspace from user uploads — never emit it yourself."].join("\n"),rules:[],schema:{type:"object",properties:{type:{type:"string",enum:["image"]},altText:{type:"string",description:"Accessible description of the image content."}},required:["type"]}},{type:"document",emittable:!1,description:["## Block: `document`","A document asset (PDF, DOCX, etc.) attached to a turn, resolved from the workspace blob store.","Constructed by the workspace from user uploads — never emit it yourself."].join("\n"),rules:[],schema:{type:"object",properties:{type:{type:"string",enum:["document"]},title:{type:"string",description:"Human-readable title or filename of the document."}},required:["type"]}},{type:"role:transition",emittable:!1,description:["## Block: `role:transition`","Marks that the active session persona has switched from one role to another.","Emitted by the workspace when the active persona changes — never emit it yourself."].join("\n"),rules:[],schema:{type:"object",properties:{type:{type:"string",enum:["role:transition"]},previousRole:{type:"string",description:"The name of the role the session is leaving."},newRole:{type:"string",description:"The name of the role the session is adopting."}},required:["type","newRole"]}}];function Mn(e,t){let r=e.filter((e=>e.emittable));if(!t)return r;if(t.only&&t.only.length>0){const e=new Set(t.only);return r.filter((t=>e.has(t.type)))}if(t.exclude&&t.exclude.length>0){const e=new Set(t.exclude);return r.filter((t=>!e.has(t.type)))}return r}var Fn=class{store=new Map;constructor(){for(const e of jn)this.store.set(e.type,e)}register(e){if(this.store.has(e.type))throw new Error(`[BlockRegistry] Block type "${e.type}" is already registered. Use update() to modify it.`);this.store.set(e.type,{...e,emittable:!0,rules:[]})}unregister(e){if(!this.store.has(e))throw new Error(`[BlockRegistry] Cannot unregister unknown block type "${e}".`);this.store.delete(e)}update(e,t){const r=this.store.get(e);r?this.store.set(e,{...r,...t,type:e}):this.store.set(e,{emittable:!0,rules:[],...t,type:e})}get(e){return this.store.get(e)}list(){return Array.from(this.store.values())}isType(e,t){return e.type===t}guard(e){return t=>t.type===e}schema(e){return{type:"object",description:"The model's structured response, containing an ordered sequence of content blocks.",properties:{blocks:{type:"array",description:"An ordered array of content blocks comprising the model's response.",items:{anyOf:Mn(Array.from(this.store.values()),e).map((e=>e.schema))}}},required:["blocks"]}}description(e){return["# BLOCK TYPES & USAGE RULES","","Your response MUST be a JSON object with a `blocks` array.","Each element of `blocks` must be one of the following types:","",Mn(Array.from(this.store.values()),e).map((e=>{const t=[e.description];return e.rules.length>0&&(t.push("**Rules:**"),t.push(...e.rules.map((e=>`- ${e}`)))),t.join("\n")})).join("\n\n"),"","## GLOBAL CONSTRAINTS","","- Output must be **valid JSON only** — no prose before or after the JSON object.","- Responses may contain multiple blocks. Blocks are rendered in order.","- **Do NOT generate IDs.** The workspace is solely responsible for block ID assignment.","- Do not infer or invent fields not defined in the block schemas above."].join("\n")}rules(e){const t=Mn(Array.from(this.store.values()),e);return Object.fromEntries(t.map((e=>[e.type,[...e.rules]])))}setRules(e,t){const r=this.store.get(e);if(!r)throw new Error(`[BlockRegistry] Cannot set rules on unknown block type "${e}".`);this.store.set(e,{...r,rules:t})}parse(e,t){const r=this.store.get(e.type);if(!r)return console.warn(`[BlockRegistry] parse() received unknown block type "${e.type}". Returning null.`),null;if(t&&r.mappings?.[t])return r.mappings[t].from(e);const{id:n,...s}=e;return{id:d.v7(),...s}}create(e,t){if(!this.store.has(e))throw new Error(`[BlockRegistry] Cannot create block of unknown type "${e}".`);return{...t,id:d.v7(),type:e}}clone(e,t){return{...structuredClone(e),...t,id:d.v7()}}},Bn=class{store=new Map;constructor(){this.registerDefaults()}registerDefaults(){this.register({kind:"text",target:"system",render:e=>({id:e.key,type:"text",text:e.content.value}),toString:e=>e.content.value,summarize:e=>({key:e.key,kind:"text",topics:e.topics,timestamp:e.timestamp,preview:e.content.value.slice(0,100)})}),this.register({kind:"json",target:"system",render:e=>({id:e.key,type:"text",text:JSON.stringify(e.content.value,null,2)}),toString:e=>JSON.stringify(e.content.value),summarize:e=>({key:e.key,kind:"json",topics:e.topics,timestamp:e.timestamp,preview:"JSON Data"})}),this.register({kind:"blob",target:"transcript",render:e=>{const{sha256:t,mediaType:r,sizeBytes:n,filename:s}=e.content,o={sha256:t,mediaType:r,sizeBytes:n,filename:s};return r.startsWith("image/")?{id:e.key,type:"image",ref:o}:{id:e.key,type:"document",ref:o,title:s}},toString:e=>e.content.filename||"unnamed blob",summarize:e=>({key:e.key,kind:"blob",topics:e.topics,timestamp:e.timestamp,mime:e.content.mediaType,size:e.content.sizeBytes,preview:e.content.filename})})}register(e){if(this.store.has(e.kind))throw new Error(`[ContextRegistry] Context kind "${e.kind}" is already registered.`);this.store.set(e.kind,e)}get(e){return this.store.get(e)}list(){return Array.from(this.store.values())}},Gn="__system__",Hn=class{constructor(e,t,r){this._actor=e,this._turn=r?JSON.parse(JSON.stringify(r)):{id:d.v7(),session:t,version:0,actor:this._actor,blocks:[],timestamp:(new Date).toISOString(),role:void 0}}_turn;addText(e){const t={id:d.v7(),type:"text",text:e};return this._turn.blocks.push(t),this}addImage(e,t){const r={id:d.v7(),type:"image",ref:e,altText:t};return this._turn.blocks.push(r),this}addDocument(e,t){const r={id:d.v7(),type:"document",ref:e,title:t};return this._turn.blocks.push(r),this}addToolUse(e,t){const r={id:d.v7(),type:"tool:use",name:e,input:t};return this._turn.blocks.push(r),this}addToolResult(e,t,r){const n={id:d.v7(),type:"tool:result",useId:e,content:t,isError:r};return this._turn.blocks.push(n),this}addSummary(e){const t={id:d.v7(),type:"summary",text:e};return this._turn.blocks.push(t),this}addRoleTransition(e,t){const r={id:d.v7(),type:"role:transition",previousRole:e,newRole:t};return this._turn.blocks.push(r),this}addThinking(e){const t={id:d.v7(),type:"thinking",thinking:e};return this._turn.blocks.push(t),this}addBlock(e){return this._turn.blocks.push(e),this}deleteBlock(e){return this._turn.blocks=this._turn.blocks.filter((t=>t.id!==e)),this}editTextBlock(e,t){const r=this._turn.blocks.findIndex((t=>t.id===e));if(-1===r)throw new Error(`Block with ID ${e} not found.`);const n=this._turn.blocks[r];if("text"!==n.type)throw new Error(`Block with ID ${e} is not a TextBlock.`);return this._turn.blocks[r]={...n,text:t},this}withId(e){return this._turn.id=e,this}withVersion(e){return this._turn.version=e,this}withTimestamp(e){return this._turn.timestamp=e,this}withParent(e){return this._turn.parent=e,this}withRoleSnapshot(e){return this._turn.role=e,this}build(){return JSON.parse(JSON.stringify(this._turn))}},qn=class{constructor(e,t){this.turnStore=e,this.sessionStore=t}async loadAllTurns(e){return this.turnStore.listBySession(e)}async loadHead(e){const t=await this.sessionStore.get(e);return t?.head??null}},$n=class e{constructor(e,t){this.nodes=e,this._head=t}static async build(t,r){const[n,s]=await Promise.all([r.loadAllTurns(t),r.loadHead(t)]),o=function(e,t){const r=function(e,t){if(!t)return new Set;const r=new Map;for(const t of e)r.set(`${t.id}:${t.version}`,t);const n=new Set;let s=t;for(;s;){const e=`${s.id}:${s.version}`;if(n.has(e))break;n.add(e);const t=r.get(e);if(!t)break;s=t.parent}return n}(e,t),n={},s={};for(const t of e){n[t.id]||(n[t.id]={id:t.id,versions:{},activeVersion:t.version,actor:t.actor,blocks:t.blocks,timestamp:t.timestamp,roleSnapshot:t.role,parent:t.parent,children:{}},s[t.id]=new Set);const e=n[t.id];e.versions[t.version]=t;const o=r.has(`${t.id}:${t.version}`),i=r.has(`${t.id}:${e.activeVersion}`);if(o&&(!i||t.version>=e.activeVersion)&&(e.activeVersion=t.version,e.blocks=t.blocks,e.timestamp=t.timestamp,e.roleSnapshot=t.role,e.parent=t.parent),t.parent){const e=`${t.parent.id}:${t.parent.version}`;if(s[t.parent.id]||(s[t.parent.id]=new Set),!s[t.parent.id].has(e+":"+t.id)){s[t.parent.id].add(e+":"+t.id),n[t.parent.id]||(n[t.parent.id]={id:t.parent.id,versions:{},activeVersion:t.parent.version,actor:"user",blocks:[],timestamp:"",roleSnapshot:void 0,children:{}});const r=n[t.parent.id];r.children[t.parent.version]||(r.children[t.parent.version]=[]),r.children[t.parent.version].push(t.id)}}}return n}(n,s);return new e(o,s)}head(){return this._head}chain(){if(!this._head)return[];const e=[];let t=this._head.id;for(;t;){const r=this.nodes[t];if(!r)break;e.push(r),t=r.parent?.id??null}return e.reverse()}getTurnSiblings(e){const t=this.nodes[e];if(!t)return[];if(!t.parent)return Object.values(this.nodes).filter((e=>!e.parent));const r=this.nodes[t.parent.id];if(!r)return[t];const n=r.children[t.parent.version];return n?n.map((e=>this.nodes[e])).filter((e=>!!e)):[t]}branchInfo(e){const t=this.nodes[e];if(!t)return{versions:[],currentIndex:-1,total:0,hasPrev:!1,hasNext:!1};const r=Object.keys(t.versions).map(Number).sort(((e,t)=>e-t)),n=r.indexOf(t.activeVersion);return{versions:r,currentIndex:n,total:r.length,hasPrev:n>0,hasNext:n<r.length-1}}graph(){return{...this.nodes}}};var Wn=class{constructor(e){this.manager=e}get workspace(){return this.manager.workspace()}roles(){return this.manager.ctx().roles.list()}role(e){return this.manager.ctx().roles.get(e)}async createRole(e,t,r,n,s=[]){if(this.workspace.index.roles[e])return bn({code:"DUPLICATE_KEY",resource:"role",key:e});const o={name:e,label:t,description:n,persona:r,preferences:s,topics:[]};return this.manager.dispatch({type:"role:add",payload:o,timestamp:(new Date).toISOString()})}async updateRole(e,t){return this.workspace.index.roles[e]?this.manager.dispatch({type:"role:update",payload:{name:e,...t},timestamp:(new Date).toISOString()}):bn({code:"NOT_FOUND",resource:"role",id:e})}async deleteRole(e){const t=this.workspace;if(!t.index.roles[e])return bn({code:"NOT_FOUND",resource:"role",id:e});return Object.values(t.index.sessions).some((t=>t.role===e))?bn({code:"INVALID_COMMAND",reason:`Cannot delete role "${e}" — it is still referenced by one or more sessions`}):this.manager.dispatch({type:"role:delete",payload:{name:e},timestamp:(new Date).toISOString()})}async addPreference(e,t){const r={id:crypto.randomUUID(),content:e,topics:t,timestamp:(new Date).toISOString()};return this.manager.dispatch({type:"preference:add",payload:r,timestamp:r.timestamp})}preferences(){return this.manager.ctx().preferences.list()}async addContext(e,t,r,n){const s={key:e,topics:r,content:t,timestamp:(new Date).toISOString(),metadata:n};return this.manager.dispatch({type:"context:add",payload:s,timestamp:s.timestamp})}context(){return this.manager.ctx().context.list()}async registerBlob(e,t,r){const n=await this.manager.dispatch({type:"blob:register",payload:{data:e,mediaType:t,filename:r},timestamp:(new Date).toISOString()});if(!n.ok)return bn(n.error);const s=n.value,o=s?.index?.blobs;if(!o)return bn({code:"BACKEND_ERROR",reason:"Blob registration succeeded but no blobs patch returned"});const i=Object.keys(o)[0];if(!i)return bn({code:"BACKEND_ERROR",reason:"No SHA256 in patch"});const a=o[i];if(!a)return bn({code:"BACKEND_ERROR",reason:"Blob record missing"});return En({sha256:i,ref:{sha256:i,mediaType:a.mediaType,sizeBytes:a.sizeBytes,filename:a.filename,previewUrl:a.previewUrl}})}},Vn=class e{constructor(e,t,r,n){this._id=e,this.manager=t,this.processor=r,this.turnRepository=n,this.workspace=new Wn(t),this.unsubscribe=t.subscribe("workspace:synced",(()=>this.sync()))}workspace;_role=void 0;_preferences=[];tree;unsubscribe;static async create(t,r,n){r.ctx().workspace;const s=new qn(r.ctx().turns,r.ctx().sessions),o=new e(t,r,n,s);return await o.sync(),o}async sync(){await this._setRole(),await this._setPreference(),await this.refreshTurnTree()}close(){this.unsubscribe?.()}async _setRole(){const e=this.meta(),t=await this.manager.ctx().roles.get(e.role);t&&(this._role=t)}async _setPreference(){const e=this.meta();this._preferences=await this.manager.ctx().preferences.load(e.preferences)}id(){return this._id}ws(){return this.manager.workspace()}meta(){return this.ws().index.sessions[this._id]}label(){return this.meta()?.label}role(){return this._role}topics(){return this.meta()?.topics??[]}preferences(){return this._preferences}head(){return this.meta()?.head??null}turns(){return this.tree.chain()}async siblings(e){return this.tree.getTurnSiblings(e)}async branchInfo(e){return this.tree.branchInfo(e)}async getTurn(e){return this.tree.graph()[e]}async rename(e){return this.meta()?this.dispatch({type:"session:update",payload:{sessionId:this._id,label:e},timestamp:(new Date).toISOString()}):bn({code:"NOT_FOUND",resource:"session",id:this._id})}async setTopics(e){return this.meta()?this.dispatch({type:"session:update",payload:{sessionId:this._id,topics:e},timestamp:(new Date).toISOString()}):bn({code:"NOT_FOUND",resource:"session",id:this._id})}async addTopics(e){return this.meta()?this.dispatch({type:"session:topics:add",payload:{sessionId:this._id,topics:e},timestamp:(new Date).toISOString()}):bn({code:"NOT_FOUND",resource:"session",id:this._id})}async setPreferences(e){if(!this.meta())return bn({code:"NOT_FOUND",resource:"session",id:this._id});const t=await this.dispatch({type:"session:preferences:override",payload:{sessionId:this._id,preferences:e},timestamp:(new Date).toISOString()});return t.ok&&await this._setPreference(),t}async fork(e,t,r,n){return this.meta()?this.dispatch({type:"session:fork",payload:{sessionId:this._id,newSessionId:e,label:t,role:r,topics:n},timestamp:(new Date).toISOString()}):bn({code:"NOT_FOUND",resource:"session",id:this._id})}async dispatch(e){return this.manager.dispatch(e)}async switchRole(e){const t=this.ws();if(!this.meta())return bn({code:"NOT_FOUND",resource:"session",id:this._id});if(e!==Gn&&!t.index.roles[e])return bn({code:"NOT_FOUND",resource:"role",id:e});const r=await this.dispatch({type:"session:update",payload:{sessionId:this._id,role:e},timestamp:(new Date).toISOString()});return r.ok&&await this._setRole(),r}async addTurn(e){if(!this.meta())return bn({code:"NOT_FOUND",resource:"session",id:this._id});const t={...e,session:this._id,version:e.version??0,parent:!e.parent&&this.head()?this.head():void 0},r=await this.dispatch({type:"turn:add",payload:{sessionId:this._id,turn:t},timestamp:t.timestamp});return r.ok&&await this.refreshTurnTree(),r}async recordUserTurn(e){return this.meta()?this.addTurn(e):bn({code:"NOT_FOUND",resource:"session",id:this._id})}async recordAssistantTurn(e,t){const r=this.ws();if(!r)return bn({code:"NOT_FOUND",resource:"workspace",id:"current"});if(!r.index.sessions[this._id])return bn({code:"NOT_FOUND",resource:"session",id:this._id});const n=this.processor.process(e,this._id);let s={};const o=[];for(const e of n){const t=await this.manager.dispatch(e);if(t.ok)s=wn(s,t.value);else{if("PERMISSION_DENIED"!==t.error.code||e.synthetic)return t;{const t=this.describeCommand(e);o.push({cmd:e,description:t})}}}const i=await this.addTurn(e);if(!i.ok)return i;if(s=wn(s,i.value),t&&o.length>0){const e=this.buildDenialTurn(o),t=await this.addTurn(e);t.ok&&(s=wn(s,t.value))}return En(s)}buildDenialTurn(e){const t=new Hn("user",this._id);for(const r of e)t.addText(`[System] User denied: ${r.description}.`);return t.build()}describeCommand(e){return"tool:call"===e.type?`tool execution: ${e.payload.tool}`:`command: ${e.type}`}async editTurn(e,t,r){if(!this.meta())return bn({code:"NOT_FOUND",resource:"session",id:this._id});const n=this.tree.graph()[e];if(!n)return bn({code:"NOT_FOUND",resource:"turn",id:e});const s=n.versions[n.activeVersion],o=n.activeVersion+1,i=await this.dispatch({type:"turn:edit",payload:{sessionId:this._id,turnId:e,newBlocks:t,roleSnapshot:r??s.role,newVersion:o},timestamp:(new Date).toISOString()});return i.ok&&(await this.dispatch({type:"session:update",payload:{sessionId:this._id,head:{id:e,version:o}},timestamp:(new Date).toISOString()}),await this.refreshTurnTree()),i}async branch(e){if(!this.meta())return bn({code:"NOT_FOUND",resource:"session",id:this._id});if(!e.parent)return bn({code:"INVALID_COMMAND",reason:"branch requires turn.parent to be set"});const t=await this.dispatch({type:"turn:branch",payload:{sessionId:this._id,turn:{...e,session:this._id}},timestamp:e.timestamp});return t.ok&&await this.refreshTurnTree(),t}async deleteTurn(e,t,r){if(!this.meta())return bn({code:"NOT_FOUND",resource:"session",id:this._id});const n=this.tree.graph();if(!n[e]?.versions[t])return bn({code:"NOT_FOUND",resource:"turn version",id:`${e}:${t}`});const s=await this.dispatch({type:"turn:delete",payload:{sessionId:this._id,turnId:e,version:t,newHead:r},timestamp:(new Date).toISOString()});return s.ok&&await this.refreshTurnTree(),s}async switchVersionLeft(e){return this.switchVersion(e,-1)}async switchVersionRight(e){return this.switchVersion(e,1)}async switchVersion(e,t){if(!this.ws())return bn({code:"NOT_FOUND",resource:"workspace",id:"current"});if(!this.meta())return bn({code:"NOT_FOUND",resource:"session",id:this._id});const r=this.tree.graph()[e];if(!r)return bn({code:"NOT_FOUND",resource:"turn",id:e});const n=Object.keys(r.versions).map(Number).sort(((e,t)=>e-t)),s=n.indexOf(r.activeVersion);if(-1===s)return bn({code:"INVALID_COMMAND",reason:"Active version not found"});const o=s+t;if(o<0||o>=n.length)return bn({code:"INVALID_COMMAND",reason:`No ${t<0?"previous":"next"} version available for turn ${e}`});const i=n[o],a=this.findSubtreeTip(this.tree.graph(),e,i),c=await this.dispatch({type:"session:update",payload:{sessionId:this._id,head:a},timestamp:(new Date).toISOString()});return c.ok&&await this.refreshTurnTree(),c}async snapshot(){const e=this,t=e.meta();if(!t)return;const r=e.ws(),n=e._role;if(!n)return;const s=await e.manager.ctx().context.getByTopics(r.index,t.topics),o=Array.from(new Set([...n.preferences,...t.preferences])),i=o.length>0?await e.manager.ctx().preferences.load(o):e._preferences,a=e.tree.chain().map((e=>e.versions[e.activeVersion])).filter((e=>!!e)),c=[...a].reverse().find((e=>"user"===e.actor));return{id:e._id,meta:t,role:n,preferences:i,context:s,model:t.metadata?.model,transcript:a,topics:t.topics,instructions:r.settings?.prompt,constraints:{role:n.constraints,session:t.constraints,turn:c?.constraints}}}async refreshTurnTree(){this.tree=await $n.build(this._id,this.turnRepository)}findSubtreeTip(e,t,r){let n=t,s=r;for(;;){const t=e[n];if(!t)break;const r=t.children[s];if(!r||0===r.length)break;const o=r[0],i=e[o];if(!i)break;n=o,s=i.activeVersion}return{id:n,version:s}}},Yn=class{constructor(e,t){this.manager=e,this.processor=t}openOnce=new Map;async open(e){let t=this.openOnce.get(e);t||(t=new fn,this.openOnce.set(e,t));const r=await t.do((async()=>{if(!this.manager.workspace().index.sessions[e])throw new Error(`Session ${e} not found in workspace index`);return Vn.create(e,this.manager,this.processor)}));if(r.error)throw r.error;return r.value}close(e){this.openOnce.delete(e)}async delete(e){const t=await this.manager.dispatch({type:"session:delete",payload:{sessionId:e},timestamp:(new Date).toISOString()});if(t.ok)return this.close(e),t.value=void 0,t;throw t.error}async create(e){const t=d.v7(),r=await this.manager.dispatch({type:"session:create",payload:{...e,id:t},timestamp:(new Date).toISOString()});if(r.ok)return this.open(t);throw r.error}list(){return Object.values(this.manager.workspace().index.sessions)}metadata(e){return this.manager.workspace().index.sessions[e]}},zn=class{constructor(e,t,r){this.storage=e,this.cache=t,this.bus=r}async register(e,t,r){const n=await Tn(e),s=await this.getRecord(n);if(s){const e={...s,refCount:s.refCount+1,lastUsedAt:(new Date).toISOString()};return await this.storage.saveRecord(e),this.cache.set(n,e),En(this.reference(e))}const o={sha256:n,mediaType:t,sizeBytes:e.byteLength,filename:r,refCount:1,remoteIds:{},createdAt:(new Date).toISOString(),lastUsedAt:(new Date).toISOString()};return this.storage.registerBlob?await this.storage.registerBlob(o,e):(await this.storage.storeBytes(n,e),await this.storage.saveRecord(o)),this.cache.set(n,o),this.bus.emit({name:"blobs:changed",payload:{sha256:n,record:o}}),En(this.reference(o))}async retain(e){const t=await this.getRecord(e);if(!t)return bn({code:"NOT_FOUND",resource:"blob",id:e});const r={...t,refCount:t.refCount+1,lastUsedAt:(new Date).toISOString()};return await this.storage.saveRecord(r),this.cache.set(e,r),En(void 0)}async release(e){const t=await this.getRecord(e);if(!t)return bn({code:"NOT_FOUND",resource:"blob",id:e});const r=Math.max(0,t.refCount-1),n={...t,refCount:r,lastUsedAt:(new Date).toISOString()};return await this.storage.saveRecord(n),this.cache.set(e,n),En(void 0)}async purge(e){return await this.storage.deleteBytes(e),await this.storage.deleteRecord(e),this.cache.delete(e),this.bus.emit({name:"blobs:changed",payload:{sha256:e}}),En(void 0)}async recordRemoteId(e,t,r,n){const s=await this.getRecord(e);if(!s)return bn({code:"NOT_FOUND",resource:"blob",id:e});const o={...s,remoteIds:{...s.remoteIds,[t]:{id:r,timestamp:n||(new Date).toISOString()}},lastUsedAt:(new Date).toISOString()};return await this.storage.saveRecord(o),this.cache.set(e,o),this.bus.emit({name:"blobs:changed",payload:{sha256:e,record:o}}),En(void 0)}async getRecord(e){const t=this.cache.get(e);if(t)return t;const r=await this.storage.loadRecord(e);return r&&this.cache.set(e,r),r}async getAllRecords(){const e=await this.storage.listRecords(),t={};for(const r of e)t[r.sha256]=r,this.cache.set(r.sha256,r);return t}reference(e){return{sha256:e.sha256,mediaType:e.mediaType,sizeBytes:e.sizeBytes,filename:e.filename}}async resolve(e,t){const r=await this.getRecord(e.sha256);if(!r)return En(null);if(t){const e=r.remoteIds[t];if(e)return En({kind:"remote",sha256:r.sha256,mediaType:r.mediaType,fileId:e.id,providerId:t,timestamp:e.timestamp});const n=await this.storage.loadBytes(r.sha256);return En(n?{kind:"inline",sha256:r.sha256,mediaType:r.mediaType,data:n}:null)}const n=await this.storage.loadBytes(r.sha256);return En(n?{kind:"inline",sha256:r.sha256,mediaType:r.mediaType,data:n}:null)}async resolveMany(e,t){const r=new Map;for(const n of e){const e=await this.resolve(n,t);if(!e.ok)return bn(e.error);if(null===e.value)return bn({code:"BLOB_ERROR",reason:`Unable to resolve blob ${n.sha256}${t?` with adapter ${t}`:""}`});r.set(n.sha256,e.value)}return En(r)}},Jn=class{constructor(e,t,r){this.collection=e,this.cache=t,this.registry=r}delegates=new Map;registerDelegate(e,t){this.delegates.set(e,t)}async get(e,t){const r=this.cache.get(e);if(r)return r;if(t){const r=this.delegates.get(t);if(r){const t=await r.get(e);return t&&this.cache.set(e,t),t}}const n=await this.collection.find({field:"key",operator:"eq",value:e});if(!n)return null;const s=n.state();return this.cache.set(e,s),s}async add(e){const t=this.delegates.get(e.content.kind);t?await t.add(e):await this.collection.create(e),this.cache.set(e.key,e)}async list(){const e=await this.collection.list({limit:1e3,type:"cursor",direction:"forward"}),t=((await e.next()).value||[]).map((e=>e.state()));for(const e of this.delegates.values()){const r=await e.list();t.push(...r)}return t}async update(e,t,r){if(r){const n=this.delegates.get(r);if(n){const r=await n.update(e,t);return r&&this.cache.set(e,r),r}}const n=await this.collection.find({field:"key",operator:"eq",value:e});if(!n)return null;await n.update(t);const s=n.state();return this.cache.set(e,s),s}async delete(e,t){if(t){const r=this.delegates.get(t);if(r){const t=await r.delete(e);return t&&this.cache.delete(e),t}}const r=await this.collection.find({field:"key",operator:"eq",value:e});if(!r)return!1;const n=await r.delete();return n&&this.cache.delete(e),n}async getByTopics(e,t){const r=new Map;for(const n of t){const t=e.topics[n];t&&t.contextKeys.forEach((t=>{const n=e.context[t],s=n?.kind||"unknown";r.has(s)||r.set(s,new Set),r.get(s).add(t)}))}if(0===r.size)return[];const n=[],s=[];for(const[e,t]of r.entries()){if(this.delegates.get(e))for(const r of t){const t=await this.get(r,e);t&&n.push(t)}else t.forEach((e=>s.push(e)))}if(s.length>0){const e=[];for(const t of s){const r=this.cache.get(t);r?n.push(r):e.push(t)}if(e.length>0){const t=await this.collection.filter({operator:"or",conditions:e.map((e=>({field:"key",operator:"eq",value:e})))});for(const e of t){const t=e.state();this.cache.set(t.key,t),n.push(t)}}}return n.sort(((e,t)=>new Date(t.timestamp).getTime()-new Date(e.timestamp).getTime()))}summarize(e){const t=this.registry?.get(e.content.kind);return t?t.summarize(e):{kind:e.content.kind,key:e.key,topics:e.topics,timestamp:e.timestamp,metadata:e.metadata}}},Kn=class{constructor(e,t){this.collection=e,this.cache=t}async get(e){const t=this.cache.get(e);if(t)return t;const r=await this.collection.find({field:"id",operator:"eq",value:e});if(!r)return null;const n=r.state();return this.cache.set(e,n),n}async add(e){await this.collection.create(e),this.cache.set(e.id,e)}async update(e,t){const r=await this.collection.find({field:"id",operator:"eq",value:e});if(!r)return null;await r.update(t);const n=r.state();return this.cache.set(e,n),n}async delete(e){const t=await this.collection.find({field:"id",operator:"eq",value:e});if(!t)return!1;const r=await t.delete();return r&&this.cache.delete(e),r}async load(e){if(0===e.length)return[];const t=[],r=[];for(const n of e){const e=this.cache.get(n);e?r.push(e):t.push(n)}if(t.length>0){const e=await this.collection.filter({operator:"or",conditions:t.map((e=>({field:"id",operator:"eq",value:e})))});for(const t of e){const e=t.state();this.cache.set(e.id,e),r.push(e)}}return r}async list(){const e=await this.collection.list({limit:1e3,type:"cursor",direction:"forward"});return((await e.next()).value||[]).map((e=>e.state()))}summarize(e){return{id:e.id,topics:e.topics,timestamp:e.timestamp,snippet:e.content.slice(0,100)}}},Xn=class{constructor(e,t){this.collection=e,this.cache=t}async get(e){const t=this.cache.get(e);if(t)return t;const r=await this.collection.find({field:"name",operator:"eq",value:e});if(!r)return null;const n=r.state();return this.cache.set(e,n),n}async add(e){await this.collection.create(e),this.cache.set(e.name,e)}async update(e,t){const r=await this.collection.find({field:"name",operator:"eq",value:e});if(!r)return null;await r.update(t);const n=r.state();return this.cache.set(e,n),n}async delete(e){const t=await this.collection.find({field:"name",operator:"eq",value:e});if(!t)return!1;const r=await t.delete();return r&&this.cache.delete(e),r}async list(){const e=await this.collection.list({limit:1e3,type:"cursor",direction:"forward"});return((await e.next()).value||[]).map((e=>e.state()))}summarize(e){return{name:e.name,label:e.label,description:e.description,preferences:e.preferences?.length??0,topics:e.topics??[],constraints:e.constraints}}},Zn=class{constructor(e,t){this.collection=e,this.cache=t}async get(e){const t=this.cache.get(e);if(t)return t;const r=await this.collection.find({field:"id",operator:"eq",value:e});if(!r)return null;const n=r.state();return this.cache.set(e,n),n}async add(e){await this.collection.create(e),this.cache.set(e.id,e)}async update(e,t){const r=await this.collection.find({field:"id",operator:"eq",value:e});if(!r)return null;await r.update(t);const n=r.state();return this.cache.set(e,n),n}async delete(e){const t=await this.collection.find({field:"id",operator:"eq",value:e});if(!t)return!1;const r=await t.delete();return r&&this.cache.delete(e),r}async list(){const e=await this.collection.list({limit:1e3,type:"cursor",direction:"forward"});return((await e.next()).value||[]).map((e=>e.state()))}summarize(e){return e}},Qn=class{constructor(e,t){this.collection=e,this.cache=t}key({id:e,session:t,version:r}){return`${t}:${r}:${e}`}async find({id:e,session:t,version:r},n=!0){const s=this.key({id:e,session:t,version:r});this.cache.get(s)&&this.cache.get(s);const o=await this.collection.find({operator:"and",conditions:[{field:"id",operator:"eq",value:e},{field:"session",operator:"eq",value:t},{field:"version",operator:"eq",value:r}]});return o?(n&&this.cache.set(s,o),o):null}async get(e){return this.find(e)}async add(e){const t=await this.collection.create(e);this.cache.set(this.key(e),t)}async update(e,t){const r=await this.find(e);return r?(await r.update(t),r.state()):null}async listBySession(e){return(await this.collection.filter({field:"session",operator:"eq",value:e})).map((e=>e.state()))}async delete(e){const t=await this.find(e,!1);if(!t)return!1;const r=await t.delete();return r&&this.cache.delete(this.key(e)),r}},es=class{constructor(e,t){this.collection=e,this.cache=t}async get(e){const t=this.cache.get(e);if(t)return t;const r=await this.collection.find({field:"id",operator:"eq",value:e});if(!r)return null;const n=r.state();return this.cache.set(e,n),n}async add(e){await this.collection.create(e),this.cache.set(e.id,e)}async update(e,t){const r=await this.collection.find({field:"id",operator:"eq",value:e});if(!r)return null;await r.update(t);const n=r.state();return this.cache.set(e,n),n}async delete(e){const t=await this.collection.find({field:"id",operator:"eq",value:e});if(!t)return!1;const r=await t.delete();return r&&this.cache.delete(e),r}async list(){const e=await this.collection.list({limit:100,type:"cursor",direction:"forward"});return((await e.next()).value||[]).map((e=>e.state()))}summarize(e){return e}},ts=class{cache;maxSize;constructor(e){this.cache=new Map,this.maxSize=e}get(e){const t=this.cache.get(e);return void 0!==t&&(this.cache.delete(e),this.cache.set(e,t)),t}set(e,t){if(this.cache.has(e))this.cache.delete(e);else if(this.cache.size>=this.maxSize){const e=this.cache.keys().next().value;void 0!==e&&this.cache.delete(e)}this.cache.set(e,t)}has(e){return this.cache.has(e)}delete(e){this.cache.delete(e)}clear(){this.cache.clear()}},rs="blob_bytes",ns="blob_records";function ss(e){return new Promise(((t,r)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>r(e.error)}))}function os(e){return new Promise(((t,r)=>{e.oncomplete=()=>t(),e.onerror=()=>r(e.error),e.onabort=()=>r(new Error("Transaction aborted"))}))}var is,as,cs,ls,us,ds,hs,fs,ps,ms,_s,ys,gs,Es,bs,ws,Ts,vs,Ss,As,Os,Rs,Cs,Is,ks,Ns,Ps,xs,Ds,Us,Ls,js,Ms,Fs,Bs,Gs,Hs,qs,$s,Ws,Vs,Ys,zs,Js,Ks,Xs,Zs,Qs,eo,to,ro,no,so,oo,io,ao,co,lo,uo,ho,fo,po,mo,_o,yo,go,Eo,bo,wo,To,vo,So,Ao,Oo,Ro,Co,Io,ko,No,Po,xo,Do,Uo,Lo,jo,Mo,Fo,Bo,Go,Ho,qo,$o,Wo,Vo,Yo,zo,Jo,Ko,Xo,Zo,Qo,ei,ti,ri,ni,si,oi,ii,ai,ci,li,ui,di,hi,fi,pi,mi,_i,yi,gi,Ei,bi,wi,Ti,vi,Si,Ai,Oi,Ri,Ci,Ii,ki={};function Ni(e,t){var r={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(r[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var s=0;for(n=Object.getOwnPropertySymbols(e);s<n.length;s++)t.indexOf(n[s])<0&&Object.prototype.propertyIsEnumerable.call(e,n[s])&&(r[n[s]]=e[n[s]])}return r}function Pi(e){var t="function"==typeof Symbol&&Symbol.iterator,r=t&&e[t],n=0;if(r)return r.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function xi(e){return this instanceof xi?(this.v=e,this):new xi(e)}function Di(e,t,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n,s=r.apply(e,t||[]),o=[];return n=Object.create(("function"==typeof AsyncIterator?AsyncIterator:Object).prototype),i("next"),i("throw"),i("return",(function(e){return function(t){return Promise.resolve(t).then(e,l)}})),n[Symbol.asyncIterator]=function(){return this},n;function i(e,t){s[e]&&(n[e]=function(t){return new Promise((function(r,n){o.push([e,t,r,n])>1||a(e,t)}))},t&&(n[e]=t(n[e])))}function a(e,t){try{(r=s[e](t)).value instanceof xi?Promise.resolve(r.value.v).then(c,l):u(o[0][2],r)}catch(e){u(o[0][3],e)}var r}function c(e){a("next",e)}function l(e){a("throw",e)}function u(e,t){e(t),o.shift(),o.length&&a(o[0][0],o[0][1])}}function Ui(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,r=e[Symbol.asyncIterator];return r?r.call(e):(e=Pi(e),t={},n("next"),n("throw"),n("return"),t[Symbol.asyncIterator]=function(){return this},t);function n(r){t[r]=e[r]&&function(t){return new Promise((function(n,s){(function(e,t,r,n){Promise.resolve(n).then((function(t){e({value:t,done:r})}),t)})(n,s,(t=e[r](t)).done,t.value)}))}}}R(ki,{GOOGLE_MODELS:()=>$a,GoogleGenAIAdapter:()=>Ka,mapBlockToPart:()=>Ya,mapTurnToContent:()=>Va,mappings:()=>qa,parseModelResponse:()=>Wa}),C(P(),1),C(Vr(),1),C(nn(),1),C(Zr(),1),C(Qr(),1),C(rn(),1),C(on(),1),(as=is||(is={})).LANGUAGE_UNSPECIFIED="LANGUAGE_UNSPECIFIED",as.PYTHON="PYTHON",(ls=cs||(cs={})).OUTCOME_UNSPECIFIED="OUTCOME_UNSPECIFIED",ls.OUTCOME_OK="OUTCOME_OK",ls.OUTCOME_FAILED="OUTCOME_FAILED",ls.OUTCOME_DEADLINE_EXCEEDED="OUTCOME_DEADLINE_EXCEEDED",(ds=us||(us={})).SCHEDULING_UNSPECIFIED="SCHEDULING_UNSPECIFIED",ds.SILENT="SILENT",ds.WHEN_IDLE="WHEN_IDLE",ds.INTERRUPT="INTERRUPT",(fs=hs||(hs={})).TYPE_UNSPECIFIED="TYPE_UNSPECIFIED",fs.STRING="STRING",fs.NUMBER="NUMBER",fs.INTEGER="INTEGER",fs.BOOLEAN="BOOLEAN",fs.ARRAY="ARRAY",fs.OBJECT="OBJECT",fs.NULL="NULL",(ms=ps||(ps={})).ENVIRONMENT_UNSPECIFIED="ENVIRONMENT_UNSPECIFIED",ms.ENVIRONMENT_BROWSER="ENVIRONMENT_BROWSER",(ys=_s||(_s={})).AUTH_TYPE_UNSPECIFIED="AUTH_TYPE_UNSPECIFIED",ys.NO_AUTH="NO_AUTH",ys.API_KEY_AUTH="API_KEY_AUTH",ys.HTTP_BASIC_AUTH="HTTP_BASIC_AUTH",ys.GOOGLE_SERVICE_ACCOUNT_AUTH="GOOGLE_SERVICE_ACCOUNT_AUTH",ys.OAUTH="OAUTH",ys.OIDC_AUTH="OIDC_AUTH",(Es=gs||(gs={})).HTTP_IN_UNSPECIFIED="HTTP_IN_UNSPECIFIED",Es.HTTP_IN_QUERY="HTTP_IN_QUERY",Es.HTTP_IN_HEADER="HTTP_IN_HEADER",Es.HTTP_IN_PATH="HTTP_IN_PATH",Es.HTTP_IN_BODY="HTTP_IN_BODY",Es.HTTP_IN_COOKIE="HTTP_IN_COOKIE",(ws=bs||(bs={})).API_SPEC_UNSPECIFIED="API_SPEC_UNSPECIFIED",ws.SIMPLE_SEARCH="SIMPLE_SEARCH",ws.ELASTIC_SEARCH="ELASTIC_SEARCH",(vs=Ts||(Ts={})).PHISH_BLOCK_THRESHOLD_UNSPECIFIED="PHISH_BLOCK_THRESHOLD_UNSPECIFIED",vs.BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",vs.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",vs.BLOCK_HIGH_AND_ABOVE="BLOCK_HIGH_AND_ABOVE",vs.BLOCK_HIGHER_AND_ABOVE="BLOCK_HIGHER_AND_ABOVE",vs.BLOCK_VERY_HIGH_AND_ABOVE="BLOCK_VERY_HIGH_AND_ABOVE",vs.BLOCK_ONLY_EXTREMELY_HIGH="BLOCK_ONLY_EXTREMELY_HIGH",(As=Ss||(Ss={})).UNSPECIFIED="UNSPECIFIED",As.BLOCKING="BLOCKING",As.NON_BLOCKING="NON_BLOCKING",(Rs=Os||(Os={})).MODE_UNSPECIFIED="MODE_UNSPECIFIED",Rs.MODE_DYNAMIC="MODE_DYNAMIC",(Is=Cs||(Cs={})).MODE_UNSPECIFIED="MODE_UNSPECIFIED",Is.AUTO="AUTO",Is.ANY="ANY",Is.NONE="NONE",Is.VALIDATED="VALIDATED",(Ns=ks||(ks={})).THINKING_LEVEL_UNSPECIFIED="THINKING_LEVEL_UNSPECIFIED",Ns.MINIMAL="MINIMAL",Ns.LOW="LOW",Ns.MEDIUM="MEDIUM",Ns.HIGH="HIGH",(xs=Ps||(Ps={})).DONT_ALLOW="DONT_ALLOW",xs.ALLOW_ADULT="ALLOW_ADULT",xs.ALLOW_ALL="ALLOW_ALL",(Us=Ds||(Ds={})).PROMINENT_PEOPLE_UNSPECIFIED="PROMINENT_PEOPLE_UNSPECIFIED",Us.ALLOW_PROMINENT_PEOPLE="ALLOW_PROMINENT_PEOPLE",Us.BLOCK_PROMINENT_PEOPLE="BLOCK_PROMINENT_PEOPLE",(js=Ls||(Ls={})).HARM_CATEGORY_UNSPECIFIED="HARM_CATEGORY_UNSPECIFIED",js.HARM_CATEGORY_HARASSMENT="HARM_CATEGORY_HARASSMENT",js.HARM_CATEGORY_HATE_SPEECH="HARM_CATEGORY_HATE_SPEECH",js.HARM_CATEGORY_SEXUALLY_EXPLICIT="HARM_CATEGORY_SEXUALLY_EXPLICIT",js.HARM_CATEGORY_DANGEROUS_CONTENT="HARM_CATEGORY_DANGEROUS_CONTENT",js.HARM_CATEGORY_CIVIC_INTEGRITY="HARM_CATEGORY_CIVIC_INTEGRITY",js.HARM_CATEGORY_IMAGE_HATE="HARM_CATEGORY_IMAGE_HATE",js.HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT="HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT",js.HARM_CATEGORY_IMAGE_HARASSMENT="HARM_CATEGORY_IMAGE_HARASSMENT",js.HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT="HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT",js.HARM_CATEGORY_JAILBREAK="HARM_CATEGORY_JAILBREAK",(Fs=Ms||(Ms={})).HARM_BLOCK_METHOD_UNSPECIFIED="HARM_BLOCK_METHOD_UNSPECIFIED",Fs.SEVERITY="SEVERITY",Fs.PROBABILITY="PROBABILITY",(Gs=Bs||(Bs={})).HARM_BLOCK_THRESHOLD_UNSPECIFIED="HARM_BLOCK_THRESHOLD_UNSPECIFIED",Gs.BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",Gs.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",Gs.BLOCK_ONLY_HIGH="BLOCK_ONLY_HIGH",Gs.BLOCK_NONE="BLOCK_NONE",Gs.OFF="OFF",(qs=Hs||(Hs={})).FINISH_REASON_UNSPECIFIED="FINISH_REASON_UNSPECIFIED",qs.STOP="STOP",qs.MAX_TOKENS="MAX_TOKENS",qs.SAFETY="SAFETY",qs.RECITATION="RECITATION",qs.LANGUAGE="LANGUAGE",qs.OTHER="OTHER",qs.BLOCKLIST="BLOCKLIST",qs.PROHIBITED_CONTENT="PROHIBITED_CONTENT",qs.SPII="SPII",qs.MALFORMED_FUNCTION_CALL="MALFORMED_FUNCTION_CALL",qs.IMAGE_SAFETY="IMAGE_SAFETY",qs.UNEXPECTED_TOOL_CALL="UNEXPECTED_TOOL_CALL",qs.IMAGE_PROHIBITED_CONTENT="IMAGE_PROHIBITED_CONTENT",qs.NO_IMAGE="NO_IMAGE",qs.IMAGE_RECITATION="IMAGE_RECITATION",qs.IMAGE_OTHER="IMAGE_OTHER",(Ws=$s||($s={})).HARM_PROBABILITY_UNSPECIFIED="HARM_PROBABILITY_UNSPECIFIED",Ws.NEGLIGIBLE="NEGLIGIBLE",Ws.LOW="LOW",Ws.MEDIUM="MEDIUM",Ws.HIGH="HIGH",(Ys=Vs||(Vs={})).HARM_SEVERITY_UNSPECIFIED="HARM_SEVERITY_UNSPECIFIED",Ys.HARM_SEVERITY_NEGLIGIBLE="HARM_SEVERITY_NEGLIGIBLE",Ys.HARM_SEVERITY_LOW="HARM_SEVERITY_LOW",Ys.HARM_SEVERITY_MEDIUM="HARM_SEVERITY_MEDIUM",Ys.HARM_SEVERITY_HIGH="HARM_SEVERITY_HIGH",(Js=zs||(zs={})).URL_RETRIEVAL_STATUS_UNSPECIFIED="URL_RETRIEVAL_STATUS_UNSPECIFIED",Js.URL_RETRIEVAL_STATUS_SUCCESS="URL_RETRIEVAL_STATUS_SUCCESS",Js.URL_RETRIEVAL_STATUS_ERROR="URL_RETRIEVAL_STATUS_ERROR",Js.URL_RETRIEVAL_STATUS_PAYWALL="URL_RETRIEVAL_STATUS_PAYWALL",Js.URL_RETRIEVAL_STATUS_UNSAFE="URL_RETRIEVAL_STATUS_UNSAFE",(Xs=Ks||(Ks={})).BLOCKED_REASON_UNSPECIFIED="BLOCKED_REASON_UNSPECIFIED",Xs.SAFETY="SAFETY",Xs.OTHER="OTHER",Xs.BLOCKLIST="BLOCKLIST",Xs.PROHIBITED_CONTENT="PROHIBITED_CONTENT",Xs.IMAGE_SAFETY="IMAGE_SAFETY",Xs.MODEL_ARMOR="MODEL_ARMOR",Xs.JAILBREAK="JAILBREAK",(Qs=Zs||(Zs={})).TRAFFIC_TYPE_UNSPECIFIED="TRAFFIC_TYPE_UNSPECIFIED",Qs.ON_DEMAND="ON_DEMAND",Qs.ON_DEMAND_PRIORITY="ON_DEMAND_PRIORITY",Qs.ON_DEMAND_FLEX="ON_DEMAND_FLEX",Qs.PROVISIONED_THROUGHPUT="PROVISIONED_THROUGHPUT",(to=eo||(eo={})).MODALITY_UNSPECIFIED="MODALITY_UNSPECIFIED",to.TEXT="TEXT",to.IMAGE="IMAGE",to.AUDIO="AUDIO",to.VIDEO="VIDEO",(no=ro||(ro={})).MODEL_STAGE_UNSPECIFIED="MODEL_STAGE_UNSPECIFIED",no.UNSTABLE_EXPERIMENTAL="UNSTABLE_EXPERIMENTAL",no.EXPERIMENTAL="EXPERIMENTAL",no.PREVIEW="PREVIEW",no.STABLE="STABLE",no.LEGACY="LEGACY",no.DEPRECATED="DEPRECATED",no.RETIRED="RETIRED",(oo=so||(so={})).MEDIA_RESOLUTION_UNSPECIFIED="MEDIA_RESOLUTION_UNSPECIFIED",oo.MEDIA_RESOLUTION_LOW="MEDIA_RESOLUTION_LOW",oo.MEDIA_RESOLUTION_MEDIUM="MEDIA_RESOLUTION_MEDIUM",oo.MEDIA_RESOLUTION_HIGH="MEDIA_RESOLUTION_HIGH",(ao=io||(io={})).TUNING_MODE_UNSPECIFIED="TUNING_MODE_UNSPECIFIED",ao.TUNING_MODE_FULL="TUNING_MODE_FULL",ao.TUNING_MODE_PEFT_ADAPTER="TUNING_MODE_PEFT_ADAPTER",(lo=co||(co={})).ADAPTER_SIZE_UNSPECIFIED="ADAPTER_SIZE_UNSPECIFIED",lo.ADAPTER_SIZE_ONE="ADAPTER_SIZE_ONE",lo.ADAPTER_SIZE_TWO="ADAPTER_SIZE_TWO",lo.ADAPTER_SIZE_FOUR="ADAPTER_SIZE_FOUR",lo.ADAPTER_SIZE_EIGHT="ADAPTER_SIZE_EIGHT",lo.ADAPTER_SIZE_SIXTEEN="ADAPTER_SIZE_SIXTEEN",lo.ADAPTER_SIZE_THIRTY_TWO="ADAPTER_SIZE_THIRTY_TWO",(ho=uo||(uo={})).JOB_STATE_UNSPECIFIED="JOB_STATE_UNSPECIFIED",ho.JOB_STATE_QUEUED="JOB_STATE_QUEUED",ho.JOB_STATE_PENDING="JOB_STATE_PENDING",ho.JOB_STATE_RUNNING="JOB_STATE_RUNNING",ho.JOB_STATE_SUCCEEDED="JOB_STATE_SUCCEEDED",ho.JOB_STATE_FAILED="JOB_STATE_FAILED",ho.JOB_STATE_CANCELLING="JOB_STATE_CANCELLING",ho.JOB_STATE_CANCELLED="JOB_STATE_CANCELLED",ho.JOB_STATE_PAUSED="JOB_STATE_PAUSED",ho.JOB_STATE_EXPIRED="JOB_STATE_EXPIRED",ho.JOB_STATE_UPDATING="JOB_STATE_UPDATING",ho.JOB_STATE_PARTIALLY_SUCCEEDED="JOB_STATE_PARTIALLY_SUCCEEDED",(po=fo||(fo={})).TUNING_JOB_STATE_UNSPECIFIED="TUNING_JOB_STATE_UNSPECIFIED",po.TUNING_JOB_STATE_WAITING_FOR_QUOTA="TUNING_JOB_STATE_WAITING_FOR_QUOTA",po.TUNING_JOB_STATE_PROCESSING_DATASET="TUNING_JOB_STATE_PROCESSING_DATASET",po.TUNING_JOB_STATE_WAITING_FOR_CAPACITY="TUNING_JOB_STATE_WAITING_FOR_CAPACITY",po.TUNING_JOB_STATE_TUNING="TUNING_JOB_STATE_TUNING",po.TUNING_JOB_STATE_POST_PROCESSING="TUNING_JOB_STATE_POST_PROCESSING",(_o=mo||(mo={})).AGGREGATION_METRIC_UNSPECIFIED="AGGREGATION_METRIC_UNSPECIFIED",_o.AVERAGE="AVERAGE",_o.MODE="MODE",_o.STANDARD_DEVIATION="STANDARD_DEVIATION",_o.VARIANCE="VARIANCE",_o.MINIMUM="MINIMUM",_o.MAXIMUM="MAXIMUM",_o.MEDIAN="MEDIAN",_o.PERCENTILE_P90="PERCENTILE_P90",_o.PERCENTILE_P95="PERCENTILE_P95",_o.PERCENTILE_P99="PERCENTILE_P99",(go=yo||(yo={})).PAIRWISE_CHOICE_UNSPECIFIED="PAIRWISE_CHOICE_UNSPECIFIED",go.BASELINE="BASELINE",go.CANDIDATE="CANDIDATE",go.TIE="TIE",(bo=Eo||(Eo={})).TUNING_TASK_UNSPECIFIED="TUNING_TASK_UNSPECIFIED",bo.TUNING_TASK_I2V="TUNING_TASK_I2V",bo.TUNING_TASK_T2V="TUNING_TASK_T2V",bo.TUNING_TASK_R2V="TUNING_TASK_R2V",(To=wo||(wo={})).STATE_UNSPECIFIED="STATE_UNSPECIFIED",To.STATE_PENDING="STATE_PENDING",To.STATE_ACTIVE="STATE_ACTIVE",To.STATE_FAILED="STATE_FAILED",(So=vo||(vo={})).MEDIA_RESOLUTION_UNSPECIFIED="MEDIA_RESOLUTION_UNSPECIFIED",So.MEDIA_RESOLUTION_LOW="MEDIA_RESOLUTION_LOW",So.MEDIA_RESOLUTION_MEDIUM="MEDIA_RESOLUTION_MEDIUM",So.MEDIA_RESOLUTION_HIGH="MEDIA_RESOLUTION_HIGH",So.MEDIA_RESOLUTION_ULTRA_HIGH="MEDIA_RESOLUTION_ULTRA_HIGH",(Oo=Ao||(Ao={})).TOOL_TYPE_UNSPECIFIED="TOOL_TYPE_UNSPECIFIED",Oo.GOOGLE_SEARCH_WEB="GOOGLE_SEARCH_WEB",Oo.GOOGLE_SEARCH_IMAGE="GOOGLE_SEARCH_IMAGE",Oo.URL_CONTEXT="URL_CONTEXT",Oo.GOOGLE_MAPS="GOOGLE_MAPS",Oo.FILE_SEARCH="FILE_SEARCH",(Ro||(Ro={})).COLLECTION="COLLECTION",(Io=Co||(Co={})).UNSPECIFIED="unspecified",Io.FLEX="flex",Io.STANDARD="standard",Io.PRIORITY="priority",(No=ko||(ko={})).FEATURE_SELECTION_PREFERENCE_UNSPECIFIED="FEATURE_SELECTION_PREFERENCE_UNSPECIFIED",No.PRIORITIZE_QUALITY="PRIORITIZE_QUALITY",No.BALANCED="BALANCED",No.PRIORITIZE_COST="PRIORITIZE_COST",(xo=Po||(Po={})).PREDICT="PREDICT",xo.EMBED_CONTENT="EMBED_CONTENT",(Uo=Do||(Do={})).BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",Uo.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",Uo.BLOCK_ONLY_HIGH="BLOCK_ONLY_HIGH",Uo.BLOCK_NONE="BLOCK_NONE",(jo=Lo||(Lo={})).auto="auto",jo.en="en",jo.ja="ja",jo.ko="ko",jo.hi="hi",jo.zh="zh",jo.pt="pt",jo.es="es",(Fo=Mo||(Mo={})).MASK_MODE_DEFAULT="MASK_MODE_DEFAULT",Fo.MASK_MODE_USER_PROVIDED="MASK_MODE_USER_PROVIDED",Fo.MASK_MODE_BACKGROUND="MASK_MODE_BACKGROUND",Fo.MASK_MODE_FOREGROUND="MASK_MODE_FOREGROUND",Fo.MASK_MODE_SEMANTIC="MASK_MODE_SEMANTIC",(Go=Bo||(Bo={})).CONTROL_TYPE_DEFAULT="CONTROL_TYPE_DEFAULT",Go.CONTROL_TYPE_CANNY="CONTROL_TYPE_CANNY",Go.CONTROL_TYPE_SCRIBBLE="CONTROL_TYPE_SCRIBBLE",Go.CONTROL_TYPE_FACE_MESH="CONTROL_TYPE_FACE_MESH",(qo=Ho||(Ho={})).SUBJECT_TYPE_DEFAULT="SUBJECT_TYPE_DEFAULT",qo.SUBJECT_TYPE_PERSON="SUBJECT_TYPE_PERSON",qo.SUBJECT_TYPE_ANIMAL="SUBJECT_TYPE_ANIMAL",qo.SUBJECT_TYPE_PRODUCT="SUBJECT_TYPE_PRODUCT",(Wo=$o||($o={})).EDIT_MODE_DEFAULT="EDIT_MODE_DEFAULT",Wo.EDIT_MODE_INPAINT_REMOVAL="EDIT_MODE_INPAINT_REMOVAL",Wo.EDIT_MODE_INPAINT_INSERTION="EDIT_MODE_INPAINT_INSERTION",Wo.EDIT_MODE_OUTPAINT="EDIT_MODE_OUTPAINT",Wo.EDIT_MODE_CONTROLLED_EDITING="EDIT_MODE_CONTROLLED_EDITING",Wo.EDIT_MODE_STYLE="EDIT_MODE_STYLE",Wo.EDIT_MODE_BGSWAP="EDIT_MODE_BGSWAP",Wo.EDIT_MODE_PRODUCT_IMAGE="EDIT_MODE_PRODUCT_IMAGE",(Yo=Vo||(Vo={})).FOREGROUND="FOREGROUND",Yo.BACKGROUND="BACKGROUND",Yo.PROMPT="PROMPT",Yo.SEMANTIC="SEMANTIC",Yo.INTERACTIVE="INTERACTIVE",(Jo=zo||(zo={})).ASSET="ASSET",Jo.STYLE="STYLE",(Xo=Ko||(Ko={})).INSERT="INSERT",Xo.REMOVE="REMOVE",Xo.REMOVE_STATIC="REMOVE_STATIC",Xo.OUTPAINT="OUTPAINT",(Qo=Zo||(Zo={})).OPTIMIZED="OPTIMIZED",Qo.LOSSLESS="LOSSLESS",(ti=ei||(ei={})).SUPERVISED_FINE_TUNING="SUPERVISED_FINE_TUNING",ti.PREFERENCE_TUNING="PREFERENCE_TUNING",ti.DISTILLATION="DISTILLATION",(ni=ri||(ri={})).STATE_UNSPECIFIED="STATE_UNSPECIFIED",ni.PROCESSING="PROCESSING",ni.ACTIVE="ACTIVE",ni.FAILED="FAILED",(oi=si||(si={})).SOURCE_UNSPECIFIED="SOURCE_UNSPECIFIED",oi.UPLOADED="UPLOADED",oi.GENERATED="GENERATED",oi.REGISTERED="REGISTERED",(ai=ii||(ii={})).TURN_COMPLETE_REASON_UNSPECIFIED="TURN_COMPLETE_REASON_UNSPECIFIED",ai.MALFORMED_FUNCTION_CALL="MALFORMED_FUNCTION_CALL",ai.RESPONSE_REJECTED="RESPONSE_REJECTED",ai.NEED_MORE_INPUT="NEED_MORE_INPUT",ai.PROHIBITED_INPUT_CONTENT="PROHIBITED_INPUT_CONTENT",ai.IMAGE_PROHIBITED_INPUT_CONTENT="IMAGE_PROHIBITED_INPUT_CONTENT",ai.INPUT_TEXT_CONTAIN_PROMINENT_PERSON_PROHIBITED="INPUT_TEXT_CONTAIN_PROMINENT_PERSON_PROHIBITED",ai.INPUT_IMAGE_CELEBRITY="INPUT_IMAGE_CELEBRITY",ai.INPUT_IMAGE_PHOTO_REALISTIC_CHILD_PROHIBITED="INPUT_IMAGE_PHOTO_REALISTIC_CHILD_PROHIBITED",ai.INPUT_TEXT_NCII_PROHIBITED="INPUT_TEXT_NCII_PROHIBITED",ai.INPUT_OTHER="INPUT_OTHER",ai.INPUT_IP_PROHIBITED="INPUT_IP_PROHIBITED",ai.BLOCKLIST="BLOCKLIST",ai.UNSAFE_PROMPT_FOR_IMAGE_GENERATION="UNSAFE_PROMPT_FOR_IMAGE_GENERATION",ai.GENERATED_IMAGE_SAFETY="GENERATED_IMAGE_SAFETY",ai.GENERATED_CONTENT_SAFETY="GENERATED_CONTENT_SAFETY",ai.GENERATED_AUDIO_SAFETY="GENERATED_AUDIO_SAFETY",ai.GENERATED_VIDEO_SAFETY="GENERATED_VIDEO_SAFETY",ai.GENERATED_CONTENT_PROHIBITED="GENERATED_CONTENT_PROHIBITED",ai.GENERATED_CONTENT_BLOCKLIST="GENERATED_CONTENT_BLOCKLIST",ai.GENERATED_IMAGE_PROHIBITED="GENERATED_IMAGE_PROHIBITED",ai.GENERATED_IMAGE_CELEBRITY="GENERATED_IMAGE_CELEBRITY",ai.GENERATED_IMAGE_PROMINENT_PEOPLE_DETECTED_BY_REWRITER="GENERATED_IMAGE_PROMINENT_PEOPLE_DETECTED_BY_REWRITER",ai.GENERATED_IMAGE_IDENTIFIABLE_PEOPLE="GENERATED_IMAGE_IDENTIFIABLE_PEOPLE",ai.GENERATED_IMAGE_MINORS="GENERATED_IMAGE_MINORS",ai.OUTPUT_IMAGE_IP_PROHIBITED="OUTPUT_IMAGE_IP_PROHIBITED",ai.GENERATED_OTHER="GENERATED_OTHER",ai.MAX_REGENERATION_REACHED="MAX_REGENERATION_REACHED",(li=ci||(ci={})).MODALITY_UNSPECIFIED="MODALITY_UNSPECIFIED",li.TEXT="TEXT",li.IMAGE="IMAGE",li.VIDEO="VIDEO",li.AUDIO="AUDIO",li.DOCUMENT="DOCUMENT",(di=ui||(ui={})).VAD_SIGNAL_TYPE_UNSPECIFIED="VAD_SIGNAL_TYPE_UNSPECIFIED",di.VAD_SIGNAL_TYPE_SOS="VAD_SIGNAL_TYPE_SOS",di.VAD_SIGNAL_TYPE_EOS="VAD_SIGNAL_TYPE_EOS",(fi=hi||(hi={})).TYPE_UNSPECIFIED="TYPE_UNSPECIFIED",fi.ACTIVITY_START="ACTIVITY_START",fi.ACTIVITY_END="ACTIVITY_END",(mi=pi||(pi={})).START_SENSITIVITY_UNSPECIFIED="START_SENSITIVITY_UNSPECIFIED",mi.START_SENSITIVITY_HIGH="START_SENSITIVITY_HIGH",mi.START_SENSITIVITY_LOW="START_SENSITIVITY_LOW",(yi=_i||(_i={})).END_SENSITIVITY_UNSPECIFIED="END_SENSITIVITY_UNSPECIFIED",yi.END_SENSITIVITY_HIGH="END_SENSITIVITY_HIGH",yi.END_SENSITIVITY_LOW="END_SENSITIVITY_LOW",(Ei=gi||(gi={})).ACTIVITY_HANDLING_UNSPECIFIED="ACTIVITY_HANDLING_UNSPECIFIED",Ei.START_OF_ACTIVITY_INTERRUPTS="START_OF_ACTIVITY_INTERRUPTS",Ei.NO_INTERRUPTION="NO_INTERRUPTION",(wi=bi||(bi={})).TURN_COVERAGE_UNSPECIFIED="TURN_COVERAGE_UNSPECIFIED",wi.TURN_INCLUDES_ONLY_ACTIVITY="TURN_INCLUDES_ONLY_ACTIVITY",wi.TURN_INCLUDES_ALL_INPUT="TURN_INCLUDES_ALL_INPUT",wi.TURN_INCLUDES_AUDIO_ACTIVITY_AND_ALL_VIDEO="TURN_INCLUDES_AUDIO_ACTIVITY_AND_ALL_VIDEO",(vi=Ti||(Ti={})).SCALE_UNSPECIFIED="SCALE_UNSPECIFIED",vi.C_MAJOR_A_MINOR="C_MAJOR_A_MINOR",vi.D_FLAT_MAJOR_B_FLAT_MINOR="D_FLAT_MAJOR_B_FLAT_MINOR",vi.D_MAJOR_B_MINOR="D_MAJOR_B_MINOR",vi.E_FLAT_MAJOR_C_MINOR="E_FLAT_MAJOR_C_MINOR",vi.E_MAJOR_D_FLAT_MINOR="E_MAJOR_D_FLAT_MINOR",vi.F_MAJOR_D_MINOR="F_MAJOR_D_MINOR",vi.G_FLAT_MAJOR_E_FLAT_MINOR="G_FLAT_MAJOR_E_FLAT_MINOR",vi.G_MAJOR_E_MINOR="G_MAJOR_E_MINOR",vi.A_FLAT_MAJOR_F_MINOR="A_FLAT_MAJOR_F_MINOR",vi.A_MAJOR_G_FLAT_MINOR="A_MAJOR_G_FLAT_MINOR",vi.B_FLAT_MAJOR_G_MINOR="B_FLAT_MAJOR_G_MINOR",vi.B_MAJOR_A_FLAT_MINOR="B_MAJOR_A_FLAT_MINOR",(Ai=Si||(Si={})).MUSIC_GENERATION_MODE_UNSPECIFIED="MUSIC_GENERATION_MODE_UNSPECIFIED",Ai.QUALITY="QUALITY",Ai.DIVERSITY="DIVERSITY",Ai.VOCALIZATION="VOCALIZATION",(Ri=Oi||(Oi={})).PLAYBACK_CONTROL_UNSPECIFIED="PLAYBACK_CONTROL_UNSPECIFIED",Ri.PLAY="PLAY",Ri.PAUSE="PAUSE",Ri.STOP="STOP",Ri.RESET_CONTEXT="RESET_CONTEXT",(Ii=Ci||(Ci={})).PAGED_ITEM_BATCH_JOBS="batchJobs",Ii.PAGED_ITEM_MODELS="models",Ii.PAGED_ITEM_TUNING_JOBS="tuningJobs",Ii.PAGED_ITEM_FILES="files",Ii.PAGED_ITEM_CACHED_CONTENTS="cachedContents",Ii.PAGED_ITEM_FILE_SEARCH_STORES="fileSearchStores",Ii.PAGED_ITEM_DOCUMENTS="documents";var Li=function(){const{crypto:e}=globalThis;if(null==e?void 0:e.randomUUID)return Li=e.randomUUID.bind(e),e.randomUUID();const t=new Uint8Array(1),r=e?()=>e.getRandomValues(t)[0]:()=>255*Math.random()&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,(e=>(+e^r()&15>>+e/4).toString(16)))};function ji(e){return"object"==typeof e&&null!==e&&("name"in e&&"AbortError"===e.name||"message"in e&&String(e.message).includes("FetchRequestCanceledException"))}var Mi=e=>{if(e instanceof Error)return e;if("object"==typeof e&&null!==e){try{if("[object Error]"===Object.prototype.toString.call(e)){const t=new Error(e.message,e.cause?{cause:e.cause}:{});return e.stack&&(t.stack=e.stack),e.cause&&!t.cause&&(t.cause=e.cause),e.name&&(t.name=e.name),t}}catch(e){}try{return new Error(JSON.stringify(e))}catch(e){}}return new Error(e)},Fi=class extends Error{},Bi=class e extends Fi{constructor(t,r,n,s){super(`${e.makeMessage(t,r,n)}`),this.status=t,this.headers=s,this.error=r}static makeMessage(e,t,r){const n=(null==t?void 0:t.message)?"string"==typeof t.message?t.message:JSON.stringify(t.message):t?JSON.stringify(t):r;return e&&n?`${e} ${n}`:e?`${e} status code (no body)`:n||"(no status code or body)"}static generate(t,r,n,s){if(!t||!s)return new Hi({message:n,cause:Mi(r)});const o=r;return 400===t?new $i(t,o,n,s):401===t?new Wi(t,o,n,s):403===t?new Vi(t,o,n,s):404===t?new Yi(t,o,n,s):409===t?new zi(t,o,n,s):422===t?new Ji(t,o,n,s):429===t?new Ki(t,o,n,s):t>=500?new Xi(t,o,n,s):new e(t,o,n,s)}},Gi=class extends Bi{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},Hi=class extends Bi{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}},qi=class extends Hi{constructor({message:e}={}){super({message:null!=e?e:"Request timed out."})}},$i=class extends Bi{},Wi=class extends Bi{},Vi=class extends Bi{},Yi=class extends Bi{},zi=class extends Bi{},Ji=class extends Bi{},Ki=class extends Bi{},Xi=class extends Bi{},Zi=/^[a-z][a-z0-9+.-]*:/i,Qi=e=>(Qi=Array.isArray)(e),ea=Qi;function ta(e){if(!e)return!0;for(const t in e)return!1;return!0}function ra(...e){const t=globalThis.ReadableStream;if(void 0===t)throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new t(...e)}function na(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return ra({start(){},async pull(e){const{done:r,value:n}=await t.next();r?e.close():e.enqueue(n)},async cancel(){var e;await(null===(e=t.return)||void 0===e?void 0:e.call(t))}})}function sa(e){if(e[Symbol.asyncIterator])return e;const t=e.getReader();return{async next(){try{const e=await t.read();return(null==e?void 0:e.done)&&t.releaseLock(),e}catch(e){throw t.releaseLock(),e}},async return(){const e=t.cancel();return t.releaseLock(),await e,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}var oa=({headers:e,body:t})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(t)});var ia=()=>{var e;if("undefined"==typeof File){const{process:t}=globalThis,r="string"==typeof(null===(e=null==t?void 0:t.versions)||void 0===e?void 0:e.node)&&parseInt(t.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(r?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function aa(e,t,r){return ia(),new File(e,null!=t?t:"unknown_file",r)}var ca=e=>null!=e&&"object"==typeof e&&"number"==typeof e.size&&"string"==typeof e.type&&"function"==typeof e.text&&"function"==typeof e.slice&&"function"==typeof e.arrayBuffer;async function la(e){var t,r,n,s,o;let i=[];if("string"==typeof e||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)i.push(e);else if(ca(e))i.push(e instanceof Blob?e:await e.arrayBuffer());else{if(!(e=>null!=e&&"object"==typeof e&&"function"==typeof e[Symbol.asyncIterator])(e)){const t=null===(o=null==e?void 0:e.constructor)||void 0===o?void 0:o.name;throw new Error(`Unexpected data type: ${typeof e}${t?`; constructor: ${t}`:""}${function(e){if("object"!=typeof e||null===e)return"";const t=Object.getOwnPropertyNames(e);return`; props: [${t.map((e=>`"${e}"`)).join(", ")}]`}(e)}`)}try{for(var a,c=!0,l=Ui(e);!(t=(a=await l.next()).done);c=!0){s=a.value,c=!1;const e=s;i.push(...await la(e))}}catch(e){r={error:e}}finally{try{c||t||!(n=l.return)||await n.call(l)}finally{if(r)throw r.error}}}return i}var ua=class{constructor(e){this._client=e}};function da(e){return e.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}ua._key=[];var ha=Object.freeze(Object.create(null)),fa=((e=da)=>function(t,...r){if(1===t.length)return t[0];let n=!1;const s=[],o=t.reduce(((t,o,i)=>{var a,c,l;/[?#]/.test(o)&&(n=!0);const u=r[i];let d=(n?encodeURIComponent:e)(""+u);return i!==r.length&&(null==u||"object"==typeof u&&u.toString===(null===(l=Object.getPrototypeOf(null!==(c=Object.getPrototypeOf(null!==(a=u.hasOwnProperty)&&void 0!==a?a:ha))&&void 0!==c?c:ha))||void 0===l?void 0:l.toString))&&(d=u+"",s.push({start:t.length+o.length,length:d.length,error:`Value of type ${Object.prototype.toString.call(u).slice(8,-1)} is not a valid path parameter`})),t+o+(i===r.length?"":d)}),""),i=o.split(/[?#]/,1)[0],a=/(^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi;let c;for(;null!==(c=a.exec(i));){const e=c[0].startsWith("/"),t=e?1:0,r=e?c[0].slice(1):c[0];s.push({start:c.index+t,length:r.length,error:`Value "${r}" can't be safely passed as a path parameter`})}if(s.sort(((e,t)=>e.start-t.start)),s.length>0){let e=0;const t=s.reduce(((t,r)=>{const n=" ".repeat(r.start-e),s="^".repeat(r.length);return e=r.start+r.length,t+n+s}),"");throw new Fi(`Path parameters result in path with invalid segments:\n${s.map((e=>e.error)).join("\n")}\n${o}\n${t}`)}return o})(da),pa=class extends ua{create(e,t){var r;const{api_version:n=this._client.apiVersion}=e,s=Ni(e,["api_version"]);if("model"in s&&"agent_config"in s)throw new Fi("Invalid request: specified `model` and `agent_config`. If specifying `model`, use `generation_config`.");if("agent"in s&&"generation_config"in s)throw new Fi("Invalid request: specified `agent` and `generation_config`. If specifying `agent`, use `agent_config`.");return this._client.post(fa`/${n}/interactions`,Object.assign(Object.assign({body:s},t),{stream:null!==(r=e.stream)&&void 0!==r&&r}))}delete(e,t={},r){const{api_version:n=this._client.apiVersion}=null!=t?t:{};return this._client.delete(fa`/${n}/interactions/${e}`,r)}cancel(e,t={},r){const{api_version:n=this._client.apiVersion}=null!=t?t:{};return this._client.post(fa`/${n}/interactions/${e}/cancel`,r)}get(e,t={},r){var n;const s=null!=t?t:{},{api_version:o=this._client.apiVersion}=s,i=Ni(s,["api_version"]);return this._client.get(fa`/${o}/interactions/${e}`,Object.assign(Object.assign({query:i},r),{stream:null!==(n=null==t?void 0:t.stream)&&void 0!==n&&n}))}};pa._key=Object.freeze(["interactions"]);var ma=class extends pa{},_a=class extends ua{create(e,t){const{api_version:r=this._client.apiVersion,webhook_id:n}=e,s=Ni(e,["api_version","webhook_id"]);return this._client.post(fa`/${r}/webhooks`,Object.assign({query:{webhook_id:n},body:s},t))}update(e,t,r){const{api_version:n=this._client.apiVersion,update_mask:s}=t,o=Ni(t,["api_version","update_mask"]);return this._client.patch(fa`/${n}/webhooks/${e}`,Object.assign({query:{update_mask:s},body:o},r))}list(e={},t){const r=null!=e?e:{},{api_version:n=this._client.apiVersion}=r,s=Ni(r,["api_version"]);return this._client.get(fa`/${n}/webhooks`,Object.assign({query:s},t))}delete(e,t={},r){const{api_version:n=this._client.apiVersion}=null!=t?t:{};return this._client.delete(fa`/${n}/webhooks/${e}`,r)}get(e,t={},r){const{api_version:n=this._client.apiVersion}=null!=t?t:{};return this._client.get(fa`/${n}/webhooks/${e}`,r)}ping(e,t=void 0,r){const{api_version:n=this._client.apiVersion,body:s}=null!=t?t:{};return this._client.post(fa`/${n}/webhooks/${e}:ping`,Object.assign({body:s},r))}rotateSigningSecret(e,t={},r){const n=null!=t?t:{},{api_version:s=this._client.apiVersion}=n,o=Ni(n,["api_version"]);return this._client.post(fa`/${s}/webhooks/${e}:rotateSigningSecret`,Object.assign({body:o},r))}};_a._key=Object.freeze(["webhooks"]);var ya,ga,Ea=class extends _a{};function ba(e){let t;return(null!=ya?ya:(t=new globalThis.TextEncoder,ya=t.encode.bind(t)))(e)}function wa(e){let t;return(null!=ga?ga:(t=new globalThis.TextDecoder,ga=t.decode.bind(t)))(e)}var Ta=class{constructor(){this.buffer=new Uint8Array,this.carriageReturnIndex=null,this.searchIndex=0}decode(e){var t;if(null==e)return[];const r=e instanceof ArrayBuffer?new Uint8Array(e):"string"==typeof e?ba(e):e;this.buffer=function(e){let t=0;for(const r of e)t+=r.length;const r=new Uint8Array(t);let n=0;for(const t of e)r.set(t,n),n+=t.length;return r}([this.buffer,r]);const n=[];let s;for(;null!=(s=va(this.buffer,null!==(t=this.carriageReturnIndex)&&void 0!==t?t:this.searchIndex));){if(s.carriage&&null==this.carriageReturnIndex){this.carriageReturnIndex=s.index;continue}if(null!=this.carriageReturnIndex&&(s.index!==this.carriageReturnIndex+1||s.carriage)){n.push(wa(this.buffer.subarray(0,this.carriageReturnIndex-1))),this.buffer=this.buffer.subarray(this.carriageReturnIndex),this.carriageReturnIndex=null,this.searchIndex=0;continue}const e=null!==this.carriageReturnIndex?s.preceding-1:s.preceding,t=wa(this.buffer.subarray(0,e));n.push(t),this.buffer=this.buffer.subarray(s.index),this.carriageReturnIndex=null,this.searchIndex=0}return this.searchIndex=Math.max(0,this.buffer.length-1),n}flush(){return this.buffer.length?this.decode("\n"):[]}};function va(e,t){const r=null!=t?t:0,n=e.indexOf(10,r),s=e.indexOf(13,r);if(-1===n&&-1===s)return null;let o;return o=-1!==n&&-1!==s?Math.min(n,s):-1!==n?n:s,10===e[o]?{preceding:o,index:o+1,carriage:!1}:{preceding:o,index:o+1,carriage:!0}}Ta.NEWLINE_CHARS=new Set(["\n","\r"]),Ta.NEWLINE_REGEXP=/\r\n|[\n\r]/g;var Sa={off:0,error:200,warn:300,info:400,debug:500},Aa=(e,t,r)=>{var n,s;if(e)return n=Sa,s=e,Object.prototype.hasOwnProperty.call(n,s)?e:void ka(r).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(Sa))}`)};function Oa(){}function Ra(e,t,r){return!t||Sa[e]>Sa[r]?Oa:t[e].bind(t)}var Ca={error:Oa,warn:Oa,info:Oa,debug:Oa},Ia=new WeakMap;function ka(e){var t;const r=e.logger,n=null!==(t=e.logLevel)&&void 0!==t?t:"off";if(!r)return Ca;const s=Ia.get(r);if(s&&s[0]===n)return s[1];const o={error:Ra("error",r,n),warn:Ra("warn",r,n),info:Ra("info",r,n),debug:Ra("debug",r,n)};return Ia.set(r,[n,o]),o}var Na=e=>(e.options&&(e.options=Object.assign({},e.options),delete e.options.headers),e.headers&&(e.headers=Object.fromEntries((e.headers instanceof Headers?[...e.headers]:Object.entries(e.headers)).map((([e,t])=>[e,"x-goog-api-key"===e.toLowerCase()||"authorization"===e.toLowerCase()||"cookie"===e.toLowerCase()||"set-cookie"===e.toLowerCase()?"***":t])))),"retryOfRequestLogID"in e&&(e.retryOfRequestLogID&&(e.retryOf=e.retryOfRequestLogID),delete e.retryOfRequestLogID),e),Pa=class e{constructor(e,t,r){this.iterator=e,this.controller=t,this.client=r}static fromSSEResponse(t,r,n){let s=!1;const o=n?ka(n):console;return new e((function(){return Di(this,arguments,(function*(){var e,n,i,a;if(s)throw new Fi("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");s=!0;let c=!1;try{try{for(var l,u=!0,d=Ui(function(e,t){return Di(this,arguments,(function*(){var r,n,s,o;if(!e.body){if(t.abort(),void 0!==globalThis.navigator&&"ReactNative"===globalThis.navigator.product)throw new Fi("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api");throw new Fi("Attempted to iterate over a response with no body")}const i=new xa,a=new Ta,c=sa(e.body);try{for(var l,u=!0,d=Ui(function(e){return Di(this,arguments,(function*(){var t,r,n,s;try{for(var o,i=!0,a=Ui(e);!(t=(o=yield xi(a.next())).done);i=!0){s=o.value,i=!1;const e=s;if(null==e)continue;const t=e instanceof ArrayBuffer?new Uint8Array(e):"string"==typeof e?ba(e):e;yield yield xi(t)}}catch(e){r={error:e}}finally{try{i||t||!(n=a.return)||(yield xi(n.call(a)))}finally{if(r)throw r.error}}}))}(c));!(r=(l=yield xi(d.next())).done);u=!0){o=l.value,u=!1;const e=o;for(const t of a.decode(e)){const e=i.decode(t);e&&(yield yield xi(e))}}}catch(e){n={error:e}}finally{try{u||r||!(s=d.return)||(yield xi(s.call(d)))}finally{if(n)throw n.error}}for(const e of a.flush()){const t=i.decode(e);t&&(yield yield xi(t))}}))}(t,r));!(e=(l=yield xi(d.next())).done);u=!0){a=l.value,u=!1;const e=a;if(!c)if(e.data.startsWith("[DONE]"))c=!0;else try{yield yield xi(JSON.parse(e.data))}catch(t){throw o.error("Could not parse message into JSON:",e.data),o.error("From chunk:",e.raw),t}}}catch(e){n={error:e}}finally{try{u||e||!(i=d.return)||(yield xi(i.call(d)))}finally{if(n)throw n.error}}c=!0}catch(e){if(ji(e))return yield xi(void 0);throw e}finally{c||r.abort()}}))}),r,n)}static fromReadableStream(t,r,n){let s=!1;return new e((function(){return Di(this,arguments,(function*(){var e,n,o,i;if(s)throw new Fi("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");s=!0;let a=!1;try{try{for(var c,l=!0,u=Ui(function(){return Di(this,arguments,(function*(){var e,r,n,s;const o=new Ta,i=sa(t);try{for(var a,c=!0,l=Ui(i);!(e=(a=yield xi(l.next())).done);c=!0){s=a.value,c=!1;const e=s;for(const t of o.decode(e))yield yield xi(t)}}catch(e){r={error:e}}finally{try{c||e||!(n=l.return)||(yield xi(n.call(l)))}finally{if(r)throw r.error}}for(const e of o.flush())yield yield xi(e)}))}());!(e=(c=yield xi(u.next())).done);l=!0){i=c.value,l=!1;const e=i;a||e&&(yield yield xi(JSON.parse(e)))}}catch(e){n={error:e}}finally{try{l||e||!(o=u.return)||(yield xi(o.call(u)))}finally{if(n)throw n.error}}a=!0}catch(e){if(ji(e))return yield xi(void 0);throw e}finally{a||r.abort()}}))}),r,n)}[Symbol.asyncIterator](){return this.iterator()}tee(){const t=[],r=[],n=this.iterator(),s=e=>({next:()=>{if(0===e.length){const e=n.next();t.push(e),r.push(e)}return e.shift()}});return[new e((()=>s(t)),this.controller,this.client),new e((()=>s(r)),this.controller,this.client)]}toReadableStream(){const e=this;let t;return ra({async start(){t=e[Symbol.asyncIterator]()},async pull(e){try{const{value:r,done:n}=await t.next();if(n)return e.close();const s=ba(JSON.stringify(r)+"\n");e.enqueue(s)}catch(t){e.error(t)}},async cancel(){var e;await(null===(e=t.return)||void 0===e?void 0:e.call(t))}})}};var xa=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;const e={event:this.event,data:this.data.join("\n"),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],e}if(this.chunks.push(e),e.startsWith(":"))return null;let[t,r,n]=function(e,t){const r=e.indexOf(t);if(-1!==r)return[e.substring(0,r),t,e.substring(r+t.length)];return[e,"",""]}(e,":");return n.startsWith(" ")&&(n=n.substring(1)),"event"===t?this.event=n:"data"===t&&this.data.push(n),null}};async function Da(e,t){const{response:r,requestLogID:n,retryOfRequestLogID:s,startTime:o}=t,i=await(async()=>{var n;if(t.options.stream)return ka(e).debug("response",r.status,r.url,r.headers,r.body),t.options.__streamClass?t.options.__streamClass.fromSSEResponse(r,t.controller,e):Pa.fromSSEResponse(r,t.controller,e);if(204===r.status)return null;if(t.options.__binaryResponse)return r;const s=r.headers.get("content-type"),o=null===(n=null==s?void 0:s.split(";")[0])||void 0===n?void 0:n.trim();if((null==o?void 0:o.includes("application/json"))||(null==o?void 0:o.endsWith("+json"))){if("0"===r.headers.get("content-length"))return;return await r.json()}return await r.text()})();return ka(e).debug(`[${n}] response parsed`,Na({retryOfRequestLogID:s,url:r.url,status:r.status,body:i,durationMs:Date.now()-o})),i}var Ua=class e extends Promise{constructor(e,t,r=Da){super((e=>{e(null)})),this.responsePromise=t,this.parseResponse=r,this.client=e}_thenUnwrap(t){return new e(this.client,this.responsePromise,(async(e,r)=>t(await this.parseResponse(e,r),r)))}asResponse(){return this.responsePromise.then((e=>e.response))}async withResponse(){const[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then((e=>this.parseResponse(this.client,e)))),this.parsedPromise}then(e,t){return this.parse().then(e,t)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}},La=Symbol("brand.privateNullableHeaders");function*ja(e){if(!e)return;if(La in e){const{values:t,nulls:r}=e;yield*t.entries();for(const e of r)yield[e,null];return}let t,r=!1;e instanceof Headers?t=e.entries():ea(e)?t=e:(r=!0,t=Object.entries(null!=e?e:{}));for(let e of t){const t=e[0];if("string"!=typeof t)throw new TypeError("expected header name to be a string");const n=ea(e[1])?e[1]:[e[1]];let s=!1;for(const e of n)void 0!==e&&(r&&!s&&(s=!0,yield[t,null]),yield[t,e])}}var Ma,Fa=e=>{const t=new Headers,r=new Set;for(const n of e){const e=new Set;for(const[s,o]of ja(n)){const n=s.toLowerCase();e.has(n)||(t.delete(s),e.add(n)),null===o?(t.delete(s),r.add(n)):(t.append(s,o),r.delete(n))}}return{[La]:!0,values:t,nulls:r}},Ba=e=>{var t,r,n,s,o;return void 0!==globalThis.process?(null===(r=null===(t=globalThis.process.env)||void 0===t?void 0:t[e])||void 0===r?void 0:r.trim())||void 0:void 0!==globalThis.Deno&&(null===(o=null===(s=null===(n=globalThis.Deno.env)||void 0===n?void 0:n.get)||void 0===s?void 0:s.call(n,e))||void 0===o?void 0:o.trim())||void 0},Ga=class e{constructor(t){var r,n,s,o,i,a,c,{baseURL:l=Ba("GEMINI_NEXT_GEN_API_BASE_URL"),apiKey:u=(null!==(r=Ba("GEMINI_API_KEY"))&&void 0!==r?r:null),apiVersion:d="v1beta"}=t,h=Ni(t,["baseURL","apiKey","apiVersion"]);const f=Object.assign(Object.assign({apiKey:u,apiVersion:d},h),{baseURL:l||"https://generativelanguage.googleapis.com"});this.baseURL=f.baseURL,this.timeout=null!==(n=f.timeout)&&void 0!==n?n:e.DEFAULT_TIMEOUT,this.logger=null!==(s=f.logger)&&void 0!==s?s:console;const p="warn";this.logLevel=p,this.logLevel=null!==(i=null!==(o=Aa(f.logLevel,"ClientOptions.logLevel",this))&&void 0!==o?o:Aa(Ba("GEMINI_NEXT_GEN_API_LOG"),"process.env['GEMINI_NEXT_GEN_API_LOG']",this))&&void 0!==i?i:p,this.fetchOptions=f.fetchOptions,this.maxRetries=null!==(a=f.maxRetries)&&void 0!==a?a:2,this.fetch=null!==(c=f.fetch)&&void 0!==c?c:function(){if("undefined"!=typeof fetch)return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new GeminiNextGenAPIClient({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}(),this.encoder=oa,this._options=f,this.apiKey=u,this.apiVersion=d,this.clientAdapter=f.clientAdapter}withOptions(e){return new this.constructor(Object.assign(Object.assign(Object.assign({},this._options),{baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,apiVersion:this.apiVersion}),e))}baseURLOverridden(){return"https://generativelanguage.googleapis.com"!==this.baseURL}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t}){if(!e.has("authorization")&&!e.has("x-goog-api-key")&&!(this.apiKey&&e.get("x-goog-api-key")||t.has("x-goog-api-key")))throw new Error('Could not resolve authentication method. Expected the apiKey to be set. Or for the "x-goog-api-key" headers to be explicitly omitted')}async authHeaders(e){const t=Fa([e.headers]);if(!t.values.has("authorization")&&!t.values.has("x-goog-api-key"))return this.apiKey?Fa([{"x-goog-api-key":this.apiKey}]):this.clientAdapter&&this.clientAdapter.isVertexAI()?Fa([await this.clientAdapter.getAuthHeaders()]):void 0}stringifyQuery(e){return function(e){return Object.entries(e).filter((([e,t])=>void 0!==t)).map((([e,t])=>{if("string"==typeof t||"number"==typeof t||"boolean"==typeof t)return`${encodeURIComponent(e)}=${encodeURIComponent(t)}`;if(null===t)return`${encodeURIComponent(e)}=`;throw new Fi(`Cannot stringify type ${typeof t}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)})).join("&")}(e)}getUserAgent(){return`${this.constructor.name}/JS 0.0.1`}defaultIdempotencyKey(){return`stainless-node-retry-${Li()}`}makeStatusError(e,t,r,n){return Bi.generate(e,t,r,n)}buildURL(e,t,r){const n=!this.baseURLOverridden()&&r||this.baseURL,s=(e=>Zi.test(e))(e)?new URL(e):new URL(n+(n.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),o=this.defaultQuery(),i=Object.fromEntries(s.searchParams);return ta(o)&&ta(i)||(t=Object.assign(Object.assign(Object.assign({},i),o),t)),"object"==typeof t&&t&&!Array.isArray(t)&&(s.search=this.stringifyQuery(t)),s.toString()}async prepareOptions(e){if(this.clientAdapter&&this.clientAdapter.isVertexAI()&&!e.path.startsWith(`/${this.apiVersion}/projects/`)){const t=e.path.slice(this.apiVersion.length+1);e.path=`/${this.apiVersion}/projects/${this.clientAdapter.getProject()}/locations/${this.clientAdapter.getLocation()}${t}`}}async prepareRequest(e,{url:t,options:r}){}get(e,t){return this.methodRequest("get",e,t)}post(e,t){return this.methodRequest("post",e,t)}patch(e,t){return this.methodRequest("patch",e,t)}put(e,t){return this.methodRequest("put",e,t)}delete(e,t){return this.methodRequest("delete",e,t)}methodRequest(e,t,r){return this.request(Promise.resolve(r).then((r=>Object.assign({method:e,path:t},r))))}request(e,t=null){return new Ua(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,r){var n,s,o;const i=await e,a=null!==(n=i.maxRetries)&&void 0!==n?n:this.maxRetries;null==t&&(t=a),await this.prepareOptions(i);const{req:c,url:l,timeout:u}=await this.buildRequest(i,{retryCount:a-t});await this.prepareRequest(c,{url:l,options:i});const d="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),h=void 0===r?"":`, retryOf: ${r}`,f=Date.now();if(ka(this).debug(`[${d}] sending request`,Na({retryOfRequestLogID:r,method:i.method,url:l,options:i,headers:c.headers})),null===(s=i.signal)||void 0===s?void 0:s.aborted)throw new Gi;const p=new AbortController,m=await this.fetchWithTimeout(l,c,u,p).catch(Mi),_=Date.now();if(m instanceof globalThis.Error){const e=`retrying, ${t} attempts remaining`;if(null===(o=i.signal)||void 0===o?void 0:o.aborted)throw new Gi;const n=ji(m)||/timed? ?out/i.test(String(m)+("cause"in m?String(m.cause):""));if(t)return ka(this).info(`[${d}] connection ${n?"timed out":"failed"} - ${e}`),ka(this).debug(`[${d}] connection ${n?"timed out":"failed"} (${e})`,Na({retryOfRequestLogID:r,url:l,durationMs:_-f,message:m.message})),this.retryRequest(i,t,null!=r?r:d);if(ka(this).info(`[${d}] connection ${n?"timed out":"failed"} - error; no more retries left`),ka(this).debug(`[${d}] connection ${n?"timed out":"failed"} (error; no more retries left)`,Na({retryOfRequestLogID:r,url:l,durationMs:_-f,message:m.message})),n)throw new qi;throw new Hi({cause:m})}const y=`[${d}${h}] ${c.method} ${l} ${m.ok?"succeeded":"failed"} with status ${m.status} in ${_-f}ms`;if(!m.ok){const e=await this.shouldRetry(m);if(t&&e){const e=`retrying, ${t} attempts remaining`;return await async function(e){var t,r;if(null===e||"object"!=typeof e)return;if(e[Symbol.asyncIterator])return void await(null===(r=(t=e[Symbol.asyncIterator]()).return)||void 0===r?void 0:r.call(t));const n=e.getReader(),s=n.cancel();n.releaseLock(),await s}(m.body),ka(this).info(`${y} - ${e}`),ka(this).debug(`[${d}] response error (${e})`,Na({retryOfRequestLogID:r,url:m.url,status:m.status,headers:m.headers,durationMs:_-f})),this.retryRequest(i,t,null!=r?r:d,m.headers)}const n=e?"error; no more retries left":"error; not retryable";ka(this).info(`${y} - ${n}`);const s=await m.text().catch((e=>Mi(e).message)),o=(e=>{try{return JSON.parse(e)}catch(e){return}})(s),a=o?void 0:s;ka(this).debug(`[${d}] response error (${n})`,Na({retryOfRequestLogID:r,url:m.url,status:m.status,headers:m.headers,message:a,durationMs:Date.now()-f}));throw this.makeStatusError(m.status,o,a,m.headers)}return ka(this).info(y),ka(this).debug(`[${d}] response start`,Na({retryOfRequestLogID:r,url:m.url,status:m.status,headers:m.headers,durationMs:_-f})),{response:m,options:i,controller:p,requestLogID:d,retryOfRequestLogID:r,startTime:f}}async fetchWithTimeout(e,t,r,n){const s=t||{},{signal:o,method:i}=s,a=Ni(s,["signal","method"]),c=this._makeAbort(n);o&&o.addEventListener("abort",c,{once:!0});const l=setTimeout(c,r),u=globalThis.ReadableStream&&a.body instanceof globalThis.ReadableStream||"object"==typeof a.body&&null!==a.body&&Symbol.asyncIterator in a.body,d=Object.assign(Object.assign(Object.assign({signal:n.signal},u?{duplex:"half"}:{}),{method:"GET"}),a);i&&(d.method=i.toUpperCase());try{return await this.fetch.call(void 0,e,d)}finally{clearTimeout(l)}}async shouldRetry(e){const t=e.headers.get("x-should-retry");return"true"===t||"false"!==t&&(408===e.status||(409===e.status||(429===e.status||e.status>=500)))}async retryRequest(e,t,r,n){var s;let o;const i=null==n?void 0:n.get("retry-after-ms");if(i){const e=parseFloat(i);Number.isNaN(e)||(o=e)}const a=null==n?void 0:n.get("retry-after");if(a&&!o){const e=parseFloat(a);o=Number.isNaN(e)?Date.parse(a)-Date.now():1e3*e}if(void 0===o){const r=null!==(s=e.maxRetries)&&void 0!==s?s:this.maxRetries;o=this.calculateDefaultRetryTimeoutMillis(t,r)}var c;return await(c=o,new Promise((e=>setTimeout(e,c)))),this.makeRequest(e,t-1,r)}calculateDefaultRetryTimeoutMillis(e,t){const r=t-e;return Math.min(.5*Math.pow(2,r),8)*(1-.25*Math.random())*1e3}async buildRequest(e,{retryCount:t=0}={}){var r,n,s;const o=Object.assign({},e),{method:i,path:a,query:c,defaultBaseURL:l}=o,u=this.buildURL(a,c,l);"timeout"in o&&((e,t)=>{if("number"!=typeof t||!Number.isInteger(t))throw new Fi(`${e} must be an integer`);if(t<0)throw new Fi(`${e} must be a positive integer`)})("timeout",o.timeout),o.timeout=null!==(r=o.timeout)&&void 0!==r?r:this.timeout;const{bodyHeaders:d,body:h}=this.buildBody({options:o}),f=await this.buildHeaders({options:e,method:i,bodyHeaders:d,retryCount:t});return{req:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({method:i,headers:f},o.signal&&{signal:o.signal}),globalThis.ReadableStream&&h instanceof globalThis.ReadableStream&&{duplex:"half"}),h&&{body:h}),null!==(n=this.fetchOptions)&&void 0!==n?n:{}),null!==(s=o.fetchOptions)&&void 0!==s?s:{}),url:u,timeout:o.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:r,retryCount:n}){let s={};this.idempotencyHeader&&"get"!==t&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),s[this.idempotencyHeader]=e.idempotencyKey);const o=await this.authHeaders(e);let i=Fa([s,{Accept:"application/json","User-Agent":this.getUserAgent()},this._options.defaultHeaders,r,e.headers,o]);return this.validateHeaders(i),i.values}_makeAbort(e){return()=>e.abort()}buildBody({options:{body:e,headers:t}}){if(!e)return{bodyHeaders:void 0,body:void 0};const r=Fa([t]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||"string"==typeof e&&r.values.has("content-type")||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:e}:"object"==typeof e&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&"function"==typeof e.next)?{bodyHeaders:void 0,body:na(e)}:"object"==typeof e&&"application/x-www-form-urlencoded"===r.values.get("content-type")?{bodyHeaders:{"content-type":"application/x-www-form-urlencoded"},body:this.stringifyQuery(e)}:this.encoder({body:e,headers:r})}};Ga.DEFAULT_TIMEOUT=6e4;var Ha=class extends Ga{constructor(){super(...arguments),this.interactions=new ma(this),this.webhooks=new Ea(this)}};Ma=Ha,Ha.GeminiNextGenAPIClient=Ma,Ha.GeminiNextGenAPIClientError=Fi,Ha.APIError=Bi,Ha.APIConnectionError=Hi,Ha.APIConnectionTimeoutError=qi,Ha.APIUserAbortError=Gi,Ha.NotFoundError=Yi,Ha.ConflictError=zi,Ha.RateLimitError=Ki,Ha.BadRequestError=$i,Ha.AuthenticationError=Wi,Ha.InternalServerError=Xi,Ha.PermissionDeniedError=Vi,Ha.UnprocessableEntityError=Ji,Ha.toFile=async function(e,t,r){if(ia(),(e=>null!=e&&"object"==typeof e&&"string"==typeof e.name&&"number"==typeof e.lastModified&&ca(e))(e=await e))return e instanceof File?e:aa([await e.arrayBuffer()],e.name);if((e=>null!=e&&"object"==typeof e&&"string"==typeof e.url&&"function"==typeof e.blob)(e)){const n=await e.blob();return t||(t=new URL(e.url).pathname.split(/[\\/]/).pop()),aa(await la(n),t,r)}const n=await la(e);if(t||(t=function(e){return("object"==typeof e&&null!==e&&("name"in e&&e.name&&String(e.name)||"url"in e&&e.url&&String(e.url)||"filename"in e&&e.filename&&String(e.filename)||"path"in e&&e.path&&String(e.path))||"").split(/[\\/]/).pop()||void 0}(e)),!(null==r?void 0:r.type)){const e=n.find((e=>"object"==typeof e&&"type"in e&&e.type));"string"==typeof e&&(r=Object.assign(Object.assign({},r),{type:e}))}return aa(n,t,r)},Ha.Interactions=ma,Ha.Webhooks=Ea;var qa={text:{to:e=>({text:e.text}),from:e=>({id:d.v4(),type:"text",text:e.text})},summary:{to:e=>({text:`[Summary]: ${e.text}`}),from:e=>({id:d.v4(),type:"summary",text:e.text})},thinking:{to:e=>({text:e.thinking}),from:e=>({id:d.v4(),type:"thinking",thinking:e.thinking})},"tool:use":{to:e=>({functionCall:{name:e.name,args:e.input}}),from:e=>({id:d.v4(),type:"tool:use",name:e.functionCall?.name??e.name,input:e.functionCall?.args??e.input??{}})},"tool:result":{to:e=>({functionResponse:{name:e.useId,response:{result:e.content}}}),from:e=>({id:d.v4(),type:"tool:result",useId:e.useId,content:e.content,isError:e.isError})},"role:transition":{to:e=>({text:`[Role transition: ${e.previousRole??"none"} → ${e.newRole}]`}),from:e=>({id:d.v4(),type:"role:transition",previousRole:e.previousRole,newRole:e.newRole})}},$a=[{provider:"google",name:"gemini-3.1-pro-preview",window:{size:1048576,out:65536},feature:{vision:!0,tools:!0,json:!0,cache:!0,streaming:!0,thinking:!0},pricing:[{unit:"token",scale:6,cost:{input:2,output:12,cache:{read:.2,write:4.5}}}],capacity:[{unit:"token",max:1e6,period:60}]},{provider:"google",name:"gemini-3-flash-preview",window:{size:1048576,out:65536},feature:{vision:!0,tools:!0,json:!0,cache:!0,streaming:!0,thinking:!0},pricing:[{unit:"token",scale:6,cost:{input:.5,output:3,cache:{read:.05,write:1}}}],capacity:[{unit:"token",max:1e6,period:60}]},{provider:"google",name:"gemini-3.1-flash-lite-preview",window:{size:1048576,out:65536},feature:{vision:!0,tools:!0,json:!0,cache:!0,streaming:!0,thinking:!0},pricing:[{unit:"token",scale:6,cost:{input:.25,output:1.5,cache:{read:.025,write:1}}}],capacity:[{unit:"token",max:4e6,period:60}]},{provider:"google",name:"gemini-2.5-pro",window:{size:1048576,out:65536},feature:{vision:!0,tools:!0,json:!0,cache:!0,streaming:!0,thinking:!0},pricing:[{unit:"token",scale:6,cost:{input:1.25,output:10,cache:{read:.125,write:4.5}}}],capacity:[{unit:"token",max:4e6,period:60}]},{provider:"google",name:"gemini-2.5-flash",window:{size:1048576,out:65536},feature:{vision:!0,tools:!0,json:!0,cache:!0,streaming:!0,thinking:!0},pricing:[{unit:"token",scale:6,cost:{input:.3,output:2.5,cache:{read:.03,write:1}}}],capacity:[{unit:"call",max:4e3,period:60},{unit:"token",max:4e6,period:60}]},{provider:"google",name:"gemini-2.5-flash-lite",window:{size:1048576,out:65536},feature:{vision:!0,tools:!0,json:!0,cache:!0,streaming:!0,thinking:!0},pricing:[{unit:"token",scale:6,cost:{input:.1,output:.4,cache:{read:.01,write:1}}}],capacity:[{unit:"call",max:4e3,period:60},{unit:"token",max:4e6,period:60}]},{provider:"google",name:"gemini-3-pro-preview",window:{size:1048576,out:65536},feature:{vision:!0,tools:!0,json:!0,cache:!0,streaming:!0,thinking:!0},pricing:[{unit:"token",scale:6,cost:{input:2,output:12,cache:{read:.2,write:4.5}}}],capacity:[{unit:"token",max:1e6,period:60}]},{provider:"google",name:"gemini-2.5-flash-image",window:{size:4096,out:0},feature:{vision:!1,tools:!1,json:!1,cache:!1,streaming:!1,thinking:!1},pricing:[{unit:"image",scale:0,cost:{input:.02,output:0}}],capacity:[{unit:"call",max:100,period:60}]},{provider:"google",name:"gemini-2.5-flash-live-preview",window:{size:1048576,out:65536},feature:{vision:!0,tools:!0,json:!0,cache:!1,streaming:!0,thinking:!0},pricing:[{unit:"token",scale:6,cost:{input:.5,output:3}}],capacity:[{unit:"concurrent",max:10,period:0}]},{provider:"google",name:"gemini-3.1-flash-live-preview",window:{size:1048576,out:65536},feature:{vision:!0,tools:!0,json:!0,cache:!1,streaming:!0,thinking:!0},pricing:[{unit:"token",scale:6,cost:{input:.5,output:3}}],capacity:[{unit:"concurrent",max:10,period:0}]},{provider:"google",name:"gemini-2.5-computer-use-preview",window:{size:1048576,out:65536},feature:{vision:!0,tools:!0,json:!0,cache:!1,streaming:!0,thinking:!0},pricing:[{unit:"token",scale:6,cost:{input:1.25,output:10}}],capacity:[{unit:"call",max:200,period:60},{unit:"token",max:1e6,period:60}]},{provider:"google",name:"gemini-embedding-001",window:{size:2048,out:0},feature:{vision:!1,tools:!1,json:!1,cache:!1,streaming:!1,thinking:!1},pricing:[{unit:"token",scale:6,cost:{input:.5,output:0}}],capacity:[{unit:"token",max:1e6,period:60}]},{provider:"google",name:"gemini-embedding-2",window:{size:8192,out:0},feature:{vision:!1,tools:!1,json:!1,cache:!1,streaming:!1,thinking:!1},pricing:[{unit:"token",scale:6,cost:{input:.3,output:0}}],capacity:[{unit:"token",max:1e6,period:60}]}];function Wa(e,t){const r=e.candidates?.[0];if(!r?.content?.parts)return bn({code:"BACKEND_ERROR",reason:"No valid content parts in response"});const n=[];let s;for(const e of r.content.parts)if(e.thought)n.push((o=e.text??"",{id:d.v7(),type:"thinking",thinking:o}));else if(e.text){s=e;break}var o;if(!s)return bn({code:"BACKEND_ERROR",reason:"Response missing JSON part"});const i=function(e){try{const t=JSON.parse(e);return t.blocks&&Array.isArray(t.blocks)?En(t.blocks):bn({code:"BACKEND_ERROR",reason:'Invalid response: missing or malformed "blocks" array'})}catch(e){return bn({code:"BACKEND_ERROR",reason:`Failed to parse response JSON: ${e instanceof Error?e.message:String(e)}`})}}(s.text);if(!i.ok)return i;for(const e of i.value){const r=t.parse(e,Ka.provider());r&&n.push(r)}return En(n)}async function Va(e,t,r){const n="assistant"===e.actor?"model":"user",s=[];for(const n of e.blocks){if("image"===n.type||"document"===n.type){const e=n.ref;if(!e)continue;const r=await za(e,t);r&&s.push(r);continue}const e=Ya(n,r);e&&s.push(e)}return{role:n,parts:s}}function Ya(e,t){const r=t.get(e.type);if(!r)throw new Error(`[GoogleGenAIAdapter] mapBlockToPart: block type "${e.type}" is not registered. Register it via registry.register() before use.`);const n=r.mappings?.[Ka.provider()];if(!n)throw new Error(`[GoogleGenAIAdapter] mapBlockToPart: no "${Ka.provider()}" mapping for block type "${e.type}". Add a mapping via registry.update("${e.type}", { mappings: { ${Ka.provider()}: { to, from } } }).`);return n.to(e)}async function za(e,t){const r=await t(e,Ka.provider());if(!r.ok||!r.value)return null;const{value:n}=r;return"remote"===n.kind?{fileData:{fileUri:n.fileId,mimeType:n.mediaType}}:{inlineData:{data:vn(n.data),mimeType:n.mediaType}}}function Ja(e){return Math.ceil(e.length/4)}var Ka=class e{constructor(e,t,r={model:"gemini-2.5-flash"}){this.client=e,this.services=t,this._models=t.models;const n=this._models.get(r.model);if(!n)throw new Error(`Could not get model: ${r.model} profile in registry.`);this.model=n,this.registerGeminiMappings()}model;_models;registerGeminiMappings(){const t=this.services.blockRegistry;for(const[r,n]of Object.entries(qa))t.update(r,{mappings:{[e.provider()]:n}})}async status(t){return{provider:e.provider(),model:this.model.name,ready:!0,window:this.model.window,feature:{vision:!0,tools:!0,json:!0,cache:!1,streaming:!0,thinking:!0},pricing:[{unit:"token",scale:6,cost:{input:.1,output:.4}}],rate:{load:0,capacity:[{unit:"call",max:1e3,period:60},{unit:"token",max:4e6,period:60}]}}}async resolve(e){const{prompt:t}=e,{assembler:r,blockRegistry:n,blobResolver:s}=this.services,o=t.model&&this._models.get(t.model)||this.model,i=r.build(t,[{label:"block-architecture",content:n.description(),position:"after:instructions"}]),a=r.join(i),c={role:"system",parts:[{text:a}]},l=t.constraints[o.name]??{tokens:{}},u=await Promise.all(t.transcript.map((e=>Va(e,s,n)))),h=n.schema(),f={model:o.name,contents:u,config:{systemInstruction:c,thinkingConfig:{includeThoughts:!0},responseMimeType:"application/json",responseSchema:h,...void 0!==l.temperature&&{temperature:l.temperature},...void 0!==l.tokens.max&&{maxOutputTokens:l.tokens.max},...l.tokens.stops?.length&&{stopSequences:l.tokens.stops},...void 0!==l.tokens.thought&&{thinkingConfig:{includeThoughts:!0,thinkingBudget:l.tokens.thought}}}},p=u.flatMap((e=>e.parts??[])).map((e=>e.text??"")).join(""),m=Ja(a),_=Ja(p),y=m+_,g=this;return{model:o.name,instructions:i,transcript:t.transcript,context:t.system.context,preferences:t.system.preferences,constraints:l,tokens:{breakdown:{system:m,transcript:_},total:y,source:"estimated",output:l.tokens.max??o.window.out,remaining:o.window.size-y},async execute(){let e;try{e=await g.client.models.generateContent(f)}catch(e){return bn({code:"BACKEND_ERROR",reason:e instanceof Error?e.message:String(e)})}const r=Wa(e,g.services.blockRegistry);if(!r.ok)return r;const n=r.value,s=new Hn("assistant",t.session);for(const e of n)s.addBlock(e);return En({turn:s.build(),effects:[]})},async*executeStream(){let e;try{e=await g.client.models.generateContentStream(f)}catch(e){const r=e instanceof Error?e.message:String(e),n=new Hn("assistant",t.session);return n.addBlock({id:d.v7(),type:"text",text:`[Stream error: ${r}]`}),void(yield{turn:n.build(),effects:[]})}const r=[];for await(const t of e){const e=t.candidates?.[0];if(e?.content?.parts)for(const t of e.content.parts)t.thought||t.text&&(r.push(t.text),yield{blocks:[{id:d.v7(),type:"text",text:t.text}]})}const n=r.join(""),s=new Hn("assistant",t.session);s.addBlock({id:d.v7(),type:"text",text:n}),yield{turn:s.build(),effects:[]}}}}static provider(){return"google"}static models(){return $a}};
|
|
2
|
-
/*! Bundled license information:
|
|
3
|
-
|
|
4
|
-
web-streams-polyfill/dist/ponyfill.es2018.js:
|
|
5
|
-
(**
|
|
6
|
-
* @license
|
|
7
|
-
* web-streams-polyfill v3.3.3
|
|
8
|
-
* Copyright 2024 Mattias Buelens, Diwank Singh Tomer and other contributors.
|
|
9
|
-
* This code is released under the MIT license.
|
|
10
|
-
* SPDX-License-Identifier: MIT
|
|
11
|
-
*)
|
|
12
|
-
|
|
13
|
-
fetch-blob/index.js:
|
|
14
|
-
(*! fetch-blob. MIT License. Jimmy Wärting <https://jimmy.warting.se/opensource> *)
|
|
15
|
-
|
|
16
|
-
formdata-polyfill/esm.min.js:
|
|
17
|
-
(*! formdata-polyfill. MIT License. Jimmy Wärting <https://jimmy.warting.se/opensource> *)
|
|
18
|
-
|
|
19
|
-
node-domexception/index.js:
|
|
20
|
-
(*! node-domexception. MIT License. Jimmy Wärting <https://jimmy.warting.se/opensource> *)
|
|
21
|
-
|
|
22
|
-
@google/genai/dist/node/index.mjs:
|
|
23
|
-
(**
|
|
24
|
-
* @license
|
|
25
|
-
* Copyright 2025 Google LLC
|
|
26
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
27
|
-
*)
|
|
28
|
-
|
|
29
|
-
@google/genai/dist/node/index.mjs:
|
|
30
|
-
(**
|
|
31
|
-
* @license
|
|
32
|
-
* Copyright 2025 Google LLC
|
|
33
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
34
|
-
*)
|
|
35
|
-
|
|
36
|
-
@google/genai/dist/node/index.mjs:
|
|
37
|
-
(**
|
|
38
|
-
* @license
|
|
39
|
-
* Copyright 2025 Google LLC
|
|
40
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
41
|
-
*)
|
|
42
|
-
|
|
43
|
-
@google/genai/dist/node/index.mjs:
|
|
44
|
-
(**
|
|
45
|
-
* @license
|
|
46
|
-
* Copyright 2025 Google LLC
|
|
47
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
48
|
-
*)
|
|
49
|
-
|
|
50
|
-
@google/genai/dist/node/index.mjs:
|
|
51
|
-
(**
|
|
52
|
-
* @license
|
|
53
|
-
* Copyright 2025 Google LLC
|
|
54
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
55
|
-
*)
|
|
56
|
-
|
|
57
|
-
@google/genai/dist/node/index.mjs:
|
|
58
|
-
(**
|
|
59
|
-
* @license
|
|
60
|
-
* Copyright 2025 Google LLC
|
|
61
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
62
|
-
*)
|
|
63
|
-
|
|
64
|
-
@google/genai/dist/node/index.mjs:
|
|
65
|
-
(**
|
|
66
|
-
* @license
|
|
67
|
-
* Copyright 2025 Google LLC
|
|
68
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
69
|
-
*)
|
|
70
|
-
|
|
71
|
-
@google/genai/dist/node/index.mjs:
|
|
72
|
-
(**
|
|
73
|
-
* @license
|
|
74
|
-
* Copyright 2025 Google LLC
|
|
75
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
76
|
-
*)
|
|
77
|
-
|
|
78
|
-
@google/genai/dist/node/index.mjs:
|
|
79
|
-
(**
|
|
80
|
-
* @license
|
|
81
|
-
* Copyright 2025 Google LLC
|
|
82
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
83
|
-
*)
|
|
84
|
-
|
|
85
|
-
@google/genai/dist/node/index.mjs:
|
|
86
|
-
(**
|
|
87
|
-
* @license
|
|
88
|
-
* Copyright 2025 Google LLC
|
|
89
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
90
|
-
*)
|
|
91
|
-
|
|
92
|
-
@google/genai/dist/node/index.mjs:
|
|
93
|
-
(**
|
|
94
|
-
* @license
|
|
95
|
-
* Copyright 2025 Google LLC
|
|
96
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
97
|
-
*)
|
|
98
|
-
|
|
99
|
-
@google/genai/dist/node/index.mjs:
|
|
100
|
-
(**
|
|
101
|
-
* @license
|
|
102
|
-
* Copyright 2025 Google LLC
|
|
103
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
104
|
-
*)
|
|
105
|
-
|
|
106
|
-
@google/genai/dist/node/index.mjs:
|
|
107
|
-
(**
|
|
108
|
-
* @license
|
|
109
|
-
* Copyright 2025 Google LLC
|
|
110
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
111
|
-
*)
|
|
112
|
-
|
|
113
|
-
@google/genai/dist/node/index.mjs:
|
|
114
|
-
(**
|
|
115
|
-
* @license
|
|
116
|
-
* Copyright 2025 Google LLC
|
|
117
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
118
|
-
*)
|
|
119
|
-
|
|
120
|
-
@google/genai/dist/node/index.mjs:
|
|
121
|
-
(**
|
|
122
|
-
* @license
|
|
123
|
-
* Copyright 2025 Google LLC
|
|
124
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
125
|
-
*)
|
|
126
|
-
|
|
127
|
-
@google/genai/dist/node/index.mjs:
|
|
128
|
-
(**
|
|
129
|
-
* @license
|
|
130
|
-
* Copyright 2025 Google LLC
|
|
131
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
132
|
-
*)
|
|
133
|
-
|
|
134
|
-
@google/genai/dist/node/index.mjs:
|
|
135
|
-
(**
|
|
136
|
-
* @license
|
|
137
|
-
* Copyright 2025 Google LLC
|
|
138
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
139
|
-
*)
|
|
140
|
-
|
|
141
|
-
@google/genai/dist/node/index.mjs:
|
|
142
|
-
(**
|
|
143
|
-
* @license
|
|
144
|
-
* Copyright 2025 Google LLC
|
|
145
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
146
|
-
*)
|
|
147
|
-
|
|
148
|
-
@google/genai/dist/node/index.mjs:
|
|
149
|
-
(**
|
|
150
|
-
* @license
|
|
151
|
-
* Copyright 2025 Google LLC
|
|
152
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
153
|
-
*)
|
|
154
|
-
|
|
155
|
-
@google/genai/dist/node/index.mjs:
|
|
156
|
-
(**
|
|
157
|
-
* @license
|
|
158
|
-
* Copyright 2025 Google LLC
|
|
159
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
160
|
-
*)
|
|
161
|
-
|
|
162
|
-
@google/genai/dist/node/index.mjs:
|
|
163
|
-
(**
|
|
164
|
-
* @license
|
|
165
|
-
* Copyright 2025 Google LLC
|
|
166
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
167
|
-
*)
|
|
168
|
-
|
|
169
|
-
@google/genai/dist/node/index.mjs:
|
|
170
|
-
(**
|
|
171
|
-
* @license
|
|
172
|
-
* Copyright 2025 Google LLC
|
|
173
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
174
|
-
*)
|
|
175
|
-
|
|
176
|
-
@google/genai/dist/node/index.mjs:
|
|
177
|
-
(**
|
|
178
|
-
* @license
|
|
179
|
-
* Copyright 2025 Google LLC
|
|
180
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
181
|
-
*)
|
|
182
|
-
|
|
183
|
-
@google/genai/dist/node/index.mjs:
|
|
184
|
-
(**
|
|
185
|
-
* @license
|
|
186
|
-
* Copyright 2025 Google LLC
|
|
187
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
188
|
-
*)
|
|
189
|
-
|
|
190
|
-
@google/genai/dist/node/index.mjs:
|
|
191
|
-
(**
|
|
192
|
-
* @license
|
|
193
|
-
* Copyright 2025 Google LLC
|
|
194
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
195
|
-
*)
|
|
196
|
-
|
|
197
|
-
@google/genai/dist/node/index.mjs:
|
|
198
|
-
(**
|
|
199
|
-
* @license
|
|
200
|
-
* Copyright 2025 Google LLC
|
|
201
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
202
|
-
*)
|
|
203
|
-
|
|
204
|
-
@google/genai/dist/node/index.mjs:
|
|
205
|
-
(**
|
|
206
|
-
* @license
|
|
207
|
-
* Copyright 2025 Google LLC
|
|
208
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
209
|
-
*)
|
|
210
|
-
|
|
211
|
-
@google/genai/dist/node/index.mjs:
|
|
212
|
-
(**
|
|
213
|
-
* @license
|
|
214
|
-
* Copyright 2025 Google LLC
|
|
215
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
216
|
-
*)
|
|
217
|
-
|
|
218
|
-
@google/genai/dist/node/index.mjs:
|
|
219
|
-
(**
|
|
220
|
-
* @license
|
|
221
|
-
* Copyright 2025 Google LLC
|
|
222
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
223
|
-
*)
|
|
224
|
-
|
|
225
|
-
@google/genai/dist/node/index.mjs:
|
|
226
|
-
(**
|
|
227
|
-
* @license
|
|
228
|
-
* Copyright 2025 Google LLC
|
|
229
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
230
|
-
*)
|
|
231
|
-
|
|
232
|
-
@google/genai/dist/node/index.mjs:
|
|
233
|
-
(**
|
|
234
|
-
* @license
|
|
235
|
-
* Copyright 2025 Google LLC
|
|
236
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
237
|
-
*)
|
|
238
|
-
|
|
239
|
-
@google/genai/dist/node/index.mjs:
|
|
240
|
-
(**
|
|
241
|
-
* @license
|
|
242
|
-
* Copyright 2025 Google LLC
|
|
243
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
244
|
-
*)
|
|
245
|
-
|
|
246
|
-
@google/genai/dist/node/index.mjs:
|
|
247
|
-
(**
|
|
248
|
-
* @license
|
|
249
|
-
* Copyright 2025 Google LLC
|
|
250
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
251
|
-
*)
|
|
252
|
-
|
|
253
|
-
@google/genai/dist/node/index.mjs:
|
|
254
|
-
(**
|
|
255
|
-
* @license
|
|
256
|
-
* Copyright 2025 Google LLC
|
|
257
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
258
|
-
*)
|
|
259
|
-
|
|
260
|
-
@google/genai/dist/node/index.mjs:
|
|
261
|
-
(**
|
|
262
|
-
* @license
|
|
263
|
-
* Copyright 2025 Google LLC
|
|
264
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
265
|
-
*)
|
|
266
|
-
|
|
267
|
-
@google/genai/dist/node/index.mjs:
|
|
268
|
-
(**
|
|
269
|
-
* @license
|
|
270
|
-
* Copyright 2025 Google LLC
|
|
271
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
272
|
-
*)
|
|
273
|
-
|
|
274
|
-
@google/genai/dist/node/index.mjs:
|
|
275
|
-
(**
|
|
276
|
-
* @license
|
|
277
|
-
* Copyright 2025 Google LLC
|
|
278
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
279
|
-
*)
|
|
280
|
-
|
|
281
|
-
@google/genai/dist/node/index.mjs:
|
|
282
|
-
(**
|
|
283
|
-
* @license
|
|
284
|
-
* Copyright 2025 Google LLC
|
|
285
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
286
|
-
*)
|
|
287
|
-
*/
|
|
288
|
-
exports.COLLECTIONS=_n,exports.EMPTY_SYSTEM_ROLE=Gn,exports.GoogleAdapter=ki,exports.IndexedDBBlobStorage=class{dbName;db=null;constructor(e={}){this.dbName=e.dbName??"aiworkspace-blobs"}async open(){this.db||(this.db=await new Promise(((e,t)=>{const r=indexedDB.open(this.dbName,1);r.onupgradeneeded=e=>{const t=e.target.result;this.createSchema(t)},r.onsuccess=()=>e(r.result),r.onerror=()=>t(r.error),r.onblocked=()=>t(new Error(`[IndexedDBBlobStorage] Database "${this.dbName}" blocked.`))})),this.db.onversionchange=()=>{this.db?.close(),this.db=null})}createSchema(e){e.objectStoreNames.contains(rs)||e.createObjectStore(rs,{keyPath:"sha256"}),e.objectStoreNames.contains(ns)||e.createObjectStore(ns,{keyPath:"sha256"})}close(){this.db?.close(),this.db=null}async deleteDatabase(){this.close(),await new Promise(((e,t)=>{const r=indexedDB.deleteDatabase(this.dbName);r.onsuccess=()=>e(),r.onerror=()=>t(r.error)}))}getDB(){if(!this.db)throw new Error("[IndexedDBBlobStorage] Database not open. Call open() first.");return this.db}readTx(...e){return this.getDB().transaction(e,"readonly")}writeTx(...e){return this.getDB().transaction(e,"readwrite")}async storeBytes(e,t){const r=this.readTx(rs);if(await ss(r.objectStore(rs).get(e)))return;const n=this.writeTx(rs);n.objectStore(rs).put({sha256:e,data:t}),await os(n)}async loadBytes(e){const t=this.readTx(rs),r=await ss(t.objectStore(rs).get(e));return r?.data??null}async hasBytes(e){const t=this.readTx(rs);return await ss(t.objectStore(rs).count(e))>0}async deleteBytes(e){const t=this.writeTx(rs);t.objectStore(rs).delete(e),await os(t)}async saveRecord(e){const t=this.writeTx(ns);t.objectStore(ns).put(e),await os(t)}async loadRecord(e){const t=this.readTx(ns);return await ss(t.objectStore(ns).get(e))??null}async deleteRecord(e){const t=this.writeTx(ns);t.objectStore(ns).delete(e),await os(t)}async listRecords(){return ss(this.readTx(ns).objectStore(ns).getAll())}async exportAllBytes(){const e=this.readTx(rs);return(await ss(e.objectStore(rs).getAll())).map((({sha256:e,data:t})=>[e,t]))}async registerBlob(e,t){await new Promise(((r,n)=>{const s=this.getDB().transaction([rs,ns],"readwrite"),o=s.objectStore(rs),i=s.objectStore(ns),a=o.count(e.sha256);a.onsuccess=()=>{0===a.result&&o.put({sha256:e.sha256,data:t}),i.put(e)},a.onerror=()=>n(a.error),s.oncomplete=()=>r(),s.onerror=()=>n(s.error),s.onabort=()=>n(new Error("registerBlob transaction aborted"))}))}},exports.LRUCache=ts,exports.MemoryBlobStorage=class{bytes=new Map;records=new Map;async storeBytes(e,t){this.bytes.has(e)||this.bytes.set(e,t)}async loadBytes(e){return this.bytes.get(e)??null}async hasBytes(e){return this.bytes.has(e)}async deleteBytes(e){this.bytes.delete(e)}async saveRecord(e){this.records.set(e.sha256,{...e})}async loadRecord(e){return this.records.get(e)??null}async deleteRecord(e){this.records.delete(e)}async listRecords(){return Array.from(this.records.values()).map((e=>({...e})))}async exportAllBytes(){return Array.from(this.bytes.entries()).map((([e,t])=>[e,new Uint8Array(t)]))}async registerBlob(e,t){this.bytes.has(e.sha256)||this.bytes.set(e.sha256,t),this.records.set(e.sha256,{...e})}},exports.Session=Vn,exports.SessionManager=Yn,exports.TurnBuilder=Hn,exports.TurnTree=$n,exports.WorkspaceManager=Sn,exports.bufferToBase64=vn,exports.computeSHA256=Tn,exports.createEmptySession=(e={})=>({id:d.v7(),label:"New Conversation",role:"assistant-default",topics:[],preferences:[],metadata:{created:(new Date).toString(),updated:(new Date).toString()},...e,head:e.head?e.head:void 0}),exports.createEmptyTurn=(e={},t)=>({id:e.id??d.v7(),version:e.version??0,session:e.session??t?.id??d.v7(),actor:"user",blocks:[{id:d.v7(),type:"text",content:"Hello, world!"}],timestamp:(new Date).toString(),role:t?.role??"default",...e,parent:e.parent?e.parent:void 0}),exports.createEmptyWorkspace=(e={})=>({id:e.id??d.v7(),settings:wn({language:"en-US",defaultRole:void 0,prompt:void 0},e.settings),project:wn({id:d.v7(),name:"Unnamed Project"},e.project),index:wn({roles:{},preferences:{},context:{},sessions:{},topics:{},blobs:{},tools:{},extensions:{}},e.index)}),exports.createWorkspace=async function(e){const{blobStorage:t,eventBus:r=u.createEventBus(),getWorkspace:n,setWorkspace:s,processor:o,guard:i,toolRegistry:a,models:c=[],extensions:l=[],extensionReducers:d={},extensionMiddleware:h=[],extensionIndexers:f=[],extensionStores:p,extensionSchemas:m=[]}=e,_=mn(e.db),y=[...m,...l.flatMap((e=>e.schemas??[]))],g={...d,...l.reduce(((e,t)=>({...e,...t.reducers})),{})},E=[...h,...l.flatMap((e=>e.middleware??[]))],b=[...f,...l.flatMap((e=>e.indexers??[]))],w=l.flatMap((e=>e.blocks??[]));await _.open(y);const T={workspace:await _.collection(_n.WORKSPACE),role:await _.collection(_n.ROLE),preference:await _.collection(_n.PREFERENCE),context:await _.collection(_n.CONTEXT),session:await _.collection(_n.SESSION),topic:await _.collection(_n.TOPIC),turn:await _.collection(_n.TURN)},v=new zn(t,new ts(200),r),S=new Bn,A={workspaceStore:new es(T.workspace,new ts(1)),roles:new Xn(T.role,new ts(100)),preferences:new Kn(T.preference,new ts(500)),context:new Jn(T.context,new ts(500),S),topics:new An(T.topic,new ts(100)),sessions:new Zn(T.session,new ts(50)),turns:new Qn(T.turn,new ts(50)),blobs:v,tools:a,db:_,indexers:[...an,...b]};if(p){const e=p(A);Object.assign(A,e)}await Promise.all(l.map((async e=>{if(e.stores){const t=await e.stores(A);Object.assign(A,t)}})));const O=new Sn({ctx:A,getWorkspace:n,updateWorkspace:async e=>{if(await s(e),e?.id||e?.settings||e?.project){const e=n();await A.workspaceStore.update(e.id,{id:e.id,settings:e.settings,project:e.project})}},guard:i,bus:r});Object.entries(Un).forEach((([e,t])=>{O.register(e,t)})),Object.entries(g).forEach((([e,t])=>{O.register(e,t)})),O.use(Nn),E.forEach((e=>{O.use(e)}));const R=new Yn(O,o),C=new Fn;w.forEach((e=>C.register(e))),l.forEach((e=>{e.contexts&&e.contexts.forEach((e=>{if(S.register(e),e.store){const t=e.store(A);A.context.registerDelegate(e.kind,t)}}))}));const I=new Ln(c),k={assembler:new Dn,processor:o,blobResolver:A.blobs.resolve.bind(A.blobs),blockRegistry:C,contextRegistry:S,models:I};return{manager:O,sessions:R,ctx:A,services:k}},exports.createWorkspaceDatabase=mn,exports.del=function(){return yn},exports.error=bn,exports.getExtension=function(e,t){return e.extensions[t]},exports.merge=wn,exports.omitNullUndefined=function(e){return Object.fromEntries(Object.entries(e).filter((([e,t])=>null!=t)))},exports.shortHash=function(e,t=4){let r=0;for(let t=0;t<e.length;t++)r=(r<<5)-r+e.charCodeAt(t),r|=0;return Math.abs(r).toString(36).padEnd(t,"0").slice(0,t)},exports.success=En;
|
|
1
|
+
"use strict";var e=require("@asaidimu/utils-events"),t=require("uuid"),s=Object.defineProperty,r=[async e=>{const t=await e.workspaceStore.list();if(0===t.length)return{};const s=t[0];return{id:s.id,settings:s.settings,project:s.project}},async e=>{const t=await e.roles.list(),s={};for(const r of t)s[r.name]=e.roles.summarize(r);return{index:{roles:s}}},async e=>{const t=await e.preferences.list(),s={};for(const r of t)s[r.id]=e.preferences.summarize(r);return{index:{preferences:s}}},async e=>{const t=await e.context.list(),s={};for(const r of t)s[r.key]=e.context.summarize(r);return{index:{context:s}}},async e=>{const t=await e.sessions.list(),s={};for(const r of t)s[r.id]=e.sessions.summarize(r);return{index:{sessions:s}}},async e=>{const t=await e.topics.list(),s={};for(const r of t)s[r.name]=e.topics.summarize(r);return{index:{topics:s}}},async e=>({index:{blobs:await e.blobs.getAllRecords()}})],n=[{name:"workspace",version:"1.0.0",description:"Workspace root containing global settings and project metadata.",fields:{id:{name:"id",type:"string",required:!0},settings:{name:"settings",type:"record",required:!0},project:{name:"project",type:"record",required:!0}},indexes:[{name:"by_id",fields:["id"],type:"unique"}],constraints:[],migrations:[]},{name:"role",version:"1.0.0",description:"AI persona with a system prompt and associated preference defaults.",fields:{name:{name:"name",type:"string",required:!0},label:{name:"label",type:"string",required:!0},description:{name:"description",type:"string",required:!1},persona:{name:"persona",type:"string",required:!0},preferences:{name:"preferences",type:"array",required:!1,itemsType:"string"},topics:{name:"topics",type:"array",required:!1},constraints:{name:"constraints",type:"record",required:!1}},indexes:[{name:"by_name",fields:["name"],type:"unique"},{name:"by_label",fields:["label"],type:"normal"}],constraints:[],migrations:[]},{name:"preference",version:"1.0.0",description:"A user behavioural instruction, scoped to zero or more topics.",fields:{id:{name:"id",type:"string",required:!0},content:{name:"content",type:"string",required:!0},topics:{name:"topics",type:"array",required:!1,itemsType:"string"},timestamp:{name:"timestamp",type:"string",required:!0}},indexes:[{name:"by_id",fields:["id"],type:"unique"},{name:"by_topics",fields:["topics"],type:"normal"},{name:"by_timestamp",fields:["timestamp"],type:"btree"}],constraints:[],migrations:[]},{name:"context",version:"1.0.0",description:"Injected background knowledge, scoped to topics. Content is a discriminated union.",fields:{key:{name:"key",type:"string",required:!0},topics:{name:"topics",type:"array",required:!1,itemsType:"string"},content:{name:"content",type:"record",required:!0},timestamp:{name:"timestamp",type:"string",required:!0},metadata:{name:"metadata",type:"record",required:!1}},indexes:[{name:"by_key",fields:["key"],type:"unique"},{name:"by_topics",fields:["topics"],type:"normal"},{name:"by_timestamp",fields:["timestamp"],type:"btree"}],constraints:[],migrations:[]},{name:"session",version:"1.0.0",description:"Session metadata. The head field tracks the current tip of the turn DAG.",fields:{id:{name:"id",type:"string",required:!0},label:{name:"label",type:"string",required:!0},role:{name:"role",type:"string",required:!0},topics:{name:"topics",type:"array",required:!1,itemsType:"string"},preferences:{name:"preferences",type:"array",required:!1,itemsType:"string"},metadata:{name:"metadata",type:"record",required:!1},head:{name:"head",type:"record",required:!1},constraints:{name:"constraints",type:"record",required:!1}},indexes:[{name:"by_id",fields:["id"],type:"unique"},{name:"by_role",fields:["role"],type:"normal"}],constraints:[],migrations:[]},{name:"turn",version:"1.0.0",description:["A single message in a session transcript, stored as a flat document.","The DAG is reconstructed in memory by TurnTree.buildNodeGraph() at session open time."].join(" "),fields:{id:{name:"id",type:"string",required:!0},session:{name:"session",type:"string",required:!0},version:{name:"version",type:"number",required:!0},actor:{name:"actor",type:"enum",required:!0,values:["user","assistant","tool"]},blocks:{name:"blocks",type:"array",required:!0},timestamp:{name:"timestamp",type:"string",required:!0},role:{name:"role",type:"string",required:!1},parent:{name:"parent",type:"record",required:!1},constraints:{name:"constraints",type:"record",required:!1}},indexes:[{name:"by_session",fields:["session"],type:"normal"},{name:"by_session_parent",fields:["session","parent"],type:"composite"},{name:"by_session_id_ver",fields:["session","id","version"],type:"composite",unique:!0}],constraints:[],migrations:[]},{name:"topic",version:"1.0.0",description:"A categorization for context and preferences, used for retrieval.",fields:{name:{name:"name",type:"string",required:!0},label:{name:"label",type:"string",required:!1},description:{name:"description",type:"string",required:!1},metadata:{name:"metadata",type:"record",required:!1},created:{name:"created",type:"string",required:!0},updated:{name:"updated",type:"string",required:!0}},indexes:[{name:"by_name",fields:["name"],type:"unique"}],constraints:[],migrations:[]}],i=class e extends Error{constructor(t,s){super(t,{cause:s}),this.name="SyncError",Object.setPrototypeOf(this,e.prototype)}},o=class extends i{constructor(e){super(`[ArtifactContainer] Operation timed out: ${e}`)}},a=class extends i{constructor(e){super("[Serializer] The serializer has been marked as done!",e)}},c=class{_locked=!1;_capacity;_yieldMode;waiters=[];constructor(e){this._capacity=e?.capacity??1/0,this._yieldMode=e?.yieldMode??"macrotask"}async lock(e){if(!this._locked)return void(this._locked=!0);if(this.waiters.length>=this._capacity)throw new Error(`Mutex queue is full (capacity: ${this._capacity})`);let t;const s=new Promise((e=>t=e));if(this.waiters.push(t),null==e)return void await s;let r;await Promise.race([s.then((()=>clearTimeout(r))),new Promise(((s,n)=>{r=setTimeout((()=>{const e=this.waiters.indexOf(t);-1!==e&&this.waiters.splice(e,1),n(new o("Mutex lock timed out"))}),e)}))])}tryLock(){return!this._locked&&(this._locked=!0,!0)}unlock(){if(!this._locked)throw new Error("Mutex is not locked");const e=this.waiters.shift();e?"microtask"===this._yieldMode?queueMicrotask(e):setTimeout(e,0):this._locked=!1}locked(){return this._locked}pending(){return this.waiters.length}},d=class{mutex=new c({yieldMode:"microtask"});promise=null;_value=null;_error;_done=!1;retry;throws;constructor({retry:e,throws:t}={}){this.retry=Boolean(e),this.throws=Boolean(t)}async do(e,t){return this._done?this.peek():this.promise?this._awaitWithTimeout(this.promise,t,"Once do() timed out"):(await this.mutex.lock(),this.promise?(this.mutex.unlock(),this._awaitWithTimeout(this.promise,t,"Once do() timed out")):(this.promise=(async()=>{try{this._value=await e(),this._done=!0}catch(e){if(this._error=e,this.retry||(this._done=!0),this.throws)throw e}finally{this.retry&&!this._done&&(this.promise=null)}return this.peek()})(),this.mutex.unlock(),this._awaitWithTimeout(this.promise,t,"Once do() timed out")))}doSync(e){if(this._done){if(this.throws&&this._error)throw this._error;return this.peek()}if(this.promise){const e=new Error("Cannot execute doSync while an async operation is pending.");if(this.throws)throw e;return{value:null,error:e}}if(!this.mutex.tryLock()){const e=new Error("Cannot execute doSync: lock is currently held.");if(this.throws)throw e;return{value:null,error:e}}if(this.promise||this._done){if(this.mutex.unlock(),this._done){if(this.throws&&this._error)throw this._error;return this.peek()}const e=new Error("Cannot execute doSync while an async operation is pending.");if(this.throws)throw e;return{value:null,error:e}}try{const t=e();this._value=t,this._done=!0}catch(e){if(this._error=e,this.retry||(this._done=!0),this.throws)throw e}finally{this.mutex.unlock()}return this.peek()}running(){return null!==this.promise&&!this.done()}peek(){return{value:this._value,error:this._error}}get(){if(!this._done)throw new Error("Once operation is not yet complete");if(this._error)throw this._error;return this._value}reset(){if(this.running())throw new Error("Cannot reset Once while an operation is in progress.");this._done=!1,this.promise=null,this._value=null,this._error=void 0}done(){return this._done}current(){return this.promise}_awaitWithTimeout(e,t,s="Operation timed out"){if(null==t)return e;let r;return Promise.race([e.then((e=>(clearTimeout(r),e))),new Promise(((e,n)=>{r=setTimeout((()=>n(new o(s))),t)}))])}},u=class{mutex;_done=!1;_lastValue=null;_lastError=void 0;_hasRun=!1;constructor(e){this.mutex=new c({capacity:e?.capacity??1e3,yieldMode:e?.yieldMode??"macrotask"})}async do(e,t){if(this._done)return{value:null,error:new a};try{await this.mutex.lock(t)}catch(e){return{value:null,error:e}}let s,r=null;try{if(this._done)throw new a;r=await e(),this._lastValue=r,this._lastError=void 0,this._hasRun=!0}catch(e){s=e,this._lastError=e,this._hasRun=!0}finally{this.mutex.unlock()}return{value:r,error:s}}peek(){return{value:this._lastValue,error:this._lastError}}hasRun(){return this._hasRun}close(){this._done=!0}pending(){return this.mutex.pending()}running(){return this.mutex.locked()}};function l(e){const t=new d({retry:!0,throws:!0}),s=new d({retry:!0,throws:!0});return{open:async(s=[])=>(await t.do((async()=>{const t=[...n,...s];await e.setupCollections(t)}))).value,collection:async t=>e.collection(t),close:async()=>(await s.do((()=>{e.close()}))).value,database:()=>e}}var p={WORKSPACE:"workspace",ROLE:"role",PREFERENCE:"preference",CONTEXT:"context",SESSION:"session",TURN:"turn",BLOB:"blob",TOPIC:"topic"},h=Symbol.for("delete"),m=e=>Array.isArray(e)?[...e]:{...e};function f(e){return{ok:!0,value:e}}function y(e){return{ok:!1,error:e}}var w=function(e){const t=e?.deleteMarker||h;function s(e){if(null==e)return e;if(Array.isArray(e))return e.filter((e=>e!==t)).map((e=>"object"!=typeof e||null===e||Array.isArray(e)?e:s(e)));if("object"==typeof e){const r={};for(const[n,i]of Object.entries(e))if(i!==t)if("object"==typeof i&&null!==i){const e=s(i);void 0!==e&&(r[n]=e)}else r[n]=i;return r}return e===t?void 0:e}return function(e,r){if("object"!=typeof e||null===e)return"object"==typeof r&&null!==r?s(r):r===t?{}:r;if("object"!=typeof r||null===r)return e;const n=m(e),i=[{target:n,source:r}];for(;i.length>0;){const{target:e,source:s}=i.pop();for(const r of Object.keys(s)){const n=s[r];if(n!==t)if(Array.isArray(n))e[r]=n;else if("object"==typeof n&&null!==n){const t=r in e&&"object"==typeof e[r]&&null!==e[r]?e[r]:{};e[r]=m(t),i.push({target:e[r],source:n})}else e[r]=n;else delete e[r]}}return n}}({deleteMarker:h});async function g(e){const t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t)).map((e=>e.toString(16).padStart(2,"0"))).join("")}function b(e){if("undefined"!=typeof Buffer)return Buffer.from(e).toString("base64");const t=[];for(let s=0;s<e.length;s+=32768){const r=e.subarray(s,s+32768);t.push(String.fromCharCode.apply(null,Array.from(r)))}return btoa(t.join(""))}var k=class{registry=new Map;middlewares=[];serializer=new u;bus;_getWorkspace;updateWorkspace;guard;_ctx;constructor(e){this._ctx=e.ctx,this._getWorkspace=e.getWorkspace,this.updateWorkspace=e.updateWorkspace,this.guard=e.guard,this.bus=e.bus}register(e,t){return this.registry.set(e,t),this}use(e){return this.middlewares.push(e),this}workspace(){return this._getWorkspace()}async dispatch(e){const t=await this.serializer.do((async()=>{if(this.guard){const t=await this.guard.authenticate({type:"command",payload:e});if(!t.ok)return y(t.error)}const t=this.registry.get(e.type);if(!t)return y({code:"INVALID_COMMAND",reason:`No reducer registered for command type: ${e.type}`});const s=this._getWorkspace(),r=await t({workspace:s,...this._ctx},e.payload);if(!r.ok)return r;let n=r.value;for(const t of this.middlewares){const r=await t({workspace:s,command:e,patch:n,...this._ctx});n=w(n,r)}return await this.updateWorkspace(n),this.bus.emit({name:"workspace:changed",payload:n}),"workspace:sync"===e.type&&this.bus.emit({name:"workspace:synced",payload:void 0}),f(n)}));if(t.error)throw t.error;return t.value}subscribe(e,t){return this.bus.subscribe(e,t)}ctx(){return{workspace:this._getWorkspace(),...this._ctx}}},x=class{constructor(e,t){this.collection=e,this.cache=t}async get(e){const t=this.cache.get(e);if(t)return t;const s=await this.collection.find({field:"name",operator:"eq",value:e});if(!s)return null;const r=s.state();return this.cache.set(e,r),r}async add(e){await this.collection.create(e),this.cache.set(e.name,e)}async update(e,t){const s=await this.collection.find({field:"name",operator:"eq",value:e});if(!s)return null;await s.update(t);const r=s.state();return this.cache.set(e,r),r}async delete(e){const t=await this.collection.find({field:"name",operator:"eq",value:e});if(!t)return!1;const s=await t.delete();return s&&this.cache.delete(e),s}async getMany(e){if(0===e.length)return[];const t=[],s=[];for(const r of e){const e=this.cache.get(r);e?t.push(e):s.push(r)}if(s.length>0){const e=await this.collection.filter({operator:"or",conditions:s.map((e=>({field:"name",operator:"eq",value:e})))});for(const s of e){const e=s.state();this.cache.set(e.name,e),t.push(e)}}return t}async list(){const e=await this.collection.list({limit:1e3,type:"cursor",direction:"forward"});return((await e.next()).value||[]).map((e=>e.state()))}referencedBy(e,t){for(const s in t.roles)if(t.roles[s].topics?.includes(e))return!0;for(const s in t.sessions)if(t.sessions[s].topics?.includes(e))return!0;for(const s in t.context)if(t.context[s].topics?.includes(e))return!0;for(const s in t.preferences)if(t.preferences[s].topics?.includes(e))return!0;return!1}summarize(e){return{topic:e.name,contextKeys:[],preferences:[],metadata:{created:e.created,updated:e.updated,entries:0}}}};function v(e,t,s,r,n,i){const o={};for(const a of t){let t=e[a];if(!t){if("add"!==n||!i)continue;t={topic:a,contextKeys:[],preferences:[],metadata:{created:(new Date).toISOString(),updated:(new Date).toISOString(),entries:0}},i.add({name:a,created:t.metadata.created,updated:t.metadata.updated})}const c=t[r],d=c.includes(s);if("add"!==n||d){if("remove"===n&&d){const e=Math.max(0,(t.metadata.entries||0)-1);o[a]={...t,[r]:c.filter((e=>e!==s)),metadata:{...t.metadata,updated:(new Date).toISOString(),entries:e}}}}else o[a]={...t,[r]:[...c,s],metadata:{...t.metadata,updated:(new Date).toISOString(),entries:(t.metadata.entries||0)+1}}}return{index:{topics:o}}}function _(e,t,s,r){return v(e,t,s,"contextKeys","add",r)}function O(e,t,s){return v(e,t,s,"contextKeys","remove")}function S(e,t,s,r){return v(e,t,s,"preferences","add",r)}function T(e,t,s){return v(e,t,s,"preferences","remove")}var N=async e=>{if(!e.patch)return;const{workspace:t,patch:s}=e,r=t.index.topics;let n={};const i=e=>{const t=e?.index?.topics;t&&(n=w(n,t))};if(s.index?.context)for(const[n,o]of Object.entries(s.index.context)){const s=t.index.context[n];if(void 0===o&&s)i(O(r,s.topics,s.key));else if(s||!o){if(s&&o){const t=s.topics??[],n=o.topics??t,a=n.filter((e=>!t.includes(e))),c=t.filter((e=>!n.includes(e)));c.length&&i(O(r,c,s.key)),a.length&&i(_(r,a,s.key,e.topics))}}else i(_(r,o.topics??[],o.key,e.topics))}if(s.index?.preferences)for(const[n,o]of Object.entries(s.index.preferences)){const s=t.index.preferences[n];if(void 0===o&&s)i(T(r,s.topics,s.id));else if(s||!o){if(s&&o){const t=s.topics??[],n=o.topics??t,a=n.filter((e=>!t.includes(e))),c=t.filter((e=>!n.includes(e)));c.length&&i(T(r,c,s.id)),a.length&&i(S(r,a,s.id,e.topics))}}else i(S(r,o.topics??[],o.id,e.topics))}return Object.keys(n).length?{index:{topics:n}}:{}},R="\n# WORKSPACE OPERATING SYSTEM\nYou are operating within a structured workspace. Your output MUST be a JSON object matching the provided schema.\nYour entire response MUST be valid JSON. Nothing else.\n".trim();function D(e){if(!e||"append"===e)return{placement:"append",label:null};if("prepend"===e)return{placement:"prepend",label:null};const[t,...s]=e.split(":");return("before"===t||"after"===t)&&s.length>0?{placement:t,label:s.join(":")}:(console.warn(`[SystemPromptAssembler] Unrecognised position "${e}", defaulting to "append".`),{placement:"append",label:null})}var I=class{build(e,t=[]){const s=[...e.system.extensions||[],...t],r=[];var n,i,o;r.push({label:"operating-system",content:R}),e.role.persona&&r.push({label:"persona",content:(n=e.role.persona,`# Persona\n${n}`)}),e.system.preferences.length>0&&r.push({label:"preferences",content:(i=e.system.preferences,`# User Preferences\n${i.map((e=>`- ${e.content}`)).join("\n")}`),metadata:{count:e.system.preferences.length}}),e.system.context.length>0&&r.push({label:"context",content:(o=e.system.context,`# Context\n${o.map((e=>{switch(e.content.kind){case"text":return`[${e.key}] ${e.content.value}`;case"json":return`[${e.key}] JSON: ${JSON.stringify(e.content.value)}`;case"blob":return`[${e.key}] Blob: ${e.content.filename??"unnamed"} (${e.content.mediaType}, ${e.content.sizeBytes} bytes)`;case"remote":return`[${e.key}] Remote: ${e.content.uri}`;default:return`[${e.key}] Unsupported context type`}})).join("\n")}`),metadata:{count:e.system.context.length}}),e.system.instructions&&r.push({label:"instructions",content:`# Instructions\n${e.system.instructions}`});const a=[...r],c=[];for(const e of s){const{position:t,...s}=e,r=D(t);if("prepend"===r.placement){c.push(s);continue}if("append"===r.placement){a.push(s);continue}const n=a.findIndex((e=>e.label===r.label));if(-1===n){console.warn(`[SystemPromptAssembler] Anchor target "${r.label}" not found in sections. Extension "${e.label}" will be appended.`),a.push(s);continue}const i="before"===r.placement?n:n+1;a.splice(i,0,s)}return[...c,...a]}join(e){return e.map((e=>e.content)).join("\n\n---\n\n")}};var E={"workspace:create":async function(e,t){const{workspaceStore:s}=e,{id:r,settings:n,project:i}=t;return await s.add({id:r,settings:n,project:i}),f({id:r,settings:n,project:i})},"workspace:sync":async function(e,t){let s={};t&&(t.id&&(s.id=t.id),t.settings&&(s.settings=t.settings),t.project&&(s.project=t.project));for(const t of e.indexers){const r=await t(e);s=w(s,r)}return f(s)},"role:add":async function(e,t){const{workspace:s,roles:r}=e,n=t;return s.index.roles[n.name]?y({code:"DUPLICATE_KEY",resource:"Role",key:n.name}):(await r.add(n),f({index:{roles:{[n.name]:r.summarize(n)}}}))},"role:update":async function(e,t){const{workspace:s,roles:r}=e,{name:n,...i}=t;if(!s.index.roles[n])return y({code:"NOT_FOUND",resource:"Role",id:n});const o=await r.update(n,i);return o?f({index:{roles:{[n]:r.summarize(o)}}}):y({code:"BACKEND_ERROR",reason:`Failed to update role ${n} in store.`})},"role:delete":async function(e,t){const{workspace:s,roles:r}=e,{name:n}=t;return s.index.roles[n]?await r.delete(n)?f({index:{roles:{[n]:h}}}):y({code:"BACKEND_ERROR",reason:`Failed to delete role ${n} from store.`}):y({code:"NOT_FOUND",resource:"Role",id:n})},"preference:add":async function(e,t){const{workspace:s,preferences:r}=e,n=t;return s.index.preferences[n.id]?y({code:"DUPLICATE_KEY",resource:"Preference",key:n.id}):(await r.add(n),f({index:{preferences:{[n.id]:r.summarize(n)}}}))},"preference:update":async function(e,t){const{workspace:s,preferences:r}=e,{id:n,...i}=t;if(!s.index.preferences[n])return y({code:"NOT_FOUND",resource:"Preference",id:n});const o=await r.update(n,i);return o?f({index:{preferences:{[n]:r.summarize(o)}}}):y({code:"BACKEND_ERROR",reason:`Failed to update preference ${n} in store.`})},"preference:delete":async function(e,t){const{workspace:s,preferences:r}=e,{id:n}=t;return s.index.preferences[n]?await r.delete(n)?f({index:{preferences:{[n]:h}}}):y({code:"BACKEND_ERROR",reason:`Failed to delete preference ${n} from store.`}):y({code:"NOT_FOUND",resource:"Preference",id:n})},"context:add":async function(e,t){const{workspace:s,context:r}=e,n=t;return s.index.context[n.key]?y({code:"DUPLICATE_KEY",resource:"Context",key:n.key}):(await r.add(n),f({index:{context:{[n.key]:r.summarize(n)}}}))},"context:update":async function(e,t){const{workspace:s,context:r}=e,{key:n,...i}=t,o=s.index.context[n];if(!o)return y({code:"NOT_FOUND",resource:"Context",id:n});const a=await r.update(n,i,o.kind);return a?f({index:{context:{[n]:r.summarize(a)}}}):y({code:"BACKEND_ERROR",reason:`Failed to update context ${n} in store.`})},"context:delete":async function(e,t){const{workspace:s,context:r}=e,{key:n}=t,i=s.index.context[n];return i?await r.delete(n,i.kind)?f({index:{context:{[n]:h}}}):y({code:"BACKEND_ERROR",reason:`Failed to delete context ${n} from store.`}):y({code:"NOT_FOUND",resource:"Context",id:n})},"topic:add":async function(e,t){const{workspace:s,topics:r}=e,n=t;return s.index.topics[n.name]?y({code:"DUPLICATE_KEY",resource:"Topic",key:n.name}):(await r.add(n),f({index:{topics:{[n.name]:r.summarize(n)}}}))},"topic:update":async function(e,t){const{workspace:s,topics:r}=e,{name:n,...i}=t;if(!s.index.topics[n])return y({code:"NOT_FOUND",resource:"Topic",id:n});const o=await r.update(n,i);return o?f({index:{topics:{[n]:{metadata:{updated:o.updated}}}}}):y({code:"BACKEND_ERROR",reason:`Failed to update topic ${n} in store.`})},"topic:delete":async function(e,t){const{workspace:s,topics:r,roles:n,sessions:i}=e,{name:o,cascade:a}=t;if(!s.index.topics[o])return y({code:"NOT_FOUND",resource:"Topic",id:o});if(r.referencedBy(o,s.index)&&!a)return y({code:"INVALID_COMMAND",reason:`Topic '${o}' is referenced by other entities. Use 'cascade: true' to force deletion.`});if(a){for(const e in s.index.roles){const t=s.index.roles[e];if(t.topics?.includes(o)){const t=await n.get(e);t&&await n.update(e,{topics:t.topics.filter((e=>e!==o))})}}for(const e in s.index.sessions){const t=s.index.sessions[e];t.topics?.includes(o)&&await i.update(e,{topics:t.topics.filter((e=>e!==o))})}}return await r.delete(o)?f({index:{topics:{[o]:h}}}):y({code:"BACKEND_ERROR",reason:`Failed to delete topic ${o} from store.`})},"topic:merge":async function(e,t){const{workspace:s,topics:r,roles:n,sessions:i}=e,{source:o,target:a}=t;if(!s.index.topics[o]||!s.index.topics[a])return y({code:"NOT_FOUND",resource:"Topic",id:s.index.topics[o]?a:o});for(const e in s.index.roles){const t=s.index.roles[e];if(t.topics?.includes(o)){const t=await n.get(e);if(t){const s=t.topics.filter((e=>e!==o));s.includes(a)||s.push(a),await n.update(e,{topics:s})}}}for(const e in s.index.sessions){const t=s.index.sessions[e];if(t.topics?.includes(o)){const s=t.topics.filter((e=>e!==o));s.includes(a)||s.push(a),await i.update(e,{topics:s})}}return await r.delete(o),f({index:{topics:{[o]:h}}})},"session:create":async function(e,t){const{workspace:s,sessions:r}=e,n=t;return s.index.sessions[n.id]?y({code:"DUPLICATE_KEY",resource:"Session",key:n.id}):(await r.add(n),f({index:{sessions:{[n.id]:r.summarize(n)}}}))},"session:update":async function(e,t){const{workspace:s,sessions:r}=e,{sessionId:n,...i}=t;if(!s.index.sessions[n])return y({code:"NOT_FOUND",resource:"Session",id:n});const o=await r.update(n,i);return o?f({index:{sessions:{[n]:r.summarize(o)}}}):y({code:"BACKEND_ERROR",reason:`Failed to update session ${n} in store.`})},"session:fork":async function(e,t){const{workspace:s,sessions:r}=e,{sessionId:n,newSessionId:i,label:o}=t,a=s.index.sessions[n];if(!a)return y({code:"NOT_FOUND",resource:"Session",id:n});const c={...a,id:i,label:o||`Fork of ${a.label}`,role:t.role?t.role:a.role,topics:t.topics?t.topics:a.topics};return await r.add(c),f({index:{sessions:{[i]:r.summarize(c)}}})},"session:delete":async function(e,t){const{workspace:s,sessions:r}=e,{sessionId:n}=t;return s.index.sessions[n]?(await r.delete(n),f({index:{sessions:{[n]:h}}})):y({code:"NOT_FOUND",resource:"Session",id:n})},"session:role:switch":async function(e,t){const{workspace:s,sessions:r}=e,{sessionId:n,roleName:i}=t;return s.index.sessions[n]?(await r.update(n,{role:i}),f({index:{sessions:{[n]:{role:i}}}})):y({code:"NOT_FOUND",resource:"Session",id:n})},"session:topics:add":async function(e,t){const{workspace:s,sessions:r}=e,{sessionId:n,topics:i}=t,o=s.index.sessions[n];if(!o)return y({code:"NOT_FOUND",resource:"Session",id:n});const a=Array.from(new Set([...o.topics,...i]));return await r.update(n,{topics:a}),f({index:{sessions:{[n]:{topics:a}}}})},"session:preferences:override":async function(e,t){const{workspace:s,sessions:r}=e,{sessionId:n,preferences:i}=t;return s.index.sessions[n]?(await r.update(n,{preferences:i}),f({index:{sessions:{[n]:{preferences:i}}}})):y({code:"NOT_FOUND",resource:"Session",id:n})},"turn:add":async function(e,t){const{workspace:s,sessions:r,turns:n}=e,{sessionId:i,turn:o}=t;if(!s.index.sessions[i])return y({code:"NOT_FOUND",resource:"Session",id:i});await n.add(o);const a={id:o.id,version:o.version};return await r.update(i,{head:a}),f({index:{sessions:{[i]:{head:a}}}})},"turn:update":async function(e,t){const{workspace:s,sessions:r,turns:n}=e,{sessionId:i,turn:o}=t;if(!s.index.sessions[i])return y({code:"NOT_FOUND",resource:"Session",id:i});await n.update(o,o);const a={id:o.id,version:o.version};return await r.update(i,{head:a}),f({index:{sessions:{[i]:{head:a}}}})},"turn:edit":async function(e,t){const{workspace:s,sessions:r,turns:n}=e,{sessionId:i,turnId:o,newBlocks:a,newVersion:c,roleSnapshot:d}=t,u=s.index.sessions[i];if(!u)return y({code:"NOT_FOUND",resource:"Session",id:i});const l=u.head;let p={};if(l&&l.id===o){const e=await n.get({id:l.id,version:l.version,session:i});e&&(p={...e})}const h={...p,id:o,version:c,blocks:a,role:d??p.role,timestamp:(new Date).toISOString(),parent:p.parent,actor:p.actor||"assistant",session:i};if(await n.add(h),u.head?.id===o){const e={id:o,version:c};return await r.update(i,{head:e}),f({index:{sessions:{[i]:{head:e}}}})}return f({})},"turn:branch":async function(e,t){const{workspace:s,sessions:r,turns:n}=e,{sessionId:i,turn:o}=t;if(!s.index.sessions[i])return y({code:"NOT_FOUND",resource:"Session",id:i});await n.add(o);const a={id:o.id,version:o.version};return await r.update(i,{head:a}),f({index:{sessions:{[i]:{head:a}}}})},"turn:delete":async function(e,t){const{workspace:s,sessions:r,turns:n}=e,{sessionId:i,turnId:o,newHead:a}=t;return s.index.sessions[i]?(await n.delete({session:i,id:o,version:t.version}),a?(await r.update(i,{head:a}),f({index:{sessions:{[i]:{head:a}}}})):f({})):y({code:"NOT_FOUND",resource:"Session",id:i})},"blob:register":async function(e,t){const{blobs:s}=e,r=await s.register(t.data,t.mediaType,t.filename);if(!r.ok)return r;const n=await s.getRecord(r.value.sha256);return n?f({index:{blobs:{[n.sha256]:n}}}):y({code:"BACKEND_ERROR",reason:`Failed to retrieve registered blob record for ${r.value.sha256}`})},"blob:retain":async function(e,t){const{blobs:s}=e,r=await s.retain(t.sha256);if(!r.ok)return r;const n=await s.getRecord(t.sha256);return f({index:{blobs:{[t.sha256]:n}}})},"blob:release":async function(e,t){const{blobs:s}=e,r=await s.release(t.sha256);if(!r.ok)return r;const n=await s.getRecord(t.sha256);return f({index:{blobs:{[t.sha256]:n||h}}})},"blob:purge":async function(e,t){const{blobs:s}=e,r=await s.purge(t.sha256);return r.ok?f({index:{blobs:{[t.sha256]:h}}}):r},"blob:record_remote_id":async function(e,t){const{blobs:s}=e,{sha256:r,providerId:n,fileId:i,timestamp:o}=t,a=await s.recordRemoteId(r,n,i,o);if(!a.ok)return a;const c=await s.getRecord(r);return f({index:{blobs:{[r]:c}}})},"tool:call":async function(e,t){return f({})}},j=class{profiles;constructor(e=[]){this.profiles=new Map;for(const t of e)this.profiles.set(t.name,t)}get(e){return this.profiles.get(e)}list(e){const t=Array.from(this.profiles.values());return e?t.filter((t=>t.provider===e)):t}register(e){this.profiles.set(e.name,e)}},B=[{type:"text",emittable:!0,description:["## Block: `text`","Primary communication block. Use for all conversational responses, explanations, and prose.","A response may contain multiple `text` blocks interleaved with other block types."].join("\n"),rules:[],schema:{type:"object",properties:{type:{type:"string",enum:["text"]},text:{type:"string",description:"The raw markdown or plain text content of the response."}},required:["type","text"]}},{type:"summary",emittable:!0,description:["## Block: `summary`","Context compression block. Replaces older conversation history with a concise digest."].join("\n"),rules:["Only emit when explicitly instructed by the system to summarise.","Never emit more than one summary block per turn.","Preserve key decisions, outcomes, and unresolved questions.","Do not summarise the current turn — only prior history."],schema:{type:"object",properties:{type:{type:"string",enum:["summary"]},text:{type:"string",description:"A concise summary replacing older conversation context."}},required:["type","text"]}},{type:"thinking",emittable:!1,description:["## Block: `thinking`","Internal chain-of-thought produced by the model before its final response.","Injected by the workspace from provider reasoning tokens — never emit it yourself."].join("\n"),rules:[],schema:{type:"object",properties:{type:{type:"string",enum:["thinking"]},thinking:{type:"string",description:"The internal reasoning text produced before the final response."}},required:["type","thinking"]}},{type:"tool:use",emittable:!1,description:["## Block: `tool:use`","Captures a model request to execute a registered tool.","Constructed by the workspace from the provider native function-call response — never emit it yourself."].join("\n"),rules:[],schema:{type:"object",properties:{type:{type:"string",enum:["tool:use"]},name:{type:"string",description:"The exact registered name of the tool to execute."},input:{type:"object",description:"The parameter arguments for the tool execution.",additionalProperties:!0}},required:["type","name","input"]}},{type:"tool:result",emittable:!1,description:["## Block: `tool:result`","Contains the output of a tool execution, including any errors.","Injected by the workspace after a tool runs — never emit it yourself."].join("\n"),rules:[],schema:{type:"object",properties:{type:{type:"string",enum:["tool:result"]},useId:{type:"string",description:"The UUID of the ToolUseBlock that triggered this execution."},content:{oneOf:[{type:"string"},{type:"object",additionalProperties:!0}],description:"The serialized output of the tool, or a structured JSON response."},isError:{type:"boolean",description:"True if the tool execution resulted in an error."}},required:["type","useId","content"]}},{type:"image",emittable:!1,description:["## Block: `image`","An image asset attached to a turn, resolved from the workspace blob store.","Constructed by the workspace from user uploads — never emit it yourself."].join("\n"),rules:[],schema:{type:"object",properties:{type:{type:"string",enum:["image"]},altText:{type:"string",description:"Accessible description of the image content."}},required:["type"]}},{type:"document",emittable:!1,description:["## Block: `document`","A document asset (PDF, DOCX, etc.) attached to a turn, resolved from the workspace blob store.","Constructed by the workspace from user uploads — never emit it yourself."].join("\n"),rules:[],schema:{type:"object",properties:{type:{type:"string",enum:["document"]},title:{type:"string",description:"Human-readable title or filename of the document."}},required:["type"]}},{type:"role:transition",emittable:!1,description:["## Block: `role:transition`","Marks that the active session persona has switched from one role to another.","Emitted by the workspace when the active persona changes — never emit it yourself."].join("\n"),rules:[],schema:{type:"object",properties:{type:{type:"string",enum:["role:transition"]},previousRole:{type:"string",description:"The name of the role the session is leaving."},newRole:{type:"string",description:"The name of the role the session is adopting."}},required:["type","newRole"]}}];function A(e,t){let s=e.filter((e=>e.emittable));if(!t)return s;if(t.only&&t.only.length>0){const e=new Set(t.only);return s.filter((t=>e.has(t.type)))}if(t.exclude&&t.exclude.length>0){const e=new Set(t.exclude);return s.filter((t=>!e.has(t.type)))}return s}var C=class{store=new Map;constructor(){for(const e of B)this.store.set(e.type,e)}register(e){if(this.store.has(e.type))throw new Error(`[BlockRegistry] Block type "${e.type}" is already registered. Use update() to modify it.`);this.store.set(e.type,{...e,emittable:!0,rules:[]})}unregister(e){if(!this.store.has(e))throw new Error(`[BlockRegistry] Cannot unregister unknown block type "${e}".`);this.store.delete(e)}update(e,t){const s=this.store.get(e);s?this.store.set(e,{...s,...t,type:e}):this.store.set(e,{emittable:!0,rules:[],...t,type:e})}get(e){return this.store.get(e)}list(){return Array.from(this.store.values())}isType(e,t){return e.type===t}guard(e){return t=>t.type===e}schema(e){return{type:"object",description:"The model's structured response, containing an ordered sequence of content blocks.",properties:{blocks:{type:"array",description:"An ordered array of content blocks comprising the model's response.",items:{anyOf:A(Array.from(this.store.values()),e).map((e=>e.schema))}}},required:["blocks"]}}description(e){return["# BLOCK TYPES & USAGE RULES","","Your response MUST be a JSON object with a `blocks` array.","Each element of `blocks` must be one of the following types:","",A(Array.from(this.store.values()),e).map((e=>{const t=[e.description];return e.rules.length>0&&(t.push("**Rules:**"),t.push(...e.rules.map((e=>`- ${e}`)))),t.join("\n")})).join("\n\n"),"","## GLOBAL CONSTRAINTS","","- Output must be **valid JSON only** — no prose before or after the JSON object.","- Responses may contain multiple blocks. Blocks are rendered in order.","- **Do NOT generate IDs.** The workspace is solely responsible for block ID assignment.","- Do not infer or invent fields not defined in the block schemas above."].join("\n")}rules(e){const t=A(Array.from(this.store.values()),e);return Object.fromEntries(t.map((e=>[e.type,[...e.rules]])))}setRules(e,t){const s=this.store.get(e);if(!s)throw new Error(`[BlockRegistry] Cannot set rules on unknown block type "${e}".`);this.store.set(e,{...s,rules:t})}parse(e,s){const r=this.store.get(e.type);if(!r)return console.warn(`[BlockRegistry] parse() received unknown block type "${e.type}". Returning null.`),null;if(s&&r.mappings?.[s])return r.mappings[s].from(e);const{id:n,...i}=e;return{id:t.v7(),...i}}create(e,s){if(!this.store.has(e))throw new Error(`[BlockRegistry] Cannot create block of unknown type "${e}".`);return{...s,id:t.v7(),type:e}}clone(e,s){return{...structuredClone(e),...s,id:t.v7()}}},q=class{store=new Map;constructor(){this.registerDefaults()}registerDefaults(){this.register({kind:"text",target:"system",render:e=>({id:e.key,type:"text",text:e.content.value}),toString:e=>e.content.value,summarize:e=>({key:e.key,kind:"text",topics:e.topics,timestamp:e.timestamp,preview:e.content.value.slice(0,100)})}),this.register({kind:"json",target:"system",render:e=>({id:e.key,type:"text",text:JSON.stringify(e.content.value,null,2)}),toString:e=>JSON.stringify(e.content.value),summarize:e=>({key:e.key,kind:"json",topics:e.topics,timestamp:e.timestamp,preview:"JSON Data"})}),this.register({kind:"blob",target:"transcript",render:e=>{const{sha256:t,mediaType:s,sizeBytes:r,filename:n}=e.content,i={sha256:t,mediaType:s,sizeBytes:r,filename:n};return s.startsWith("image/")?{id:e.key,type:"image",ref:i}:{id:e.key,type:"document",ref:i,title:n}},toString:e=>e.content.filename||"unnamed blob",summarize:e=>({key:e.key,kind:"blob",topics:e.topics,timestamp:e.timestamp,mime:e.content.mediaType,size:e.content.sizeBytes,preview:e.content.filename})})}register(e){if(this.store.has(e.kind))throw new Error(`[ContextRegistry] Context kind "${e.kind}" is already registered.`);this.store.set(e.kind,e)}get(e){return this.store.get(e)}list(){return Array.from(this.store.values())}},U="__system__",$=class{constructor(e,s,r){this._actor=e,this._turn=r?JSON.parse(JSON.stringify(r)):{id:t.v7(),session:s,version:0,actor:this._actor,blocks:[],timestamp:(new Date).toISOString(),role:void 0}}_turn;addText(e){const s={id:t.v7(),type:"text",text:e};return this._turn.blocks.push(s),this}addImage(e,s){const r={id:t.v7(),type:"image",ref:e,altText:s};return this._turn.blocks.push(r),this}addDocument(e,s){const r={id:t.v7(),type:"document",ref:e,title:s};return this._turn.blocks.push(r),this}addToolUse(e,s){const r={id:t.v7(),type:"tool:use",name:e,input:s};return this._turn.blocks.push(r),this}addToolResult(e,s,r){const n={id:t.v7(),type:"tool:result",useId:e,content:s,isError:r};return this._turn.blocks.push(n),this}addSummary(e){const s={id:t.v7(),type:"summary",text:e};return this._turn.blocks.push(s),this}addRoleTransition(e,s){const r={id:t.v7(),type:"role:transition",previousRole:e,newRole:s};return this._turn.blocks.push(r),this}addThinking(e){const s={id:t.v7(),type:"thinking",thinking:e};return this._turn.blocks.push(s),this}addBlock(e){return this._turn.blocks.push(e),this}deleteBlock(e){return this._turn.blocks=this._turn.blocks.filter((t=>t.id!==e)),this}editTextBlock(e,t){const s=this._turn.blocks.findIndex((t=>t.id===e));if(-1===s)throw new Error(`Block with ID ${e} not found.`);const r=this._turn.blocks[s];if("text"!==r.type)throw new Error(`Block with ID ${e} is not a TextBlock.`);return this._turn.blocks[s]={...r,text:t},this}withId(e){return this._turn.id=e,this}withVersion(e){return this._turn.version=e,this}withTimestamp(e){return this._turn.timestamp=e,this}withParent(e){return this._turn.parent=e,this}withRoleSnapshot(e){return this._turn.role=e,this}build(){return JSON.parse(JSON.stringify(this._turn))}},M=class{constructor(e,t){this.turnStore=e,this.sessionStore=t}async loadAllTurns(e){return this.turnStore.listBySession(e)}async loadHead(e){const t=await this.sessionStore.get(e);return t?.head??null}},z=class e{constructor(e,t){this.nodes=e,this._head=t}static async build(t,s){const[r,n]=await Promise.all([s.loadAllTurns(t),s.loadHead(t)]),i=function(e,t){const s=function(e,t){if(!t)return new Set;const s=new Map;for(const t of e)s.set(`${t.id}:${t.version}`,t);const r=new Set;let n=t;for(;n;){const e=`${n.id}:${n.version}`;if(r.has(e))break;r.add(e);const t=s.get(e);if(!t)break;n=t.parent}return r}(e,t),r={},n={};for(const t of e){r[t.id]||(r[t.id]={id:t.id,versions:{},activeVersion:t.version,actor:t.actor,blocks:t.blocks,timestamp:t.timestamp,roleSnapshot:t.role,parent:t.parent,children:{}},n[t.id]=new Set);const e=r[t.id];e.versions[t.version]=t;const i=s.has(`${t.id}:${t.version}`),o=s.has(`${t.id}:${e.activeVersion}`);if(i&&(!o||t.version>=e.activeVersion)&&(e.activeVersion=t.version,e.blocks=t.blocks,e.timestamp=t.timestamp,e.roleSnapshot=t.role,e.parent=t.parent),t.parent){const e=`${t.parent.id}:${t.parent.version}`;if(n[t.parent.id]||(n[t.parent.id]=new Set),!n[t.parent.id].has(e+":"+t.id)){n[t.parent.id].add(e+":"+t.id),r[t.parent.id]||(r[t.parent.id]={id:t.parent.id,versions:{},activeVersion:t.parent.version,actor:"user",blocks:[],timestamp:"",roleSnapshot:void 0,children:{}});const s=r[t.parent.id];s.children[t.parent.version]||(s.children[t.parent.version]=[]),s.children[t.parent.version].push(t.id)}}}return r}(r,n);return new e(i,n)}head(){return this._head}chain(){if(!this._head)return[];const e=[];let t=this._head.id;for(;t;){const s=this.nodes[t];if(!s)break;e.push(s),t=s.parent?.id??null}return e.reverse()}getTurnSiblings(e){const t=this.nodes[e];if(!t)return[];if(!t.parent)return Object.values(this.nodes).filter((e=>!e.parent));const s=this.nodes[t.parent.id];if(!s)return[t];const r=s.children[t.parent.version];return r?r.map((e=>this.nodes[e])).filter((e=>!!e)):[t]}branchInfo(e){const t=this.nodes[e];if(!t)return{versions:[],currentIndex:-1,total:0,hasPrev:!1,hasNext:!1};const s=Object.keys(t.versions).map(Number).sort(((e,t)=>e-t)),r=s.indexOf(t.activeVersion);return{versions:s,currentIndex:r,total:s.length,hasPrev:r>0,hasNext:r<s.length-1}}graph(){return{...this.nodes}}};var F=class{constructor(e){this.manager=e}get workspace(){return this.manager.workspace()}roles(){return this.manager.ctx().roles.list()}role(e){return this.manager.ctx().roles.get(e)}async createRole(e,t,s,r,n=[]){if(this.workspace.index.roles[e])return y({code:"DUPLICATE_KEY",resource:"role",key:e});const i={name:e,label:t,description:r,persona:s,preferences:n,topics:[]};return this.manager.dispatch({type:"role:add",payload:i,timestamp:(new Date).toISOString()})}async updateRole(e,t){return this.workspace.index.roles[e]?this.manager.dispatch({type:"role:update",payload:{name:e,...t},timestamp:(new Date).toISOString()}):y({code:"NOT_FOUND",resource:"role",id:e})}async deleteRole(e){const t=this.workspace;if(!t.index.roles[e])return y({code:"NOT_FOUND",resource:"role",id:e});return Object.values(t.index.sessions).some((t=>t.role===e))?y({code:"INVALID_COMMAND",reason:`Cannot delete role "${e}" — it is still referenced by one or more sessions`}):this.manager.dispatch({type:"role:delete",payload:{name:e},timestamp:(new Date).toISOString()})}async addPreference(e,t){const s={id:crypto.randomUUID(),content:e,topics:t,timestamp:(new Date).toISOString()};return this.manager.dispatch({type:"preference:add",payload:s,timestamp:s.timestamp})}preferences(){return this.manager.ctx().preferences.list()}async addContext(e,t,s,r){const n={key:e,topics:s,content:t,timestamp:(new Date).toISOString(),metadata:r};return this.manager.dispatch({type:"context:add",payload:n,timestamp:n.timestamp})}context(){return this.manager.ctx().context.list()}async registerBlob(e,t,s){const r=await this.manager.dispatch({type:"blob:register",payload:{data:e,mediaType:t,filename:s},timestamp:(new Date).toISOString()});if(!r.ok)return y(r.error);const n=r.value,i=n?.index?.blobs;if(!i)return y({code:"BACKEND_ERROR",reason:"Blob registration succeeded but no blobs patch returned"});const o=Object.keys(i)[0];if(!o)return y({code:"BACKEND_ERROR",reason:"No SHA256 in patch"});const a=i[o];if(!a)return y({code:"BACKEND_ERROR",reason:"Blob record missing"});return f({sha256:o,ref:{sha256:o,mediaType:a.mediaType,sizeBytes:a.sizeBytes,filename:a.filename,previewUrl:a.previewUrl}})}},P=class e{constructor(e,t,s,r){this._id=e,this.manager=t,this.processor=s,this.turnRepository=r,this.workspace=new F(t),this.unsubscribe=t.subscribe("workspace:synced",(()=>this.sync()))}workspace;_role=void 0;_preferences=[];tree;unsubscribe;static async create(t,s,r){s.ctx().workspace;const n=new M(s.ctx().turns,s.ctx().sessions),i=new e(t,s,r,n);return await i.sync(),i}async sync(){await this._setRole(),await this._setPreference(),await this.refreshTurnTree()}close(){this.unsubscribe?.()}async _setRole(){const e=this.meta(),t=await this.manager.ctx().roles.get(e.role);t&&(this._role=t)}async _setPreference(){const e=this.meta();this._preferences=await this.manager.ctx().preferences.load(e.preferences)}id(){return this._id}ws(){return this.manager.workspace()}meta(){return this.ws().index.sessions[this._id]}label(){return this.meta()?.label}role(){return this._role}topics(){return this.meta()?.topics??[]}preferences(){return this._preferences}head(){return this.meta()?.head??null}turns(){return this.tree.chain()}async siblings(e){return this.tree.getTurnSiblings(e)}async branchInfo(e){return this.tree.branchInfo(e)}async getTurn(e){return this.tree.graph()[e]}async rename(e){return this.meta()?this.dispatch({type:"session:update",payload:{sessionId:this._id,label:e},timestamp:(new Date).toISOString()}):y({code:"NOT_FOUND",resource:"session",id:this._id})}async setTopics(e){return this.meta()?this.dispatch({type:"session:update",payload:{sessionId:this._id,topics:e},timestamp:(new Date).toISOString()}):y({code:"NOT_FOUND",resource:"session",id:this._id})}async addTopics(e){return this.meta()?this.dispatch({type:"session:topics:add",payload:{sessionId:this._id,topics:e},timestamp:(new Date).toISOString()}):y({code:"NOT_FOUND",resource:"session",id:this._id})}async setPreferences(e){if(!this.meta())return y({code:"NOT_FOUND",resource:"session",id:this._id});const t=await this.dispatch({type:"session:preferences:override",payload:{sessionId:this._id,preferences:e},timestamp:(new Date).toISOString()});return t.ok&&await this._setPreference(),t}async fork(e,t,s,r){return this.meta()?this.dispatch({type:"session:fork",payload:{sessionId:this._id,newSessionId:e,label:t,role:s,topics:r},timestamp:(new Date).toISOString()}):y({code:"NOT_FOUND",resource:"session",id:this._id})}async dispatch(e){return this.manager.dispatch(e)}async switchRole(e){const t=this.ws();if(!this.meta())return y({code:"NOT_FOUND",resource:"session",id:this._id});if(e!==U&&!t.index.roles[e])return y({code:"NOT_FOUND",resource:"role",id:e});const s=await this.dispatch({type:"session:update",payload:{sessionId:this._id,role:e},timestamp:(new Date).toISOString()});return s.ok&&await this._setRole(),s}async addTurn(e){if(!this.meta())return y({code:"NOT_FOUND",resource:"session",id:this._id});const t={...e,session:this._id,version:e.version??0,parent:!e.parent&&this.head()?this.head():void 0},s=await this.dispatch({type:"turn:add",payload:{sessionId:this._id,turn:t},timestamp:t.timestamp});return s.ok&&await this.refreshTurnTree(),s}async recordUserTurn(e){return this.meta()?this.addTurn(e):y({code:"NOT_FOUND",resource:"session",id:this._id})}async recordAssistantTurn(e,t){const s=this.ws();if(!s)return y({code:"NOT_FOUND",resource:"workspace",id:"current"});if(!s.index.sessions[this._id])return y({code:"NOT_FOUND",resource:"session",id:this._id});const r=this.processor.process(e,this._id);let n={};const i=[];for(const e of r){const t=await this.manager.dispatch(e);if(t.ok)n=w(n,t.value);else{if("PERMISSION_DENIED"!==t.error.code||e.synthetic)return t;{const t=this.describeCommand(e);i.push({cmd:e,description:t})}}}const o=await this.addTurn(e);if(!o.ok)return o;if(n=w(n,o.value),t&&i.length>0){const e=this.buildDenialTurn(i),t=await this.addTurn(e);t.ok&&(n=w(n,t.value))}return f(n)}buildDenialTurn(e){const t=new $("user",this._id);for(const s of e)t.addText(`[System] User denied: ${s.description}.`);return t.build()}describeCommand(e){return"tool:call"===e.type?`tool execution: ${e.payload.tool}`:`command: ${e.type}`}async editTurn(e,t,s){if(!this.meta())return y({code:"NOT_FOUND",resource:"session",id:this._id});const r=this.tree.graph()[e];if(!r)return y({code:"NOT_FOUND",resource:"turn",id:e});const n=r.versions[r.activeVersion],i=r.activeVersion+1,o=await this.dispatch({type:"turn:edit",payload:{sessionId:this._id,turnId:e,newBlocks:t,roleSnapshot:s??n.role,newVersion:i},timestamp:(new Date).toISOString()});return o.ok&&(await this.dispatch({type:"session:update",payload:{sessionId:this._id,head:{id:e,version:i}},timestamp:(new Date).toISOString()}),await this.refreshTurnTree()),o}async branch(e){if(!this.meta())return y({code:"NOT_FOUND",resource:"session",id:this._id});if(!e.parent)return y({code:"INVALID_COMMAND",reason:"branch requires turn.parent to be set"});const t=await this.dispatch({type:"turn:branch",payload:{sessionId:this._id,turn:{...e,session:this._id}},timestamp:e.timestamp});return t.ok&&await this.refreshTurnTree(),t}async deleteTurn(e,t,s){if(!this.meta())return y({code:"NOT_FOUND",resource:"session",id:this._id});const r=this.tree.graph();if(!r[e]?.versions[t])return y({code:"NOT_FOUND",resource:"turn version",id:`${e}:${t}`});const n=await this.dispatch({type:"turn:delete",payload:{sessionId:this._id,turnId:e,version:t,newHead:s},timestamp:(new Date).toISOString()});return n.ok&&await this.refreshTurnTree(),n}async switchVersionLeft(e){return this.switchVersion(e,-1)}async switchVersionRight(e){return this.switchVersion(e,1)}async switchVersion(e,t){if(!this.ws())return y({code:"NOT_FOUND",resource:"workspace",id:"current"});if(!this.meta())return y({code:"NOT_FOUND",resource:"session",id:this._id});const s=this.tree.graph()[e];if(!s)return y({code:"NOT_FOUND",resource:"turn",id:e});const r=Object.keys(s.versions).map(Number).sort(((e,t)=>e-t)),n=r.indexOf(s.activeVersion);if(-1===n)return y({code:"INVALID_COMMAND",reason:"Active version not found"});const i=n+t;if(i<0||i>=r.length)return y({code:"INVALID_COMMAND",reason:`No ${t<0?"previous":"next"} version available for turn ${e}`});const o=r[i],a=this.findSubtreeTip(this.tree.graph(),e,o),c=await this.dispatch({type:"session:update",payload:{sessionId:this._id,head:a},timestamp:(new Date).toISOString()});return c.ok&&await this.refreshTurnTree(),c}async snapshot(){const e=this,t=e.meta();if(!t)return;const s=e.ws(),r=e._role;if(!r)return;const n=await e.manager.ctx().context.getByTopics(s.index,t.topics),i=Array.from(new Set([...r.preferences,...t.preferences])),o=i.length>0?await e.manager.ctx().preferences.load(i):e._preferences,a=e.tree.chain().map((e=>e.versions[e.activeVersion])).filter((e=>!!e)),c=[...a].reverse().find((e=>"user"===e.actor));return{id:e._id,meta:t,role:r,preferences:o,context:n,model:t.metadata?.model,transcript:a,topics:t.topics,instructions:s.settings?.prompt,constraints:{role:r.constraints,session:t.constraints,turn:c?.constraints}}}async refreshTurnTree(){this.tree=await z.build(this._id,this.turnRepository)}findSubtreeTip(e,t,s){let r=t,n=s;for(;;){const t=e[r];if(!t)break;const s=t.children[n];if(!s||0===s.length)break;const i=s[0],o=e[i];if(!o)break;r=i,n=o.activeVersion}return{id:r,version:n}}},K=class{constructor(e,t){this.manager=e,this.processor=t}openOnce=new Map;async open(e){let t=this.openOnce.get(e);t||(t=new d,this.openOnce.set(e,t));const s=await t.do((async()=>{if(!this.manager.workspace().index.sessions[e])throw new Error(`Session ${e} not found in workspace index`);return P.create(e,this.manager,this.processor)}));if(s.error)throw s.error;return s.value}close(e){this.openOnce.delete(e)}async delete(e){const t=await this.manager.dispatch({type:"session:delete",payload:{sessionId:e},timestamp:(new Date).toISOString()});if(t.ok)return this.close(e),t.value=void 0,t;throw t.error}async create(e){const s=t.v7(),r=await this.manager.dispatch({type:"session:create",payload:{...e,id:s},timestamp:(new Date).toISOString()});if(r.ok)return this.open(s);throw r.error}list(){return Object.values(this.manager.workspace().index.sessions)}metadata(e){return this.manager.workspace().index.sessions[e]}},L=class{constructor(e,t,s){this.storage=e,this.cache=t,this.bus=s}async register(e,t,s){const r=await g(e),n=await this.getRecord(r);if(n){const e={...n,refCount:n.refCount+1,lastUsedAt:(new Date).toISOString()};return await this.storage.saveRecord(e),this.cache.set(r,e),f(this.reference(e))}const i={sha256:r,mediaType:t,sizeBytes:e.byteLength,filename:s,refCount:1,remoteIds:{},createdAt:(new Date).toISOString(),lastUsedAt:(new Date).toISOString()};return this.storage.registerBlob?await this.storage.registerBlob(i,e):(await this.storage.storeBytes(r,e),await this.storage.saveRecord(i)),this.cache.set(r,i),this.bus.emit({name:"blobs:changed",payload:{sha256:r,record:i}}),f(this.reference(i))}async retain(e){const t=await this.getRecord(e);if(!t)return y({code:"NOT_FOUND",resource:"blob",id:e});const s={...t,refCount:t.refCount+1,lastUsedAt:(new Date).toISOString()};return await this.storage.saveRecord(s),this.cache.set(e,s),f(void 0)}async release(e){const t=await this.getRecord(e);if(!t)return y({code:"NOT_FOUND",resource:"blob",id:e});const s=Math.max(0,t.refCount-1),r={...t,refCount:s,lastUsedAt:(new Date).toISOString()};return await this.storage.saveRecord(r),this.cache.set(e,r),f(void 0)}async purge(e){return await this.storage.deleteBytes(e),await this.storage.deleteRecord(e),this.cache.delete(e),this.bus.emit({name:"blobs:changed",payload:{sha256:e}}),f(void 0)}async recordRemoteId(e,t,s,r){const n=await this.getRecord(e);if(!n)return y({code:"NOT_FOUND",resource:"blob",id:e});const i={...n,remoteIds:{...n.remoteIds,[t]:{id:s,timestamp:r||(new Date).toISOString()}},lastUsedAt:(new Date).toISOString()};return await this.storage.saveRecord(i),this.cache.set(e,i),this.bus.emit({name:"blobs:changed",payload:{sha256:e,record:i}}),f(void 0)}async getRecord(e){const t=this.cache.get(e);if(t)return t;const s=await this.storage.loadRecord(e);return s&&this.cache.set(e,s),s}async getAllRecords(){const e=await this.storage.listRecords(),t={};for(const s of e)t[s.sha256]=s,this.cache.set(s.sha256,s);return t}reference(e){return{sha256:e.sha256,mediaType:e.mediaType,sizeBytes:e.sizeBytes,filename:e.filename}}async resolve(e,t){const s=await this.getRecord(e.sha256);if(!s)return f(null);if(t){const e=s.remoteIds[t];if(e)return f({kind:"remote",sha256:s.sha256,mediaType:s.mediaType,fileId:e.id,providerId:t,timestamp:e.timestamp});const r=await this.storage.loadBytes(s.sha256);return f(r?{kind:"inline",sha256:s.sha256,mediaType:s.mediaType,data:r}:null)}const r=await this.storage.loadBytes(s.sha256);return f(r?{kind:"inline",sha256:s.sha256,mediaType:s.mediaType,data:r}:null)}async resolveMany(e,t){const s=new Map;for(const r of e){const e=await this.resolve(r,t);if(!e.ok)return y(e.error);if(null===e.value)return y({code:"BLOB_ERROR",reason:`Unable to resolve blob ${r.sha256}${t?` with adapter ${t}`:""}`});s.set(r.sha256,e.value)}return f(s)}},V=class{constructor(e,t,s){this.collection=e,this.cache=t,this.registry=s}delegates=new Map;registerDelegate(e,t){this.delegates.set(e,t)}async get(e,t){const s=this.cache.get(e);if(s)return s;if(t){const s=this.delegates.get(t);if(s){const t=await s.get(e);return t&&this.cache.set(e,t),t}}const r=await this.collection.find({field:"key",operator:"eq",value:e});if(!r)return null;const n=r.state();return this.cache.set(e,n),n}async add(e){const t=this.delegates.get(e.content.kind);t?await t.add(e):await this.collection.create(e),this.cache.set(e.key,e)}async list(){const e=await this.collection.list({limit:1e3,type:"cursor",direction:"forward"}),t=((await e.next()).value||[]).map((e=>e.state()));for(const e of this.delegates.values()){const s=await e.list();t.push(...s)}return t}async update(e,t,s){if(s){const r=this.delegates.get(s);if(r){const s=await r.update(e,t);return s&&this.cache.set(e,s),s}}const r=await this.collection.find({field:"key",operator:"eq",value:e});if(!r)return null;await r.update(t);const n=r.state();return this.cache.set(e,n),n}async delete(e,t){if(t){const s=this.delegates.get(t);if(s){const t=await s.delete(e);return t&&this.cache.delete(e),t}}const s=await this.collection.find({field:"key",operator:"eq",value:e});if(!s)return!1;const r=await s.delete();return r&&this.cache.delete(e),r}async getByTopics(e,t){const s=new Map;for(const r of t){const t=e.topics[r];t&&t.contextKeys.forEach((t=>{const r=e.context[t],n=r?.kind||"unknown";s.has(n)||s.set(n,new Set),s.get(n).add(t)}))}if(0===s.size)return[];const r=[],n=[];for(const[e,t]of s.entries()){if(this.delegates.get(e))for(const s of t){const t=await this.get(s,e);t&&r.push(t)}else t.forEach((e=>n.push(e)))}if(n.length>0){const e=[];for(const t of n){const s=this.cache.get(t);s?r.push(s):e.push(t)}if(e.length>0){const t=await this.collection.filter({operator:"or",conditions:e.map((e=>({field:"key",operator:"eq",value:e})))});for(const e of t){const t=e.state();this.cache.set(t.key,t),r.push(t)}}}return r.sort(((e,t)=>new Date(t.timestamp).getTime()-new Date(e.timestamp).getTime()))}summarize(e){const t=this.registry?.get(e.content.kind);return t?t.summarize(e):{kind:e.content.kind,key:e.key,topics:e.topics,timestamp:e.timestamp,metadata:e.metadata}}},W=class{constructor(e,t){this.collection=e,this.cache=t}async get(e){const t=this.cache.get(e);if(t)return t;const s=await this.collection.find({field:"id",operator:"eq",value:e});if(!s)return null;const r=s.state();return this.cache.set(e,r),r}async add(e){await this.collection.create(e),this.cache.set(e.id,e)}async update(e,t){const s=await this.collection.find({field:"id",operator:"eq",value:e});if(!s)return null;await s.update(t);const r=s.state();return this.cache.set(e,r),r}async delete(e){const t=await this.collection.find({field:"id",operator:"eq",value:e});if(!t)return!1;const s=await t.delete();return s&&this.cache.delete(e),s}async load(e){if(0===e.length)return[];const t=[],s=[];for(const r of e){const e=this.cache.get(r);e?s.push(e):t.push(r)}if(t.length>0){const e=await this.collection.filter({operator:"or",conditions:t.map((e=>({field:"id",operator:"eq",value:e})))});for(const t of e){const e=t.state();this.cache.set(e.id,e),s.push(e)}}return s}async list(){const e=await this.collection.list({limit:1e3,type:"cursor",direction:"forward"});return((await e.next()).value||[]).map((e=>e.state()))}summarize(e){return{id:e.id,topics:e.topics,timestamp:e.timestamp,snippet:e.content.slice(0,100)}}},J=class{constructor(e,t){this.collection=e,this.cache=t}async get(e){const t=this.cache.get(e);if(t)return t;const s=await this.collection.find({field:"name",operator:"eq",value:e});if(!s)return null;const r=s.state();return this.cache.set(e,r),r}async add(e){await this.collection.create(e),this.cache.set(e.name,e)}async update(e,t){const s=await this.collection.find({field:"name",operator:"eq",value:e});if(!s)return null;await s.update(t);const r=s.state();return this.cache.set(e,r),r}async delete(e){const t=await this.collection.find({field:"name",operator:"eq",value:e});if(!t)return!1;const s=await t.delete();return s&&this.cache.delete(e),s}async list(){const e=await this.collection.list({limit:1e3,type:"cursor",direction:"forward"});return((await e.next()).value||[]).map((e=>e.state()))}summarize(e){return{name:e.name,label:e.label,description:e.description,preferences:e.preferences?.length??0,topics:e.topics??[],constraints:e.constraints}}},G=class{constructor(e,t){this.collection=e,this.cache=t}async get(e){const t=this.cache.get(e);if(t)return t;const s=await this.collection.find({field:"id",operator:"eq",value:e});if(!s)return null;const r=s.state();return this.cache.set(e,r),r}async add(e){await this.collection.create(e),this.cache.set(e.id,e)}async update(e,t){const s=await this.collection.find({field:"id",operator:"eq",value:e});if(!s)return null;await s.update(t);const r=s.state();return this.cache.set(e,r),r}async delete(e){const t=await this.collection.find({field:"id",operator:"eq",value:e});if(!t)return!1;const s=await t.delete();return s&&this.cache.delete(e),s}async list(){const e=await this.collection.list({limit:1e3,type:"cursor",direction:"forward"});return((await e.next()).value||[]).map((e=>e.state()))}summarize(e){return e}},Y=class{constructor(e,t){this.collection=e,this.cache=t}key({id:e,session:t,version:s}){return`${t}:${s}:${e}`}async find({id:e,session:t,version:s},r=!0){const n=this.key({id:e,session:t,version:s});this.cache.get(n)&&this.cache.get(n);const i=await this.collection.find({operator:"and",conditions:[{field:"id",operator:"eq",value:e},{field:"session",operator:"eq",value:t},{field:"version",operator:"eq",value:s}]});return i?(r&&this.cache.set(n,i),i):null}async get(e){return this.find(e)}async add(e){const t=await this.collection.create(e);this.cache.set(this.key(e),t)}async update(e,t){const s=await this.find(e);return s?(await s.update(t),s.state()):null}async listBySession(e){return(await this.collection.filter({field:"session",operator:"eq",value:e})).map((e=>e.state()))}async delete(e){const t=await this.find(e,!1);if(!t)return!1;const s=await t.delete();return s&&this.cache.delete(this.key(e)),s}},H=class{constructor(e,t){this.collection=e,this.cache=t}async get(e){const t=this.cache.get(e);if(t)return t;const s=await this.collection.find({field:"id",operator:"eq",value:e});if(!s)return null;const r=s.state();return this.cache.set(e,r),r}async add(e){await this.collection.create(e),this.cache.set(e.id,e)}async update(e,t){const s=await this.collection.find({field:"id",operator:"eq",value:e});if(!s)return null;await s.update(t);const r=s.state();return this.cache.set(e,r),r}async delete(e){const t=await this.collection.find({field:"id",operator:"eq",value:e});if(!t)return!1;const s=await t.delete();return s&&this.cache.delete(e),s}async list(){const e=await this.collection.list({limit:100,type:"cursor",direction:"forward"});return((await e.next()).value||[]).map((e=>e.state()))}summarize(e){return e}},X=class{cache;maxSize;constructor(e){this.cache=new Map,this.maxSize=e}get(e){const t=this.cache.get(e);return void 0!==t&&(this.cache.delete(e),this.cache.set(e,t)),t}set(e,t){if(this.cache.has(e))this.cache.delete(e);else if(this.cache.size>=this.maxSize){const e=this.cache.keys().next().value;void 0!==e&&this.cache.delete(e)}this.cache.set(e,t)}has(e){return this.cache.has(e)}delete(e){this.cache.delete(e)}clear(){this.cache.clear()}},Q="blob_bytes",Z="blob_records";function ee(e){return new Promise(((t,s)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>s(e.error)}))}function te(e){return new Promise(((t,s)=>{e.oncomplete=()=>t(),e.onerror=()=>s(e.error),e.onabort=()=>s(new Error("Transaction aborted"))}))}var se={};((e,t)=>{for(var r in t)s(e,r,{get:t[r],enumerable:!0})})(se,{GOOGLE_MODELS:()=>ne,GoogleGenAIAdapter:()=>ue,mapBlockToPart:()=>ae,mapTurnToContent:()=>oe,mappings:()=>re,parseModelResponse:()=>ie});var re={text:{to:e=>({text:e.text}),from:e=>({id:t.v4(),type:"text",text:e.text})},summary:{to:e=>({text:`[Summary]: ${e.text}`}),from:e=>({id:t.v4(),type:"summary",text:e.text})},thinking:{to:e=>({text:e.thinking}),from:e=>({id:t.v4(),type:"thinking",thinking:e.thinking})},"tool:use":{to:e=>({functionCall:{name:e.name,args:e.input}}),from:e=>({id:t.v4(),type:"tool:use",name:e.functionCall?.name??e.name,input:e.functionCall?.args??e.input??{}})},"tool:result":{to:e=>({functionResponse:{name:e.useId,response:{result:e.content}}}),from:e=>({id:t.v4(),type:"tool:result",useId:e.useId,content:e.content,isError:e.isError})},"role:transition":{to:e=>({text:`[Role transition: ${e.previousRole??"none"} → ${e.newRole}]`}),from:e=>({id:t.v4(),type:"role:transition",previousRole:e.previousRole,newRole:e.newRole})}},ne=[{provider:"google",name:"gemini-3.1-pro-preview",window:{size:1048576,out:65536},feature:{vision:!0,tools:!0,json:!0,cache:!0,streaming:!0,thinking:!0},pricing:[{unit:"token",scale:6,cost:{input:2,output:12,cache:{read:.2,write:4.5}}}],capacity:[{unit:"token",max:1e6,period:60}]},{provider:"google",name:"gemini-3-flash-preview",window:{size:1048576,out:65536},feature:{vision:!0,tools:!0,json:!0,cache:!0,streaming:!0,thinking:!0},pricing:[{unit:"token",scale:6,cost:{input:.5,output:3,cache:{read:.05,write:1}}}],capacity:[{unit:"token",max:1e6,period:60}]},{provider:"google",name:"gemini-3.1-flash-lite-preview",window:{size:1048576,out:65536},feature:{vision:!0,tools:!0,json:!0,cache:!0,streaming:!0,thinking:!0},pricing:[{unit:"token",scale:6,cost:{input:.25,output:1.5,cache:{read:.025,write:1}}}],capacity:[{unit:"token",max:4e6,period:60}]},{provider:"google",name:"gemini-2.5-pro",window:{size:1048576,out:65536},feature:{vision:!0,tools:!0,json:!0,cache:!0,streaming:!0,thinking:!0},pricing:[{unit:"token",scale:6,cost:{input:1.25,output:10,cache:{read:.125,write:4.5}}}],capacity:[{unit:"token",max:4e6,period:60}]},{provider:"google",name:"gemini-2.5-flash",window:{size:1048576,out:65536},feature:{vision:!0,tools:!0,json:!0,cache:!0,streaming:!0,thinking:!0},pricing:[{unit:"token",scale:6,cost:{input:.3,output:2.5,cache:{read:.03,write:1}}}],capacity:[{unit:"call",max:4e3,period:60},{unit:"token",max:4e6,period:60}]},{provider:"google",name:"gemini-2.5-flash-lite",window:{size:1048576,out:65536},feature:{vision:!0,tools:!0,json:!0,cache:!0,streaming:!0,thinking:!0},pricing:[{unit:"token",scale:6,cost:{input:.1,output:.4,cache:{read:.01,write:1}}}],capacity:[{unit:"call",max:4e3,period:60},{unit:"token",max:4e6,period:60}]},{provider:"google",name:"gemini-3-pro-preview",window:{size:1048576,out:65536},feature:{vision:!0,tools:!0,json:!0,cache:!0,streaming:!0,thinking:!0},pricing:[{unit:"token",scale:6,cost:{input:2,output:12,cache:{read:.2,write:4.5}}}],capacity:[{unit:"token",max:1e6,period:60}]},{provider:"google",name:"gemini-2.5-flash-image",window:{size:4096,out:0},feature:{vision:!1,tools:!1,json:!1,cache:!1,streaming:!1,thinking:!1},pricing:[{unit:"image",scale:0,cost:{input:.02,output:0}}],capacity:[{unit:"call",max:100,period:60}]},{provider:"google",name:"gemini-2.5-flash-live-preview",window:{size:1048576,out:65536},feature:{vision:!0,tools:!0,json:!0,cache:!1,streaming:!0,thinking:!0},pricing:[{unit:"token",scale:6,cost:{input:.5,output:3}}],capacity:[{unit:"concurrent",max:10,period:0}]},{provider:"google",name:"gemini-3.1-flash-live-preview",window:{size:1048576,out:65536},feature:{vision:!0,tools:!0,json:!0,cache:!1,streaming:!0,thinking:!0},pricing:[{unit:"token",scale:6,cost:{input:.5,output:3}}],capacity:[{unit:"concurrent",max:10,period:0}]},{provider:"google",name:"gemini-2.5-computer-use-preview",window:{size:1048576,out:65536},feature:{vision:!0,tools:!0,json:!0,cache:!1,streaming:!0,thinking:!0},pricing:[{unit:"token",scale:6,cost:{input:1.25,output:10}}],capacity:[{unit:"call",max:200,period:60},{unit:"token",max:1e6,period:60}]},{provider:"google",name:"gemini-embedding-001",window:{size:2048,out:0},feature:{vision:!1,tools:!1,json:!1,cache:!1,streaming:!1,thinking:!1},pricing:[{unit:"token",scale:6,cost:{input:.5,output:0}}],capacity:[{unit:"token",max:1e6,period:60}]},{provider:"google",name:"gemini-embedding-2",window:{size:8192,out:0},feature:{vision:!1,tools:!1,json:!1,cache:!1,streaming:!1,thinking:!1},pricing:[{unit:"token",scale:6,cost:{input:.3,output:0}}],capacity:[{unit:"token",max:1e6,period:60}]}];function ie(e,s){const r=e.candidates?.[0];if(!r?.content?.parts)return y({code:"BACKEND_ERROR",reason:"No valid content parts in response"});const n=[];let i;for(const e of r.content.parts)if(e.thought)n.push((o=e.text??"",{id:t.v7(),type:"thinking",thinking:o}));else if(e.text){i=e;break}var o;if(!i)return y({code:"BACKEND_ERROR",reason:"Response missing JSON part"});const a=function(e){try{const t=JSON.parse(e);return t.blocks&&Array.isArray(t.blocks)?f(t.blocks):y({code:"BACKEND_ERROR",reason:'Invalid response: missing or malformed "blocks" array'})}catch(e){return y({code:"BACKEND_ERROR",reason:`Failed to parse response JSON: ${e instanceof Error?e.message:String(e)}`})}}(i.text);if(!a.ok)return a;for(const e of a.value){const t=s.parse(e,ue.provider());t&&n.push(t)}return f(n)}async function oe(e,t,s){const r="assistant"===e.actor?"model":"user",n=[];for(const r of e.blocks){if("image"===r.type||"document"===r.type){const e=r.ref;if(!e)continue;const s=await ce(e,t);s&&n.push(s);continue}const e=ae(r,s);e&&n.push(e)}return{role:r,parts:n}}function ae(e,t){const s=t.get(e.type);if(!s)throw new Error(`[GoogleGenAIAdapter] mapBlockToPart: block type "${e.type}" is not registered. Register it via registry.register() before use.`);const r=s.mappings?.[ue.provider()];if(!r)throw new Error(`[GoogleGenAIAdapter] mapBlockToPart: no "${ue.provider()}" mapping for block type "${e.type}". Add a mapping via registry.update("${e.type}", { mappings: { ${ue.provider()}: { to, from } } }).`);return r.to(e)}async function ce(e,t){const s=await t(e,ue.provider());if(!s.ok||!s.value)return null;const{value:r}=s;return"remote"===r.kind?{fileData:{fileUri:r.fileId,mimeType:r.mediaType}}:{inlineData:{data:b(r.data),mimeType:r.mediaType}}}function de(e){return Math.ceil(e.length/4)}var ue=class e{constructor(e,t,s={model:"gemini-2.5-flash"}){this.client=e,this.services=t,this._models=t.models;const r=this._models.get(s.model);if(!r)throw new Error(`Could not get model: ${s.model} profile in registry.`);this.model=r,this.registerGeminiMappings()}model;_models;registerGeminiMappings(){const t=this.services.blockRegistry;for(const[s,r]of Object.entries(re))t.update(s,{mappings:{[e.provider()]:r}})}async status(t){return{provider:e.provider(),model:this.model.name,ready:!0,window:this.model.window,feature:{vision:!0,tools:!0,json:!0,cache:!1,streaming:!0,thinking:!0},pricing:[{unit:"token",scale:6,cost:{input:.1,output:.4}}],rate:{load:0,capacity:[{unit:"call",max:1e3,period:60},{unit:"token",max:4e6,period:60}]}}}async resolve(e){const{prompt:s}=e,{assembler:r,blockRegistry:n,blobResolver:i}=this.services,o=s.model&&this._models.get(s.model)||this.model,a=r.build(s,[{label:"block-architecture",content:n.description(),position:"after:instructions"}]),c=r.join(a),d={role:"system",parts:[{text:c}]},u=s.constraints[o.name]??{tokens:{}},l=await Promise.all(s.transcript.map((e=>oe(e,i,n)))),p=n.schema(),h={model:o.name,contents:l,config:{systemInstruction:d,thinkingConfig:{includeThoughts:!0},responseMimeType:"application/json",responseSchema:p,...void 0!==u.temperature&&{temperature:u.temperature},...void 0!==u.tokens.max&&{maxOutputTokens:u.tokens.max},...u.tokens.stops?.length&&{stopSequences:u.tokens.stops},...void 0!==u.tokens.thought&&{thinkingConfig:{includeThoughts:!0,thinkingBudget:u.tokens.thought}}}},m=l.flatMap((e=>e.parts??[])).map((e=>e.text??"")).join(""),w=de(c),g=de(m),b=w+g,k=this;return{model:o.name,instructions:a,transcript:s.transcript,context:s.system.context,preferences:s.system.preferences,constraints:u,tokens:{breakdown:{system:w,transcript:g},total:b,source:"estimated",output:u.tokens.max??o.window.out,remaining:o.window.size-b},async execute(){let e;try{e=await k.client.models.generateContent(h)}catch(e){return y({code:"BACKEND_ERROR",reason:e instanceof Error?e.message:String(e)})}const t=ie(e,k.services.blockRegistry);if(!t.ok)return t;const r=t.value,n=new $("assistant",s.session);for(const e of r)n.addBlock(e);return f({turn:n.build(),effects:[]})},async*executeStream(){let e;try{e=await k.client.models.generateContentStream(h)}catch(e){const r=e instanceof Error?e.message:String(e),n=new $("assistant",s.session);return n.addBlock({id:t.v7(),type:"text",text:`[Stream error: ${r}]`}),void(yield{turn:n.build(),effects:[]})}const r=[];for await(const s of e){const e=s.candidates?.[0];if(e?.content?.parts)for(const s of e.content.parts)s.thought||s.text&&(r.push(s.text),yield{blocks:[{id:t.v7(),type:"text",text:s.text}]})}const n=r.join(""),i=new $("assistant",s.session);i.addBlock({id:t.v7(),type:"text",text:n}),yield{turn:i.build(),effects:[]}}}}static provider(){return"google"}static models(){return ne}};exports.COLLECTIONS=p,exports.EMPTY_SYSTEM_ROLE=U,exports.GoogleAdapter=se,exports.IndexedDBBlobStorage=class{dbName;db=null;constructor(e={}){this.dbName=e.dbName??"aiworkspace-blobs"}async open(){this.db||(this.db=await new Promise(((e,t)=>{const s=indexedDB.open(this.dbName,1);s.onupgradeneeded=e=>{const t=e.target.result;this.createSchema(t)},s.onsuccess=()=>e(s.result),s.onerror=()=>t(s.error),s.onblocked=()=>t(new Error(`[IndexedDBBlobStorage] Database "${this.dbName}" blocked.`))})),this.db.onversionchange=()=>{this.db?.close(),this.db=null})}createSchema(e){e.objectStoreNames.contains(Q)||e.createObjectStore(Q,{keyPath:"sha256"}),e.objectStoreNames.contains(Z)||e.createObjectStore(Z,{keyPath:"sha256"})}close(){this.db?.close(),this.db=null}async deleteDatabase(){this.close(),await new Promise(((e,t)=>{const s=indexedDB.deleteDatabase(this.dbName);s.onsuccess=()=>e(),s.onerror=()=>t(s.error)}))}getDB(){if(!this.db)throw new Error("[IndexedDBBlobStorage] Database not open. Call open() first.");return this.db}readTx(...e){return this.getDB().transaction(e,"readonly")}writeTx(...e){return this.getDB().transaction(e,"readwrite")}async storeBytes(e,t){const s=this.readTx(Q);if(await ee(s.objectStore(Q).get(e)))return;const r=this.writeTx(Q);r.objectStore(Q).put({sha256:e,data:t}),await te(r)}async loadBytes(e){const t=this.readTx(Q),s=await ee(t.objectStore(Q).get(e));return s?.data??null}async hasBytes(e){const t=this.readTx(Q);return await ee(t.objectStore(Q).count(e))>0}async deleteBytes(e){const t=this.writeTx(Q);t.objectStore(Q).delete(e),await te(t)}async saveRecord(e){const t=this.writeTx(Z);t.objectStore(Z).put(e),await te(t)}async loadRecord(e){const t=this.readTx(Z);return await ee(t.objectStore(Z).get(e))??null}async deleteRecord(e){const t=this.writeTx(Z);t.objectStore(Z).delete(e),await te(t)}async listRecords(){return ee(this.readTx(Z).objectStore(Z).getAll())}async exportAllBytes(){const e=this.readTx(Q);return(await ee(e.objectStore(Q).getAll())).map((({sha256:e,data:t})=>[e,t]))}async registerBlob(e,t){await new Promise(((s,r)=>{const n=this.getDB().transaction([Q,Z],"readwrite"),i=n.objectStore(Q),o=n.objectStore(Z),a=i.count(e.sha256);a.onsuccess=()=>{0===a.result&&i.put({sha256:e.sha256,data:t}),o.put(e)},a.onerror=()=>r(a.error),n.oncomplete=()=>s(),n.onerror=()=>r(n.error),n.onabort=()=>r(new Error("registerBlob transaction aborted"))}))}},exports.LRUCache=X,exports.MemoryBlobStorage=class{bytes=new Map;records=new Map;async storeBytes(e,t){this.bytes.has(e)||this.bytes.set(e,t)}async loadBytes(e){return this.bytes.get(e)??null}async hasBytes(e){return this.bytes.has(e)}async deleteBytes(e){this.bytes.delete(e)}async saveRecord(e){this.records.set(e.sha256,{...e})}async loadRecord(e){return this.records.get(e)??null}async deleteRecord(e){this.records.delete(e)}async listRecords(){return Array.from(this.records.values()).map((e=>({...e})))}async exportAllBytes(){return Array.from(this.bytes.entries()).map((([e,t])=>[e,new Uint8Array(t)]))}async registerBlob(e,t){this.bytes.has(e.sha256)||this.bytes.set(e.sha256,t),this.records.set(e.sha256,{...e})}},exports.Session=P,exports.SessionManager=K,exports.TurnBuilder=$,exports.TurnTree=z,exports.WorkspaceManager=k,exports.bufferToBase64=b,exports.computeSHA256=g,exports.createEmptySession=(e={})=>({id:t.v7(),label:"New Conversation",role:"assistant-default",topics:[],preferences:[],metadata:{created:(new Date).toString(),updated:(new Date).toString()},...e,head:e.head?e.head:void 0}),exports.createEmptyTurn=(e={},s)=>({id:e.id??t.v7(),version:e.version??0,session:e.session??s?.id??t.v7(),actor:"user",blocks:[{id:t.v7(),type:"text",content:"Hello, world!"}],timestamp:(new Date).toString(),role:s?.role??"default",...e,parent:e.parent?e.parent:void 0}),exports.createEmptyWorkspace=(e={})=>({id:e.id??t.v7(),settings:w({language:"en-US",defaultRole:void 0,prompt:void 0},e.settings),project:w({id:t.v7(),name:"Unnamed Project"},e.project),index:w({roles:{},preferences:{},context:{},sessions:{},topics:{},blobs:{},tools:{},extensions:{}},e.index)}),exports.createWorkspace=async function(t){const{blobStorage:s,eventBus:n=e.createEventBus(),getWorkspace:i,setWorkspace:o,processor:a,guard:c,toolRegistry:d,models:u=[],extensions:h=[],extensionReducers:m={},extensionMiddleware:f=[],extensionIndexers:y=[],extensionStores:w,extensionSchemas:g=[]}=t,b=l(t.db),v=[...g,...h.flatMap((e=>e.schemas??[]))],_={...m,...h.reduce(((e,t)=>({...e,...t.reducers})),{})},O=[...f,...h.flatMap((e=>e.middleware??[]))],S=[...y,...h.flatMap((e=>e.indexers??[]))],T=h.flatMap((e=>e.blocks??[]));await b.open(v);const R={workspace:await b.collection(p.WORKSPACE),role:await b.collection(p.ROLE),preference:await b.collection(p.PREFERENCE),context:await b.collection(p.CONTEXT),session:await b.collection(p.SESSION),topic:await b.collection(p.TOPIC),turn:await b.collection(p.TURN)},D=new L(s,new X(200),n),B=new q,A={workspaceStore:new H(R.workspace,new X(1)),roles:new J(R.role,new X(100)),preferences:new W(R.preference,new X(500)),context:new V(R.context,new X(500),B),topics:new x(R.topic,new X(100)),sessions:new G(R.session,new X(50)),turns:new Y(R.turn,new X(50)),blobs:D,tools:d,db:b,indexers:[...r,...S]};if(w){const e=w(A);Object.assign(A,e)}await Promise.all(h.map((async e=>{if(e.stores){const t=await e.stores(A);Object.assign(A,t)}})));const U=new k({ctx:A,getWorkspace:i,updateWorkspace:async e=>{if(await o(e),e?.id||e?.settings||e?.project){const e=i();await A.workspaceStore.update(e.id,{id:e.id,settings:e.settings,project:e.project})}},guard:c,bus:n});Object.entries(E).forEach((([e,t])=>{U.register(e,t)})),Object.entries(_).forEach((([e,t])=>{U.register(e,t)})),U.use(N),O.forEach((e=>{U.use(e)}));const $=new K(U,a),M=new C;T.forEach((e=>M.register(e))),h.forEach((e=>{e.contexts&&e.contexts.forEach((e=>{if(B.register(e),e.store){const t=e.store(A);A.context.registerDelegate(e.kind,t)}}))}));const z=new j(u),F={assembler:new I,processor:a,blobResolver:A.blobs.resolve.bind(A.blobs),blockRegistry:M,contextRegistry:B,models:z};return{manager:U,sessions:$,ctx:A,services:F}},exports.createWorkspaceDatabase=l,exports.del=function(){return h},exports.error=y,exports.getExtension=function(e,t){return e.extensions[t]},exports.merge=w,exports.omitNullUndefined=function(e){return Object.fromEntries(Object.entries(e).filter((([e,t])=>null!=t)))},exports.shortHash=function(e,t=4){let s=0;for(let t=0;t<e.length;t++)s=(s<<5)-s+e.charCodeAt(t),s|=0;return Math.abs(s).toString(36).padEnd(t,"0").slice(0,t)},exports.success=f;
|