@n24q02m/workspace 0.9.0-beta.1 → 0.9.1-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/NOTICE +11 -5
  2. package/bin/cli.mjs +52 -52
  3. package/build/src/cli/tools.integration.test.js +26 -5
  4. package/build/src/cli/tools.integration.test.js.map +1 -1
  5. package/build/src/docs/docs.md +5 -1
  6. package/build/src/docs/overview.md +14 -0
  7. package/build/src/services/FormsService.d.ts +4 -4
  8. package/build/src/services/FormsService.js +4 -4
  9. package/build/src/services/FormsService.test.js +3 -3
  10. package/build/src/services/FormsService.test.js.map +1 -1
  11. package/build/src/tools/domains/error-payload.test.d.ts +2 -0
  12. package/build/src/tools/domains/error-payload.test.d.ts.map +1 -0
  13. package/build/src/tools/domains/error-payload.test.js +94 -0
  14. package/build/src/tools/domains/error-payload.test.js.map +1 -0
  15. package/build/src/tools/domains/factory.d.ts.map +1 -1
  16. package/build/src/tools/domains/factory.js +27 -1
  17. package/build/src/tools/domains/factory.js.map +1 -1
  18. package/build/src/tools/domains/factory.test.js +41 -0
  19. package/build/src/tools/domains/factory.test.js.map +1 -1
  20. package/build/src/vendored/services/CalendarService.d.ts.map +1 -1
  21. package/build/src/vendored/services/CalendarService.js +19 -15
  22. package/build/src/vendored/services/CalendarService.js.map +1 -1
  23. package/build/src/vendored/services/CalendarService.test.d.ts +2 -0
  24. package/build/src/vendored/services/CalendarService.test.d.ts.map +1 -0
  25. package/build/src/vendored/services/CalendarService.test.js +1227 -0
  26. package/build/src/vendored/services/CalendarService.test.js.map +1 -0
  27. package/build/src/vendored/services/CalendarValidation.test.d.ts +2 -0
  28. package/build/src/vendored/services/CalendarValidation.test.d.ts.map +1 -0
  29. package/build/src/vendored/services/CalendarValidation.test.js +312 -0
  30. package/build/src/vendored/services/CalendarValidation.test.js.map +1 -0
  31. package/build/src/vendored/services/ChatService.test.d.ts +2 -0
  32. package/build/src/vendored/services/ChatService.test.d.ts.map +1 -0
  33. package/build/src/vendored/services/ChatService.test.js +505 -0
  34. package/build/src/vendored/services/ChatService.test.js.map +1 -0
  35. package/build/src/vendored/services/DocsService.d.ts.map +1 -1
  36. package/build/src/vendored/services/DocsService.js +6 -1
  37. package/build/src/vendored/services/DocsService.js.map +1 -1
  38. package/build/src/vendored/services/DocsService.test.js +943 -5
  39. package/build/src/vendored/services/DocsService.test.js.map +1 -1
  40. package/build/src/vendored/services/DriveService.test.js +797 -9
  41. package/build/src/vendored/services/DriveService.test.js.map +1 -1
  42. package/build/src/vendored/services/SheetsService.test.js +328 -0
  43. package/build/src/vendored/services/SheetsService.test.js.map +1 -1
  44. package/build/src/vendored/utils/MimeHelper.test.js +329 -0
  45. package/build/src/vendored/utils/MimeHelper.test.js.map +1 -1
  46. package/build/src/vendored/utils/validation.d.ts.map +1 -1
  47. package/build/src/vendored/utils/validation.js +10 -1
  48. package/build/src/vendored/utils/validation.js.map +1 -1
  49. package/build/src/vendored/utils/validation.test.d.ts +2 -0
  50. package/build/src/vendored/utils/validation.test.d.ts.map +1 -0
  51. package/build/src/vendored/utils/validation.test.js +260 -0
  52. package/build/src/vendored/utils/validation.test.js.map +1 -0
  53. package/build/tsconfig.tsbuildinfo +1 -1
  54. package/npm-shrinkwrap.json +2 -2
  55. package/package.json +1 -1
package/bin/cli.mjs CHANGED
@@ -1,54 +1,54 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire } from 'module';const require = createRequire(import.meta.url);
3
- var Pf=Object.create;var ao=Object.defineProperty;var If=Object.getOwnPropertyDescriptor;var Of=Object.getOwnPropertyNames;var kf=Object.getPrototypeOf,$f=Object.prototype.hasOwnProperty;var Z=(n=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(n,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):n)(function(n){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+n+'" is not supported')});var G=(n,e,t)=>()=>{if(t)throw t[0];try{return n&&(e=n(n=0)),e}catch(s){throw t=[s],s}};var X=(n,e)=>()=>{try{return e||n((e={exports:{}}).exports,e),e.exports}catch(t){throw e=0,t}},Ea=(n,e)=>{for(var t in e)ao(n,t,{get:e[t],enumerable:!0})},Df=(n,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Of(e))!$f.call(n,o)&&o!==t&&ao(n,o,{get:()=>e[o],enumerable:!(s=If(e,o))||s.enumerable});return n};var Ht=(n,e,t)=>(t=n!=null?Pf(kf(n)):{},Df(e||!n||!n.__esModule?ao(t,"default",{value:n,enumerable:!0}):t,n));var Eo=X((XS,Fc)=>{"use strict";var Wn=Object.prototype.hasOwnProperty,Mc=Object.prototype.toString,Oc=Object.defineProperty,kc=Object.getOwnPropertyDescriptor,$c=function(e){return typeof Array.isArray=="function"?Array.isArray(e):Mc.call(e)==="[object Array]"},Dc=function(e){if(!e||Mc.call(e)!=="[object Object]")return!1;var t=Wn.call(e,"constructor"),s=e.constructor&&e.constructor.prototype&&Wn.call(e.constructor.prototype,"isPrototypeOf");if(e.constructor&&!t&&!s)return!1;var o;for(o in e);return typeof o>"u"||Wn.call(e,o)},Lc=function(e,t){Oc&&t.name==="__proto__"?Oc(e,t.name,{enumerable:!0,configurable:!0,value:t.newValue,writable:!0}):e[t.name]=t.newValue},Nc=function(e,t){if(t==="__proto__")if(Wn.call(e,t)){if(kc)return kc(e,t).value}else return;return e[t]};Fc.exports=function n(){var e,t,s,o,a,l,d=arguments[0],p=1,u=arguments.length,f=!1;for(typeof d=="boolean"&&(f=d,d=arguments[1]||{},p=2),(d==null||typeof d!="object"&&typeof d!="function")&&(d={});p<u;++p)if(e=arguments[p],e!=null)for(t in e)s=Nc(d,t),o=Nc(e,t),d!==o&&(f&&o&&(Dc(o)||(a=$c(o)))?(a?(a=!1,l=s&&$c(s)?s:[]):l=s&&Dc(s)?s:{},Lc(d,{name:t,newValue:n(f,l,o)})):typeof o<"u"&&Lc(d,{name:t,newValue:o}));return d}});var Bc=X((QS,Jp)=>{Jp.exports={name:"gaxios",version:"8.0.0",description:"A simple common HTTP client specifically for Google APIs and services.",main:"build/cjs/src/index.js",types:"build/cjs/src/index.d.ts",files:["build/"],exports:{".":{import:{types:"./build/esm/src/index.d.ts",default:"./build/esm/src/index.js"},require:{types:"./build/cjs/src/index.d.ts",default:"./build/cjs/src/index.js"}}},scripts:{lint:"gts check --no-inline-config",test:"c8 mocha build/esm/test","presystem-test":"npm run compile","system-test":"mocha build/esm/system-test --timeout 80000",compile:"tsc -b ./tsconfig.json ./tsconfig.cjs.json && node utils/enable-esm.mjs",fix:"gts fix",prepare:"npm run compile",pretest:"npm run compile",webpack:"webpack","prebrowser-test":"npm run compile","browser-test":"node build/browser-test/browser-test-runner.js",docs:"jsdoc -c .jsdoc.js","samples-test":"cd samples/ && npm link ../ && npm test && cd ../",prelint:"cd samples; npm link ../; npm install",clean:"gts clean"},repository:{type:"git",directory:"core/packages/gaxios",url:"https://github.com/googleapis/google-cloud-node.git"},keywords:["google"],engines:{node:">=22"},author:"Google, LLC",license:"Apache-2.0",devDependencies:{"@babel/plugin-proposal-private-methods":"^7.18.6","@types/cors":"^2.8.6","@types/express":"^5.0.0","@types/extend":"^3.0.1","@types/mocha":"^10.0.10","@types/multiparty":"4.2.1","@types/mv":"^2.1.0","@types/ncp":"^2.0.8","@types/node":"^24.0.0","@types/sinon":"^21.0.0","@types/tmp":"^0.2.6",assert:"^2.0.0",browserify:"^17.0.0",c8:"^10.1.3",cors:"^2.8.5",express:"^5.0.0",gts:"^6.0.2","is-docker":"^3.0.0",jsdoc:"^4.0.4","jsdoc-fresh":"^6.0.0","jsdoc-region-tag":"^5.0.0",karma:"^6.0.0","karma-chrome-launcher":"^3.0.0","karma-coverage":"^2.0.0","karma-firefox-launcher":"^2.0.0","karma-mocha":"^2.0.0","karma-remap-coverage":"^0.1.5","karma-sourcemap-loader":"^0.4.0","karma-webpack":"^5.0.0",mocha:"^11.1.0",multiparty:"^4.2.1",mv:"^2.1.1",ncp:"^2.0.0",nock:"14.0.5","null-loader":"^4.0.1","pack-n-play":"^4.0.0",puppeteer:"^24.0.0",sinon:"21.0.3","stream-browserify":"^3.0.0",tmp:"0.2.7","ts-loader":"^9.5.2",typescript:"5.8.3","undici-types":"^7.24.1",webpack:"^5.97.1","webpack-cli":"^6.0.1"},dependencies:{extend:"^3.0.2","https-proxy-agent":"^7.0.1","node-fetch":"^3.3.2"},homepage:"https://github.com/googleapis/google-cloud-node/tree/main/core/packages/gaxios"}});var qc=X((KS,Uc)=>{var Vp=Bc();Uc.exports={pkg:Vp}});var Gc=X((nw,Hc)=>{var Xt=1e3,Qt=Xt*60,Kt=Qt*60,At=Kt*24,Qp=At*7,Kp=At*365.25;Hc.exports=function(n,e){e=e||{};var t=typeof n;if(t==="string"&&n.length>0)return em(n);if(t==="number"&&isFinite(n))return e.long?rm(n):tm(n);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(n))};function em(n){if(n=String(n),!(n.length>100)){var e=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(n);if(e){var t=parseFloat(e[1]),s=(e[2]||"ms").toLowerCase();switch(s){case"years":case"year":case"yrs":case"yr":case"y":return t*Kp;case"weeks":case"week":case"w":return t*Qp;case"days":case"day":case"d":return t*At;case"hours":case"hour":case"hrs":case"hr":case"h":return t*Kt;case"minutes":case"minute":case"mins":case"min":case"m":return t*Qt;case"seconds":case"second":case"secs":case"sec":case"s":return t*Xt;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:return}}}}function tm(n){var e=Math.abs(n);return e>=At?Math.round(n/At)+"d":e>=Kt?Math.round(n/Kt)+"h":e>=Qt?Math.round(n/Qt)+"m":e>=Xt?Math.round(n/Xt)+"s":n+"ms"}function rm(n){var e=Math.abs(n);return e>=At?zn(n,e,At,"day"):e>=Kt?zn(n,e,Kt,"hour"):e>=Qt?zn(n,e,Qt,"minute"):e>=Xt?zn(n,e,Xt,"second"):n+" ms"}function zn(n,e,t,s){var o=e>=t*1.5;return Math.round(n/t)+" "+s+(o?"s":"")}});var Po=X((sw,Jc)=>{function nm(n){t.debug=t,t.default=t,t.coerce=p,t.disable=l,t.enable=o,t.enabled=d,t.humanize=Gc(),t.destroy=u,Object.keys(n).forEach(f=>{t[f]=n[f]}),t.names=[],t.skips=[],t.formatters={};function e(f){let y=0;for(let g=0;g<f.length;g++)y=(y<<5)-y+f.charCodeAt(g),y|=0;return t.colors[Math.abs(y)%t.colors.length]}t.selectColor=e;function t(f){let y,g=null,_,S;function E(...R){if(!E.enabled)return;let x=E,A=Number(new Date),C=A-(y||A);x.diff=C,x.prev=y,x.curr=A,y=A,R[0]=t.coerce(R[0]),typeof R[0]!="string"&&R.unshift("%O");let v=0;R[0]=R[0].replace(/%([a-zA-Z%])/g,($,H)=>{if($==="%%")return"%";v++;let Ve=t.formatters[H];if(typeof Ve=="function"){let cr=R[v];$=Ve.call(x,cr),R.splice(v,1),v--}return $}),t.formatArgs.call(x,R),(x.log||t.log).apply(x,R)}return E.namespace=f,E.useColors=t.useColors(),E.color=t.selectColor(f),E.extend=s,E.destroy=t.destroy,Object.defineProperty(E,"enabled",{enumerable:!0,configurable:!1,get:()=>g!==null?g:(_!==t.namespaces&&(_=t.namespaces,S=t.enabled(f)),S),set:R=>{g=R}}),typeof t.init=="function"&&t.init(E),E}function s(f,y){let g=t(this.namespace+(typeof y>"u"?":":y)+f);return g.log=this.log,g}function o(f){t.save(f),t.namespaces=f,t.names=[],t.skips=[];let y=(typeof f=="string"?f:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(let g of y)g[0]==="-"?t.skips.push(g.slice(1)):t.names.push(g)}function a(f,y){let g=0,_=0,S=-1,E=0;for(;g<f.length;)if(_<y.length&&(y[_]===f[g]||y[_]==="*"))y[_]==="*"?(S=_,E=g,_++):(g++,_++);else if(S!==-1)_=S+1,E++,g=E;else return!1;for(;_<y.length&&y[_]==="*";)_++;return _===y.length}function l(){let f=[...t.names,...t.skips.map(y=>"-"+y)].join(",");return t.enable(""),f}function d(f){for(let y of t.skips)if(a(f,y))return!1;for(let y of t.names)if(a(f,y))return!0;return!1}function p(f){return f instanceof Error?f.stack||f.message:f}function u(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return t.enable(t.load()),t}Jc.exports=nm});var Vc=X((ne,Hn)=>{ne.formatArgs=om;ne.save=im;ne.load=am;ne.useColors=sm;ne.storage=cm();ne.destroy=(()=>{let n=!1;return()=>{n||(n=!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`."))}})();ne.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"];function sm(){if(typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let n;return typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&(n=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(n[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function om(n){if(n[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+n[0]+(this.useColors?"%c ":" ")+"+"+Hn.exports.humanize(this.diff),!this.useColors)return;let e="color: "+this.color;n.splice(1,0,e,"color: inherit");let t=0,s=0;n[0].replace(/%[a-zA-Z%]/g,o=>{o!=="%%"&&(t++,o==="%c"&&(s=t))}),n.splice(s,0,e)}ne.log=console.debug||console.log||(()=>{});function im(n){try{n?ne.storage.setItem("debug",n):ne.storage.removeItem("debug")}catch{}}function am(){let n;try{n=ne.storage.getItem("debug")||ne.storage.getItem("DEBUG")}catch{}return!n&&typeof process<"u"&&"env"in process&&(n=process.env.DEBUG),n}function cm(){try{return localStorage}catch{}}Hn.exports=Po()(ne);var{formatters:lm}=Hn.exports;lm.j=function(n){try{return JSON.stringify(n)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var Zc=X((ow,Yc)=>{"use strict";Yc.exports=(n,e=process.argv)=>{let t=n.startsWith("-")?"":n.length===1?"-":"--",s=e.indexOf(t+n),o=e.indexOf("--");return s!==-1&&(o===-1||s<o)}});var Kc=X((iw,Qc)=>{"use strict";var um=Z("os"),Xc=Z("tty"),ge=Zc(),{env:J}=process,dt;ge("no-color")||ge("no-colors")||ge("color=false")||ge("color=never")?dt=0:(ge("color")||ge("colors")||ge("color=true")||ge("color=always"))&&(dt=1);"FORCE_COLOR"in J&&(J.FORCE_COLOR==="true"?dt=1:J.FORCE_COLOR==="false"?dt=0:dt=J.FORCE_COLOR.length===0?1:Math.min(parseInt(J.FORCE_COLOR,10),3));function Io(n){return n===0?!1:{level:n,hasBasic:!0,has256:n>=2,has16m:n>=3}}function Oo(n,e){if(dt===0)return 0;if(ge("color=16m")||ge("color=full")||ge("color=truecolor"))return 3;if(ge("color=256"))return 2;if(n&&!e&&dt===void 0)return 0;let t=dt||0;if(J.TERM==="dumb")return t;if(process.platform==="win32"){let s=um.release().split(".");return Number(s[0])>=10&&Number(s[2])>=10586?Number(s[2])>=14931?3:2:1}if("CI"in J)return["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE"].some(s=>s in J)||J.CI_NAME==="codeship"?1:t;if("TEAMCITY_VERSION"in J)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(J.TEAMCITY_VERSION)?1:0;if(J.COLORTERM==="truecolor")return 3;if("TERM_PROGRAM"in J){let s=parseInt((J.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(J.TERM_PROGRAM){case"iTerm.app":return s>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(J.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(J.TERM)||"COLORTERM"in J?1:t}function dm(n){let e=Oo(n,n&&n.isTTY);return Io(e)}Qc.exports={supportsColor:dm,stdout:Io(Oo(!0,Xc.isatty(1))),stderr:Io(Oo(!0,Xc.isatty(2)))}});var tl=X((V,Jn)=>{var fm=Z("tty"),Gn=Z("util");V.init=Sm;V.log=gm;V.formatArgs=mm;V.save=ym;V.load=bm;V.useColors=pm;V.destroy=Gn.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");V.colors=[6,2,3,4,5,1];try{let n=Kc();n&&(n.stderr||n).level>=2&&(V.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{}V.inspectOpts=Object.keys(process.env).filter(n=>/^debug_/i.test(n)).reduce((n,e)=>{let t=e.substring(6).toLowerCase().replace(/_([a-z])/g,(o,a)=>a.toUpperCase()),s=process.env[e];return/^(yes|on|true|enabled)$/i.test(s)?s=!0:/^(no|off|false|disabled)$/i.test(s)?s=!1:s==="null"?s=null:s=Number(s),n[t]=s,n},{});function pm(){return"colors"in V.inspectOpts?!!V.inspectOpts.colors:fm.isatty(process.stderr.fd)}function mm(n){let{namespace:e,useColors:t}=this;if(t){let s=this.color,o="\x1B[3"+(s<8?s:"8;5;"+s),a=` ${o};1m${e} \x1B[0m`;n[0]=a+n[0].split(`
3
+ var Pf=Object.create;var cs=Object.defineProperty;var If=Object.getOwnPropertyDescriptor;var Of=Object.getOwnPropertyNames;var kf=Object.getPrototypeOf,$f=Object.prototype.hasOwnProperty;var Z=(r=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(r,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):r)(function(r){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+r+'" is not supported')});var G=(r,e,t)=>()=>{if(t)throw t[0];try{return r&&(e=r(r=0)),e}catch(o){throw t=[o],o}};var X=(r,e)=>()=>{try{return e||r((e={exports:{}}).exports,e),e.exports}catch(t){throw e=0,t}},Ea=(r,e)=>{for(var t in e)cs(r,t,{get:e[t],enumerable:!0})},Df=(r,e,t,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Of(e))!$f.call(r,s)&&s!==t&&cs(r,s,{get:()=>e[s],enumerable:!(o=If(e,s))||o.enumerable});return r};var Ht=(r,e,t)=>(t=r!=null?Pf(kf(r)):{},Df(e||!r||!r.__esModule?cs(t,"default",{value:r,enumerable:!0}):t,r));var Es=X((QS,Fc)=>{"use strict";var Wn=Object.prototype.hasOwnProperty,Mc=Object.prototype.toString,Oc=Object.defineProperty,kc=Object.getOwnPropertyDescriptor,$c=function(e){return typeof Array.isArray=="function"?Array.isArray(e):Mc.call(e)==="[object Array]"},Dc=function(e){if(!e||Mc.call(e)!=="[object Object]")return!1;var t=Wn.call(e,"constructor"),o=e.constructor&&e.constructor.prototype&&Wn.call(e.constructor.prototype,"isPrototypeOf");if(e.constructor&&!t&&!o)return!1;var s;for(s in e);return typeof s>"u"||Wn.call(e,s)},Lc=function(e,t){Oc&&t.name==="__proto__"?Oc(e,t.name,{enumerable:!0,configurable:!0,value:t.newValue,writable:!0}):e[t.name]=t.newValue},Nc=function(e,t){if(t==="__proto__")if(Wn.call(e,t)){if(kc)return kc(e,t).value}else return;return e[t]};Fc.exports=function r(){var e,t,o,s,a,l,d=arguments[0],p=1,u=arguments.length,f=!1;for(typeof d=="boolean"&&(f=d,d=arguments[1]||{},p=2),(d==null||typeof d!="object"&&typeof d!="function")&&(d={});p<u;++p)if(e=arguments[p],e!=null)for(t in e)o=Nc(d,t),s=Nc(e,t),d!==s&&(f&&s&&(Dc(s)||(a=$c(s)))?(a?(a=!1,l=o&&$c(o)?o:[]):l=o&&Dc(o)?o:{},Lc(d,{name:t,newValue:r(f,l,s)})):typeof s<"u"&&Lc(d,{name:t,newValue:s}));return d}});var Bc=X((KS,Vp)=>{Vp.exports={name:"gaxios",version:"8.0.0",description:"A simple common HTTP client specifically for Google APIs and services.",main:"build/cjs/src/index.js",types:"build/cjs/src/index.d.ts",files:["build/"],exports:{".":{import:{types:"./build/esm/src/index.d.ts",default:"./build/esm/src/index.js"},require:{types:"./build/cjs/src/index.d.ts",default:"./build/cjs/src/index.js"}}},scripts:{lint:"gts check --no-inline-config",test:"c8 mocha build/esm/test","presystem-test":"npm run compile","system-test":"mocha build/esm/system-test --timeout 80000",compile:"tsc -b ./tsconfig.json ./tsconfig.cjs.json && node utils/enable-esm.mjs",fix:"gts fix",prepare:"npm run compile",pretest:"npm run compile",webpack:"webpack","prebrowser-test":"npm run compile","browser-test":"node build/browser-test/browser-test-runner.js",docs:"jsdoc -c .jsdoc.js","samples-test":"cd samples/ && npm link ../ && npm test && cd ../",prelint:"cd samples; npm link ../; npm install",clean:"gts clean"},repository:{type:"git",directory:"core/packages/gaxios",url:"https://github.com/googleapis/google-cloud-node.git"},keywords:["google"],engines:{node:">=22"},author:"Google, LLC",license:"Apache-2.0",devDependencies:{"@babel/plugin-proposal-private-methods":"^7.18.6","@types/cors":"^2.8.6","@types/express":"^5.0.0","@types/extend":"^3.0.1","@types/mocha":"^10.0.10","@types/multiparty":"4.2.1","@types/mv":"^2.1.0","@types/ncp":"^2.0.8","@types/node":"^24.0.0","@types/sinon":"^21.0.0","@types/tmp":"^0.2.6",assert:"^2.0.0",browserify:"^17.0.0",c8:"^10.1.3",cors:"^2.8.5",express:"^5.0.0",gts:"^6.0.2","is-docker":"^3.0.0",jsdoc:"^4.0.4","jsdoc-fresh":"^6.0.0","jsdoc-region-tag":"^5.0.0",karma:"^6.0.0","karma-chrome-launcher":"^3.0.0","karma-coverage":"^2.0.0","karma-firefox-launcher":"^2.0.0","karma-mocha":"^2.0.0","karma-remap-coverage":"^0.1.5","karma-sourcemap-loader":"^0.4.0","karma-webpack":"^5.0.0",mocha:"^11.1.0",multiparty:"^4.2.1",mv:"^2.1.1",ncp:"^2.0.0",nock:"14.0.5","null-loader":"^4.0.1","pack-n-play":"^4.0.0",puppeteer:"^24.0.0",sinon:"21.0.3","stream-browserify":"^3.0.0",tmp:"0.2.7","ts-loader":"^9.5.2",typescript:"5.8.3","undici-types":"^7.24.1",webpack:"^5.97.1","webpack-cli":"^6.0.1"},dependencies:{extend:"^3.0.2","https-proxy-agent":"^7.0.1","node-fetch":"^3.3.2"},homepage:"https://github.com/googleapis/google-cloud-node/tree/main/core/packages/gaxios"}});var qc=X((ew,Uc)=>{var Yp=Bc();Uc.exports={pkg:Yp}});var Gc=X((ow,Hc)=>{var Xt=1e3,Qt=Xt*60,Kt=Qt*60,At=Kt*24,Kp=At*7,em=At*365.25;Hc.exports=function(r,e){e=e||{};var t=typeof r;if(t==="string"&&r.length>0)return tm(r);if(t==="number"&&isFinite(r))return e.long?nm(r):rm(r);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(r))};function tm(r){if(r=String(r),!(r.length>100)){var e=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(r);if(e){var t=parseFloat(e[1]),o=(e[2]||"ms").toLowerCase();switch(o){case"years":case"year":case"yrs":case"yr":case"y":return t*em;case"weeks":case"week":case"w":return t*Kp;case"days":case"day":case"d":return t*At;case"hours":case"hour":case"hrs":case"hr":case"h":return t*Kt;case"minutes":case"minute":case"mins":case"min":case"m":return t*Qt;case"seconds":case"second":case"secs":case"sec":case"s":return t*Xt;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:return}}}}function rm(r){var e=Math.abs(r);return e>=At?Math.round(r/At)+"d":e>=Kt?Math.round(r/Kt)+"h":e>=Qt?Math.round(r/Qt)+"m":e>=Xt?Math.round(r/Xt)+"s":r+"ms"}function nm(r){var e=Math.abs(r);return e>=At?zn(r,e,At,"day"):e>=Kt?zn(r,e,Kt,"hour"):e>=Qt?zn(r,e,Qt,"minute"):e>=Xt?zn(r,e,Xt,"second"):r+" ms"}function zn(r,e,t,o){var s=e>=t*1.5;return Math.round(r/t)+" "+o+(s?"s":"")}});var Ps=X((sw,Jc)=>{function om(r){t.debug=t,t.default=t,t.coerce=p,t.disable=l,t.enable=s,t.enabled=d,t.humanize=Gc(),t.destroy=u,Object.keys(r).forEach(f=>{t[f]=r[f]}),t.names=[],t.skips=[],t.formatters={};function e(f){let y=0;for(let g=0;g<f.length;g++)y=(y<<5)-y+f.charCodeAt(g),y|=0;return t.colors[Math.abs(y)%t.colors.length]}t.selectColor=e;function t(f){let y,g=null,_,S;function E(...R){if(!E.enabled)return;let x=E,A=Number(new Date),C=A-(y||A);x.diff=C,x.prev=y,x.curr=A,y=A,R[0]=t.coerce(R[0]),typeof R[0]!="string"&&R.unshift("%O");let v=0;R[0]=R[0].replace(/%([a-zA-Z%])/g,($,H)=>{if($==="%%")return"%";v++;let Ve=t.formatters[H];if(typeof Ve=="function"){let cr=R[v];$=Ve.call(x,cr),R.splice(v,1),v--}return $}),t.formatArgs.call(x,R),(x.log||t.log).apply(x,R)}return E.namespace=f,E.useColors=t.useColors(),E.color=t.selectColor(f),E.extend=o,E.destroy=t.destroy,Object.defineProperty(E,"enabled",{enumerable:!0,configurable:!1,get:()=>g!==null?g:(_!==t.namespaces&&(_=t.namespaces,S=t.enabled(f)),S),set:R=>{g=R}}),typeof t.init=="function"&&t.init(E),E}function o(f,y){let g=t(this.namespace+(typeof y>"u"?":":y)+f);return g.log=this.log,g}function s(f){t.save(f),t.namespaces=f,t.names=[],t.skips=[];let y=(typeof f=="string"?f:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(let g of y)g[0]==="-"?t.skips.push(g.slice(1)):t.names.push(g)}function a(f,y){let g=0,_=0,S=-1,E=0;for(;g<f.length;)if(_<y.length&&(y[_]===f[g]||y[_]==="*"))y[_]==="*"?(S=_,E=g,_++):(g++,_++);else if(S!==-1)_=S+1,E++,g=E;else return!1;for(;_<y.length&&y[_]==="*";)_++;return _===y.length}function l(){let f=[...t.names,...t.skips.map(y=>"-"+y)].join(",");return t.enable(""),f}function d(f){for(let y of t.skips)if(a(f,y))return!1;for(let y of t.names)if(a(f,y))return!0;return!1}function p(f){return f instanceof Error?f.stack||f.message:f}function u(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return t.enable(t.load()),t}Jc.exports=om});var Vc=X((ne,Hn)=>{ne.formatArgs=im;ne.save=am;ne.load=cm;ne.useColors=sm;ne.storage=lm();ne.destroy=(()=>{let r=!1;return()=>{r||(r=!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`."))}})();ne.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"];function sm(){if(typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let r;return typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&(r=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(r[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function im(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+Hn.exports.humanize(this.diff),!this.useColors)return;let e="color: "+this.color;r.splice(1,0,e,"color: inherit");let t=0,o=0;r[0].replace(/%[a-zA-Z%]/g,s=>{s!=="%%"&&(t++,s==="%c"&&(o=t))}),r.splice(o,0,e)}ne.log=console.debug||console.log||(()=>{});function am(r){try{r?ne.storage.setItem("debug",r):ne.storage.removeItem("debug")}catch{}}function cm(){let r;try{r=ne.storage.getItem("debug")||ne.storage.getItem("DEBUG")}catch{}return!r&&typeof process<"u"&&"env"in process&&(r=process.env.DEBUG),r}function lm(){try{return localStorage}catch{}}Hn.exports=Ps()(ne);var{formatters:um}=Hn.exports;um.j=function(r){try{return JSON.stringify(r)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var Zc=X((iw,Yc)=>{"use strict";Yc.exports=(r,e=process.argv)=>{let t=r.startsWith("-")?"":r.length===1?"-":"--",o=e.indexOf(t+r),s=e.indexOf("--");return o!==-1&&(s===-1||o<s)}});var Kc=X((aw,Qc)=>{"use strict";var dm=Z("os"),Xc=Z("tty"),ge=Zc(),{env:J}=process,dt;ge("no-color")||ge("no-colors")||ge("color=false")||ge("color=never")?dt=0:(ge("color")||ge("colors")||ge("color=true")||ge("color=always"))&&(dt=1);"FORCE_COLOR"in J&&(J.FORCE_COLOR==="true"?dt=1:J.FORCE_COLOR==="false"?dt=0:dt=J.FORCE_COLOR.length===0?1:Math.min(parseInt(J.FORCE_COLOR,10),3));function Is(r){return r===0?!1:{level:r,hasBasic:!0,has256:r>=2,has16m:r>=3}}function Os(r,e){if(dt===0)return 0;if(ge("color=16m")||ge("color=full")||ge("color=truecolor"))return 3;if(ge("color=256"))return 2;if(r&&!e&&dt===void 0)return 0;let t=dt||0;if(J.TERM==="dumb")return t;if(process.platform==="win32"){let o=dm.release().split(".");return Number(o[0])>=10&&Number(o[2])>=10586?Number(o[2])>=14931?3:2:1}if("CI"in J)return["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE"].some(o=>o in J)||J.CI_NAME==="codeship"?1:t;if("TEAMCITY_VERSION"in J)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(J.TEAMCITY_VERSION)?1:0;if(J.COLORTERM==="truecolor")return 3;if("TERM_PROGRAM"in J){let o=parseInt((J.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(J.TERM_PROGRAM){case"iTerm.app":return o>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(J.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(J.TERM)||"COLORTERM"in J?1:t}function fm(r){let e=Os(r,r&&r.isTTY);return Is(e)}Qc.exports={supportsColor:fm,stdout:Is(Os(!0,Xc.isatty(1))),stderr:Is(Os(!0,Xc.isatty(2)))}});var tl=X((V,Jn)=>{var pm=Z("tty"),Gn=Z("util");V.init=wm;V.log=ym;V.formatArgs=hm;V.save=bm;V.load=Sm;V.useColors=mm;V.destroy=Gn.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");V.colors=[6,2,3,4,5,1];try{let r=Kc();r&&(r.stderr||r).level>=2&&(V.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{}V.inspectOpts=Object.keys(process.env).filter(r=>/^debug_/i.test(r)).reduce((r,e)=>{let t=e.substring(6).toLowerCase().replace(/_([a-z])/g,(s,a)=>a.toUpperCase()),o=process.env[e];return/^(yes|on|true|enabled)$/i.test(o)?o=!0:/^(no|off|false|disabled)$/i.test(o)?o=!1:o==="null"?o=null:o=Number(o),r[t]=o,r},{});function mm(){return"colors"in V.inspectOpts?!!V.inspectOpts.colors:pm.isatty(process.stderr.fd)}function hm(r){let{namespace:e,useColors:t}=this;if(t){let o=this.color,s="\x1B[3"+(o<8?o:"8;5;"+o),a=` ${s};1m${e} \x1B[0m`;r[0]=a+r[0].split(`
4
4
  `).join(`
5
- `+a),n.push(o+"m+"+Jn.exports.humanize(this.diff)+"\x1B[0m")}else n[0]=hm()+e+" "+n[0]}function hm(){return V.inspectOpts.hideDate?"":new Date().toISOString()+" "}function gm(...n){return process.stderr.write(Gn.formatWithOptions(V.inspectOpts,...n)+`
6
- `)}function ym(n){n?process.env.DEBUG=n:delete process.env.DEBUG}function bm(){return process.env.DEBUG}function Sm(n){n.inspectOpts={};let e=Object.keys(V.inspectOpts);for(let t=0;t<e.length;t++)n.inspectOpts[e[t]]=V.inspectOpts[e[t]]}Jn.exports=Po()(V);var{formatters:el}=Jn.exports;el.o=function(n){return this.inspectOpts.colors=this.useColors,Gn.inspect(n,this.inspectOpts).split(`
7
- `).map(e=>e.trim()).join(" ")};el.O=function(n){return this.inspectOpts.colors=this.useColors,Gn.inspect(n,this.inspectOpts)}});var $o=X((aw,ko)=>{typeof process>"u"||process.type==="renderer"||process.browser===!0||process.__nwjs?ko.exports=Vc():ko.exports=tl()});var sl=X(se=>{"use strict";var wm=se&&se.__createBinding||(Object.create?(function(n,e,t,s){s===void 0&&(s=t);var o=Object.getOwnPropertyDescriptor(e,t);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(n,s,o)}):(function(n,e,t,s){s===void 0&&(s=t),n[s]=e[t]})),_m=se&&se.__setModuleDefault||(Object.create?(function(n,e){Object.defineProperty(n,"default",{enumerable:!0,value:e})}):function(n,e){n.default=e}),rl=se&&se.__importStar||function(n){if(n&&n.__esModule)return n;var e={};if(n!=null)for(var t in n)t!=="default"&&Object.prototype.hasOwnProperty.call(n,t)&&wm(e,n,t);return _m(e,n),e};Object.defineProperty(se,"__esModule",{value:!0});se.req=se.json=se.toBuffer=void 0;var Tm=rl(Z("http")),Rm=rl(Z("https"));async function nl(n){let e=0,t=[];for await(let s of n)e+=s.length,t.push(s);return Buffer.concat(t,e)}se.toBuffer=nl;async function Em(n){let t=(await nl(n)).toString("utf8");try{return JSON.parse(t)}catch(s){let o=s;throw o.message+=` (input: ${t})`,o}}se.json=Em;function xm(n,e={}){let s=((typeof n=="string"?n:n.href).startsWith("https:")?Rm:Tm).request(n,e),o=new Promise((a,l)=>{s.once("response",a).once("error",l).end()});return s.then=o.then.bind(o),s}se.req=xm});var cl=X(ue=>{"use strict";var il=ue&&ue.__createBinding||(Object.create?(function(n,e,t,s){s===void 0&&(s=t);var o=Object.getOwnPropertyDescriptor(e,t);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(n,s,o)}):(function(n,e,t,s){s===void 0&&(s=t),n[s]=e[t]})),vm=ue&&ue.__setModuleDefault||(Object.create?(function(n,e){Object.defineProperty(n,"default",{enumerable:!0,value:e})}):function(n,e){n.default=e}),al=ue&&ue.__importStar||function(n){if(n&&n.__esModule)return n;var e={};if(n!=null)for(var t in n)t!=="default"&&Object.prototype.hasOwnProperty.call(n,t)&&il(e,n,t);return vm(e,n),e},Cm=ue&&ue.__exportStar||function(n,e){for(var t in n)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&il(e,n,t)};Object.defineProperty(ue,"__esModule",{value:!0});ue.Agent=void 0;var Am=al(Z("net")),ol=al(Z("http")),Pm=Z("https");Cm(sl(),ue);var ke=Symbol("AgentBaseInternalState"),Do=class extends ol.Agent{constructor(e){super(e),this[ke]={}}isSecureEndpoint(e){if(e){if(typeof e.secureEndpoint=="boolean")return e.secureEndpoint;if(typeof e.protocol=="string")return e.protocol==="https:"}let{stack:t}=new Error;return typeof t!="string"?!1:t.split(`
8
- `).some(s=>s.indexOf("(https.js:")!==-1||s.indexOf("node:https:")!==-1)}incrementSockets(e){if(this.maxSockets===1/0&&this.maxTotalSockets===1/0)return null;this.sockets[e]||(this.sockets[e]=[]);let t=new Am.Socket({writable:!1});return this.sockets[e].push(t),this.totalSocketCount++,t}decrementSockets(e,t){if(!this.sockets[e]||t===null)return;let s=this.sockets[e],o=s.indexOf(t);o!==-1&&(s.splice(o,1),this.totalSocketCount--,s.length===0&&delete this.sockets[e])}getName(e){return this.isSecureEndpoint(e)?Pm.Agent.prototype.getName.call(this,e):super.getName(e)}createSocket(e,t,s){let o={...t,secureEndpoint:this.isSecureEndpoint(t)},a=this.getName(o),l=this.incrementSockets(a);Promise.resolve().then(()=>this.connect(e,o)).then(d=>{if(this.decrementSockets(a,l),d instanceof ol.Agent)try{return d.addRequest(e,o)}catch(p){return s(p)}this[ke].currentSocket=d,super.createSocket(e,t,s)},d=>{this.decrementSockets(a,l),s(d)})}createConnection(){let e=this[ke].currentSocket;if(this[ke].currentSocket=void 0,!e)throw new Error("No socket was returned in the `connect()` function");return e}get defaultPort(){return this[ke].defaultPort??(this.protocol==="https:"?443:80)}set defaultPort(e){this[ke]&&(this[ke].defaultPort=e)}get protocol(){return this[ke].protocol??(this.isSecureEndpoint()?"https:":"http:")}set protocol(e){this[ke]&&(this[ke].protocol=e)}};ue.Agent=Do});var ll=X(er=>{"use strict";var Im=er&&er.__importDefault||function(n){return n&&n.__esModule?n:{default:n}};Object.defineProperty(er,"__esModule",{value:!0});er.parseProxyResponse=void 0;var Om=Im($o()),Vn=(0,Om.default)("https-proxy-agent:parse-proxy-response");function km(n){return new Promise((e,t)=>{let s=0,o=[];function a(){let f=n.read();f?u(f):n.once("readable",a)}function l(){n.removeListener("end",d),n.removeListener("error",p),n.removeListener("readable",a)}function d(){l(),Vn("onend"),t(new Error("Proxy connection ended before receiving CONNECT response"))}function p(f){l(),Vn("onerror %o",f),t(f)}function u(f){o.push(f),s+=f.length;let y=Buffer.concat(o,s),g=y.indexOf(`\r
5
+ `+a),r.push(s+"m+"+Jn.exports.humanize(this.diff)+"\x1B[0m")}else r[0]=gm()+e+" "+r[0]}function gm(){return V.inspectOpts.hideDate?"":new Date().toISOString()+" "}function ym(...r){return process.stderr.write(Gn.formatWithOptions(V.inspectOpts,...r)+`
6
+ `)}function bm(r){r?process.env.DEBUG=r:delete process.env.DEBUG}function Sm(){return process.env.DEBUG}function wm(r){r.inspectOpts={};let e=Object.keys(V.inspectOpts);for(let t=0;t<e.length;t++)r.inspectOpts[e[t]]=V.inspectOpts[e[t]]}Jn.exports=Ps()(V);var{formatters:el}=Jn.exports;el.o=function(r){return this.inspectOpts.colors=this.useColors,Gn.inspect(r,this.inspectOpts).split(`
7
+ `).map(e=>e.trim()).join(" ")};el.O=function(r){return this.inspectOpts.colors=this.useColors,Gn.inspect(r,this.inspectOpts)}});var $s=X((cw,ks)=>{typeof process>"u"||process.type==="renderer"||process.browser===!0||process.__nwjs?ks.exports=Vc():ks.exports=tl()});var ol=X(oe=>{"use strict";var _m=oe&&oe.__createBinding||(Object.create?(function(r,e,t,o){o===void 0&&(o=t);var s=Object.getOwnPropertyDescriptor(e,t);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,o,s)}):(function(r,e,t,o){o===void 0&&(o=t),r[o]=e[t]})),Tm=oe&&oe.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),rl=oe&&oe.__importStar||function(r){if(r&&r.__esModule)return r;var e={};if(r!=null)for(var t in r)t!=="default"&&Object.prototype.hasOwnProperty.call(r,t)&&_m(e,r,t);return Tm(e,r),e};Object.defineProperty(oe,"__esModule",{value:!0});oe.req=oe.json=oe.toBuffer=void 0;var Rm=rl(Z("http")),Em=rl(Z("https"));async function nl(r){let e=0,t=[];for await(let o of r)e+=o.length,t.push(o);return Buffer.concat(t,e)}oe.toBuffer=nl;async function xm(r){let t=(await nl(r)).toString("utf8");try{return JSON.parse(t)}catch(o){let s=o;throw s.message+=` (input: ${t})`,s}}oe.json=xm;function vm(r,e={}){let o=((typeof r=="string"?r:r.href).startsWith("https:")?Em:Rm).request(r,e),s=new Promise((a,l)=>{o.once("response",a).once("error",l).end()});return o.then=s.then.bind(s),o}oe.req=vm});var cl=X(ue=>{"use strict";var il=ue&&ue.__createBinding||(Object.create?(function(r,e,t,o){o===void 0&&(o=t);var s=Object.getOwnPropertyDescriptor(e,t);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,o,s)}):(function(r,e,t,o){o===void 0&&(o=t),r[o]=e[t]})),Cm=ue&&ue.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),al=ue&&ue.__importStar||function(r){if(r&&r.__esModule)return r;var e={};if(r!=null)for(var t in r)t!=="default"&&Object.prototype.hasOwnProperty.call(r,t)&&il(e,r,t);return Cm(e,r),e},Am=ue&&ue.__exportStar||function(r,e){for(var t in r)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&il(e,r,t)};Object.defineProperty(ue,"__esModule",{value:!0});ue.Agent=void 0;var Pm=al(Z("net")),sl=al(Z("http")),Im=Z("https");Am(ol(),ue);var ke=Symbol("AgentBaseInternalState"),Ds=class extends sl.Agent{constructor(e){super(e),this[ke]={}}isSecureEndpoint(e){if(e){if(typeof e.secureEndpoint=="boolean")return e.secureEndpoint;if(typeof e.protocol=="string")return e.protocol==="https:"}let{stack:t}=new Error;return typeof t!="string"?!1:t.split(`
8
+ `).some(o=>o.indexOf("(https.js:")!==-1||o.indexOf("node:https:")!==-1)}incrementSockets(e){if(this.maxSockets===1/0&&this.maxTotalSockets===1/0)return null;this.sockets[e]||(this.sockets[e]=[]);let t=new Pm.Socket({writable:!1});return this.sockets[e].push(t),this.totalSocketCount++,t}decrementSockets(e,t){if(!this.sockets[e]||t===null)return;let o=this.sockets[e],s=o.indexOf(t);s!==-1&&(o.splice(s,1),this.totalSocketCount--,o.length===0&&delete this.sockets[e])}getName(e){return this.isSecureEndpoint(e)?Im.Agent.prototype.getName.call(this,e):super.getName(e)}createSocket(e,t,o){let s={...t,secureEndpoint:this.isSecureEndpoint(t)},a=this.getName(s),l=this.incrementSockets(a);Promise.resolve().then(()=>this.connect(e,s)).then(d=>{if(this.decrementSockets(a,l),d instanceof sl.Agent)try{return d.addRequest(e,s)}catch(p){return o(p)}this[ke].currentSocket=d,super.createSocket(e,t,o)},d=>{this.decrementSockets(a,l),o(d)})}createConnection(){let e=this[ke].currentSocket;if(this[ke].currentSocket=void 0,!e)throw new Error("No socket was returned in the `connect()` function");return e}get defaultPort(){return this[ke].defaultPort??(this.protocol==="https:"?443:80)}set defaultPort(e){this[ke]&&(this[ke].defaultPort=e)}get protocol(){return this[ke].protocol??(this.isSecureEndpoint()?"https:":"http:")}set protocol(e){this[ke]&&(this[ke].protocol=e)}};ue.Agent=Ds});var ll=X(er=>{"use strict";var Om=er&&er.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(er,"__esModule",{value:!0});er.parseProxyResponse=void 0;var km=Om($s()),Vn=(0,km.default)("https-proxy-agent:parse-proxy-response");function $m(r){return new Promise((e,t)=>{let o=0,s=[];function a(){let f=r.read();f?u(f):r.once("readable",a)}function l(){r.removeListener("end",d),r.removeListener("error",p),r.removeListener("readable",a)}function d(){l(),Vn("onend"),t(new Error("Proxy connection ended before receiving CONNECT response"))}function p(f){l(),Vn("onerror %o",f),t(f)}function u(f){s.push(f),o+=f.length;let y=Buffer.concat(s,o),g=y.indexOf(`\r
9
9
  \r
10
10
  `);if(g===-1){Vn("have not received end of HTTP headers yet..."),a();return}let _=y.slice(0,g).toString("ascii").split(`\r
11
- `),S=_.shift();if(!S)return n.destroy(),t(new Error("No header received from proxy CONNECT response"));let E=S.split(" "),R=+E[1],x=E.slice(2).join(" "),A={};for(let C of _){if(!C)continue;let v=C.indexOf(":");if(v===-1)return n.destroy(),t(new Error(`Invalid header from proxy CONNECT response: "${C}"`));let k=C.slice(0,v).toLowerCase(),$=C.slice(v+1).trimStart(),H=A[k];typeof H=="string"?A[k]=[H,$]:Array.isArray(H)?H.push($):A[k]=$}Vn("got proxy server response: %o %o",S,A),l(),e({connect:{statusCode:R,statusText:x,headers:A},buffered:y})}n.on("error",p),n.on("end",d),a()})}er.parseProxyResponse=km});var hl=X(ye=>{"use strict";var $m=ye&&ye.__createBinding||(Object.create?(function(n,e,t,s){s===void 0&&(s=t);var o=Object.getOwnPropertyDescriptor(e,t);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(n,s,o)}):(function(n,e,t,s){s===void 0&&(s=t),n[s]=e[t]})),Dm=ye&&ye.__setModuleDefault||(Object.create?(function(n,e){Object.defineProperty(n,"default",{enumerable:!0,value:e})}):function(n,e){n.default=e}),pl=ye&&ye.__importStar||function(n){if(n&&n.__esModule)return n;var e={};if(n!=null)for(var t in n)t!=="default"&&Object.prototype.hasOwnProperty.call(n,t)&&$m(e,n,t);return Dm(e,n),e},ml=ye&&ye.__importDefault||function(n){return n&&n.__esModule?n:{default:n}};Object.defineProperty(ye,"__esModule",{value:!0});ye.HttpsProxyAgent=void 0;var Yn=pl(Z("net")),ul=pl(Z("tls")),Lm=ml(Z("assert")),Nm=ml($o()),Mm=cl(),Fm=Z("url"),Bm=ll(),vr=(0,Nm.default)("https-proxy-agent"),dl=n=>n.servername===void 0&&n.host&&!Yn.isIP(n.host)?{...n,servername:n.host}:n,Zn=class extends Mm.Agent{constructor(e,t){super(t),this.options={path:void 0},this.proxy=typeof e=="string"?new Fm.URL(e):e,this.proxyHeaders=t?.headers??{},vr("Creating new HttpsProxyAgent instance: %o",this.proxy.href);let s=(this.proxy.hostname||this.proxy.host).replace(/^\[|\]$/g,""),o=this.proxy.port?parseInt(this.proxy.port,10):this.proxy.protocol==="https:"?443:80;this.connectOpts={ALPNProtocols:["http/1.1"],...t?fl(t,"headers"):null,host:s,port:o}}async connect(e,t){let{proxy:s}=this;if(!t.host)throw new TypeError('No "host" provided');let o;s.protocol==="https:"?(vr("Creating `tls.Socket`: %o",this.connectOpts),o=ul.connect(dl(this.connectOpts))):(vr("Creating `net.Socket`: %o",this.connectOpts),o=Yn.connect(this.connectOpts));let a=typeof this.proxyHeaders=="function"?this.proxyHeaders():{...this.proxyHeaders},l=Yn.isIPv6(t.host)?`[${t.host}]`:t.host,d=`CONNECT ${l}:${t.port} HTTP/1.1\r
12
- `;if(s.username||s.password){let g=`${decodeURIComponent(s.username)}:${decodeURIComponent(s.password)}`;a["Proxy-Authorization"]=`Basic ${Buffer.from(g).toString("base64")}`}a.Host=`${l}:${t.port}`,a["Proxy-Connection"]||(a["Proxy-Connection"]=this.keepAlive?"Keep-Alive":"close");for(let g of Object.keys(a))d+=`${g}: ${a[g]}\r
13
- `;let p=(0,Bm.parseProxyResponse)(o);o.write(`${d}\r
14
- `);let{connect:u,buffered:f}=await p;if(e.emit("proxyConnect",u),this.emit("proxyConnect",u,e),u.statusCode===200)return e.once("socket",Um),t.secureEndpoint?(vr("Upgrading socket connection to TLS"),ul.connect({...fl(dl(t),"host","path","port"),socket:o})):o;o.destroy();let y=new Yn.Socket({writable:!1});return y.readable=!0,e.once("socket",g=>{vr("Replaying proxy buffer for failed request"),(0,Lm.default)(g.listenerCount("data")>0),g.push(f),g.push(null)}),y}};Zn.protocols=["http","https"];ye.HttpsProxyAgent=Zn;function Um(n){n.resume()}function fl(n,...e){let t={},s;for(s in n)e.includes(s)||(t[s]=n[s]);return t}});function qm(n){if(!/^data:/i.test(n))throw new TypeError('`uri` does not appear to be a Data URI (must begin with "data:")');n=n.replace(/\r?\n/g,"");let e=n.indexOf(",");if(e===-1||e<=4)throw new TypeError("malformed data: URI");let t=n.substring(5,e).split(";"),s="",o=!1,a=t[0]||"text/plain",l=a;for(let f=1;f<t.length;f++)t[f]==="base64"?o=!0:t[f]&&(l+=`;${t[f]}`,t[f].indexOf("charset=")===0&&(s=t[f].substring(8)));!t[0]&&!s.length&&(l+=";charset=US-ASCII",s="US-ASCII");let d=o?"base64":"ascii",p=unescape(n.substring(e+1)),u=Buffer.from(p,d);return u.type=a,u.typeFull=l,u.charset=s,u}var gl,yl=G(()=>{gl=qm});var Sl=X((Xn,bl)=>{(function(n,e){typeof Xn=="object"&&typeof bl<"u"?e(Xn):typeof define=="function"&&define.amd?define(["exports"],e):(n=typeof globalThis<"u"?globalThis:n||self,e(n.WebStreamsPolyfill={}))})(Xn,(function(n){"use strict";function e(){}function t(r){return typeof r=="object"&&r!==null||typeof r=="function"}let s=e;function o(r,i){try{Object.defineProperty(r,"name",{value:i,configurable:!0})}catch{}}let a=Promise,l=Promise.prototype.then,d=Promise.reject.bind(a);function p(r){return new a(r)}function u(r){return p(i=>i(r))}function f(r){return d(r)}function y(r,i,c){return l.call(r,i,c)}function g(r,i,c){y(y(r,i,c),void 0,s)}function _(r,i){g(r,i)}function S(r,i){g(r,void 0,i)}function E(r,i,c){return y(r,i,c)}function R(r){y(r,void 0,s)}let x=r=>{if(typeof queueMicrotask=="function")x=queueMicrotask;else{let i=u(void 0);x=c=>y(i,c)}return x(r)};function A(r,i,c){if(typeof r!="function")throw new TypeError("Argument is not a function");return Function.prototype.apply.call(r,i,c)}function C(r,i,c){try{return u(A(r,i,c))}catch(h){return f(h)}}let v=16384;class k{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(i){let c=this._back,h=c;c._elements.length===v-1&&(h={_elements:[],_next:void 0}),c._elements.push(i),h!==c&&(this._back=h,c._next=h),++this._size}shift(){let i=this._front,c=i,h=this._cursor,b=h+1,w=i._elements,T=w[h];return b===v&&(c=i._next,b=0),--this._size,this._cursor=b,i!==c&&(this._front=c),w[h]=void 0,T}forEach(i){let c=this._cursor,h=this._front,b=h._elements;for(;(c!==b.length||h._next!==void 0)&&!(c===b.length&&(h=h._next,b=h._elements,c=0,b.length===0));)i(b[c]),++c}peek(){let i=this._front,c=this._cursor;return i._elements[c]}}let $=Symbol("[[AbortSteps]]"),H=Symbol("[[ErrorSteps]]"),Ve=Symbol("[[CancelSteps]]"),cr=Symbol("[[PullSteps]]"),Ts=Symbol("[[ReleaseSteps]]");function ci(r,i){r._ownerReadableStream=i,i._reader=r,i._state==="readable"?Es(r):i._state==="closed"?Fu(r):li(r,i._storedError)}function Rs(r,i){let c=r._ownerReadableStream;return _e(c,i)}function Le(r){let i=r._ownerReadableStream;i._state==="readable"?xs(r,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")):Bu(r,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")),i._readableStreamController[Ts](),i._reader=void 0,r._ownerReadableStream=void 0}function Nr(r){return new TypeError("Cannot "+r+" a stream using a released reader")}function Es(r){r._closedPromise=p((i,c)=>{r._closedPromise_resolve=i,r._closedPromise_reject=c})}function li(r,i){Es(r),xs(r,i)}function Fu(r){Es(r),ui(r)}function xs(r,i){r._closedPromise_reject!==void 0&&(R(r._closedPromise),r._closedPromise_reject(i),r._closedPromise_resolve=void 0,r._closedPromise_reject=void 0)}function Bu(r,i){li(r,i)}function ui(r){r._closedPromise_resolve!==void 0&&(r._closedPromise_resolve(void 0),r._closedPromise_resolve=void 0,r._closedPromise_reject=void 0)}let di=Number.isFinite||function(r){return typeof r=="number"&&isFinite(r)},Uu=Math.trunc||function(r){return r<0?Math.ceil(r):Math.floor(r)};function qu(r){return typeof r=="object"||typeof r=="function"}function Ce(r,i){if(r!==void 0&&!qu(r))throw new TypeError(`${i} is not an object.`)}function fe(r,i){if(typeof r!="function")throw new TypeError(`${i} is not a function.`)}function ju(r){return typeof r=="object"&&r!==null||typeof r=="function"}function fi(r,i){if(!ju(r))throw new TypeError(`${i} is not an object.`)}function Ne(r,i,c){if(r===void 0)throw new TypeError(`Parameter ${i} is required in '${c}'.`)}function vs(r,i,c){if(r===void 0)throw new TypeError(`${i} is required in '${c}'.`)}function Cs(r){return Number(r)}function pi(r){return r===0?0:r}function Wu(r){return pi(Uu(r))}function As(r,i){let h=Number.MAX_SAFE_INTEGER,b=Number(r);if(b=pi(b),!di(b))throw new TypeError(`${i} is not a finite number`);if(b=Wu(b),b<0||b>h)throw new TypeError(`${i} is outside the accepted range of 0 to ${h}, inclusive`);return!di(b)||b===0?0:b}function Ps(r,i){if(!tt(r))throw new TypeError(`${i} is not a ReadableStream.`)}function $t(r){return new Ye(r)}function mi(r,i){r._reader._readRequests.push(i)}function Is(r,i,c){let b=r._reader._readRequests.shift();c?b._closeSteps():b._chunkSteps(i)}function Mr(r){return r._reader._readRequests.length}function hi(r){let i=r._reader;return!(i===void 0||!Ze(i))}class Ye{constructor(i){if(Ne(i,1,"ReadableStreamDefaultReader"),Ps(i,"First parameter"),rt(i))throw new TypeError("This stream has already been locked for exclusive reading by another reader");ci(this,i),this._readRequests=new k}get closed(){return Ze(this)?this._closedPromise:f(Fr("closed"))}cancel(i=void 0){return Ze(this)?this._ownerReadableStream===void 0?f(Nr("cancel")):Rs(this,i):f(Fr("cancel"))}read(){if(!Ze(this))return f(Fr("read"));if(this._ownerReadableStream===void 0)return f(Nr("read from"));let i,c,h=p((w,T)=>{i=w,c=T});return lr(this,{_chunkSteps:w=>i({value:w,done:!1}),_closeSteps:()=>i({value:void 0,done:!0}),_errorSteps:w=>c(w)}),h}releaseLock(){if(!Ze(this))throw Fr("releaseLock");this._ownerReadableStream!==void 0&&zu(this)}}Object.defineProperties(Ye.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),o(Ye.prototype.cancel,"cancel"),o(Ye.prototype.read,"read"),o(Ye.prototype.releaseLock,"releaseLock"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Ye.prototype,Symbol.toStringTag,{value:"ReadableStreamDefaultReader",configurable:!0});function Ze(r){return!t(r)||!Object.prototype.hasOwnProperty.call(r,"_readRequests")?!1:r instanceof Ye}function lr(r,i){let c=r._ownerReadableStream;c._disturbed=!0,c._state==="closed"?i._closeSteps():c._state==="errored"?i._errorSteps(c._storedError):c._readableStreamController[cr](i)}function zu(r){Le(r);let i=new TypeError("Reader was released");gi(r,i)}function gi(r,i){let c=r._readRequests;r._readRequests=new k,c.forEach(h=>{h._errorSteps(i)})}function Fr(r){return new TypeError(`ReadableStreamDefaultReader.prototype.${r} can only be used on a ReadableStreamDefaultReader`)}let Hu=Object.getPrototypeOf(Object.getPrototypeOf(async function*(){}).prototype);class yi{constructor(i,c){this._ongoingPromise=void 0,this._isFinished=!1,this._reader=i,this._preventCancel=c}next(){let i=()=>this._nextSteps();return this._ongoingPromise=this._ongoingPromise?E(this._ongoingPromise,i,i):i(),this._ongoingPromise}return(i){let c=()=>this._returnSteps(i);return this._ongoingPromise?E(this._ongoingPromise,c,c):c()}_nextSteps(){if(this._isFinished)return Promise.resolve({value:void 0,done:!0});let i=this._reader,c,h,b=p((T,P)=>{c=T,h=P});return lr(i,{_chunkSteps:T=>{this._ongoingPromise=void 0,x(()=>c({value:T,done:!1}))},_closeSteps:()=>{this._ongoingPromise=void 0,this._isFinished=!0,Le(i),c({value:void 0,done:!0})},_errorSteps:T=>{this._ongoingPromise=void 0,this._isFinished=!0,Le(i),h(T)}}),b}_returnSteps(i){if(this._isFinished)return Promise.resolve({value:i,done:!0});this._isFinished=!0;let c=this._reader;if(!this._preventCancel){let h=Rs(c,i);return Le(c),E(h,()=>({value:i,done:!0}))}return Le(c),u({value:i,done:!0})}}let bi={next(){return Si(this)?this._asyncIteratorImpl.next():f(wi("next"))},return(r){return Si(this)?this._asyncIteratorImpl.return(r):f(wi("return"))}};Object.setPrototypeOf(bi,Hu);function Gu(r,i){let c=$t(r),h=new yi(c,i),b=Object.create(bi);return b._asyncIteratorImpl=h,b}function Si(r){if(!t(r)||!Object.prototype.hasOwnProperty.call(r,"_asyncIteratorImpl"))return!1;try{return r._asyncIteratorImpl instanceof yi}catch{return!1}}function wi(r){return new TypeError(`ReadableStreamAsyncIterator.${r} can only be used on a ReadableSteamAsyncIterator`)}let _i=Number.isNaN||function(r){return r!==r};var Os,ks,$s;function ur(r){return r.slice()}function Ti(r,i,c,h,b){new Uint8Array(r).set(new Uint8Array(c,h,b),i)}let Me=r=>(typeof r.transfer=="function"?Me=i=>i.transfer():typeof structuredClone=="function"?Me=i=>structuredClone(i,{transfer:[i]}):Me=i=>i,Me(r)),Xe=r=>(typeof r.detached=="boolean"?Xe=i=>i.detached:Xe=i=>i.byteLength===0,Xe(r));function Ri(r,i,c){if(r.slice)return r.slice(i,c);let h=c-i,b=new ArrayBuffer(h);return Ti(b,0,r,i,h),b}function Br(r,i){let c=r[i];if(c!=null){if(typeof c!="function")throw new TypeError(`${String(i)} is not a function`);return c}}function Ju(r){let i={[Symbol.iterator]:()=>r.iterator},c=(async function*(){return yield*i})(),h=c.next;return{iterator:c,nextMethod:h,done:!1}}let Ds=($s=(Os=Symbol.asyncIterator)!==null&&Os!==void 0?Os:(ks=Symbol.for)===null||ks===void 0?void 0:ks.call(Symbol,"Symbol.asyncIterator"))!==null&&$s!==void 0?$s:"@@asyncIterator";function Ei(r,i="sync",c){if(c===void 0)if(i==="async"){if(c=Br(r,Ds),c===void 0){let w=Br(r,Symbol.iterator),T=Ei(r,"sync",w);return Ju(T)}}else c=Br(r,Symbol.iterator);if(c===void 0)throw new TypeError("The object is not iterable");let h=A(c,r,[]);if(!t(h))throw new TypeError("The iterator method must return an object");let b=h.next;return{iterator:h,nextMethod:b,done:!1}}function Vu(r){let i=A(r.nextMethod,r.iterator,[]);if(!t(i))throw new TypeError("The iterator.next() method must return an object");return i}function Yu(r){return!!r.done}function Zu(r){return r.value}function Xu(r){return!(typeof r!="number"||_i(r)||r<0)}function xi(r){let i=Ri(r.buffer,r.byteOffset,r.byteOffset+r.byteLength);return new Uint8Array(i)}function Ls(r){let i=r._queue.shift();return r._queueTotalSize-=i.size,r._queueTotalSize<0&&(r._queueTotalSize=0),i.value}function Ns(r,i,c){if(!Xu(c)||c===1/0)throw new RangeError("Size must be a finite, non-NaN, non-negative number.");r._queue.push({value:i,size:c}),r._queueTotalSize+=c}function Qu(r){return r._queue.peek().value}function Qe(r){r._queue=new k,r._queueTotalSize=0}function vi(r){return r===DataView}function Ku(r){return vi(r.constructor)}function ed(r){return vi(r)?1:r.BYTES_PER_ELEMENT}class bt{constructor(){throw new TypeError("Illegal constructor")}get view(){if(!Ms(this))throw js("view");return this._view}respond(i){if(!Ms(this))throw js("respond");if(Ne(i,1,"respond"),i=As(i,"First parameter"),this._associatedReadableByteStreamController===void 0)throw new TypeError("This BYOB request has been invalidated");if(Xe(this._view.buffer))throw new TypeError("The BYOB request's buffer has been detached and so cannot be used as a response");Wr(this._associatedReadableByteStreamController,i)}respondWithNewView(i){if(!Ms(this))throw js("respondWithNewView");if(Ne(i,1,"respondWithNewView"),!ArrayBuffer.isView(i))throw new TypeError("You can only respond with array buffer views");if(this._associatedReadableByteStreamController===void 0)throw new TypeError("This BYOB request has been invalidated");if(Xe(i.buffer))throw new TypeError("The given view's buffer has been detached and so cannot be used as a response");zr(this._associatedReadableByteStreamController,i)}}Object.defineProperties(bt.prototype,{respond:{enumerable:!0},respondWithNewView:{enumerable:!0},view:{enumerable:!0}}),o(bt.prototype.respond,"respond"),o(bt.prototype.respondWithNewView,"respondWithNewView"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(bt.prototype,Symbol.toStringTag,{value:"ReadableStreamBYOBRequest",configurable:!0});class Fe{constructor(){throw new TypeError("Illegal constructor")}get byobRequest(){if(!St(this))throw fr("byobRequest");return qs(this)}get desiredSize(){if(!St(this))throw fr("desiredSize");return Ni(this)}close(){if(!St(this))throw fr("close");if(this._closeRequested)throw new TypeError("The stream has already been closed; do not close it again!");let i=this._controlledReadableByteStream._state;if(i!=="readable")throw new TypeError(`The stream (in ${i} state) is not in the readable state and cannot be closed`);dr(this)}enqueue(i){if(!St(this))throw fr("enqueue");if(Ne(i,1,"enqueue"),!ArrayBuffer.isView(i))throw new TypeError("chunk must be an array buffer view");if(i.byteLength===0)throw new TypeError("chunk must have non-zero byteLength");if(i.buffer.byteLength===0)throw new TypeError("chunk's buffer must have non-zero byteLength");if(this._closeRequested)throw new TypeError("stream is closed or draining");let c=this._controlledReadableByteStream._state;if(c!=="readable")throw new TypeError(`The stream (in ${c} state) is not in the readable state and cannot be enqueued to`);jr(this,i)}error(i=void 0){if(!St(this))throw fr("error");pe(this,i)}[Ve](i){Ci(this),Qe(this);let c=this._cancelAlgorithm(i);return qr(this),c}[cr](i){let c=this._controlledReadableByteStream;if(this._queueTotalSize>0){Li(this,i);return}let h=this._autoAllocateChunkSize;if(h!==void 0){let b;try{b=new ArrayBuffer(h)}catch(T){i._errorSteps(T);return}let w={buffer:b,bufferByteLength:h,byteOffset:0,byteLength:h,bytesFilled:0,minimumFill:1,elementSize:1,viewConstructor:Uint8Array,readerType:"default"};this._pendingPullIntos.push(w)}mi(c,i),wt(this)}[Ts](){if(this._pendingPullIntos.length>0){let i=this._pendingPullIntos.peek();i.readerType="none",this._pendingPullIntos=new k,this._pendingPullIntos.push(i)}}}Object.defineProperties(Fe.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},byobRequest:{enumerable:!0},desiredSize:{enumerable:!0}}),o(Fe.prototype.close,"close"),o(Fe.prototype.enqueue,"enqueue"),o(Fe.prototype.error,"error"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Fe.prototype,Symbol.toStringTag,{value:"ReadableByteStreamController",configurable:!0});function St(r){return!t(r)||!Object.prototype.hasOwnProperty.call(r,"_controlledReadableByteStream")?!1:r instanceof Fe}function Ms(r){return!t(r)||!Object.prototype.hasOwnProperty.call(r,"_associatedReadableByteStreamController")?!1:r instanceof bt}function wt(r){if(!od(r))return;if(r._pulling){r._pullAgain=!0;return}r._pulling=!0;let c=r._pullAlgorithm();g(c,()=>(r._pulling=!1,r._pullAgain&&(r._pullAgain=!1,wt(r)),null),h=>(pe(r,h),null))}function Ci(r){Bs(r),r._pendingPullIntos=new k}function Fs(r,i){let c=!1;r._state==="closed"&&(c=!0);let h=Ai(i);i.readerType==="default"?Is(r,h,c):dd(r,h,c)}function Ai(r){let i=r.bytesFilled,c=r.elementSize;return new r.viewConstructor(r.buffer,r.byteOffset,i/c)}function Ur(r,i,c,h){r._queue.push({buffer:i,byteOffset:c,byteLength:h}),r._queueTotalSize+=h}function Pi(r,i,c,h){let b;try{b=Ri(i,c,c+h)}catch(w){throw pe(r,w),w}Ur(r,b,0,h)}function Ii(r,i){i.bytesFilled>0&&Pi(r,i.buffer,i.byteOffset,i.bytesFilled),Dt(r)}function Oi(r,i){let c=Math.min(r._queueTotalSize,i.byteLength-i.bytesFilled),h=i.bytesFilled+c,b=c,w=!1,T=h%i.elementSize,P=h-T;P>=i.minimumFill&&(b=P-i.bytesFilled,w=!0);let D=r._queue;for(;b>0;){let I=D.peek(),L=Math.min(b,I.byteLength),N=i.byteOffset+i.bytesFilled;Ti(i.buffer,N,I.buffer,I.byteOffset,L),I.byteLength===L?D.shift():(I.byteOffset+=L,I.byteLength-=L),r._queueTotalSize-=L,ki(r,L,i),b-=L}return w}function ki(r,i,c){c.bytesFilled+=i}function $i(r){r._queueTotalSize===0&&r._closeRequested?(qr(r),br(r._controlledReadableByteStream)):wt(r)}function Bs(r){r._byobRequest!==null&&(r._byobRequest._associatedReadableByteStreamController=void 0,r._byobRequest._view=null,r._byobRequest=null)}function Us(r){for(;r._pendingPullIntos.length>0;){if(r._queueTotalSize===0)return;let i=r._pendingPullIntos.peek();Oi(r,i)&&(Dt(r),Fs(r._controlledReadableByteStream,i))}}function td(r){let i=r._controlledReadableByteStream._reader;for(;i._readRequests.length>0;){if(r._queueTotalSize===0)return;let c=i._readRequests.shift();Li(r,c)}}function rd(r,i,c,h){let b=r._controlledReadableByteStream,w=i.constructor,T=ed(w),{byteOffset:P,byteLength:D}=i,I=c*T,L;try{L=Me(i.buffer)}catch(B){h._errorSteps(B);return}let N={buffer:L,bufferByteLength:L.byteLength,byteOffset:P,byteLength:D,bytesFilled:0,minimumFill:I,elementSize:T,viewConstructor:w,readerType:"byob"};if(r._pendingPullIntos.length>0){r._pendingPullIntos.push(N),Bi(b,h);return}if(b._state==="closed"){let B=new w(N.buffer,N.byteOffset,0);h._closeSteps(B);return}if(r._queueTotalSize>0){if(Oi(r,N)){let B=Ai(N);$i(r),h._chunkSteps(B);return}if(r._closeRequested){let B=new TypeError("Insufficient bytes to fill elements in the given buffer");pe(r,B),h._errorSteps(B);return}}r._pendingPullIntos.push(N),Bi(b,h),wt(r)}function nd(r,i){i.readerType==="none"&&Dt(r);let c=r._controlledReadableByteStream;if(Ws(c))for(;Ui(c)>0;){let h=Dt(r);Fs(c,h)}}function sd(r,i,c){if(ki(r,i,c),c.readerType==="none"){Ii(r,c),Us(r);return}if(c.bytesFilled<c.minimumFill)return;Dt(r);let h=c.bytesFilled%c.elementSize;if(h>0){let b=c.byteOffset+c.bytesFilled;Pi(r,c.buffer,b-h,h)}c.bytesFilled-=h,Fs(r._controlledReadableByteStream,c),Us(r)}function Di(r,i){let c=r._pendingPullIntos.peek();Bs(r),r._controlledReadableByteStream._state==="closed"?nd(r,c):sd(r,i,c),wt(r)}function Dt(r){return r._pendingPullIntos.shift()}function od(r){let i=r._controlledReadableByteStream;return i._state!=="readable"||r._closeRequested||!r._started?!1:!!(hi(i)&&Mr(i)>0||Ws(i)&&Ui(i)>0||Ni(r)>0)}function qr(r){r._pullAlgorithm=void 0,r._cancelAlgorithm=void 0}function dr(r){let i=r._controlledReadableByteStream;if(!(r._closeRequested||i._state!=="readable")){if(r._queueTotalSize>0){r._closeRequested=!0;return}if(r._pendingPullIntos.length>0){let c=r._pendingPullIntos.peek();if(c.bytesFilled%c.elementSize!==0){let h=new TypeError("Insufficient bytes to fill elements in the given buffer");throw pe(r,h),h}}qr(r),br(i)}}function jr(r,i){let c=r._controlledReadableByteStream;if(r._closeRequested||c._state!=="readable")return;let{buffer:h,byteOffset:b,byteLength:w}=i;if(Xe(h))throw new TypeError("chunk's buffer is detached and so cannot be enqueued");let T=Me(h);if(r._pendingPullIntos.length>0){let P=r._pendingPullIntos.peek();if(Xe(P.buffer))throw new TypeError("The BYOB request's buffer has been detached and so cannot be filled with an enqueued chunk");Bs(r),P.buffer=Me(P.buffer),P.readerType==="none"&&Ii(r,P)}if(hi(c))if(td(r),Mr(c)===0)Ur(r,T,b,w);else{r._pendingPullIntos.length>0&&Dt(r);let P=new Uint8Array(T,b,w);Is(c,P,!1)}else Ws(c)?(Ur(r,T,b,w),Us(r)):Ur(r,T,b,w);wt(r)}function pe(r,i){let c=r._controlledReadableByteStream;c._state==="readable"&&(Ci(r),Qe(r),qr(r),ua(c,i))}function Li(r,i){let c=r._queue.shift();r._queueTotalSize-=c.byteLength,$i(r);let h=new Uint8Array(c.buffer,c.byteOffset,c.byteLength);i._chunkSteps(h)}function qs(r){if(r._byobRequest===null&&r._pendingPullIntos.length>0){let i=r._pendingPullIntos.peek(),c=new Uint8Array(i.buffer,i.byteOffset+i.bytesFilled,i.byteLength-i.bytesFilled),h=Object.create(bt.prototype);ad(h,r,c),r._byobRequest=h}return r._byobRequest}function Ni(r){let i=r._controlledReadableByteStream._state;return i==="errored"?null:i==="closed"?0:r._strategyHWM-r._queueTotalSize}function Wr(r,i){let c=r._pendingPullIntos.peek();if(r._controlledReadableByteStream._state==="closed"){if(i!==0)throw new TypeError("bytesWritten must be 0 when calling respond() on a closed stream")}else{if(i===0)throw new TypeError("bytesWritten must be greater than 0 when calling respond() on a readable stream");if(c.bytesFilled+i>c.byteLength)throw new RangeError("bytesWritten out of range")}c.buffer=Me(c.buffer),Di(r,i)}function zr(r,i){let c=r._pendingPullIntos.peek();if(r._controlledReadableByteStream._state==="closed"){if(i.byteLength!==0)throw new TypeError("The view's length must be 0 when calling respondWithNewView() on a closed stream")}else if(i.byteLength===0)throw new TypeError("The view's length must be greater than 0 when calling respondWithNewView() on a readable stream");if(c.byteOffset+c.bytesFilled!==i.byteOffset)throw new RangeError("The region specified by view does not match byobRequest");if(c.bufferByteLength!==i.buffer.byteLength)throw new RangeError("The buffer of view has different capacity than byobRequest");if(c.bytesFilled+i.byteLength>c.byteLength)throw new RangeError("The region specified by view is larger than byobRequest");let b=i.byteLength;c.buffer=Me(i.buffer),Di(r,b)}function Mi(r,i,c,h,b,w,T){i._controlledReadableByteStream=r,i._pullAgain=!1,i._pulling=!1,i._byobRequest=null,i._queue=i._queueTotalSize=void 0,Qe(i),i._closeRequested=!1,i._started=!1,i._strategyHWM=w,i._pullAlgorithm=h,i._cancelAlgorithm=b,i._autoAllocateChunkSize=T,i._pendingPullIntos=new k,r._readableStreamController=i;let P=c();g(u(P),()=>(i._started=!0,wt(i),null),D=>(pe(i,D),null))}function id(r,i,c){let h=Object.create(Fe.prototype),b,w,T;i.start!==void 0?b=()=>i.start(h):b=()=>{},i.pull!==void 0?w=()=>i.pull(h):w=()=>u(void 0),i.cancel!==void 0?T=D=>i.cancel(D):T=()=>u(void 0);let P=i.autoAllocateChunkSize;if(P===0)throw new TypeError("autoAllocateChunkSize must be greater than 0");Mi(r,h,b,w,T,c,P)}function ad(r,i,c){r._associatedReadableByteStreamController=i,r._view=c}function js(r){return new TypeError(`ReadableStreamBYOBRequest.prototype.${r} can only be used on a ReadableStreamBYOBRequest`)}function fr(r){return new TypeError(`ReadableByteStreamController.prototype.${r} can only be used on a ReadableByteStreamController`)}function cd(r,i){Ce(r,i);let c=r?.mode;return{mode:c===void 0?void 0:ld(c,`${i} has member 'mode' that`)}}function ld(r,i){if(r=`${r}`,r!=="byob")throw new TypeError(`${i} '${r}' is not a valid enumeration value for ReadableStreamReaderMode`);return r}function ud(r,i){var c;Ce(r,i);let h=(c=r?.min)!==null&&c!==void 0?c:1;return{min:As(h,`${i} has member 'min' that`)}}function Fi(r){return new Ke(r)}function Bi(r,i){r._reader._readIntoRequests.push(i)}function dd(r,i,c){let b=r._reader._readIntoRequests.shift();c?b._closeSteps(i):b._chunkSteps(i)}function Ui(r){return r._reader._readIntoRequests.length}function Ws(r){let i=r._reader;return!(i===void 0||!_t(i))}class Ke{constructor(i){if(Ne(i,1,"ReadableStreamBYOBReader"),Ps(i,"First parameter"),rt(i))throw new TypeError("This stream has already been locked for exclusive reading by another reader");if(!St(i._readableStreamController))throw new TypeError("Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte source");ci(this,i),this._readIntoRequests=new k}get closed(){return _t(this)?this._closedPromise:f(Hr("closed"))}cancel(i=void 0){return _t(this)?this._ownerReadableStream===void 0?f(Nr("cancel")):Rs(this,i):f(Hr("cancel"))}read(i,c={}){if(!_t(this))return f(Hr("read"));if(!ArrayBuffer.isView(i))return f(new TypeError("view must be an array buffer view"));if(i.byteLength===0)return f(new TypeError("view must have non-zero byteLength"));if(i.buffer.byteLength===0)return f(new TypeError("view's buffer must have non-zero byteLength"));if(Xe(i.buffer))return f(new TypeError("view's buffer has been detached"));let h;try{h=ud(c,"options")}catch(I){return f(I)}let b=h.min;if(b===0)return f(new TypeError("options.min must be greater than 0"));if(Ku(i)){if(b>i.byteLength)return f(new RangeError("options.min must be less than or equal to view's byteLength"))}else if(b>i.length)return f(new RangeError("options.min must be less than or equal to view's length"));if(this._ownerReadableStream===void 0)return f(Nr("read from"));let w,T,P=p((I,L)=>{w=I,T=L});return qi(this,i,b,{_chunkSteps:I=>w({value:I,done:!1}),_closeSteps:I=>w({value:I,done:!0}),_errorSteps:I=>T(I)}),P}releaseLock(){if(!_t(this))throw Hr("releaseLock");this._ownerReadableStream!==void 0&&fd(this)}}Object.defineProperties(Ke.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),o(Ke.prototype.cancel,"cancel"),o(Ke.prototype.read,"read"),o(Ke.prototype.releaseLock,"releaseLock"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Ke.prototype,Symbol.toStringTag,{value:"ReadableStreamBYOBReader",configurable:!0});function _t(r){return!t(r)||!Object.prototype.hasOwnProperty.call(r,"_readIntoRequests")?!1:r instanceof Ke}function qi(r,i,c,h){let b=r._ownerReadableStream;b._disturbed=!0,b._state==="errored"?h._errorSteps(b._storedError):rd(b._readableStreamController,i,c,h)}function fd(r){Le(r);let i=new TypeError("Reader was released");ji(r,i)}function ji(r,i){let c=r._readIntoRequests;r._readIntoRequests=new k,c.forEach(h=>{h._errorSteps(i)})}function Hr(r){return new TypeError(`ReadableStreamBYOBReader.prototype.${r} can only be used on a ReadableStreamBYOBReader`)}function pr(r,i){let{highWaterMark:c}=r;if(c===void 0)return i;if(_i(c)||c<0)throw new RangeError("Invalid highWaterMark");return c}function Gr(r){let{size:i}=r;return i||(()=>1)}function Jr(r,i){Ce(r,i);let c=r?.highWaterMark,h=r?.size;return{highWaterMark:c===void 0?void 0:Cs(c),size:h===void 0?void 0:pd(h,`${i} has member 'size' that`)}}function pd(r,i){return fe(r,i),c=>Cs(r(c))}function md(r,i){Ce(r,i);let c=r?.abort,h=r?.close,b=r?.start,w=r?.type,T=r?.write;return{abort:c===void 0?void 0:hd(c,r,`${i} has member 'abort' that`),close:h===void 0?void 0:gd(h,r,`${i} has member 'close' that`),start:b===void 0?void 0:yd(b,r,`${i} has member 'start' that`),write:T===void 0?void 0:bd(T,r,`${i} has member 'write' that`),type:w}}function hd(r,i,c){return fe(r,c),h=>C(r,i,[h])}function gd(r,i,c){return fe(r,c),()=>C(r,i,[])}function yd(r,i,c){return fe(r,c),h=>A(r,i,[h])}function bd(r,i,c){return fe(r,c),(h,b)=>C(r,i,[h,b])}function Wi(r,i){if(!Lt(r))throw new TypeError(`${i} is not a WritableStream.`)}function Sd(r){if(typeof r!="object"||r===null)return!1;try{return typeof r.aborted=="boolean"}catch{return!1}}let wd=typeof AbortController=="function";function _d(){if(wd)return new AbortController}class et{constructor(i={},c={}){i===void 0?i=null:fi(i,"First parameter");let h=Jr(c,"Second parameter"),b=md(i,"First parameter");if(Hi(this),b.type!==void 0)throw new RangeError("Invalid type is specified");let T=Gr(h),P=pr(h,1);Ld(this,b,P,T)}get locked(){if(!Lt(this))throw Qr("locked");return Nt(this)}abort(i=void 0){return Lt(this)?Nt(this)?f(new TypeError("Cannot abort a stream that already has a writer")):Vr(this,i):f(Qr("abort"))}close(){return Lt(this)?Nt(this)?f(new TypeError("Cannot close a stream that already has a writer")):Ae(this)?f(new TypeError("Cannot close an already-closing stream")):Gi(this):f(Qr("close"))}getWriter(){if(!Lt(this))throw Qr("getWriter");return zi(this)}}Object.defineProperties(et.prototype,{abort:{enumerable:!0},close:{enumerable:!0},getWriter:{enumerable:!0},locked:{enumerable:!0}}),o(et.prototype.abort,"abort"),o(et.prototype.close,"close"),o(et.prototype.getWriter,"getWriter"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(et.prototype,Symbol.toStringTag,{value:"WritableStream",configurable:!0});function zi(r){return new Be(r)}function Td(r,i,c,h,b=1,w=()=>1){let T=Object.create(et.prototype);Hi(T);let P=Object.create(Mt.prototype);return Qi(T,P,r,i,c,h,b,w),T}function Hi(r){r._state="writable",r._storedError=void 0,r._writer=void 0,r._writableStreamController=void 0,r._writeRequests=new k,r._inFlightWriteRequest=void 0,r._closeRequest=void 0,r._inFlightCloseRequest=void 0,r._pendingAbortRequest=void 0,r._backpressure=!1}function Lt(r){return!t(r)||!Object.prototype.hasOwnProperty.call(r,"_writableStreamController")?!1:r instanceof et}function Nt(r){return r._writer!==void 0}function Vr(r,i){var c;if(r._state==="closed"||r._state==="errored")return u(void 0);r._writableStreamController._abortReason=i,(c=r._writableStreamController._abortController)===null||c===void 0||c.abort(i);let h=r._state;if(h==="closed"||h==="errored")return u(void 0);if(r._pendingAbortRequest!==void 0)return r._pendingAbortRequest._promise;let b=!1;h==="erroring"&&(b=!0,i=void 0);let w=p((T,P)=>{r._pendingAbortRequest={_promise:void 0,_resolve:T,_reject:P,_reason:i,_wasAlreadyErroring:b}});return r._pendingAbortRequest._promise=w,b||Hs(r,i),w}function Gi(r){let i=r._state;if(i==="closed"||i==="errored")return f(new TypeError(`The stream (in ${i} state) is not in the writable state and cannot be closed`));let c=p((b,w)=>{let T={_resolve:b,_reject:w};r._closeRequest=T}),h=r._writer;return h!==void 0&&r._backpressure&&i==="writable"&&Ks(h),Nd(r._writableStreamController),c}function Rd(r){return p((c,h)=>{let b={_resolve:c,_reject:h};r._writeRequests.push(b)})}function zs(r,i){if(r._state==="writable"){Hs(r,i);return}Gs(r)}function Hs(r,i){let c=r._writableStreamController;r._state="erroring",r._storedError=i;let h=r._writer;h!==void 0&&Vi(h,i),!Ad(r)&&c._started&&Gs(r)}function Gs(r){r._state="errored",r._writableStreamController[H]();let i=r._storedError;if(r._writeRequests.forEach(b=>{b._reject(i)}),r._writeRequests=new k,r._pendingAbortRequest===void 0){Yr(r);return}let c=r._pendingAbortRequest;if(r._pendingAbortRequest=void 0,c._wasAlreadyErroring){c._reject(i),Yr(r);return}let h=r._writableStreamController[$](c._reason);g(h,()=>(c._resolve(),Yr(r),null),b=>(c._reject(b),Yr(r),null))}function Ed(r){r._inFlightWriteRequest._resolve(void 0),r._inFlightWriteRequest=void 0}function xd(r,i){r._inFlightWriteRequest._reject(i),r._inFlightWriteRequest=void 0,zs(r,i)}function vd(r){r._inFlightCloseRequest._resolve(void 0),r._inFlightCloseRequest=void 0,r._state==="erroring"&&(r._storedError=void 0,r._pendingAbortRequest!==void 0&&(r._pendingAbortRequest._resolve(),r._pendingAbortRequest=void 0)),r._state="closed";let c=r._writer;c!==void 0&&ra(c)}function Cd(r,i){r._inFlightCloseRequest._reject(i),r._inFlightCloseRequest=void 0,r._pendingAbortRequest!==void 0&&(r._pendingAbortRequest._reject(i),r._pendingAbortRequest=void 0),zs(r,i)}function Ae(r){return!(r._closeRequest===void 0&&r._inFlightCloseRequest===void 0)}function Ad(r){return!(r._inFlightWriteRequest===void 0&&r._inFlightCloseRequest===void 0)}function Pd(r){r._inFlightCloseRequest=r._closeRequest,r._closeRequest=void 0}function Id(r){r._inFlightWriteRequest=r._writeRequests.shift()}function Yr(r){r._closeRequest!==void 0&&(r._closeRequest._reject(r._storedError),r._closeRequest=void 0);let i=r._writer;i!==void 0&&Xs(i,r._storedError)}function Js(r,i){let c=r._writer;c!==void 0&&i!==r._backpressure&&(i?Wd(c):Ks(c)),r._backpressure=i}class Be{constructor(i){if(Ne(i,1,"WritableStreamDefaultWriter"),Wi(i,"First parameter"),Nt(i))throw new TypeError("This stream has already been locked for exclusive writing by another writer");this._ownerWritableStream=i,i._writer=this;let c=i._state;if(c==="writable")!Ae(i)&&i._backpressure?en(this):na(this),Kr(this);else if(c==="erroring")Qs(this,i._storedError),Kr(this);else if(c==="closed")na(this),qd(this);else{let h=i._storedError;Qs(this,h),ta(this,h)}}get closed(){return Tt(this)?this._closedPromise:f(Rt("closed"))}get desiredSize(){if(!Tt(this))throw Rt("desiredSize");if(this._ownerWritableStream===void 0)throw hr("desiredSize");return Dd(this)}get ready(){return Tt(this)?this._readyPromise:f(Rt("ready"))}abort(i=void 0){return Tt(this)?this._ownerWritableStream===void 0?f(hr("abort")):Od(this,i):f(Rt("abort"))}close(){if(!Tt(this))return f(Rt("close"));let i=this._ownerWritableStream;return i===void 0?f(hr("close")):Ae(i)?f(new TypeError("Cannot close an already-closing stream")):Ji(this)}releaseLock(){if(!Tt(this))throw Rt("releaseLock");this._ownerWritableStream!==void 0&&Yi(this)}write(i=void 0){return Tt(this)?this._ownerWritableStream===void 0?f(hr("write to")):Zi(this,i):f(Rt("write"))}}Object.defineProperties(Be.prototype,{abort:{enumerable:!0},close:{enumerable:!0},releaseLock:{enumerable:!0},write:{enumerable:!0},closed:{enumerable:!0},desiredSize:{enumerable:!0},ready:{enumerable:!0}}),o(Be.prototype.abort,"abort"),o(Be.prototype.close,"close"),o(Be.prototype.releaseLock,"releaseLock"),o(Be.prototype.write,"write"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Be.prototype,Symbol.toStringTag,{value:"WritableStreamDefaultWriter",configurable:!0});function Tt(r){return!t(r)||!Object.prototype.hasOwnProperty.call(r,"_ownerWritableStream")?!1:r instanceof Be}function Od(r,i){let c=r._ownerWritableStream;return Vr(c,i)}function Ji(r){let i=r._ownerWritableStream;return Gi(i)}function kd(r){let i=r._ownerWritableStream,c=i._state;return Ae(i)||c==="closed"?u(void 0):c==="errored"?f(i._storedError):Ji(r)}function $d(r,i){r._closedPromiseState==="pending"?Xs(r,i):jd(r,i)}function Vi(r,i){r._readyPromiseState==="pending"?sa(r,i):zd(r,i)}function Dd(r){let i=r._ownerWritableStream,c=i._state;return c==="errored"||c==="erroring"?null:c==="closed"?0:Ki(i._writableStreamController)}function Yi(r){let i=r._ownerWritableStream,c=new TypeError("Writer was released and can no longer be used to monitor the stream's closedness");Vi(r,c),$d(r,c),i._writer=void 0,r._ownerWritableStream=void 0}function Zi(r,i){let c=r._ownerWritableStream,h=c._writableStreamController,b=Md(h,i);if(c!==r._ownerWritableStream)return f(hr("write to"));let w=c._state;if(w==="errored")return f(c._storedError);if(Ae(c)||w==="closed")return f(new TypeError("The stream is closing or closed and cannot be written to"));if(w==="erroring")return f(c._storedError);let T=Rd(c);return Fd(h,i,b),T}let Xi={};class Mt{constructor(){throw new TypeError("Illegal constructor")}get abortReason(){if(!Vs(this))throw Zs("abortReason");return this._abortReason}get signal(){if(!Vs(this))throw Zs("signal");if(this._abortController===void 0)throw new TypeError("WritableStreamDefaultController.prototype.signal is not supported");return this._abortController.signal}error(i=void 0){if(!Vs(this))throw Zs("error");this._controlledWritableStream._state==="writable"&&ea(this,i)}[$](i){let c=this._abortAlgorithm(i);return Zr(this),c}[H](){Qe(this)}}Object.defineProperties(Mt.prototype,{abortReason:{enumerable:!0},signal:{enumerable:!0},error:{enumerable:!0}}),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Mt.prototype,Symbol.toStringTag,{value:"WritableStreamDefaultController",configurable:!0});function Vs(r){return!t(r)||!Object.prototype.hasOwnProperty.call(r,"_controlledWritableStream")?!1:r instanceof Mt}function Qi(r,i,c,h,b,w,T,P){i._controlledWritableStream=r,r._writableStreamController=i,i._queue=void 0,i._queueTotalSize=void 0,Qe(i),i._abortReason=void 0,i._abortController=_d(),i._started=!1,i._strategySizeAlgorithm=P,i._strategyHWM=T,i._writeAlgorithm=h,i._closeAlgorithm=b,i._abortAlgorithm=w;let D=Ys(i);Js(r,D);let I=c(),L=u(I);g(L,()=>(i._started=!0,Xr(i),null),N=>(i._started=!0,zs(r,N),null))}function Ld(r,i,c,h){let b=Object.create(Mt.prototype),w,T,P,D;i.start!==void 0?w=()=>i.start(b):w=()=>{},i.write!==void 0?T=I=>i.write(I,b):T=()=>u(void 0),i.close!==void 0?P=()=>i.close():P=()=>u(void 0),i.abort!==void 0?D=I=>i.abort(I):D=()=>u(void 0),Qi(r,b,w,T,P,D,c,h)}function Zr(r){r._writeAlgorithm=void 0,r._closeAlgorithm=void 0,r._abortAlgorithm=void 0,r._strategySizeAlgorithm=void 0}function Nd(r){Ns(r,Xi,0),Xr(r)}function Md(r,i){try{return r._strategySizeAlgorithm(i)}catch(c){return mr(r,c),1}}function Ki(r){return r._strategyHWM-r._queueTotalSize}function Fd(r,i,c){try{Ns(r,i,c)}catch(b){mr(r,b);return}let h=r._controlledWritableStream;if(!Ae(h)&&h._state==="writable"){let b=Ys(r);Js(h,b)}Xr(r)}function Xr(r){let i=r._controlledWritableStream;if(!r._started||i._inFlightWriteRequest!==void 0)return;if(i._state==="erroring"){Gs(i);return}if(r._queue.length===0)return;let h=Qu(r);h===Xi?Bd(r):Ud(r,h)}function mr(r,i){r._controlledWritableStream._state==="writable"&&ea(r,i)}function Bd(r){let i=r._controlledWritableStream;Pd(i),Ls(r);let c=r._closeAlgorithm();Zr(r),g(c,()=>(vd(i),null),h=>(Cd(i,h),null))}function Ud(r,i){let c=r._controlledWritableStream;Id(c);let h=r._writeAlgorithm(i);g(h,()=>{Ed(c);let b=c._state;if(Ls(r),!Ae(c)&&b==="writable"){let w=Ys(r);Js(c,w)}return Xr(r),null},b=>(c._state==="writable"&&Zr(r),xd(c,b),null))}function Ys(r){return Ki(r)<=0}function ea(r,i){let c=r._controlledWritableStream;Zr(r),Hs(c,i)}function Qr(r){return new TypeError(`WritableStream.prototype.${r} can only be used on a WritableStream`)}function Zs(r){return new TypeError(`WritableStreamDefaultController.prototype.${r} can only be used on a WritableStreamDefaultController`)}function Rt(r){return new TypeError(`WritableStreamDefaultWriter.prototype.${r} can only be used on a WritableStreamDefaultWriter`)}function hr(r){return new TypeError("Cannot "+r+" a stream using a released writer")}function Kr(r){r._closedPromise=p((i,c)=>{r._closedPromise_resolve=i,r._closedPromise_reject=c,r._closedPromiseState="pending"})}function ta(r,i){Kr(r),Xs(r,i)}function qd(r){Kr(r),ra(r)}function Xs(r,i){r._closedPromise_reject!==void 0&&(R(r._closedPromise),r._closedPromise_reject(i),r._closedPromise_resolve=void 0,r._closedPromise_reject=void 0,r._closedPromiseState="rejected")}function jd(r,i){ta(r,i)}function ra(r){r._closedPromise_resolve!==void 0&&(r._closedPromise_resolve(void 0),r._closedPromise_resolve=void 0,r._closedPromise_reject=void 0,r._closedPromiseState="resolved")}function en(r){r._readyPromise=p((i,c)=>{r._readyPromise_resolve=i,r._readyPromise_reject=c}),r._readyPromiseState="pending"}function Qs(r,i){en(r),sa(r,i)}function na(r){en(r),Ks(r)}function sa(r,i){r._readyPromise_reject!==void 0&&(R(r._readyPromise),r._readyPromise_reject(i),r._readyPromise_resolve=void 0,r._readyPromise_reject=void 0,r._readyPromiseState="rejected")}function Wd(r){en(r)}function zd(r,i){Qs(r,i)}function Ks(r){r._readyPromise_resolve!==void 0&&(r._readyPromise_resolve(void 0),r._readyPromise_resolve=void 0,r._readyPromise_reject=void 0,r._readyPromiseState="fulfilled")}function Hd(){if(typeof globalThis<"u")return globalThis;if(typeof self<"u")return self;if(typeof global<"u")return global}let eo=Hd();function Gd(r){if(!(typeof r=="function"||typeof r=="object")||r.name!=="DOMException")return!1;try{return new r,!0}catch{return!1}}function Jd(){let r=eo?.DOMException;return Gd(r)?r:void 0}function Vd(){let r=function(c,h){this.message=c||"",this.name=h||"Error",Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)};return o(r,"DOMException"),r.prototype=Object.create(Error.prototype),Object.defineProperty(r.prototype,"constructor",{value:r,writable:!0,configurable:!0}),r}let Yd=Jd()||Vd();function oa(r,i,c,h,b,w){let T=$t(r),P=zi(i);r._disturbed=!0;let D=!1,I=u(void 0);return p((L,N)=>{let B;if(w!==void 0){if(B=()=>{let O=w.reason!==void 0?w.reason:new Yd("Aborted","AbortError"),M=[];h||M.push(()=>i._state==="writable"?Vr(i,O):u(void 0)),b||M.push(()=>r._state==="readable"?_e(r,O):u(void 0)),re(()=>Promise.all(M.map(q=>q())),!0,O)},w.aborted){B();return}w.addEventListener("abort",B)}function Te(){return p((O,M)=>{function q(ae){ae?O():y(qt(),q,M)}q(!1)})}function qt(){return D?u(!0):y(P._readyPromise,()=>p((O,M)=>{lr(T,{_chunkSteps:q=>{I=y(Zi(P,q),void 0,e),O(!1)},_closeSteps:()=>O(!0),_errorSteps:M})}))}if(qe(r,T._closedPromise,O=>(h?me(!0,O):re(()=>Vr(i,O),!0,O),null)),qe(i,P._closedPromise,O=>(b?me(!0,O):re(()=>_e(r,O),!0,O),null)),ee(r,T._closedPromise,()=>(c?me():re(()=>kd(P)),null)),Ae(i)||i._state==="closed"){let O=new TypeError("the destination writable stream closed before all data could be piped to it");b?me(!0,O):re(()=>_e(r,O),!0,O)}R(Te());function st(){let O=I;return y(I,()=>O!==I?st():void 0)}function qe(O,M,q){O._state==="errored"?q(O._storedError):S(M,q)}function ee(O,M,q){O._state==="closed"?q():_(M,q)}function re(O,M,q){if(D)return;D=!0,i._state==="writable"&&!Ae(i)?_(st(),ae):ae();function ae(){return g(O(),()=>je(M,q),jt=>je(!0,jt)),null}}function me(O,M){D||(D=!0,i._state==="writable"&&!Ae(i)?_(st(),()=>je(O,M)):je(O,M))}function je(O,M){return Yi(P),Le(T),w!==void 0&&w.removeEventListener("abort",B),O?N(M):L(void 0),null}})}class Ue{constructor(){throw new TypeError("Illegal constructor")}get desiredSize(){if(!tn(this))throw nn("desiredSize");return to(this)}close(){if(!tn(this))throw nn("close");if(!Bt(this))throw new TypeError("The stream is not in a state that permits close");Et(this)}enqueue(i=void 0){if(!tn(this))throw nn("enqueue");if(!Bt(this))throw new TypeError("The stream is not in a state that permits enqueue");return Ft(this,i)}error(i=void 0){if(!tn(this))throw nn("error");we(this,i)}[Ve](i){Qe(this);let c=this._cancelAlgorithm(i);return rn(this),c}[cr](i){let c=this._controlledReadableStream;if(this._queue.length>0){let h=Ls(this);this._closeRequested&&this._queue.length===0?(rn(this),br(c)):gr(this),i._chunkSteps(h)}else mi(c,i),gr(this)}[Ts](){}}Object.defineProperties(Ue.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},desiredSize:{enumerable:!0}}),o(Ue.prototype.close,"close"),o(Ue.prototype.enqueue,"enqueue"),o(Ue.prototype.error,"error"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Ue.prototype,Symbol.toStringTag,{value:"ReadableStreamDefaultController",configurable:!0});function tn(r){return!t(r)||!Object.prototype.hasOwnProperty.call(r,"_controlledReadableStream")?!1:r instanceof Ue}function gr(r){if(!ia(r))return;if(r._pulling){r._pullAgain=!0;return}r._pulling=!0;let c=r._pullAlgorithm();g(c,()=>(r._pulling=!1,r._pullAgain&&(r._pullAgain=!1,gr(r)),null),h=>(we(r,h),null))}function ia(r){let i=r._controlledReadableStream;return!Bt(r)||!r._started?!1:!!(rt(i)&&Mr(i)>0||to(r)>0)}function rn(r){r._pullAlgorithm=void 0,r._cancelAlgorithm=void 0,r._strategySizeAlgorithm=void 0}function Et(r){if(!Bt(r))return;let i=r._controlledReadableStream;r._closeRequested=!0,r._queue.length===0&&(rn(r),br(i))}function Ft(r,i){if(!Bt(r))return;let c=r._controlledReadableStream;if(rt(c)&&Mr(c)>0)Is(c,i,!1);else{let h;try{h=r._strategySizeAlgorithm(i)}catch(b){throw we(r,b),b}try{Ns(r,i,h)}catch(b){throw we(r,b),b}}gr(r)}function we(r,i){let c=r._controlledReadableStream;c._state==="readable"&&(Qe(r),rn(r),ua(c,i))}function to(r){let i=r._controlledReadableStream._state;return i==="errored"?null:i==="closed"?0:r._strategyHWM-r._queueTotalSize}function Zd(r){return!ia(r)}function Bt(r){let i=r._controlledReadableStream._state;return!r._closeRequested&&i==="readable"}function aa(r,i,c,h,b,w,T){i._controlledReadableStream=r,i._queue=void 0,i._queueTotalSize=void 0,Qe(i),i._started=!1,i._closeRequested=!1,i._pullAgain=!1,i._pulling=!1,i._strategySizeAlgorithm=T,i._strategyHWM=w,i._pullAlgorithm=h,i._cancelAlgorithm=b,r._readableStreamController=i;let P=c();g(u(P),()=>(i._started=!0,gr(i),null),D=>(we(i,D),null))}function Xd(r,i,c,h){let b=Object.create(Ue.prototype),w,T,P;i.start!==void 0?w=()=>i.start(b):w=()=>{},i.pull!==void 0?T=()=>i.pull(b):T=()=>u(void 0),i.cancel!==void 0?P=D=>i.cancel(D):P=()=>u(void 0),aa(r,b,w,T,P,c,h)}function nn(r){return new TypeError(`ReadableStreamDefaultController.prototype.${r} can only be used on a ReadableStreamDefaultController`)}function Qd(r,i){return St(r._readableStreamController)?ef(r):Kd(r)}function Kd(r,i){let c=$t(r),h=!1,b=!1,w=!1,T=!1,P,D,I,L,N,B=p(ee=>{N=ee});function Te(){return h?(b=!0,u(void 0)):(h=!0,lr(c,{_chunkSteps:re=>{x(()=>{b=!1;let me=re,je=re;w||Ft(I._readableStreamController,me),T||Ft(L._readableStreamController,je),h=!1,b&&Te()})},_closeSteps:()=>{h=!1,w||Et(I._readableStreamController),T||Et(L._readableStreamController),(!w||!T)&&N(void 0)},_errorSteps:()=>{h=!1}}),u(void 0))}function qt(ee){if(w=!0,P=ee,T){let re=ur([P,D]),me=_e(r,re);N(me)}return B}function st(ee){if(T=!0,D=ee,w){let re=ur([P,D]),me=_e(r,re);N(me)}return B}function qe(){}return I=yr(qe,Te,qt),L=yr(qe,Te,st),S(c._closedPromise,ee=>(we(I._readableStreamController,ee),we(L._readableStreamController,ee),(!w||!T)&&N(void 0),null)),[I,L]}function ef(r){let i=$t(r),c=!1,h=!1,b=!1,w=!1,T=!1,P,D,I,L,N,B=p(O=>{N=O});function Te(O){S(O._closedPromise,M=>(O!==i||(pe(I._readableStreamController,M),pe(L._readableStreamController,M),(!w||!T)&&N(void 0)),null))}function qt(){_t(i)&&(Le(i),i=$t(r),Te(i)),lr(i,{_chunkSteps:M=>{x(()=>{h=!1,b=!1;let q=M,ae=M;if(!w&&!T)try{ae=xi(M)}catch(jt){pe(I._readableStreamController,jt),pe(L._readableStreamController,jt),N(_e(r,jt));return}w||jr(I._readableStreamController,q),T||jr(L._readableStreamController,ae),c=!1,h?qe():b&&ee()})},_closeSteps:()=>{c=!1,w||dr(I._readableStreamController),T||dr(L._readableStreamController),I._readableStreamController._pendingPullIntos.length>0&&Wr(I._readableStreamController,0),L._readableStreamController._pendingPullIntos.length>0&&Wr(L._readableStreamController,0),(!w||!T)&&N(void 0)},_errorSteps:()=>{c=!1}})}function st(O,M){Ze(i)&&(Le(i),i=Fi(r),Te(i));let q=M?L:I,ae=M?I:L;qi(i,O,1,{_chunkSteps:Wt=>{x(()=>{h=!1,b=!1;let zt=M?T:w;if(M?w:T)zt||zr(q._readableStreamController,Wt);else{let Ra;try{Ra=xi(Wt)}catch(io){pe(q._readableStreamController,io),pe(ae._readableStreamController,io),N(_e(r,io));return}zt||zr(q._readableStreamController,Wt),jr(ae._readableStreamController,Ra)}c=!1,h?qe():b&&ee()})},_closeSteps:Wt=>{c=!1;let zt=M?T:w,fn=M?w:T;zt||dr(q._readableStreamController),fn||dr(ae._readableStreamController),Wt!==void 0&&(zt||zr(q._readableStreamController,Wt),!fn&&ae._readableStreamController._pendingPullIntos.length>0&&Wr(ae._readableStreamController,0)),(!zt||!fn)&&N(void 0)},_errorSteps:()=>{c=!1}})}function qe(){if(c)return h=!0,u(void 0);c=!0;let O=qs(I._readableStreamController);return O===null?qt():st(O._view,!1),u(void 0)}function ee(){if(c)return b=!0,u(void 0);c=!0;let O=qs(L._readableStreamController);return O===null?qt():st(O._view,!0),u(void 0)}function re(O){if(w=!0,P=O,T){let M=ur([P,D]),q=_e(r,M);N(q)}return B}function me(O){if(T=!0,D=O,w){let M=ur([P,D]),q=_e(r,M);N(q)}return B}function je(){}return I=la(je,qe,re),L=la(je,ee,me),Te(i),[I,L]}function tf(r){return t(r)&&typeof r.getReader<"u"}function rf(r){return tf(r)?sf(r.getReader()):nf(r)}function nf(r){let i,c=Ei(r,"async"),h=e;function b(){let T;try{T=Vu(c)}catch(D){return f(D)}let P=u(T);return E(P,D=>{if(!t(D))throw new TypeError("The promise returned by the iterator.next() method must fulfill with an object");if(Yu(D))Et(i._readableStreamController);else{let L=Zu(D);Ft(i._readableStreamController,L)}})}function w(T){let P=c.iterator,D;try{D=Br(P,"return")}catch(N){return f(N)}if(D===void 0)return u(void 0);let I;try{I=A(D,P,[T])}catch(N){return f(N)}let L=u(I);return E(L,N=>{if(!t(N))throw new TypeError("The promise returned by the iterator.return() method must fulfill with an object")})}return i=yr(h,b,w,0),i}function sf(r){let i,c=e;function h(){let w;try{w=r.read()}catch(T){return f(T)}return E(w,T=>{if(!t(T))throw new TypeError("The promise returned by the reader.read() method must fulfill with an object");if(T.done)Et(i._readableStreamController);else{let P=T.value;Ft(i._readableStreamController,P)}})}function b(w){try{return u(r.cancel(w))}catch(T){return f(T)}}return i=yr(c,h,b,0),i}function of(r,i){Ce(r,i);let c=r,h=c?.autoAllocateChunkSize,b=c?.cancel,w=c?.pull,T=c?.start,P=c?.type;return{autoAllocateChunkSize:h===void 0?void 0:As(h,`${i} has member 'autoAllocateChunkSize' that`),cancel:b===void 0?void 0:af(b,c,`${i} has member 'cancel' that`),pull:w===void 0?void 0:cf(w,c,`${i} has member 'pull' that`),start:T===void 0?void 0:lf(T,c,`${i} has member 'start' that`),type:P===void 0?void 0:uf(P,`${i} has member 'type' that`)}}function af(r,i,c){return fe(r,c),h=>C(r,i,[h])}function cf(r,i,c){return fe(r,c),h=>C(r,i,[h])}function lf(r,i,c){return fe(r,c),h=>A(r,i,[h])}function uf(r,i){if(r=`${r}`,r!=="bytes")throw new TypeError(`${i} '${r}' is not a valid enumeration value for ReadableStreamType`);return r}function df(r,i){return Ce(r,i),{preventCancel:!!r?.preventCancel}}function ca(r,i){Ce(r,i);let c=r?.preventAbort,h=r?.preventCancel,b=r?.preventClose,w=r?.signal;return w!==void 0&&ff(w,`${i} has member 'signal' that`),{preventAbort:!!c,preventCancel:!!h,preventClose:!!b,signal:w}}function ff(r,i){if(!Sd(r))throw new TypeError(`${i} is not an AbortSignal.`)}function pf(r,i){Ce(r,i);let c=r?.readable;vs(c,"readable","ReadableWritablePair"),Ps(c,`${i} has member 'readable' that`);let h=r?.writable;return vs(h,"writable","ReadableWritablePair"),Wi(h,`${i} has member 'writable' that`),{readable:c,writable:h}}class Q{constructor(i={},c={}){i===void 0?i=null:fi(i,"First parameter");let h=Jr(c,"Second parameter"),b=of(i,"First parameter");if(ro(this),b.type==="bytes"){if(h.size!==void 0)throw new RangeError("The strategy for a byte stream cannot have a size function");let w=pr(h,0);id(this,b,w)}else{let w=Gr(h),T=pr(h,1);Xd(this,b,T,w)}}get locked(){if(!tt(this))throw xt("locked");return rt(this)}cancel(i=void 0){return tt(this)?rt(this)?f(new TypeError("Cannot cancel a stream that already has a reader")):_e(this,i):f(xt("cancel"))}getReader(i=void 0){if(!tt(this))throw xt("getReader");return cd(i,"First parameter").mode===void 0?$t(this):Fi(this)}pipeThrough(i,c={}){if(!tt(this))throw xt("pipeThrough");Ne(i,1,"pipeThrough");let h=pf(i,"First parameter"),b=ca(c,"Second parameter");if(rt(this))throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream");if(Nt(h.writable))throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream");let w=oa(this,h.writable,b.preventClose,b.preventAbort,b.preventCancel,b.signal);return R(w),h.readable}pipeTo(i,c={}){if(!tt(this))return f(xt("pipeTo"));if(i===void 0)return f("Parameter 1 is required in 'pipeTo'.");if(!Lt(i))return f(new TypeError("ReadableStream.prototype.pipeTo's first argument must be a WritableStream"));let h;try{h=ca(c,"Second parameter")}catch(b){return f(b)}return rt(this)?f(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream")):Nt(i)?f(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream")):oa(this,i,h.preventClose,h.preventAbort,h.preventCancel,h.signal)}tee(){if(!tt(this))throw xt("tee");let i=Qd(this);return ur(i)}values(i=void 0){if(!tt(this))throw xt("values");let c=df(i,"First parameter");return Gu(this,c.preventCancel)}[Ds](i){return this.values(i)}static from(i){return rf(i)}}Object.defineProperties(Q,{from:{enumerable:!0}}),Object.defineProperties(Q.prototype,{cancel:{enumerable:!0},getReader:{enumerable:!0},pipeThrough:{enumerable:!0},pipeTo:{enumerable:!0},tee:{enumerable:!0},values:{enumerable:!0},locked:{enumerable:!0}}),o(Q.from,"from"),o(Q.prototype.cancel,"cancel"),o(Q.prototype.getReader,"getReader"),o(Q.prototype.pipeThrough,"pipeThrough"),o(Q.prototype.pipeTo,"pipeTo"),o(Q.prototype.tee,"tee"),o(Q.prototype.values,"values"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Q.prototype,Symbol.toStringTag,{value:"ReadableStream",configurable:!0}),Object.defineProperty(Q.prototype,Ds,{value:Q.prototype.values,writable:!0,configurable:!0});function yr(r,i,c,h=1,b=()=>1){let w=Object.create(Q.prototype);ro(w);let T=Object.create(Ue.prototype);return aa(w,T,r,i,c,h,b),w}function la(r,i,c){let h=Object.create(Q.prototype);ro(h);let b=Object.create(Fe.prototype);return Mi(h,b,r,i,c,0,void 0),h}function ro(r){r._state="readable",r._reader=void 0,r._storedError=void 0,r._disturbed=!1}function tt(r){return!t(r)||!Object.prototype.hasOwnProperty.call(r,"_readableStreamController")?!1:r instanceof Q}function rt(r){return r._reader!==void 0}function _e(r,i){if(r._disturbed=!0,r._state==="closed")return u(void 0);if(r._state==="errored")return f(r._storedError);br(r);let c=r._reader;if(c!==void 0&&_t(c)){let b=c._readIntoRequests;c._readIntoRequests=new k,b.forEach(w=>{w._closeSteps(void 0)})}let h=r._readableStreamController[Ve](i);return E(h,e)}function br(r){r._state="closed";let i=r._reader;if(i!==void 0&&(ui(i),Ze(i))){let c=i._readRequests;i._readRequests=new k,c.forEach(h=>{h._closeSteps()})}}function ua(r,i){r._state="errored",r._storedError=i;let c=r._reader;c!==void 0&&(xs(c,i),Ze(c)?gi(c,i):ji(c,i))}function xt(r){return new TypeError(`ReadableStream.prototype.${r} can only be used on a ReadableStream`)}function da(r,i){Ce(r,i);let c=r?.highWaterMark;return vs(c,"highWaterMark","QueuingStrategyInit"),{highWaterMark:Cs(c)}}let fa=r=>r.byteLength;o(fa,"size");class sn{constructor(i){Ne(i,1,"ByteLengthQueuingStrategy"),i=da(i,"First parameter"),this._byteLengthQueuingStrategyHighWaterMark=i.highWaterMark}get highWaterMark(){if(!ma(this))throw pa("highWaterMark");return this._byteLengthQueuingStrategyHighWaterMark}get size(){if(!ma(this))throw pa("size");return fa}}Object.defineProperties(sn.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(sn.prototype,Symbol.toStringTag,{value:"ByteLengthQueuingStrategy",configurable:!0});function pa(r){return new TypeError(`ByteLengthQueuingStrategy.prototype.${r} can only be used on a ByteLengthQueuingStrategy`)}function ma(r){return!t(r)||!Object.prototype.hasOwnProperty.call(r,"_byteLengthQueuingStrategyHighWaterMark")?!1:r instanceof sn}let ha=()=>1;o(ha,"size");class on{constructor(i){Ne(i,1,"CountQueuingStrategy"),i=da(i,"First parameter"),this._countQueuingStrategyHighWaterMark=i.highWaterMark}get highWaterMark(){if(!ya(this))throw ga("highWaterMark");return this._countQueuingStrategyHighWaterMark}get size(){if(!ya(this))throw ga("size");return ha}}Object.defineProperties(on.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(on.prototype,Symbol.toStringTag,{value:"CountQueuingStrategy",configurable:!0});function ga(r){return new TypeError(`CountQueuingStrategy.prototype.${r} can only be used on a CountQueuingStrategy`)}function ya(r){return!t(r)||!Object.prototype.hasOwnProperty.call(r,"_countQueuingStrategyHighWaterMark")?!1:r instanceof on}function mf(r,i){Ce(r,i);let c=r?.cancel,h=r?.flush,b=r?.readableType,w=r?.start,T=r?.transform,P=r?.writableType;return{cancel:c===void 0?void 0:bf(c,r,`${i} has member 'cancel' that`),flush:h===void 0?void 0:hf(h,r,`${i} has member 'flush' that`),readableType:b,start:w===void 0?void 0:gf(w,r,`${i} has member 'start' that`),transform:T===void 0?void 0:yf(T,r,`${i} has member 'transform' that`),writableType:P}}function hf(r,i,c){return fe(r,c),h=>C(r,i,[h])}function gf(r,i,c){return fe(r,c),h=>A(r,i,[h])}function yf(r,i,c){return fe(r,c),(h,b)=>C(r,i,[h,b])}function bf(r,i,c){return fe(r,c),h=>C(r,i,[h])}class an{constructor(i={},c={},h={}){i===void 0&&(i=null);let b=Jr(c,"Second parameter"),w=Jr(h,"Third parameter"),T=mf(i,"First parameter");if(T.readableType!==void 0)throw new RangeError("Invalid readableType specified");if(T.writableType!==void 0)throw new RangeError("Invalid writableType specified");let P=pr(w,0),D=Gr(w),I=pr(b,1),L=Gr(b),N,B=p(Te=>{N=Te});Sf(this,B,I,L,P,D),_f(this,T),T.start!==void 0?N(T.start(this._transformStreamController)):N(void 0)}get readable(){if(!ba(this))throw Ta("readable");return this._readable}get writable(){if(!ba(this))throw Ta("writable");return this._writable}}Object.defineProperties(an.prototype,{readable:{enumerable:!0},writable:{enumerable:!0}}),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(an.prototype,Symbol.toStringTag,{value:"TransformStream",configurable:!0});function Sf(r,i,c,h,b,w){function T(){return i}function P(B){return Ef(r,B)}function D(B){return xf(r,B)}function I(){return vf(r)}r._writable=Td(T,P,I,D,c,h);function L(){return Cf(r)}function N(B){return Af(r,B)}r._readable=yr(T,L,N,b,w),r._backpressure=void 0,r._backpressureChangePromise=void 0,r._backpressureChangePromise_resolve=void 0,cn(r,!0),r._transformStreamController=void 0}function ba(r){return!t(r)||!Object.prototype.hasOwnProperty.call(r,"_transformStreamController")?!1:r instanceof an}function Sa(r,i){we(r._readable._readableStreamController,i),no(r,i)}function no(r,i){un(r._transformStreamController),mr(r._writable._writableStreamController,i),so(r)}function so(r){r._backpressure&&cn(r,!1)}function cn(r,i){r._backpressureChangePromise!==void 0&&r._backpressureChangePromise_resolve(),r._backpressureChangePromise=p(c=>{r._backpressureChangePromise_resolve=c}),r._backpressure=i}class nt{constructor(){throw new TypeError("Illegal constructor")}get desiredSize(){if(!ln(this))throw dn("desiredSize");let i=this._controlledTransformStream._readable._readableStreamController;return to(i)}enqueue(i=void 0){if(!ln(this))throw dn("enqueue");wa(this,i)}error(i=void 0){if(!ln(this))throw dn("error");Tf(this,i)}terminate(){if(!ln(this))throw dn("terminate");Rf(this)}}Object.defineProperties(nt.prototype,{enqueue:{enumerable:!0},error:{enumerable:!0},terminate:{enumerable:!0},desiredSize:{enumerable:!0}}),o(nt.prototype.enqueue,"enqueue"),o(nt.prototype.error,"error"),o(nt.prototype.terminate,"terminate"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(nt.prototype,Symbol.toStringTag,{value:"TransformStreamDefaultController",configurable:!0});function ln(r){return!t(r)||!Object.prototype.hasOwnProperty.call(r,"_controlledTransformStream")?!1:r instanceof nt}function wf(r,i,c,h,b){i._controlledTransformStream=r,r._transformStreamController=i,i._transformAlgorithm=c,i._flushAlgorithm=h,i._cancelAlgorithm=b,i._finishPromise=void 0,i._finishPromise_resolve=void 0,i._finishPromise_reject=void 0}function _f(r,i){let c=Object.create(nt.prototype),h,b,w;i.transform!==void 0?h=T=>i.transform(T,c):h=T=>{try{return wa(c,T),u(void 0)}catch(P){return f(P)}},i.flush!==void 0?b=()=>i.flush(c):b=()=>u(void 0),i.cancel!==void 0?w=T=>i.cancel(T):w=()=>u(void 0),wf(r,c,h,b,w)}function un(r){r._transformAlgorithm=void 0,r._flushAlgorithm=void 0,r._cancelAlgorithm=void 0}function wa(r,i){let c=r._controlledTransformStream,h=c._readable._readableStreamController;if(!Bt(h))throw new TypeError("Readable side is not in a state that permits enqueue");try{Ft(h,i)}catch(w){throw no(c,w),c._readable._storedError}Zd(h)!==c._backpressure&&cn(c,!0)}function Tf(r,i){Sa(r._controlledTransformStream,i)}function _a(r,i){let c=r._transformAlgorithm(i);return E(c,void 0,h=>{throw Sa(r._controlledTransformStream,h),h})}function Rf(r){let i=r._controlledTransformStream,c=i._readable._readableStreamController;Et(c);let h=new TypeError("TransformStream terminated");no(i,h)}function Ef(r,i){let c=r._transformStreamController;if(r._backpressure){let h=r._backpressureChangePromise;return E(h,()=>{let b=r._writable;if(b._state==="erroring")throw b._storedError;return _a(c,i)})}return _a(c,i)}function xf(r,i){let c=r._transformStreamController;if(c._finishPromise!==void 0)return c._finishPromise;let h=r._readable;c._finishPromise=p((w,T)=>{c._finishPromise_resolve=w,c._finishPromise_reject=T});let b=c._cancelAlgorithm(i);return un(c),g(b,()=>(h._state==="errored"?Ut(c,h._storedError):(we(h._readableStreamController,i),oo(c)),null),w=>(we(h._readableStreamController,w),Ut(c,w),null)),c._finishPromise}function vf(r){let i=r._transformStreamController;if(i._finishPromise!==void 0)return i._finishPromise;let c=r._readable;i._finishPromise=p((b,w)=>{i._finishPromise_resolve=b,i._finishPromise_reject=w});let h=i._flushAlgorithm();return un(i),g(h,()=>(c._state==="errored"?Ut(i,c._storedError):(Et(c._readableStreamController),oo(i)),null),b=>(we(c._readableStreamController,b),Ut(i,b),null)),i._finishPromise}function Cf(r){return cn(r,!1),r._backpressureChangePromise}function Af(r,i){let c=r._transformStreamController;if(c._finishPromise!==void 0)return c._finishPromise;let h=r._writable;c._finishPromise=p((w,T)=>{c._finishPromise_resolve=w,c._finishPromise_reject=T});let b=c._cancelAlgorithm(i);return un(c),g(b,()=>(h._state==="errored"?Ut(c,h._storedError):(mr(h._writableStreamController,i),so(r),oo(c)),null),w=>(mr(h._writableStreamController,w),so(r),Ut(c,w),null)),c._finishPromise}function dn(r){return new TypeError(`TransformStreamDefaultController.prototype.${r} can only be used on a TransformStreamDefaultController`)}function oo(r){r._finishPromise_resolve!==void 0&&(r._finishPromise_resolve(),r._finishPromise_resolve=void 0,r._finishPromise_reject=void 0)}function Ut(r,i){r._finishPromise_reject!==void 0&&(R(r._finishPromise),r._finishPromise_reject(i),r._finishPromise_resolve=void 0,r._finishPromise_reject=void 0)}function Ta(r){return new TypeError(`TransformStream.prototype.${r} can only be used on a TransformStream`)}n.ByteLengthQueuingStrategy=sn,n.CountQueuingStrategy=on,n.ReadableByteStreamController=Fe,n.ReadableStream=Q,n.ReadableStreamBYOBReader=Ke,n.ReadableStreamBYOBRequest=bt,n.ReadableStreamDefaultController=Ue,n.ReadableStreamDefaultReader=Ye,n.TransformStream=an,n.TransformStreamDefaultController=nt,n.WritableStream=et,n.WritableStreamDefaultController=Mt,n.WritableStreamDefaultWriter=Be}))});var wl=X(()=>{if(!globalThis.ReadableStream)try{let n=Z("node:process"),{emitWarning:e}=n;try{n.emitWarning=()=>{},Object.assign(globalThis,Z("node:stream/web")),n.emitWarning=e}catch(t){throw n.emitWarning=e,t}}catch{Object.assign(globalThis,Sl())}try{let{Blob:n}=Z("buffer");n&&!n.prototype.stream&&(n.prototype.stream=function(t){let s=0,o=this;return new ReadableStream({type:"bytes",async pull(a){let d=await o.slice(s,Math.min(o.size,s+65536)).arrayBuffer();s+=d.byteLength,a.enqueue(new Uint8Array(d)),s===o.size&&a.close()}})})}catch{}});async function*Lo(n,e=!0){for(let t of n)if("stream"in t)yield*t.stream();else if(ArrayBuffer.isView(t))if(e){let s=t.byteOffset,o=t.byteOffset+t.byteLength;for(;s!==o;){let a=Math.min(o-s,_l),l=t.buffer.slice(s,s+a);s+=l.byteLength,yield new Uint8Array(l)}}else yield t;else{let s=0,o=t;for(;s!==o.size;){let l=await o.slice(s,Math.min(o.size,s+_l)).arrayBuffer();s+=l.byteLength,yield new Uint8Array(l)}}}var hw,_l,Tl,jm,Ee,Cr=G(()=>{hw=Ht(wl(),1);_l=65536;Tl=class No{#e=[];#t="";#r=0;#n="transparent";constructor(e=[],t={}){if(typeof e!="object"||e===null)throw new TypeError("Failed to construct 'Blob': The provided value cannot be converted to a sequence.");if(typeof e[Symbol.iterator]!="function")throw new TypeError("Failed to construct 'Blob': The object must have a callable @@iterator property.");if(typeof t!="object"&&typeof t!="function")throw new TypeError("Failed to construct 'Blob': parameter 2 cannot convert to dictionary.");t===null&&(t={});let s=new TextEncoder;for(let a of e){let l;ArrayBuffer.isView(a)?l=new Uint8Array(a.buffer.slice(a.byteOffset,a.byteOffset+a.byteLength)):a instanceof ArrayBuffer?l=new Uint8Array(a.slice(0)):a instanceof No?l=a:l=s.encode(`${a}`),this.#r+=ArrayBuffer.isView(l)?l.byteLength:l.size,this.#e.push(l)}this.#n=`${t.endings===void 0?"transparent":t.endings}`;let o=t.type===void 0?"":String(t.type);this.#t=/^[\x20-\x7E]*$/.test(o)?o:""}get size(){return this.#r}get type(){return this.#t}async text(){let e=new TextDecoder,t="";for await(let s of Lo(this.#e,!1))t+=e.decode(s,{stream:!0});return t+=e.decode(),t}async arrayBuffer(){let e=new Uint8Array(this.size),t=0;for await(let s of Lo(this.#e,!1))e.set(s,t),t+=s.length;return e.buffer}stream(){let e=Lo(this.#e,!0);return new globalThis.ReadableStream({type:"bytes",async pull(t){let s=await e.next();s.done?t.close():t.enqueue(s.value)},async cancel(){await e.return()}})}slice(e=0,t=this.size,s=""){let{size:o}=this,a=e<0?Math.max(o+e,0):Math.min(e,o),l=t<0?Math.max(o+t,0):Math.min(t,o),d=Math.max(l-a,0),p=this.#e,u=[],f=0;for(let g of p){if(f>=d)break;let _=ArrayBuffer.isView(g)?g.byteLength:g.size;if(a&&_<=a)a-=_,l-=_;else{let S;ArrayBuffer.isView(g)?(S=g.subarray(a,Math.min(_,l)),f+=S.byteLength):(S=g.slice(a,Math.min(_,l)),f+=S.size),l-=_,u.push(S),a=0}}let y=new No([],{type:String(s).toLowerCase()});return y.#r=d,y.#e=u,y}get[Symbol.toStringTag](){return"Blob"}static[Symbol.hasInstance](e){return e&&typeof e=="object"&&typeof e.constructor=="function"&&(typeof e.stream=="function"||typeof e.arrayBuffer=="function")&&/^(Blob|File)$/.test(e[Symbol.toStringTag])}};Object.defineProperties(Tl.prototype,{size:{enumerable:!0},type:{enumerable:!0},slice:{enumerable:!0}});jm=Tl,Ee=jm});var Wm,zm,ft,Mo=G(()=>{Cr();Wm=class extends Ee{#e=0;#t="";constructor(e,t,s={}){if(arguments.length<2)throw new TypeError(`Failed to construct 'File': 2 arguments required, but only ${arguments.length} present.`);super(e,s),s===null&&(s={});let o=s.lastModified===void 0?Date.now():Number(s.lastModified);Number.isNaN(o)||(this.#e=o),this.#t=String(t)}get name(){return this.#t}get lastModified(){return this.#e}get[Symbol.toStringTag](){return"File"}static[Symbol.hasInstance](e){return!!e&&e instanceof Ee&&/^(File)$/.test(e[Symbol.toStringTag])}},zm=Wm,ft=zm});function xl(n,e=Ee){var t=`${Rl()}${Rl()}`.replace(/\./g,"").slice(-28).padStart(32,"-"),s=[],o=`--${t}\r
15
- Content-Disposition: form-data; name="`;return n.forEach((a,l)=>typeof a=="string"?s.push(o+Fo(l)+`"\r
11
+ `),S=_.shift();if(!S)return r.destroy(),t(new Error("No header received from proxy CONNECT response"));let E=S.split(" "),R=+E[1],x=E.slice(2).join(" "),A={};for(let C of _){if(!C)continue;let v=C.indexOf(":");if(v===-1)return r.destroy(),t(new Error(`Invalid header from proxy CONNECT response: "${C}"`));let k=C.slice(0,v).toLowerCase(),$=C.slice(v+1).trimStart(),H=A[k];typeof H=="string"?A[k]=[H,$]:Array.isArray(H)?H.push($):A[k]=$}Vn("got proxy server response: %o %o",S,A),l(),e({connect:{statusCode:R,statusText:x,headers:A},buffered:y})}r.on("error",p),r.on("end",d),a()})}er.parseProxyResponse=$m});var hl=X(ye=>{"use strict";var Dm=ye&&ye.__createBinding||(Object.create?(function(r,e,t,o){o===void 0&&(o=t);var s=Object.getOwnPropertyDescriptor(e,t);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,o,s)}):(function(r,e,t,o){o===void 0&&(o=t),r[o]=e[t]})),Lm=ye&&ye.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),pl=ye&&ye.__importStar||function(r){if(r&&r.__esModule)return r;var e={};if(r!=null)for(var t in r)t!=="default"&&Object.prototype.hasOwnProperty.call(r,t)&&Dm(e,r,t);return Lm(e,r),e},ml=ye&&ye.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(ye,"__esModule",{value:!0});ye.HttpsProxyAgent=void 0;var Yn=pl(Z("net")),ul=pl(Z("tls")),Nm=ml(Z("assert")),Mm=ml($s()),Fm=cl(),Bm=Z("url"),Um=ll(),vr=(0,Mm.default)("https-proxy-agent"),dl=r=>r.servername===void 0&&r.host&&!Yn.isIP(r.host)?{...r,servername:r.host}:r,Zn=class extends Fm.Agent{constructor(e,t){super(t),this.options={path:void 0},this.proxy=typeof e=="string"?new Bm.URL(e):e,this.proxyHeaders=t?.headers??{},vr("Creating new HttpsProxyAgent instance: %o",this.proxy.href);let o=(this.proxy.hostname||this.proxy.host).replace(/^\[|\]$/g,""),s=this.proxy.port?parseInt(this.proxy.port,10):this.proxy.protocol==="https:"?443:80;this.connectOpts={ALPNProtocols:["http/1.1"],...t?fl(t,"headers"):null,host:o,port:s}}async connect(e,t){let{proxy:o}=this;if(!t.host)throw new TypeError('No "host" provided');let s;o.protocol==="https:"?(vr("Creating `tls.Socket`: %o",this.connectOpts),s=ul.connect(dl(this.connectOpts))):(vr("Creating `net.Socket`: %o",this.connectOpts),s=Yn.connect(this.connectOpts));let a=typeof this.proxyHeaders=="function"?this.proxyHeaders():{...this.proxyHeaders},l=Yn.isIPv6(t.host)?`[${t.host}]`:t.host,d=`CONNECT ${l}:${t.port} HTTP/1.1\r
12
+ `;if(o.username||o.password){let g=`${decodeURIComponent(o.username)}:${decodeURIComponent(o.password)}`;a["Proxy-Authorization"]=`Basic ${Buffer.from(g).toString("base64")}`}a.Host=`${l}:${t.port}`,a["Proxy-Connection"]||(a["Proxy-Connection"]=this.keepAlive?"Keep-Alive":"close");for(let g of Object.keys(a))d+=`${g}: ${a[g]}\r
13
+ `;let p=(0,Um.parseProxyResponse)(s);s.write(`${d}\r
14
+ `);let{connect:u,buffered:f}=await p;if(e.emit("proxyConnect",u),this.emit("proxyConnect",u,e),u.statusCode===200)return e.once("socket",qm),t.secureEndpoint?(vr("Upgrading socket connection to TLS"),ul.connect({...fl(dl(t),"host","path","port"),socket:s})):s;s.destroy();let y=new Yn.Socket({writable:!1});return y.readable=!0,e.once("socket",g=>{vr("Replaying proxy buffer for failed request"),(0,Nm.default)(g.listenerCount("data")>0),g.push(f),g.push(null)}),y}};Zn.protocols=["http","https"];ye.HttpsProxyAgent=Zn;function qm(r){r.resume()}function fl(r,...e){let t={},o;for(o in r)e.includes(o)||(t[o]=r[o]);return t}});function jm(r){if(!/^data:/i.test(r))throw new TypeError('`uri` does not appear to be a Data URI (must begin with "data:")');r=r.replace(/\r?\n/g,"");let e=r.indexOf(",");if(e===-1||e<=4)throw new TypeError("malformed data: URI");let t=r.substring(5,e).split(";"),o="",s=!1,a=t[0]||"text/plain",l=a;for(let f=1;f<t.length;f++)t[f]==="base64"?s=!0:t[f]&&(l+=`;${t[f]}`,t[f].indexOf("charset=")===0&&(o=t[f].substring(8)));!t[0]&&!o.length&&(l+=";charset=US-ASCII",o="US-ASCII");let d=s?"base64":"ascii",p=unescape(r.substring(e+1)),u=Buffer.from(p,d);return u.type=a,u.typeFull=l,u.charset=o,u}var gl,yl=G(()=>{gl=jm});var Sl=X((Xn,bl)=>{(function(r,e){typeof Xn=="object"&&typeof bl<"u"?e(Xn):typeof define=="function"&&define.amd?define(["exports"],e):(r=typeof globalThis<"u"?globalThis:r||self,e(r.WebStreamsPolyfill={}))})(Xn,(function(r){"use strict";function e(){}function t(n){return typeof n=="object"&&n!==null||typeof n=="function"}let o=e;function s(n,i){try{Object.defineProperty(n,"name",{value:i,configurable:!0})}catch{}}let a=Promise,l=Promise.prototype.then,d=Promise.reject.bind(a);function p(n){return new a(n)}function u(n){return p(i=>i(n))}function f(n){return d(n)}function y(n,i,c){return l.call(n,i,c)}function g(n,i,c){y(y(n,i,c),void 0,o)}function _(n,i){g(n,i)}function S(n,i){g(n,void 0,i)}function E(n,i,c){return y(n,i,c)}function R(n){y(n,void 0,o)}let x=n=>{if(typeof queueMicrotask=="function")x=queueMicrotask;else{let i=u(void 0);x=c=>y(i,c)}return x(n)};function A(n,i,c){if(typeof n!="function")throw new TypeError("Argument is not a function");return Function.prototype.apply.call(n,i,c)}function C(n,i,c){try{return u(A(n,i,c))}catch(h){return f(h)}}let v=16384;class k{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(i){let c=this._back,h=c;c._elements.length===v-1&&(h={_elements:[],_next:void 0}),c._elements.push(i),h!==c&&(this._back=h,c._next=h),++this._size}shift(){let i=this._front,c=i,h=this._cursor,b=h+1,w=i._elements,T=w[h];return b===v&&(c=i._next,b=0),--this._size,this._cursor=b,i!==c&&(this._front=c),w[h]=void 0,T}forEach(i){let c=this._cursor,h=this._front,b=h._elements;for(;(c!==b.length||h._next!==void 0)&&!(c===b.length&&(h=h._next,b=h._elements,c=0,b.length===0));)i(b[c]),++c}peek(){let i=this._front,c=this._cursor;return i._elements[c]}}let $=Symbol("[[AbortSteps]]"),H=Symbol("[[ErrorSteps]]"),Ve=Symbol("[[CancelSteps]]"),cr=Symbol("[[PullSteps]]"),Ro=Symbol("[[ReleaseSteps]]");function ci(n,i){n._ownerReadableStream=i,i._reader=n,i._state==="readable"?xo(n):i._state==="closed"?Fu(n):li(n,i._storedError)}function Eo(n,i){let c=n._ownerReadableStream;return _e(c,i)}function Le(n){let i=n._ownerReadableStream;i._state==="readable"?vo(n,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")):Bu(n,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")),i._readableStreamController[Ro](),i._reader=void 0,n._ownerReadableStream=void 0}function Nr(n){return new TypeError("Cannot "+n+" a stream using a released reader")}function xo(n){n._closedPromise=p((i,c)=>{n._closedPromise_resolve=i,n._closedPromise_reject=c})}function li(n,i){xo(n),vo(n,i)}function Fu(n){xo(n),ui(n)}function vo(n,i){n._closedPromise_reject!==void 0&&(R(n._closedPromise),n._closedPromise_reject(i),n._closedPromise_resolve=void 0,n._closedPromise_reject=void 0)}function Bu(n,i){li(n,i)}function ui(n){n._closedPromise_resolve!==void 0&&(n._closedPromise_resolve(void 0),n._closedPromise_resolve=void 0,n._closedPromise_reject=void 0)}let di=Number.isFinite||function(n){return typeof n=="number"&&isFinite(n)},Uu=Math.trunc||function(n){return n<0?Math.ceil(n):Math.floor(n)};function qu(n){return typeof n=="object"||typeof n=="function"}function Ce(n,i){if(n!==void 0&&!qu(n))throw new TypeError(`${i} is not an object.`)}function fe(n,i){if(typeof n!="function")throw new TypeError(`${i} is not a function.`)}function ju(n){return typeof n=="object"&&n!==null||typeof n=="function"}function fi(n,i){if(!ju(n))throw new TypeError(`${i} is not an object.`)}function Ne(n,i,c){if(n===void 0)throw new TypeError(`Parameter ${i} is required in '${c}'.`)}function Co(n,i,c){if(n===void 0)throw new TypeError(`${i} is required in '${c}'.`)}function Ao(n){return Number(n)}function pi(n){return n===0?0:n}function Wu(n){return pi(Uu(n))}function Po(n,i){let h=Number.MAX_SAFE_INTEGER,b=Number(n);if(b=pi(b),!di(b))throw new TypeError(`${i} is not a finite number`);if(b=Wu(b),b<0||b>h)throw new TypeError(`${i} is outside the accepted range of 0 to ${h}, inclusive`);return!di(b)||b===0?0:b}function Io(n,i){if(!tt(n))throw new TypeError(`${i} is not a ReadableStream.`)}function $t(n){return new Ye(n)}function mi(n,i){n._reader._readRequests.push(i)}function Oo(n,i,c){let b=n._reader._readRequests.shift();c?b._closeSteps():b._chunkSteps(i)}function Mr(n){return n._reader._readRequests.length}function hi(n){let i=n._reader;return!(i===void 0||!Ze(i))}class Ye{constructor(i){if(Ne(i,1,"ReadableStreamDefaultReader"),Io(i,"First parameter"),rt(i))throw new TypeError("This stream has already been locked for exclusive reading by another reader");ci(this,i),this._readRequests=new k}get closed(){return Ze(this)?this._closedPromise:f(Fr("closed"))}cancel(i=void 0){return Ze(this)?this._ownerReadableStream===void 0?f(Nr("cancel")):Eo(this,i):f(Fr("cancel"))}read(){if(!Ze(this))return f(Fr("read"));if(this._ownerReadableStream===void 0)return f(Nr("read from"));let i,c,h=p((w,T)=>{i=w,c=T});return lr(this,{_chunkSteps:w=>i({value:w,done:!1}),_closeSteps:()=>i({value:void 0,done:!0}),_errorSteps:w=>c(w)}),h}releaseLock(){if(!Ze(this))throw Fr("releaseLock");this._ownerReadableStream!==void 0&&zu(this)}}Object.defineProperties(Ye.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),s(Ye.prototype.cancel,"cancel"),s(Ye.prototype.read,"read"),s(Ye.prototype.releaseLock,"releaseLock"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Ye.prototype,Symbol.toStringTag,{value:"ReadableStreamDefaultReader",configurable:!0});function Ze(n){return!t(n)||!Object.prototype.hasOwnProperty.call(n,"_readRequests")?!1:n instanceof Ye}function lr(n,i){let c=n._ownerReadableStream;c._disturbed=!0,c._state==="closed"?i._closeSteps():c._state==="errored"?i._errorSteps(c._storedError):c._readableStreamController[cr](i)}function zu(n){Le(n);let i=new TypeError("Reader was released");gi(n,i)}function gi(n,i){let c=n._readRequests;n._readRequests=new k,c.forEach(h=>{h._errorSteps(i)})}function Fr(n){return new TypeError(`ReadableStreamDefaultReader.prototype.${n} can only be used on a ReadableStreamDefaultReader`)}let Hu=Object.getPrototypeOf(Object.getPrototypeOf(async function*(){}).prototype);class yi{constructor(i,c){this._ongoingPromise=void 0,this._isFinished=!1,this._reader=i,this._preventCancel=c}next(){let i=()=>this._nextSteps();return this._ongoingPromise=this._ongoingPromise?E(this._ongoingPromise,i,i):i(),this._ongoingPromise}return(i){let c=()=>this._returnSteps(i);return this._ongoingPromise?E(this._ongoingPromise,c,c):c()}_nextSteps(){if(this._isFinished)return Promise.resolve({value:void 0,done:!0});let i=this._reader,c,h,b=p((T,P)=>{c=T,h=P});return lr(i,{_chunkSteps:T=>{this._ongoingPromise=void 0,x(()=>c({value:T,done:!1}))},_closeSteps:()=>{this._ongoingPromise=void 0,this._isFinished=!0,Le(i),c({value:void 0,done:!0})},_errorSteps:T=>{this._ongoingPromise=void 0,this._isFinished=!0,Le(i),h(T)}}),b}_returnSteps(i){if(this._isFinished)return Promise.resolve({value:i,done:!0});this._isFinished=!0;let c=this._reader;if(!this._preventCancel){let h=Eo(c,i);return Le(c),E(h,()=>({value:i,done:!0}))}return Le(c),u({value:i,done:!0})}}let bi={next(){return Si(this)?this._asyncIteratorImpl.next():f(wi("next"))},return(n){return Si(this)?this._asyncIteratorImpl.return(n):f(wi("return"))}};Object.setPrototypeOf(bi,Hu);function Gu(n,i){let c=$t(n),h=new yi(c,i),b=Object.create(bi);return b._asyncIteratorImpl=h,b}function Si(n){if(!t(n)||!Object.prototype.hasOwnProperty.call(n,"_asyncIteratorImpl"))return!1;try{return n._asyncIteratorImpl instanceof yi}catch{return!1}}function wi(n){return new TypeError(`ReadableStreamAsyncIterator.${n} can only be used on a ReadableSteamAsyncIterator`)}let _i=Number.isNaN||function(n){return n!==n};var ko,$o,Do;function ur(n){return n.slice()}function Ti(n,i,c,h,b){new Uint8Array(n).set(new Uint8Array(c,h,b),i)}let Me=n=>(typeof n.transfer=="function"?Me=i=>i.transfer():typeof structuredClone=="function"?Me=i=>structuredClone(i,{transfer:[i]}):Me=i=>i,Me(n)),Xe=n=>(typeof n.detached=="boolean"?Xe=i=>i.detached:Xe=i=>i.byteLength===0,Xe(n));function Ri(n,i,c){if(n.slice)return n.slice(i,c);let h=c-i,b=new ArrayBuffer(h);return Ti(b,0,n,i,h),b}function Br(n,i){let c=n[i];if(c!=null){if(typeof c!="function")throw new TypeError(`${String(i)} is not a function`);return c}}function Ju(n){let i={[Symbol.iterator]:()=>n.iterator},c=(async function*(){return yield*i})(),h=c.next;return{iterator:c,nextMethod:h,done:!1}}let Lo=(Do=(ko=Symbol.asyncIterator)!==null&&ko!==void 0?ko:($o=Symbol.for)===null||$o===void 0?void 0:$o.call(Symbol,"Symbol.asyncIterator"))!==null&&Do!==void 0?Do:"@@asyncIterator";function Ei(n,i="sync",c){if(c===void 0)if(i==="async"){if(c=Br(n,Lo),c===void 0){let w=Br(n,Symbol.iterator),T=Ei(n,"sync",w);return Ju(T)}}else c=Br(n,Symbol.iterator);if(c===void 0)throw new TypeError("The object is not iterable");let h=A(c,n,[]);if(!t(h))throw new TypeError("The iterator method must return an object");let b=h.next;return{iterator:h,nextMethod:b,done:!1}}function Vu(n){let i=A(n.nextMethod,n.iterator,[]);if(!t(i))throw new TypeError("The iterator.next() method must return an object");return i}function Yu(n){return!!n.done}function Zu(n){return n.value}function Xu(n){return!(typeof n!="number"||_i(n)||n<0)}function xi(n){let i=Ri(n.buffer,n.byteOffset,n.byteOffset+n.byteLength);return new Uint8Array(i)}function No(n){let i=n._queue.shift();return n._queueTotalSize-=i.size,n._queueTotalSize<0&&(n._queueTotalSize=0),i.value}function Mo(n,i,c){if(!Xu(c)||c===1/0)throw new RangeError("Size must be a finite, non-NaN, non-negative number.");n._queue.push({value:i,size:c}),n._queueTotalSize+=c}function Qu(n){return n._queue.peek().value}function Qe(n){n._queue=new k,n._queueTotalSize=0}function vi(n){return n===DataView}function Ku(n){return vi(n.constructor)}function ed(n){return vi(n)?1:n.BYTES_PER_ELEMENT}class bt{constructor(){throw new TypeError("Illegal constructor")}get view(){if(!Fo(this))throw Wo("view");return this._view}respond(i){if(!Fo(this))throw Wo("respond");if(Ne(i,1,"respond"),i=Po(i,"First parameter"),this._associatedReadableByteStreamController===void 0)throw new TypeError("This BYOB request has been invalidated");if(Xe(this._view.buffer))throw new TypeError("The BYOB request's buffer has been detached and so cannot be used as a response");Wr(this._associatedReadableByteStreamController,i)}respondWithNewView(i){if(!Fo(this))throw Wo("respondWithNewView");if(Ne(i,1,"respondWithNewView"),!ArrayBuffer.isView(i))throw new TypeError("You can only respond with array buffer views");if(this._associatedReadableByteStreamController===void 0)throw new TypeError("This BYOB request has been invalidated");if(Xe(i.buffer))throw new TypeError("The given view's buffer has been detached and so cannot be used as a response");zr(this._associatedReadableByteStreamController,i)}}Object.defineProperties(bt.prototype,{respond:{enumerable:!0},respondWithNewView:{enumerable:!0},view:{enumerable:!0}}),s(bt.prototype.respond,"respond"),s(bt.prototype.respondWithNewView,"respondWithNewView"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(bt.prototype,Symbol.toStringTag,{value:"ReadableStreamBYOBRequest",configurable:!0});class Fe{constructor(){throw new TypeError("Illegal constructor")}get byobRequest(){if(!St(this))throw fr("byobRequest");return jo(this)}get desiredSize(){if(!St(this))throw fr("desiredSize");return Ni(this)}close(){if(!St(this))throw fr("close");if(this._closeRequested)throw new TypeError("The stream has already been closed; do not close it again!");let i=this._controlledReadableByteStream._state;if(i!=="readable")throw new TypeError(`The stream (in ${i} state) is not in the readable state and cannot be closed`);dr(this)}enqueue(i){if(!St(this))throw fr("enqueue");if(Ne(i,1,"enqueue"),!ArrayBuffer.isView(i))throw new TypeError("chunk must be an array buffer view");if(i.byteLength===0)throw new TypeError("chunk must have non-zero byteLength");if(i.buffer.byteLength===0)throw new TypeError("chunk's buffer must have non-zero byteLength");if(this._closeRequested)throw new TypeError("stream is closed or draining");let c=this._controlledReadableByteStream._state;if(c!=="readable")throw new TypeError(`The stream (in ${c} state) is not in the readable state and cannot be enqueued to`);jr(this,i)}error(i=void 0){if(!St(this))throw fr("error");pe(this,i)}[Ve](i){Ci(this),Qe(this);let c=this._cancelAlgorithm(i);return qr(this),c}[cr](i){let c=this._controlledReadableByteStream;if(this._queueTotalSize>0){Li(this,i);return}let h=this._autoAllocateChunkSize;if(h!==void 0){let b;try{b=new ArrayBuffer(h)}catch(T){i._errorSteps(T);return}let w={buffer:b,bufferByteLength:h,byteOffset:0,byteLength:h,bytesFilled:0,minimumFill:1,elementSize:1,viewConstructor:Uint8Array,readerType:"default"};this._pendingPullIntos.push(w)}mi(c,i),wt(this)}[Ro](){if(this._pendingPullIntos.length>0){let i=this._pendingPullIntos.peek();i.readerType="none",this._pendingPullIntos=new k,this._pendingPullIntos.push(i)}}}Object.defineProperties(Fe.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},byobRequest:{enumerable:!0},desiredSize:{enumerable:!0}}),s(Fe.prototype.close,"close"),s(Fe.prototype.enqueue,"enqueue"),s(Fe.prototype.error,"error"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Fe.prototype,Symbol.toStringTag,{value:"ReadableByteStreamController",configurable:!0});function St(n){return!t(n)||!Object.prototype.hasOwnProperty.call(n,"_controlledReadableByteStream")?!1:n instanceof Fe}function Fo(n){return!t(n)||!Object.prototype.hasOwnProperty.call(n,"_associatedReadableByteStreamController")?!1:n instanceof bt}function wt(n){if(!sd(n))return;if(n._pulling){n._pullAgain=!0;return}n._pulling=!0;let c=n._pullAlgorithm();g(c,()=>(n._pulling=!1,n._pullAgain&&(n._pullAgain=!1,wt(n)),null),h=>(pe(n,h),null))}function Ci(n){Uo(n),n._pendingPullIntos=new k}function Bo(n,i){let c=!1;n._state==="closed"&&(c=!0);let h=Ai(i);i.readerType==="default"?Oo(n,h,c):dd(n,h,c)}function Ai(n){let i=n.bytesFilled,c=n.elementSize;return new n.viewConstructor(n.buffer,n.byteOffset,i/c)}function Ur(n,i,c,h){n._queue.push({buffer:i,byteOffset:c,byteLength:h}),n._queueTotalSize+=h}function Pi(n,i,c,h){let b;try{b=Ri(i,c,c+h)}catch(w){throw pe(n,w),w}Ur(n,b,0,h)}function Ii(n,i){i.bytesFilled>0&&Pi(n,i.buffer,i.byteOffset,i.bytesFilled),Dt(n)}function Oi(n,i){let c=Math.min(n._queueTotalSize,i.byteLength-i.bytesFilled),h=i.bytesFilled+c,b=c,w=!1,T=h%i.elementSize,P=h-T;P>=i.minimumFill&&(b=P-i.bytesFilled,w=!0);let D=n._queue;for(;b>0;){let I=D.peek(),L=Math.min(b,I.byteLength),N=i.byteOffset+i.bytesFilled;Ti(i.buffer,N,I.buffer,I.byteOffset,L),I.byteLength===L?D.shift():(I.byteOffset+=L,I.byteLength-=L),n._queueTotalSize-=L,ki(n,L,i),b-=L}return w}function ki(n,i,c){c.bytesFilled+=i}function $i(n){n._queueTotalSize===0&&n._closeRequested?(qr(n),br(n._controlledReadableByteStream)):wt(n)}function Uo(n){n._byobRequest!==null&&(n._byobRequest._associatedReadableByteStreamController=void 0,n._byobRequest._view=null,n._byobRequest=null)}function qo(n){for(;n._pendingPullIntos.length>0;){if(n._queueTotalSize===0)return;let i=n._pendingPullIntos.peek();Oi(n,i)&&(Dt(n),Bo(n._controlledReadableByteStream,i))}}function td(n){let i=n._controlledReadableByteStream._reader;for(;i._readRequests.length>0;){if(n._queueTotalSize===0)return;let c=i._readRequests.shift();Li(n,c)}}function rd(n,i,c,h){let b=n._controlledReadableByteStream,w=i.constructor,T=ed(w),{byteOffset:P,byteLength:D}=i,I=c*T,L;try{L=Me(i.buffer)}catch(B){h._errorSteps(B);return}let N={buffer:L,bufferByteLength:L.byteLength,byteOffset:P,byteLength:D,bytesFilled:0,minimumFill:I,elementSize:T,viewConstructor:w,readerType:"byob"};if(n._pendingPullIntos.length>0){n._pendingPullIntos.push(N),Bi(b,h);return}if(b._state==="closed"){let B=new w(N.buffer,N.byteOffset,0);h._closeSteps(B);return}if(n._queueTotalSize>0){if(Oi(n,N)){let B=Ai(N);$i(n),h._chunkSteps(B);return}if(n._closeRequested){let B=new TypeError("Insufficient bytes to fill elements in the given buffer");pe(n,B),h._errorSteps(B);return}}n._pendingPullIntos.push(N),Bi(b,h),wt(n)}function nd(n,i){i.readerType==="none"&&Dt(n);let c=n._controlledReadableByteStream;if(zo(c))for(;Ui(c)>0;){let h=Dt(n);Bo(c,h)}}function od(n,i,c){if(ki(n,i,c),c.readerType==="none"){Ii(n,c),qo(n);return}if(c.bytesFilled<c.minimumFill)return;Dt(n);let h=c.bytesFilled%c.elementSize;if(h>0){let b=c.byteOffset+c.bytesFilled;Pi(n,c.buffer,b-h,h)}c.bytesFilled-=h,Bo(n._controlledReadableByteStream,c),qo(n)}function Di(n,i){let c=n._pendingPullIntos.peek();Uo(n),n._controlledReadableByteStream._state==="closed"?nd(n,c):od(n,i,c),wt(n)}function Dt(n){return n._pendingPullIntos.shift()}function sd(n){let i=n._controlledReadableByteStream;return i._state!=="readable"||n._closeRequested||!n._started?!1:!!(hi(i)&&Mr(i)>0||zo(i)&&Ui(i)>0||Ni(n)>0)}function qr(n){n._pullAlgorithm=void 0,n._cancelAlgorithm=void 0}function dr(n){let i=n._controlledReadableByteStream;if(!(n._closeRequested||i._state!=="readable")){if(n._queueTotalSize>0){n._closeRequested=!0;return}if(n._pendingPullIntos.length>0){let c=n._pendingPullIntos.peek();if(c.bytesFilled%c.elementSize!==0){let h=new TypeError("Insufficient bytes to fill elements in the given buffer");throw pe(n,h),h}}qr(n),br(i)}}function jr(n,i){let c=n._controlledReadableByteStream;if(n._closeRequested||c._state!=="readable")return;let{buffer:h,byteOffset:b,byteLength:w}=i;if(Xe(h))throw new TypeError("chunk's buffer is detached and so cannot be enqueued");let T=Me(h);if(n._pendingPullIntos.length>0){let P=n._pendingPullIntos.peek();if(Xe(P.buffer))throw new TypeError("The BYOB request's buffer has been detached and so cannot be filled with an enqueued chunk");Uo(n),P.buffer=Me(P.buffer),P.readerType==="none"&&Ii(n,P)}if(hi(c))if(td(n),Mr(c)===0)Ur(n,T,b,w);else{n._pendingPullIntos.length>0&&Dt(n);let P=new Uint8Array(T,b,w);Oo(c,P,!1)}else zo(c)?(Ur(n,T,b,w),qo(n)):Ur(n,T,b,w);wt(n)}function pe(n,i){let c=n._controlledReadableByteStream;c._state==="readable"&&(Ci(n),Qe(n),qr(n),ua(c,i))}function Li(n,i){let c=n._queue.shift();n._queueTotalSize-=c.byteLength,$i(n);let h=new Uint8Array(c.buffer,c.byteOffset,c.byteLength);i._chunkSteps(h)}function jo(n){if(n._byobRequest===null&&n._pendingPullIntos.length>0){let i=n._pendingPullIntos.peek(),c=new Uint8Array(i.buffer,i.byteOffset+i.bytesFilled,i.byteLength-i.bytesFilled),h=Object.create(bt.prototype);ad(h,n,c),n._byobRequest=h}return n._byobRequest}function Ni(n){let i=n._controlledReadableByteStream._state;return i==="errored"?null:i==="closed"?0:n._strategyHWM-n._queueTotalSize}function Wr(n,i){let c=n._pendingPullIntos.peek();if(n._controlledReadableByteStream._state==="closed"){if(i!==0)throw new TypeError("bytesWritten must be 0 when calling respond() on a closed stream")}else{if(i===0)throw new TypeError("bytesWritten must be greater than 0 when calling respond() on a readable stream");if(c.bytesFilled+i>c.byteLength)throw new RangeError("bytesWritten out of range")}c.buffer=Me(c.buffer),Di(n,i)}function zr(n,i){let c=n._pendingPullIntos.peek();if(n._controlledReadableByteStream._state==="closed"){if(i.byteLength!==0)throw new TypeError("The view's length must be 0 when calling respondWithNewView() on a closed stream")}else if(i.byteLength===0)throw new TypeError("The view's length must be greater than 0 when calling respondWithNewView() on a readable stream");if(c.byteOffset+c.bytesFilled!==i.byteOffset)throw new RangeError("The region specified by view does not match byobRequest");if(c.bufferByteLength!==i.buffer.byteLength)throw new RangeError("The buffer of view has different capacity than byobRequest");if(c.bytesFilled+i.byteLength>c.byteLength)throw new RangeError("The region specified by view is larger than byobRequest");let b=i.byteLength;c.buffer=Me(i.buffer),Di(n,b)}function Mi(n,i,c,h,b,w,T){i._controlledReadableByteStream=n,i._pullAgain=!1,i._pulling=!1,i._byobRequest=null,i._queue=i._queueTotalSize=void 0,Qe(i),i._closeRequested=!1,i._started=!1,i._strategyHWM=w,i._pullAlgorithm=h,i._cancelAlgorithm=b,i._autoAllocateChunkSize=T,i._pendingPullIntos=new k,n._readableStreamController=i;let P=c();g(u(P),()=>(i._started=!0,wt(i),null),D=>(pe(i,D),null))}function id(n,i,c){let h=Object.create(Fe.prototype),b,w,T;i.start!==void 0?b=()=>i.start(h):b=()=>{},i.pull!==void 0?w=()=>i.pull(h):w=()=>u(void 0),i.cancel!==void 0?T=D=>i.cancel(D):T=()=>u(void 0);let P=i.autoAllocateChunkSize;if(P===0)throw new TypeError("autoAllocateChunkSize must be greater than 0");Mi(n,h,b,w,T,c,P)}function ad(n,i,c){n._associatedReadableByteStreamController=i,n._view=c}function Wo(n){return new TypeError(`ReadableStreamBYOBRequest.prototype.${n} can only be used on a ReadableStreamBYOBRequest`)}function fr(n){return new TypeError(`ReadableByteStreamController.prototype.${n} can only be used on a ReadableByteStreamController`)}function cd(n,i){Ce(n,i);let c=n?.mode;return{mode:c===void 0?void 0:ld(c,`${i} has member 'mode' that`)}}function ld(n,i){if(n=`${n}`,n!=="byob")throw new TypeError(`${i} '${n}' is not a valid enumeration value for ReadableStreamReaderMode`);return n}function ud(n,i){var c;Ce(n,i);let h=(c=n?.min)!==null&&c!==void 0?c:1;return{min:Po(h,`${i} has member 'min' that`)}}function Fi(n){return new Ke(n)}function Bi(n,i){n._reader._readIntoRequests.push(i)}function dd(n,i,c){let b=n._reader._readIntoRequests.shift();c?b._closeSteps(i):b._chunkSteps(i)}function Ui(n){return n._reader._readIntoRequests.length}function zo(n){let i=n._reader;return!(i===void 0||!_t(i))}class Ke{constructor(i){if(Ne(i,1,"ReadableStreamBYOBReader"),Io(i,"First parameter"),rt(i))throw new TypeError("This stream has already been locked for exclusive reading by another reader");if(!St(i._readableStreamController))throw new TypeError("Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte source");ci(this,i),this._readIntoRequests=new k}get closed(){return _t(this)?this._closedPromise:f(Hr("closed"))}cancel(i=void 0){return _t(this)?this._ownerReadableStream===void 0?f(Nr("cancel")):Eo(this,i):f(Hr("cancel"))}read(i,c={}){if(!_t(this))return f(Hr("read"));if(!ArrayBuffer.isView(i))return f(new TypeError("view must be an array buffer view"));if(i.byteLength===0)return f(new TypeError("view must have non-zero byteLength"));if(i.buffer.byteLength===0)return f(new TypeError("view's buffer must have non-zero byteLength"));if(Xe(i.buffer))return f(new TypeError("view's buffer has been detached"));let h;try{h=ud(c,"options")}catch(I){return f(I)}let b=h.min;if(b===0)return f(new TypeError("options.min must be greater than 0"));if(Ku(i)){if(b>i.byteLength)return f(new RangeError("options.min must be less than or equal to view's byteLength"))}else if(b>i.length)return f(new RangeError("options.min must be less than or equal to view's length"));if(this._ownerReadableStream===void 0)return f(Nr("read from"));let w,T,P=p((I,L)=>{w=I,T=L});return qi(this,i,b,{_chunkSteps:I=>w({value:I,done:!1}),_closeSteps:I=>w({value:I,done:!0}),_errorSteps:I=>T(I)}),P}releaseLock(){if(!_t(this))throw Hr("releaseLock");this._ownerReadableStream!==void 0&&fd(this)}}Object.defineProperties(Ke.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),s(Ke.prototype.cancel,"cancel"),s(Ke.prototype.read,"read"),s(Ke.prototype.releaseLock,"releaseLock"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Ke.prototype,Symbol.toStringTag,{value:"ReadableStreamBYOBReader",configurable:!0});function _t(n){return!t(n)||!Object.prototype.hasOwnProperty.call(n,"_readIntoRequests")?!1:n instanceof Ke}function qi(n,i,c,h){let b=n._ownerReadableStream;b._disturbed=!0,b._state==="errored"?h._errorSteps(b._storedError):rd(b._readableStreamController,i,c,h)}function fd(n){Le(n);let i=new TypeError("Reader was released");ji(n,i)}function ji(n,i){let c=n._readIntoRequests;n._readIntoRequests=new k,c.forEach(h=>{h._errorSteps(i)})}function Hr(n){return new TypeError(`ReadableStreamBYOBReader.prototype.${n} can only be used on a ReadableStreamBYOBReader`)}function pr(n,i){let{highWaterMark:c}=n;if(c===void 0)return i;if(_i(c)||c<0)throw new RangeError("Invalid highWaterMark");return c}function Gr(n){let{size:i}=n;return i||(()=>1)}function Jr(n,i){Ce(n,i);let c=n?.highWaterMark,h=n?.size;return{highWaterMark:c===void 0?void 0:Ao(c),size:h===void 0?void 0:pd(h,`${i} has member 'size' that`)}}function pd(n,i){return fe(n,i),c=>Ao(n(c))}function md(n,i){Ce(n,i);let c=n?.abort,h=n?.close,b=n?.start,w=n?.type,T=n?.write;return{abort:c===void 0?void 0:hd(c,n,`${i} has member 'abort' that`),close:h===void 0?void 0:gd(h,n,`${i} has member 'close' that`),start:b===void 0?void 0:yd(b,n,`${i} has member 'start' that`),write:T===void 0?void 0:bd(T,n,`${i} has member 'write' that`),type:w}}function hd(n,i,c){return fe(n,c),h=>C(n,i,[h])}function gd(n,i,c){return fe(n,c),()=>C(n,i,[])}function yd(n,i,c){return fe(n,c),h=>A(n,i,[h])}function bd(n,i,c){return fe(n,c),(h,b)=>C(n,i,[h,b])}function Wi(n,i){if(!Lt(n))throw new TypeError(`${i} is not a WritableStream.`)}function Sd(n){if(typeof n!="object"||n===null)return!1;try{return typeof n.aborted=="boolean"}catch{return!1}}let wd=typeof AbortController=="function";function _d(){if(wd)return new AbortController}class et{constructor(i={},c={}){i===void 0?i=null:fi(i,"First parameter");let h=Jr(c,"Second parameter"),b=md(i,"First parameter");if(Hi(this),b.type!==void 0)throw new RangeError("Invalid type is specified");let T=Gr(h),P=pr(h,1);Ld(this,b,P,T)}get locked(){if(!Lt(this))throw Qr("locked");return Nt(this)}abort(i=void 0){return Lt(this)?Nt(this)?f(new TypeError("Cannot abort a stream that already has a writer")):Vr(this,i):f(Qr("abort"))}close(){return Lt(this)?Nt(this)?f(new TypeError("Cannot close a stream that already has a writer")):Ae(this)?f(new TypeError("Cannot close an already-closing stream")):Gi(this):f(Qr("close"))}getWriter(){if(!Lt(this))throw Qr("getWriter");return zi(this)}}Object.defineProperties(et.prototype,{abort:{enumerable:!0},close:{enumerable:!0},getWriter:{enumerable:!0},locked:{enumerable:!0}}),s(et.prototype.abort,"abort"),s(et.prototype.close,"close"),s(et.prototype.getWriter,"getWriter"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(et.prototype,Symbol.toStringTag,{value:"WritableStream",configurable:!0});function zi(n){return new Be(n)}function Td(n,i,c,h,b=1,w=()=>1){let T=Object.create(et.prototype);Hi(T);let P=Object.create(Mt.prototype);return Qi(T,P,n,i,c,h,b,w),T}function Hi(n){n._state="writable",n._storedError=void 0,n._writer=void 0,n._writableStreamController=void 0,n._writeRequests=new k,n._inFlightWriteRequest=void 0,n._closeRequest=void 0,n._inFlightCloseRequest=void 0,n._pendingAbortRequest=void 0,n._backpressure=!1}function Lt(n){return!t(n)||!Object.prototype.hasOwnProperty.call(n,"_writableStreamController")?!1:n instanceof et}function Nt(n){return n._writer!==void 0}function Vr(n,i){var c;if(n._state==="closed"||n._state==="errored")return u(void 0);n._writableStreamController._abortReason=i,(c=n._writableStreamController._abortController)===null||c===void 0||c.abort(i);let h=n._state;if(h==="closed"||h==="errored")return u(void 0);if(n._pendingAbortRequest!==void 0)return n._pendingAbortRequest._promise;let b=!1;h==="erroring"&&(b=!0,i=void 0);let w=p((T,P)=>{n._pendingAbortRequest={_promise:void 0,_resolve:T,_reject:P,_reason:i,_wasAlreadyErroring:b}});return n._pendingAbortRequest._promise=w,b||Go(n,i),w}function Gi(n){let i=n._state;if(i==="closed"||i==="errored")return f(new TypeError(`The stream (in ${i} state) is not in the writable state and cannot be closed`));let c=p((b,w)=>{let T={_resolve:b,_reject:w};n._closeRequest=T}),h=n._writer;return h!==void 0&&n._backpressure&&i==="writable"&&es(h),Nd(n._writableStreamController),c}function Rd(n){return p((c,h)=>{let b={_resolve:c,_reject:h};n._writeRequests.push(b)})}function Ho(n,i){if(n._state==="writable"){Go(n,i);return}Jo(n)}function Go(n,i){let c=n._writableStreamController;n._state="erroring",n._storedError=i;let h=n._writer;h!==void 0&&Vi(h,i),!Ad(n)&&c._started&&Jo(n)}function Jo(n){n._state="errored",n._writableStreamController[H]();let i=n._storedError;if(n._writeRequests.forEach(b=>{b._reject(i)}),n._writeRequests=new k,n._pendingAbortRequest===void 0){Yr(n);return}let c=n._pendingAbortRequest;if(n._pendingAbortRequest=void 0,c._wasAlreadyErroring){c._reject(i),Yr(n);return}let h=n._writableStreamController[$](c._reason);g(h,()=>(c._resolve(),Yr(n),null),b=>(c._reject(b),Yr(n),null))}function Ed(n){n._inFlightWriteRequest._resolve(void 0),n._inFlightWriteRequest=void 0}function xd(n,i){n._inFlightWriteRequest._reject(i),n._inFlightWriteRequest=void 0,Ho(n,i)}function vd(n){n._inFlightCloseRequest._resolve(void 0),n._inFlightCloseRequest=void 0,n._state==="erroring"&&(n._storedError=void 0,n._pendingAbortRequest!==void 0&&(n._pendingAbortRequest._resolve(),n._pendingAbortRequest=void 0)),n._state="closed";let c=n._writer;c!==void 0&&ra(c)}function Cd(n,i){n._inFlightCloseRequest._reject(i),n._inFlightCloseRequest=void 0,n._pendingAbortRequest!==void 0&&(n._pendingAbortRequest._reject(i),n._pendingAbortRequest=void 0),Ho(n,i)}function Ae(n){return!(n._closeRequest===void 0&&n._inFlightCloseRequest===void 0)}function Ad(n){return!(n._inFlightWriteRequest===void 0&&n._inFlightCloseRequest===void 0)}function Pd(n){n._inFlightCloseRequest=n._closeRequest,n._closeRequest=void 0}function Id(n){n._inFlightWriteRequest=n._writeRequests.shift()}function Yr(n){n._closeRequest!==void 0&&(n._closeRequest._reject(n._storedError),n._closeRequest=void 0);let i=n._writer;i!==void 0&&Qo(i,n._storedError)}function Vo(n,i){let c=n._writer;c!==void 0&&i!==n._backpressure&&(i?Wd(c):es(c)),n._backpressure=i}class Be{constructor(i){if(Ne(i,1,"WritableStreamDefaultWriter"),Wi(i,"First parameter"),Nt(i))throw new TypeError("This stream has already been locked for exclusive writing by another writer");this._ownerWritableStream=i,i._writer=this;let c=i._state;if(c==="writable")!Ae(i)&&i._backpressure?en(this):na(this),Kr(this);else if(c==="erroring")Ko(this,i._storedError),Kr(this);else if(c==="closed")na(this),qd(this);else{let h=i._storedError;Ko(this,h),ta(this,h)}}get closed(){return Tt(this)?this._closedPromise:f(Rt("closed"))}get desiredSize(){if(!Tt(this))throw Rt("desiredSize");if(this._ownerWritableStream===void 0)throw hr("desiredSize");return Dd(this)}get ready(){return Tt(this)?this._readyPromise:f(Rt("ready"))}abort(i=void 0){return Tt(this)?this._ownerWritableStream===void 0?f(hr("abort")):Od(this,i):f(Rt("abort"))}close(){if(!Tt(this))return f(Rt("close"));let i=this._ownerWritableStream;return i===void 0?f(hr("close")):Ae(i)?f(new TypeError("Cannot close an already-closing stream")):Ji(this)}releaseLock(){if(!Tt(this))throw Rt("releaseLock");this._ownerWritableStream!==void 0&&Yi(this)}write(i=void 0){return Tt(this)?this._ownerWritableStream===void 0?f(hr("write to")):Zi(this,i):f(Rt("write"))}}Object.defineProperties(Be.prototype,{abort:{enumerable:!0},close:{enumerable:!0},releaseLock:{enumerable:!0},write:{enumerable:!0},closed:{enumerable:!0},desiredSize:{enumerable:!0},ready:{enumerable:!0}}),s(Be.prototype.abort,"abort"),s(Be.prototype.close,"close"),s(Be.prototype.releaseLock,"releaseLock"),s(Be.prototype.write,"write"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Be.prototype,Symbol.toStringTag,{value:"WritableStreamDefaultWriter",configurable:!0});function Tt(n){return!t(n)||!Object.prototype.hasOwnProperty.call(n,"_ownerWritableStream")?!1:n instanceof Be}function Od(n,i){let c=n._ownerWritableStream;return Vr(c,i)}function Ji(n){let i=n._ownerWritableStream;return Gi(i)}function kd(n){let i=n._ownerWritableStream,c=i._state;return Ae(i)||c==="closed"?u(void 0):c==="errored"?f(i._storedError):Ji(n)}function $d(n,i){n._closedPromiseState==="pending"?Qo(n,i):jd(n,i)}function Vi(n,i){n._readyPromiseState==="pending"?oa(n,i):zd(n,i)}function Dd(n){let i=n._ownerWritableStream,c=i._state;return c==="errored"||c==="erroring"?null:c==="closed"?0:Ki(i._writableStreamController)}function Yi(n){let i=n._ownerWritableStream,c=new TypeError("Writer was released and can no longer be used to monitor the stream's closedness");Vi(n,c),$d(n,c),i._writer=void 0,n._ownerWritableStream=void 0}function Zi(n,i){let c=n._ownerWritableStream,h=c._writableStreamController,b=Md(h,i);if(c!==n._ownerWritableStream)return f(hr("write to"));let w=c._state;if(w==="errored")return f(c._storedError);if(Ae(c)||w==="closed")return f(new TypeError("The stream is closing or closed and cannot be written to"));if(w==="erroring")return f(c._storedError);let T=Rd(c);return Fd(h,i,b),T}let Xi={};class Mt{constructor(){throw new TypeError("Illegal constructor")}get abortReason(){if(!Yo(this))throw Xo("abortReason");return this._abortReason}get signal(){if(!Yo(this))throw Xo("signal");if(this._abortController===void 0)throw new TypeError("WritableStreamDefaultController.prototype.signal is not supported");return this._abortController.signal}error(i=void 0){if(!Yo(this))throw Xo("error");this._controlledWritableStream._state==="writable"&&ea(this,i)}[$](i){let c=this._abortAlgorithm(i);return Zr(this),c}[H](){Qe(this)}}Object.defineProperties(Mt.prototype,{abortReason:{enumerable:!0},signal:{enumerable:!0},error:{enumerable:!0}}),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Mt.prototype,Symbol.toStringTag,{value:"WritableStreamDefaultController",configurable:!0});function Yo(n){return!t(n)||!Object.prototype.hasOwnProperty.call(n,"_controlledWritableStream")?!1:n instanceof Mt}function Qi(n,i,c,h,b,w,T,P){i._controlledWritableStream=n,n._writableStreamController=i,i._queue=void 0,i._queueTotalSize=void 0,Qe(i),i._abortReason=void 0,i._abortController=_d(),i._started=!1,i._strategySizeAlgorithm=P,i._strategyHWM=T,i._writeAlgorithm=h,i._closeAlgorithm=b,i._abortAlgorithm=w;let D=Zo(i);Vo(n,D);let I=c(),L=u(I);g(L,()=>(i._started=!0,Xr(i),null),N=>(i._started=!0,Ho(n,N),null))}function Ld(n,i,c,h){let b=Object.create(Mt.prototype),w,T,P,D;i.start!==void 0?w=()=>i.start(b):w=()=>{},i.write!==void 0?T=I=>i.write(I,b):T=()=>u(void 0),i.close!==void 0?P=()=>i.close():P=()=>u(void 0),i.abort!==void 0?D=I=>i.abort(I):D=()=>u(void 0),Qi(n,b,w,T,P,D,c,h)}function Zr(n){n._writeAlgorithm=void 0,n._closeAlgorithm=void 0,n._abortAlgorithm=void 0,n._strategySizeAlgorithm=void 0}function Nd(n){Mo(n,Xi,0),Xr(n)}function Md(n,i){try{return n._strategySizeAlgorithm(i)}catch(c){return mr(n,c),1}}function Ki(n){return n._strategyHWM-n._queueTotalSize}function Fd(n,i,c){try{Mo(n,i,c)}catch(b){mr(n,b);return}let h=n._controlledWritableStream;if(!Ae(h)&&h._state==="writable"){let b=Zo(n);Vo(h,b)}Xr(n)}function Xr(n){let i=n._controlledWritableStream;if(!n._started||i._inFlightWriteRequest!==void 0)return;if(i._state==="erroring"){Jo(i);return}if(n._queue.length===0)return;let h=Qu(n);h===Xi?Bd(n):Ud(n,h)}function mr(n,i){n._controlledWritableStream._state==="writable"&&ea(n,i)}function Bd(n){let i=n._controlledWritableStream;Pd(i),No(n);let c=n._closeAlgorithm();Zr(n),g(c,()=>(vd(i),null),h=>(Cd(i,h),null))}function Ud(n,i){let c=n._controlledWritableStream;Id(c);let h=n._writeAlgorithm(i);g(h,()=>{Ed(c);let b=c._state;if(No(n),!Ae(c)&&b==="writable"){let w=Zo(n);Vo(c,w)}return Xr(n),null},b=>(c._state==="writable"&&Zr(n),xd(c,b),null))}function Zo(n){return Ki(n)<=0}function ea(n,i){let c=n._controlledWritableStream;Zr(n),Go(c,i)}function Qr(n){return new TypeError(`WritableStream.prototype.${n} can only be used on a WritableStream`)}function Xo(n){return new TypeError(`WritableStreamDefaultController.prototype.${n} can only be used on a WritableStreamDefaultController`)}function Rt(n){return new TypeError(`WritableStreamDefaultWriter.prototype.${n} can only be used on a WritableStreamDefaultWriter`)}function hr(n){return new TypeError("Cannot "+n+" a stream using a released writer")}function Kr(n){n._closedPromise=p((i,c)=>{n._closedPromise_resolve=i,n._closedPromise_reject=c,n._closedPromiseState="pending"})}function ta(n,i){Kr(n),Qo(n,i)}function qd(n){Kr(n),ra(n)}function Qo(n,i){n._closedPromise_reject!==void 0&&(R(n._closedPromise),n._closedPromise_reject(i),n._closedPromise_resolve=void 0,n._closedPromise_reject=void 0,n._closedPromiseState="rejected")}function jd(n,i){ta(n,i)}function ra(n){n._closedPromise_resolve!==void 0&&(n._closedPromise_resolve(void 0),n._closedPromise_resolve=void 0,n._closedPromise_reject=void 0,n._closedPromiseState="resolved")}function en(n){n._readyPromise=p((i,c)=>{n._readyPromise_resolve=i,n._readyPromise_reject=c}),n._readyPromiseState="pending"}function Ko(n,i){en(n),oa(n,i)}function na(n){en(n),es(n)}function oa(n,i){n._readyPromise_reject!==void 0&&(R(n._readyPromise),n._readyPromise_reject(i),n._readyPromise_resolve=void 0,n._readyPromise_reject=void 0,n._readyPromiseState="rejected")}function Wd(n){en(n)}function zd(n,i){Ko(n,i)}function es(n){n._readyPromise_resolve!==void 0&&(n._readyPromise_resolve(void 0),n._readyPromise_resolve=void 0,n._readyPromise_reject=void 0,n._readyPromiseState="fulfilled")}function Hd(){if(typeof globalThis<"u")return globalThis;if(typeof self<"u")return self;if(typeof global<"u")return global}let ts=Hd();function Gd(n){if(!(typeof n=="function"||typeof n=="object")||n.name!=="DOMException")return!1;try{return new n,!0}catch{return!1}}function Jd(){let n=ts?.DOMException;return Gd(n)?n:void 0}function Vd(){let n=function(c,h){this.message=c||"",this.name=h||"Error",Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)};return s(n,"DOMException"),n.prototype=Object.create(Error.prototype),Object.defineProperty(n.prototype,"constructor",{value:n,writable:!0,configurable:!0}),n}let Yd=Jd()||Vd();function sa(n,i,c,h,b,w){let T=$t(n),P=zi(i);n._disturbed=!0;let D=!1,I=u(void 0);return p((L,N)=>{let B;if(w!==void 0){if(B=()=>{let O=w.reason!==void 0?w.reason:new Yd("Aborted","AbortError"),M=[];h||M.push(()=>i._state==="writable"?Vr(i,O):u(void 0)),b||M.push(()=>n._state==="readable"?_e(n,O):u(void 0)),re(()=>Promise.all(M.map(q=>q())),!0,O)},w.aborted){B();return}w.addEventListener("abort",B)}function Te(){return p((O,M)=>{function q(ae){ae?O():y(qt(),q,M)}q(!1)})}function qt(){return D?u(!0):y(P._readyPromise,()=>p((O,M)=>{lr(T,{_chunkSteps:q=>{I=y(Zi(P,q),void 0,e),O(!1)},_closeSteps:()=>O(!0),_errorSteps:M})}))}if(qe(n,T._closedPromise,O=>(h?me(!0,O):re(()=>Vr(i,O),!0,O),null)),qe(i,P._closedPromise,O=>(b?me(!0,O):re(()=>_e(n,O),!0,O),null)),ee(n,T._closedPromise,()=>(c?me():re(()=>kd(P)),null)),Ae(i)||i._state==="closed"){let O=new TypeError("the destination writable stream closed before all data could be piped to it");b?me(!0,O):re(()=>_e(n,O),!0,O)}R(Te());function ot(){let O=I;return y(I,()=>O!==I?ot():void 0)}function qe(O,M,q){O._state==="errored"?q(O._storedError):S(M,q)}function ee(O,M,q){O._state==="closed"?q():_(M,q)}function re(O,M,q){if(D)return;D=!0,i._state==="writable"&&!Ae(i)?_(ot(),ae):ae();function ae(){return g(O(),()=>je(M,q),jt=>je(!0,jt)),null}}function me(O,M){D||(D=!0,i._state==="writable"&&!Ae(i)?_(ot(),()=>je(O,M)):je(O,M))}function je(O,M){return Yi(P),Le(T),w!==void 0&&w.removeEventListener("abort",B),O?N(M):L(void 0),null}})}class Ue{constructor(){throw new TypeError("Illegal constructor")}get desiredSize(){if(!tn(this))throw nn("desiredSize");return rs(this)}close(){if(!tn(this))throw nn("close");if(!Bt(this))throw new TypeError("The stream is not in a state that permits close");Et(this)}enqueue(i=void 0){if(!tn(this))throw nn("enqueue");if(!Bt(this))throw new TypeError("The stream is not in a state that permits enqueue");return Ft(this,i)}error(i=void 0){if(!tn(this))throw nn("error");we(this,i)}[Ve](i){Qe(this);let c=this._cancelAlgorithm(i);return rn(this),c}[cr](i){let c=this._controlledReadableStream;if(this._queue.length>0){let h=No(this);this._closeRequested&&this._queue.length===0?(rn(this),br(c)):gr(this),i._chunkSteps(h)}else mi(c,i),gr(this)}[Ro](){}}Object.defineProperties(Ue.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},desiredSize:{enumerable:!0}}),s(Ue.prototype.close,"close"),s(Ue.prototype.enqueue,"enqueue"),s(Ue.prototype.error,"error"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Ue.prototype,Symbol.toStringTag,{value:"ReadableStreamDefaultController",configurable:!0});function tn(n){return!t(n)||!Object.prototype.hasOwnProperty.call(n,"_controlledReadableStream")?!1:n instanceof Ue}function gr(n){if(!ia(n))return;if(n._pulling){n._pullAgain=!0;return}n._pulling=!0;let c=n._pullAlgorithm();g(c,()=>(n._pulling=!1,n._pullAgain&&(n._pullAgain=!1,gr(n)),null),h=>(we(n,h),null))}function ia(n){let i=n._controlledReadableStream;return!Bt(n)||!n._started?!1:!!(rt(i)&&Mr(i)>0||rs(n)>0)}function rn(n){n._pullAlgorithm=void 0,n._cancelAlgorithm=void 0,n._strategySizeAlgorithm=void 0}function Et(n){if(!Bt(n))return;let i=n._controlledReadableStream;n._closeRequested=!0,n._queue.length===0&&(rn(n),br(i))}function Ft(n,i){if(!Bt(n))return;let c=n._controlledReadableStream;if(rt(c)&&Mr(c)>0)Oo(c,i,!1);else{let h;try{h=n._strategySizeAlgorithm(i)}catch(b){throw we(n,b),b}try{Mo(n,i,h)}catch(b){throw we(n,b),b}}gr(n)}function we(n,i){let c=n._controlledReadableStream;c._state==="readable"&&(Qe(n),rn(n),ua(c,i))}function rs(n){let i=n._controlledReadableStream._state;return i==="errored"?null:i==="closed"?0:n._strategyHWM-n._queueTotalSize}function Zd(n){return!ia(n)}function Bt(n){let i=n._controlledReadableStream._state;return!n._closeRequested&&i==="readable"}function aa(n,i,c,h,b,w,T){i._controlledReadableStream=n,i._queue=void 0,i._queueTotalSize=void 0,Qe(i),i._started=!1,i._closeRequested=!1,i._pullAgain=!1,i._pulling=!1,i._strategySizeAlgorithm=T,i._strategyHWM=w,i._pullAlgorithm=h,i._cancelAlgorithm=b,n._readableStreamController=i;let P=c();g(u(P),()=>(i._started=!0,gr(i),null),D=>(we(i,D),null))}function Xd(n,i,c,h){let b=Object.create(Ue.prototype),w,T,P;i.start!==void 0?w=()=>i.start(b):w=()=>{},i.pull!==void 0?T=()=>i.pull(b):T=()=>u(void 0),i.cancel!==void 0?P=D=>i.cancel(D):P=()=>u(void 0),aa(n,b,w,T,P,c,h)}function nn(n){return new TypeError(`ReadableStreamDefaultController.prototype.${n} can only be used on a ReadableStreamDefaultController`)}function Qd(n,i){return St(n._readableStreamController)?ef(n):Kd(n)}function Kd(n,i){let c=$t(n),h=!1,b=!1,w=!1,T=!1,P,D,I,L,N,B=p(ee=>{N=ee});function Te(){return h?(b=!0,u(void 0)):(h=!0,lr(c,{_chunkSteps:re=>{x(()=>{b=!1;let me=re,je=re;w||Ft(I._readableStreamController,me),T||Ft(L._readableStreamController,je),h=!1,b&&Te()})},_closeSteps:()=>{h=!1,w||Et(I._readableStreamController),T||Et(L._readableStreamController),(!w||!T)&&N(void 0)},_errorSteps:()=>{h=!1}}),u(void 0))}function qt(ee){if(w=!0,P=ee,T){let re=ur([P,D]),me=_e(n,re);N(me)}return B}function ot(ee){if(T=!0,D=ee,w){let re=ur([P,D]),me=_e(n,re);N(me)}return B}function qe(){}return I=yr(qe,Te,qt),L=yr(qe,Te,ot),S(c._closedPromise,ee=>(we(I._readableStreamController,ee),we(L._readableStreamController,ee),(!w||!T)&&N(void 0),null)),[I,L]}function ef(n){let i=$t(n),c=!1,h=!1,b=!1,w=!1,T=!1,P,D,I,L,N,B=p(O=>{N=O});function Te(O){S(O._closedPromise,M=>(O!==i||(pe(I._readableStreamController,M),pe(L._readableStreamController,M),(!w||!T)&&N(void 0)),null))}function qt(){_t(i)&&(Le(i),i=$t(n),Te(i)),lr(i,{_chunkSteps:M=>{x(()=>{h=!1,b=!1;let q=M,ae=M;if(!w&&!T)try{ae=xi(M)}catch(jt){pe(I._readableStreamController,jt),pe(L._readableStreamController,jt),N(_e(n,jt));return}w||jr(I._readableStreamController,q),T||jr(L._readableStreamController,ae),c=!1,h?qe():b&&ee()})},_closeSteps:()=>{c=!1,w||dr(I._readableStreamController),T||dr(L._readableStreamController),I._readableStreamController._pendingPullIntos.length>0&&Wr(I._readableStreamController,0),L._readableStreamController._pendingPullIntos.length>0&&Wr(L._readableStreamController,0),(!w||!T)&&N(void 0)},_errorSteps:()=>{c=!1}})}function ot(O,M){Ze(i)&&(Le(i),i=Fi(n),Te(i));let q=M?L:I,ae=M?I:L;qi(i,O,1,{_chunkSteps:Wt=>{x(()=>{h=!1,b=!1;let zt=M?T:w;if(M?w:T)zt||zr(q._readableStreamController,Wt);else{let Ra;try{Ra=xi(Wt)}catch(as){pe(q._readableStreamController,as),pe(ae._readableStreamController,as),N(_e(n,as));return}zt||zr(q._readableStreamController,Wt),jr(ae._readableStreamController,Ra)}c=!1,h?qe():b&&ee()})},_closeSteps:Wt=>{c=!1;let zt=M?T:w,fn=M?w:T;zt||dr(q._readableStreamController),fn||dr(ae._readableStreamController),Wt!==void 0&&(zt||zr(q._readableStreamController,Wt),!fn&&ae._readableStreamController._pendingPullIntos.length>0&&Wr(ae._readableStreamController,0)),(!zt||!fn)&&N(void 0)},_errorSteps:()=>{c=!1}})}function qe(){if(c)return h=!0,u(void 0);c=!0;let O=jo(I._readableStreamController);return O===null?qt():ot(O._view,!1),u(void 0)}function ee(){if(c)return b=!0,u(void 0);c=!0;let O=jo(L._readableStreamController);return O===null?qt():ot(O._view,!0),u(void 0)}function re(O){if(w=!0,P=O,T){let M=ur([P,D]),q=_e(n,M);N(q)}return B}function me(O){if(T=!0,D=O,w){let M=ur([P,D]),q=_e(n,M);N(q)}return B}function je(){}return I=la(je,qe,re),L=la(je,ee,me),Te(i),[I,L]}function tf(n){return t(n)&&typeof n.getReader<"u"}function rf(n){return tf(n)?of(n.getReader()):nf(n)}function nf(n){let i,c=Ei(n,"async"),h=e;function b(){let T;try{T=Vu(c)}catch(D){return f(D)}let P=u(T);return E(P,D=>{if(!t(D))throw new TypeError("The promise returned by the iterator.next() method must fulfill with an object");if(Yu(D))Et(i._readableStreamController);else{let L=Zu(D);Ft(i._readableStreamController,L)}})}function w(T){let P=c.iterator,D;try{D=Br(P,"return")}catch(N){return f(N)}if(D===void 0)return u(void 0);let I;try{I=A(D,P,[T])}catch(N){return f(N)}let L=u(I);return E(L,N=>{if(!t(N))throw new TypeError("The promise returned by the iterator.return() method must fulfill with an object")})}return i=yr(h,b,w,0),i}function of(n){let i,c=e;function h(){let w;try{w=n.read()}catch(T){return f(T)}return E(w,T=>{if(!t(T))throw new TypeError("The promise returned by the reader.read() method must fulfill with an object");if(T.done)Et(i._readableStreamController);else{let P=T.value;Ft(i._readableStreamController,P)}})}function b(w){try{return u(n.cancel(w))}catch(T){return f(T)}}return i=yr(c,h,b,0),i}function sf(n,i){Ce(n,i);let c=n,h=c?.autoAllocateChunkSize,b=c?.cancel,w=c?.pull,T=c?.start,P=c?.type;return{autoAllocateChunkSize:h===void 0?void 0:Po(h,`${i} has member 'autoAllocateChunkSize' that`),cancel:b===void 0?void 0:af(b,c,`${i} has member 'cancel' that`),pull:w===void 0?void 0:cf(w,c,`${i} has member 'pull' that`),start:T===void 0?void 0:lf(T,c,`${i} has member 'start' that`),type:P===void 0?void 0:uf(P,`${i} has member 'type' that`)}}function af(n,i,c){return fe(n,c),h=>C(n,i,[h])}function cf(n,i,c){return fe(n,c),h=>C(n,i,[h])}function lf(n,i,c){return fe(n,c),h=>A(n,i,[h])}function uf(n,i){if(n=`${n}`,n!=="bytes")throw new TypeError(`${i} '${n}' is not a valid enumeration value for ReadableStreamType`);return n}function df(n,i){return Ce(n,i),{preventCancel:!!n?.preventCancel}}function ca(n,i){Ce(n,i);let c=n?.preventAbort,h=n?.preventCancel,b=n?.preventClose,w=n?.signal;return w!==void 0&&ff(w,`${i} has member 'signal' that`),{preventAbort:!!c,preventCancel:!!h,preventClose:!!b,signal:w}}function ff(n,i){if(!Sd(n))throw new TypeError(`${i} is not an AbortSignal.`)}function pf(n,i){Ce(n,i);let c=n?.readable;Co(c,"readable","ReadableWritablePair"),Io(c,`${i} has member 'readable' that`);let h=n?.writable;return Co(h,"writable","ReadableWritablePair"),Wi(h,`${i} has member 'writable' that`),{readable:c,writable:h}}class Q{constructor(i={},c={}){i===void 0?i=null:fi(i,"First parameter");let h=Jr(c,"Second parameter"),b=sf(i,"First parameter");if(ns(this),b.type==="bytes"){if(h.size!==void 0)throw new RangeError("The strategy for a byte stream cannot have a size function");let w=pr(h,0);id(this,b,w)}else{let w=Gr(h),T=pr(h,1);Xd(this,b,T,w)}}get locked(){if(!tt(this))throw xt("locked");return rt(this)}cancel(i=void 0){return tt(this)?rt(this)?f(new TypeError("Cannot cancel a stream that already has a reader")):_e(this,i):f(xt("cancel"))}getReader(i=void 0){if(!tt(this))throw xt("getReader");return cd(i,"First parameter").mode===void 0?$t(this):Fi(this)}pipeThrough(i,c={}){if(!tt(this))throw xt("pipeThrough");Ne(i,1,"pipeThrough");let h=pf(i,"First parameter"),b=ca(c,"Second parameter");if(rt(this))throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream");if(Nt(h.writable))throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream");let w=sa(this,h.writable,b.preventClose,b.preventAbort,b.preventCancel,b.signal);return R(w),h.readable}pipeTo(i,c={}){if(!tt(this))return f(xt("pipeTo"));if(i===void 0)return f("Parameter 1 is required in 'pipeTo'.");if(!Lt(i))return f(new TypeError("ReadableStream.prototype.pipeTo's first argument must be a WritableStream"));let h;try{h=ca(c,"Second parameter")}catch(b){return f(b)}return rt(this)?f(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream")):Nt(i)?f(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream")):sa(this,i,h.preventClose,h.preventAbort,h.preventCancel,h.signal)}tee(){if(!tt(this))throw xt("tee");let i=Qd(this);return ur(i)}values(i=void 0){if(!tt(this))throw xt("values");let c=df(i,"First parameter");return Gu(this,c.preventCancel)}[Lo](i){return this.values(i)}static from(i){return rf(i)}}Object.defineProperties(Q,{from:{enumerable:!0}}),Object.defineProperties(Q.prototype,{cancel:{enumerable:!0},getReader:{enumerable:!0},pipeThrough:{enumerable:!0},pipeTo:{enumerable:!0},tee:{enumerable:!0},values:{enumerable:!0},locked:{enumerable:!0}}),s(Q.from,"from"),s(Q.prototype.cancel,"cancel"),s(Q.prototype.getReader,"getReader"),s(Q.prototype.pipeThrough,"pipeThrough"),s(Q.prototype.pipeTo,"pipeTo"),s(Q.prototype.tee,"tee"),s(Q.prototype.values,"values"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Q.prototype,Symbol.toStringTag,{value:"ReadableStream",configurable:!0}),Object.defineProperty(Q.prototype,Lo,{value:Q.prototype.values,writable:!0,configurable:!0});function yr(n,i,c,h=1,b=()=>1){let w=Object.create(Q.prototype);ns(w);let T=Object.create(Ue.prototype);return aa(w,T,n,i,c,h,b),w}function la(n,i,c){let h=Object.create(Q.prototype);ns(h);let b=Object.create(Fe.prototype);return Mi(h,b,n,i,c,0,void 0),h}function ns(n){n._state="readable",n._reader=void 0,n._storedError=void 0,n._disturbed=!1}function tt(n){return!t(n)||!Object.prototype.hasOwnProperty.call(n,"_readableStreamController")?!1:n instanceof Q}function rt(n){return n._reader!==void 0}function _e(n,i){if(n._disturbed=!0,n._state==="closed")return u(void 0);if(n._state==="errored")return f(n._storedError);br(n);let c=n._reader;if(c!==void 0&&_t(c)){let b=c._readIntoRequests;c._readIntoRequests=new k,b.forEach(w=>{w._closeSteps(void 0)})}let h=n._readableStreamController[Ve](i);return E(h,e)}function br(n){n._state="closed";let i=n._reader;if(i!==void 0&&(ui(i),Ze(i))){let c=i._readRequests;i._readRequests=new k,c.forEach(h=>{h._closeSteps()})}}function ua(n,i){n._state="errored",n._storedError=i;let c=n._reader;c!==void 0&&(vo(c,i),Ze(c)?gi(c,i):ji(c,i))}function xt(n){return new TypeError(`ReadableStream.prototype.${n} can only be used on a ReadableStream`)}function da(n,i){Ce(n,i);let c=n?.highWaterMark;return Co(c,"highWaterMark","QueuingStrategyInit"),{highWaterMark:Ao(c)}}let fa=n=>n.byteLength;s(fa,"size");class on{constructor(i){Ne(i,1,"ByteLengthQueuingStrategy"),i=da(i,"First parameter"),this._byteLengthQueuingStrategyHighWaterMark=i.highWaterMark}get highWaterMark(){if(!ma(this))throw pa("highWaterMark");return this._byteLengthQueuingStrategyHighWaterMark}get size(){if(!ma(this))throw pa("size");return fa}}Object.defineProperties(on.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(on.prototype,Symbol.toStringTag,{value:"ByteLengthQueuingStrategy",configurable:!0});function pa(n){return new TypeError(`ByteLengthQueuingStrategy.prototype.${n} can only be used on a ByteLengthQueuingStrategy`)}function ma(n){return!t(n)||!Object.prototype.hasOwnProperty.call(n,"_byteLengthQueuingStrategyHighWaterMark")?!1:n instanceof on}let ha=()=>1;s(ha,"size");class sn{constructor(i){Ne(i,1,"CountQueuingStrategy"),i=da(i,"First parameter"),this._countQueuingStrategyHighWaterMark=i.highWaterMark}get highWaterMark(){if(!ya(this))throw ga("highWaterMark");return this._countQueuingStrategyHighWaterMark}get size(){if(!ya(this))throw ga("size");return ha}}Object.defineProperties(sn.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(sn.prototype,Symbol.toStringTag,{value:"CountQueuingStrategy",configurable:!0});function ga(n){return new TypeError(`CountQueuingStrategy.prototype.${n} can only be used on a CountQueuingStrategy`)}function ya(n){return!t(n)||!Object.prototype.hasOwnProperty.call(n,"_countQueuingStrategyHighWaterMark")?!1:n instanceof sn}function mf(n,i){Ce(n,i);let c=n?.cancel,h=n?.flush,b=n?.readableType,w=n?.start,T=n?.transform,P=n?.writableType;return{cancel:c===void 0?void 0:bf(c,n,`${i} has member 'cancel' that`),flush:h===void 0?void 0:hf(h,n,`${i} has member 'flush' that`),readableType:b,start:w===void 0?void 0:gf(w,n,`${i} has member 'start' that`),transform:T===void 0?void 0:yf(T,n,`${i} has member 'transform' that`),writableType:P}}function hf(n,i,c){return fe(n,c),h=>C(n,i,[h])}function gf(n,i,c){return fe(n,c),h=>A(n,i,[h])}function yf(n,i,c){return fe(n,c),(h,b)=>C(n,i,[h,b])}function bf(n,i,c){return fe(n,c),h=>C(n,i,[h])}class an{constructor(i={},c={},h={}){i===void 0&&(i=null);let b=Jr(c,"Second parameter"),w=Jr(h,"Third parameter"),T=mf(i,"First parameter");if(T.readableType!==void 0)throw new RangeError("Invalid readableType specified");if(T.writableType!==void 0)throw new RangeError("Invalid writableType specified");let P=pr(w,0),D=Gr(w),I=pr(b,1),L=Gr(b),N,B=p(Te=>{N=Te});Sf(this,B,I,L,P,D),_f(this,T),T.start!==void 0?N(T.start(this._transformStreamController)):N(void 0)}get readable(){if(!ba(this))throw Ta("readable");return this._readable}get writable(){if(!ba(this))throw Ta("writable");return this._writable}}Object.defineProperties(an.prototype,{readable:{enumerable:!0},writable:{enumerable:!0}}),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(an.prototype,Symbol.toStringTag,{value:"TransformStream",configurable:!0});function Sf(n,i,c,h,b,w){function T(){return i}function P(B){return Ef(n,B)}function D(B){return xf(n,B)}function I(){return vf(n)}n._writable=Td(T,P,I,D,c,h);function L(){return Cf(n)}function N(B){return Af(n,B)}n._readable=yr(T,L,N,b,w),n._backpressure=void 0,n._backpressureChangePromise=void 0,n._backpressureChangePromise_resolve=void 0,cn(n,!0),n._transformStreamController=void 0}function ba(n){return!t(n)||!Object.prototype.hasOwnProperty.call(n,"_transformStreamController")?!1:n instanceof an}function Sa(n,i){we(n._readable._readableStreamController,i),os(n,i)}function os(n,i){un(n._transformStreamController),mr(n._writable._writableStreamController,i),ss(n)}function ss(n){n._backpressure&&cn(n,!1)}function cn(n,i){n._backpressureChangePromise!==void 0&&n._backpressureChangePromise_resolve(),n._backpressureChangePromise=p(c=>{n._backpressureChangePromise_resolve=c}),n._backpressure=i}class nt{constructor(){throw new TypeError("Illegal constructor")}get desiredSize(){if(!ln(this))throw dn("desiredSize");let i=this._controlledTransformStream._readable._readableStreamController;return rs(i)}enqueue(i=void 0){if(!ln(this))throw dn("enqueue");wa(this,i)}error(i=void 0){if(!ln(this))throw dn("error");Tf(this,i)}terminate(){if(!ln(this))throw dn("terminate");Rf(this)}}Object.defineProperties(nt.prototype,{enqueue:{enumerable:!0},error:{enumerable:!0},terminate:{enumerable:!0},desiredSize:{enumerable:!0}}),s(nt.prototype.enqueue,"enqueue"),s(nt.prototype.error,"error"),s(nt.prototype.terminate,"terminate"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(nt.prototype,Symbol.toStringTag,{value:"TransformStreamDefaultController",configurable:!0});function ln(n){return!t(n)||!Object.prototype.hasOwnProperty.call(n,"_controlledTransformStream")?!1:n instanceof nt}function wf(n,i,c,h,b){i._controlledTransformStream=n,n._transformStreamController=i,i._transformAlgorithm=c,i._flushAlgorithm=h,i._cancelAlgorithm=b,i._finishPromise=void 0,i._finishPromise_resolve=void 0,i._finishPromise_reject=void 0}function _f(n,i){let c=Object.create(nt.prototype),h,b,w;i.transform!==void 0?h=T=>i.transform(T,c):h=T=>{try{return wa(c,T),u(void 0)}catch(P){return f(P)}},i.flush!==void 0?b=()=>i.flush(c):b=()=>u(void 0),i.cancel!==void 0?w=T=>i.cancel(T):w=()=>u(void 0),wf(n,c,h,b,w)}function un(n){n._transformAlgorithm=void 0,n._flushAlgorithm=void 0,n._cancelAlgorithm=void 0}function wa(n,i){let c=n._controlledTransformStream,h=c._readable._readableStreamController;if(!Bt(h))throw new TypeError("Readable side is not in a state that permits enqueue");try{Ft(h,i)}catch(w){throw os(c,w),c._readable._storedError}Zd(h)!==c._backpressure&&cn(c,!0)}function Tf(n,i){Sa(n._controlledTransformStream,i)}function _a(n,i){let c=n._transformAlgorithm(i);return E(c,void 0,h=>{throw Sa(n._controlledTransformStream,h),h})}function Rf(n){let i=n._controlledTransformStream,c=i._readable._readableStreamController;Et(c);let h=new TypeError("TransformStream terminated");os(i,h)}function Ef(n,i){let c=n._transformStreamController;if(n._backpressure){let h=n._backpressureChangePromise;return E(h,()=>{let b=n._writable;if(b._state==="erroring")throw b._storedError;return _a(c,i)})}return _a(c,i)}function xf(n,i){let c=n._transformStreamController;if(c._finishPromise!==void 0)return c._finishPromise;let h=n._readable;c._finishPromise=p((w,T)=>{c._finishPromise_resolve=w,c._finishPromise_reject=T});let b=c._cancelAlgorithm(i);return un(c),g(b,()=>(h._state==="errored"?Ut(c,h._storedError):(we(h._readableStreamController,i),is(c)),null),w=>(we(h._readableStreamController,w),Ut(c,w),null)),c._finishPromise}function vf(n){let i=n._transformStreamController;if(i._finishPromise!==void 0)return i._finishPromise;let c=n._readable;i._finishPromise=p((b,w)=>{i._finishPromise_resolve=b,i._finishPromise_reject=w});let h=i._flushAlgorithm();return un(i),g(h,()=>(c._state==="errored"?Ut(i,c._storedError):(Et(c._readableStreamController),is(i)),null),b=>(we(c._readableStreamController,b),Ut(i,b),null)),i._finishPromise}function Cf(n){return cn(n,!1),n._backpressureChangePromise}function Af(n,i){let c=n._transformStreamController;if(c._finishPromise!==void 0)return c._finishPromise;let h=n._writable;c._finishPromise=p((w,T)=>{c._finishPromise_resolve=w,c._finishPromise_reject=T});let b=c._cancelAlgorithm(i);return un(c),g(b,()=>(h._state==="errored"?Ut(c,h._storedError):(mr(h._writableStreamController,i),ss(n),is(c)),null),w=>(mr(h._writableStreamController,w),ss(n),Ut(c,w),null)),c._finishPromise}function dn(n){return new TypeError(`TransformStreamDefaultController.prototype.${n} can only be used on a TransformStreamDefaultController`)}function is(n){n._finishPromise_resolve!==void 0&&(n._finishPromise_resolve(),n._finishPromise_resolve=void 0,n._finishPromise_reject=void 0)}function Ut(n,i){n._finishPromise_reject!==void 0&&(R(n._finishPromise),n._finishPromise_reject(i),n._finishPromise_resolve=void 0,n._finishPromise_reject=void 0)}function Ta(n){return new TypeError(`TransformStream.prototype.${n} can only be used on a TransformStream`)}r.ByteLengthQueuingStrategy=on,r.CountQueuingStrategy=sn,r.ReadableByteStreamController=Fe,r.ReadableStream=Q,r.ReadableStreamBYOBReader=Ke,r.ReadableStreamBYOBRequest=bt,r.ReadableStreamDefaultController=Ue,r.ReadableStreamDefaultReader=Ye,r.TransformStream=an,r.TransformStreamDefaultController=nt,r.WritableStream=et,r.WritableStreamDefaultController=Mt,r.WritableStreamDefaultWriter=Be}))});var wl=X(()=>{if(!globalThis.ReadableStream)try{let r=Z("node:process"),{emitWarning:e}=r;try{r.emitWarning=()=>{},Object.assign(globalThis,Z("node:stream/web")),r.emitWarning=e}catch(t){throw r.emitWarning=e,t}}catch{Object.assign(globalThis,Sl())}try{let{Blob:r}=Z("buffer");r&&!r.prototype.stream&&(r.prototype.stream=function(t){let o=0,s=this;return new ReadableStream({type:"bytes",async pull(a){let d=await s.slice(o,Math.min(s.size,o+65536)).arrayBuffer();o+=d.byteLength,a.enqueue(new Uint8Array(d)),o===s.size&&a.close()}})})}catch{}});async function*Ls(r,e=!0){for(let t of r)if("stream"in t)yield*t.stream();else if(ArrayBuffer.isView(t))if(e){let o=t.byteOffset,s=t.byteOffset+t.byteLength;for(;o!==s;){let a=Math.min(s-o,_l),l=t.buffer.slice(o,o+a);o+=l.byteLength,yield new Uint8Array(l)}}else yield t;else{let o=0,s=t;for(;o!==s.size;){let l=await s.slice(o,Math.min(s.size,o+_l)).arrayBuffer();o+=l.byteLength,yield new Uint8Array(l)}}}var gw,_l,Tl,Wm,Ee,Cr=G(()=>{gw=Ht(wl(),1);_l=65536;Tl=class Ns{#e=[];#t="";#r=0;#n="transparent";constructor(e=[],t={}){if(typeof e!="object"||e===null)throw new TypeError("Failed to construct 'Blob': The provided value cannot be converted to a sequence.");if(typeof e[Symbol.iterator]!="function")throw new TypeError("Failed to construct 'Blob': The object must have a callable @@iterator property.");if(typeof t!="object"&&typeof t!="function")throw new TypeError("Failed to construct 'Blob': parameter 2 cannot convert to dictionary.");t===null&&(t={});let o=new TextEncoder;for(let a of e){let l;ArrayBuffer.isView(a)?l=new Uint8Array(a.buffer.slice(a.byteOffset,a.byteOffset+a.byteLength)):a instanceof ArrayBuffer?l=new Uint8Array(a.slice(0)):a instanceof Ns?l=a:l=o.encode(`${a}`),this.#r+=ArrayBuffer.isView(l)?l.byteLength:l.size,this.#e.push(l)}this.#n=`${t.endings===void 0?"transparent":t.endings}`;let s=t.type===void 0?"":String(t.type);this.#t=/^[\x20-\x7E]*$/.test(s)?s:""}get size(){return this.#r}get type(){return this.#t}async text(){let e=new TextDecoder,t="";for await(let o of Ls(this.#e,!1))t+=e.decode(o,{stream:!0});return t+=e.decode(),t}async arrayBuffer(){let e=new Uint8Array(this.size),t=0;for await(let o of Ls(this.#e,!1))e.set(o,t),t+=o.length;return e.buffer}stream(){let e=Ls(this.#e,!0);return new globalThis.ReadableStream({type:"bytes",async pull(t){let o=await e.next();o.done?t.close():t.enqueue(o.value)},async cancel(){await e.return()}})}slice(e=0,t=this.size,o=""){let{size:s}=this,a=e<0?Math.max(s+e,0):Math.min(e,s),l=t<0?Math.max(s+t,0):Math.min(t,s),d=Math.max(l-a,0),p=this.#e,u=[],f=0;for(let g of p){if(f>=d)break;let _=ArrayBuffer.isView(g)?g.byteLength:g.size;if(a&&_<=a)a-=_,l-=_;else{let S;ArrayBuffer.isView(g)?(S=g.subarray(a,Math.min(_,l)),f+=S.byteLength):(S=g.slice(a,Math.min(_,l)),f+=S.size),l-=_,u.push(S),a=0}}let y=new Ns([],{type:String(o).toLowerCase()});return y.#r=d,y.#e=u,y}get[Symbol.toStringTag](){return"Blob"}static[Symbol.hasInstance](e){return e&&typeof e=="object"&&typeof e.constructor=="function"&&(typeof e.stream=="function"||typeof e.arrayBuffer=="function")&&/^(Blob|File)$/.test(e[Symbol.toStringTag])}};Object.defineProperties(Tl.prototype,{size:{enumerable:!0},type:{enumerable:!0},slice:{enumerable:!0}});Wm=Tl,Ee=Wm});var zm,Hm,ft,Ms=G(()=>{Cr();zm=class extends Ee{#e=0;#t="";constructor(e,t,o={}){if(arguments.length<2)throw new TypeError(`Failed to construct 'File': 2 arguments required, but only ${arguments.length} present.`);super(e,o),o===null&&(o={});let s=o.lastModified===void 0?Date.now():Number(o.lastModified);Number.isNaN(s)||(this.#e=s),this.#t=String(t)}get name(){return this.#t}get lastModified(){return this.#e}get[Symbol.toStringTag](){return"File"}static[Symbol.hasInstance](e){return!!e&&e instanceof Ee&&/^(File)$/.test(e[Symbol.toStringTag])}},Hm=zm,ft=Hm});function xl(r,e=Ee){var t=`${Rl()}${Rl()}`.replace(/\./g,"").slice(-28).padStart(32,"-"),o=[],s=`--${t}\r
15
+ Content-Disposition: form-data; name="`;return r.forEach((a,l)=>typeof a=="string"?o.push(s+Fs(l)+`"\r
16
16
  \r
17
17
  ${a.replace(/\r(?!\n)|(?<!\r)\n/g,`\r
18
18
  `)}\r
19
- `):s.push(o+Fo(l)+`"; filename="${Fo(a.name,1)}"\r
19
+ `):o.push(s+Fs(l)+`"; filename="${Fs(a.name,1)}"\r
20
20
  Content-Type: ${a.type||"application/octet-stream"}\r
21
21
  \r
22
22
  `,a,`\r
23
- `)),s.push(`--${t}--`),new e(s,{type:"multipart/form-data; boundary="+t})}var Ar,Hm,Gm,Rl,Jm,El,Fo,Pt,pt,Qn=G(()=>{Cr();Mo();({toStringTag:Ar,iterator:Hm,hasInstance:Gm}=Symbol),Rl=Math.random,Jm="append,set,get,getAll,delete,keys,values,entries,forEach,constructor".split(","),El=(n,e,t)=>(n+="",/^(Blob|File)$/.test(e&&e[Ar])?[(t=t!==void 0?t+"":e[Ar]=="File"?e.name:"blob",n),e.name!==t||e[Ar]=="blob"?new ft([e],t,e):e]:[n,e+""]),Fo=(n,e)=>(e?n:n.replace(/\r?\n|\r/g,`\r
24
- `)).replace(/\n/g,"%0A").replace(/\r/g,"%0D").replace(/"/g,"%22"),Pt=(n,e,t)=>{if(e.length<t)throw new TypeError(`Failed to execute '${n}' on 'FormData': ${t} arguments required, but only ${e.length} present.`)},pt=class{#e=[];constructor(...e){if(e.length)throw new TypeError("Failed to construct 'FormData': parameter 1 is not of type 'HTMLFormElement'.")}get[Ar](){return"FormData"}[Hm](){return this.entries()}static[Gm](e){return e&&typeof e=="object"&&e[Ar]==="FormData"&&!Jm.some(t=>typeof e[t]!="function")}append(...e){Pt("append",arguments,2),this.#e.push(El(...e))}delete(e){Pt("delete",arguments,1),e+="",this.#e=this.#e.filter(([t])=>t!==e)}get(e){Pt("get",arguments,1),e+="";for(var t=this.#e,s=t.length,o=0;o<s;o++)if(t[o][0]===e)return t[o][1];return null}getAll(e,t){return Pt("getAll",arguments,1),t=[],e+="",this.#e.forEach(s=>s[0]===e&&t.push(s[1])),t}has(e){return Pt("has",arguments,1),e+="",this.#e.some(t=>t[0]===e)}forEach(e,t){Pt("forEach",arguments,1);for(var[s,o]of this)e.call(t,o,s,this)}set(...e){Pt("set",arguments,2);var t=[],s=!0;e=El(...e),this.#e.forEach(o=>{o[0]===e[0]?s&&(s=!t.push(e)):t.push(o)}),s&&t.push(e),this.#e=t}*entries(){yield*this.#e}*keys(){for(var[e]of this)yield e}*values(){for(var[,e]of this)yield e}}});var Je,Kn=G(()=>{Je=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}}});var te,Bo=G(()=>{Kn();te=class extends Je{constructor(e,t,s){super(e,t),s&&(this.code=this.errno=s.code,this.erroredSysCall=s.syscall)}}});var es,Uo,Pr,vl,Cl,Al,ts=G(()=>{es=Symbol.toStringTag,Uo=n=>typeof n=="object"&&typeof n.append=="function"&&typeof n.delete=="function"&&typeof n.get=="function"&&typeof n.getAll=="function"&&typeof n.has=="function"&&typeof n.set=="function"&&typeof n.sort=="function"&&n[es]==="URLSearchParams",Pr=n=>n&&typeof n=="object"&&typeof n.arrayBuffer=="function"&&typeof n.type=="string"&&typeof n.stream=="function"&&typeof n.constructor=="function"&&/^(Blob|File)$/.test(n[es]),vl=n=>typeof n=="object"&&(n[es]==="AbortSignal"||n[es]==="EventTarget"),Cl=(n,e)=>{let t=new URL(e).hostname,s=new URL(n).hostname;return t===s||t.endsWith(`.${s}`)},Al=(n,e)=>{let t=new URL(e).protocol,s=new URL(n).protocol;return t===s}});var Il=X((Aw,Pl)=>{if(!globalThis.DOMException)try{let{MessageChannel:n}=Z("worker_threads"),e=new n().port1,t=new ArrayBuffer;e.postMessage(t,[t,t])}catch(n){n.constructor.name==="DOMException"&&(globalThis.DOMException=n.constructor)}Pl.exports=globalThis.DOMException});import{statSync as Ol,createReadStream as Vm,promises as Ym}from"node:fs";import{basename as Zm}from"node:path";var kl,qo,$l,Dl,Ll,Nl,Ml,Fl,rs,jo=G(()=>{kl=Ht(Il(),1);Mo();Cr();({stat:qo}=Ym),$l=(n,e)=>Ml(Ol(n),n,e),Dl=(n,e)=>qo(n).then(t=>Ml(t,n,e)),Ll=(n,e)=>qo(n).then(t=>Fl(t,n,e)),Nl=(n,e)=>Fl(Ol(n),n,e),Ml=(n,e,t="")=>new Ee([new rs({path:e,size:n.size,lastModified:n.mtimeMs,start:0})],{type:t}),Fl=(n,e,t="")=>new ft([new rs({path:e,size:n.size,lastModified:n.mtimeMs,start:0})],Zm(e),{type:t,lastModified:n.mtimeMs}),rs=class n{#e;#t;constructor(e){this.#e=e.path,this.#t=e.start,this.size=e.size,this.lastModified=e.lastModified}slice(e,t){return new n({path:this.#e,lastModified:this.lastModified,size:t-e,start:this.#t+e})}async*stream(){let{mtimeMs:e}=await qo(this.#e);if(e>this.lastModified)throw new kl.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*Vm(this.#e,{start:this.#t,end:this.#t+this.size-1})}get[Symbol.toStringTag](){return"Blob"}}});var Ul={};Ea(Ul,{toFormData:()=>nh});function rh(n){let e=n.match(/\bfilename=("(.*?)"|([^()<>@,;:\\"/[\]?={}\s\t]+))($|;\s)/i);if(!e)return;let t=e[2]||e[3]||"",s=t.slice(t.lastIndexOf("\\")+1);return s=s.replace(/%22/g,'"'),s=s.replace(/&#(\d{4});/g,(o,a)=>String.fromCharCode(a)),s}async function nh(n,e){if(!/multipart/i.test(e))throw new TypeError("Failed to fetch");let t=e.match(/boundary=(?:"([^"]+)"|([^;]+))/i);if(!t)throw new TypeError("no or bad content-type header, no multipart boundary");let s=new Wo(t[1]||t[2]),o,a,l,d,p,u,f=[],y=new pt,g=x=>{l+=R.decode(x,{stream:!0})},_=x=>{f.push(x)},S=()=>{let x=new ft(f,u,{type:p});y.append(d,x)},E=()=>{y.append(d,l)},R=new TextDecoder("utf-8");R.decode(),s.onPartBegin=function(){s.onPartData=g,s.onPartEnd=E,o="",a="",l="",d="",p="",u=null,f.length=0},s.onHeaderField=function(x){o+=R.decode(x,{stream:!0})},s.onHeaderValue=function(x){a+=R.decode(x,{stream:!0})},s.onHeaderEnd=function(){if(a+=R.decode(),o=o.toLowerCase(),o==="content-disposition"){let x=a.match(/\bname=("([^"]*)"|([^()<>@,;:\\"/[\]?={}\s\t]+))/i);x&&(d=x[2]||x[3]||""),u=rh(a),u&&(s.onPartData=_,s.onPartEnd=S)}else o==="content-type"&&(p=a);a="",o=""};for await(let x of n)s.write(x);return s.end(),y}var $e,j,Bl,mt,ns,ss,Xm,Ir,Qm,Km,eh,th,It,Wo,ql=G(()=>{jo();Qn();$e=0,j={START_BOUNDARY:$e++,HEADER_FIELD_START:$e++,HEADER_FIELD:$e++,HEADER_VALUE_START:$e++,HEADER_VALUE:$e++,HEADER_VALUE_ALMOST_DONE:$e++,HEADERS_ALMOST_DONE:$e++,PART_DATA_START:$e++,PART_DATA:$e++,END:$e++},Bl=1,mt={PART_BOUNDARY:Bl,LAST_BOUNDARY:Bl*=2},ns=10,ss=13,Xm=32,Ir=45,Qm=58,Km=97,eh=122,th=n=>n|32,It=()=>{},Wo=class{constructor(e){this.index=0,this.flags=0,this.onHeaderEnd=It,this.onHeaderField=It,this.onHeadersEnd=It,this.onHeaderValue=It,this.onPartBegin=It,this.onPartData=It,this.onPartEnd=It,this.boundaryChars={},e=`\r
25
- --`+e;let t=new Uint8Array(e.length);for(let s=0;s<e.length;s++)t[s]=e.charCodeAt(s),this.boundaryChars[t[s]]=!0;this.boundary=t,this.lookbehind=new Uint8Array(this.boundary.length+8),this.state=j.START_BOUNDARY}write(e){let t=0,s=e.length,o=this.index,{lookbehind:a,boundary:l,boundaryChars:d,index:p,state:u,flags:f}=this,y=this.boundary.length,g=y-1,_=e.length,S,E,R=v=>{this[v+"Mark"]=t},x=v=>{delete this[v+"Mark"]},A=(v,k,$,H)=>{(k===void 0||k!==$)&&this[v](H&&H.subarray(k,$))},C=(v,k)=>{let $=v+"Mark";$ in this&&(k?(A(v,this[$],t,e),delete this[$]):(A(v,this[$],e.length,e),this[$]=0))};for(t=0;t<s;t++)switch(S=e[t],u){case j.START_BOUNDARY:if(p===l.length-2){if(S===Ir)f|=mt.LAST_BOUNDARY;else if(S!==ss)return;p++;break}else if(p-1===l.length-2){if(f&mt.LAST_BOUNDARY&&S===Ir)u=j.END,f=0;else if(!(f&mt.LAST_BOUNDARY)&&S===ns)p=0,A("onPartBegin"),u=j.HEADER_FIELD_START;else return;break}S!==l[p+2]&&(p=-2),S===l[p+2]&&p++;break;case j.HEADER_FIELD_START:u=j.HEADER_FIELD,R("onHeaderField"),p=0;case j.HEADER_FIELD:if(S===ss){x("onHeaderField"),u=j.HEADERS_ALMOST_DONE;break}if(p++,S===Ir)break;if(S===Qm){if(p===1)return;C("onHeaderField",!0),u=j.HEADER_VALUE_START;break}if(E=th(S),E<Km||E>eh)return;break;case j.HEADER_VALUE_START:if(S===Xm)break;R("onHeaderValue"),u=j.HEADER_VALUE;case j.HEADER_VALUE:S===ss&&(C("onHeaderValue",!0),A("onHeaderEnd"),u=j.HEADER_VALUE_ALMOST_DONE);break;case j.HEADER_VALUE_ALMOST_DONE:if(S!==ns)return;u=j.HEADER_FIELD_START;break;case j.HEADERS_ALMOST_DONE:if(S!==ns)return;A("onHeadersEnd"),u=j.PART_DATA_START;break;case j.PART_DATA_START:u=j.PART_DATA,R("onPartData");case j.PART_DATA:if(o=p,p===0){for(t+=g;t<_&&!(e[t]in d);)t+=y;t-=g,S=e[t]}if(p<l.length)l[p]===S?(p===0&&C("onPartData",!0),p++):p=0;else if(p===l.length)p++,S===ss?f|=mt.PART_BOUNDARY:S===Ir?f|=mt.LAST_BOUNDARY:p=0;else if(p-1===l.length)if(f&mt.PART_BOUNDARY){if(p=0,S===ns){f&=~mt.PART_BOUNDARY,A("onPartEnd"),A("onPartBegin"),u=j.HEADER_FIELD_START;break}}else f&mt.LAST_BOUNDARY&&S===Ir?(A("onPartEnd"),u=j.END,f=0):p=0;if(p>0)a[p-1]=S;else if(o>0){let v=new Uint8Array(a.buffer,a.byteOffset,a.byteLength);A("onPartData",0,o,v),o=0,R("onPartData"),t--}break;case j.END:break;default:throw new Error(`Unexpected state entered: ${u}`)}C("onHeaderField"),C("onHeaderValue"),C("onPartData"),this.index=p,this.state=u,this.flags=f}end(){if(this.state===j.HEADER_FIELD_START&&this.index===0||this.state===j.PART_DATA&&this.index===this.boundary.length)this.onPartEnd();else if(this.state!==j.END)throw new Error("MultipartParser.end(): stream ended unexpectedly")}}});import ht,{PassThrough as jl}from"node:stream";import{types as Wl,deprecate as Ho,promisify as sh}from"node:util";import{Buffer as be}from"node:buffer";async function zo(n){if(n[oe].disturbed)throw new TypeError(`body used already for: ${n.url}`);if(n[oe].disturbed=!0,n[oe].error)throw n[oe].error;let{body:e}=n;if(e===null)return be.alloc(0);if(!(e instanceof ht))return be.alloc(0);let t=[],s=0;try{for await(let o of e){if(n.size>0&&s+o.length>n.size){let a=new te(`content size at ${n.url} over limit: ${n.size}`,"max-size");throw e.destroy(a),a}s+=o.length,t.push(o)}}catch(o){throw o instanceof Je?o:new te(`Invalid response body while trying to fetch ${n.url}: ${o.message}`,"system",o)}if(e.readableEnded===!0||e._readableState.ended===!0)try{return t.every(o=>typeof o=="string")?be.from(t.join("")):be.concat(t,s)}catch(o){throw new te(`Could not create Buffer from response body for ${n.url}: ${o.message}`,"system",o)}else throw new te(`Premature close of server response while trying to fetch ${n.url}`)}var oh,oe,De,tr,ih,os,zl,Hl,is=G(()=>{Cr();Qn();Bo();Kn();ts();oh=sh(ht.pipeline),oe=Symbol("Body internals"),De=class{constructor(e,{size:t=0}={}){let s=null;e===null?e=null:Uo(e)?e=be.from(e.toString()):Pr(e)||be.isBuffer(e)||(Wl.isAnyArrayBuffer(e)?e=be.from(e):ArrayBuffer.isView(e)?e=be.from(e.buffer,e.byteOffset,e.byteLength):e instanceof ht||(e instanceof pt?(e=xl(e),s=e.type.split("=")[1]):e=be.from(String(e))));let o=e;be.isBuffer(e)?o=ht.Readable.from(e):Pr(e)&&(o=ht.Readable.from(e.stream())),this[oe]={body:e,stream:o,boundary:s,disturbed:!1,error:null},this.size=t,e instanceof ht&&e.on("error",a=>{let l=a instanceof Je?a:new te(`Invalid response body while trying to fetch ${this.url}: ${a.message}`,"system",a);this[oe].error=l})}get body(){return this[oe].stream}get bodyUsed(){return this[oe].disturbed}async arrayBuffer(){let{buffer:e,byteOffset:t,byteLength:s}=await zo(this);return e.slice(t,t+s)}async formData(){let e=this.headers.get("content-type");if(e.startsWith("application/x-www-form-urlencoded")){let s=new pt,o=new URLSearchParams(await this.text());for(let[a,l]of o)s.append(a,l);return s}let{toFormData:t}=await Promise.resolve().then(()=>(ql(),Ul));return t(this.body,e)}async blob(){let e=this.headers&&this.headers.get("content-type")||this[oe].body&&this[oe].body.type||"",t=await this.arrayBuffer();return new Ee([t],{type:e})}async json(){let e=await this.text();return JSON.parse(e)}async text(){let e=await zo(this);return new TextDecoder().decode(e)}buffer(){return zo(this)}};De.prototype.buffer=Ho(De.prototype.buffer,"Please use 'response.arrayBuffer()' instead of 'response.buffer()'","node-fetch#buffer");Object.defineProperties(De.prototype,{body:{enumerable:!0},bodyUsed:{enumerable:!0},arrayBuffer:{enumerable:!0},blob:{enumerable:!0},json:{enumerable:!0},text:{enumerable:!0},data:{get:Ho(()=>{},"data doesn't exist, use json(), text(), arrayBuffer(), or body instead","https://github.com/node-fetch/node-fetch/issues/1000 (response)")}});tr=(n,e)=>{let t,s,{body:o}=n[oe];if(n.bodyUsed)throw new Error("cannot clone body after it is used");return o instanceof ht&&typeof o.getBoundary!="function"&&(t=new jl({highWaterMark:e}),s=new jl({highWaterMark:e}),o.pipe(t),o.pipe(s),n[oe].stream=t,o=s),o},ih=Ho(n=>n.getBoundary(),"form-data doesn't follow the spec and requires special treatment. Use alternative package","https://github.com/node-fetch/node-fetch/issues/1167"),os=(n,e)=>n===null?null:typeof n=="string"?"text/plain;charset=UTF-8":Uo(n)?"application/x-www-form-urlencoded;charset=UTF-8":Pr(n)?n.type||null:be.isBuffer(n)||Wl.isAnyArrayBuffer(n)||ArrayBuffer.isView(n)?null:n instanceof pt?`multipart/form-data; boundary=${e[oe].boundary}`:n&&typeof n.getBoundary=="function"?`multipart/form-data;boundary=${ih(n)}`:n instanceof ht?null:"text/plain;charset=UTF-8",zl=n=>{let{body:e}=n[oe];return e===null?0:Pr(e)?e.size:be.isBuffer(e)?e.length:e&&typeof e.getLengthSync=="function"&&e.hasKnownLength&&e.hasKnownLength()?e.getLengthSync():null},Hl=async(n,{body:e})=>{e===null?n.end():await oh(e,n)}});import{types as Gl}from"node:util";import cs from"node:http";function Jl(n=[]){return new ie(n.reduce((e,t,s,o)=>(s%2===0&&e.push(o.slice(s,s+2)),e),[]).filter(([e,t])=>{try{return as(e),Go(e,String(t)),!0}catch{return!1}}))}var as,Go,ie,ls=G(()=>{as=typeof cs.validateHeaderName=="function"?cs.validateHeaderName:n=>{if(!/^[\^`\-\w!#$%&'*+.|~]+$/.test(n)){let e=new TypeError(`Header name must be a valid HTTP token [${n}]`);throw Object.defineProperty(e,"code",{value:"ERR_INVALID_HTTP_TOKEN"}),e}},Go=typeof cs.validateHeaderValue=="function"?cs.validateHeaderValue:(n,e)=>{if(/[^\t\u0020-\u007E\u0080-\u00FF]/.test(e)){let t=new TypeError(`Invalid character in header content ["${n}"]`);throw Object.defineProperty(t,"code",{value:"ERR_INVALID_CHAR"}),t}},ie=class n extends URLSearchParams{constructor(e){let t=[];if(e instanceof n){let s=e.raw();for(let[o,a]of Object.entries(s))t.push(...a.map(l=>[o,l]))}else if(e!=null)if(typeof e=="object"&&!Gl.isBoxedPrimitive(e)){let s=e[Symbol.iterator];if(s==null)t.push(...Object.entries(e));else{if(typeof s!="function")throw new TypeError("Header pairs must be iterable");t=[...e].map(o=>{if(typeof o!="object"||Gl.isBoxedPrimitive(o))throw new TypeError("Each header pair must be an iterable object");return[...o]}).map(o=>{if(o.length!==2)throw new TypeError("Each header pair must be a name/value tuple");return[...o]})}}else throw new TypeError("Failed to construct 'Headers': The provided value is not of type '(sequence<sequence<ByteString>> or record<ByteString, ByteString>)");return t=t.length>0?t.map(([s,o])=>(as(s),Go(s,String(o)),[String(s).toLowerCase(),String(o)])):void 0,super(t),new Proxy(this,{get(s,o,a){switch(o){case"append":case"set":return(l,d)=>(as(l),Go(l,String(d)),URLSearchParams.prototype[o].call(s,String(l).toLowerCase(),String(d)));case"delete":case"has":case"getAll":return l=>(as(l),URLSearchParams.prototype[o].call(s,String(l).toLowerCase()));case"keys":return()=>(s.sort(),new Set(URLSearchParams.prototype.keys.call(s)).keys());default:return Reflect.get(s,o,a)}}})}get[Symbol.toStringTag](){return this.constructor.name}toString(){return Object.prototype.toString.call(this)}get(e){let t=this.getAll(e);if(t.length===0)return null;let s=t.join(", ");return/^content-encoding$/i.test(e)&&(s=s.toLowerCase()),s}forEach(e,t=void 0){for(let s of this.keys())Reflect.apply(e,t,[this.get(s),s,this])}*values(){for(let e of this.keys())yield this.get(e)}*entries(){for(let 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)=>{let s=this.getAll(t);return t==="host"?e[t]=s[0]:e[t]=s.length>1?s:s[0],e},{})}};Object.defineProperties(ie.prototype,["get","entries","forEach","values"].reduce((n,e)=>(n[e]={enumerable:!0},n),{}))});var ah,Or,Jo=G(()=>{ah=new Set([301,302,303,307,308]),Or=n=>ah.has(n)});var xe,de,Vl=G(()=>{ls();is();Jo();xe=Symbol("Response internals"),de=class n extends De{constructor(e=null,t={}){super(e,t);let s=t.status!=null?t.status:200,o=new ie(t.headers);if(e!==null&&!o.has("Content-Type")){let a=os(e,this);a&&o.append("Content-Type",a)}this[xe]={type:"default",url:t.url,status:s,statusText:t.statusText||"",headers:o,counter:t.counter,highWaterMark:t.highWaterMark}}get type(){return this[xe].type}get url(){return this[xe].url||""}get status(){return this[xe].status}get ok(){return this[xe].status>=200&&this[xe].status<300}get redirected(){return this[xe].counter>0}get statusText(){return this[xe].statusText}get headers(){return this[xe].headers}get highWaterMark(){return this[xe].highWaterMark}clone(){return new n(tr(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(e,t=302){if(!Or(t))throw new RangeError('Failed to execute "redirect" on "response": Invalid status code');return new n(null,{headers:{location:new URL(e).toString()},status:t})}static error(){let e=new n(null,{status:0,statusText:""});return e[xe].type="error",e}static json(e=void 0,t={}){let s=JSON.stringify(e);if(s===void 0)throw new TypeError("data is not JSON serializable");let o=new ie(t&&t.headers);return o.has("content-type")||o.set("content-type","application/json"),new n(s,{...t,headers:o})}get[Symbol.toStringTag](){return"Response"}};Object.defineProperties(de.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}})});var Yl,Zl=G(()=>{Yl=n=>{if(n.search)return n.search;let e=n.href.length-1,t=n.hash||(n.href[e]==="#"?"#":"");return n.href[e-t.length]==="?"?"?":""}});import{isIP as ch}from"node:net";function Xl(n,e=!1){return n==null||(n=new URL(n),/^(about|blob|data):$/.test(n.protocol))?"no-referrer":(n.username="",n.password="",n.hash="",e&&(n.pathname="",n.search=""),n)}function eu(n){if(!Ql.has(n))throw new TypeError(`Invalid referrerPolicy: ${n}`);return n}function lh(n){if(/^(http|ws)s:$/.test(n.protocol))return!0;let e=n.host.replace(/(^\[)|(]$)/g,""),t=ch(e);return t===4&&/^127\./.test(e)||t===6&&/^(((0+:){7})|(::(0+:){0,6}))0*1$/.test(e)?!0:n.host==="localhost"||n.host.endsWith(".localhost")?!1:n.protocol==="file:"}function rr(n){return/^about:(blank|srcdoc)$/.test(n)||n.protocol==="data:"||/^(blob|filesystem):$/.test(n.protocol)?!0:lh(n)}function tu(n,{referrerURLCallback:e,referrerOriginCallback:t}={}){if(n.referrer==="no-referrer"||n.referrerPolicy==="")return null;let s=n.referrerPolicy;if(n.referrer==="about:client")return"no-referrer";let o=n.referrer,a=Xl(o),l=Xl(o,!0);a.toString().length>4096&&(a=l),e&&(a=e(a)),t&&(l=t(l));let d=new URL(n.url);switch(s){case"no-referrer":return"no-referrer";case"origin":return l;case"unsafe-url":return a;case"strict-origin":return rr(a)&&!rr(d)?"no-referrer":l.toString();case"strict-origin-when-cross-origin":return a.origin===d.origin?a:rr(a)&&!rr(d)?"no-referrer":l;case"same-origin":return a.origin===d.origin?a:"no-referrer";case"origin-when-cross-origin":return a.origin===d.origin?a:l;case"no-referrer-when-downgrade":return rr(a)&&!rr(d)?"no-referrer":a;default:throw new TypeError(`Invalid referrerPolicy: ${s}`)}}function ru(n){let e=(n.get("referrer-policy")||"").split(/[,\s]+/),t="";for(let s of e)s&&Ql.has(s)&&(t=s);return t}var Ql,Kl,Vo=G(()=>{Ql=new Set(["","no-referrer","no-referrer-when-downgrade","same-origin","origin","strict-origin","origin-when-cross-origin","strict-origin-when-cross-origin","unsafe-url"]),Kl="strict-origin-when-cross-origin"});import{format as uh}from"node:url";import{deprecate as dh}from"node:util";var Y,kr,fh,gt,nu,su=G(()=>{ls();is();ts();Zl();Vo();Y=Symbol("Request internals"),kr=n=>typeof n=="object"&&typeof n[Y]=="object",fh=dh(()=>{},".data is not a valid RequestInit property, use .body instead","https://github.com/node-fetch/node-fetch/issues/1000 (request)"),gt=class n extends De{constructor(e,t={}){let s;if(kr(e)?s=new URL(e.url):(s=new URL(e),e={}),s.username!==""||s.password!=="")throw new TypeError(`${s} is an url with embedded credentials.`);let o=t.method||e.method||"GET";if(/^(delete|get|head|options|post|put)$/i.test(o)&&(o=o.toUpperCase()),!kr(t)&&"data"in t&&fh(),(t.body!=null||kr(e)&&e.body!==null)&&(o==="GET"||o==="HEAD"))throw new TypeError("Request with GET/HEAD method cannot have body");let a=t.body?t.body:kr(e)&&e.body!==null?tr(e):null;super(a,{size:t.size||e.size||0});let l=new ie(t.headers||e.headers||{});if(a!==null&&!l.has("Content-Type")){let u=os(a,this);u&&l.set("Content-Type",u)}let d=kr(e)?e.signal:null;if("signal"in t&&(d=t.signal),d!=null&&!vl(d))throw new TypeError("Expected signal to be an instanceof AbortSignal or EventTarget");let p=t.referrer==null?e.referrer:t.referrer;if(p==="")p="no-referrer";else if(p){let u=new URL(p);p=/^about:(\/\/)?client$/.test(u)?"client":u}else p=void 0;this[Y]={method:o,redirect:t.redirect||e.redirect||"follow",headers:l,parsedURL:s,signal:d,referrer:p},this.follow=t.follow===void 0?e.follow===void 0?20:e.follow:t.follow,this.compress=t.compress===void 0?e.compress===void 0?!0: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[Y].method}get url(){return uh(this[Y].parsedURL)}get headers(){return this[Y].headers}get redirect(){return this[Y].redirect}get signal(){return this[Y].signal}get referrer(){if(this[Y].referrer==="no-referrer")return"";if(this[Y].referrer==="client")return"about:client";if(this[Y].referrer)return this[Y].referrer.toString()}get referrerPolicy(){return this[Y].referrerPolicy}set referrerPolicy(e){this[Y].referrerPolicy=eu(e)}clone(){return new n(this)}get[Symbol.toStringTag](){return"Request"}};Object.defineProperties(gt.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}});nu=n=>{let{parsedURL:e}=n[Y],t=new ie(n[Y].headers);t.has("Accept")||t.set("Accept","*/*");let s=null;if(n.body===null&&/^(post|put)$/i.test(n.method)&&(s="0"),n.body!==null){let d=zl(n);typeof d=="number"&&!Number.isNaN(d)&&(s=String(d))}s&&t.set("Content-Length",s),n.referrerPolicy===""&&(n.referrerPolicy=Kl),n.referrer&&n.referrer!=="no-referrer"?n[Y].referrer=tu(n):n[Y].referrer="no-referrer",n[Y].referrer instanceof URL&&t.set("Referer",n.referrer),t.has("User-Agent")||t.set("User-Agent","node-fetch"),n.compress&&!t.has("Accept-Encoding")&&t.set("Accept-Encoding","gzip, deflate, br");let{agent:o}=n;typeof o=="function"&&(o=o(e));let a=Yl(e),l={path:e.pathname+a,method:n.method,headers:t[Symbol.for("nodejs.util.inspect.custom")](),insecureHTTPParser:n.insecureHTTPParser,agent:o};return{parsedURL:e,options:l}}});var $r,ou=G(()=>{Kn();$r=class extends Je{constructor(e,t="aborted"){super(e,t)}}});var cu={};Ea(cu,{AbortError:()=>$r,Blob:()=>Ee,FetchError:()=>te,File:()=>ft,FormData:()=>pt,Headers:()=>ie,Request:()=>gt,Response:()=>de,blobFrom:()=>Dl,blobFromSync:()=>$l,default:()=>Yo,fileFrom:()=>Ll,fileFromSync:()=>Nl,isRedirect:()=>Or});import ph from"node:http";import mh from"node:https";import nr from"node:zlib";import iu,{PassThrough as au,pipeline as sr}from"node:stream";import{Buffer as us}from"node:buffer";async function Yo(n,e){return new Promise((t,s)=>{let o=new gt(n,e),{parsedURL:a,options:l}=nu(o);if(!hh.has(a.protocol))throw new TypeError(`node-fetch cannot load ${n}. URL scheme "${a.protocol.replace(/:$/,"")}" is not supported.`);if(a.protocol==="data:"){let S=gl(o.url),E=new de(S,{headers:{"Content-Type":S.typeFull}});t(E);return}let d=(a.protocol==="https:"?mh:ph).request,{signal:p}=o,u=null,f=()=>{let S=new $r("The operation was aborted.");s(S),o.body&&o.body instanceof iu.Readable&&o.body.destroy(S),!(!u||!u.body)&&u.body.emit("error",S)};if(p&&p.aborted){f();return}let y=()=>{f(),_()},g=d(a.toString(),l);p&&p.addEventListener("abort",y);let _=()=>{g.abort(),p&&p.removeEventListener("abort",y)};g.on("error",S=>{s(new te(`request to ${o.url} failed, reason: ${S.message}`,"system",S)),_()}),gh(g,S=>{u&&u.body&&u.body.destroy(S)}),process.version<"v14"&&g.on("socket",S=>{let E;S.prependListener("end",()=>{E=S._eventsCount}),S.prependListener("close",R=>{if(u&&E<S._eventsCount&&!R){let x=new Error("Premature close");x.code="ERR_STREAM_PREMATURE_CLOSE",u.body.emit("error",x)}})}),g.on("response",S=>{g.setTimeout(0);let E=Jl(S.rawHeaders);if(Or(S.statusCode)){let v=E.get("Location"),k=null;try{k=v===null?null:new URL(v,o.url)}catch{if(o.redirect!=="manual"){s(new te(`uri requested responds with an invalid redirect URL: ${v}`,"invalid-redirect")),_();return}}switch(o.redirect){case"error":s(new te(`uri requested responds with a redirect, redirect mode is set to error: ${o.url}`,"no-redirect")),_();return;case"manual":break;case"follow":{if(k===null)break;if(o.counter>=o.follow){s(new te(`maximum redirect reached at: ${o.url}`,"max-redirect")),_();return}let $={headers:new ie(o.headers),follow:o.follow,counter:o.counter+1,agent:o.agent,compress:o.compress,method:o.method,body:tr(o),signal:o.signal,size:o.size,referrer:o.referrer,referrerPolicy:o.referrerPolicy};if(!Cl(o.url,k)||!Al(o.url,k))for(let Ve of["authorization","www-authenticate","cookie","cookie2"])$.headers.delete(Ve);if(S.statusCode!==303&&o.body&&e.body instanceof iu.Readable){s(new te("Cannot follow redirect with body being a readable stream","unsupported-redirect")),_();return}(S.statusCode===303||(S.statusCode===301||S.statusCode===302)&&o.method==="POST")&&($.method="GET",$.body=void 0,$.headers.delete("content-length"));let H=ru(E);H&&($.referrerPolicy=H),t(Yo(new gt(k,$))),_();return}default:return s(new TypeError(`Redirect option '${o.redirect}' is not a valid value of RequestRedirect`))}}p&&S.once("end",()=>{p.removeEventListener("abort",y)});let R=sr(S,new au,v=>{v&&s(v)});process.version<"v12.10"&&S.on("aborted",y);let x={url:o.url,status:S.statusCode,statusText:S.statusMessage,headers:E,size:o.size,counter:o.counter,highWaterMark:o.highWaterMark},A=E.get("Content-Encoding");if(!o.compress||o.method==="HEAD"||A===null||S.statusCode===204||S.statusCode===304){u=new de(R,x),t(u);return}let C={flush:nr.Z_SYNC_FLUSH,finishFlush:nr.Z_SYNC_FLUSH};if(A==="gzip"||A==="x-gzip"){R=sr(R,nr.createGunzip(C),v=>{v&&s(v)}),u=new de(R,x),t(u);return}if(A==="deflate"||A==="x-deflate"){let v=sr(S,new au,k=>{k&&s(k)});v.once("data",k=>{(k[0]&15)===8?R=sr(R,nr.createInflate(),$=>{$&&s($)}):R=sr(R,nr.createInflateRaw(),$=>{$&&s($)}),u=new de(R,x),t(u)}),v.once("end",()=>{u||(u=new de(R,x),t(u))});return}if(A==="br"){R=sr(R,nr.createBrotliDecompress(),v=>{v&&s(v)}),u=new de(R,x),t(u);return}u=new de(R,x),t(u)}),Hl(g,o).catch(s)})}function gh(n,e){let t=us.from(`0\r
23
+ `)),o.push(`--${t}--`),new e(o,{type:"multipart/form-data; boundary="+t})}var Ar,Gm,Jm,Rl,Vm,El,Fs,Pt,pt,Qn=G(()=>{Cr();Ms();({toStringTag:Ar,iterator:Gm,hasInstance:Jm}=Symbol),Rl=Math.random,Vm="append,set,get,getAll,delete,keys,values,entries,forEach,constructor".split(","),El=(r,e,t)=>(r+="",/^(Blob|File)$/.test(e&&e[Ar])?[(t=t!==void 0?t+"":e[Ar]=="File"?e.name:"blob",r),e.name!==t||e[Ar]=="blob"?new ft([e],t,e):e]:[r,e+""]),Fs=(r,e)=>(e?r:r.replace(/\r?\n|\r/g,`\r
24
+ `)).replace(/\n/g,"%0A").replace(/\r/g,"%0D").replace(/"/g,"%22"),Pt=(r,e,t)=>{if(e.length<t)throw new TypeError(`Failed to execute '${r}' on 'FormData': ${t} arguments required, but only ${e.length} present.`)},pt=class{#e=[];constructor(...e){if(e.length)throw new TypeError("Failed to construct 'FormData': parameter 1 is not of type 'HTMLFormElement'.")}get[Ar](){return"FormData"}[Gm](){return this.entries()}static[Jm](e){return e&&typeof e=="object"&&e[Ar]==="FormData"&&!Vm.some(t=>typeof e[t]!="function")}append(...e){Pt("append",arguments,2),this.#e.push(El(...e))}delete(e){Pt("delete",arguments,1),e+="",this.#e=this.#e.filter(([t])=>t!==e)}get(e){Pt("get",arguments,1),e+="";for(var t=this.#e,o=t.length,s=0;s<o;s++)if(t[s][0]===e)return t[s][1];return null}getAll(e,t){return Pt("getAll",arguments,1),t=[],e+="",this.#e.forEach(o=>o[0]===e&&t.push(o[1])),t}has(e){return Pt("has",arguments,1),e+="",this.#e.some(t=>t[0]===e)}forEach(e,t){Pt("forEach",arguments,1);for(var[o,s]of this)e.call(t,s,o,this)}set(...e){Pt("set",arguments,2);var t=[],o=!0;e=El(...e),this.#e.forEach(s=>{s[0]===e[0]?o&&(o=!t.push(e)):t.push(s)}),o&&t.push(e),this.#e=t}*entries(){yield*this.#e}*keys(){for(var[e]of this)yield e}*values(){for(var[,e]of this)yield e}}});var Je,Kn=G(()=>{Je=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}}});var te,Bs=G(()=>{Kn();te=class extends Je{constructor(e,t,o){super(e,t),o&&(this.code=this.errno=o.code,this.erroredSysCall=o.syscall)}}});var eo,Us,Pr,vl,Cl,Al,to=G(()=>{eo=Symbol.toStringTag,Us=r=>typeof r=="object"&&typeof r.append=="function"&&typeof r.delete=="function"&&typeof r.get=="function"&&typeof r.getAll=="function"&&typeof r.has=="function"&&typeof r.set=="function"&&typeof r.sort=="function"&&r[eo]==="URLSearchParams",Pr=r=>r&&typeof r=="object"&&typeof r.arrayBuffer=="function"&&typeof r.type=="string"&&typeof r.stream=="function"&&typeof r.constructor=="function"&&/^(Blob|File)$/.test(r[eo]),vl=r=>typeof r=="object"&&(r[eo]==="AbortSignal"||r[eo]==="EventTarget"),Cl=(r,e)=>{let t=new URL(e).hostname,o=new URL(r).hostname;return t===o||t.endsWith(`.${o}`)},Al=(r,e)=>{let t=new URL(e).protocol,o=new URL(r).protocol;return t===o}});var Il=X((Pw,Pl)=>{if(!globalThis.DOMException)try{let{MessageChannel:r}=Z("worker_threads"),e=new r().port1,t=new ArrayBuffer;e.postMessage(t,[t,t])}catch(r){r.constructor.name==="DOMException"&&(globalThis.DOMException=r.constructor)}Pl.exports=globalThis.DOMException});import{statSync as Ol,createReadStream as Ym,promises as Zm}from"node:fs";import{basename as Xm}from"node:path";var kl,qs,$l,Dl,Ll,Nl,Ml,Fl,ro,js=G(()=>{kl=Ht(Il(),1);Ms();Cr();({stat:qs}=Zm),$l=(r,e)=>Ml(Ol(r),r,e),Dl=(r,e)=>qs(r).then(t=>Ml(t,r,e)),Ll=(r,e)=>qs(r).then(t=>Fl(t,r,e)),Nl=(r,e)=>Fl(Ol(r),r,e),Ml=(r,e,t="")=>new Ee([new ro({path:e,size:r.size,lastModified:r.mtimeMs,start:0})],{type:t}),Fl=(r,e,t="")=>new ft([new ro({path:e,size:r.size,lastModified:r.mtimeMs,start:0})],Xm(e),{type:t,lastModified:r.mtimeMs}),ro=class r{#e;#t;constructor(e){this.#e=e.path,this.#t=e.start,this.size=e.size,this.lastModified=e.lastModified}slice(e,t){return new r({path:this.#e,lastModified:this.lastModified,size:t-e,start:this.#t+e})}async*stream(){let{mtimeMs:e}=await qs(this.#e);if(e>this.lastModified)throw new kl.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*Ym(this.#e,{start:this.#t,end:this.#t+this.size-1})}get[Symbol.toStringTag](){return"Blob"}}});var Ul={};Ea(Ul,{toFormData:()=>oh});function nh(r){let e=r.match(/\bfilename=("(.*?)"|([^()<>@,;:\\"/[\]?={}\s\t]+))($|;\s)/i);if(!e)return;let t=e[2]||e[3]||"",o=t.slice(t.lastIndexOf("\\")+1);return o=o.replace(/%22/g,'"'),o=o.replace(/&#(\d{4});/g,(s,a)=>String.fromCharCode(a)),o}async function oh(r,e){if(!/multipart/i.test(e))throw new TypeError("Failed to fetch");let t=e.match(/boundary=(?:"([^"]+)"|([^;]+))/i);if(!t)throw new TypeError("no or bad content-type header, no multipart boundary");let o=new Ws(t[1]||t[2]),s,a,l,d,p,u,f=[],y=new pt,g=x=>{l+=R.decode(x,{stream:!0})},_=x=>{f.push(x)},S=()=>{let x=new ft(f,u,{type:p});y.append(d,x)},E=()=>{y.append(d,l)},R=new TextDecoder("utf-8");R.decode(),o.onPartBegin=function(){o.onPartData=g,o.onPartEnd=E,s="",a="",l="",d="",p="",u=null,f.length=0},o.onHeaderField=function(x){s+=R.decode(x,{stream:!0})},o.onHeaderValue=function(x){a+=R.decode(x,{stream:!0})},o.onHeaderEnd=function(){if(a+=R.decode(),s=s.toLowerCase(),s==="content-disposition"){let x=a.match(/\bname=("([^"]*)"|([^()<>@,;:\\"/[\]?={}\s\t]+))/i);x&&(d=x[2]||x[3]||""),u=nh(a),u&&(o.onPartData=_,o.onPartEnd=S)}else s==="content-type"&&(p=a);a="",s=""};for await(let x of r)o.write(x);return o.end(),y}var $e,j,Bl,mt,no,oo,Qm,Ir,Km,eh,th,rh,It,Ws,ql=G(()=>{js();Qn();$e=0,j={START_BOUNDARY:$e++,HEADER_FIELD_START:$e++,HEADER_FIELD:$e++,HEADER_VALUE_START:$e++,HEADER_VALUE:$e++,HEADER_VALUE_ALMOST_DONE:$e++,HEADERS_ALMOST_DONE:$e++,PART_DATA_START:$e++,PART_DATA:$e++,END:$e++},Bl=1,mt={PART_BOUNDARY:Bl,LAST_BOUNDARY:Bl*=2},no=10,oo=13,Qm=32,Ir=45,Km=58,eh=97,th=122,rh=r=>r|32,It=()=>{},Ws=class{constructor(e){this.index=0,this.flags=0,this.onHeaderEnd=It,this.onHeaderField=It,this.onHeadersEnd=It,this.onHeaderValue=It,this.onPartBegin=It,this.onPartData=It,this.onPartEnd=It,this.boundaryChars={},e=`\r
25
+ --`+e;let t=new Uint8Array(e.length);for(let o=0;o<e.length;o++)t[o]=e.charCodeAt(o),this.boundaryChars[t[o]]=!0;this.boundary=t,this.lookbehind=new Uint8Array(this.boundary.length+8),this.state=j.START_BOUNDARY}write(e){let t=0,o=e.length,s=this.index,{lookbehind:a,boundary:l,boundaryChars:d,index:p,state:u,flags:f}=this,y=this.boundary.length,g=y-1,_=e.length,S,E,R=v=>{this[v+"Mark"]=t},x=v=>{delete this[v+"Mark"]},A=(v,k,$,H)=>{(k===void 0||k!==$)&&this[v](H&&H.subarray(k,$))},C=(v,k)=>{let $=v+"Mark";$ in this&&(k?(A(v,this[$],t,e),delete this[$]):(A(v,this[$],e.length,e),this[$]=0))};for(t=0;t<o;t++)switch(S=e[t],u){case j.START_BOUNDARY:if(p===l.length-2){if(S===Ir)f|=mt.LAST_BOUNDARY;else if(S!==oo)return;p++;break}else if(p-1===l.length-2){if(f&mt.LAST_BOUNDARY&&S===Ir)u=j.END,f=0;else if(!(f&mt.LAST_BOUNDARY)&&S===no)p=0,A("onPartBegin"),u=j.HEADER_FIELD_START;else return;break}S!==l[p+2]&&(p=-2),S===l[p+2]&&p++;break;case j.HEADER_FIELD_START:u=j.HEADER_FIELD,R("onHeaderField"),p=0;case j.HEADER_FIELD:if(S===oo){x("onHeaderField"),u=j.HEADERS_ALMOST_DONE;break}if(p++,S===Ir)break;if(S===Km){if(p===1)return;C("onHeaderField",!0),u=j.HEADER_VALUE_START;break}if(E=rh(S),E<eh||E>th)return;break;case j.HEADER_VALUE_START:if(S===Qm)break;R("onHeaderValue"),u=j.HEADER_VALUE;case j.HEADER_VALUE:S===oo&&(C("onHeaderValue",!0),A("onHeaderEnd"),u=j.HEADER_VALUE_ALMOST_DONE);break;case j.HEADER_VALUE_ALMOST_DONE:if(S!==no)return;u=j.HEADER_FIELD_START;break;case j.HEADERS_ALMOST_DONE:if(S!==no)return;A("onHeadersEnd"),u=j.PART_DATA_START;break;case j.PART_DATA_START:u=j.PART_DATA,R("onPartData");case j.PART_DATA:if(s=p,p===0){for(t+=g;t<_&&!(e[t]in d);)t+=y;t-=g,S=e[t]}if(p<l.length)l[p]===S?(p===0&&C("onPartData",!0),p++):p=0;else if(p===l.length)p++,S===oo?f|=mt.PART_BOUNDARY:S===Ir?f|=mt.LAST_BOUNDARY:p=0;else if(p-1===l.length)if(f&mt.PART_BOUNDARY){if(p=0,S===no){f&=~mt.PART_BOUNDARY,A("onPartEnd"),A("onPartBegin"),u=j.HEADER_FIELD_START;break}}else f&mt.LAST_BOUNDARY&&S===Ir?(A("onPartEnd"),u=j.END,f=0):p=0;if(p>0)a[p-1]=S;else if(s>0){let v=new Uint8Array(a.buffer,a.byteOffset,a.byteLength);A("onPartData",0,s,v),s=0,R("onPartData"),t--}break;case j.END:break;default:throw new Error(`Unexpected state entered: ${u}`)}C("onHeaderField"),C("onHeaderValue"),C("onPartData"),this.index=p,this.state=u,this.flags=f}end(){if(this.state===j.HEADER_FIELD_START&&this.index===0||this.state===j.PART_DATA&&this.index===this.boundary.length)this.onPartEnd();else if(this.state!==j.END)throw new Error("MultipartParser.end(): stream ended unexpectedly")}}});import ht,{PassThrough as jl}from"node:stream";import{types as Wl,deprecate as Hs,promisify as sh}from"node:util";import{Buffer as be}from"node:buffer";async function zs(r){if(r[se].disturbed)throw new TypeError(`body used already for: ${r.url}`);if(r[se].disturbed=!0,r[se].error)throw r[se].error;let{body:e}=r;if(e===null)return be.alloc(0);if(!(e instanceof ht))return be.alloc(0);let t=[],o=0;try{for await(let s of e){if(r.size>0&&o+s.length>r.size){let a=new te(`content size at ${r.url} over limit: ${r.size}`,"max-size");throw e.destroy(a),a}o+=s.length,t.push(s)}}catch(s){throw s instanceof Je?s:new te(`Invalid response body while trying to fetch ${r.url}: ${s.message}`,"system",s)}if(e.readableEnded===!0||e._readableState.ended===!0)try{return t.every(s=>typeof s=="string")?be.from(t.join("")):be.concat(t,o)}catch(s){throw new te(`Could not create Buffer from response body for ${r.url}: ${s.message}`,"system",s)}else throw new te(`Premature close of server response while trying to fetch ${r.url}`)}var ih,se,De,tr,ah,so,zl,Hl,io=G(()=>{Cr();Qn();Bs();Kn();to();ih=sh(ht.pipeline),se=Symbol("Body internals"),De=class{constructor(e,{size:t=0}={}){let o=null;e===null?e=null:Us(e)?e=be.from(e.toString()):Pr(e)||be.isBuffer(e)||(Wl.isAnyArrayBuffer(e)?e=be.from(e):ArrayBuffer.isView(e)?e=be.from(e.buffer,e.byteOffset,e.byteLength):e instanceof ht||(e instanceof pt?(e=xl(e),o=e.type.split("=")[1]):e=be.from(String(e))));let s=e;be.isBuffer(e)?s=ht.Readable.from(e):Pr(e)&&(s=ht.Readable.from(e.stream())),this[se]={body:e,stream:s,boundary:o,disturbed:!1,error:null},this.size=t,e instanceof ht&&e.on("error",a=>{let l=a instanceof Je?a:new te(`Invalid response body while trying to fetch ${this.url}: ${a.message}`,"system",a);this[se].error=l})}get body(){return this[se].stream}get bodyUsed(){return this[se].disturbed}async arrayBuffer(){let{buffer:e,byteOffset:t,byteLength:o}=await zs(this);return e.slice(t,t+o)}async formData(){let e=this.headers.get("content-type");if(e.startsWith("application/x-www-form-urlencoded")){let o=new pt,s=new URLSearchParams(await this.text());for(let[a,l]of s)o.append(a,l);return o}let{toFormData:t}=await Promise.resolve().then(()=>(ql(),Ul));return t(this.body,e)}async blob(){let e=this.headers&&this.headers.get("content-type")||this[se].body&&this[se].body.type||"",t=await this.arrayBuffer();return new Ee([t],{type:e})}async json(){let e=await this.text();return JSON.parse(e)}async text(){let e=await zs(this);return new TextDecoder().decode(e)}buffer(){return zs(this)}};De.prototype.buffer=Hs(De.prototype.buffer,"Please use 'response.arrayBuffer()' instead of 'response.buffer()'","node-fetch#buffer");Object.defineProperties(De.prototype,{body:{enumerable:!0},bodyUsed:{enumerable:!0},arrayBuffer:{enumerable:!0},blob:{enumerable:!0},json:{enumerable:!0},text:{enumerable:!0},data:{get:Hs(()=>{},"data doesn't exist, use json(), text(), arrayBuffer(), or body instead","https://github.com/node-fetch/node-fetch/issues/1000 (response)")}});tr=(r,e)=>{let t,o,{body:s}=r[se];if(r.bodyUsed)throw new Error("cannot clone body after it is used");return s instanceof ht&&typeof s.getBoundary!="function"&&(t=new jl({highWaterMark:e}),o=new jl({highWaterMark:e}),s.pipe(t),s.pipe(o),r[se].stream=t,s=o),s},ah=Hs(r=>r.getBoundary(),"form-data doesn't follow the spec and requires special treatment. Use alternative package","https://github.com/node-fetch/node-fetch/issues/1167"),so=(r,e)=>r===null?null:typeof r=="string"?"text/plain;charset=UTF-8":Us(r)?"application/x-www-form-urlencoded;charset=UTF-8":Pr(r)?r.type||null:be.isBuffer(r)||Wl.isAnyArrayBuffer(r)||ArrayBuffer.isView(r)?null:r instanceof pt?`multipart/form-data; boundary=${e[se].boundary}`:r&&typeof r.getBoundary=="function"?`multipart/form-data;boundary=${ah(r)}`:r instanceof ht?null:"text/plain;charset=UTF-8",zl=r=>{let{body:e}=r[se];return e===null?0:Pr(e)?e.size:be.isBuffer(e)?e.length:e&&typeof e.getLengthSync=="function"&&e.hasKnownLength&&e.hasKnownLength()?e.getLengthSync():null},Hl=async(r,{body:e})=>{e===null?r.end():await ih(e,r)}});import{types as Gl}from"node:util";import co from"node:http";function Jl(r=[]){return new ie(r.reduce((e,t,o,s)=>(o%2===0&&e.push(s.slice(o,o+2)),e),[]).filter(([e,t])=>{try{return ao(e),Gs(e,String(t)),!0}catch{return!1}}))}var ao,Gs,ie,lo=G(()=>{ao=typeof co.validateHeaderName=="function"?co.validateHeaderName:r=>{if(!/^[\^`\-\w!#$%&'*+.|~]+$/.test(r)){let e=new TypeError(`Header name must be a valid HTTP token [${r}]`);throw Object.defineProperty(e,"code",{value:"ERR_INVALID_HTTP_TOKEN"}),e}},Gs=typeof co.validateHeaderValue=="function"?co.validateHeaderValue:(r,e)=>{if(/[^\t\u0020-\u007E\u0080-\u00FF]/.test(e)){let t=new TypeError(`Invalid character in header content ["${r}"]`);throw Object.defineProperty(t,"code",{value:"ERR_INVALID_CHAR"}),t}},ie=class r extends URLSearchParams{constructor(e){let t=[];if(e instanceof r){let o=e.raw();for(let[s,a]of Object.entries(o))t.push(...a.map(l=>[s,l]))}else if(e!=null)if(typeof e=="object"&&!Gl.isBoxedPrimitive(e)){let o=e[Symbol.iterator];if(o==null)t.push(...Object.entries(e));else{if(typeof o!="function")throw new TypeError("Header pairs must be iterable");t=[...e].map(s=>{if(typeof s!="object"||Gl.isBoxedPrimitive(s))throw new TypeError("Each header pair must be an iterable object");return[...s]}).map(s=>{if(s.length!==2)throw new TypeError("Each header pair must be a name/value tuple");return[...s]})}}else throw new TypeError("Failed to construct 'Headers': The provided value is not of type '(sequence<sequence<ByteString>> or record<ByteString, ByteString>)");return t=t.length>0?t.map(([o,s])=>(ao(o),Gs(o,String(s)),[String(o).toLowerCase(),String(s)])):void 0,super(t),new Proxy(this,{get(o,s,a){switch(s){case"append":case"set":return(l,d)=>(ao(l),Gs(l,String(d)),URLSearchParams.prototype[s].call(o,String(l).toLowerCase(),String(d)));case"delete":case"has":case"getAll":return l=>(ao(l),URLSearchParams.prototype[s].call(o,String(l).toLowerCase()));case"keys":return()=>(o.sort(),new Set(URLSearchParams.prototype.keys.call(o)).keys());default:return Reflect.get(o,s,a)}}})}get[Symbol.toStringTag](){return this.constructor.name}toString(){return Object.prototype.toString.call(this)}get(e){let t=this.getAll(e);if(t.length===0)return null;let o=t.join(", ");return/^content-encoding$/i.test(e)&&(o=o.toLowerCase()),o}forEach(e,t=void 0){for(let o of this.keys())Reflect.apply(e,t,[this.get(o),o,this])}*values(){for(let e of this.keys())yield this.get(e)}*entries(){for(let 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)=>{let o=this.getAll(t);return t==="host"?e[t]=o[0]:e[t]=o.length>1?o:o[0],e},{})}};Object.defineProperties(ie.prototype,["get","entries","forEach","values"].reduce((r,e)=>(r[e]={enumerable:!0},r),{}))});var ch,Or,Js=G(()=>{ch=new Set([301,302,303,307,308]),Or=r=>ch.has(r)});var xe,de,Vl=G(()=>{lo();io();Js();xe=Symbol("Response internals"),de=class r extends De{constructor(e=null,t={}){super(e,t);let o=t.status!=null?t.status:200,s=new ie(t.headers);if(e!==null&&!s.has("Content-Type")){let a=so(e,this);a&&s.append("Content-Type",a)}this[xe]={type:"default",url:t.url,status:o,statusText:t.statusText||"",headers:s,counter:t.counter,highWaterMark:t.highWaterMark}}get type(){return this[xe].type}get url(){return this[xe].url||""}get status(){return this[xe].status}get ok(){return this[xe].status>=200&&this[xe].status<300}get redirected(){return this[xe].counter>0}get statusText(){return this[xe].statusText}get headers(){return this[xe].headers}get highWaterMark(){return this[xe].highWaterMark}clone(){return new r(tr(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(e,t=302){if(!Or(t))throw new RangeError('Failed to execute "redirect" on "response": Invalid status code');return new r(null,{headers:{location:new URL(e).toString()},status:t})}static error(){let e=new r(null,{status:0,statusText:""});return e[xe].type="error",e}static json(e=void 0,t={}){let o=JSON.stringify(e);if(o===void 0)throw new TypeError("data is not JSON serializable");let s=new ie(t&&t.headers);return s.has("content-type")||s.set("content-type","application/json"),new r(o,{...t,headers:s})}get[Symbol.toStringTag](){return"Response"}};Object.defineProperties(de.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}})});var Yl,Zl=G(()=>{Yl=r=>{if(r.search)return r.search;let e=r.href.length-1,t=r.hash||(r.href[e]==="#"?"#":"");return r.href[e-t.length]==="?"?"?":""}});import{isIP as lh}from"node:net";function Xl(r,e=!1){return r==null||(r=new URL(r),/^(about|blob|data):$/.test(r.protocol))?"no-referrer":(r.username="",r.password="",r.hash="",e&&(r.pathname="",r.search=""),r)}function eu(r){if(!Ql.has(r))throw new TypeError(`Invalid referrerPolicy: ${r}`);return r}function uh(r){if(/^(http|ws)s:$/.test(r.protocol))return!0;let e=r.host.replace(/(^\[)|(]$)/g,""),t=lh(e);return t===4&&/^127\./.test(e)||t===6&&/^(((0+:){7})|(::(0+:){0,6}))0*1$/.test(e)?!0:r.host==="localhost"||r.host.endsWith(".localhost")?!1:r.protocol==="file:"}function rr(r){return/^about:(blank|srcdoc)$/.test(r)||r.protocol==="data:"||/^(blob|filesystem):$/.test(r.protocol)?!0:uh(r)}function tu(r,{referrerURLCallback:e,referrerOriginCallback:t}={}){if(r.referrer==="no-referrer"||r.referrerPolicy==="")return null;let o=r.referrerPolicy;if(r.referrer==="about:client")return"no-referrer";let s=r.referrer,a=Xl(s),l=Xl(s,!0);a.toString().length>4096&&(a=l),e&&(a=e(a)),t&&(l=t(l));let d=new URL(r.url);switch(o){case"no-referrer":return"no-referrer";case"origin":return l;case"unsafe-url":return a;case"strict-origin":return rr(a)&&!rr(d)?"no-referrer":l.toString();case"strict-origin-when-cross-origin":return a.origin===d.origin?a:rr(a)&&!rr(d)?"no-referrer":l;case"same-origin":return a.origin===d.origin?a:"no-referrer";case"origin-when-cross-origin":return a.origin===d.origin?a:l;case"no-referrer-when-downgrade":return rr(a)&&!rr(d)?"no-referrer":a;default:throw new TypeError(`Invalid referrerPolicy: ${o}`)}}function ru(r){let e=(r.get("referrer-policy")||"").split(/[,\s]+/),t="";for(let o of e)o&&Ql.has(o)&&(t=o);return t}var Ql,Kl,Vs=G(()=>{Ql=new Set(["","no-referrer","no-referrer-when-downgrade","same-origin","origin","strict-origin","origin-when-cross-origin","strict-origin-when-cross-origin","unsafe-url"]),Kl="strict-origin-when-cross-origin"});import{format as dh}from"node:url";import{deprecate as fh}from"node:util";var Y,kr,ph,gt,nu,ou=G(()=>{lo();io();to();Zl();Vs();Y=Symbol("Request internals"),kr=r=>typeof r=="object"&&typeof r[Y]=="object",ph=fh(()=>{},".data is not a valid RequestInit property, use .body instead","https://github.com/node-fetch/node-fetch/issues/1000 (request)"),gt=class r extends De{constructor(e,t={}){let o;if(kr(e)?o=new URL(e.url):(o=new URL(e),e={}),o.username!==""||o.password!=="")throw new TypeError(`${o} is an url with embedded credentials.`);let s=t.method||e.method||"GET";if(/^(delete|get|head|options|post|put)$/i.test(s)&&(s=s.toUpperCase()),!kr(t)&&"data"in t&&ph(),(t.body!=null||kr(e)&&e.body!==null)&&(s==="GET"||s==="HEAD"))throw new TypeError("Request with GET/HEAD method cannot have body");let a=t.body?t.body:kr(e)&&e.body!==null?tr(e):null;super(a,{size:t.size||e.size||0});let l=new ie(t.headers||e.headers||{});if(a!==null&&!l.has("Content-Type")){let u=so(a,this);u&&l.set("Content-Type",u)}let d=kr(e)?e.signal:null;if("signal"in t&&(d=t.signal),d!=null&&!vl(d))throw new TypeError("Expected signal to be an instanceof AbortSignal or EventTarget");let p=t.referrer==null?e.referrer:t.referrer;if(p==="")p="no-referrer";else if(p){let u=new URL(p);p=/^about:(\/\/)?client$/.test(u)?"client":u}else p=void 0;this[Y]={method:s,redirect:t.redirect||e.redirect||"follow",headers:l,parsedURL:o,signal:d,referrer:p},this.follow=t.follow===void 0?e.follow===void 0?20:e.follow:t.follow,this.compress=t.compress===void 0?e.compress===void 0?!0: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[Y].method}get url(){return dh(this[Y].parsedURL)}get headers(){return this[Y].headers}get redirect(){return this[Y].redirect}get signal(){return this[Y].signal}get referrer(){if(this[Y].referrer==="no-referrer")return"";if(this[Y].referrer==="client")return"about:client";if(this[Y].referrer)return this[Y].referrer.toString()}get referrerPolicy(){return this[Y].referrerPolicy}set referrerPolicy(e){this[Y].referrerPolicy=eu(e)}clone(){return new r(this)}get[Symbol.toStringTag](){return"Request"}};Object.defineProperties(gt.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}});nu=r=>{let{parsedURL:e}=r[Y],t=new ie(r[Y].headers);t.has("Accept")||t.set("Accept","*/*");let o=null;if(r.body===null&&/^(post|put)$/i.test(r.method)&&(o="0"),r.body!==null){let d=zl(r);typeof d=="number"&&!Number.isNaN(d)&&(o=String(d))}o&&t.set("Content-Length",o),r.referrerPolicy===""&&(r.referrerPolicy=Kl),r.referrer&&r.referrer!=="no-referrer"?r[Y].referrer=tu(r):r[Y].referrer="no-referrer",r[Y].referrer instanceof URL&&t.set("Referer",r.referrer),t.has("User-Agent")||t.set("User-Agent","node-fetch"),r.compress&&!t.has("Accept-Encoding")&&t.set("Accept-Encoding","gzip, deflate, br");let{agent:s}=r;typeof s=="function"&&(s=s(e));let a=Yl(e),l={path:e.pathname+a,method:r.method,headers:t[Symbol.for("nodejs.util.inspect.custom")](),insecureHTTPParser:r.insecureHTTPParser,agent:s};return{parsedURL:e,options:l}}});var $r,su=G(()=>{Kn();$r=class extends Je{constructor(e,t="aborted"){super(e,t)}}});var cu={};Ea(cu,{AbortError:()=>$r,Blob:()=>Ee,FetchError:()=>te,File:()=>ft,FormData:()=>pt,Headers:()=>ie,Request:()=>gt,Response:()=>de,blobFrom:()=>Dl,blobFromSync:()=>$l,default:()=>Ys,fileFrom:()=>Ll,fileFromSync:()=>Nl,isRedirect:()=>Or});import mh from"node:http";import hh from"node:https";import nr from"node:zlib";import iu,{PassThrough as au,pipeline as or}from"node:stream";import{Buffer as uo}from"node:buffer";async function Ys(r,e){return new Promise((t,o)=>{let s=new gt(r,e),{parsedURL:a,options:l}=nu(s);if(!gh.has(a.protocol))throw new TypeError(`node-fetch cannot load ${r}. URL scheme "${a.protocol.replace(/:$/,"")}" is not supported.`);if(a.protocol==="data:"){let S=gl(s.url),E=new de(S,{headers:{"Content-Type":S.typeFull}});t(E);return}let d=(a.protocol==="https:"?hh:mh).request,{signal:p}=s,u=null,f=()=>{let S=new $r("The operation was aborted.");o(S),s.body&&s.body instanceof iu.Readable&&s.body.destroy(S),!(!u||!u.body)&&u.body.emit("error",S)};if(p&&p.aborted){f();return}let y=()=>{f(),_()},g=d(a.toString(),l);p&&p.addEventListener("abort",y);let _=()=>{g.abort(),p&&p.removeEventListener("abort",y)};g.on("error",S=>{o(new te(`request to ${s.url} failed, reason: ${S.message}`,"system",S)),_()}),yh(g,S=>{u&&u.body&&u.body.destroy(S)}),process.version<"v14"&&g.on("socket",S=>{let E;S.prependListener("end",()=>{E=S._eventsCount}),S.prependListener("close",R=>{if(u&&E<S._eventsCount&&!R){let x=new Error("Premature close");x.code="ERR_STREAM_PREMATURE_CLOSE",u.body.emit("error",x)}})}),g.on("response",S=>{g.setTimeout(0);let E=Jl(S.rawHeaders);if(Or(S.statusCode)){let v=E.get("Location"),k=null;try{k=v===null?null:new URL(v,s.url)}catch{if(s.redirect!=="manual"){o(new te(`uri requested responds with an invalid redirect URL: ${v}`,"invalid-redirect")),_();return}}switch(s.redirect){case"error":o(new te(`uri requested responds with a redirect, redirect mode is set to error: ${s.url}`,"no-redirect")),_();return;case"manual":break;case"follow":{if(k===null)break;if(s.counter>=s.follow){o(new te(`maximum redirect reached at: ${s.url}`,"max-redirect")),_();return}let $={headers:new ie(s.headers),follow:s.follow,counter:s.counter+1,agent:s.agent,compress:s.compress,method:s.method,body:tr(s),signal:s.signal,size:s.size,referrer:s.referrer,referrerPolicy:s.referrerPolicy};if(!Cl(s.url,k)||!Al(s.url,k))for(let Ve of["authorization","www-authenticate","cookie","cookie2"])$.headers.delete(Ve);if(S.statusCode!==303&&s.body&&e.body instanceof iu.Readable){o(new te("Cannot follow redirect with body being a readable stream","unsupported-redirect")),_();return}(S.statusCode===303||(S.statusCode===301||S.statusCode===302)&&s.method==="POST")&&($.method="GET",$.body=void 0,$.headers.delete("content-length"));let H=ru(E);H&&($.referrerPolicy=H),t(Ys(new gt(k,$))),_();return}default:return o(new TypeError(`Redirect option '${s.redirect}' is not a valid value of RequestRedirect`))}}p&&S.once("end",()=>{p.removeEventListener("abort",y)});let R=or(S,new au,v=>{v&&o(v)});process.version<"v12.10"&&S.on("aborted",y);let x={url:s.url,status:S.statusCode,statusText:S.statusMessage,headers:E,size:s.size,counter:s.counter,highWaterMark:s.highWaterMark},A=E.get("Content-Encoding");if(!s.compress||s.method==="HEAD"||A===null||S.statusCode===204||S.statusCode===304){u=new de(R,x),t(u);return}let C={flush:nr.Z_SYNC_FLUSH,finishFlush:nr.Z_SYNC_FLUSH};if(A==="gzip"||A==="x-gzip"){R=or(R,nr.createGunzip(C),v=>{v&&o(v)}),u=new de(R,x),t(u);return}if(A==="deflate"||A==="x-deflate"){let v=or(S,new au,k=>{k&&o(k)});v.once("data",k=>{(k[0]&15)===8?R=or(R,nr.createInflate(),$=>{$&&o($)}):R=or(R,nr.createInflateRaw(),$=>{$&&o($)}),u=new de(R,x),t(u)}),v.once("end",()=>{u||(u=new de(R,x),t(u))});return}if(A==="br"){R=or(R,nr.createBrotliDecompress(),v=>{v&&o(v)}),u=new de(R,x),t(u);return}u=new de(R,x),t(u)}),Hl(g,s).catch(o)})}function yh(r,e){let t=uo.from(`0\r
26
26
  \r
27
- `),s=!1,o=!1,a;n.on("response",l=>{let{headers:d}=l;s=d["transfer-encoding"]==="chunked"&&!d["content-length"]}),n.on("socket",l=>{let d=()=>{if(s&&!o){let u=new Error("Premature close");u.code="ERR_STREAM_PREMATURE_CLOSE",e(u)}},p=u=>{o=us.compare(u.slice(-5),t)===0,!o&&a&&(o=us.compare(a.slice(-3),t.slice(0,3))===0&&us.compare(u.slice(-2),t.slice(3))===0),a=u};l.prependListener("close",d),l.on("data",p),n.on("close",()=>{l.removeListener("close",d),l.removeListener("data",p)})})}var hh,lu=G(()=>{yl();is();Vl();ls();su();Bo();ou();Jo();Qn();ts();Vo();jo();hh=new Set(["data:","http:","https:"])});import{realpathSync as Mu}from"node:fs";import{fileURLToPath as Ig}from"node:url";import{Server as Og}from"@modelcontextprotocol/sdk/server/index.js";import{StdioServerTransport as kg}from"@modelcontextprotocol/sdk/server/stdio.js";import{buildCli as $g}from"@n24q02m/hull";import{localAuthContext as zf,runWithAuthContext as Hf}from"@n24q02m/hull/token-auth";import{PerPluginStore as Lf}from"@n24q02m/hull/storage";var ce="workspace",We="workspace",pn="better-workspace",xa="https://accounts.google.com/o/oauth2/v2/auth",va="https://oauth2.googleapis.com/token",mn=["openid","email","profile"];function vt(n){if(typeof n!="string")return;let e=n.split(".")[1];if(e)try{let t=JSON.parse(Buffer.from(e,"base64url").toString("utf8"));return typeof t.email=="string"?t.email.toLowerCase():void 0}catch{return}}function Ca(n){return n!==null&&n.version===void 0&&typeof n.access_token=="string"}var Aa="(unidentified)",Sr=n=>n.trim().toLowerCase(),hn=class{constructor(e=null){this.store=new Lf(We,e)}async load(){let e=await this.store.load();if(e===null)return null;if(!Ca(e)){let a=e;return a.version===2&&a.accounts?a:null}let t=e,s=vt(t.id_token);if(!s)return null;let o={version:2,accounts:{[s]:t},primary:s};return await this.store.save(o),o}async loadLegacy(){let e=await this.store.load();return Ca(e)?e:null}async adoptLegacy(e){let t=await this.loadLegacy();if(!t)return null;let s=Sr(e);return await this.store.save({version:2,accounts:{[s]:t},primary:s}),t}async put(e,t,s={}){let o=Sr(e),a=await this.load(),l={};if(!a){let f=await this.loadLegacy();if(f){if(!s.absorbLegacy)throw new Error('Refusing to overwrite credentials stored in the older single-account layout. Adopt them first, or clear them deliberately with config(action="setup_reset") before adding a new account.');l={[Aa]:f}}}let d=a??{version:2,accounts:l,primary:o},p={...d.accounts,[o]:t},u=s.makePrimary||!d.accounts[d.primary]?o:d.primary;await this.store.save({version:2,accounts:p,primary:u})}async get(e){let t=await this.load();if(!t)return null;let s=e?Sr(e):t.primary,o=t.accounts[s];return o?{email:s,record:o}:null}async list(){let e=await this.load();return e?{accounts:Object.keys(e.accounts).sort(),primary:e.primary}:{accounts:[],primary:null}}async remove(e){let t=await this.load();if(!t)return{removed:!1,newPrimary:null};let s=Sr(e);if(!t.accounts[s])return{removed:!1,newPrimary:t.primary};let o={...t.accounts};delete o[s];let a=Object.keys(o);if(a.length===0)return await this.store.clear(),{removed:!0,newPrimary:null};let l=a.find(p=>p!==Aa)??a[0],d=t.primary===s?l:t.primary;return await this.store.save({version:2,accounts:o,primary:d}),{removed:!0,newPrimary:d}}async setPrimary(e){let t=await this.load(),s=Sr(e);if(!t?.accounts[s])throw new Error(`Account ${s} is not configured.`);await this.store.save({...t,primary:s})}async clear(){await this.store.clear()}};var Nf=1e4;function wr(n){n.close().catch(e=>{console.error(`[${ce}] failed to close the consent callback server:`,e)})}function gn(n,e=Nf){let t=setTimeout(()=>wr(n),e);typeof t.unref=="function"&&t.unref()}import{currentUser as Mf}from"@n24q02m/hull/token-auth";function _r(){let n=Mf();return n.mode==="no-auth"?void 0:n.namespace}function Gt(){let n=_r();return n===void 0?"workspace auth":`workspace auth --user ${n}`}import{google as Pa}from"googleapis";var yn=class{constructor(e,t=null){this.scopes=e;this.accounts=new hn(t)}async saveTokens(e,t={}){let s={...e},o=e.expires_in;s.expiry_date===void 0&&typeof o=="number"&&(s.expiry_date=Date.now()+o*1e3);let a=t.email?.trim().toLowerCase()??vt(e.id_token);if(!a)throw new Error("Cannot store Google tokens without an account email (no id_token email claim and none passed).");return await this.accounts.put(a,s,{makePrimary:t.makePrimary,absorbLegacy:!0}),a}async listAccounts(){return this.accounts.list()}async removeAccount(e){return this.accounts.remove(e)}async setPrimary(e){return this.accounts.setPrimary(e)}async clear(){await this.accounts.clear()}async fetchAccountEmail(e){try{let{data:t}=await Pa.oauth2({version:"v2",auth:e}).userinfo.get();return typeof t.email=="string"?t.email.toLowerCase():void 0}catch{return}}buildBareClient(e){let t=new Pa.auth.OAuth2({clientId:process.env.GOOGLE_OAUTH_CLIENT_ID,clientSecret:process.env.GOOGLE_OAUTH_CLIENT_SECRET});return t.setCredentials({access_token:e.access_token,refresh_token:e.refresh_token,expiry_date:e.expiry_date,scope:e.scope,token_type:e.token_type}),t}buildClient(e,t){let s=this.buildBareClient(t);return s.on("tokens",o=>{this.saveTokens({...t,...o},{email:e})}),s}async getAuthenticatedClient(e){let t=await this.accounts.get(e);if(t)return this.buildClient(t.email,t.record);if(!e){let s=await this.accounts.loadLegacy();if(s){let o=await this.fetchAccountEmail(this.buildBareClient(s));if(o)return await this.accounts.adoptLegacy(o),this.buildClient(o,s);throw new Error('Stored Google credentials are from an older single-account layout and the account email could not be resolved. Run config(action="account_add") to re-authorize, or re-authorize the existing account.')}}if(e){let{accounts:s}=await this.accounts.list(),o=s.length>0?` Configured accounts: ${s.join(", ")}.`:"";throw new Error(`Account ${e.trim().toLowerCase()} is not configured.${o}`)}throw new Error(`Google account not configured. Run \`${Gt()}\` on the host to complete the Google consent (see setup docs).`)}};var Oa="",Ia=new Map,Tr=new Map;function bn(){return _r()??Oa}function Ct(){return Tr.get(bn())??"awaiting_setup"}function le(){let n=bn(),e=Ia.get(n);return e||(e=new yn(mn,n===Oa?null:n),Ia.set(n,e)),e}async function ot(){let n=bn(),e=le(),{accounts:t}=await e.listAccounts();if(t.length>0)return Tr.set(n,"configured"),"configured";try{return await e.getAuthenticatedClient(),Tr.set(n,"configured"),"configured"}catch{return Tr.set(n,"awaiting_setup"),"awaiting_setup"}}async function ka(){await le().clear(),Tr.set(bn(),"awaiting_setup")}import{randomBytes as Ff,timingSafeEqual as Bf}from"node:crypto";import{createServer as Uf}from"node:http";var Rr="127.0.0.1",$a="/callback";function co(n){return n.replace(/[&<>"']/g,e=>{switch(e){case"&":return"&amp;";case"<":return"&lt;";case">":return"&gt;";case'"':return"&quot;";default:return"&#39;"}})}function it(n,e,t,s){n.writeHead(e,{"Content-Type":"text/html; charset=utf-8","Cache-Control":"no-store"}),n.end(`<!doctype html><meta charset="utf-8"><title>${co(t)}</title><h1>${co(t)}</h1><p>${co(s)}</p>`)}function qf(n,e){let t=Buffer.from(n),s=Buffer.from(e);return t.length===s.length&&Bf(t,s)}async function jf(n,e,t){let s=new URLSearchParams({grant_type:"authorization_code",code:e,client_id:n.clientId,client_secret:n.clientSecret,redirect_uri:t}),o=await fetch(va,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:s});if(!o.ok)throw new Error(`Google token exchange failed (HTTP ${o.status}).`);return await o.json()}async function Sn(n){let e=Ff(16).toString("base64url"),t="",s=async(d,p)=>{let u=new URL(d.url??"/",`http://${Rr}`);if(d.method!=="GET"){it(p,405,"Method not allowed","Use GET.");return}if(u.pathname==="/"){let g=new URL(xa);g.search=new URLSearchParams({client_id:n.clientId,redirect_uri:t,response_type:"code",scope:n.scopes.join(" "),state:e,access_type:"offline",prompt:"consent"}).toString(),p.writeHead(302,{Location:g.toString(),"Cache-Control":"no-store"}),p.end();return}if(u.pathname!==$a){it(p,404,"Not found","Nothing here.");return}let f=u.searchParams.get("state")??"";if(!qf(f,e)){it(p,400,"Authorization failed","The consent response did not match this session. Start again.");return}if(u.searchParams.get("error")){it(p,400,"Authorization cancelled","Google did not grant access. Nothing was stored.");return}let y=u.searchParams.get("code");if(!y){it(p,400,"Authorization failed","Google returned no authorization code.");return}try{let g=await jf(n,y,t);await n.onTokens(g),it(p,200,"Authorization complete","You can close this tab.")}catch(g){let _=g instanceof Error?g.message:"Authorization failed.";it(p,500,"Authorization failed",_)}},o=Uf((d,p)=>{s(d,p).catch(u=>{console.error("[workspace] consent request failed:",u),p.headersSent||it(p,500,"Authorization failed","Unexpected error.")})}),a=Promise.withResolvers();o.once("error",a.reject),o.listen(n.port??0,Rr,()=>{o.off("error",a.reject),a.resolve()}),await a.promise;let{port:l}=o.address();return t=`http://${Rr}:${l}${$a}`,{url:`http://${Rr}:${l}/`,host:Rr,port:l,close:()=>{let d=Promise.withResolvers();return o.close(p=>p?d.reject(p):d.resolve()),o.closeIdleConnections(),d.promise}}}var lo=["openid","email","profile","https://www.googleapis.com/auth/documents","https://www.googleapis.com/auth/drive","https://www.googleapis.com/auth/calendar","https://www.googleapis.com/auth/gmail.modify","https://www.googleapis.com/auth/spreadsheets","https://www.googleapis.com/auth/presentations","https://www.googleapis.com/auth/tasks","https://www.googleapis.com/auth/chat.messages","https://www.googleapis.com/auth/contacts.readonly","https://www.googleapis.com/auth/forms.body","https://www.googleapis.com/auth/forms.responses.readonly"];async function Da(n={}){let e=process.env.GOOGLE_OAUTH_CLIENT_ID,t=process.env.GOOGLE_OAUTH_CLIENT_SECRET;if(!e||!t)throw new Error("GOOGLE_OAUTH_CLIENT_ID / GOOGLE_OAUTH_CLIENT_SECRET required for OAuth setup.");let s=Promise.withResolvers(),o=null,a=await Sn({clientId:e,clientSecret:t,scopes:lo,onTokens:async l=>{if(o===null){o=le().saveTokens(l).then(p=>(s.resolve(),p),p=>{throw s.reject(p),p}),await o;return}let d=await o;if(vt(l.id_token)!==d)throw new Error(`Setup already completed for ${d}. Use config(action="account_add") to add another account.`)}});process.stderr.write(`[${ce}] Google authorization required. Open ${a.url} in a browser to continue.
28
- `);try{await s.promise}catch(l){throw wr(a),l}gn(a,n.graceMs)}var Wf=600*1e3;async function wn(n={}){let e=process.env.GOOGLE_OAUTH_CLIENT_ID,t=process.env.GOOGLE_OAUTH_CLIENT_SECRET;if(!e||!t)throw new Error("GOOGLE_OAUTH_CLIENT_ID / GOOGLE_OAUTH_CLIENT_SECRET required to add an account.");let s=Promise.withResolvers(),o=null,a=await Sn({clientId:e,clientSecret:t,scopes:lo,onTokens:async u=>{if(o===null){o=le().saveTokens(u,{makePrimary:n.makePrimary}).then(y=>(s.resolve(y),y),y=>{throw s.reject(y),y}),await o;return}let f=await o;if(vt(u.id_token)!==f)throw new Error(`This add-account flow already completed for ${f}. Call config(action="account_add") again to add a different account.`)}}),l=Promise.withResolvers(),d=setTimeout(()=>l.reject(new Error("Add-account flow timed out before the Google consent completed.")),n.ttlMs??Wf);typeof d.unref=="function"&&d.unref();let p=Promise.race([s.promise,l.promise]);return p.then(()=>{clearTimeout(d),gn(a,n.graceMs)},()=>{clearTimeout(d),wr(a)}),{url:a.url,done:p}}var Gf=/^[a-zA-Z0-9._-]+$/;function Jf(n){let e=n.indexOf("--user");if(e===-1)return{};let t=n[e+1];return!t||t.startsWith("--")?{error:"--user requires a namespace value."}:Gf.test(t)?{user:t}:{error:'--user must contain only letters, digits, ".", "_" or "-".'}}async function La(){let n=await wn();process.stderr.write(`[workspace] Google authorization required. Open ${n.url} in a browser to continue.
29
- `);let e=await n.done;return process.stdout.write(`Added ${e}
30
- `),0}async function Na(n){let{user:e,error:t}=Jf(n);if(t)return process.stderr.write(`${t}
31
- `),2;try{return e===void 0?await La():await Hf({...zf(),uid:e,namespace:e,mode:"multi"},La)}catch(s){return process.stderr.write(`auth failed: ${s instanceof Error?s.message:String(s)}
32
- `),1}}import{readFile as Rh}from"node:fs/promises";import{basename as Eh,dirname as xh,isAbsolute as vh,join as Ko,relative as Ch,sep as Ah}from"node:path";import{fileURLToPath as Ph}from"node:url";var U=class extends Error{constructor(t,s,o,a){super(t);this.message=t;this.code=s;this.suggestion=o;this.details=a;this.name="WorkspaceMCPError"}toJSON(){return{error:this.name,code:this.code,message:this.message,suggestion:this.suggestion,details:this.details}}};function Ma(n){if(!n||typeof n!="object")return n;let e={message:n.message,name:n.name,code:n.code};return n.status&&(e.status=n.status),n.response?.status&&(e.status=n.response.status),e}var Vf=new Set(["authorization","proxy-authorization","x-api-key","x-auth-token","cookie","set-cookie"]);function Jt(n){if(!(!n||typeof n!="object"))for(let e of Object.keys(n))Vf.has(e.toLowerCase())&&delete n[e]}function Fa(n,e=new WeakSet){if(!(!n||typeof n!="object")&&!e.has(n)){e.add(n),delete n.sensitive_token,delete n.internal_config,delete n.user_email,Jt(n.headers),Jt(n._headers),n.request&&(Jt(n.request.headers),Jt(n.request._headers)),n.config&&Jt(n.config.headers),n.response&&Jt(n.response.headers);for(let t of Object.keys(n))typeof n[t]=="object"&&n[t]!==null&&Fa(n[t],e)}}function Yf(n){return!n||typeof n!="object"?null:n.message?.includes("ECONNREFUSED")||n.message?.includes("ENOTFOUND")?new U("Cannot connect to the Google API","NETWORK_ERROR","Check your internet connection and try again"):null}function Zf(n){return!n||typeof n!="object"||!n.code?null:new U(n.message||"Unknown error occurred",String(n.code).toUpperCase(),"Check the error details and try again",Ma(n))}function Xf(n){return!n||typeof n!="object"?new U("Unknown error occurred","UNKNOWN_ERROR","Please check your request and try again"):new U(n.message||"Unknown error occurred","UNKNOWN_ERROR","Please check your request and try again",Ma(n))}function Qf(n){return n instanceof U?n:(Fa(n),Yf(n)||Zf(n)||Xf(n))}function Ba(n,e){if(!n||e.length===0)return null;let t=n.toLowerCase(),s=null,o=0,a=t.length,l=Math.max(0,a-1),d=new Int32Array(l),p=0;for(let u=0;u<l;u++){let f=t.charCodeAt(u)|t.charCodeAt(u+1)<<16,y=!1;for(let g=0;g<p;g++)if(d[g]===f){y=!0;break}y||(d[p++]=f)}for(let u of e){let f=u.toLowerCase();if(f.startsWith(t)||t.startsWith(f))return u;let y=f.length,g=Math.max(0,y-1);if(g===0)continue;let _=new Int32Array(g),S=0;for(let x=0;x<g;x++){let A=f.charCodeAt(x)|f.charCodeAt(x+1)<<16,C=!1;for(let v=0;v<S;v++)if(_[v]===A){C=!0;break}C||(_[S++]=A)}let E=0;for(let x=0;x<p;x++){let A=d[x];for(let C=0;C<S;C++)if(_[C]===A){E++;break}}let R=2*E/(p+S);R>o&&R>.4&&(o=R,s=u)}return s}function Ua(n){let e=`Error: ${n.message}`,t=n.suggestion||tp(n).join(`
27
+ `),o=!1,s=!1,a;r.on("response",l=>{let{headers:d}=l;o=d["transfer-encoding"]==="chunked"&&!d["content-length"]}),r.on("socket",l=>{let d=()=>{if(o&&!s){let u=new Error("Premature close");u.code="ERR_STREAM_PREMATURE_CLOSE",e(u)}},p=u=>{s=uo.compare(u.slice(-5),t)===0,!s&&a&&(s=uo.compare(a.slice(-3),t.slice(0,3))===0&&uo.compare(u.slice(-2),t.slice(3))===0),a=u};l.prependListener("close",d),l.on("data",p),r.on("close",()=>{l.removeListener("close",d),l.removeListener("data",p)})})}var gh,lu=G(()=>{yl();io();Vl();lo();ou();Bs();su();Js();Qn();to();Vs();js();gh=new Set(["data:","http:","https:"])});import{realpathSync as Mu}from"node:fs";import{fileURLToPath as Og}from"node:url";import{Server as kg}from"@modelcontextprotocol/sdk/server/index.js";import{StdioServerTransport as $g}from"@modelcontextprotocol/sdk/server/stdio.js";import{buildCli as Dg}from"@n24q02m/hull";import{localAuthContext as zf,runWithAuthContext as Hf}from"@n24q02m/hull/token-auth";import{PerPluginStore as Lf}from"@n24q02m/hull/storage";var ce="workspace",We="workspace",pn="better-workspace",xa="https://accounts.google.com/o/oauth2/v2/auth",va="https://oauth2.googleapis.com/token",mn=["openid","email","profile"];function vt(r){if(typeof r!="string")return;let e=r.split(".")[1];if(e)try{let t=JSON.parse(Buffer.from(e,"base64url").toString("utf8"));return typeof t.email=="string"?t.email.toLowerCase():void 0}catch{return}}function Ca(r){return r!==null&&r.version===void 0&&typeof r.access_token=="string"}var Aa="(unidentified)",Sr=r=>r.trim().toLowerCase(),hn=class{constructor(e=null){this.store=new Lf(We,e)}async load(){let e=await this.store.load();if(e===null)return null;if(!Ca(e)){let a=e;return a.version===2&&a.accounts?a:null}let t=e,o=vt(t.id_token);if(!o)return null;let s={version:2,accounts:{[o]:t},primary:o};return await this.store.save(s),s}async loadLegacy(){let e=await this.store.load();return Ca(e)?e:null}async adoptLegacy(e){let t=await this.loadLegacy();if(!t)return null;let o=Sr(e);return await this.store.save({version:2,accounts:{[o]:t},primary:o}),t}async put(e,t,o={}){let s=Sr(e),a=await this.load(),l={};if(!a){let f=await this.loadLegacy();if(f){if(!o.absorbLegacy)throw new Error('Refusing to overwrite credentials stored in the older single-account layout. Adopt them first, or clear them deliberately with config(action="setup_reset") before adding a new account.');l={[Aa]:f}}}let d=a??{version:2,accounts:l,primary:s},p={...d.accounts,[s]:t},u=o.makePrimary||!d.accounts[d.primary]?s:d.primary;await this.store.save({version:2,accounts:p,primary:u})}async get(e){let t=await this.load();if(!t)return null;let o=e?Sr(e):t.primary,s=t.accounts[o];return s?{email:o,record:s}:null}async list(){let e=await this.load();return e?{accounts:Object.keys(e.accounts).sort(),primary:e.primary}:{accounts:[],primary:null}}async remove(e){let t=await this.load();if(!t)return{removed:!1,newPrimary:null};let o=Sr(e);if(!t.accounts[o])return{removed:!1,newPrimary:t.primary};let s={...t.accounts};delete s[o];let a=Object.keys(s);if(a.length===0)return await this.store.clear(),{removed:!0,newPrimary:null};let l=a.find(p=>p!==Aa)??a[0],d=t.primary===o?l:t.primary;return await this.store.save({version:2,accounts:s,primary:d}),{removed:!0,newPrimary:d}}async setPrimary(e){let t=await this.load(),o=Sr(e);if(!t?.accounts[o])throw new Error(`Account ${o} is not configured.`);await this.store.save({...t,primary:o})}async clear(){await this.store.clear()}};var Nf=1e4;function wr(r){r.close().catch(e=>{console.error(`[${ce}] failed to close the consent callback server:`,e)})}function gn(r,e=Nf){let t=setTimeout(()=>wr(r),e);typeof t.unref=="function"&&t.unref()}import{currentUser as Mf}from"@n24q02m/hull/token-auth";function _r(){let r=Mf();return r.mode==="no-auth"?void 0:r.namespace}function Gt(){let r=_r();return r===void 0?"workspace auth":`workspace auth --user ${r}`}import{google as Pa}from"googleapis";var yn=class{constructor(e,t=null){this.scopes=e;this.accounts=new hn(t)}async saveTokens(e,t={}){let o={...e},s=e.expires_in;o.expiry_date===void 0&&typeof s=="number"&&(o.expiry_date=Date.now()+s*1e3);let a=t.email?.trim().toLowerCase()??vt(e.id_token);if(!a)throw new Error("Cannot store Google tokens without an account email (no id_token email claim and none passed).");return await this.accounts.put(a,o,{makePrimary:t.makePrimary,absorbLegacy:!0}),a}async listAccounts(){return this.accounts.list()}async removeAccount(e){return this.accounts.remove(e)}async setPrimary(e){return this.accounts.setPrimary(e)}async clear(){await this.accounts.clear()}async fetchAccountEmail(e){try{let{data:t}=await Pa.oauth2({version:"v2",auth:e}).userinfo.get();return typeof t.email=="string"?t.email.toLowerCase():void 0}catch{return}}buildBareClient(e){let t=new Pa.auth.OAuth2({clientId:process.env.GOOGLE_OAUTH_CLIENT_ID,clientSecret:process.env.GOOGLE_OAUTH_CLIENT_SECRET});return t.setCredentials({access_token:e.access_token,refresh_token:e.refresh_token,expiry_date:e.expiry_date,scope:e.scope,token_type:e.token_type}),t}buildClient(e,t){let o=this.buildBareClient(t);return o.on("tokens",s=>{this.saveTokens({...t,...s},{email:e})}),o}async getAuthenticatedClient(e){let t=await this.accounts.get(e);if(t)return this.buildClient(t.email,t.record);if(!e){let o=await this.accounts.loadLegacy();if(o){let s=await this.fetchAccountEmail(this.buildBareClient(o));if(s)return await this.accounts.adoptLegacy(s),this.buildClient(s,o);throw new Error('Stored Google credentials are from an older single-account layout and the account email could not be resolved. Run config(action="account_add") to re-authorize, or re-authorize the existing account.')}}if(e){let{accounts:o}=await this.accounts.list(),s=o.length>0?` Configured accounts: ${o.join(", ")}.`:"";throw new Error(`Account ${e.trim().toLowerCase()} is not configured.${s}`)}throw new Error(`Google account not configured. Run \`${Gt()}\` on the host to complete the Google consent (see setup docs).`)}};var Oa="",Ia=new Map,Tr=new Map;function bn(){return _r()??Oa}function Ct(){return Tr.get(bn())??"awaiting_setup"}function le(){let r=bn(),e=Ia.get(r);return e||(e=new yn(mn,r===Oa?null:r),Ia.set(r,e)),e}async function st(){let r=bn(),e=le(),{accounts:t}=await e.listAccounts();if(t.length>0)return Tr.set(r,"configured"),"configured";try{return await e.getAuthenticatedClient(),Tr.set(r,"configured"),"configured"}catch{return Tr.set(r,"awaiting_setup"),"awaiting_setup"}}async function ka(){await le().clear(),Tr.set(bn(),"awaiting_setup")}import{randomBytes as Ff,timingSafeEqual as Bf}from"node:crypto";import{createServer as Uf}from"node:http";var Rr="127.0.0.1",$a="/callback";function ls(r){return r.replace(/[&<>"']/g,e=>{switch(e){case"&":return"&amp;";case"<":return"&lt;";case">":return"&gt;";case'"':return"&quot;";default:return"&#39;"}})}function it(r,e,t,o){r.writeHead(e,{"Content-Type":"text/html; charset=utf-8","Cache-Control":"no-store"}),r.end(`<!doctype html><meta charset="utf-8"><title>${ls(t)}</title><h1>${ls(t)}</h1><p>${ls(o)}</p>`)}function qf(r,e){let t=Buffer.from(r),o=Buffer.from(e);return t.length===o.length&&Bf(t,o)}async function jf(r,e,t){let o=new URLSearchParams({grant_type:"authorization_code",code:e,client_id:r.clientId,client_secret:r.clientSecret,redirect_uri:t}),s=await fetch(va,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:o});if(!s.ok)throw new Error(`Google token exchange failed (HTTP ${s.status}).`);return await s.json()}async function Sn(r){let e=Ff(16).toString("base64url"),t="",o=async(d,p)=>{let u=new URL(d.url??"/",`http://${Rr}`);if(d.method!=="GET"){it(p,405,"Method not allowed","Use GET.");return}if(u.pathname==="/"){let g=new URL(xa);g.search=new URLSearchParams({client_id:r.clientId,redirect_uri:t,response_type:"code",scope:r.scopes.join(" "),state:e,access_type:"offline",prompt:"consent"}).toString(),p.writeHead(302,{Location:g.toString(),"Cache-Control":"no-store"}),p.end();return}if(u.pathname!==$a){it(p,404,"Not found","Nothing here.");return}let f=u.searchParams.get("state")??"";if(!qf(f,e)){it(p,400,"Authorization failed","The consent response did not match this session. Start again.");return}if(u.searchParams.get("error")){it(p,400,"Authorization cancelled","Google did not grant access. Nothing was stored.");return}let y=u.searchParams.get("code");if(!y){it(p,400,"Authorization failed","Google returned no authorization code.");return}try{let g=await jf(r,y,t);await r.onTokens(g),it(p,200,"Authorization complete","You can close this tab.")}catch(g){let _=g instanceof Error?g.message:"Authorization failed.";it(p,500,"Authorization failed",_)}},s=Uf((d,p)=>{o(d,p).catch(u=>{console.error("[workspace] consent request failed:",u),p.headersSent||it(p,500,"Authorization failed","Unexpected error.")})}),a=Promise.withResolvers();s.once("error",a.reject),s.listen(r.port??0,Rr,()=>{s.off("error",a.reject),a.resolve()}),await a.promise;let{port:l}=s.address();return t=`http://${Rr}:${l}${$a}`,{url:`http://${Rr}:${l}/`,host:Rr,port:l,close:()=>{let d=Promise.withResolvers();return s.close(p=>p?d.reject(p):d.resolve()),s.closeIdleConnections(),d.promise}}}var us=["openid","email","profile","https://www.googleapis.com/auth/documents","https://www.googleapis.com/auth/drive","https://www.googleapis.com/auth/calendar","https://www.googleapis.com/auth/gmail.modify","https://www.googleapis.com/auth/spreadsheets","https://www.googleapis.com/auth/presentations","https://www.googleapis.com/auth/tasks","https://www.googleapis.com/auth/chat.messages","https://www.googleapis.com/auth/contacts.readonly","https://www.googleapis.com/auth/forms.body","https://www.googleapis.com/auth/forms.responses.readonly"];async function Da(r={}){let e=process.env.GOOGLE_OAUTH_CLIENT_ID,t=process.env.GOOGLE_OAUTH_CLIENT_SECRET;if(!e||!t)throw new Error("GOOGLE_OAUTH_CLIENT_ID / GOOGLE_OAUTH_CLIENT_SECRET required for OAuth setup.");let o=Promise.withResolvers(),s=null,a=await Sn({clientId:e,clientSecret:t,scopes:us,onTokens:async l=>{if(s===null){s=le().saveTokens(l).then(p=>(o.resolve(),p),p=>{throw o.reject(p),p}),await s;return}let d=await s;if(vt(l.id_token)!==d)throw new Error(`Setup already completed for ${d}. Use config(action="account_add") to add another account.`)}});process.stderr.write(`[${ce}] Google authorization required. Open ${a.url} in a browser to continue.
28
+ `);try{await o.promise}catch(l){throw wr(a),l}gn(a,r.graceMs)}var Wf=600*1e3;async function wn(r={}){let e=process.env.GOOGLE_OAUTH_CLIENT_ID,t=process.env.GOOGLE_OAUTH_CLIENT_SECRET;if(!e||!t)throw new Error("GOOGLE_OAUTH_CLIENT_ID / GOOGLE_OAUTH_CLIENT_SECRET required to add an account.");let o=Promise.withResolvers(),s=null,a=await Sn({clientId:e,clientSecret:t,scopes:us,onTokens:async u=>{if(s===null){s=le().saveTokens(u,{makePrimary:r.makePrimary}).then(y=>(o.resolve(y),y),y=>{throw o.reject(y),y}),await s;return}let f=await s;if(vt(u.id_token)!==f)throw new Error(`This add-account flow already completed for ${f}. Call config(action="account_add") again to add a different account.`)}}),l=Promise.withResolvers(),d=setTimeout(()=>l.reject(new Error("Add-account flow timed out before the Google consent completed.")),r.ttlMs??Wf);typeof d.unref=="function"&&d.unref();let p=Promise.race([o.promise,l.promise]);return p.then(()=>{clearTimeout(d),gn(a,r.graceMs)},()=>{clearTimeout(d),wr(a)}),{url:a.url,done:p}}var Gf=/^[a-zA-Z0-9._-]+$/;function Jf(r){let e=r.indexOf("--user");if(e===-1)return{};let t=r[e+1];return!t||t.startsWith("--")?{error:"--user requires a namespace value."}:Gf.test(t)?{user:t}:{error:'--user must contain only letters, digits, ".", "_" or "-".'}}async function La(){let r=await wn();process.stderr.write(`[workspace] Google authorization required. Open ${r.url} in a browser to continue.
29
+ `);let e=await r.done;return process.stdout.write(`Added ${e}
30
+ `),0}async function Na(r){let{user:e,error:t}=Jf(r);if(t)return process.stderr.write(`${t}
31
+ `),2;try{return e===void 0?await La():await Hf({...zf(),uid:e,namespace:e,mode:"multi"},La)}catch(o){return process.stderr.write(`auth failed: ${o instanceof Error?o.message:String(o)}
32
+ `),1}}import{readFile as Eh}from"node:fs/promises";import{basename as xh,dirname as vh,isAbsolute as Ch,join as Ks,relative as Ah,sep as Ph}from"node:path";import{fileURLToPath as Ih}from"node:url";var U=class extends Error{constructor(t,o,s,a){super(t);this.message=t;this.code=o;this.suggestion=s;this.details=a;this.name="WorkspaceMCPError"}toJSON(){return{error:this.name,code:this.code,message:this.message,suggestion:this.suggestion,details:this.details}}};function Ma(r){if(!r||typeof r!="object")return r;let e={message:r.message,name:r.name,code:r.code};return r.status&&(e.status=r.status),r.response?.status&&(e.status=r.response.status),e}var Vf=new Set(["authorization","proxy-authorization","x-api-key","x-auth-token","cookie","set-cookie"]);function Jt(r){if(!(!r||typeof r!="object"))for(let e of Object.keys(r))Vf.has(e.toLowerCase())&&delete r[e]}function Fa(r,e=new WeakSet){if(!(!r||typeof r!="object")&&!e.has(r)){e.add(r),delete r.sensitive_token,delete r.internal_config,delete r.user_email,Jt(r.headers),Jt(r._headers),r.request&&(Jt(r.request.headers),Jt(r.request._headers)),r.config&&Jt(r.config.headers),r.response&&Jt(r.response.headers);for(let t of Object.keys(r))typeof r[t]=="object"&&r[t]!==null&&Fa(r[t],e)}}function Yf(r){return!r||typeof r!="object"?null:r.message?.includes("ECONNREFUSED")||r.message?.includes("ENOTFOUND")?new U("Cannot connect to the Google API","NETWORK_ERROR","Check your internet connection and try again"):null}function Zf(r){return!r||typeof r!="object"||!r.code?null:new U(r.message||"Unknown error occurred",String(r.code).toUpperCase(),"Check the error details and try again",Ma(r))}function Xf(r){return!r||typeof r!="object"?new U("Unknown error occurred","UNKNOWN_ERROR","Please check your request and try again"):new U(r.message||"Unknown error occurred","UNKNOWN_ERROR","Please check your request and try again",Ma(r))}function Qf(r){return r instanceof U?r:(Fa(r),Yf(r)||Zf(r)||Xf(r))}function Ba(r,e){if(!r||e.length===0)return null;let t=r.toLowerCase(),o=null,s=0,a=t.length,l=Math.max(0,a-1),d=new Int32Array(l),p=0;for(let u=0;u<l;u++){let f=t.charCodeAt(u)|t.charCodeAt(u+1)<<16,y=!1;for(let g=0;g<p;g++)if(d[g]===f){y=!0;break}y||(d[p++]=f)}for(let u of e){let f=u.toLowerCase();if(f.startsWith(t)||t.startsWith(f))return u;let y=f.length,g=Math.max(0,y-1);if(g===0)continue;let _=new Int32Array(g),S=0;for(let x=0;x<g;x++){let A=f.charCodeAt(x)|f.charCodeAt(x+1)<<16,C=!1;for(let v=0;v<S;v++)if(_[v]===A){C=!0;break}C||(_[S++]=A)}let E=0;for(let x=0;x<p;x++){let A=d[x];for(let C=0;C<S;C++)if(_[C]===A){E++;break}}let R=2*E/(p+S);R>s&&R>.4&&(s=R,o=u)}return o}function Ua(r){let e=`Error: ${r.message}`,t=r.suggestion||tp(r).join(`
33
33
  - `);return t&&(e+=`
34
34
 
35
- Suggestion: ${n.suggestion?t:`
36
- - ${t}`}`),n.details&&(e+=`
35
+ Suggestion: ${r.suggestion?t:`
36
+ - ${t}`}`),r.details&&(e+=`
37
37
 
38
- Details: ${JSON.stringify(n.details,null,2)}`),e}var Kf={},ep=["Review request parameters","Try again in a few moments"];function tp(n){return Kf[n.code]||ep}function _n(n){return async(...e)=>{try{return await n(...e)}catch(t){throw Qf(t)}}}var fo=["status","setup_start","setup_reset","setup_complete","set","cache_clear","account_add","account_list","account_remove","account_set_default"],rp=fo.join(", ");async function uo(){let n=Ct(),{accounts:e,primary:t}=await le().listAccounts();return JSON.stringify({state:n,configured:n==="configured",accounts:e,primary:t})}function Re(n){return{content:[{type:"text",text:n}]}}function qa(n){if(!n.account)throw new U(`${n.action} requires an account`,"VALIDATION_ERROR",'Pass account="<email>" (see config action="account_list")');return n.account}function ja(n){return _n(async()=>{switch(n.action){case"status":return Re(await uo());case"setup_start":return Re(`Run \`${Gt()}\` on the host to start the Google consent flow, then retry the tool. Stdio servers start this flow automatically on first run.`);case"setup_reset":return await ka(),Re(await uo());case"setup_complete":return await ot(),Re(await uo());case"set":return Re("No mutable runtime settings in M1. To update credentials, use setup_reset then restart the server.");case"cache_clear":return Re("No client-side cache to clear in M1.");case"account_list":{let{accounts:e,primary:t}=await le().listAccounts();return Re(JSON.stringify({accounts:e,primary:t}))}case"account_remove":{let e=qa(n),{removed:t,newPrimary:s}=await le().removeAccount(e);return await ot(),Re(JSON.stringify({removed:t,primary:s}))}case"account_set_default":{let e=qa(n);return await le().setPrimary(e),Re(JSON.stringify({primary:e.trim().toLowerCase()}))}case"account_add":{let e=n.value==="primary",t=_r();if(t!==void 0)return Re(JSON.stringify({open:null,next:`Google consent cannot be started over HTTP. On the host where this server runs, run \`workspace auth --user ${t}\` and open the URL it prints. Then call config(action="account_list") to confirm.`,default_account:e?'value="primary" is not available over HTTP and was ignored. Adding an account does not change your default; call config(action="account_set_default", account="<email>") once it appears in account_list.':'Adding an account does not change your default. Call config(action="account_set_default", account="<email>") to change it. (If you had no accounts at all, the first one becomes the default.)'}));let s=await wn({makePrimary:e});return s.done.catch(()=>{}),Re(JSON.stringify({open:s.url,next:'Complete the Google consent in the browser, then call config(action="account_list") to confirm.'}))}default:throw new U(`Unsupported action: ${n.action}`,"VALIDATION_ERROR",`Valid actions: ${rp}`)}})()}import lp from"node:crypto";import{google as up}from"googleapis";var np=!1;function m(n){np&&process.stderr.write(`[workspace] ${n}
39
- `)}var W={retryConfig:{retry:3,noResponseRetries:3,retryDelay:1e3,httpMethodsToRetry:["GET","HEAD","OPTIONS","DELETE","PUT"],statusCodesToRetry:[[429,429],[500,599]],onRetryAttempt:n=>{let e=n.config;m(`Retrying request to ${e.url}, attempt #${e.retryConfig?.currentRetryAttempt}`),m(`Error: ${n.message}`)}},timeout:3e4},Iy={...W,timeout:6e4};import{z as K}from"zod";import*as Wa from"node:path";var Tn=K.string().email("Invalid email format"),at=K.union([Tn,K.array(Tn)]),$y=K.object({filePath:K.string().refine(n=>Wa.isAbsolute(n),{message:"filePath must be an absolute path"}).describe('Absolute local filesystem path to the file to attach (e.g., "/Users/name/downloads/report.pdf"). Use gmail.downloadAttachment first to save an email attachment locally before referencing it here.'),filename:K.string().optional().describe("Display name for the attachment in the email. Defaults to the filename portion of filePath."),mimeType:K.string().optional().describe('MIME type of the attachment (e.g., "application/pdf"). Inferred from the file extension when omitted; falls back to "application/octet-stream".')}),Vt=K.string().refine(n=>/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{3})?(Z|[+-]\d{2}:\d{2})$/.test(n)?!isNaN(Date.parse(n)):!1,{message:"Invalid ISO 8601 datetime format. Expected format: YYYY-MM-DDTHH:mm:ss[.sss][Z|\xB1HH:mm]"}),za=K.string().regex(/^[a-zA-Z0-9_-]+$/,"Invalid document ID format. Document IDs should only contain letters, numbers, hyphens, and underscores"),Dy=K.string().regex(/^https:\/\/(docs|drive|sheets|slides)\.google\.com\/.+\/d\/([a-zA-Z0-9_-]+)/,"Invalid Google Workspace URL format"),Ly=K.string().min(1,"Folder name cannot be empty").max(255,"Folder name too long (max 255 characters)").refine(n=>!/[<>:"/\\|?*\x00-\x1F]/.test(n),"Folder name contains invalid characters"),Ny=K.union([K.literal("primary"),Tn]),My=K.string().transform(n=>n.replace(/\\/g,"\\\\").replace(/'/g,"\\'").replace(/"/g,'\\"')),Fy=K.number().int("Page size must be an integer").min(1,"Page size must be at least 1").max(100,"Page size cannot exceed 100");function po(n,e){return t=>{try{return n.parse(t),{success:!0}}catch(s){return s instanceof K.ZodError?{success:!1,error:s.issues[0].message}:{success:!1,error:e}}}}var By=po(Tn,"Invalid email format"),Uy=po(Vt,"Invalid datetime format"),qy=po(za,"Invalid document ID");function ct(n){if(za.safeParse(n).success)return n;let e=n.match(/\/d\/([a-zA-Z0-9_-]+)/);if(e&&e[1])return e[1];throw new Error("Invalid document ID or URL")}import{z as Ja}from"zod";var sp=Ja.string().refine(n=>{if(!/^\d{4}-\d{2}-\d{2}$/.test(n))return!1;let e=Date.parse(`${n}T00:00:00Z`);return Number.isNaN(e)?!1:new Date(e).toISOString().slice(0,10)===n},{message:"Invalid date format. Expected YYYY-MM-DD"});function ze(n,e){return new Ja.ZodError([{code:"custom",message:e,path:n}])}function Ha(n,e){let t=!!e.dateTime,s=!!e.date;if(!t&&!s||t&&s)throw ze([n],`${n} must have exactly one of "dateTime" (for timed events) or "date" (for all-day events)`)}function Ga(n,e){if(!e)return;let t=!!e.dateTime,s=!!e.date;if(!t&&!s||t&&s)throw ze([n],`${n} must have exactly one of "dateTime" (for timed events) or "date" (for all-day events)`)}function Rn(n,e){e.dateTime&&Vt.parse(e.dateTime),e.date&&sp.parse(e.date)}function op(n){if(!n)throw ze(["workingLocationProperties"],'workingLocationProperties is required when eventType is "workingLocation"');if(n.type==="officeLocation"&&!n.officeLocation)throw ze(["workingLocationProperties","officeLocation"],'officeLocation is required when workingLocationProperties.type is "officeLocation"');if(n.type==="customLocation"&&!n.customLocation)throw ze(["workingLocationProperties","customLocation"],'customLocation is required when workingLocationProperties.type is "customLocation"')}function ip(n,e){let t=new Date(`${n}T00:00:00Z`);return t.setUTCDate(t.getUTCDate()+e),t.toISOString().slice(0,10)}function ap(n){if(n.eventType==="workingLocation"&&n.start.date&&n.end.date){if(n.end.date<n.start.date)throw ze(["start","end"],"end.date must be on or after start.date");if(ip(n.start.date,1)!==n.end.date)throw ze(["start","end"],"all-day workingLocation events must span exactly one day")}}function cp(n){if(Ha("start",n.start),Ha("end",n.end),Rn("start",n.start),Rn("end",n.end),(!n.eventType||n.eventType==="default")&&!n.summary)throw ze(["summary"],"summary is required for regular events");if((n.eventType==="focusTime"||n.eventType==="outOfOffice")&&(n.start.date||n.end.date))throw ze(["start","end"],`${n.eventType} events cannot be all-day events; use dateTime instead of date`);n.eventType==="workingLocation"&&(op(n.workingLocationProperties),ap(n)),n.attendees&&at.parse(n.attendees)}function Va(n){cp({summary:n.summary,start:n.start,end:n.end,attendees:n.attendees,eventType:n.eventType,workingLocationProperties:n.workingLocationProperties})}function Ya(n){Ga("start",n.start),Ga("end",n.end),n.start&&Rn("start",n.start),n.end&&Rn("end",n.end),n.attendees&&at.parse(n.attendees)}import{z as Za}from"zod";var En=class{constructor(e){this.authManager=e;this.primaryCalendarId=null;this.listCalendars=async()=>{m("listCalendars called");try{m("Getting calendar instance...");let e=await this.getCalendar();m("Making API call to calendar.calendarList.list()...");let t=await e.calendarList.list();m(`Found ${t.data.items?.length} calendars.`);let s=t.data.items||[];return m(`Returning calendar data: ${JSON.stringify(s.map(o=>({id:o?.id,summary:o?.summary})))}`),{content:[{type:"text",text:JSON.stringify(s.map(o=>({id:o?.id,summary:o?.summary})))}]}}catch(e){let t=e instanceof Error?e.message:String(e);return m(`Error during calendar.list: ${t}`),{content:[{type:"text",text:JSON.stringify({error:t})}]}}};this.createEvent=async e=>{let{calendarId:t,description:s,start:o,end:a,attendees:l,sendUpdates:d,addGoogleMeet:p,attachments:u,eventType:f,focusTimeProperties:y,outOfOfficeProperties:g,workingLocationProperties:_}=e,S={focusTime:"Focus Time",outOfOffice:"Out of Office",workingLocation:"Working Location"},E=e.summary??(f?S[f]:void 0);try{Va(e)}catch(A){return this.createValidationErrorResponse(A)}let R=t||await this.getPrimaryCalendarId();m(`Creating event in calendar: ${R}`),m(`Event summary: ${E}`),f&&m(`Event type: ${f}`),s&&m(`Event description: ${s}`),m(`Event start: ${o.dateTime||o.date}`),m(`Event end: ${a.dateTime||a.date}`),m(`Event attendees: ${l?.join(", ")}`),p&&m("Adding Google Meet link"),u?.length&&m(`Attachments: ${u.length} file(s)`);let x=d;x===void 0&&(x=l?.length?"all":"none"),x&&m(`Sending updates: ${x}`);try{let A={summary:E,description:s,start:o,end:a,attendees:l?.map($=>({email:$}))};if(f&&f!=="default"&&(A.eventType=f),f==="focusTime")A.transparency="opaque",A.focusTimeProperties={chatStatus:y?.chatStatus??"doNotDisturb",autoDeclineMode:y?.autoDeclineMode??"declineOnlyNewConflictingInvitations"},y?.declineMessage!==void 0&&(A.focusTimeProperties.declineMessage=y.declineMessage);else if(f==="outOfOffice")A.transparency="opaque",A.outOfOfficeProperties={autoDeclineMode:g?.autoDeclineMode??"declineOnlyNewConflictingInvitations"},g?.declineMessage!==void 0&&(A.outOfOfficeProperties.declineMessage=g.declineMessage);else if(f==="workingLocation"){let $=_;A.visibility="public",A.transparency="transparent";let H={type:$.type};$.type==="homeOffice"?H.homeOffice={}:$.type==="officeLocation"&&$.officeLocation?H.officeLocation={buildingId:$.officeLocation.buildingId,label:$.officeLocation.label}:$.type==="customLocation"&&$.customLocation&&(H.customLocation={label:$.customLocation.label}),A.workingLocationProperties=H}let C=await this.getCalendar(),v={calendarId:R,requestBody:A,sendUpdates:x};this.applyMeetAndAttachments(A,v,p,u,{allowEmptyAttachments:!1});let k=await C.events.insert(v);return m(`Successfully created event: ${k.data.id}`),{content:[{type:"text",text:JSON.stringify(k.data)}]}}catch(A){let C=this.extractErrorMessage(A);return m(`Error during calendar.createEvent: ${C}`),{content:[{type:"text",text:JSON.stringify({error:C})}]}}};this.listEvents=async e=>{let{calendarId:t,timeMin:s=new Date().toISOString(),attendeeResponseStatus:o=["accepted","tentative","needsAction"],eventTypes:a}=e,l=e.timeMax;if(!l){let p=new Date;p.setDate(p.getDate()+30),l=p.toISOString()}let d=t||await this.getPrimaryCalendarId();m(`Listing events for calendar: ${d}`);try{let p=await this.getCalendar(),u={calendarId:d,timeMin:s,timeMax:l,singleEvents:!0,fields:"nextPageToken, items(id,summary,start,end,description,htmlLink,attendees,status,eventType,focusTimeProperties,outOfOfficeProperties,workingLocationProperties,attachments(fileId,fileUrl,title,mimeType,iconLink))"};a&&a.length>0&&(u.eventTypes=a),e.maxResults!==void 0&&(u.maxResults=e.maxResults),e.pageToken!==void 0&&(u.pageToken=e.pageToken);let f=await p.events.list(u),y=f.data.items?.filter(g=>g.status!=="cancelled"&&(!!g.summary||g.eventType&&g.eventType!=="default")).filter(g=>{if(!g.attendees||g.attendees.length===0||g.attendees.length===1&&g.attendees[0].self)return!0;let _=g.attendees.find(S=>S.self);return _?o.includes(_.responseStatus||"needsAction"):!0});return m(`Found ${y?.length} events after filtering.`),{content:[{type:"text",text:JSON.stringify({events:y??[],nextPageToken:f.data.nextPageToken??null})}]}}catch(p){let u=p instanceof Error?p.message:String(p);return m(`Error during calendar.listEvents: ${u}`),{content:[{type:"text",text:JSON.stringify({error:u})}]}}};this.getEvent=async e=>{let{eventId:t,calendarId:s}=e,o=s||await this.getPrimaryCalendarId();m(`Getting event ${t} from calendar: ${o}`);try{let l=await(await this.getCalendar()).events.get({calendarId:o,eventId:t});return m(`Successfully retrieved event: ${l.data.id}`),{content:[{type:"text",text:JSON.stringify(l.data)}]}}catch(a){let l=a.response?.data?.error?.message||(a instanceof Error?a.message:String(a));return m(`Error during calendar.getEvent: ${l}`),{content:[{type:"text",text:JSON.stringify({error:l})}]}}};this.deleteEvent=async e=>{let{eventId:t,calendarId:s}=e,o=s||await this.getPrimaryCalendarId();m(`Deleting event ${t} from calendar: ${o}`);try{return await(await this.getCalendar()).events.delete({calendarId:o,eventId:t}),m(`Successfully deleted event: ${t}`),{content:[{type:"text",text:JSON.stringify({message:`Successfully deleted event ${t}`})}]}}catch(a){let l=a.response?.data?.error?.message||(a instanceof Error?a.message:String(a));return m(`Error during calendar.deleteEvent: ${l}`),{content:[{type:"text",text:JSON.stringify({error:l})}]}}};this.updateEvent=async e=>{let{eventId:t,calendarId:s,summary:o,description:a,start:l,end:d,attendees:p,addGoogleMeet:u,attachments:f}=e;try{Ya(e)}catch(g){return this.createValidationErrorResponse(g)}let y=s||await this.getPrimaryCalendarId();m(`Updating event ${t} in calendar: ${y}`),u&&m("Adding Google Meet link"),f?.length&&m(`Attachments: ${f.length} file(s)`);try{let g=await this.getCalendar(),_={};o!==void 0&&(_.summary=o),a!==void 0&&(_.description=a),l&&(_.start=l),d&&(_.end=d),p!==void 0&&(_.attendees=p.map(R=>({email:R})));let S={calendarId:y,eventId:t,requestBody:_};this.applyMeetAndAttachments(_,S,u,f,{allowEmptyAttachments:!0});let E=await g.events.patch(S);return m(`Successfully updated event: ${E.data.id}`),{content:[{type:"text",text:JSON.stringify(E.data)}]}}catch(g){let _=this.extractErrorMessage(g);return m(`Error during calendar.updateEvent: ${_}`),{content:[{type:"text",text:JSON.stringify({error:_})}]}}};this.respondToEvent=async e=>{let{eventId:t,calendarId:s,responseStatus:o,sendNotification:a=!0,responseMessage:l}=e,d=s||await this.getPrimaryCalendarId();m(`Responding to event ${t} in calendar: ${d} with status: ${o}`),l&&m(`Response message: ${l}`);try{let p=await this.getCalendar(),u=await p.events.get({calendarId:d,eventId:t});if(!u.data.attendees||u.data.attendees.length===0)return m("Event has no attendees"),{content:[{type:"text",text:JSON.stringify({error:"Event has no attendees"})}]};let f=u.data.attendees.find(g=>g.self===!0);if(!f)return m("User is not an attendee of this event"),{content:[{type:"text",text:JSON.stringify({error:"You are not an attendee of this event"})}]};f.responseStatus=o,l!==void 0&&(f.comment=l);let y=await p.events.patch({calendarId:d,eventId:t,sendNotifications:a,requestBody:{attendees:u.data.attendees}});return m(`Successfully responded to event: ${y.data.id} with status: ${o}`),{content:[{type:"text",text:JSON.stringify({eventId:y.data.id,summary:y.data.summary,responseStatus:o,message:`Successfully ${o} the meeting invitation${l?" with message":""}`})}]}}catch(p){let u=p instanceof Error?p.message:String(p);return m(`Error during calendar.respondToEvent: ${u}`),{content:[{type:"text",text:JSON.stringify({error:u})}]}}};this.findFreeTime=async e=>{let{attendees:t,timeMin:s,timeMax:o,duration:a}=e;try{Vt.parse(s),Vt.parse(o)}catch(l){return this.createValidationErrorResponse(l)}m(`Finding free time for attendees: ${t.join(", ")}`),m(`Time range: ${s} - ${o}`),m(`Duration: ${a} minutes`);try{let l=await this.getCalendar(),d=await Promise.all(t.map(async R=>R==="me"?{id:await this.getPrimaryCalendarId()}:{id:R})),p=await l.freebusy.query({requestBody:{items:d,timeMin:s,timeMax:o}}),u=Object.values(p.data.calendars||{}).flatMap(R=>R.busy||[]);if(u.length===0)return m("No busy times found, returning the start of the time range."),{content:[{type:"text",text:JSON.stringify({start:s,end:new Date(Date.parse(s)+a*6e4).toISOString()})}]};let f=u.filter(R=>R.start&&R.end).map(R=>({start:Date.parse(R.start),end:Date.parse(R.end)})).sort((R,x)=>R.start-x.start),y=[];for(let R of f)if(y.length===0)y.push(R);else{let x=y[y.length-1];R.start<=x.end?x.end=Math.max(x.end,R.end):y.push(R)}let g=Date.parse(s),_=Date.parse(o),S=a*6e4;if(y.length===0){let R=new Date(g+S);return m(`No busy times, found free time: ${s} - ${R.toISOString()}`),{content:[{type:"text",text:JSON.stringify({start:s,end:R.toISOString()})}]}}if(g+S<=y[0].start){let R=new Date(g+S);return m(`Found free time: ${s} - ${R.toISOString()}`),{content:[{type:"text",text:JSON.stringify({start:s,end:R.toISOString()})}]}}for(let R=0;R<y.length-1;R++){let x=y[R].end;if(y[R+1].start-x>=S){let C=new Date(x),v=new Date(x+S);return m(`Found free time: ${C.toISOString()} - ${v.toISOString()}`),{content:[{type:"text",text:JSON.stringify({start:C.toISOString(),end:v.toISOString()})}]}}}let E=y[y.length-1].end;if(E+S<=_){let R=new Date(E),x=new Date(E+S);return m(`Found free time: ${R.toISOString()} - ${x.toISOString()}`),{content:[{type:"text",text:JSON.stringify({start:R.toISOString(),end:x.toISOString()})}]}}return m("No available free time found"),{content:[{type:"text",text:JSON.stringify({error:"No available free time found"})}]}}catch(l){let d=l instanceof Error?l.message:String(l);return m(`Error during calendar.findFreeTime: ${d}`),{content:[{type:"text",text:JSON.stringify({error:d})}]}}}}applyMeetAndAttachments(e,t,s,o,a){s&&(e.conferenceData={createRequest:{requestId:lp.randomUUID(),conferenceSolutionKey:{type:"hangoutsMeet"}}},t.conferenceDataVersion=1),o&&(o.length>0||a?.allowEmptyAttachments)&&(e.attachments=o.map(l=>({fileUrl:l.fileUrl,title:l.title,mimeType:l.mimeType})),t.supportsAttachments=!0)}createValidationErrorResponse(e){let t=e instanceof Za.ZodError?e.issues.map(o=>o.path.length?`${o.path.join(".")}: ${o.message}`:o.message).join("; "):e instanceof Error?e.message:"Validation failed",s="Please use strict ISO 8601 format with seconds and timezone. Examples: 2024-01-15T10:30:00Z (UTC) or 2024-01-15T10:30:00-05:00 (EST)";return e instanceof Za.ZodError&&e.issues.some(o=>o.path.includes("attendees")||o.message.includes("email"))&&(s="Please ensure all attendee emails are in a valid format."),{content:[{type:"text",text:JSON.stringify({error:"Invalid input format",details:t,help:s})}]}}extractErrorMessage(e){let t=e?.response?.data?.error;if(t){let s=t.message??"Unknown Error",o=t.code?` (code ${t.code})`:"";if(t.errors?.length){let a=t.errors.map(l=>{let p=[[l.domain,l.locationType,l.location].filter(Boolean).join("."),l.reason].filter(Boolean).join(" ");return p?`${p}: ${l.message}`:l.message}).join("; ");return t.errors.length===1&&(s===t.errors[0].message||s.includes(t.errors[0].message??""))?`${a}${o}`:`${s}${o}: ${a}`}return`${s}${o}`}return e instanceof Error?e.message:String(e)}async getCalendar(){m("Getting authenticated client for calendar...");let e=await this.authManager.getAuthenticatedClient();m("Got auth client, creating calendar instance...");let t={...W,auth:e};return up.calendar({version:"v3",...t})}async getPrimaryCalendarId(){if(this.primaryCalendarId)return this.primaryCalendarId;m("Getting primary calendar ID...");let s=(await(await this.getCalendar()).calendarList.list()).data.items?.find(o=>o.primary);return s&&s.id?(m(`Found primary calendar: ${s.id}`),this.primaryCalendarId=s.id,s.id):(m('No primary calendar found, defaulting to "primary"'),"primary")}};var dp="Pass full: true for the complete payload, or raise max_chars up to 100000.",fp="Pass full: true for every item, or narrow the request; this listing returns one response with no cursor.",pp="Request another page with pageToken, or raise max_chars up to 100000.",He=()=>({hint:dp}),Pe=n=>({items:n,hint:fp}),Ie=()=>({hint:pp}),Xa={getSuggestions:Pe(100)},Qa={getText:He(),getMetadata:Pe(100),getImages:Pe(100),getSpeakerNotes:Pe(100)},Ka={get:He(),search:Ie(),listLabels:Pe(100),modify:He(),modifyThread:He()},ec={search:Ie(),getComments:Ie(),findFolder:Pe(50)},tc={listSpaces:Ie(),findSpaceByName:Pe(50),getMessages:Ie(),listThreads:Ie()},rc={listCalendars:Pe(100),listEvents:Ie(),getEvent:He(),findFreeTime:Pe(50)},nc={listTaskLists:Ie(),listTasks:Ie()},sc={getUserProfile:He(),getMe:He(),getUserRelations:Pe(50)},oc={get:He(),listResponses:Ie(),getResponse:He()};import{AsyncLocalStorage as mp}from"node:async_hooks";var ic=new mp;function ac(n,e){return ic.run({account:n},e)}function cc(){return ic.getStore()?.account}var xn=class{constructor(e=[]){this.scopes=e}async getAuthenticatedClient(){return le().getAuthenticatedClient(cc())}};var he=Number.POSITIVE_INFINITY,vn={nextPageToken:!0,next_page_token:!0,nextPageCursor:!0,pageToken:!0,page_token:!0,nextSyncToken:!0,syncToken:!0,continuationToken:!0,cursor:!0};function hp(n){let e=n.trim();if(!(!e.startsWith("{")&&!e.startsWith("[")))try{return{value:JSON.parse(e)}}catch{return}}function fc(n,e,t){let s=Math.max(n-e,0);return`[Content truncated: showing ${e} of ${n} characters (${s} omitted). ${t}]`}function pc(n,e={}){if(n.full===!0)return{chars:he,items:he};let t=e.items??he,s=n.max_chars;if(s===void 0)return{chars:e.chars??2e4,items:t};if(typeof s!="number"||!Number.isInteger(s)||s<1||s>1e5)throw new Error("max_chars must be an integer between 1 and 100000.");return{chars:s,items:t}}function lc(n,e){return typeof e=="number"?`${n}[${e}]`:`${n}.${e}`}function uc(n,e,t="$"){let s=[],o=(l,d)=>{if(Array.isArray(l)){let p=e.items===he?l:l.slice(0,e.items);return p.length<l.length&&s.push({path:d,returned:p.length,total:l.length}),p.map((u,f)=>o(u,lc(d,f)))}if(typeof l=="string")return e.stringChars===he||l.length<=e.stringChars?l:`${l.slice(0,e.stringChars)}[+${l.length-e.stringChars} chars]`;if(l&&typeof l=="object"){let p={};for(let[u,f]of Object.entries(l))p[u]=vn[u]?f:o(f,lc(d,u));return p}return l};return{value:o(n,t),lists:s}}function mo(n,e,t,s,o){let a={truncated:!0,total_characters:t,returned_characters:s,note:fc(t,s,o)};if(e.length>0&&(a.omitted_items=e),Array.isArray(n))return JSON.stringify({items:n,_truncation:a});let l="_truncation"in n?"_response_truncation":"_truncation";return JSON.stringify({...n,[l]:a})}function dc(n,e,t){let s=n.length;if(e.chars===he||s<=e.chars)return{text:n,truncated:!1,totalCharacters:s};let o=n.slice(0,e.chars);return{text:`${o}
38
+ Details: ${JSON.stringify(r.details,null,2)}`),e}var Kf={},ep=["Review request parameters","Try again in a few moments"];function tp(r){return Kf[r.code]||ep}function _n(r){return async(...e)=>{try{return await r(...e)}catch(t){throw Qf(t)}}}var fs=["status","setup_start","setup_reset","setup_complete","set","cache_clear","account_add","account_list","account_remove","account_set_default"],rp=fs.join(", ");async function ds(){let r=Ct(),{accounts:e,primary:t}=await le().listAccounts();return JSON.stringify({state:r,configured:r==="configured",accounts:e,primary:t})}function Re(r){return{content:[{type:"text",text:r}]}}function qa(r){if(!r.account)throw new U(`${r.action} requires an account`,"VALIDATION_ERROR",'Pass account="<email>" (see config action="account_list")');return r.account}function ja(r){return _n(async()=>{switch(r.action){case"status":return Re(await ds());case"setup_start":return Re(`Run \`${Gt()}\` on the host to start the Google consent flow, then retry the tool. Stdio servers start this flow automatically on first run.`);case"setup_reset":return await ka(),Re(await ds());case"setup_complete":return await st(),Re(await ds());case"set":return Re("No mutable runtime settings in M1. To update credentials, use setup_reset then restart the server.");case"cache_clear":return Re("No client-side cache to clear in M1.");case"account_list":{let{accounts:e,primary:t}=await le().listAccounts();return Re(JSON.stringify({accounts:e,primary:t}))}case"account_remove":{let e=qa(r),{removed:t,newPrimary:o}=await le().removeAccount(e);return await st(),Re(JSON.stringify({removed:t,primary:o}))}case"account_set_default":{let e=qa(r);return await le().setPrimary(e),Re(JSON.stringify({primary:e.trim().toLowerCase()}))}case"account_add":{let e=r.value==="primary",t=_r();if(t!==void 0)return Re(JSON.stringify({open:null,next:`Google consent cannot be started over HTTP. On the host where this server runs, run \`workspace auth --user ${t}\` and open the URL it prints. Then call config(action="account_list") to confirm.`,default_account:e?'value="primary" is not available over HTTP and was ignored. Adding an account does not change your default; call config(action="account_set_default", account="<email>") once it appears in account_list.':'Adding an account does not change your default. Call config(action="account_set_default", account="<email>") to change it. (If you had no accounts at all, the first one becomes the default.)'}));let o=await wn({makePrimary:e});return o.done.catch(()=>{}),Re(JSON.stringify({open:o.url,next:'Complete the Google consent in the browser, then call config(action="account_list") to confirm.'}))}default:throw new U(`Unsupported action: ${r.action}`,"VALIDATION_ERROR",`Valid actions: ${rp}`)}})()}import lp from"node:crypto";import{google as up}from"googleapis";var np=!1;function m(r){np&&process.stderr.write(`[workspace] ${r}
39
+ `)}var W={retryConfig:{retry:3,noResponseRetries:3,retryDelay:1e3,httpMethodsToRetry:["GET","HEAD","OPTIONS","DELETE","PUT"],statusCodesToRetry:[[429,429],[500,599]],onRetryAttempt:r=>{let e=r.config;m(`Retrying request to ${e.url}, attempt #${e.retryConfig?.currentRetryAttempt}`),m(`Error: ${r.message}`)}},timeout:3e4},Oy={...W,timeout:6e4};import{z as K}from"zod";import*as Wa from"node:path";var Tn=K.string().email("Invalid email format"),at=K.union([Tn,K.array(Tn)]),Dy=K.object({filePath:K.string().refine(r=>Wa.isAbsolute(r),{message:"filePath must be an absolute path"}).describe('Absolute local filesystem path to the file to attach (e.g., "/Users/name/downloads/report.pdf"). Use gmail.downloadAttachment first to save an email attachment locally before referencing it here.'),filename:K.string().optional().describe("Display name for the attachment in the email. Defaults to the filename portion of filePath."),mimeType:K.string().optional().describe('MIME type of the attachment (e.g., "application/pdf"). Inferred from the file extension when omitted; falls back to "application/octet-stream".')}),Vt=K.string().refine(r=>{if(!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{3})?(Z|[+-]\d{2}:\d{2})$/.test(r)||isNaN(Date.parse(r)))return!1;let[t,o,s]=r.slice(0,10).split("-").map(Number),l=[31,t%4===0&&t%100!==0||t%400===0?29:28,31,30,31,30,31,31,30,31,30,31];return s<=l[o-1]},{message:"Invalid ISO 8601 datetime format. Expected format: YYYY-MM-DDTHH:mm:ss[.sss][Z|\xB1HH:mm]"}),za=K.string().regex(/^[a-zA-Z0-9_-]+$/,"Invalid document ID format. Document IDs should only contain letters, numbers, hyphens, and underscores"),Ly=K.string().regex(/^https:\/\/(docs|drive|sheets|slides)\.google\.com\/.+\/d\/([a-zA-Z0-9_-]+)/,"Invalid Google Workspace URL format"),Ny=K.string().min(1,"Folder name cannot be empty").max(255,"Folder name too long (max 255 characters)").refine(r=>!/[<>:"/\\|?*\x00-\x1F]/.test(r),"Folder name contains invalid characters"),My=K.union([K.literal("primary"),Tn]),Fy=K.string().transform(r=>r.replace(/\\/g,"\\\\").replace(/'/g,"\\'").replace(/"/g,'\\"')),By=K.number().int("Page size must be an integer").min(1,"Page size must be at least 1").max(100,"Page size cannot exceed 100");function ps(r,e){return t=>{try{return r.parse(t),{success:!0}}catch(o){return o instanceof K.ZodError?{success:!1,error:o.issues[0].message}:{success:!1,error:e}}}}var Uy=ps(Tn,"Invalid email format"),qy=ps(Vt,"Invalid datetime format"),jy=ps(za,"Invalid document ID");function ct(r){if(za.safeParse(r).success)return r;let e=r.match(/\/d\/([a-zA-Z0-9_-]+)/);if(e&&e[1])return e[1];throw new Error("Invalid document ID or URL")}import{z as Ja}from"zod";var op=Ja.string().refine(r=>{if(!/^\d{4}-\d{2}-\d{2}$/.test(r))return!1;let e=Date.parse(`${r}T00:00:00Z`);return Number.isNaN(e)?!1:new Date(e).toISOString().slice(0,10)===r},{message:"Invalid date format. Expected YYYY-MM-DD"});function ze(r,e){return new Ja.ZodError([{code:"custom",message:e,path:r}])}function Ha(r,e){let t=!!e.dateTime,o=!!e.date;if(!t&&!o||t&&o)throw ze([r],`${r} must have exactly one of "dateTime" (for timed events) or "date" (for all-day events)`)}function Ga(r,e){if(!e)return;let t=!!e.dateTime,o=!!e.date;if(!t&&!o||t&&o)throw ze([r],`${r} must have exactly one of "dateTime" (for timed events) or "date" (for all-day events)`)}function Rn(r,e){e.dateTime&&Vt.parse(e.dateTime),e.date&&op.parse(e.date)}function sp(r){if(!r)throw ze(["workingLocationProperties"],'workingLocationProperties is required when eventType is "workingLocation"');if(r.type==="officeLocation"&&!r.officeLocation)throw ze(["workingLocationProperties","officeLocation"],'officeLocation is required when workingLocationProperties.type is "officeLocation"');if(r.type==="customLocation"&&!r.customLocation)throw ze(["workingLocationProperties","customLocation"],'customLocation is required when workingLocationProperties.type is "customLocation"')}function ip(r,e){let t=new Date(`${r}T00:00:00Z`);return t.setUTCDate(t.getUTCDate()+e),t.toISOString().slice(0,10)}function ap(r){if(r.eventType==="workingLocation"&&r.start.date&&r.end.date){if(r.end.date<r.start.date)throw ze(["start","end"],"end.date must be on or after start.date");if(ip(r.start.date,1)!==r.end.date)throw ze(["start","end"],"all-day workingLocation events must span exactly one day")}}function cp(r){if(Ha("start",r.start),Ha("end",r.end),Rn("start",r.start),Rn("end",r.end),(!r.eventType||r.eventType==="default")&&!r.summary)throw ze(["summary"],"summary is required for regular events");if((r.eventType==="focusTime"||r.eventType==="outOfOffice")&&(r.start.date||r.end.date))throw ze(["start","end"],`${r.eventType} events cannot be all-day events; use dateTime instead of date`);r.eventType==="workingLocation"&&(sp(r.workingLocationProperties),ap(r)),r.attendees&&at.parse(r.attendees)}function Va(r){cp({summary:r.summary,start:r.start,end:r.end,attendees:r.attendees,eventType:r.eventType,workingLocationProperties:r.workingLocationProperties})}function Ya(r){Ga("start",r.start),Ga("end",r.end),r.start&&Rn("start",r.start),r.end&&Rn("end",r.end),r.attendees&&at.parse(r.attendees)}import{z as Za}from"zod";var En=class{constructor(e){this.authManager=e;this.primaryCalendarId=null;this.listCalendars=async()=>{m("listCalendars called");try{m("Getting calendar instance...");let e=await this.getCalendar();m("Making API call to calendar.calendarList.list()...");let t=await e.calendarList.list();m(`Found ${t.data.items?.length} calendars.`);let o=t.data.items||[];return m(`Returning calendar data: ${JSON.stringify(o.map(s=>({id:s?.id,summary:s?.summary})))}`),{content:[{type:"text",text:JSON.stringify(o.map(s=>({id:s?.id,summary:s?.summary})))}]}}catch(e){let t=e instanceof Error?e.message:String(e);return m(`Error during calendar.list: ${t}`),{content:[{type:"text",text:JSON.stringify({error:t})}]}}};this.createEvent=async e=>{let{calendarId:t,description:o,start:s,end:a,attendees:l,sendUpdates:d,addGoogleMeet:p,attachments:u,eventType:f,focusTimeProperties:y,outOfOfficeProperties:g,workingLocationProperties:_}=e,S={focusTime:"Focus Time",outOfOffice:"Out of Office",workingLocation:"Working Location"},E=e.summary??(f?S[f]:void 0);try{Va(e)}catch(A){return this.createValidationErrorResponse(A)}let R=t||await this.getPrimaryCalendarId();m(`Creating event in calendar: ${R}`),m(`Event summary: ${E}`),f&&m(`Event type: ${f}`),o&&m(`Event description: ${o}`),m(`Event start: ${s.dateTime||s.date}`),m(`Event end: ${a.dateTime||a.date}`),m(`Event attendees: ${l?.join(", ")}`),p&&m("Adding Google Meet link"),u?.length&&m(`Attachments: ${u.length} file(s)`);let x=d;x===void 0&&(x=l?.length?"all":"none"),x&&m(`Sending updates: ${x}`);try{let A={summary:E,description:o,start:s,end:a,attendees:l?.map($=>({email:$}))};if(f&&f!=="default"&&(A.eventType=f),f==="focusTime")A.transparency="opaque",A.focusTimeProperties={chatStatus:y?.chatStatus??"doNotDisturb",autoDeclineMode:y?.autoDeclineMode??"declineOnlyNewConflictingInvitations"},y?.declineMessage!==void 0&&(A.focusTimeProperties.declineMessage=y.declineMessage);else if(f==="outOfOffice")A.transparency="opaque",A.outOfOfficeProperties={autoDeclineMode:g?.autoDeclineMode??"declineOnlyNewConflictingInvitations"},g?.declineMessage!==void 0&&(A.outOfOfficeProperties.declineMessage=g.declineMessage);else if(f==="workingLocation"){let $=_;A.visibility="public",A.transparency="transparent";let H={type:$.type};$.type==="homeOffice"?H.homeOffice={}:$.type==="officeLocation"&&$.officeLocation?H.officeLocation={buildingId:$.officeLocation.buildingId,label:$.officeLocation.label}:$.type==="customLocation"&&$.customLocation&&(H.customLocation={label:$.customLocation.label}),A.workingLocationProperties=H}let C=await this.getCalendar(),v={calendarId:R,requestBody:A,sendUpdates:x};this.applyMeetAndAttachments(A,v,p,u,{allowEmptyAttachments:!1});let k=await C.events.insert(v);return m(`Successfully created event: ${k.data.id}`),{content:[{type:"text",text:JSON.stringify(k.data)}]}}catch(A){let C=this.extractErrorMessage(A);return m(`Error during calendar.createEvent: ${C}`),{content:[{type:"text",text:JSON.stringify({error:C})}]}}};this.listEvents=async e=>{let{calendarId:t,timeMin:o=new Date().toISOString(),attendeeResponseStatus:s=["accepted","tentative","needsAction"],eventTypes:a}=e,l=e.timeMax;if(!l){let p=new Date;p.setDate(p.getDate()+30),l=p.toISOString()}let d=t||await this.getPrimaryCalendarId();m(`Listing events for calendar: ${d}`);try{let p=await this.getCalendar(),u={calendarId:d,timeMin:o,timeMax:l,singleEvents:!0,fields:"nextPageToken, items(id,summary,start,end,description,htmlLink,attendees,status,eventType,focusTimeProperties,outOfOfficeProperties,workingLocationProperties,attachments(fileId,fileUrl,title,mimeType,iconLink))"};a&&a.length>0&&(u.eventTypes=a),e.maxResults!==void 0&&(u.maxResults=e.maxResults),e.pageToken!==void 0&&(u.pageToken=e.pageToken);let f=await p.events.list(u),y=f.data.items?.filter(g=>g.status!=="cancelled"&&(!!g.summary||g.eventType&&g.eventType!=="default")).filter(g=>{if(!g.attendees||g.attendees.length===0||g.attendees.length===1&&g.attendees[0].self)return!0;let _=g.attendees.find(S=>S.self);return _?s.includes(_.responseStatus||"needsAction"):!0});return m(`Found ${y?.length} events after filtering.`),{content:[{type:"text",text:JSON.stringify({events:y??[],nextPageToken:f.data.nextPageToken??null})}]}}catch(p){let u=p instanceof Error?p.message:String(p);return m(`Error during calendar.listEvents: ${u}`),{content:[{type:"text",text:JSON.stringify({error:u})}]}}};this.getEvent=async e=>{let{eventId:t,calendarId:o}=e,s=o||await this.getPrimaryCalendarId();m(`Getting event ${t} from calendar: ${s}`);try{let l=await(await this.getCalendar()).events.get({calendarId:s,eventId:t});return m(`Successfully retrieved event: ${l.data.id}`),{content:[{type:"text",text:JSON.stringify(l.data)}]}}catch(a){let l=a.response?.data?.error?.message||(a instanceof Error?a.message:String(a));return m(`Error during calendar.getEvent: ${l}`),{content:[{type:"text",text:JSON.stringify({error:l})}]}}};this.deleteEvent=async e=>{let{eventId:t,calendarId:o}=e,s=o||await this.getPrimaryCalendarId();m(`Deleting event ${t} from calendar: ${s}`);try{return await(await this.getCalendar()).events.delete({calendarId:s,eventId:t}),m(`Successfully deleted event: ${t}`),{content:[{type:"text",text:JSON.stringify({message:`Successfully deleted event ${t}`})}]}}catch(a){let l=a.response?.data?.error?.message||(a instanceof Error?a.message:String(a));return m(`Error during calendar.deleteEvent: ${l}`),{content:[{type:"text",text:JSON.stringify({error:l})}]}}};this.updateEvent=async e=>{let{eventId:t,calendarId:o,summary:s,description:a,start:l,end:d,attendees:p,addGoogleMeet:u,attachments:f}=e;try{Ya(e)}catch(g){return this.createValidationErrorResponse(g)}let y=o||await this.getPrimaryCalendarId();m(`Updating event ${t} in calendar: ${y}`),u&&m("Adding Google Meet link"),f?.length&&m(`Attachments: ${f.length} file(s)`);try{let g=await this.getCalendar(),_={};s!==void 0&&(_.summary=s),a!==void 0&&(_.description=a),l&&(_.start=l),d&&(_.end=d),p!==void 0&&(_.attendees=p.map(R=>({email:R})));let S={calendarId:y,eventId:t,requestBody:_};this.applyMeetAndAttachments(_,S,u,f,{allowEmptyAttachments:!0});let E=await g.events.patch(S);return m(`Successfully updated event: ${E.data.id}`),{content:[{type:"text",text:JSON.stringify(E.data)}]}}catch(g){let _=this.extractErrorMessage(g);return m(`Error during calendar.updateEvent: ${_}`),{content:[{type:"text",text:JSON.stringify({error:_})}]}}};this.respondToEvent=async e=>{let{eventId:t,calendarId:o,responseStatus:s,sendNotification:a=!0,responseMessage:l}=e,d=o||await this.getPrimaryCalendarId();m(`Responding to event ${t} in calendar: ${d} with status: ${s}`),l&&m(`Response message: ${l}`);try{let p=await this.getCalendar(),u=await p.events.get({calendarId:d,eventId:t});if(!u.data.attendees||u.data.attendees.length===0)return m("Event has no attendees"),{content:[{type:"text",text:JSON.stringify({error:"Event has no attendees"})}]};let f=u.data.attendees.find(g=>g.self===!0);if(!f)return m("User is not an attendee of this event"),{content:[{type:"text",text:JSON.stringify({error:"You are not an attendee of this event"})}]};f.responseStatus=s,l!==void 0&&(f.comment=l);let y=await p.events.patch({calendarId:d,eventId:t,sendNotifications:a,requestBody:{attendees:u.data.attendees}});return m(`Successfully responded to event: ${y.data.id} with status: ${s}`),{content:[{type:"text",text:JSON.stringify({eventId:y.data.id,summary:y.data.summary,responseStatus:s,message:`Successfully ${s} the meeting invitation${l?" with message":""}`})}]}}catch(p){let u=p instanceof Error?p.message:String(p);return m(`Error during calendar.respondToEvent: ${u}`),{content:[{type:"text",text:JSON.stringify({error:u})}]}}};this.findFreeTime=async e=>{let{attendees:t,timeMin:o,timeMax:s,duration:a}=e;try{Vt.parse(o),Vt.parse(s)}catch(l){return this.createValidationErrorResponse(l)}m(`Finding free time for attendees: ${t.join(", ")}`),m(`Time range: ${o} - ${s}`),m(`Duration: ${a} minutes`);try{let l=await this.getCalendar(),d=await Promise.all(t.map(async R=>R==="me"?{id:await this.getPrimaryCalendarId()}:{id:R})),p=await l.freebusy.query({requestBody:{items:d,timeMin:o,timeMax:s}}),u=Object.values(p.data.calendars||{}).flatMap(R=>R.busy||[]);if(u.length===0)return m("No busy times found, returning the start of the time range."),{content:[{type:"text",text:JSON.stringify({start:o,end:new Date(Date.parse(o)+a*6e4).toISOString()})}]};let f=u.filter(R=>R.start&&R.end).map(R=>({start:Date.parse(R.start),end:Date.parse(R.end)})).sort((R,x)=>R.start-x.start),y=[];for(let R of f)if(y.length===0)y.push(R);else{let x=y[y.length-1];R.start<=x.end?x.end=Math.max(x.end,R.end):y.push(R)}let g=Date.parse(o),_=Date.parse(s),S=a*6e4;if(y.length===0){let R=new Date(g+S);return m(`No busy times, found free time: ${o} - ${R.toISOString()}`),{content:[{type:"text",text:JSON.stringify({start:o,end:R.toISOString()})}]}}if(g+S<=y[0].start){let R=new Date(g+S);return m(`Found free time: ${o} - ${R.toISOString()}`),{content:[{type:"text",text:JSON.stringify({start:o,end:R.toISOString()})}]}}for(let R=0;R<y.length-1;R++){let x=y[R].end;if(y[R+1].start-x>=S){let C=new Date(x),v=new Date(x+S);return m(`Found free time: ${C.toISOString()} - ${v.toISOString()}`),{content:[{type:"text",text:JSON.stringify({start:C.toISOString(),end:v.toISOString()})}]}}}let E=y[y.length-1].end;if(E+S<=_){let R=new Date(E),x=new Date(E+S);return m(`Found free time: ${R.toISOString()} - ${x.toISOString()}`),{content:[{type:"text",text:JSON.stringify({start:R.toISOString(),end:x.toISOString()})}]}}return m("No available free time found"),{content:[{type:"text",text:JSON.stringify({error:"No available free time found"})}]}}catch(l){let d=l instanceof Error?l.message:String(l);return m(`Error during calendar.findFreeTime: ${d}`),{content:[{type:"text",text:JSON.stringify({error:d})}]}}}}applyMeetAndAttachments(e,t,o,s,a){o&&(e.conferenceData={createRequest:{requestId:lp.randomUUID(),conferenceSolutionKey:{type:"hangoutsMeet"}}},t.conferenceDataVersion=1),s&&(s.length>0||a?.allowEmptyAttachments)&&(e.attachments=s.map(l=>({fileUrl:l.fileUrl,title:l.title,mimeType:l.mimeType})),t.supportsAttachments=!0)}createValidationErrorResponse(e){let t=e instanceof Za.ZodError?e.issues.map(s=>s.path.length?`${s.path.join(".")}: ${s.message}`:s.message).join("; "):e instanceof Error?e.message:"Validation failed",o="Please use strict ISO 8601 format with seconds and timezone. Examples: 2024-01-15T10:30:00Z (UTC) or 2024-01-15T10:30:00-05:00 (EST)";return e instanceof Za.ZodError&&e.issues.some(s=>s.path.includes("attendees")||s.message.includes("email"))&&(o="Please ensure all attendee emails are in a valid format."),{content:[{type:"text",text:JSON.stringify({error:"Invalid input format",details:t,help:o})}]}}extractErrorMessage(e){let t=e?.response?.data?.error;if(t){let o=t.message??"Unknown Error",s=t.code?` (code ${t.code})`:"",a=Array.isArray(t.errors)?t.errors:[],l=a.map(d=>[[[d.domain,d.locationType,d.location].filter(Boolean).join("."),d.reason].filter(Boolean).join(" "),d.message].filter(Boolean).join(": ")).filter(Boolean);if(l.length){let d=l.join("; "),p=a.length===1?a[0].message:void 0;return p&&o.includes(p)?`${d}${s}`:`${o}${s}: ${d}`}return`${o}${s}`}return e instanceof Error?e.message:String(e)}async getCalendar(){m("Getting authenticated client for calendar...");let e=await this.authManager.getAuthenticatedClient();m("Got auth client, creating calendar instance...");let t={...W,auth:e};return up.calendar({version:"v3",...t})}async getPrimaryCalendarId(){if(this.primaryCalendarId)return this.primaryCalendarId;m("Getting primary calendar ID...");let o=(await(await this.getCalendar()).calendarList.list()).data.items?.find(s=>s.primary);return o&&o.id?(m(`Found primary calendar: ${o.id}`),this.primaryCalendarId=o.id,o.id):(m('No primary calendar found, defaulting to "primary"'),"primary")}};var dp="Pass full: true for the complete payload, or raise max_chars up to 100000.",fp="Pass full: true for every item, or narrow the request; this listing returns one response with no cursor.",pp="Request another page with pageToken, or raise max_chars up to 100000.",He=()=>({hint:dp}),Pe=r=>({items:r,hint:fp}),Ie=()=>({hint:pp}),Xa={getSuggestions:Pe(100)},Qa={getText:He(),getMetadata:Pe(100),getImages:Pe(100),getSpeakerNotes:Pe(100)},Ka={get:He(),search:Ie(),listLabels:Pe(100),modify:He(),modifyThread:He()},ec={search:Ie(),getComments:Ie(),findFolder:Pe(50)},tc={listSpaces:Ie(),findSpaceByName:Pe(50),getMessages:Ie(),listThreads:Ie()},rc={listCalendars:Pe(100),listEvents:Ie(),getEvent:He(),findFreeTime:Pe(50)},nc={listTaskLists:Ie(),listTasks:Ie()},oc={getUserProfile:He(),getMe:He(),getUserRelations:Pe(50)},sc={get:He(),listResponses:Ie(),getResponse:He()};import{AsyncLocalStorage as mp}from"node:async_hooks";var ic=new mp;function ac(r,e){return ic.run({account:r},e)}function cc(){return ic.getStore()?.account}var xn=class{constructor(e=[]){this.scopes=e}async getAuthenticatedClient(){return le().getAuthenticatedClient(cc())}};var he=Number.POSITIVE_INFINITY,vn={nextPageToken:!0,next_page_token:!0,nextPageCursor:!0,pageToken:!0,page_token:!0,nextSyncToken:!0,syncToken:!0,continuationToken:!0,cursor:!0};function hp(r){let e=r.trim();if(!(!e.startsWith("{")&&!e.startsWith("[")))try{return{value:JSON.parse(e)}}catch{return}}function fc(r,e,t){let o=Math.max(r-e,0);return`[Content truncated: showing ${e} of ${r} characters (${o} omitted). ${t}]`}function pc(r,e={}){if(r.full===!0)return{chars:he,items:he};let t=e.items??he,o=r.max_chars;if(o===void 0)return{chars:e.chars??2e4,items:t};if(typeof o!="number"||!Number.isInteger(o)||o<1||o>1e5)throw new Error("max_chars must be an integer between 1 and 100000.");return{chars:o,items:t}}function lc(r,e){return typeof e=="number"?`${r}[${e}]`:`${r}.${e}`}function uc(r,e,t="$"){let o=[],s=(l,d)=>{if(Array.isArray(l)){let p=e.items===he?l:l.slice(0,e.items);return p.length<l.length&&o.push({path:d,returned:p.length,total:l.length}),p.map((u,f)=>s(u,lc(d,f)))}if(typeof l=="string")return e.stringChars===he||l.length<=e.stringChars?l:`${l.slice(0,e.stringChars)}[+${l.length-e.stringChars} chars]`;if(l&&typeof l=="object"){let p={};for(let[u,f]of Object.entries(l))p[u]=vn[u]?f:s(f,lc(d,u));return p}return l};return{value:s(r,t),lists:o}}function ms(r,e,t,o,s){let a={truncated:!0,total_characters:t,returned_characters:o,note:fc(t,o,s)};if(e.length>0&&(a.omitted_items=e),Array.isArray(r))return JSON.stringify({items:r,_truncation:a});let l="_truncation"in r?"_response_truncation":"_truncation";return JSON.stringify({...r,[l]:a})}function dc(r,e,t){let o=r.length;if(e.chars===he||o<=e.chars)return{text:r,truncated:!1,totalCharacters:o};let s=r.slice(0,e.chars);return{text:`${s}
40
40
 
41
- ${fc(s,o.length,t)}`,truncated:!0,totalCharacters:s}}function gp(n,e,t){let s=n.length;if(e.chars===he&&e.items===he)return{text:n,truncated:!1,totalCharacters:s};let o=hp(n);if(!o)return dc(n,e,t);let a=e.items===he?[he,1,0]:[e.items,Math.max(1,Math.floor(e.items/2)),1,0],l=[he,4e3,1e3,256,64],d=uc(o.value,{items:0,stringChars:64});for(let u of a)for(let f of l){let y=uc(o.value,{items:u,stringChars:f});if(y.lists.length===0&&f===he){if(s<=e.chars)return{text:n,truncated:!1,totalCharacters:s};continue}d=y;let _=JSON.stringify(y.value)??"",S=mo(y.value,y.lists,s,_.length,t);if(S.length<=e.chars)return{text:S,truncated:!0,totalCharacters:s}}let p=yp(d.value,d.lists,s,t,e.chars);return p?{text:p,truncated:!0,totalCharacters:s}:dc(n,e,t)}function yp(n,e,t,s,o){let a=Array.isArray(n)?[["items",n]]:Object.entries(n);if(a.length===0)return;let l=[...a.filter(([u])=>vn[u]),...a.filter(([u])=>!vn[u])],d={};for(let[u,f]of l){let y={...d,[u]:f};(mo(y,e,t,JSON.stringify(y).length,s).length<=o||vn[u])&&(d[u]=f)}let p=JSON.stringify(d)??"";return mo(d,e,t,p.length,s)}function mc(n,e,t){if(n.isError)return n;let s=!1,o=n.content.map(a=>{if(a.type!=="text")return a;let l=gp(a.text,e,t);return l.truncated?(s=!0,{...a,text:l.text}):a});return s?{...n,content:o}:n}var bp=20,hc=100,Sp="Pass full: true for the complete payload, or raise max_chars up to 100000.",wp=["max_chars","full"];function _p(n,e){if(n===void 0)return bp;if(typeof n!="number"||!Number.isFinite(n)||!Number.isInteger(n))throw new U(`${e} must be an integer`,"VALIDATION_ERROR",`Use an integer from 1 to ${hc}`);return Math.min(Math.max(n,1),hc)}function Tp(n,e,t){let s={...e},o=t?.[n];return o&&(s[o]=_p(s[o],o)),s}function z(n,e,t={}){let s=t.noAuth?new n:new n(new xn(mn));return function(a){return _n(async()=>{let{action:l,account:d,...p}=a;if(!e.includes(l))throw new U(`Unknown action: ${l}`,"VALIDATION_ERROR",`Valid actions: ${e.join(", ")}`);let u=Tp(l,p,t.pagination),f=t.bounds?.[l];if(t.bounds)for(let S of wp)delete u[S];let y=f?pc(p,f):void 0,g=s[l],_=await ac(d,()=>g(u));return!f||!y?_:mc(_,y,f.hint??Sp)})()}}var Cn=["listCalendars","createEvent","listEvents","getEvent","deleteEvent","updateEvent","respondToEvent","findFreeTime"],gc=z(En,Cn,{pagination:{listEvents:"maxResults"},bounds:rc});import{google as yc}from"googleapis";var An=class{constructor(e){this.authManager=e;this.listSpaces=async({pageSize:e,pageToken:t}={})=>{m("Listing chat spaces");try{let o=await(await this.getChatClient()).spaces.list({...e!==void 0&&{pageSize:e},...t!==void 0&&{pageToken:t}}),a=o.data.spaces||[];return m(`Successfully listed ${a.length} chat spaces.`),{content:[{type:"text",text:JSON.stringify({spaces:a,nextPageToken:o.data.nextPageToken??null})}]}}catch(s){let o=s instanceof Error?s.message:String(s);return m(`Error during chat.listSpaces: ${o}`),s instanceof Error&&s.stack&&m(`Stack trace: ${s.stack}`),m(`Full error object: ${JSON.stringify(s,null,2)}`),{content:[{type:"text",text:JSON.stringify({error:"An error occurred while listing chat spaces.",details:o})}]}}};this.sendMessage=async({spaceName:e,message:t,threadName:s})=>{m(`Sending message to space: ${e}${s?` in thread: ${s}`:""}`);try{let a=await(await this.getChatClient()).spaces.messages.create({parent:e,messageReplyOption:s?"REPLY_MESSAGE_FALLBACK_TO_NEW_THREAD":void 0,requestBody:{text:t,thread:s?{name:s}:void 0}});return m(`Successfully sent message to space: ${e}`),{content:[{type:"text",text:JSON.stringify(a.data)}]}}catch(o){let a=o instanceof Error?o.message:String(o);return m(`Error during chat.sendMessage: ${a}`),o instanceof Error&&o.stack&&m(`Stack trace: ${o.stack}`),m(`Full error object: ${JSON.stringify(o,null,2)}`),{content:[{type:"text",text:JSON.stringify({error:"An error occurred while sending the message.",details:a})}]}}};this.findSpaceByName=async({displayName:e})=>{m(`Finding space with display name: ${e}`);try{let t=await this.getChatClient(),s,o=[];do{let l=await t.spaces.list({pageToken:s}),d=l.data.spaces||[];o=o.concat(d),s=l.data.nextPageToken||void 0}while(s);let a=o.filter(l=>l.displayName===e);return a.length>0?(m(`Found ${a.length} space(s) with display name: ${e}`),{content:[{type:"text",text:JSON.stringify(a)}]}):(m(`No space found with display name: ${e}`),{content:[{type:"text",text:JSON.stringify({error:`No space found with display name: ${e}`})}]})}catch(t){let s=t instanceof Error?t.message:String(t);return m(`Error during chat.findSpaceByName: ${s}`),t instanceof Error&&t.stack&&m(`Stack trace: ${t.stack}`),m(`Full error object: ${JSON.stringify(t,null,2)}`),{content:[{type:"text",text:JSON.stringify({error:"An error occurred while finding the space.",details:s})}]}}};this.getMessages=async({spaceName:e,unreadOnly:t,pageSize:s,pageToken:o,orderBy:a,threadName:l})=>{m(`Listing messages for space: ${e}`);try{let d=await this.getChatClient(),p=[];if(l&&p.push(`thread.name = "${l}"`),t){let E=(await(await this.getPeopleClient()).people.get({resourceName:"people/me",personFields:"metadata"})).data.metadata?.sources?.find(k=>k.type==="PROFILE")?.id;if(!E)throw new Error("Could not determine user ID.");let R=`users/${E}`,v=((await d.spaces.members.list({parent:e})).data.memberships||[]).find(k=>k.member?.name===R)?.lastReadTime;v?p.push(`createTime > "${v}"`):m(`No last read time found for user in space: ${e}`)}let u=p.join(" AND "),f=await d.spaces.messages.list({parent:e,filter:u||void 0,pageSize:s,pageToken:o,orderBy:a}),y=f.data.messages||[],g=t?`Successfully listed ${y.length} unread messages for space: ${e}`:`Successfully listed ${y.length} messages for space: ${e}`;return m(g),{content:[{type:"text",text:JSON.stringify({messages:y,nextPageToken:f.data.nextPageToken})}]}}catch(d){let p=d instanceof Error?d.message:String(d);return m(`Error during chat.getMessages: ${p}`),d instanceof Error&&d.stack&&m(`Stack trace: ${d.stack}`),m(`Full error object: ${JSON.stringify(d,null,2)}`),{content:[{type:"text",text:JSON.stringify({error:"An error occurred while listing messages.",details:p})}]}}};this.sendDm=async({email:e,message:t,threadName:s})=>{m(`chat.sendDm called with: email=${e}, message=${t}${s?`, threadName=${s}`:""}`);try{let a=(await this._setupDmSpace(e)).name;if(!a)throw new Error("Could not determine the space name for the DM.");let d=await(await this.getChatClient()).spaces.messages.create({parent:a,messageReplyOption:s?"REPLY_MESSAGE_FALLBACK_TO_NEW_THREAD":void 0,requestBody:{text:t,thread:s?{name:s}:void 0}});return m(`Successfully sent DM to: ${e}`),{content:[{type:"text",text:JSON.stringify(d.data)}]}}catch(o){let a=o instanceof Error?o.message:String(o);return m(`Error during chat.sendDm: ${a}`),o instanceof Error&&o.stack&&m(`Stack trace: ${o.stack}`),m(`Full error object: ${JSON.stringify(o,null,2)}`),{content:[{type:"text",text:JSON.stringify({error:"An error occurred while sending the DM.",details:a})}]}}};this.findDmByEmail=async({email:e})=>{m(`Finding DM space with user: ${e}`);try{let t=await this._setupDmSpace(e);return m(`Found or created DM space: ${t.name}`),{content:[{type:"text",text:JSON.stringify(t)}]}}catch(t){let s=t instanceof Error?t.message:String(t);return m(`Error during chat.findDmByEmail: ${s}`),t instanceof Error&&t.stack&&m(`Stack trace: ${t.stack}`),m(`Full error object: ${JSON.stringify(t,null,2)}`),{content:[{type:"text",text:JSON.stringify({error:"An error occurred while finding the DM space.",details:s})}]}}};this.listThreads=async({spaceName:e,pageSize:t,pageToken:s})=>{m(`Listing threads for space: ${e}`);try{let a=await(await this.getChatClient()).spaces.messages.list({parent:e,pageSize:t,pageToken:s,orderBy:"createTime desc"}),l=a.data.messages||[],d=[],p=new Set;for(let u of l)u.thread?.name&&!p.has(u.thread.name)&&(d.push(u),p.add(u.thread.name));return m(`Successfully listed ${d.length} threads for space: ${e}`),{content:[{type:"text",text:JSON.stringify({threads:d,nextPageToken:a.data.nextPageToken})}]}}catch(o){let a=o instanceof Error?o.message:String(o);return m(`Error during chat.listThreads: ${a}`),o instanceof Error&&o.stack&&m(`Stack trace: ${o.stack}`),m(`Full error object: ${JSON.stringify(o,null,2)}`),{content:[{type:"text",text:JSON.stringify({error:"An error occurred while listing threads.",details:a})}]}}};this.setUpSpace=async({displayName:e,userNames:t})=>{m(`Creating space with display name: ${e}`);try{let s=t.map(l=>({member:{name:l,type:"HUMAN"}})),a=await(await this.getChatClient()).spaces.setup({requestBody:{space:{spaceType:"SPACE",displayName:e},memberships:s}});return m(`Successfully created space: ${a.data.name}`),{content:[{type:"text",text:JSON.stringify(a.data)}]}}catch(s){let o=s instanceof Error?s.message:String(s);return m(`Error during chat.createSpace: ${o}`),s instanceof Error&&s.stack&&m(`Stack trace: ${s.stack}`),m(`Full error object: ${JSON.stringify(s,null,2)}`),{content:[{type:"text",text:JSON.stringify({error:"An error occurred while creating the space.",details:o})}]}}}}async getChatClient(){let e=await this.authManager.getAuthenticatedClient(),t={...W,auth:e};return yc.chat({version:"v1",...t})}async getPeopleClient(){let e=await this.authManager.getAuthenticatedClient(),t={...W,auth:e};return yc.people({version:"v1",...t})}async _setupDmSpace(e){let t={name:`users/${e}`,type:"HUMAN"},a=(await(await this.getChatClient()).spaces.setup({requestBody:{space:{spaceType:"DIRECT_MESSAGE"},memberships:[{member:t}]}})).data;if(!a)throw new Error("Could not find or create a DM space.");return a}};var Pn=["listSpaces","sendMessage","findSpaceByName","getMessages","sendDm","findDmByEmail","listThreads","setUpSpace"],bc=z(An,Pn,{pagination:{listSpaces:"pageSize",getMessages:"pageSize",listThreads:"pageSize"},bounds:tc});import{google as xp}from"googleapis";var Rp=/\/d\/([a-zA-Z0-9-_]+)/;function F(n){if(m(`[IdUtils] Attempting to extract doc ID from URL: ${n}`),!n||typeof n!="string"){m("[IdUtils] Invalid input: URL is null or not a string.");return}let e=n.match(Rp);if(e&&e[1]){let t=e[1];return m(`[IdUtils] Successfully extracted doc ID: ${t}`),t}m("[IdUtils] Could not extract doc ID from URL.")}var Ep=Number.POSITIVE_INFINITY;function Yt(n,e,t){return`[Content truncated: showing ${e} of ${n} characters (${n-e} omitted). ${t}]`}function ho(n,e){if(e===!0)return Ep;if(n===void 0)return 2e4;if(typeof n!="number"||!Number.isInteger(n)||n<1||n>1e5)throw new Error("max_chars must be an integer between 1 and 100000.");return n}function Sc(n,e,t){let s=n.length;return s<=e?{text:n,truncated:!1,totalCharacters:s,returnedCharacters:s}:{text:`${n.slice(0,e)}
41
+ ${fc(o,s.length,t)}`,truncated:!0,totalCharacters:o}}function gp(r,e,t){let o=r.length;if(e.chars===he&&e.items===he)return{text:r,truncated:!1,totalCharacters:o};let s=hp(r);if(!s)return dc(r,e,t);let a=e.items===he?[he,1,0]:[e.items,Math.max(1,Math.floor(e.items/2)),1,0],l=[he,4e3,1e3,256,64],d=uc(s.value,{items:0,stringChars:64});for(let u of a)for(let f of l){let y=uc(s.value,{items:u,stringChars:f});if(y.lists.length===0&&f===he){if(o<=e.chars)return{text:r,truncated:!1,totalCharacters:o};continue}d=y;let _=JSON.stringify(y.value)??"",S=ms(y.value,y.lists,o,_.length,t);if(S.length<=e.chars)return{text:S,truncated:!0,totalCharacters:o}}let p=yp(d.value,d.lists,o,t,e.chars);return p?{text:p,truncated:!0,totalCharacters:o}:dc(r,e,t)}function yp(r,e,t,o,s){let a=Array.isArray(r)?[["items",r]]:Object.entries(r);if(a.length===0)return;let l=[...a.filter(([u])=>vn[u]),...a.filter(([u])=>!vn[u])],d={};for(let[u,f]of l){let y={...d,[u]:f};(ms(y,e,t,JSON.stringify(y).length,o).length<=s||vn[u])&&(d[u]=f)}let p=JSON.stringify(d)??"";return ms(d,e,t,p.length,o)}function mc(r,e,t){if(r.isError)return r;let o=!1,s=r.content.map(a=>{if(a.type!=="text")return a;let l=gp(a.text,e,t);return l.truncated?(o=!0,{...a,text:l.text}):a});return o?{...r,content:s}:r}var bp=20,hc=100,Sp="Pass full: true for the complete payload, or raise max_chars up to 100000.",wp=["max_chars","full"];function _p(r,e){if(r===void 0)return bp;if(typeof r!="number"||!Number.isFinite(r)||!Number.isInteger(r))throw new U(`${e} must be an integer`,"VALIDATION_ERROR",`Use an integer from 1 to ${hc}`);return Math.min(Math.max(r,1),hc)}function Tp(r,e,t){let o={...e},s=t?.[r];return s&&(o[s]=_p(o[s],s)),o}function Rp(r){if(r.isError===!0)return r;let e=r.content[0];if(e?.type!=="text"||!e.text.startsWith("{")||!e.text.includes('"error"'))return r;let t;try{t=JSON.parse(e.text)}catch{return r}return typeof t.error!="string"?r:{...r,isError:!0}}function z(r,e,t={}){let o=t.noAuth?new r:new r(new xn(mn));return function(a){return _n(async()=>{let{action:l,account:d,...p}=a;if(!e.includes(l))throw new U(`Unknown action: ${l}`,"VALIDATION_ERROR",`Valid actions: ${e.join(", ")}`);let u=Tp(l,p,t.pagination),f=t.bounds?.[l];if(t.bounds)for(let S of wp)delete u[S];let y=f?pc(p,f):void 0,g=o[l],_=Rp(await ac(d,()=>g(u)));return!f||!y?_:mc(_,y,f.hint??Sp)})()}}var Cn=["listCalendars","createEvent","listEvents","getEvent","deleteEvent","updateEvent","respondToEvent","findFreeTime"],gc=z(En,Cn,{pagination:{listEvents:"maxResults"},bounds:rc});import{google as yc}from"googleapis";var An=class{constructor(e){this.authManager=e;this.listSpaces=async({pageSize:e,pageToken:t}={})=>{m("Listing chat spaces");try{let s=await(await this.getChatClient()).spaces.list({...e!==void 0&&{pageSize:e},...t!==void 0&&{pageToken:t}}),a=s.data.spaces||[];return m(`Successfully listed ${a.length} chat spaces.`),{content:[{type:"text",text:JSON.stringify({spaces:a,nextPageToken:s.data.nextPageToken??null})}]}}catch(o){let s=o instanceof Error?o.message:String(o);return m(`Error during chat.listSpaces: ${s}`),o instanceof Error&&o.stack&&m(`Stack trace: ${o.stack}`),m(`Full error object: ${JSON.stringify(o,null,2)}`),{content:[{type:"text",text:JSON.stringify({error:"An error occurred while listing chat spaces.",details:s})}]}}};this.sendMessage=async({spaceName:e,message:t,threadName:o})=>{m(`Sending message to space: ${e}${o?` in thread: ${o}`:""}`);try{let a=await(await this.getChatClient()).spaces.messages.create({parent:e,messageReplyOption:o?"REPLY_MESSAGE_FALLBACK_TO_NEW_THREAD":void 0,requestBody:{text:t,thread:o?{name:o}:void 0}});return m(`Successfully sent message to space: ${e}`),{content:[{type:"text",text:JSON.stringify(a.data)}]}}catch(s){let a=s instanceof Error?s.message:String(s);return m(`Error during chat.sendMessage: ${a}`),s instanceof Error&&s.stack&&m(`Stack trace: ${s.stack}`),m(`Full error object: ${JSON.stringify(s,null,2)}`),{content:[{type:"text",text:JSON.stringify({error:"An error occurred while sending the message.",details:a})}]}}};this.findSpaceByName=async({displayName:e})=>{m(`Finding space with display name: ${e}`);try{let t=await this.getChatClient(),o,s=[];do{let l=await t.spaces.list({pageToken:o}),d=l.data.spaces||[];s=s.concat(d),o=l.data.nextPageToken||void 0}while(o);let a=s.filter(l=>l.displayName===e);return a.length>0?(m(`Found ${a.length} space(s) with display name: ${e}`),{content:[{type:"text",text:JSON.stringify(a)}]}):(m(`No space found with display name: ${e}`),{content:[{type:"text",text:JSON.stringify({error:`No space found with display name: ${e}`})}]})}catch(t){let o=t instanceof Error?t.message:String(t);return m(`Error during chat.findSpaceByName: ${o}`),t instanceof Error&&t.stack&&m(`Stack trace: ${t.stack}`),m(`Full error object: ${JSON.stringify(t,null,2)}`),{content:[{type:"text",text:JSON.stringify({error:"An error occurred while finding the space.",details:o})}]}}};this.getMessages=async({spaceName:e,unreadOnly:t,pageSize:o,pageToken:s,orderBy:a,threadName:l})=>{m(`Listing messages for space: ${e}`);try{let d=await this.getChatClient(),p=[];if(l&&p.push(`thread.name = "${l}"`),t){let E=(await(await this.getPeopleClient()).people.get({resourceName:"people/me",personFields:"metadata"})).data.metadata?.sources?.find(k=>k.type==="PROFILE")?.id;if(!E)throw new Error("Could not determine user ID.");let R=`users/${E}`,v=((await d.spaces.members.list({parent:e})).data.memberships||[]).find(k=>k.member?.name===R)?.lastReadTime;v?p.push(`createTime > "${v}"`):m(`No last read time found for user in space: ${e}`)}let u=p.join(" AND "),f=await d.spaces.messages.list({parent:e,filter:u||void 0,pageSize:o,pageToken:s,orderBy:a}),y=f.data.messages||[],g=t?`Successfully listed ${y.length} unread messages for space: ${e}`:`Successfully listed ${y.length} messages for space: ${e}`;return m(g),{content:[{type:"text",text:JSON.stringify({messages:y,nextPageToken:f.data.nextPageToken})}]}}catch(d){let p=d instanceof Error?d.message:String(d);return m(`Error during chat.getMessages: ${p}`),d instanceof Error&&d.stack&&m(`Stack trace: ${d.stack}`),m(`Full error object: ${JSON.stringify(d,null,2)}`),{content:[{type:"text",text:JSON.stringify({error:"An error occurred while listing messages.",details:p})}]}}};this.sendDm=async({email:e,message:t,threadName:o})=>{m(`chat.sendDm called with: email=${e}, message=${t}${o?`, threadName=${o}`:""}`);try{let a=(await this._setupDmSpace(e)).name;if(!a)throw new Error("Could not determine the space name for the DM.");let d=await(await this.getChatClient()).spaces.messages.create({parent:a,messageReplyOption:o?"REPLY_MESSAGE_FALLBACK_TO_NEW_THREAD":void 0,requestBody:{text:t,thread:o?{name:o}:void 0}});return m(`Successfully sent DM to: ${e}`),{content:[{type:"text",text:JSON.stringify(d.data)}]}}catch(s){let a=s instanceof Error?s.message:String(s);return m(`Error during chat.sendDm: ${a}`),s instanceof Error&&s.stack&&m(`Stack trace: ${s.stack}`),m(`Full error object: ${JSON.stringify(s,null,2)}`),{content:[{type:"text",text:JSON.stringify({error:"An error occurred while sending the DM.",details:a})}]}}};this.findDmByEmail=async({email:e})=>{m(`Finding DM space with user: ${e}`);try{let t=await this._setupDmSpace(e);return m(`Found or created DM space: ${t.name}`),{content:[{type:"text",text:JSON.stringify(t)}]}}catch(t){let o=t instanceof Error?t.message:String(t);return m(`Error during chat.findDmByEmail: ${o}`),t instanceof Error&&t.stack&&m(`Stack trace: ${t.stack}`),m(`Full error object: ${JSON.stringify(t,null,2)}`),{content:[{type:"text",text:JSON.stringify({error:"An error occurred while finding the DM space.",details:o})}]}}};this.listThreads=async({spaceName:e,pageSize:t,pageToken:o})=>{m(`Listing threads for space: ${e}`);try{let a=await(await this.getChatClient()).spaces.messages.list({parent:e,pageSize:t,pageToken:o,orderBy:"createTime desc"}),l=a.data.messages||[],d=[],p=new Set;for(let u of l)u.thread?.name&&!p.has(u.thread.name)&&(d.push(u),p.add(u.thread.name));return m(`Successfully listed ${d.length} threads for space: ${e}`),{content:[{type:"text",text:JSON.stringify({threads:d,nextPageToken:a.data.nextPageToken})}]}}catch(s){let a=s instanceof Error?s.message:String(s);return m(`Error during chat.listThreads: ${a}`),s instanceof Error&&s.stack&&m(`Stack trace: ${s.stack}`),m(`Full error object: ${JSON.stringify(s,null,2)}`),{content:[{type:"text",text:JSON.stringify({error:"An error occurred while listing threads.",details:a})}]}}};this.setUpSpace=async({displayName:e,userNames:t})=>{m(`Creating space with display name: ${e}`);try{let o=t.map(l=>({member:{name:l,type:"HUMAN"}})),a=await(await this.getChatClient()).spaces.setup({requestBody:{space:{spaceType:"SPACE",displayName:e},memberships:o}});return m(`Successfully created space: ${a.data.name}`),{content:[{type:"text",text:JSON.stringify(a.data)}]}}catch(o){let s=o instanceof Error?o.message:String(o);return m(`Error during chat.createSpace: ${s}`),o instanceof Error&&o.stack&&m(`Stack trace: ${o.stack}`),m(`Full error object: ${JSON.stringify(o,null,2)}`),{content:[{type:"text",text:JSON.stringify({error:"An error occurred while creating the space.",details:s})}]}}}}async getChatClient(){let e=await this.authManager.getAuthenticatedClient(),t={...W,auth:e};return yc.chat({version:"v1",...t})}async getPeopleClient(){let e=await this.authManager.getAuthenticatedClient(),t={...W,auth:e};return yc.people({version:"v1",...t})}async _setupDmSpace(e){let t={name:`users/${e}`,type:"HUMAN"},a=(await(await this.getChatClient()).spaces.setup({requestBody:{space:{spaceType:"DIRECT_MESSAGE"},memberships:[{member:t}]}})).data;if(!a)throw new Error("Could not find or create a DM space.");return a}};var Pn=["listSpaces","sendMessage","findSpaceByName","getMessages","sendDm","findDmByEmail","listThreads","setUpSpace"],bc=z(An,Pn,{pagination:{listSpaces:"pageSize",getMessages:"pageSize",listThreads:"pageSize"},bounds:tc});import{google as vp}from"googleapis";var Ep=/\/d\/([a-zA-Z0-9-_]+)/;function F(r){if(m(`[IdUtils] Attempting to extract doc ID from URL: ${r}`),!r||typeof r!="string"){m("[IdUtils] Invalid input: URL is null or not a string.");return}let e=r.match(Ep);if(e&&e[1]){let t=e[1];return m(`[IdUtils] Successfully extracted doc ID: ${t}`),t}m("[IdUtils] Could not extract doc ID from URL.")}var xp=Number.POSITIVE_INFINITY;function Yt(r,e,t){return`[Content truncated: showing ${e} of ${r} characters (${r-e} omitted). ${t}]`}function hs(r,e){if(e===!0)return xp;if(r===void 0)return 2e4;if(typeof r!="number"||!Number.isInteger(r)||r<1||r>1e5)throw new Error("max_chars must be an integer between 1 and 100000.");return r}function Sc(r,e,t){let o=r.length;return o<=e?{text:r,truncated:!1,totalCharacters:o,returnedCharacters:o}:{text:`${r.slice(0,e)}
42
42
 
43
- ${Yt(s,e,t)}`,truncated:!0,totalCharacters:s,returnedCharacters:e}}function wc(n,e,t){let s=JSON.stringify(n,null,2),o=Object.values(n).reduce((_,S)=>_+S.length,0);if(s.length<=e)return{text:s,truncated:!1,totalCharacters:s.length,returnedCharacters:s.length,returnedRows:o,totalRows:o};let l=Math.max(e-512,0),d={},p=0,u=0,f=!1;for(let[_,S]of Object.entries(n)){let E=[];d[_]=E,p+=JSON.stringify(_).length+4;for(let R of S){let x=JSON.stringify(R);if(p+x.length>l){f=!0;break}E.push(R),u+=1,p+=x.length+2}if(f)break}let y=JSON.stringify(d);return{text:JSON.stringify({...d,_truncation:{truncated:!0,total_characters:s.length,returned_characters:y.length,returned_rows:u,total_rows:o,note:Yt(s.length,y.length,t)}}),truncated:!0,totalCharacters:s.length,returnedCharacters:y.length,returnedRows:u,totalRows:o}}var go="tabs(tabProperties,documentTab(body,headers,footers,footnotes))",vp=2e4,Cp=2e3,bo=1e5;function yo(n,e){let t=n.length;if(t<=e)return{text:n,truncated:!1,totalCharacters:t};let s=Yt(t,e,`Request a larger limit, up to ${bo}.`);return{text:`${n.slice(0,e)}
43
+ ${Yt(o,e,t)}`,truncated:!0,totalCharacters:o,returnedCharacters:e}}function wc(r,e,t){let o=JSON.stringify(r,null,2),s=Object.values(r).reduce((_,S)=>_+S.length,0);if(o.length<=e)return{text:o,truncated:!1,totalCharacters:o.length,returnedCharacters:o.length,returnedRows:s,totalRows:s};let l=Math.max(e-512,0),d={},p=0,u=0,f=!1;for(let[_,S]of Object.entries(r)){let E=[];d[_]=E,p+=JSON.stringify(_).length+4;for(let R of S){let x=JSON.stringify(R);if(p+x.length>l){f=!0;break}E.push(R),u+=1,p+=x.length+2}if(f)break}let y=JSON.stringify(d);return{text:JSON.stringify({...d,_truncation:{truncated:!0,total_characters:o.length,returned_characters:y.length,returned_rows:u,total_rows:s,note:Yt(o.length,y.length,t)}}),truncated:!0,totalCharacters:o.length,returnedCharacters:y.length,returnedRows:u,totalRows:s}}var gs="tabs(tabProperties,documentTab(body,headers,footers,footnotes))",Cp=2e4,Ap=2e3,bs=1e5;function ys(r,e){let t=r.length;if(t<=e)return{text:r,truncated:!1,totalCharacters:t};let o=Yt(t,e,`Request a larger limit, up to ${bs}.`);return{text:`${r.slice(0,e)}
44
44
 
45
- ${s}`,truncated:!0,totalCharacters:t}}var In=class n{constructor(e){this.authManager=e;this.getSuggestions=async({documentId:e})=>{m(`[DocsService] Starting getSuggestions for document: ${e}`);try{let t=F(e)||e,o=await(await this.getDocsClient()).documents.get({documentId:t,suggestionsViewMode:"SUGGESTIONS_INLINE",fields:"title,body"}),a=this._extractSuggestions(o.data.body);return m(`[DocsService] Found ${a.length} suggestions for document: ${t}`),{content:[{type:"text",text:JSON.stringify({title:o.data.title,suggestions:a},null,2)}]}}catch(t){let s=t instanceof Error?t.message:String(t);return m(`[DocsService] Error during docs.getSuggestions: ${s}`),{isError:!0,content:[{type:"text",text:JSON.stringify({error:s})}]}}};this.create=async({title:e,content:t})=>{m(`[DocsService] Starting create with title: ${e}, content: ${t?"true":"false"}`);try{m("[DocsService] Calling docs.documents.create");let s=await this.getDocsClient(),o=await s.documents.create({requestBody:{title:e}});m("[DocsService] docs.documents.create finished");let a=o.data.documentId,l=o.data.title;return t&&(m("[DocsService] Inserting content into new doc"),await s.documents.batchUpdate({documentId:a,requestBody:{requests:[{insertText:{location:{index:1},text:t}}]}}),m("[DocsService] Content insertion finished")),{content:[{type:"text",text:JSON.stringify({documentId:a,title:l})}]}}catch(s){let o=s instanceof Error?s.message:String(s);return m(`Error during docs.create: ${o}`),{content:[{type:"text",text:JSON.stringify({error:o})}]}}};this.writeText=async({documentId:e,text:t,position:s="end",tabId:o})=>{m(`[DocsService] Starting writeText for document: ${e}, position: ${s}, tabId: ${o}`);try{let a=F(e)||e,l=await this.getDocsClient();if(s==="end"&&!o)await l.documents.batchUpdate({documentId:a,requestBody:{requests:[{insertText:{text:t}}]}});else{let d;if(s==="beginning")d=1;else if(s==="end"){let p=await l.documents.get({documentId:a,fields:go,includeTabsContent:!0}),u=this._flattenTabs(p.data.tabs||[]),f;if(o){let _=u.find(S=>S.tabProperties?.tabId===o);if(!_)throw new Error(`Tab with ID ${o} not found.`);f=_.documentTab?.body?.content}else u.length>0&&(f=u[0].documentTab?.body?.content);let g=f?.[f.length-1]?.endIndex||1;d=Math.max(1,g-1)}else if(d=parseInt(s,10),isNaN(d)||d<1)throw new Error(`Invalid position: "${s}". Use "beginning", "end", or a positive integer index.`);await l.documents.batchUpdate({documentId:a,requestBody:{requests:[{insertText:{location:{index:d,tabId:o},text:t}}]}})}return m(`[DocsService] Finished writeText for document: ${a}`),{content:[{type:"text",text:`Successfully wrote text to document ${a} at position ${s}`}]}}catch(a){let l=a instanceof Error?a.message:String(a);return m(`[DocsService] Error during docs.writeText: ${l}`),{content:[{type:"text",text:JSON.stringify({error:l})}]}}};this.formatText=async({documentId:e,formats:t,tabId:s})=>{m(`[DocsService] Starting formatText for document: ${e}, ${t.length} format(s)`);try{let o=F(e)||e,a=[];for(let d of t){let p={startIndex:d.startIndex,endIndex:d.endIndex,tabId:s},u=n.HEADING_STYLES[d.style.toLowerCase()];if(u){a.push({updateParagraphStyle:{range:p,paragraphStyle:{namedStyleType:u},fields:"namedStyleType"}});continue}let f=n.TEXT_STYLES[d.style.toLowerCase()];if(f){a.push({updateTextStyle:{range:p,textStyle:f,fields:Object.keys(f).join(",")}});continue}if(d.style.toLowerCase()==="code"){a.push({updateTextStyle:{range:p,textStyle:{weightedFontFamily:{fontFamily:"Courier New"}},fields:"weightedFontFamily"}});continue}if(d.style.toLowerCase()==="link"&&d.url){a.push({updateTextStyle:{range:p,textStyle:{link:{url:d.url}},fields:"link"}});continue}m(`[DocsService] Unknown format style: ${d.style}`)}return a.length===0?{content:[{type:"text",text:"No valid formatting requests to apply."}]}:(await(await this.getDocsClient()).documents.batchUpdate({documentId:o,requestBody:{requests:a}}),m(`[DocsService] Finished formatText for document: ${o}, applied ${a.length} format(s)`),{content:[{type:"text",text:`Successfully applied ${a.length} format(s) to document ${o}`}]})}catch(o){let a=o instanceof Error?o.message:String(o);return m(`[DocsService] Error during docs.formatText: ${a}`),{content:[{type:"text",text:JSON.stringify({error:a})}]}}};this.getText=async({documentId:e,tabId:t,limit:s,preview:o=!1})=>{m(`[DocsService] Starting getText for document: ${e}, tabId: ${t}`);try{let a=s??(o?Cp:vp);if(!Number.isInteger(a)||a<1||a>bo)throw new Error(`limit must be an integer from 1 to ${bo}.`);let l=ct(e),p=await(await this.getDocsClient()).documents.get({documentId:l,fields:`title,${go}`,includeTabsContent:!0,suggestionsViewMode:"PREVIEW_WITHOUT_SUGGESTIONS"}),u=p.data.title,f=this._flattenTabs(p.data.tabs||[]);if(t){let g=f.find(E=>E.tabProperties?.tabId===t);if(!g)throw new Error(`Tab with ID ${t} not found.`);let _=g.documentTab?.body?.content;if(!_)return{content:[{type:"text",text:""}]};let S=u?`Document Title: ${u}
45
+ ${o}`,truncated:!0,totalCharacters:t}}var In=class r{constructor(e){this.authManager=e;this.getSuggestions=async({documentId:e})=>{m(`[DocsService] Starting getSuggestions for document: ${e}`);try{let t=F(e)||e,s=await(await this.getDocsClient()).documents.get({documentId:t,suggestionsViewMode:"SUGGESTIONS_INLINE",fields:"title,body"}),a=this._extractSuggestions(s.data.body);return m(`[DocsService] Found ${a.length} suggestions for document: ${t}`),{content:[{type:"text",text:JSON.stringify({title:s.data.title,suggestions:a},null,2)}]}}catch(t){let o=t instanceof Error?t.message:String(t);return m(`[DocsService] Error during docs.getSuggestions: ${o}`),{isError:!0,content:[{type:"text",text:JSON.stringify({error:o})}]}}};this.create=async({title:e,content:t})=>{m(`[DocsService] Starting create with title: ${e}, content: ${t?"true":"false"}`);try{m("[DocsService] Calling docs.documents.create");let o=await this.getDocsClient(),s=await o.documents.create({requestBody:{title:e}});m("[DocsService] docs.documents.create finished");let a=s.data.documentId,l=s.data.title;return t&&(m("[DocsService] Inserting content into new doc"),await o.documents.batchUpdate({documentId:a,requestBody:{requests:[{insertText:{location:{index:1},text:t}}]}}),m("[DocsService] Content insertion finished")),{content:[{type:"text",text:JSON.stringify({documentId:a,title:l})}]}}catch(o){let s=o instanceof Error?o.message:String(o);return m(`Error during docs.create: ${s}`),{content:[{type:"text",text:JSON.stringify({error:s})}]}}};this.writeText=async({documentId:e,text:t,position:o="end",tabId:s})=>{m(`[DocsService] Starting writeText for document: ${e}, position: ${o}, tabId: ${s}`);try{let a=F(e)||e,l=await this.getDocsClient();if(o==="end"&&!s)await l.documents.batchUpdate({documentId:a,requestBody:{requests:[{insertText:{text:t}}]}});else{let d;if(o==="beginning")d=1;else if(o==="end"){let p=await l.documents.get({documentId:a,fields:gs,includeTabsContent:!0}),u=this._flattenTabs(p.data.tabs||[]),f;if(s){let _=u.find(S=>S.tabProperties?.tabId===s);if(!_)throw new Error(`Tab with ID ${s} not found.`);f=_.documentTab?.body?.content}else u.length>0&&(f=u[0].documentTab?.body?.content);let g=f?.[f.length-1]?.endIndex||1;d=Math.max(1,g-1)}else if(d=parseInt(o,10),isNaN(d)||d<1)throw new Error(`Invalid position: "${o}". Use "beginning", "end", or a positive integer index.`);await l.documents.batchUpdate({documentId:a,requestBody:{requests:[{insertText:{location:{index:d,tabId:s},text:t}}]}})}return m(`[DocsService] Finished writeText for document: ${a}`),{content:[{type:"text",text:`Successfully wrote text to document ${a} at position ${o}`}]}}catch(a){let l=a instanceof Error?a.message:String(a);return m(`[DocsService] Error during docs.writeText: ${l}`),{content:[{type:"text",text:JSON.stringify({error:l})}]}}};this.formatText=async({documentId:e,formats:t,tabId:o})=>{m(`[DocsService] Starting formatText for document: ${e}, ${t.length} format(s)`);try{let s=F(e)||e,a=[];for(let d of t){let p={startIndex:d.startIndex,endIndex:d.endIndex,tabId:o},u=r.HEADING_STYLES[d.style.toLowerCase()];if(u){a.push({updateParagraphStyle:{range:p,paragraphStyle:{namedStyleType:u},fields:"namedStyleType"}});continue}let f=r.TEXT_STYLES[d.style.toLowerCase()];if(f){a.push({updateTextStyle:{range:p,textStyle:f,fields:Object.keys(f).join(",")}});continue}if(d.style.toLowerCase()==="code"){a.push({updateTextStyle:{range:p,textStyle:{weightedFontFamily:{fontFamily:"Courier New"}},fields:"weightedFontFamily"}});continue}if(d.style.toLowerCase()==="link"&&d.url){a.push({updateTextStyle:{range:p,textStyle:{link:{url:d.url}},fields:"link"}});continue}m(`[DocsService] Unknown format style: ${d.style}`)}return a.length===0?{content:[{type:"text",text:"No valid formatting requests to apply."}]}:(await(await this.getDocsClient()).documents.batchUpdate({documentId:s,requestBody:{requests:a}}),m(`[DocsService] Finished formatText for document: ${s}, applied ${a.length} format(s)`),{content:[{type:"text",text:`Successfully applied ${a.length} format(s) to document ${s}`}]})}catch(s){let a=s instanceof Error?s.message:String(s);return m(`[DocsService] Error during docs.formatText: ${a}`),{content:[{type:"text",text:JSON.stringify({error:a})}]}}};this.getText=async({documentId:e,tabId:t,limit:o,preview:s=!1})=>{m(`[DocsService] Starting getText for document: ${e}, tabId: ${t}`);try{let a=o??(s?Ap:Cp);if(!Number.isInteger(a)||a<1||a>bs)throw new Error(`limit must be an integer from 1 to ${bs}.`);let l=ct(e),p=await(await this.getDocsClient()).documents.get({documentId:l,fields:`title,${gs}`,includeTabsContent:!0,suggestionsViewMode:"PREVIEW_WITHOUT_SUGGESTIONS"}),u=p.data.title,f=this._flattenTabs(p.data.tabs||[]);if(t){let g=f.find(E=>E.tabProperties?.tabId===t);if(!g)throw new Error(`Tab with ID ${t} not found.`);let _=g.documentTab?.body?.content;if(!_)return{content:[{type:"text",text:""}]};let S=u?`Document Title: ${u}
46
46
 
47
- `:"";return _.forEach(E=>{S+=this._readStructuralElement(E)}),{content:[{type:"text",text:yo(S,a).text}]}}if(f.length===0)return{content:[{type:"text",text:""}]};if(f.length===1){let g=f[0],_=u?`Document Title: ${u}
47
+ `:"";return _.forEach(E=>{S+=this._readStructuralElement(E)}),{content:[{type:"text",text:ys(S,a).text}]}}if(f.length===0)return{content:[{type:"text",text:""}]};if(f.length===1){let g=f[0],_=u?`Document Title: ${u}
48
48
 
49
- `:"";return g.documentTab?.body?.content?.forEach(S=>{_+=this._readStructuralElement(S)}),{content:[{type:"text",text:yo(_,a).text}]}}let y=f.map((g,_)=>{let S="";g.documentTab?.body?.content?.forEach(R=>{S+=this._readStructuralElement(R)});let E=yo(S,a);return{tabId:g.tabProperties?.tabId,title:g.tabProperties?.title,content:E.text,truncated:E.truncated,totalCharacters:E.totalCharacters,index:_}});return{content:[{type:"text",text:JSON.stringify({title:u,tabs:y},null,2)}]}}catch(a){let l=a instanceof Error?a.message:String(a);return m(`[DocsService] Error during docs.getText: ${l}`),{content:[{type:"text",text:JSON.stringify({error:l})}]}}};this.replaceText=async({documentId:e,findText:t,replaceText:s,tabId:o})=>{m(`[DocsService] Starting replaceText for document: ${e}, tabId: ${o}`);try{let a=F(e)||e,l=await this.getDocsClient(),d=await l.documents.get({documentId:a,fields:go,includeTabsContent:!0}),p=this._flattenTabs(d.data.tabs||[]),u=[];if(o){let f=p.find(_=>_.tabProperties?.tabId===o);if(!f)throw new Error(`Tab with ID ${o} not found.`);let y=f.documentTab?.body?.content,g=this._generateReplacementRequests(y,o,t,s);for(let _ of g)u.push(_)}else for(let f of p){let y=f.tabProperties?.tabId,g=f.documentTab?.body?.content,_=this._generateReplacementRequests(g,y,t,s);for(let S of _)u.push(S)}return u.length>0&&await l.documents.batchUpdate({documentId:a,requestBody:{requests:u}}),m(`[DocsService] Finished replaceText for document: ${a}`),{content:[{type:"text",text:`Successfully replaced text in document ${a}`}]}}catch(a){let l=a instanceof Error?a.message:String(a);return m(`[DocsService] Error during docs.replaceText: ${l}`),{content:[{type:"text",text:JSON.stringify({error:l})}]}}}}_flattenTabs(e){return e.flatMap(t=>{let s=t.childTabs?this._flattenTabs(t.childTabs):[];return[t,...s]})}async getDocsClient(){let e=await this.authManager.getAuthenticatedClient(),t={...W,auth:e};return xp.docs({version:"v1",...t})}_extractSuggestions(e){let t=[];if(!e?.content)return t;let s=o=>{o?.forEach(a=>{if(a.paragraph){if(a.paragraph.suggestedParagraphStyleChanges)for(let[l,d]of Object.entries(a.paragraph.suggestedParagraphStyleChanges))t.push({type:"paragraphStyleChange",text:this._getParagraphText(a.paragraph),suggestionIds:[l],namedStyleType:d?.paragraphStyle?.namedStyleType??void 0,startIndex:a.startIndex??void 0,endIndex:a.endIndex??void 0});a.paragraph.elements?.forEach(l=>{if(l.textRun){let d={text:l.textRun.content||"",startIndex:l.startIndex??void 0,endIndex:l.endIndex??void 0};l.textRun.suggestedInsertionIds&&t.push({...d,type:"insertion",suggestionIds:l.textRun.suggestedInsertionIds}),l.textRun.suggestedDeletionIds&&t.push({...d,type:"deletion",suggestionIds:l.textRun.suggestedDeletionIds}),l.textRun.suggestedTextStyleChanges&&t.push({...d,type:"styleChange",suggestionIds:Object.keys(l.textRun.suggestedTextStyleChanges),textStyle:l.textRun.textStyle})}})}else a.table&&a.table.tableRows?.forEach(l=>{l.tableCells?.forEach(d=>{s(d.content)})})})};return s(e.content),t}_getParagraphText(e){return e?.elements?e.elements.map(t=>t.textRun?.content||"").join(""):""}static{this.HEADING_STYLES={heading1:"HEADING_1",heading2:"HEADING_2",heading3:"HEADING_3",heading4:"HEADING_4",heading5:"HEADING_5",heading6:"HEADING_6",normalText:"NORMAL_TEXT"}}static{this.TEXT_STYLES={bold:{bold:!0},italic:{italic:!0},underline:{underline:!0},strikethrough:{strikethrough:!0}}}_readStructuralElement(e){let t="";return e.paragraph?e.paragraph.elements?.forEach(s=>{s.textRun&&s.textRun.content?t+=s.textRun.content:s.person?.personProperties?t+=this._renderPersonChip(s.person.personProperties):s.richLink?.richLinkProperties?t+=this._renderRichLinkChip(s.richLink.richLinkProperties):s.dateElement?.dateElementProperties&&(t+=this._renderDateChip(s.dateElement.dateElementProperties))}):e.table&&e.table.tableRows?.forEach(s=>{s.tableCells?.forEach(o=>{o.content?.forEach(a=>{t+=this._readStructuralElement(a)})})}),t}_renderPersonChip(e){let{name:t,email:s}=e;return s?`[${t||s}](mailto:${s})`:t||""}_renderRichLinkChip(e){let{title:t,uri:s}=e;return s?`[${t||s}](${s})`:t||""}_renderDateChip(e){let{displayText:t,timestamp:s}=e;return t||s||""}_generateReplacementRequests(e,t,s,o){let a=[],l=this._getFullDocumentText(e),d=[],p=0;for(;(p=l.indexOf(s,p))!==-1;)d.push(p+1),p+=s.length;let u=o.length-s.length,f=0;for(let y=0;y<d.length;y++){let _=d[y]+f;a.push({deleteContentRange:{range:{tabId:t,startIndex:_,endIndex:_+s.length}}}),a.push({insertText:{location:{tabId:t,index:_},text:o}}),f+=u}return a}_getFullDocumentText(e){let t="";return e&&e.forEach(s=>{t+=this._readStructuralElement(s)}),t}};var So=["getText","create","writeText","getSuggestions","replaceText","formatText"],_c=z(In,So,{bounds:Xa});import{google as Op}from"googleapis";function On(n){return n.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}import*as wo from"node:fs";import*as lt from"node:path";import kn from"node:path";import Ap from"node:fs";import{fileURLToPath as Pp}from"node:url";function Ip(){let n=kn.dirname(Pp(import.meta.url));for(;n!==kn.dirname(n);){if(Ap.existsSync(kn.join(n,"package.json")))return n;n=kn.dirname(n)}return process.cwd()}var $n=Ip();var kp=25,$p=new Set(["drive.google.com","docs.google.com"]);function Dp(n){try{return $p.has(new URL(n).hostname)}catch{return!1}}var Lp=[{pattern:/\/folders\/([a-zA-Z0-9-_]+)/,type:"folder"},{pattern:/\/file\/d\/([a-zA-Z0-9-_]+)/,type:"file"},{pattern:/\/document\/d\/([a-zA-Z0-9-_]+)/,type:"file"},{pattern:/\/spreadsheets\/d\/([a-zA-Z0-9-_]+)/,type:"file"},{pattern:/\/presentation\/d\/([a-zA-Z0-9-_]+)/,type:"file"},{pattern:/\/forms\/d\/([a-zA-Z0-9-_]+)/,type:"file"},{pattern:/[?&]id=([a-zA-Z0-9-_]+)/,type:"unknown"}],Dn=class{constructor(e){this.authManager=e;this.findFolder=async({folderName:e})=>{m(`Searching for folder with name: ${e}`);try{let t=await this.getDriveClient(),s=`mimeType='application/vnd.google-apps.folder' and name = '${On(e)}'`;m(`Executing Drive API query: ${s}`);let a=(await t.files.list({q:s,fields:"files(id, name)",spaces:"drive",supportsAllDrives:!0,includeItemsFromAllDrives:!0})).data.files||[];return m(`Found ${a.length} folders.`),m(`API Response: ${JSON.stringify(a,null,2)}`),{content:[{type:"text",text:JSON.stringify(a)}]}}catch(t){return this.handleError("drive.findFolder",t)}};this.createFolder=async({name:e,parentId:t})=>{m(`Creating folder with name: ${e} ${t?`in parent: ${t}`:""}`);try{let s=await this.getDriveClient(),o={name:e,mimeType:"application/vnd.google-apps.folder"};t&&(o.parents=[t]);let a=await s.files.create({requestBody:o,fields:"id, name",supportsAllDrives:!0});return m(`Created folder: ${a.data.name} (${a.data.id})`),{content:[{type:"text",text:JSON.stringify({id:a.data.id,name:a.data.name})}]}}catch(s){let o=s instanceof Error?s.message:String(s);return m(`Error during drive.createFolder: ${o}`),{content:[{type:"text",text:JSON.stringify({error:o})}]}}};this.search=async({query:e,pageSize:t=10,pageToken:s,corpus:o,unreadOnly:a,sharedWithMe:l})=>{let d=await this.getDriveClient(),p=e,u=!1;if(e&&Dp(e)){u=!0,m(`Detected Google Drive URL in query: ${e}`);let f=null,y="unknown";for(let g of Lp){let _=e.match(g.pattern);if(_){f=_[1],y=g.type;break}}if(f){let g=y==="folder";if(y==="unknown")try{(await d.files.get({fileId:f,fields:"mimeType",supportsAllDrives:!0})).data.mimeType==="application/vnd.google-apps.folder"&&(g=!0)}catch{m(`Could not determine type of ID from URL, treating as file: ${f}`)}if(g)p=`'${f}' in parents`,m(`Extracted Folder ID from URL: ${f}, using query: ${p}`);else{m(`Extracted File ID from URL: ${f}, using files.get`);try{let _=await d.files.get({fileId:f,fields:"id, name, modifiedTime, viewedByMeTime, mimeType, parents",supportsAllDrives:!0});return{content:[{type:"text",text:JSON.stringify({files:[_.data],nextPageToken:null})}]}}catch(_){let S=_ instanceof Error?_.message:String(_);return m(`Error during drive.files.get: ${S}`),{content:[{type:"text",text:JSON.stringify({error:S})}]}}}}else return m(`Could not extract file/folder ID from URL: ${e}`),{content:[{type:"text",text:JSON.stringify({error:"Invalid Drive URL. Please provide a valid Google Drive URL or a search query.",details:"Could not extract file or folder ID from the provided URL."})}]}}if(e&&!u){let f="title:",y=e.trim();if(y.startsWith(f)){let g=y.substring(f.length).trim();(g.startsWith("'")&&g.endsWith("'")||g.startsWith('"')&&g.endsWith('"'))&&(g=g.substring(1,g.length-1)),p=`name contains '${On(g)}'`}else new RegExp(`^[a-zA-Z0-9-_]{${kp},}$`).test(y)&&!y.includes(" ")?(p=`'${y}' in parents`,m(`Detected Drive ID: ${y}, listing contents`)):/( and | or | not | contains | in |=)/.test(y)||(p=`fullText contains '${On(y)}'`)}l&&(m("Searching for files shared with the user."),p?p+=" and sharedWithMe":p="sharedWithMe"),m(`Executing Drive search with query: ${p}`),o&&m(`Using corpus: ${o}`),a&&m("Filtering for unread files only.");try{let f=await d.files.list({q:p,pageSize:t,pageToken:s,corpus:o,fields:"nextPageToken, files(id, name, modifiedTime, viewedByMeTime, mimeType, parents)",supportsAllDrives:!0,includeItemsFromAllDrives:!0}),y=f.data.files||[],g=f.data.nextPageToken;return a&&(y=y.filter(_=>!_.viewedByMeTime)),m(`Found ${y.length} files.`),g&&m(`Next page token: ${g}`),{content:[{type:"text",text:JSON.stringify({files:y,nextPageToken:g})}]}}catch(f){let y=f instanceof Error?f.message:String(f);return m(`Error during drive.search: ${y}`),{content:[{type:"text",text:JSON.stringify({error:y})}]}}};this.trashFile=async({fileId:e})=>{m(`Trashing Drive file: ${e}`);try{let t=await this.getDriveClient(),s=ct(e),o=await t.files.update({fileId:s,requestBody:{trashed:!0},fields:"id, name",supportsAllDrives:!0});return m(`Successfully trashed file: ${s}`),{content:[{type:"text",text:JSON.stringify({id:o.data.id,name:o.data.name,trashed:!0})}]}}catch(t){return this.handleError("drive.trashFile",t)}};this.renameFile=async({fileId:e,newName:t})=>{m(`Renaming Drive file: ${e} to "${t}"`);try{let s=await this.getDriveClient(),o=ct(e),a=await s.files.update({fileId:o,requestBody:{name:t},fields:"id, name",supportsAllDrives:!0});return m(`Successfully renamed file: ${o} to "${a.data.name}"`),{content:[{type:"text",text:JSON.stringify({id:a.data.id,name:a.data.name})}]}}catch(s){return this.handleError("drive.renameFile",s)}};this.getComments=async({fileId:e,pageSize:t,pageToken:s})=>{m(`[DriveService] Starting getComments for file: ${e}`);try{let o=await this.getDriveClient(),a=ct(e),l=await o.comments.list({fileId:a,...t!==void 0&&{pageSize:t},...s!==void 0&&{pageToken:s},fields:"nextPageToken, comments(id, content, author(displayName, emailAddress), createdTime, resolved, quotedFileContent(value), replies(id, content, author(displayName, emailAddress), createdTime, action))"}),d=l.data.comments||[];return m(`[DriveService] Found ${d.length} comments for file: ${e}`),{content:[{type:"text",text:JSON.stringify({comments:d,nextPageToken:l.data.nextPageToken??null},null,2)}]}}catch(o){return this.handleError("drive.getComments",o)}};this.moveFile=async({fileId:e,folderId:t,folderName:s})=>{m(`Moving Drive file: ${e} to ${t?`folder ID: ${t}`:`folder name: ${s}`}`);try{let o=await this.getDriveClient(),a=ct(e),l=t;if(!l&&s){let f=await this.findFolder({folderName:s}),y=JSON.parse(f.content[0].text);if(y.error)throw new Error(y.error);let g=y;if(g.length===0)throw new Error(`Folder not found: ${s}`);g.length>1&&m(`Warning: Found multiple folders with name "${s}". Using the first one found.`),l=g[0].id}if(!l)throw new Error("Either folderId or folderName must be provided.");let p=(await o.files.get({fileId:a,fields:"parents",supportsAllDrives:!0})).data.parents?.join(","),u=await o.files.update({fileId:a,addParents:l,removeParents:p,fields:"id, name, parents",supportsAllDrives:!0});return m(`Successfully moved file ${a} to folder ${l}`),{content:[{type:"text",text:JSON.stringify({id:u.data.id,name:u.data.name,parents:u.data.parents})}]}}catch(o){return this.handleError("drive.moveFile",o)}};this.downloadFile=async({fileId:e,localPath:t})=>{m(`Downloading Drive file ${e} to ${t}`);try{let s=await this.getDriveClient(),o=ct(e),a=await s.files.get({fileId:o,fields:"id, name, mimeType",supportsAllDrives:!0}),l=a.data.mimeType||"",d={"application/vnd.google-apps.document":{tool:"docs.getText",idName:"documentId",type:"Google Doc"},"application/vnd.google-apps.spreadsheet":{tool:"sheets.getText",idName:"spreadsheetId",type:"Google Sheet"},"application/vnd.google-apps.presentation":{tool:"slides.getText",idName:"presentationId",type:"Google Slide"}};if(l in d){let g=d[l];return{content:[{type:"text",text:`This is a ${g.type}. Direct download is not supported. Please use the '${g.tool}' tool with ${g.idName}: ${o}`}]}}if(l.includes("vnd.google-apps."))return{content:[{type:"text",text:`This is a Google Workspace file type (${l}). Direct media download is not supported. Please use specific tools (docs.getText, slides.getText, etc.) or export it if supported.`}]};let p=await s.files.get({fileId:o,alt:"media",supportsAllDrives:!0},{responseType:"arraybuffer"}),u=Buffer.from(p.data),f=lt.isAbsolute(t)?t:lt.resolve($n,t);if(!f.startsWith($n+lt.sep)&&f!==$n)throw new Error("localPath must be within the project root.");let y=lt.dirname(f);return await wo.promises.mkdir(y,{recursive:!0}),await wo.promises.writeFile(f,u),{content:[{type:"text",text:`Successfully downloaded file ${a.data.name} to ${f}`}]}}catch(s){let o=s instanceof Error?s.message:String(s);return m(`Error during drive.downloadFile: ${o}`),{content:[{type:"text",text:JSON.stringify({error:o})}]}}}}async getDriveClient(){let e=await this.authManager.getAuthenticatedClient(),t={...W,auth:e};return Op.drive({version:"v3",...t})}handleError(e,t){let s=t instanceof Error?t.message:String(t);return m(`Error during ${e}: ${s}`),{isError:!0,content:[{type:"text",text:JSON.stringify({error:s})}]}}};var _o=["findFolder","createFolder","search","trashFile","renameFile","getComments","moveFile","downloadFile"],Tc=z(Dn,_o,{pagination:{search:"pageSize",getComments:"pageSize"},bounds:ec});import{google as Np}from"googleapis";var Mp=/\/forms\/d\/e\/[\w-]+/,Fp=/\/forms\/d\/([\w-]+)/;function Ln(n){let e=n?.trim()??"";if(!e)throw new Error("formId is required.");if(!e.includes("/"))return e;if(Mp.test(e))throw new Error(`"${e}" is a form's public responder link, which carries a different ID than the API uses. Open the form for editing and pass the ID from https://docs.google.com/forms/d/<formId>/edit instead.`);let t=e.match(Fp);if(t)return t[1];throw new Error(`Could not extract a form ID from "${e}". Pass the ID itself, or the editor URL https://docs.google.com/forms/d/<formId>/edit.`)}function Er(n){return{content:[{type:"text",text:JSON.stringify(n)}]}}var Nn=class{constructor(e){this.authManager=e;this.create=async({title:e,documentTitle:t})=>{if(m(`[FormsService] create title=${e}`),!e?.trim())throw new Error("title is required to create a form.");let o=await(await this.getFormsClient()).forms.create({requestBody:{info:{title:e,...t?{documentTitle:t}:{}}}});return Er({formId:o.data.formId,title:o.data.info?.title,responderUri:o.data.responderUri})};this.get=async({formId:e})=>{let t=Ln(e);m(`[FormsService] get formId=${t}`);let o=await(await this.getFormsClient()).forms.get({formId:t});return Er(o.data)};this.batchUpdate=async({formId:e,requests:t})=>{let s=Ln(e);if(!Array.isArray(t)||t.length===0)throw new Error("batchUpdate needs at least one request in `requests`.");m(`[FormsService] batchUpdate formId=${s}, ${t.length} request(s)`);let a=await(await this.getFormsClient()).forms.batchUpdate({formId:s,requestBody:{requests:t}});return Er(a.data)};this.listResponses=async({formId:e,pageSize:t,pageToken:s,filter:o})=>{let a=Ln(e);m(`[FormsService] listResponses formId=${a}`);let d=await(await this.getFormsClient()).forms.responses.list({formId:a,...t===void 0?{}:{pageSize:t},...s===void 0?{}:{pageToken:s},...o===void 0?{}:{filter:o}});return Er({responses:d.data.responses??[],...d.data.nextPageToken?{nextPageToken:d.data.nextPageToken}:{}})};this.getResponse=async({formId:e,responseId:t})=>{let s=Ln(e);if(!t?.trim())throw new Error("responseId is required.");m(`[FormsService] getResponse formId=${s}, responseId=${t}`);let a=await(await this.getFormsClient()).forms.responses.get({formId:s,responseId:t});return Er(a.data)}}async getFormsClient(){let e=await this.authManager.getAuthenticatedClient();return Np.forms({version:"v1",...W,auth:e})}};var To=["create","get","batchUpdate","listResponses","getResponse"],Rc=z(Nn,To,{pagination:{listResponses:"pageSize"},bounds:oc});import{google as qp}from"googleapis";import*as ut from"node:fs/promises";import*as Ge from"node:path";import{randomUUID as Bp}from"node:crypto";var Zt=class n{static createMimeMessage({to:e,subject:t,body:s,from:o,cc:a,bcc:l,replyTo:d,inReplyTo:p,references:u,isHtml:f=!1}){let y=`=?utf-8?B?${Buffer.from(t).toString("base64")}?=`,g=[];o&&g.push(`From: ${o}`),g.push(`To: ${e}`),a&&g.push(`Cc: ${a}`),l&&g.push(`Bcc: ${l}`),d&&g.push(`Reply-To: ${d}`),p&&g.push(`In-Reply-To: ${n.sanitizeHeaderValue(p)}`),u&&g.push(`References: ${n.sanitizeHeaderValue(u)}`),g.push(`Subject: ${y}`),f?g.push("Content-Type: text/html; charset=utf-8"):g.push("Content-Type: text/plain; charset=utf-8"),g.push(""),g.push(s);let _=g.join(`\r
50
- `);return Buffer.from(_).toString("base64url")}static sanitizeHeaderValue(e){return e.replace(/[\r\n\x00-\x1f\x7f]/g,"")}static sanitizeHeaderFilename(e){return n.sanitizeHeaderValue(e).replace(/\\/g,"\\\\").replace(/"/g,'\\"')}static createMimeMessageWithAttachments({to:e,subject:t,body:s,from:o,cc:a,bcc:l,replyTo:d,inReplyTo:p,references:u,attachments:f,isHtml:y=!1}){let g=`boundary_${Date.now()}_${Bp().replace(/-/g,"")}`,_=`=?utf-8?B?${Buffer.from(t).toString("base64")}?=`,S=[];if(o&&S.push(`From: ${o}`),S.push(`To: ${e}`),a&&S.push(`Cc: ${a}`),l&&S.push(`Bcc: ${l}`),d&&S.push(`Reply-To: ${d}`),S.push(`Subject: ${_}`),S.push("MIME-Version: 1.0"),!f||f.length===0)return this.createMimeMessage({to:e,subject:t,body:s,from:o,cc:a,bcc:l,replyTo:d,inReplyTo:p,references:u,isHtml:y});p&&S.push(`In-Reply-To: ${n.sanitizeHeaderValue(p)}`),u&&S.push(`References: ${n.sanitizeHeaderValue(u)}`),S.push(`Content-Type: multipart/mixed; boundary="${g}"`),S.push(""),S.push(`--${g}`),y?S.push("Content-Type: text/html; charset=utf-8"):S.push("Content-Type: text/plain; charset=utf-8"),S.push(""),S.push(s);for(let R of f){let x=n.sanitizeHeaderValue(R.contentType||"application/octet-stream"),A=n.sanitizeHeaderFilename(R.filename);S.push(`--${g}`),S.push(`Content-Type: ${x}`),S.push("Content-Transfer-Encoding: base64"),S.push(`Content-Disposition: attachment; filename="${A}"`),S.push("");let C=typeof R.content=="string"?R.content:R.content.toString("base64");for(let v=0;v<C.length;v+=76)S.push(C.slice(v,v+76))}S.push(`--${g}--`);let E=S.join(`\r
51
- `);return Buffer.from(E).toString("base64url")}static decodeBase64Url(e){return Buffer.from(e,"base64url").toString("utf-8")}};var Ro="No labels to add or remove were provided. No action taken.";import{ZodError as jp}from"zod";var Wp={".pdf":"application/pdf",".doc":"application/msword",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".xls":"application/vnd.ms-excel",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",".ppt":"application/vnd.ms-powerpoint",".pptx":"application/vnd.openxmlformats-officedocument.presentationml.presentation",".txt":"text/plain",".csv":"text/csv",".html":"text/html",".htm":"text/html",".json":"application/json",".xml":"application/xml",".zip":"application/zip",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".svg":"image/svg+xml",".mp4":"video/mp4",".mp3":"audio/mpeg"},xc=18*1024*1024;function vc(n){if(n>xc)throw new Error(`Total attachment size (${(n/1024/1024).toFixed(2)}MB) exceeds the maximum allowed limit of ${xc/1024/1024}MB.`)}function zp(n){let e=Ge.extname(n).toLowerCase();return Wp[e]??"application/octet-stream"}var Mn=class{constructor(e){this.authManager=e;this.search=async({query:e,maxResults:t=100,pageToken:s,labelIds:o,includeSpamTrash:a=!1})=>{try{m(`Gmail search - query: ${e}, maxResults: ${t}`);let d=await(await this.getGmailClient()).users.messages.list({userId:"me",q:e,maxResults:t,pageToken:s,labelIds:o,includeSpamTrash:a}),p=d.data.messages||[],u=d.data.nextPageToken,f=d.data.resultSizeEstimate;return m(`Found ${p.length} messages, estimated total: ${f}`),{content:[{type:"text",text:JSON.stringify({messages:p.map(y=>({id:y.id,threadId:y.threadId})),nextPageToken:u,resultSizeEstimate:f},null,2)}]}}catch(l){return this.handleError(l,"gmail.search")}};this.get=async({messageId:e,format:t="full"})=>{try{m(`Getting message ${e} with format: ${t}`);let a=(await(await this.getGmailClient()).users.messages.get({userId:"me",id:e,format:t})).data;if(t==="metadata"||t==="full"){let l=a.payload?.headers||[],d=S=>l.find(E=>E.name===S)?.value,p=d("Subject"),u=d("From"),f=d("To"),y=d("Date"),g="",_=[];if(t==="full"&&a.payload){let S=this.extractAttachmentsAndBody(a.payload);g=S.body,_=S.attachments}return{content:[{type:"text",text:JSON.stringify({id:a.id,threadId:a.threadId,labelIds:a.labelIds,snippet:a.snippet,subject:p,from:u,to:f,date:y,body:g||a.snippet,attachments:_},null,2)}]}}return{content:[{type:"text",text:JSON.stringify(a,null,2)}]}}catch(s){return this.handleError(s,"gmail.get")}};this.downloadAttachment=async({messageId:e,attachmentId:t,localPath:s})=>{try{if(m(`Downloading attachment ${t} from message ${e} to ${s}`),!Ge.isAbsolute(s))throw new Error("localPath must be an absolute path.");let l=(await(await this.getGmailClient()).users.messages.attachments.get({userId:"me",messageId:e,id:t})).data.data;if(!l)throw new Error("Attachment data is empty");await ut.mkdir(Ge.dirname(s),{recursive:!0});let d=Buffer.from(l,"base64url");return await ut.writeFile(s,d),m(`Attachment downloaded successfully to ${s}`),{content:[{type:"text",text:JSON.stringify({message:`Attachment downloaded successfully to ${s}`,path:s})}]}}catch(o){return this.handleError(o,"gmail.downloadAttachment")}};this.modify=async({messageId:e,addLabelIds:t=[],removeLabelIds:s=[]})=>{try{m(`Modifying message ${e} with addLabelIds: ${t}, removeLabelIds: ${s}`);let l=(await(await this.getGmailClient()).users.messages.modify({userId:"me",id:e,requestBody:{addLabelIds:t,removeLabelIds:s}})).data;return{content:[{type:"text",text:JSON.stringify(l,null,2)}]}}catch(o){return this.handleError(o,"gmail.modify")}};this.batchModify=async({messageIds:e,addLabelIds:t=[],removeLabelIds:s=[]})=>{try{if(t.length===0&&s.length===0)return{content:[{type:"text",text:JSON.stringify({status:"noop",message:Ro})}]};if(e.length>1e3)throw new Error(`Too many message IDs. Maximum is ${1e3}, got ${e.length}.`);return m(`Batch modifying ${e.length} messages with addLabelIds: ${t}, removeLabelIds: ${s}`),await(await this.getGmailClient()).users.messages.batchModify({userId:"me",requestBody:{ids:e,addLabelIds:t,removeLabelIds:s}}),{content:[{type:"text",text:JSON.stringify({modifiedCount:e.length,addLabelIds:t,removeLabelIds:s,status:"success"},null,2)}]}}catch(o){return this.handleError(o,"gmail.batchModify")}};this.modifyThread=async({threadId:e,addLabelIds:t=[],removeLabelIds:s=[]})=>{try{if(t.length===0&&s.length===0)return{content:[{type:"text",text:JSON.stringify({status:"noop",message:Ro})}]};m(`Modifying thread ${e} with addLabelIds: ${t}, removeLabelIds: ${s}`);let l=(await(await this.getGmailClient()).users.threads.modify({userId:"me",id:e,requestBody:{addLabelIds:t,removeLabelIds:s}})).data;return{content:[{type:"text",text:JSON.stringify(l,null,2)}]}}catch(o){return this.handleError(o,"gmail.modifyThread")}};this.send=async({to:e,subject:t,body:s,cc:o,bcc:a,replyTo:l,isHtml:d=!1})=>{try{let p=this.validateEmailAddresses({to:e,cc:o,bcc:a,replyTo:l});if(p)return p;m(`Sending email to: ${e}, subject: ${t}`);let u=Zt.createMimeMessage({to:Array.isArray(e)?e.join(", "):e,subject:t,body:s,cc:o?Array.isArray(o)?o.join(", "):o:void 0,bcc:a?Array.isArray(a)?a.join(", "):a:void 0,replyTo:l,isHtml:d}),y=await(await this.getGmailClient()).users.messages.send({userId:"me",requestBody:{raw:u}});return m(`Email sent successfully: ${y.data.id}`),{content:[{type:"text",text:JSON.stringify({id:y.data.id,threadId:y.data.threadId,labelIds:y.data.labelIds,status:"sent"},null,2)}]}}catch(p){return this.handleError(p,"gmail.send")}};this.createDraft=async({to:e,subject:t,body:s,cc:o,bcc:a,replyTo:l,isHtml:d=!1,threadId:p,attachments:u})=>{try{let f=this.validateEmailAddresses({to:e,cc:o,bcc:a,replyTo:l});if(f)return f;m(`Creating draft - to: ${e}, subject: ${t}`);let y=await this.getGmailClient(),g,_;if(p)try{let x=(await y.users.threads.get({userId:"me",id:p,format:"metadata",metadataHeaders:["Message-ID","References"]})).data.messages||[];if(x.length>0){let C=x[x.length-1].payload?.headers||[],v=C.find($=>$.name?.toLowerCase()==="message-id"),k=C.find($=>$.name?.toLowerCase()==="references");if(v?.value){g=v.value;let $=k?.value||"";_=$?`${$} ${v.value}`:v.value}}}catch(R){m(`Warning: Could not fetch thread ${p} for reply headers: ${R}`)}let S;if(u&&u.length>0){let x=(await Promise.all(u.map(async C=>{if(!Ge.isAbsolute(C.filePath))throw new Error(`Attachment filePath must be an absolute path: ${C.filePath}`);let v;try{v=await ut.stat(C.filePath)}catch(k){throw new Error(`Could not access attachment file ${C.filePath}: ${k instanceof Error?k.message:String(k)}`)}if(!v.isFile())throw new Error(`Attachment path is not a file: ${C.filePath}`);return v.size}))).reduce((C,v)=>C+v,0);vc(x);let A=await Promise.all(u.map(async C=>{let v;try{v=await ut.readFile(C.filePath)}catch(k){throw new Error(`Could not read attachment file ${C.filePath}: ${k instanceof Error?k.message:String(k)}`)}return{filename:C.filename||Ge.basename(C.filePath),content:v,contentType:C.mimeType||zp(C.filePath)}}));vc(A.reduce((C,v)=>C+v.content.length,0)),S=Zt.createMimeMessageWithAttachments({to:Array.isArray(e)?e.join(", "):e,subject:t,body:s,cc:o?Array.isArray(o)?o.join(", "):o:void 0,bcc:a?Array.isArray(a)?a.join(", "):a:void 0,replyTo:l,inReplyTo:g,references:_,isHtml:d,attachments:A})}else S=Zt.createMimeMessage({to:Array.isArray(e)?e.join(", "):e,subject:t,body:s,cc:o?Array.isArray(o)?o.join(", "):o:void 0,bcc:a?Array.isArray(a)?a.join(", "):a:void 0,replyTo:l,isHtml:d,inReplyTo:g,references:_});let E=await y.users.drafts.create({userId:"me",requestBody:{message:{raw:S,...p&&{threadId:p}}}});return m(`Draft created successfully: ${E.data.id}`),{content:[{type:"text",text:JSON.stringify({id:E.data.id,message:{id:E.data.message?.id,threadId:E.data.message?.threadId,labelIds:E.data.message?.labelIds},status:"draft_created"},null,2)}]}}catch(f){return this.handleError(f,"gmail.createDraft")}};this.sendDraft=async({draftId:e})=>{try{m(`Sending draft: ${e}`);let s=await(await this.getGmailClient()).users.drafts.send({userId:"me",requestBody:{id:e}});return m(`Draft sent successfully: ${s.data.id}`),{content:[{type:"text",text:JSON.stringify({id:s.data.id,threadId:s.data.threadId,labelIds:s.data.labelIds,status:"sent"},null,2)}]}}catch(t){return this.handleError(t,"gmail.sendDraft")}};this.listLabels=async()=>{try{m("Listing Gmail labels");let s=(await(await this.getGmailClient()).users.labels.list({userId:"me"})).data.labels||[];return m(`Found ${s.length} labels`),{content:[{type:"text",text:JSON.stringify({labels:s.map(o=>({id:o.id,name:o.name,type:o.type,messageListVisibility:o.messageListVisibility,labelListVisibility:o.labelListVisibility}))},null,2)}]}}catch(e){return this.handleError(e,"gmail.listLabels")}};this.createLabel=async({name:e,labelListVisibility:t="labelShow",messageListVisibility:s="show"})=>{try{m(`Creating Gmail label: ${e}`);let l=(await(await this.getGmailClient()).users.labels.create({userId:"me",requestBody:{name:e,labelListVisibility:t,messageListVisibility:s}})).data;return m(`Created label: ${l.name} with id: ${l.id}`),{content:[{type:"text",text:JSON.stringify({id:l.id,name:l.name,type:l.type,messageListVisibility:l.messageListVisibility,labelListVisibility:l.labelListVisibility,status:"created"},null,2)}]}}catch(o){return this.handleError(o,"gmail.createLabel")}}}async getGmailClient(){let e=await this.authManager.getAuthenticatedClient(),t={...W,auth:e};return qp.gmail({version:"v1",...t})}handleError(e,t){let s=e instanceof Error?e.message:String(e);return m(`Error during ${t}: ${s}`),{content:[{type:"text",text:JSON.stringify({error:s})}]}}validateEmailAddresses({to:e,cc:t,bcc:s,replyTo:o}){try{return at.parse(e),t&&at.parse(t),s&&at.parse(s),o&&at.parse(o),null}catch(a){if(!(a instanceof jp))throw a;return m(`Rejected invalid email address input: ${a.message}`),{content:[{type:"text",text:JSON.stringify({error:"Invalid email address format",details:a.message})}]}}}extractAttachmentsAndBody(e,t={body:"",attachments:[]}){if(!e)return t;if(e.body?.data&&(!e.filename||!e.body.attachmentId)&&e.mimeType?.startsWith("text/")&&(!t.body||e.mimeType==="text/plain")&&(t.body=Buffer.from(e.body.data,"base64").toString("utf-8")),e.filename&&e.body?.attachmentId&&t.attachments.push({filename:e.filename,mimeType:e.mimeType,attachmentId:e.body.attachmentId,size:e.body.size}),e.parts)for(let s of e.parts)this.extractAttachmentsAndBody(s,t);return t}};var Fn=["search","get","downloadAttachment","modify","batchModify","modifyThread","send","createDraft","sendDraft","listLabels","createLabel"],Cc=z(Mn,Fn,{pagination:{search:"maxResults"},bounds:Ka});import{google as Hp}from"googleapis";var Bn=class{constructor(e){this.authManager=e;this.getUserProfile=async({userId:e,email:t,name:s})=>{m(`[PeopleService] Starting getUserProfile with: userId=${e}, email=${t}, name=${s}`);try{if(!e&&!t&&!s)throw new Error("Either userId, email, or name must be provided.");let o=await this.getPeopleClient();if(e){let a=e.startsWith("people/")?e:`people/${e}`,l=await o.people.get({resourceName:a,personFields:"names,emailAddresses"});return m(`[PeopleService] Finished getUserProfile for user: ${e}`),{content:[{type:"text",text:JSON.stringify({results:[{person:l.data}]})}]}}else if(t||s){let a=t||s,l=await o.people.searchDirectoryPeople({query:a,readMask:"names,emailAddresses",sources:["DIRECTORY_SOURCE_TYPE_DOMAIN_CONTACT","DIRECTORY_SOURCE_TYPE_DOMAIN_PROFILE"]});return m(`[PeopleService] Finished getUserProfile search for: ${a}`),{content:[{type:"text",text:JSON.stringify(l.data)}]}}else throw new Error("Either userId, email, or name must be provided.")}catch(o){let a=o instanceof Error?o.message:String(o);return m(`[PeopleService] Error during people.getUserProfile: ${a}`),{content:[{type:"text",text:JSON.stringify({error:a})}]}}};this.getMe=async()=>{m("[PeopleService] Starting getMe");try{let t=await(await this.getPeopleClient()).people.get({resourceName:"people/me",personFields:"names,emailAddresses"});return m("[PeopleService] Finished getMe"),{content:[{type:"text",text:JSON.stringify(t.data)}]}}catch(e){let t=e instanceof Error?e.message:String(e);return m(`[PeopleService] Error during people.getMe: ${t}`),{content:[{type:"text",text:JSON.stringify({error:t})}]}}};this.getUserRelations=async({userId:e,relationType:t})=>{let s=e?e.startsWith("people/")?e:`people/${e}`:"people/me";m(`[PeopleService] Starting getUserRelations for ${s} with relationType=${t}`);try{let a=await(await this.getPeopleClient()).people.get({resourceName:s,personFields:"relations"});m("[PeopleService] Finished getUserRelations API call");let l=a.data?.relations||[],d=t?l.filter(u=>u.type?.toLowerCase()===t.toLowerCase()):l;t?m(`[PeopleService] Filtered to ${d.length} relations of type: ${t}`):m(`[PeopleService] Returning all ${d.length} relations`);let p={resourceName:s,...t&&{relationType:t},relations:d};return{content:[{type:"text",text:JSON.stringify(p)}]}}catch(o){let a=o instanceof Error?o.message:String(o);return m(`[PeopleService] Error during people.getUserRelations: ${a}`),{content:[{type:"text",text:JSON.stringify({error:a})}]}}}}async getPeopleClient(){let e=await this.authManager.getAuthenticatedClient(),t={...W,auth:e};return Hp.people({version:"v1",...t})}};var Un=["getUserProfile","getMe","getUserRelations"],Ac=z(Bn,Un,{bounds:sc});import{google as Gp}from"googleapis";var qn=class n{constructor(e){this.authManager=e;this.getText=async({spreadsheetId:e,format:t="text",max_chars:s,full:o})=>{m(`[SheetsService] Starting getText for spreadsheet: ${e} with format: ${t}`);try{let a=F(e)||e,l=ho(s,o),d=await this.getSheetsClient(),p=await d.spreadsheets.get({spreadsheetId:a,includeGridData:!1}),u="",f={};p.data.properties?.title&&t!=="json"&&(u+=`Spreadsheet Title: ${p.data.properties.title}
49
+ `:"";return g.documentTab?.body?.content?.forEach(S=>{_+=this._readStructuralElement(S)}),{content:[{type:"text",text:ys(_,a).text}]}}let y=f.map((g,_)=>{let S="";g.documentTab?.body?.content?.forEach(R=>{S+=this._readStructuralElement(R)});let E=ys(S,a);return{tabId:g.tabProperties?.tabId,title:g.tabProperties?.title,content:E.text,truncated:E.truncated,totalCharacters:E.totalCharacters,index:_}});return{content:[{type:"text",text:JSON.stringify({title:u,tabs:y},null,2)}]}}catch(a){let l=a instanceof Error?a.message:String(a);return m(`[DocsService] Error during docs.getText: ${l}`),{content:[{type:"text",text:JSON.stringify({error:l})}]}}};this.replaceText=async({documentId:e,findText:t,replaceText:o,tabId:s})=>{m(`[DocsService] Starting replaceText for document: ${e}, tabId: ${s}`);try{if(!t)throw new Error("findText must not be empty.");let a=F(e)||e,l=await this.getDocsClient(),d=await l.documents.get({documentId:a,fields:gs,includeTabsContent:!0}),p=this._flattenTabs(d.data.tabs||[]),u=[];if(s){let f=p.find(_=>_.tabProperties?.tabId===s);if(!f)throw new Error(`Tab with ID ${s} not found.`);let y=f.documentTab?.body?.content,g=this._generateReplacementRequests(y,s,t,o);for(let _ of g)u.push(_)}else for(let f of p){let y=f.tabProperties?.tabId,g=f.documentTab?.body?.content,_=this._generateReplacementRequests(g,y,t,o);for(let S of _)u.push(S)}return u.length>0&&await l.documents.batchUpdate({documentId:a,requestBody:{requests:u}}),m(`[DocsService] Finished replaceText for document: ${a}`),{content:[{type:"text",text:`Successfully replaced text in document ${a}`}]}}catch(a){let l=a instanceof Error?a.message:String(a);return m(`[DocsService] Error during docs.replaceText: ${l}`),{content:[{type:"text",text:JSON.stringify({error:l})}]}}}}_flattenTabs(e){return e.flatMap(t=>{let o=t.childTabs?this._flattenTabs(t.childTabs):[];return[t,...o]})}async getDocsClient(){let e=await this.authManager.getAuthenticatedClient(),t={...W,auth:e};return vp.docs({version:"v1",...t})}_extractSuggestions(e){let t=[];if(!e?.content)return t;let o=s=>{s?.forEach(a=>{if(a.paragraph){if(a.paragraph.suggestedParagraphStyleChanges)for(let[l,d]of Object.entries(a.paragraph.suggestedParagraphStyleChanges))t.push({type:"paragraphStyleChange",text:this._getParagraphText(a.paragraph),suggestionIds:[l],namedStyleType:d?.paragraphStyle?.namedStyleType??void 0,startIndex:a.startIndex??void 0,endIndex:a.endIndex??void 0});a.paragraph.elements?.forEach(l=>{if(l.textRun){let d={text:l.textRun.content||"",startIndex:l.startIndex??void 0,endIndex:l.endIndex??void 0};l.textRun.suggestedInsertionIds&&t.push({...d,type:"insertion",suggestionIds:l.textRun.suggestedInsertionIds}),l.textRun.suggestedDeletionIds&&t.push({...d,type:"deletion",suggestionIds:l.textRun.suggestedDeletionIds}),l.textRun.suggestedTextStyleChanges&&t.push({...d,type:"styleChange",suggestionIds:Object.keys(l.textRun.suggestedTextStyleChanges),textStyle:l.textRun.textStyle})}})}else a.table&&a.table.tableRows?.forEach(l=>{l.tableCells?.forEach(d=>{o(d.content)})})})};return o(e.content),t}_getParagraphText(e){return e?.elements?e.elements.map(t=>t.textRun?.content||"").join(""):""}static{this.HEADING_STYLES={heading1:"HEADING_1",heading2:"HEADING_2",heading3:"HEADING_3",heading4:"HEADING_4",heading5:"HEADING_5",heading6:"HEADING_6",normaltext:"NORMAL_TEXT"}}static{this.TEXT_STYLES={bold:{bold:!0},italic:{italic:!0},underline:{underline:!0},strikethrough:{strikethrough:!0}}}_readStructuralElement(e){let t="";return e.paragraph?e.paragraph.elements?.forEach(o=>{o.textRun&&o.textRun.content?t+=o.textRun.content:o.person?.personProperties?t+=this._renderPersonChip(o.person.personProperties):o.richLink?.richLinkProperties?t+=this._renderRichLinkChip(o.richLink.richLinkProperties):o.dateElement?.dateElementProperties&&(t+=this._renderDateChip(o.dateElement.dateElementProperties))}):e.table&&e.table.tableRows?.forEach(o=>{o.tableCells?.forEach(s=>{s.content?.forEach(a=>{t+=this._readStructuralElement(a)})})}),t}_renderPersonChip(e){let{name:t,email:o}=e;return o?`[${t||o}](mailto:${o})`:t||""}_renderRichLinkChip(e){let{title:t,uri:o}=e;return o?`[${t||o}](${o})`:t||""}_renderDateChip(e){let{displayText:t,timestamp:o}=e;return t||o||""}_generateReplacementRequests(e,t,o,s){let a=[],l=this._getFullDocumentText(e),d=[],p=0;for(;(p=l.indexOf(o,p))!==-1;)d.push(p+1),p+=o.length;let u=s.length-o.length,f=0;for(let y=0;y<d.length;y++){let _=d[y]+f;a.push({deleteContentRange:{range:{tabId:t,startIndex:_,endIndex:_+o.length}}}),a.push({insertText:{location:{tabId:t,index:_},text:s}}),f+=u}return a}_getFullDocumentText(e){let t="";return e&&e.forEach(o=>{t+=this._readStructuralElement(o)}),t}};var Ss=["getText","create","writeText","getSuggestions","replaceText","formatText"],_c=z(In,Ss,{bounds:Xa});import{google as kp}from"googleapis";function On(r){return r.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}import*as ws from"node:fs";import*as lt from"node:path";import kn from"node:path";import Pp from"node:fs";import{fileURLToPath as Ip}from"node:url";function Op(){let r=kn.dirname(Ip(import.meta.url));for(;r!==kn.dirname(r);){if(Pp.existsSync(kn.join(r,"package.json")))return r;r=kn.dirname(r)}return process.cwd()}var $n=Op();var $p=25,Dp=new Set(["drive.google.com","docs.google.com"]);function Lp(r){try{return Dp.has(new URL(r).hostname)}catch{return!1}}var Np=[{pattern:/\/folders\/([a-zA-Z0-9-_]+)/,type:"folder"},{pattern:/\/file\/d\/([a-zA-Z0-9-_]+)/,type:"file"},{pattern:/\/document\/d\/([a-zA-Z0-9-_]+)/,type:"file"},{pattern:/\/spreadsheets\/d\/([a-zA-Z0-9-_]+)/,type:"file"},{pattern:/\/presentation\/d\/([a-zA-Z0-9-_]+)/,type:"file"},{pattern:/\/forms\/d\/([a-zA-Z0-9-_]+)/,type:"file"},{pattern:/[?&]id=([a-zA-Z0-9-_]+)/,type:"unknown"}],Dn=class{constructor(e){this.authManager=e;this.findFolder=async({folderName:e})=>{m(`Searching for folder with name: ${e}`);try{let t=await this.getDriveClient(),o=`mimeType='application/vnd.google-apps.folder' and name = '${On(e)}'`;m(`Executing Drive API query: ${o}`);let a=(await t.files.list({q:o,fields:"files(id, name)",spaces:"drive",supportsAllDrives:!0,includeItemsFromAllDrives:!0})).data.files||[];return m(`Found ${a.length} folders.`),m(`API Response: ${JSON.stringify(a,null,2)}`),{content:[{type:"text",text:JSON.stringify(a)}]}}catch(t){return this.handleError("drive.findFolder",t)}};this.createFolder=async({name:e,parentId:t})=>{m(`Creating folder with name: ${e} ${t?`in parent: ${t}`:""}`);try{let o=await this.getDriveClient(),s={name:e,mimeType:"application/vnd.google-apps.folder"};t&&(s.parents=[t]);let a=await o.files.create({requestBody:s,fields:"id, name",supportsAllDrives:!0});return m(`Created folder: ${a.data.name} (${a.data.id})`),{content:[{type:"text",text:JSON.stringify({id:a.data.id,name:a.data.name})}]}}catch(o){let s=o instanceof Error?o.message:String(o);return m(`Error during drive.createFolder: ${s}`),{content:[{type:"text",text:JSON.stringify({error:s})}]}}};this.search=async({query:e,pageSize:t=10,pageToken:o,corpus:s,unreadOnly:a,sharedWithMe:l})=>{let d=await this.getDriveClient(),p=e,u=!1;if(e&&Lp(e)){u=!0,m(`Detected Google Drive URL in query: ${e}`);let f=null,y="unknown";for(let g of Np){let _=e.match(g.pattern);if(_){f=_[1],y=g.type;break}}if(f){let g=y==="folder";if(y==="unknown")try{(await d.files.get({fileId:f,fields:"mimeType",supportsAllDrives:!0})).data.mimeType==="application/vnd.google-apps.folder"&&(g=!0)}catch{m(`Could not determine type of ID from URL, treating as file: ${f}`)}if(g)p=`'${f}' in parents`,m(`Extracted Folder ID from URL: ${f}, using query: ${p}`);else{m(`Extracted File ID from URL: ${f}, using files.get`);try{let _=await d.files.get({fileId:f,fields:"id, name, modifiedTime, viewedByMeTime, mimeType, parents",supportsAllDrives:!0});return{content:[{type:"text",text:JSON.stringify({files:[_.data],nextPageToken:null})}]}}catch(_){let S=_ instanceof Error?_.message:String(_);return m(`Error during drive.files.get: ${S}`),{content:[{type:"text",text:JSON.stringify({error:S})}]}}}}else return m(`Could not extract file/folder ID from URL: ${e}`),{content:[{type:"text",text:JSON.stringify({error:"Invalid Drive URL. Please provide a valid Google Drive URL or a search query.",details:"Could not extract file or folder ID from the provided URL."})}]}}if(e&&!u){let f="title:",y=e.trim();if(y.startsWith(f)){let g=y.substring(f.length).trim();(g.startsWith("'")&&g.endsWith("'")||g.startsWith('"')&&g.endsWith('"'))&&(g=g.substring(1,g.length-1)),p=`name contains '${On(g)}'`}else new RegExp(`^[a-zA-Z0-9-_]{${$p},}$`).test(y)&&!y.includes(" ")?(p=`'${y}' in parents`,m(`Detected Drive ID: ${y}, listing contents`)):/( and | or | not | contains | in |=)/.test(y)||(p=`fullText contains '${On(y)}'`)}l&&(m("Searching for files shared with the user."),p?p+=" and sharedWithMe":p="sharedWithMe"),m(`Executing Drive search with query: ${p}`),s&&m(`Using corpus: ${s}`),a&&m("Filtering for unread files only.");try{let f=await d.files.list({q:p,pageSize:t,pageToken:o,corpus:s,fields:"nextPageToken, files(id, name, modifiedTime, viewedByMeTime, mimeType, parents)",supportsAllDrives:!0,includeItemsFromAllDrives:!0}),y=f.data.files||[],g=f.data.nextPageToken;return a&&(y=y.filter(_=>!_.viewedByMeTime)),m(`Found ${y.length} files.`),g&&m(`Next page token: ${g}`),{content:[{type:"text",text:JSON.stringify({files:y,nextPageToken:g})}]}}catch(f){let y=f instanceof Error?f.message:String(f);return m(`Error during drive.search: ${y}`),{content:[{type:"text",text:JSON.stringify({error:y})}]}}};this.trashFile=async({fileId:e})=>{m(`Trashing Drive file: ${e}`);try{let t=await this.getDriveClient(),o=ct(e),s=await t.files.update({fileId:o,requestBody:{trashed:!0},fields:"id, name",supportsAllDrives:!0});return m(`Successfully trashed file: ${o}`),{content:[{type:"text",text:JSON.stringify({id:s.data.id,name:s.data.name,trashed:!0})}]}}catch(t){return this.handleError("drive.trashFile",t)}};this.renameFile=async({fileId:e,newName:t})=>{m(`Renaming Drive file: ${e} to "${t}"`);try{let o=await this.getDriveClient(),s=ct(e),a=await o.files.update({fileId:s,requestBody:{name:t},fields:"id, name",supportsAllDrives:!0});return m(`Successfully renamed file: ${s} to "${a.data.name}"`),{content:[{type:"text",text:JSON.stringify({id:a.data.id,name:a.data.name})}]}}catch(o){return this.handleError("drive.renameFile",o)}};this.getComments=async({fileId:e,pageSize:t,pageToken:o})=>{m(`[DriveService] Starting getComments for file: ${e}`);try{let s=await this.getDriveClient(),a=ct(e),l=await s.comments.list({fileId:a,...t!==void 0&&{pageSize:t},...o!==void 0&&{pageToken:o},fields:"nextPageToken, comments(id, content, author(displayName, emailAddress), createdTime, resolved, quotedFileContent(value), replies(id, content, author(displayName, emailAddress), createdTime, action))"}),d=l.data.comments||[];return m(`[DriveService] Found ${d.length} comments for file: ${e}`),{content:[{type:"text",text:JSON.stringify({comments:d,nextPageToken:l.data.nextPageToken??null},null,2)}]}}catch(s){return this.handleError("drive.getComments",s)}};this.moveFile=async({fileId:e,folderId:t,folderName:o})=>{m(`Moving Drive file: ${e} to ${t?`folder ID: ${t}`:`folder name: ${o}`}`);try{let s=await this.getDriveClient(),a=ct(e),l=t;if(!l&&o){let f=await this.findFolder({folderName:o}),y=JSON.parse(f.content[0].text);if(y.error)throw new Error(y.error);let g=y;if(g.length===0)throw new Error(`Folder not found: ${o}`);g.length>1&&m(`Warning: Found multiple folders with name "${o}". Using the first one found.`),l=g[0].id}if(!l)throw new Error("Either folderId or folderName must be provided.");let p=(await s.files.get({fileId:a,fields:"parents",supportsAllDrives:!0})).data.parents?.join(","),u=await s.files.update({fileId:a,addParents:l,removeParents:p,fields:"id, name, parents",supportsAllDrives:!0});return m(`Successfully moved file ${a} to folder ${l}`),{content:[{type:"text",text:JSON.stringify({id:u.data.id,name:u.data.name,parents:u.data.parents})}]}}catch(s){return this.handleError("drive.moveFile",s)}};this.downloadFile=async({fileId:e,localPath:t})=>{m(`Downloading Drive file ${e} to ${t}`);try{let o=await this.getDriveClient(),s=ct(e),a=await o.files.get({fileId:s,fields:"id, name, mimeType",supportsAllDrives:!0}),l=a.data.mimeType||"",d={"application/vnd.google-apps.document":{tool:"docs.getText",idName:"documentId",type:"Google Doc"},"application/vnd.google-apps.spreadsheet":{tool:"sheets.getText",idName:"spreadsheetId",type:"Google Sheet"},"application/vnd.google-apps.presentation":{tool:"slides.getText",idName:"presentationId",type:"Google Slide"}};if(l in d){let g=d[l];return{content:[{type:"text",text:`This is a ${g.type}. Direct download is not supported. Please use the '${g.tool}' tool with ${g.idName}: ${s}`}]}}if(l.includes("vnd.google-apps."))return{content:[{type:"text",text:`This is a Google Workspace file type (${l}). Direct media download is not supported. Please use specific tools (docs.getText, slides.getText, etc.) or export it if supported.`}]};let p=await o.files.get({fileId:s,alt:"media",supportsAllDrives:!0},{responseType:"arraybuffer"}),u=Buffer.from(p.data),f=lt.isAbsolute(t)?t:lt.resolve($n,t);if(!f.startsWith($n+lt.sep)&&f!==$n)throw new Error("localPath must be within the project root.");let y=lt.dirname(f);return await ws.promises.mkdir(y,{recursive:!0}),await ws.promises.writeFile(f,u),{content:[{type:"text",text:`Successfully downloaded file ${a.data.name} to ${f}`}]}}catch(o){let s=o instanceof Error?o.message:String(o);return m(`Error during drive.downloadFile: ${s}`),{content:[{type:"text",text:JSON.stringify({error:s})}]}}}}async getDriveClient(){let e=await this.authManager.getAuthenticatedClient(),t={...W,auth:e};return kp.drive({version:"v3",...t})}handleError(e,t){let o=t instanceof Error?t.message:String(t);return m(`Error during ${e}: ${o}`),{isError:!0,content:[{type:"text",text:JSON.stringify({error:o})}]}}};var _s=["findFolder","createFolder","search","trashFile","renameFile","getComments","moveFile","downloadFile"],Tc=z(Dn,_s,{pagination:{search:"pageSize",getComments:"pageSize"},bounds:ec});import{google as Mp}from"googleapis";var Fp=/\/forms\/d\/e\/[\w-]+/,Bp=/\/forms\/d\/([\w-]+)/;function Ln(r){let e=r?.trim()??"";if(!e)throw new Error("formId is required.");if(!e.includes("/"))return e;if(Fp.test(e))throw new Error(`"${e}" is a form's public responder link, which carries a different ID than the API uses. Open the form for editing and pass the ID from https://docs.google.com/forms/d/<formId>/edit instead.`);let t=e.match(Bp);if(t)return t[1];throw new Error(`Could not extract a form ID from "${e}". Pass the ID itself, or the editor URL https://docs.google.com/forms/d/<formId>/edit.`)}function Er(r){return{content:[{type:"text",text:JSON.stringify(r)}]}}var Nn=class{constructor(e){this.authManager=e;this.create=async({title:e,documentTitle:t})=>{if(m(`[FormsService] create title=${e}`),!e?.trim())throw new Error("title is required to create a form.");let s=await(await this.getFormsClient()).forms.create({requestBody:{info:{title:e,...t?{documentTitle:t}:{}}}});return Er({formId:s.data.formId,title:s.data.info?.title,responderUri:s.data.responderUri})};this.get=async({formId:e})=>{let t=Ln(e);m(`[FormsService] get formId=${t}`);let s=await(await this.getFormsClient()).forms.get({formId:t});return Er(s.data)};this.batchUpdate=async({formId:e,requests:t})=>{let o=Ln(e);if(!Array.isArray(t)||t.length===0)throw new Error("batchUpdate needs at least one request in `requests`.");m(`[FormsService] batchUpdate formId=${o}, ${t.length} request(s)`);let a=await(await this.getFormsClient()).forms.batchUpdate({formId:o,requestBody:{requests:t}});return Er(a.data)};this.listResponses=async({formId:e,pageSize:t,pageToken:o,filter:s})=>{let a=Ln(e);m(`[FormsService] listResponses formId=${a}`);let d=await(await this.getFormsClient()).forms.responses.list({formId:a,...t===void 0?{}:{pageSize:t},...o===void 0?{}:{pageToken:o},...s===void 0?{}:{filter:s}});return Er({responses:d.data.responses??[],...d.data.nextPageToken?{nextPageToken:d.data.nextPageToken}:{}})};this.getResponse=async({formId:e,responseId:t})=>{let o=Ln(e);if(!t?.trim())throw new Error("responseId is required.");m(`[FormsService] getResponse formId=${o}, responseId=${t}`);let a=await(await this.getFormsClient()).forms.responses.get({formId:o,responseId:t});return Er(a.data)}}async getFormsClient(){let e=await this.authManager.getAuthenticatedClient();return Mp.forms({version:"v1",...W,auth:e})}};var Ts=["create","get","batchUpdate","listResponses","getResponse"],Rc=z(Nn,Ts,{pagination:{listResponses:"pageSize"},bounds:sc});import{google as jp}from"googleapis";import*as ut from"node:fs/promises";import*as Ge from"node:path";import{randomUUID as Up}from"node:crypto";var Zt=class r{static createMimeMessage({to:e,subject:t,body:o,from:s,cc:a,bcc:l,replyTo:d,inReplyTo:p,references:u,isHtml:f=!1}){let y=`=?utf-8?B?${Buffer.from(t).toString("base64")}?=`,g=[];s&&g.push(`From: ${s}`),g.push(`To: ${e}`),a&&g.push(`Cc: ${a}`),l&&g.push(`Bcc: ${l}`),d&&g.push(`Reply-To: ${d}`),p&&g.push(`In-Reply-To: ${r.sanitizeHeaderValue(p)}`),u&&g.push(`References: ${r.sanitizeHeaderValue(u)}`),g.push(`Subject: ${y}`),f?g.push("Content-Type: text/html; charset=utf-8"):g.push("Content-Type: text/plain; charset=utf-8"),g.push(""),g.push(o);let _=g.join(`\r
50
+ `);return Buffer.from(_).toString("base64url")}static sanitizeHeaderValue(e){return e.replace(/[\r\n\x00-\x1f\x7f]/g,"")}static sanitizeHeaderFilename(e){return r.sanitizeHeaderValue(e).replace(/\\/g,"\\\\").replace(/"/g,'\\"')}static createMimeMessageWithAttachments({to:e,subject:t,body:o,from:s,cc:a,bcc:l,replyTo:d,inReplyTo:p,references:u,attachments:f,isHtml:y=!1}){let g=`boundary_${Date.now()}_${Up().replace(/-/g,"")}`,_=`=?utf-8?B?${Buffer.from(t).toString("base64")}?=`,S=[];if(s&&S.push(`From: ${s}`),S.push(`To: ${e}`),a&&S.push(`Cc: ${a}`),l&&S.push(`Bcc: ${l}`),d&&S.push(`Reply-To: ${d}`),S.push(`Subject: ${_}`),S.push("MIME-Version: 1.0"),!f||f.length===0)return this.createMimeMessage({to:e,subject:t,body:o,from:s,cc:a,bcc:l,replyTo:d,inReplyTo:p,references:u,isHtml:y});p&&S.push(`In-Reply-To: ${r.sanitizeHeaderValue(p)}`),u&&S.push(`References: ${r.sanitizeHeaderValue(u)}`),S.push(`Content-Type: multipart/mixed; boundary="${g}"`),S.push(""),S.push(`--${g}`),y?S.push("Content-Type: text/html; charset=utf-8"):S.push("Content-Type: text/plain; charset=utf-8"),S.push(""),S.push(o);for(let R of f){let x=r.sanitizeHeaderValue(R.contentType||"application/octet-stream"),A=r.sanitizeHeaderFilename(R.filename);S.push(`--${g}`),S.push(`Content-Type: ${x}`),S.push("Content-Transfer-Encoding: base64"),S.push(`Content-Disposition: attachment; filename="${A}"`),S.push("");let C=typeof R.content=="string"?R.content:R.content.toString("base64");for(let v=0;v<C.length;v+=76)S.push(C.slice(v,v+76))}S.push(`--${g}--`);let E=S.join(`\r
51
+ `);return Buffer.from(E).toString("base64url")}static decodeBase64Url(e){return Buffer.from(e,"base64url").toString("utf-8")}};var Rs="No labels to add or remove were provided. No action taken.";import{ZodError as Wp}from"zod";var zp={".pdf":"application/pdf",".doc":"application/msword",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".xls":"application/vnd.ms-excel",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",".ppt":"application/vnd.ms-powerpoint",".pptx":"application/vnd.openxmlformats-officedocument.presentationml.presentation",".txt":"text/plain",".csv":"text/csv",".html":"text/html",".htm":"text/html",".json":"application/json",".xml":"application/xml",".zip":"application/zip",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".svg":"image/svg+xml",".mp4":"video/mp4",".mp3":"audio/mpeg"},xc=18*1024*1024;function vc(r){if(r>xc)throw new Error(`Total attachment size (${(r/1024/1024).toFixed(2)}MB) exceeds the maximum allowed limit of ${xc/1024/1024}MB.`)}function Hp(r){let e=Ge.extname(r).toLowerCase();return zp[e]??"application/octet-stream"}var Mn=class{constructor(e){this.authManager=e;this.search=async({query:e,maxResults:t=100,pageToken:o,labelIds:s,includeSpamTrash:a=!1})=>{try{m(`Gmail search - query: ${e}, maxResults: ${t}`);let d=await(await this.getGmailClient()).users.messages.list({userId:"me",q:e,maxResults:t,pageToken:o,labelIds:s,includeSpamTrash:a}),p=d.data.messages||[],u=d.data.nextPageToken,f=d.data.resultSizeEstimate;return m(`Found ${p.length} messages, estimated total: ${f}`),{content:[{type:"text",text:JSON.stringify({messages:p.map(y=>({id:y.id,threadId:y.threadId})),nextPageToken:u,resultSizeEstimate:f},null,2)}]}}catch(l){return this.handleError(l,"gmail.search")}};this.get=async({messageId:e,format:t="full"})=>{try{m(`Getting message ${e} with format: ${t}`);let a=(await(await this.getGmailClient()).users.messages.get({userId:"me",id:e,format:t})).data;if(t==="metadata"||t==="full"){let l=a.payload?.headers||[],d=S=>l.find(E=>E.name===S)?.value,p=d("Subject"),u=d("From"),f=d("To"),y=d("Date"),g="",_=[];if(t==="full"&&a.payload){let S=this.extractAttachmentsAndBody(a.payload);g=S.body,_=S.attachments}return{content:[{type:"text",text:JSON.stringify({id:a.id,threadId:a.threadId,labelIds:a.labelIds,snippet:a.snippet,subject:p,from:u,to:f,date:y,body:g||a.snippet,attachments:_},null,2)}]}}return{content:[{type:"text",text:JSON.stringify(a,null,2)}]}}catch(o){return this.handleError(o,"gmail.get")}};this.downloadAttachment=async({messageId:e,attachmentId:t,localPath:o})=>{try{if(m(`Downloading attachment ${t} from message ${e} to ${o}`),!Ge.isAbsolute(o))throw new Error("localPath must be an absolute path.");let l=(await(await this.getGmailClient()).users.messages.attachments.get({userId:"me",messageId:e,id:t})).data.data;if(!l)throw new Error("Attachment data is empty");await ut.mkdir(Ge.dirname(o),{recursive:!0});let d=Buffer.from(l,"base64url");return await ut.writeFile(o,d),m(`Attachment downloaded successfully to ${o}`),{content:[{type:"text",text:JSON.stringify({message:`Attachment downloaded successfully to ${o}`,path:o})}]}}catch(s){return this.handleError(s,"gmail.downloadAttachment")}};this.modify=async({messageId:e,addLabelIds:t=[],removeLabelIds:o=[]})=>{try{m(`Modifying message ${e} with addLabelIds: ${t}, removeLabelIds: ${o}`);let l=(await(await this.getGmailClient()).users.messages.modify({userId:"me",id:e,requestBody:{addLabelIds:t,removeLabelIds:o}})).data;return{content:[{type:"text",text:JSON.stringify(l,null,2)}]}}catch(s){return this.handleError(s,"gmail.modify")}};this.batchModify=async({messageIds:e,addLabelIds:t=[],removeLabelIds:o=[]})=>{try{if(t.length===0&&o.length===0)return{content:[{type:"text",text:JSON.stringify({status:"noop",message:Rs})}]};if(e.length>1e3)throw new Error(`Too many message IDs. Maximum is ${1e3}, got ${e.length}.`);return m(`Batch modifying ${e.length} messages with addLabelIds: ${t}, removeLabelIds: ${o}`),await(await this.getGmailClient()).users.messages.batchModify({userId:"me",requestBody:{ids:e,addLabelIds:t,removeLabelIds:o}}),{content:[{type:"text",text:JSON.stringify({modifiedCount:e.length,addLabelIds:t,removeLabelIds:o,status:"success"},null,2)}]}}catch(s){return this.handleError(s,"gmail.batchModify")}};this.modifyThread=async({threadId:e,addLabelIds:t=[],removeLabelIds:o=[]})=>{try{if(t.length===0&&o.length===0)return{content:[{type:"text",text:JSON.stringify({status:"noop",message:Rs})}]};m(`Modifying thread ${e} with addLabelIds: ${t}, removeLabelIds: ${o}`);let l=(await(await this.getGmailClient()).users.threads.modify({userId:"me",id:e,requestBody:{addLabelIds:t,removeLabelIds:o}})).data;return{content:[{type:"text",text:JSON.stringify(l,null,2)}]}}catch(s){return this.handleError(s,"gmail.modifyThread")}};this.send=async({to:e,subject:t,body:o,cc:s,bcc:a,replyTo:l,isHtml:d=!1})=>{try{let p=this.validateEmailAddresses({to:e,cc:s,bcc:a,replyTo:l});if(p)return p;m(`Sending email to: ${e}, subject: ${t}`);let u=Zt.createMimeMessage({to:Array.isArray(e)?e.join(", "):e,subject:t,body:o,cc:s?Array.isArray(s)?s.join(", "):s:void 0,bcc:a?Array.isArray(a)?a.join(", "):a:void 0,replyTo:l,isHtml:d}),y=await(await this.getGmailClient()).users.messages.send({userId:"me",requestBody:{raw:u}});return m(`Email sent successfully: ${y.data.id}`),{content:[{type:"text",text:JSON.stringify({id:y.data.id,threadId:y.data.threadId,labelIds:y.data.labelIds,status:"sent"},null,2)}]}}catch(p){return this.handleError(p,"gmail.send")}};this.createDraft=async({to:e,subject:t,body:o,cc:s,bcc:a,replyTo:l,isHtml:d=!1,threadId:p,attachments:u})=>{try{let f=this.validateEmailAddresses({to:e,cc:s,bcc:a,replyTo:l});if(f)return f;m(`Creating draft - to: ${e}, subject: ${t}`);let y=await this.getGmailClient(),g,_;if(p)try{let x=(await y.users.threads.get({userId:"me",id:p,format:"metadata",metadataHeaders:["Message-ID","References"]})).data.messages||[];if(x.length>0){let C=x[x.length-1].payload?.headers||[],v=C.find($=>$.name?.toLowerCase()==="message-id"),k=C.find($=>$.name?.toLowerCase()==="references");if(v?.value){g=v.value;let $=k?.value||"";_=$?`${$} ${v.value}`:v.value}}}catch(R){m(`Warning: Could not fetch thread ${p} for reply headers: ${R}`)}let S;if(u&&u.length>0){let x=(await Promise.all(u.map(async C=>{if(!Ge.isAbsolute(C.filePath))throw new Error(`Attachment filePath must be an absolute path: ${C.filePath}`);let v;try{v=await ut.stat(C.filePath)}catch(k){throw new Error(`Could not access attachment file ${C.filePath}: ${k instanceof Error?k.message:String(k)}`)}if(!v.isFile())throw new Error(`Attachment path is not a file: ${C.filePath}`);return v.size}))).reduce((C,v)=>C+v,0);vc(x);let A=await Promise.all(u.map(async C=>{let v;try{v=await ut.readFile(C.filePath)}catch(k){throw new Error(`Could not read attachment file ${C.filePath}: ${k instanceof Error?k.message:String(k)}`)}return{filename:C.filename||Ge.basename(C.filePath),content:v,contentType:C.mimeType||Hp(C.filePath)}}));vc(A.reduce((C,v)=>C+v.content.length,0)),S=Zt.createMimeMessageWithAttachments({to:Array.isArray(e)?e.join(", "):e,subject:t,body:o,cc:s?Array.isArray(s)?s.join(", "):s:void 0,bcc:a?Array.isArray(a)?a.join(", "):a:void 0,replyTo:l,inReplyTo:g,references:_,isHtml:d,attachments:A})}else S=Zt.createMimeMessage({to:Array.isArray(e)?e.join(", "):e,subject:t,body:o,cc:s?Array.isArray(s)?s.join(", "):s:void 0,bcc:a?Array.isArray(a)?a.join(", "):a:void 0,replyTo:l,isHtml:d,inReplyTo:g,references:_});let E=await y.users.drafts.create({userId:"me",requestBody:{message:{raw:S,...p&&{threadId:p}}}});return m(`Draft created successfully: ${E.data.id}`),{content:[{type:"text",text:JSON.stringify({id:E.data.id,message:{id:E.data.message?.id,threadId:E.data.message?.threadId,labelIds:E.data.message?.labelIds},status:"draft_created"},null,2)}]}}catch(f){return this.handleError(f,"gmail.createDraft")}};this.sendDraft=async({draftId:e})=>{try{m(`Sending draft: ${e}`);let o=await(await this.getGmailClient()).users.drafts.send({userId:"me",requestBody:{id:e}});return m(`Draft sent successfully: ${o.data.id}`),{content:[{type:"text",text:JSON.stringify({id:o.data.id,threadId:o.data.threadId,labelIds:o.data.labelIds,status:"sent"},null,2)}]}}catch(t){return this.handleError(t,"gmail.sendDraft")}};this.listLabels=async()=>{try{m("Listing Gmail labels");let o=(await(await this.getGmailClient()).users.labels.list({userId:"me"})).data.labels||[];return m(`Found ${o.length} labels`),{content:[{type:"text",text:JSON.stringify({labels:o.map(s=>({id:s.id,name:s.name,type:s.type,messageListVisibility:s.messageListVisibility,labelListVisibility:s.labelListVisibility}))},null,2)}]}}catch(e){return this.handleError(e,"gmail.listLabels")}};this.createLabel=async({name:e,labelListVisibility:t="labelShow",messageListVisibility:o="show"})=>{try{m(`Creating Gmail label: ${e}`);let l=(await(await this.getGmailClient()).users.labels.create({userId:"me",requestBody:{name:e,labelListVisibility:t,messageListVisibility:o}})).data;return m(`Created label: ${l.name} with id: ${l.id}`),{content:[{type:"text",text:JSON.stringify({id:l.id,name:l.name,type:l.type,messageListVisibility:l.messageListVisibility,labelListVisibility:l.labelListVisibility,status:"created"},null,2)}]}}catch(s){return this.handleError(s,"gmail.createLabel")}}}async getGmailClient(){let e=await this.authManager.getAuthenticatedClient(),t={...W,auth:e};return jp.gmail({version:"v1",...t})}handleError(e,t){let o=e instanceof Error?e.message:String(e);return m(`Error during ${t}: ${o}`),{content:[{type:"text",text:JSON.stringify({error:o})}]}}validateEmailAddresses({to:e,cc:t,bcc:o,replyTo:s}){try{return at.parse(e),t&&at.parse(t),o&&at.parse(o),s&&at.parse(s),null}catch(a){if(!(a instanceof Wp))throw a;return m(`Rejected invalid email address input: ${a.message}`),{content:[{type:"text",text:JSON.stringify({error:"Invalid email address format",details:a.message})}]}}}extractAttachmentsAndBody(e,t={body:"",attachments:[]}){if(!e)return t;if(e.body?.data&&(!e.filename||!e.body.attachmentId)&&e.mimeType?.startsWith("text/")&&(!t.body||e.mimeType==="text/plain")&&(t.body=Buffer.from(e.body.data,"base64").toString("utf-8")),e.filename&&e.body?.attachmentId&&t.attachments.push({filename:e.filename,mimeType:e.mimeType,attachmentId:e.body.attachmentId,size:e.body.size}),e.parts)for(let o of e.parts)this.extractAttachmentsAndBody(o,t);return t}};var Fn=["search","get","downloadAttachment","modify","batchModify","modifyThread","send","createDraft","sendDraft","listLabels","createLabel"],Cc=z(Mn,Fn,{pagination:{search:"maxResults"},bounds:Ka});import{google as Gp}from"googleapis";var Bn=class{constructor(e){this.authManager=e;this.getUserProfile=async({userId:e,email:t,name:o})=>{m(`[PeopleService] Starting getUserProfile with: userId=${e}, email=${t}, name=${o}`);try{if(!e&&!t&&!o)throw new Error("Either userId, email, or name must be provided.");let s=await this.getPeopleClient();if(e){let a=e.startsWith("people/")?e:`people/${e}`,l=await s.people.get({resourceName:a,personFields:"names,emailAddresses"});return m(`[PeopleService] Finished getUserProfile for user: ${e}`),{content:[{type:"text",text:JSON.stringify({results:[{person:l.data}]})}]}}else if(t||o){let a=t||o,l=await s.people.searchDirectoryPeople({query:a,readMask:"names,emailAddresses",sources:["DIRECTORY_SOURCE_TYPE_DOMAIN_CONTACT","DIRECTORY_SOURCE_TYPE_DOMAIN_PROFILE"]});return m(`[PeopleService] Finished getUserProfile search for: ${a}`),{content:[{type:"text",text:JSON.stringify(l.data)}]}}else throw new Error("Either userId, email, or name must be provided.")}catch(s){let a=s instanceof Error?s.message:String(s);return m(`[PeopleService] Error during people.getUserProfile: ${a}`),{content:[{type:"text",text:JSON.stringify({error:a})}]}}};this.getMe=async()=>{m("[PeopleService] Starting getMe");try{let t=await(await this.getPeopleClient()).people.get({resourceName:"people/me",personFields:"names,emailAddresses"});return m("[PeopleService] Finished getMe"),{content:[{type:"text",text:JSON.stringify(t.data)}]}}catch(e){let t=e instanceof Error?e.message:String(e);return m(`[PeopleService] Error during people.getMe: ${t}`),{content:[{type:"text",text:JSON.stringify({error:t})}]}}};this.getUserRelations=async({userId:e,relationType:t})=>{let o=e?e.startsWith("people/")?e:`people/${e}`:"people/me";m(`[PeopleService] Starting getUserRelations for ${o} with relationType=${t}`);try{let a=await(await this.getPeopleClient()).people.get({resourceName:o,personFields:"relations"});m("[PeopleService] Finished getUserRelations API call");let l=a.data?.relations||[],d=t?l.filter(u=>u.type?.toLowerCase()===t.toLowerCase()):l;t?m(`[PeopleService] Filtered to ${d.length} relations of type: ${t}`):m(`[PeopleService] Returning all ${d.length} relations`);let p={resourceName:o,...t&&{relationType:t},relations:d};return{content:[{type:"text",text:JSON.stringify(p)}]}}catch(s){let a=s instanceof Error?s.message:String(s);return m(`[PeopleService] Error during people.getUserRelations: ${a}`),{content:[{type:"text",text:JSON.stringify({error:a})}]}}}}async getPeopleClient(){let e=await this.authManager.getAuthenticatedClient(),t={...W,auth:e};return Gp.people({version:"v1",...t})}};var Un=["getUserProfile","getMe","getUserRelations"],Ac=z(Bn,Un,{bounds:oc});import{google as Jp}from"googleapis";var qn=class r{constructor(e){this.authManager=e;this.getText=async({spreadsheetId:e,format:t="text",max_chars:o,full:s})=>{m(`[SheetsService] Starting getText for spreadsheet: ${e} with format: ${t}`);try{let a=F(e)||e,l=hs(o,s),d=await this.getSheetsClient(),p=await d.spreadsheets.get({spreadsheetId:a,includeGridData:!1}),u="",f={};p.data.properties?.title&&t!=="json"&&(u+=`Spreadsheet Title: ${p.data.properties.title}
52
52
 
53
53
  `);let y=p.data.sheets?.map(E=>E.properties?.title).filter(E=>!!E)||[],g=await this.readAllSheets(d,a,y);for(let{sheetName:E,values:R}of g){if(R===null){t==="json"?m(`[SheetsService] Skipping sheet ${E} in JSON output due to error`):u+=`Sheet Name: ${E}
54
54
  (Error reading sheet)
@@ -59,14 +59,14 @@ ${s}`,truncated:!0,totalCharacters:t}}var In=class n{constructor(e){this.authMan
59
59
  `))&&(v=`"${v.replace(/"/g,'""')}"`),u+=v}u+=`
60
60
  `}else for(let x=0;x<R.length;x++){let A=R[x];for(let C=0;C<A.length;C++)C>0&&(u+=" | "),u+=A[C]||"";u+=`
61
61
  `}u+=`
62
- `}}t==="json"&&(u=JSON.stringify(f,null,2));let _="Pass a larger max_chars (up to "+1e5+"), full:true, a narrower format, or getRange for one tab.";if(t==="json"){let E=wc(f,l,_);return m(`[SheetsService] Finished getText for spreadsheet: ${a} (${E.returnedRows}/${E.totalRows} rows, ${E.returnedCharacters}/${E.totalCharacters} chars)`),{content:[{type:"text",text:E.text}]}}let S=Sc(u.trim(),l,_);return m(`[SheetsService] Finished getText for spreadsheet: ${a}`),{content:[{type:"text",text:S.text}]}}catch(a){let l=a instanceof Error?a.message:String(a);return m(`[SheetsService] Error during sheets.getText: ${l}`),{content:[{type:"text",text:JSON.stringify({error:l})}]}}};this.getRange=async({spreadsheetId:e,range:t,max_chars:s,full:o})=>{m(`[SheetsService] Starting getRange for spreadsheet: ${e}, range: ${t}`);try{let a=F(e)||e,l=ho(s,o),p=await(await this.getSheetsClient()).spreadsheets.values.get({spreadsheetId:a,range:t}),u=p.data.values||[],f=JSON.stringify({range:p.data.range,values:u});if(f.length<=l)return m(`[SheetsService] Finished getRange for spreadsheet: ${a}`),{content:[{type:"text",text:f}]};let y=0,g=u.length;for(;y<g;){let E=Math.ceil((y+g)/2);JSON.stringify({range:p.data.range,values:u.slice(0,E)}).length<=l?y=E:g=E-1}let _=JSON.stringify({range:p.data.range,values:u.slice(0,y)}),S="Pass a larger max_chars (up to "+1e5+"), full:true, or narrow the range.";return m(`[SheetsService] Finished getRange for spreadsheet: ${a} (${y}/${u.length} rows)`),{content:[{type:"text",text:JSON.stringify({range:p.data.range,values:u.slice(0,y),truncated:!0,total_characters:f.length,returned_characters:_.length,returned_rows:y,total_rows:u.length,truncation_note:Yt(f.length,_.length,S)},null,2)}]}}catch(a){let l=a instanceof Error?a.message:String(a);return m(`[SheetsService] Error during sheets.getRange: ${l}`),{content:[{type:"text",text:JSON.stringify({error:l})}]}}};this.getMetadata=async({spreadsheetId:e})=>{m(`[SheetsService] Starting getMetadata for spreadsheet: ${e}`);try{let t=F(e)||e,o=await(await this.getSheetsClient()).spreadsheets.get({spreadsheetId:t,includeGridData:!1}),a={spreadsheetId:o.data.spreadsheetId,title:o.data.properties?.title,sheets:o.data.sheets?.map(l=>({sheetId:l.properties?.sheetId,title:l.properties?.title,index:l.properties?.index,rowCount:l.properties?.gridProperties?.rowCount,columnCount:l.properties?.gridProperties?.columnCount})),locale:o.data.properties?.locale,timeZone:o.data.properties?.timeZone};return m(`[SheetsService] Finished getMetadata for spreadsheet: ${t}`),{content:[{type:"text",text:JSON.stringify(a)}]}}catch(t){let s=t instanceof Error?t.message:String(t);return m(`[SheetsService] Error during sheets.getMetadata: ${s}`),{content:[{type:"text",text:JSON.stringify({error:s})}]}}}}async getSheetsClient(){let e=await this.authManager.getAuthenticatedClient(),t={...W,auth:e};return Gp.sheets({version:"v4",...t})}static sheetRange(e){return`'${e.replace(/'/g,"''")}'`}async readAllSheets(e,t,s){if(s.length===0)return[];let o=s.map(l=>n.sheetRange(l));try{let d=(await e.spreadsheets.values.batchGet({spreadsheetId:t,ranges:o})).data.valueRanges;if(!d||d.length!==o.length)throw new Error(`batchGet returned ${d?.length??0} value ranges for ${o.length} sheets`);return s.map((p,u)=>({sheetName:p,values:d[u].values||[]}))}catch(l){m(`[SheetsService] batchGet failed, falling back to per-sheet reads: ${l}`)}return await Promise.all(s.map(async l=>{try{let d=await e.spreadsheets.values.get({spreadsheetId:t,range:n.sheetRange(l)});return{sheetName:l,values:d.data.values||[]}}catch(d){return m(`[SheetsService] Error reading sheet ${l}: ${d}`),{sheetName:l,values:null}}}))}};var jn=["getText","getRange","getMetadata"],Ic=z(qn,jn);import{google as _h}from"googleapis";import*as fs from"node:fs/promises";import*as ir from"node:path";var du=Ht(Eo(),1);import{Agent as yh}from"https";var vo=Ht(Eo(),1),jc=Ht(qc(),1),Co=jc.default.pkg,xo=Symbol.for(`${Co.name}-gaxios-error`),Oe=class n extends Error{config;response;code;status;error;[xo]=Co.version;static[Symbol.hasInstance](e){return e&&typeof e=="object"&&xo in e&&e[xo]===Co.version?!0:Function.prototype[Symbol.hasInstance].call(n,e)}constructor(e,t,s,o){if(super(e,{cause:o}),this.config=t,this.response=s,this.error=o instanceof Error?o:void 0,this.config=(0,vo.default)(!0,{},t),this.response&&(this.response.config=(0,vo.default)(!0,{},this.response.config)),this.response){try{this.response.data=Yp(this.config.responseType,this.response?.bodyUsed?this.response?.data:void 0)}catch{}this.status=this.response.status}o instanceof DOMException?this.code=o.name:o&&typeof o=="object"&&"code"in o&&(typeof o.code=="string"||typeof o.code=="number")&&(this.code=o.code)}static extractAPIErrorFromResponse(e,t="The request failed"){let s=t;if(typeof e.data=="string"&&(s=e.data),e.data&&typeof e.data=="object"&&"error"in e.data&&e.data.error&&!e.ok){if(typeof e.data.error=="string")return{message:e.data.error,code:e.status,status:e.statusText};if(typeof e.data.error=="object"){s="message"in e.data.error&&typeof e.data.error.message=="string"?e.data.error.message:s;let o="status"in e.data.error&&typeof e.data.error.status=="string"?e.data.error.status:e.statusText,a="code"in e.data.error&&typeof e.data.error.code=="number"?e.data.error.code:e.status;if("errors"in e.data.error&&Array.isArray(e.data.error.errors)){let l=[];for(let d of e.data.error.errors)typeof d=="object"&&"message"in d&&typeof d.message=="string"&&l.push(d.message);return Object.assign({message:l.join(`
63
- `)||s,code:a,status:o},e.data.error)}return Object.assign({message:s,code:a,status:o},e.data.error)}}return{message:s,code:e.status,status:e.statusText}}};function Yp(n,e){switch(n){case"stream":return e;case"json":return JSON.parse(JSON.stringify(e));case"arraybuffer":return JSON.parse(Buffer.from(e).toString("utf8"));case"blob":return JSON.parse(e.text());default:return e}}function Ao(n){let e="<<REDACTED> - See `errorRedactor` option in `gaxios` for configuration>.";function t(a){a&&a.forEach((l,d)=>{(/^authentication$/i.test(d)||/^authorization$/i.test(d)||/secret/i.test(d))&&a.set(d,e)})}function s(a,l){if(typeof a=="object"&&a!==null&&typeof a[l]=="string"){let d=a[l];(/grant_type=/i.test(d)||/assertion=/i.test(d)||/secret/i.test(d))&&(a[l]=e)}}function o(a){!a||typeof a!="object"||(a instanceof FormData||a instanceof URLSearchParams||"forEach"in a&&"set"in a?a.forEach((l,d)=>{(["grant_type","assertion"].includes(d)||/secret/.test(d))&&a.set(d,e)}):("grant_type"in a&&(a.grant_type=e),"assertion"in a&&(a.assertion=e),"client_secret"in a&&(a.client_secret=e)))}return n.config&&(t(n.config.headers),s(n.config,"data"),o(n.config.data),s(n.config,"body"),o(n.config.body),n.config.url.searchParams.has("token")&&n.config.url.searchParams.set("token",e),n.config.url.searchParams.has("client_secret")&&n.config.url.searchParams.set("client_secret",e)),n.response&&(Ao({config:n.response.config}),t(n.response.headers),n.response.bodyUsed&&(s(n.response,"data"),o(n.response.data))),n}async function Wc(n){let e=zc(n);if(!n||!n.config||!e&&!n.config.retry)return{shouldRetry:!1};e=e||{},e.currentRetryAttempt=e.currentRetryAttempt||0,e.retry=e.retry===void 0||e.retry===null?3:e.retry,e.httpMethodsToRetry=e.httpMethodsToRetry||["GET","HEAD","PUT","OPTIONS","DELETE"],e.noResponseRetries=e.noResponseRetries===void 0||e.noResponseRetries===null?2:e.noResponseRetries,e.retryDelayMultiplier=e.retryDelayMultiplier?e.retryDelayMultiplier:2,e.timeOfFirstRequest=e.timeOfFirstRequest?e.timeOfFirstRequest:Date.now(),e.totalTimeout=e.totalTimeout?e.totalTimeout:Number.MAX_SAFE_INTEGER,e.maxRetryDelay=e.maxRetryDelay?e.maxRetryDelay:Number.MAX_SAFE_INTEGER;let t=[[100,199],[408,408],[429,429],[500,599]];if(e.statusCodesToRetry=e.statusCodesToRetry||t,n.config.retryConfig=e,!await(e.shouldRetry||Zp)(n))return{shouldRetry:!1,config:n.config};let o=Xp(e);n.config.retryConfig.currentRetryAttempt+=1;let a=e.retryBackoff?e.retryBackoff(n,o):new Promise(l=>{setTimeout(l,o)});return e.onRetryAttempt&&await e.onRetryAttempt(n),await a,{shouldRetry:!0,config:n.config}}function Zp(n){let e=zc(n);if(n.config.signal?.aborted&&n.code!=="TimeoutError"||n.code==="AbortError"||!e||e.retry===0||!n.response&&(e.currentRetryAttempt||0)>=e.noResponseRetries||!e.httpMethodsToRetry||!e.httpMethodsToRetry.includes(n.config.method?.toUpperCase()||"GET"))return!1;if(n.response&&n.response.status){let t=!1;for(let[s,o]of e.statusCodesToRetry){let a=n.response.status;if(a>=s&&a<=o){t=!0;break}}if(!t)return!1}return e.currentRetryAttempt=e.currentRetryAttempt||0,!(e.currentRetryAttempt>=e.retry)}function zc(n){if(n&&n.config&&n.config.retryConfig)return n.config.retryConfig}function Xp(n){let t=(n.currentRetryAttempt?0:n.retryDelay??100)+(Math.pow(n.retryDelayMultiplier,n.currentRetryAttempt)-1)/2*1e3,s=n.totalTimeout-(Date.now()-n.timeOfFirstRequest);return Math.min(t,s,n.maxRetryDelay)}import{Readable as uu}from"stream";var xr=class extends Set{};var or,bh=async()=>globalThis.crypto?.randomUUID()||(await import("crypto")).randomUUID(),Sh=204,Dr=class{agentCache=new Map;defaults;interceptors;constructor(e){this.defaults=e||{},this.interceptors={request:new xr,response:new xr}}fetch(...e){let t=e[0],s=e[1],o,a=new Headers;return typeof t=="string"?o=new URL(t):t instanceof URL?o=t:t&&t.url&&(o=new URL(t.url)),t&&typeof t=="object"&&"headers"in t&&or.mergeHeaders(a,t.headers),s&&or.mergeHeaders(a,new Headers(s.headers)),typeof t=="object"&&!(t instanceof URL)?this.request({...s,...t,headers:a,url:o}):this.request({...s,headers:a,url:o})}async request(e={}){let t=await this.#n(e);return t=await this.#t(t),this.#r(this._request(t))}async _defaultAdapter(e){let t=e.fetchImplementation||this.defaults.fetchImplementation||await or.#c(),s={...e};delete s.data;let o=await t(e.url,s),a=await this.getResponseData(e,o);return Object.getOwnPropertyDescriptor(o,"data")?.configurable||Object.defineProperties(o,{data:{configurable:!0,writable:!0,enumerable:!0,value:a}}),Object.assign(o,{config:e,data:a})}async _request(e){try{let t;if(e.adapter?t=await e.adapter(e,this._defaultAdapter.bind(this)):t=await this._defaultAdapter(e),!e.validateStatus(t.status)){if(e.responseType==="stream"){let o=[];for await(let a of t.data)o.push(a);t.data=Buffer.concat(o.map(a=>typeof a=="string"?Buffer.from(a):a)).toString("utf8")}let s=Oe.extractAPIErrorFromResponse(t,`Request failed with status code ${t.status}`);throw new Oe(s?.message,e,t,s)}return t}catch(t){let s;t instanceof Oe?s=t:t instanceof Error?s=new Oe(t.message,e,void 0,t):s=new Oe("Unexpected Gaxios Error",e,void 0,t);let{shouldRetry:o,config:a}=await Wc(s);if(o&&a)return s.config.retryConfig.currentRetryAttempt=a.retryConfig.currentRetryAttempt,e.retryConfig=s.config?.retryConfig,this.#s(e),this._request(e);throw e.errorRedactor&&e.errorRedactor(s),s}}async getResponseData(e,t){if(t.status===Sh)return"";if(e.maxContentLength&&t.headers.has("content-length")&&e.maxContentLength<Number.parseInt(t.headers?.get("content-length")||""))throw new Oe("Response's `Content-Length` is over the limit.",e,Object.assign(t,{config:e}));switch(e.responseType){case"stream":return t.body;case"json":{let s=await t.text();try{return JSON.parse(s)}catch{return s}}case"arraybuffer":return t.arrayBuffer();case"blob":return t.blob();case"text":return t.text();default:return this.getResponseDataFromContentType(t)}}#e(e,t=[]){let s=new URL(e),o=[...t],a=(process.env.NO_PROXY??process.env.no_proxy)?.split(",")||[];for(let l of a)o.push(l.trim());for(let l of o)if(l instanceof RegExp){if(l.test(s.toString()))return!1}else if(l instanceof URL){if(l.origin===s.origin)return!1}else if(l.startsWith("*.")||l.startsWith(".")){let d=l.replace(/^\*\./,".");if(s.hostname.endsWith(d))return!1}else if(l===s.origin||l===s.hostname||l===s.href)return!1;return!0}async#t(e){let t=Promise.resolve(e);for(let s of this.interceptors.request.values())s&&(t=t.then(s.resolved,s.rejected));return t}async#r(e){let t=Promise.resolve(e);for(let s of this.interceptors.response.values())s&&(t=t.then(s.resolved,s.rejected));return t}async#n(e){let t=new Headers(this.defaults.headers);or.mergeHeaders(t,e.headers);let s=(0,du.default)(!0,{},this.defaults,e);if(!s.url)throw new Error("URL is required.");if(s.baseURL&&(s.url=new URL(s.url,s.baseURL)),s.url=new URL(s.url),s.params)if(s.paramsSerializer){let l=s.paramsSerializer(s.params);l.startsWith("?")&&(l=l.slice(1));let d=s.url.toString().includes("?")?"&":"?";s.url=s.url+d+l}else{let l=s.url instanceof URL?s.url:new URL(s.url);for(let[d,p]of new URLSearchParams(s.params))l.searchParams.append(d,p);s.url=l}typeof e.maxContentLength=="number"&&(s.size=e.maxContentLength),typeof e.maxRedirects=="number"&&(s.follow=e.maxRedirects);let o=typeof s.data=="string"||s.data instanceof ArrayBuffer||s.data instanceof Blob||globalThis.File&&s.data instanceof File||s.data instanceof FormData||s.data instanceof uu||s.data instanceof ReadableStream||s.data instanceof String||s.data instanceof URLSearchParams||ArrayBuffer.isView(s.data)||["Blob","File","FormData"].includes(s.data?.constructor?.name||"");if(s.multipart?.length){let l=await bh();t.set("content-type",`multipart/related; boundary=${l}`),s.body=uu.from(this.getMultipartRequest(s.multipart,l))}else o?s.body=s.data:typeof s.data=="object"?t.get("Content-Type")==="application/x-www-form-urlencoded"?s.body=s.paramsSerializer?s.paramsSerializer(s.data):new URLSearchParams(s.data):(t.has("content-type")||t.set("content-type","application/json"),s.body=JSON.stringify(s.data)):s.data&&(s.body=s.data);s.validateStatus=s.validateStatus||this.validateStatus,s.responseType=s.responseType||"unknown",!t.has("accept")&&s.responseType==="json"&&t.set("accept","application/json");let a=s.proxy||process?.env?.HTTPS_PROXY||process?.env?.https_proxy||process?.env?.HTTP_PROXY||process?.env?.http_proxy;if(!s.agent)if(a&&this.#e(s.url,s.noProxy)){let l=await or.#a();this.agentCache.has(a)?s.agent=this.agentCache.get(a):(s.agent=new l(a,{cert:s.cert,key:s.key}),this.agentCache.set(a,s.agent))}else s.cert&&s.key&&(this.agentCache.has(s.key)?s.agent=this.agentCache.get(s.key):(s.agent=new yh({cert:s.cert,key:s.key}),this.agentCache.set(s.key,s.agent)));return typeof s.errorRedactor!="function"&&s.errorRedactor!==!1&&(s.errorRedactor=Ao),s.body&&!("duplex"in s)&&(s.duplex="half"),this.#s(s),Object.assign(s,{headers:t,url:s.url instanceof URL?s.url:new URL(s.url)})}#s(e){if(e.timeout){let t=AbortSignal.timeout(e.timeout);e.signal&&!e.signal.aborted?e.signal=AbortSignal.any([e.signal,t]):e.signal=t}}validateStatus(e){return e>=200&&e<300}async getResponseDataFromContentType(e){let t=e.headers.get("Content-Type");if(t===null)return e.text();if(t=t.toLowerCase(),t.includes("application/json")){let s=await e.text();try{s=JSON.parse(s)}catch{}return s}else return t.match(/^text\//)?e.text():e.blob()}async*getMultipartRequest(e,t){let s=`--${t}--`;for(let o of e){let a=o.headers.get("Content-Type")||"application/octet-stream";yield`--${t}\r
62
+ `}}t==="json"&&(u=JSON.stringify(f,null,2));let _="Pass a larger max_chars (up to "+1e5+"), full:true, a narrower format, or getRange for one tab.";if(t==="json"){let E=wc(f,l,_);return m(`[SheetsService] Finished getText for spreadsheet: ${a} (${E.returnedRows}/${E.totalRows} rows, ${E.returnedCharacters}/${E.totalCharacters} chars)`),{content:[{type:"text",text:E.text}]}}let S=Sc(u.trim(),l,_);return m(`[SheetsService] Finished getText for spreadsheet: ${a}`),{content:[{type:"text",text:S.text}]}}catch(a){let l=a instanceof Error?a.message:String(a);return m(`[SheetsService] Error during sheets.getText: ${l}`),{content:[{type:"text",text:JSON.stringify({error:l})}]}}};this.getRange=async({spreadsheetId:e,range:t,max_chars:o,full:s})=>{m(`[SheetsService] Starting getRange for spreadsheet: ${e}, range: ${t}`);try{let a=F(e)||e,l=hs(o,s),p=await(await this.getSheetsClient()).spreadsheets.values.get({spreadsheetId:a,range:t}),u=p.data.values||[],f=JSON.stringify({range:p.data.range,values:u});if(f.length<=l)return m(`[SheetsService] Finished getRange for spreadsheet: ${a}`),{content:[{type:"text",text:f}]};let y=0,g=u.length;for(;y<g;){let E=Math.ceil((y+g)/2);JSON.stringify({range:p.data.range,values:u.slice(0,E)}).length<=l?y=E:g=E-1}let _=JSON.stringify({range:p.data.range,values:u.slice(0,y)}),S="Pass a larger max_chars (up to "+1e5+"), full:true, or narrow the range.";return m(`[SheetsService] Finished getRange for spreadsheet: ${a} (${y}/${u.length} rows)`),{content:[{type:"text",text:JSON.stringify({range:p.data.range,values:u.slice(0,y),truncated:!0,total_characters:f.length,returned_characters:_.length,returned_rows:y,total_rows:u.length,truncation_note:Yt(f.length,_.length,S)},null,2)}]}}catch(a){let l=a instanceof Error?a.message:String(a);return m(`[SheetsService] Error during sheets.getRange: ${l}`),{content:[{type:"text",text:JSON.stringify({error:l})}]}}};this.getMetadata=async({spreadsheetId:e})=>{m(`[SheetsService] Starting getMetadata for spreadsheet: ${e}`);try{let t=F(e)||e,s=await(await this.getSheetsClient()).spreadsheets.get({spreadsheetId:t,includeGridData:!1}),a={spreadsheetId:s.data.spreadsheetId,title:s.data.properties?.title,sheets:s.data.sheets?.map(l=>({sheetId:l.properties?.sheetId,title:l.properties?.title,index:l.properties?.index,rowCount:l.properties?.gridProperties?.rowCount,columnCount:l.properties?.gridProperties?.columnCount})),locale:s.data.properties?.locale,timeZone:s.data.properties?.timeZone};return m(`[SheetsService] Finished getMetadata for spreadsheet: ${t}`),{content:[{type:"text",text:JSON.stringify(a)}]}}catch(t){let o=t instanceof Error?t.message:String(t);return m(`[SheetsService] Error during sheets.getMetadata: ${o}`),{content:[{type:"text",text:JSON.stringify({error:o})}]}}}}async getSheetsClient(){let e=await this.authManager.getAuthenticatedClient(),t={...W,auth:e};return Jp.sheets({version:"v4",...t})}static sheetRange(e){return`'${e.replace(/'/g,"''")}'`}async readAllSheets(e,t,o){if(o.length===0)return[];let s=o.map(l=>r.sheetRange(l));try{let d=(await e.spreadsheets.values.batchGet({spreadsheetId:t,ranges:s})).data.valueRanges;if(!d||d.length!==s.length)throw new Error(`batchGet returned ${d?.length??0} value ranges for ${s.length} sheets`);return o.map((p,u)=>({sheetName:p,values:d[u].values||[]}))}catch(l){m(`[SheetsService] batchGet failed, falling back to per-sheet reads: ${l}`)}return await Promise.all(o.map(async l=>{try{let d=await e.spreadsheets.values.get({spreadsheetId:t,range:r.sheetRange(l)});return{sheetName:l,values:d.data.values||[]}}catch(d){return m(`[SheetsService] Error reading sheet ${l}: ${d}`),{sheetName:l,values:null}}}))}};var jn=["getText","getRange","getMetadata"],Ic=z(qn,jn);import{google as Th}from"googleapis";import*as po from"node:fs/promises";import*as ir from"node:path";var du=Ht(Es(),1);import{Agent as bh}from"https";var vs=Ht(Es(),1),jc=Ht(qc(),1),Cs=jc.default.pkg,xs=Symbol.for(`${Cs.name}-gaxios-error`),Oe=class r extends Error{config;response;code;status;error;[xs]=Cs.version;static[Symbol.hasInstance](e){return e&&typeof e=="object"&&xs in e&&e[xs]===Cs.version?!0:Function.prototype[Symbol.hasInstance].call(r,e)}constructor(e,t,o,s){if(super(e,{cause:s}),this.config=t,this.response=o,this.error=s instanceof Error?s:void 0,this.config=(0,vs.default)(!0,{},t),this.response&&(this.response.config=(0,vs.default)(!0,{},this.response.config)),this.response){try{this.response.data=Zp(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&&typeof s=="object"&&"code"in s&&(typeof s.code=="string"||typeof s.code=="number")&&(this.code=s.code)}static extractAPIErrorFromResponse(e,t="The request failed"){let o=t;if(typeof e.data=="string"&&(o=e.data),e.data&&typeof e.data=="object"&&"error"in e.data&&e.data.error&&!e.ok){if(typeof e.data.error=="string")return{message:e.data.error,code:e.status,status:e.statusText};if(typeof e.data.error=="object"){o="message"in e.data.error&&typeof e.data.error.message=="string"?e.data.error.message:o;let s="status"in e.data.error&&typeof e.data.error.status=="string"?e.data.error.status:e.statusText,a="code"in e.data.error&&typeof e.data.error.code=="number"?e.data.error.code:e.status;if("errors"in e.data.error&&Array.isArray(e.data.error.errors)){let l=[];for(let d of e.data.error.errors)typeof d=="object"&&"message"in d&&typeof d.message=="string"&&l.push(d.message);return Object.assign({message:l.join(`
63
+ `)||o,code:a,status:s},e.data.error)}return Object.assign({message:o,code:a,status:s},e.data.error)}}return{message:o,code:e.status,status:e.statusText}}};function Zp(r,e){switch(r){case"stream":return e;case"json":return JSON.parse(JSON.stringify(e));case"arraybuffer":return JSON.parse(Buffer.from(e).toString("utf8"));case"blob":return JSON.parse(e.text());default:return e}}function As(r){let e="<<REDACTED> - See `errorRedactor` option in `gaxios` for configuration>.";function t(a){a&&a.forEach((l,d)=>{(/^authentication$/i.test(d)||/^authorization$/i.test(d)||/secret/i.test(d))&&a.set(d,e)})}function o(a,l){if(typeof a=="object"&&a!==null&&typeof a[l]=="string"){let d=a[l];(/grant_type=/i.test(d)||/assertion=/i.test(d)||/secret/i.test(d))&&(a[l]=e)}}function s(a){!a||typeof a!="object"||(a instanceof FormData||a instanceof URLSearchParams||"forEach"in a&&"set"in a?a.forEach((l,d)=>{(["grant_type","assertion"].includes(d)||/secret/.test(d))&&a.set(d,e)}):("grant_type"in a&&(a.grant_type=e),"assertion"in a&&(a.assertion=e),"client_secret"in a&&(a.client_secret=e)))}return r.config&&(t(r.config.headers),o(r.config,"data"),s(r.config.data),o(r.config,"body"),s(r.config.body),r.config.url.searchParams.has("token")&&r.config.url.searchParams.set("token",e),r.config.url.searchParams.has("client_secret")&&r.config.url.searchParams.set("client_secret",e)),r.response&&(As({config:r.response.config}),t(r.response.headers),r.response.bodyUsed&&(o(r.response,"data"),s(r.response.data))),r}async function Wc(r){let e=zc(r);if(!r||!r.config||!e&&!r.config.retry)return{shouldRetry:!1};e=e||{},e.currentRetryAttempt=e.currentRetryAttempt||0,e.retry=e.retry===void 0||e.retry===null?3:e.retry,e.httpMethodsToRetry=e.httpMethodsToRetry||["GET","HEAD","PUT","OPTIONS","DELETE"],e.noResponseRetries=e.noResponseRetries===void 0||e.noResponseRetries===null?2:e.noResponseRetries,e.retryDelayMultiplier=e.retryDelayMultiplier?e.retryDelayMultiplier:2,e.timeOfFirstRequest=e.timeOfFirstRequest?e.timeOfFirstRequest:Date.now(),e.totalTimeout=e.totalTimeout?e.totalTimeout:Number.MAX_SAFE_INTEGER,e.maxRetryDelay=e.maxRetryDelay?e.maxRetryDelay:Number.MAX_SAFE_INTEGER;let t=[[100,199],[408,408],[429,429],[500,599]];if(e.statusCodesToRetry=e.statusCodesToRetry||t,r.config.retryConfig=e,!await(e.shouldRetry||Xp)(r))return{shouldRetry:!1,config:r.config};let s=Qp(e);r.config.retryConfig.currentRetryAttempt+=1;let a=e.retryBackoff?e.retryBackoff(r,s):new Promise(l=>{setTimeout(l,s)});return e.onRetryAttempt&&await e.onRetryAttempt(r),await a,{shouldRetry:!0,config:r.config}}function Xp(r){let e=zc(r);if(r.config.signal?.aborted&&r.code!=="TimeoutError"||r.code==="AbortError"||!e||e.retry===0||!r.response&&(e.currentRetryAttempt||0)>=e.noResponseRetries||!e.httpMethodsToRetry||!e.httpMethodsToRetry.includes(r.config.method?.toUpperCase()||"GET"))return!1;if(r.response&&r.response.status){let t=!1;for(let[o,s]of e.statusCodesToRetry){let a=r.response.status;if(a>=o&&a<=s){t=!0;break}}if(!t)return!1}return e.currentRetryAttempt=e.currentRetryAttempt||0,!(e.currentRetryAttempt>=e.retry)}function zc(r){if(r&&r.config&&r.config.retryConfig)return r.config.retryConfig}function Qp(r){let t=(r.currentRetryAttempt?0:r.retryDelay??100)+(Math.pow(r.retryDelayMultiplier,r.currentRetryAttempt)-1)/2*1e3,o=r.totalTimeout-(Date.now()-r.timeOfFirstRequest);return Math.min(t,o,r.maxRetryDelay)}import{Readable as uu}from"stream";var xr=class extends Set{};var sr,Sh=async()=>globalThis.crypto?.randomUUID()||(await import("crypto")).randomUUID(),wh=204,Dr=class{agentCache=new Map;defaults;interceptors;constructor(e){this.defaults=e||{},this.interceptors={request:new xr,response:new xr}}fetch(...e){let t=e[0],o=e[1],s,a=new Headers;return typeof t=="string"?s=new URL(t):t instanceof URL?s=t:t&&t.url&&(s=new URL(t.url)),t&&typeof t=="object"&&"headers"in t&&sr.mergeHeaders(a,t.headers),o&&sr.mergeHeaders(a,new Headers(o.headers)),typeof t=="object"&&!(t instanceof URL)?this.request({...o,...t,headers:a,url:s}):this.request({...o,headers:a,url:s})}async request(e={}){let t=await this.#n(e);return t=await this.#t(t),this.#r(this._request(t))}async _defaultAdapter(e){let t=e.fetchImplementation||this.defaults.fetchImplementation||await sr.#c(),o={...e};delete o.data;let s=await t(e.url,o),a=await this.getResponseData(e,s);return Object.getOwnPropertyDescriptor(s,"data")?.configurable||Object.defineProperties(s,{data:{configurable:!0,writable:!0,enumerable:!0,value:a}}),Object.assign(s,{config:e,data:a})}async _request(e){try{let t;if(e.adapter?t=await e.adapter(e,this._defaultAdapter.bind(this)):t=await this._defaultAdapter(e),!e.validateStatus(t.status)){if(e.responseType==="stream"){let s=[];for await(let a of t.data)s.push(a);t.data=Buffer.concat(s.map(a=>typeof a=="string"?Buffer.from(a):a)).toString("utf8")}let o=Oe.extractAPIErrorFromResponse(t,`Request failed with status code ${t.status}`);throw new Oe(o?.message,e,t,o)}return t}catch(t){let o;t instanceof Oe?o=t:t instanceof Error?o=new Oe(t.message,e,void 0,t):o=new Oe("Unexpected Gaxios Error",e,void 0,t);let{shouldRetry:s,config:a}=await Wc(o);if(s&&a)return o.config.retryConfig.currentRetryAttempt=a.retryConfig.currentRetryAttempt,e.retryConfig=o.config?.retryConfig,this.#o(e),this._request(e);throw e.errorRedactor&&e.errorRedactor(o),o}}async getResponseData(e,t){if(t.status===wh)return"";if(e.maxContentLength&&t.headers.has("content-length")&&e.maxContentLength<Number.parseInt(t.headers?.get("content-length")||""))throw new Oe("Response's `Content-Length` is over the limit.",e,Object.assign(t,{config:e}));switch(e.responseType){case"stream":return t.body;case"json":{let o=await t.text();try{return JSON.parse(o)}catch{return o}}case"arraybuffer":return t.arrayBuffer();case"blob":return t.blob();case"text":return t.text();default:return this.getResponseDataFromContentType(t)}}#e(e,t=[]){let o=new URL(e),s=[...t],a=(process.env.NO_PROXY??process.env.no_proxy)?.split(",")||[];for(let l of a)s.push(l.trim());for(let l of s)if(l instanceof RegExp){if(l.test(o.toString()))return!1}else if(l instanceof URL){if(l.origin===o.origin)return!1}else if(l.startsWith("*.")||l.startsWith(".")){let d=l.replace(/^\*\./,".");if(o.hostname.endsWith(d))return!1}else if(l===o.origin||l===o.hostname||l===o.href)return!1;return!0}async#t(e){let t=Promise.resolve(e);for(let o of this.interceptors.request.values())o&&(t=t.then(o.resolved,o.rejected));return t}async#r(e){let t=Promise.resolve(e);for(let o of this.interceptors.response.values())o&&(t=t.then(o.resolved,o.rejected));return t}async#n(e){let t=new Headers(this.defaults.headers);sr.mergeHeaders(t,e.headers);let o=(0,du.default)(!0,{},this.defaults,e);if(!o.url)throw new Error("URL is required.");if(o.baseURL&&(o.url=new URL(o.url,o.baseURL)),o.url=new URL(o.url),o.params)if(o.paramsSerializer){let l=o.paramsSerializer(o.params);l.startsWith("?")&&(l=l.slice(1));let d=o.url.toString().includes("?")?"&":"?";o.url=o.url+d+l}else{let l=o.url instanceof URL?o.url:new URL(o.url);for(let[d,p]of new URLSearchParams(o.params))l.searchParams.append(d,p);o.url=l}typeof e.maxContentLength=="number"&&(o.size=e.maxContentLength),typeof e.maxRedirects=="number"&&(o.follow=e.maxRedirects);let s=typeof o.data=="string"||o.data instanceof ArrayBuffer||o.data instanceof Blob||globalThis.File&&o.data instanceof File||o.data instanceof FormData||o.data instanceof uu||o.data instanceof ReadableStream||o.data instanceof String||o.data instanceof URLSearchParams||ArrayBuffer.isView(o.data)||["Blob","File","FormData"].includes(o.data?.constructor?.name||"");if(o.multipart?.length){let l=await Sh();t.set("content-type",`multipart/related; boundary=${l}`),o.body=uu.from(this.getMultipartRequest(o.multipart,l))}else s?o.body=o.data:typeof o.data=="object"?t.get("Content-Type")==="application/x-www-form-urlencoded"?o.body=o.paramsSerializer?o.paramsSerializer(o.data):new URLSearchParams(o.data):(t.has("content-type")||t.set("content-type","application/json"),o.body=JSON.stringify(o.data)):o.data&&(o.body=o.data);o.validateStatus=o.validateStatus||this.validateStatus,o.responseType=o.responseType||"unknown",!t.has("accept")&&o.responseType==="json"&&t.set("accept","application/json");let a=o.proxy||process?.env?.HTTPS_PROXY||process?.env?.https_proxy||process?.env?.HTTP_PROXY||process?.env?.http_proxy;if(!o.agent)if(a&&this.#e(o.url,o.noProxy)){let l=await sr.#a();this.agentCache.has(a)?o.agent=this.agentCache.get(a):(o.agent=new l(a,{cert:o.cert,key:o.key}),this.agentCache.set(a,o.agent))}else o.cert&&o.key&&(this.agentCache.has(o.key)?o.agent=this.agentCache.get(o.key):(o.agent=new bh({cert:o.cert,key:o.key}),this.agentCache.set(o.key,o.agent)));return typeof o.errorRedactor!="function"&&o.errorRedactor!==!1&&(o.errorRedactor=As),o.body&&!("duplex"in o)&&(o.duplex="half"),this.#o(o),Object.assign(o,{headers:t,url:o.url instanceof URL?o.url:new URL(o.url)})}#o(e){if(e.timeout){let t=AbortSignal.timeout(e.timeout);e.signal&&!e.signal.aborted?e.signal=AbortSignal.any([e.signal,t]):e.signal=t}}validateStatus(e){return e>=200&&e<300}async getResponseDataFromContentType(e){let t=e.headers.get("Content-Type");if(t===null)return e.text();if(t=t.toLowerCase(),t.includes("application/json")){let o=await e.text();try{o=JSON.parse(o)}catch{}return o}else return t.match(/^text\//)?e.text():e.blob()}async*getMultipartRequest(e,t){let o=`--${t}--`;for(let s of e){let a=s.headers.get("Content-Type")||"application/octet-stream";yield`--${t}\r
64
64
  Content-Type: ${a}\r
65
65
  \r
66
- `,typeof o.content=="string"?yield o.content:yield*o.content,yield`\r
67
- `}yield s}static#o;static#i;static async#a(){return this.#o||=(await Promise.resolve().then(()=>Ht(hl(),1))).HttpsProxyAgent,this.#o}static async#c(){let e=typeof window<"u"&&!!window;return this.#i||=e?window.fetch:(await Promise.resolve().then(()=>(lu(),cu))).default,this.#i}static mergeHeaders(e,...t){e=e instanceof Headers?e:new Headers(e);for(let s of t)(s instanceof Headers?s:new Headers(s)).forEach((a,l)=>{l==="set-cookie"?e.append(l,a):e.set(l,a)});return e}};or=Dr;var wh=new Dr;async function fu(n){return wh.request(n)}var pu=["BLANK","TITLE","TITLE_AND_BODY","TITLE_AND_TWO_COLUMNS","TITLE_ONLY","SECTION_HEADER","SECTION_TITLE_AND_DESCRIPTION","ONE_COLUMN_TEXT","MAIN_POINT","BIG_NUMBER"],mu=["ALL","FIXED_RANGE","FROM_START_INDEX"],ds=class{constructor(e){this.authManager=e;this.getText=async({presentationId:e})=>{m(`[SlidesService] Starting getText for presentation: ${e}`);try{let t=F(e)||e,o=await(await this.getSlidesClient()).presentations.get({presentationId:t,fields:"title,slides(pageElements(shape(text,shapeProperties),table(tableRows(tableCells(text)))))"}),a="";return o.data.title&&(a+=`Presentation Title: ${o.data.title}
66
+ `,typeof s.content=="string"?yield s.content:yield*s.content,yield`\r
67
+ `}yield o}static#s;static#i;static async#a(){return this.#s||=(await Promise.resolve().then(()=>Ht(hl(),1))).HttpsProxyAgent,this.#s}static async#c(){let e=typeof window<"u"&&!!window;return this.#i||=e?window.fetch:(await Promise.resolve().then(()=>(lu(),cu))).default,this.#i}static mergeHeaders(e,...t){e=e instanceof Headers?e:new Headers(e);for(let o of t)(o instanceof Headers?o:new Headers(o)).forEach((a,l)=>{l==="set-cookie"?e.append(l,a):e.set(l,a)});return e}};sr=Dr;var _h=new Dr;async function fu(r){return _h.request(r)}var pu=["BLANK","TITLE","TITLE_AND_BODY","TITLE_AND_TWO_COLUMNS","TITLE_ONLY","SECTION_HEADER","SECTION_TITLE_AND_DESCRIPTION","ONE_COLUMN_TEXT","MAIN_POINT","BIG_NUMBER"],mu=["ALL","FIXED_RANGE","FROM_START_INDEX"],fo=class{constructor(e){this.authManager=e;this.getText=async({presentationId:e})=>{m(`[SlidesService] Starting getText for presentation: ${e}`);try{let t=F(e)||e,s=await(await this.getSlidesClient()).presentations.get({presentationId:t,fields:"title,slides(pageElements(shape(text,shapeProperties),table(tableRows(tableCells(text)))))"}),a="";return s.data.title&&(a+=`Presentation Title: ${s.data.title}
68
68
 
69
- `),o.data.slides&&o.data.slides.forEach((l,d)=>{a+=`
69
+ `),s.data.slides&&s.data.slides.forEach((l,d)=>{a+=`
70
70
  --- Slide ${d+1} ---
71
71
  `,l.pageElements&&l.pageElements.forEach(p=>{if(p.shape&&p.shape.text){let u=this.extractTextFromTextContent(p.shape.text);u&&(a+=u+`
72
72
  `)}p.table&&p.table.tableRows&&(a+=`
@@ -74,8 +74,8 @@ Content-Type: ${a}\r
74
74
  `,p.table.tableRows.forEach(u=>{let f=[];u.tableCells&&u.tableCells.forEach(y=>{let g=y.text?this.extractTextFromTextContent(y.text):"";f.push(g.trim())}),a+=f.join(" | ")+`
75
75
  `}),a+=`--- End Table Data ---
76
76
  `)}),a+=`
77
- `}),m(`[SlidesService] Finished getText for presentation: ${t}`),{content:[{type:"text",text:a.trim()}]}}catch(t){let s=t instanceof Error?t.message:String(t);return m(`[SlidesService] Error during slides.getText: ${s}`),{content:[{type:"text",text:JSON.stringify({error:s})}]}}};this.getMetadata=async({presentationId:e})=>{m(`[SlidesService] Starting getMetadata for presentation: ${e}`);try{let t=F(e)||e,o=await(await this.getSlidesClient()).presentations.get({presentationId:t,fields:"presentationId,title,slides(objectId),pageSize,notesMaster,masters,layouts"}),a={presentationId:o.data.presentationId,title:o.data.title,slideCount:o.data.slides?.length||0,slides:o.data.slides?.map(({objectId:l})=>({objectId:l}))??[],pageSize:o.data.pageSize,hasMasters:!!o.data.masters?.length,hasLayouts:!!o.data.layouts?.length,hasNotesMaster:!!o.data.notesMaster};return m(`[SlidesService] Finished getMetadata for presentation: ${t}`),{content:[{type:"text",text:JSON.stringify(a)}]}}catch(t){let s=t instanceof Error?t.message:String(t);return m(`[SlidesService] Error during slides.getMetadata: ${s}`),{content:[{type:"text",text:JSON.stringify({error:s})}]}}};this.getImages=async({presentationId:e,localPath:t})=>{m(`[SlidesService] Starting getImages for presentation: ${e} (localPath: ${t})`);try{let s=F(e)||e,a=await(await this.getSlidesClient()).presentations.get({presentationId:s,fields:"slides(objectId,pageElements(objectId,title,description,image(contentUrl,sourceUrl)))"}),l=await Promise.all((a.data.slides??[]).flatMap((d,p)=>(d.pageElements??[]).filter(u=>u.image).map(async u=>{let f={slideIndex:p+1,slideObjectId:d.objectId,elementObjectId:u.objectId,title:u.title,description:u.description,contentUrl:u.image?.contentUrl,sourceUrl:u.image?.sourceUrl};if(f.contentUrl){let y=`slide_${f.slideIndex}_${u.objectId}.png`,g=ir.join(t,y);try{await this.downloadToLocal(f.contentUrl,g),f.localPath=g}catch(_){m(`[SlidesService] Failed to download image ${u.objectId}: ${_}`),f.downloadError=String(_)}}return f})));return m(`[SlidesService] Finished getImages for presentation: ${s}`),{content:[{type:"text",text:JSON.stringify({images:l})}]}}catch(s){let o=s instanceof Error?s.message:String(s);return m(`[SlidesService] Error during slides.getImages: ${o}`),{content:[{type:"text",text:JSON.stringify({error:o})}]}}};this.create=async({title:e})=>{m(`[SlidesService] Creating presentation: ${e}`);try{let s=await(await this.getSlidesClient()).presentations.create({requestBody:{title:e}}),o={presentationId:s.data.presentationId,title:s.data.title,url:`https://docs.google.com/presentation/d/${s.data.presentationId}/edit`};return m(`[SlidesService] Created presentation: ${o.presentationId}`),this.formatResult(o)}catch(t){return this.formatError("slides.create",t)}};this.addSlide=async({presentationId:e,insertionIndex:t,layoutId:s,predefinedLayout:o,objectId:a})=>{m(`[SlidesService] Adding slide to presentation: ${e}`);try{let l=F(e)||e,d=await this.getSlidesClient(),p={};if(t!==void 0&&(p.insertionIndex=t),a&&(p.objectId=a),s)p.slideLayoutReference={layoutId:s};else if(o){if(!pu.includes(o))throw new Error(`Invalid predefinedLayout "${o}". Expected one of: ${pu.join(", ")}.`);p.slideLayoutReference={predefinedLayout:o}}let f=(await d.presentations.batchUpdate({presentationId:l,requestBody:{requests:[{createSlide:p}]}})).data.replies?.[0]?.createSlide?.objectId;if(!f)throw new Error("createSlide returned no objectId; batchUpdate reply was empty or malformed.");return m(`[SlidesService] Added slide: ${f}`),this.formatResult({presentationId:l,slideObjectId:f})}catch(l){return this.formatError("slides.addSlide",l)}};this.deleteSlide=async({presentationId:e,slideObjectId:t})=>{m(`[SlidesService] Deleting slide ${t} from presentation: ${e}`);try{let s=F(e)||e;return await(await this.getSlidesClient()).presentations.batchUpdate({presentationId:s,requestBody:{requests:[{deleteObject:{objectId:t}}]}}),m(`[SlidesService] Deleted slide: ${t}`),this.formatResult({presentationId:s,deletedSlideObjectId:t})}catch(s){return this.formatError("slides.deleteSlide",s)}};this.duplicateSlide=async({presentationId:e,slideObjectId:t})=>{m(`[SlidesService] Duplicating slide ${t} in presentation: ${e}`);try{let s=F(e)||e,l=(await(await this.getSlidesClient()).presentations.batchUpdate({presentationId:s,requestBody:{requests:[{duplicateObject:{objectId:t}}]}})).data.replies?.[0]?.duplicateObject?.objectId;if(!l)throw new Error("duplicateObject returned no objectId; batchUpdate reply was empty or malformed.");return m(`[SlidesService] Duplicated slide to: ${l}`),this.formatResult({presentationId:s,sourceSlideObjectId:t,newSlideObjectId:l})}catch(s){return this.formatError("slides.duplicateSlide",s)}};this.reorderSlides=async({presentationId:e,slideObjectIds:t,insertionIndex:s})=>{m(`[SlidesService] Reordering slides in presentation: ${e}`);try{let o=F(e)||e;return await(await this.getSlidesClient()).presentations.batchUpdate({presentationId:o,requestBody:{requests:[{updateSlidesPosition:{slideObjectIds:t,insertionIndex:s}}]}}),m(`[SlidesService] Reordered slides in presentation: ${o}`),this.formatResult({presentationId:o,slideObjectIds:t,insertionIndex:s})}catch(o){return this.formatError("slides.reorderSlides",o)}};this.getSpeakerNotes=async({presentationId:e})=>{m(`[SlidesService] Getting speaker notes for presentation: ${e}`);try{let t=F(e)||e,a=((await(await this.getSlidesClient()).presentations.get({presentationId:t,fields:"slides(objectId,slideProperties(notesPage(notesProperties(speakerNotesObjectId),pageElements(objectId,shape(text)))))"})).data.slides??[]).map((l,d)=>{let p=l.slideProperties?.notesPage,u=p?.notesProperties?.speakerNotesObjectId,f="";if(u&&p?.pageElements){let y=p.pageElements.find(g=>g.objectId===u);y?.shape?.text&&(f=this.extractTextFromTextContent(y.shape.text).trim())}return{slideIndex:d,slideObjectId:l.objectId,speakerNotesObjectId:u,notes:f}});return m(`[SlidesService] Retrieved speaker notes for presentation: ${t}`),this.formatResult({presentationId:t,slides:a})}catch(t){return this.formatError("slides.getSpeakerNotes",t)}};this.updateSpeakerNotes=async({presentationId:e,slideObjectId:t,notes:s})=>{m(`[SlidesService] Updating speaker notes for slide ${t} in presentation: ${e}`);try{let o=F(e)||e,a=await this.getSlidesClient(),d=(await a.presentations.get({presentationId:o,fields:"slides(objectId,slideProperties(notesPage(notesProperties(speakerNotesObjectId),pageElements(objectId,shape(text)))))"})).data.slides?.find(g=>g.objectId===t);if(!d)throw new Error(`Slide not found: ${t}`);let p=d.slideProperties?.notesPage?.notesProperties?.speakerNotesObjectId;if(!p)throw new Error(`Speaker notes object not found for slide: ${t}`);let u=[];d.slideProperties?.notesPage?.pageElements?.find(g=>g.objectId===p)?.shape?.text?.textElements?.length&&u.push({deleteText:{objectId:p,textRange:{type:"ALL"}}}),s.length>0&&u.push({insertText:{objectId:p,insertionIndex:0,text:s}});let y=u.length===0;return y?m(`[SlidesService] updateSpeakerNotes is a no-op for slide ${t} (existing notes already match input).`):await a.presentations.batchUpdate({presentationId:o,requestBody:{requests:u}}),m(`[SlidesService] Updated speaker notes for slide: ${t}`),this.formatResult({presentationId:o,slideObjectId:t,speakerNotesObjectId:p,notes:s,noOp:y})}catch(o){return this.formatError("slides.updateSpeakerNotes",o)}};this.replaceAllText=async({presentationId:e,findText:t,replaceText:s,matchCase:o=!0})=>{m(`[SlidesService] Replacing all text in presentation: ${e}`);try{let a=F(e)||e,p=(await(await this.getSlidesClient()).presentations.batchUpdate({presentationId:a,requestBody:{requests:[{replaceAllText:{containsText:{text:t,matchCase:o},replaceText:s}}]}})).data.replies?.[0]?.replaceAllText;if(!p)throw new Error("replaceAllText returned no reply; batchUpdate reply was empty or malformed.");let u=p.occurrencesChanged??0;return m(`[SlidesService] Replaced ${u} occurrences in presentation: ${a}`),this.formatResult({presentationId:a,findText:t,replaceText:s,occurrencesChanged:u})}catch(a){return this.formatError("slides.replaceAllText",a)}};this.insertText=async({presentationId:e,objectId:t,text:s,insertionIndex:o=0})=>{m(`[SlidesService] Inserting text into object ${t} in presentation: ${e}`);try{let a=F(e)||e;return await(await this.getSlidesClient()).presentations.batchUpdate({presentationId:a,requestBody:{requests:[{insertText:{objectId:t,insertionIndex:o,text:s}}]}}),m(`[SlidesService] Inserted text into object ${t} in presentation: ${a}`),this.formatResult({presentationId:a,objectId:t,insertionIndex:o,textLength:s.length})}catch(a){return this.formatError("slides.insertText",a)}};this.deleteText=async({presentationId:e,objectId:t,range:s={type:"ALL"}})=>{m(`[SlidesService] Deleting text from object ${t} in presentation: ${e}`);try{let o=F(e)||e,a=await this.getSlidesClient(),l=this.buildRange(s);return await a.presentations.batchUpdate({presentationId:o,requestBody:{requests:[{deleteText:{objectId:t,textRange:l}}]}}),m(`[SlidesService] Deleted text from object ${t} in presentation: ${o}`),this.formatResult({presentationId:o,objectId:t,textRange:l})}catch(o){return this.formatError("slides.deleteText",o)}};this.addShape=async({presentationId:e,slideObjectId:t,shapeType:s,x:o,y:a,width:l,height:d,objectId:p})=>{m(`[SlidesService] Adding shape to slide ${t} in presentation: ${e}`);try{let u=F(e)||e,f=await this.getSlidesClient(),y={shapeType:s,elementProperties:{pageObjectId:t,size:{width:{magnitude:l,unit:"PT"},height:{magnitude:d,unit:"PT"}},transform:{scaleX:1,scaleY:1,translateX:o,translateY:a,unit:"PT"}}};p&&(y.objectId=p);let _=(await f.presentations.batchUpdate({presentationId:u,requestBody:{requests:[{createShape:y}]}})).data.replies?.[0]?.createShape?.objectId;if(!_)throw new Error("createShape returned no objectId; batchUpdate reply was empty or malformed.");return m(`[SlidesService] Added shape: ${_}`),this.formatResult({presentationId:u,slideObjectId:t,shapeObjectId:_,shapeType:s})}catch(u){return this.formatError("slides.addShape",u)}};this.addImage=async({presentationId:e,slideObjectId:t,imageUrl:s,x:o,y:a,width:l,height:d,objectId:p})=>{m(`[SlidesService] Adding image to slide ${t} in presentation: ${e}`);try{let u=F(e)||e,f=await this.getSlidesClient(),y={url:s,elementProperties:{pageObjectId:t,size:{width:{magnitude:l,unit:"PT"},height:{magnitude:d,unit:"PT"}},transform:{scaleX:1,scaleY:1,translateX:o,translateY:a,unit:"PT"}}};p&&(y.objectId=p);let _=(await f.presentations.batchUpdate({presentationId:u,requestBody:{requests:[{createImage:y}]}})).data.replies?.[0]?.createImage?.objectId;if(!_)throw new Error("createImage returned no objectId; batchUpdate reply was empty or malformed.");return m(`[SlidesService] Added image: ${_}`),this.formatResult({presentationId:u,slideObjectId:t,imageObjectId:_,imageUrl:s})}catch(u){return this.formatError("slides.addImage",u)}};this.addTable=async({presentationId:e,slideObjectId:t,rows:s,columns:o,x:a,y:l,width:d,height:p,objectId:u})=>{m(`[SlidesService] Adding table to slide ${t} in presentation: ${e}`);try{let f=F(e)||e,y=await this.getSlidesClient(),g={rows:s,columns:o,elementProperties:{pageObjectId:t,size:{width:{magnitude:d,unit:"PT"},height:{magnitude:p,unit:"PT"}},transform:{scaleX:1,scaleY:1,translateX:a,translateY:l,unit:"PT"}}};u&&(g.objectId=u);let S=(await y.presentations.batchUpdate({presentationId:f,requestBody:{requests:[{createTable:g}]}})).data.replies?.[0]?.createTable?.objectId;if(!S)throw new Error("createTable returned no objectId; batchUpdate reply was empty or malformed.");return m(`[SlidesService] Added table: ${S}`),this.formatResult({presentationId:f,slideObjectId:t,tableObjectId:S,rows:s,columns:o})}catch(f){return this.formatError("slides.addTable",f)}};this.updateTextStyle=async({presentationId:e,objectId:t,style:s,range:o={type:"ALL"},fields:a})=>{m(`[SlidesService] Updating text style for object ${t} in presentation: ${e}`);try{let l=F(e)||e,d=await this.getSlidesClient(),p=this.parseJsonObject(s,"style",'{"bold": true}'),u=this.buildRange(o);return await d.presentations.batchUpdate({presentationId:l,requestBody:{requests:[{updateTextStyle:{objectId:t,textRange:u,style:p,fields:a}}]}}),m(`[SlidesService] Updated text style for object ${t} in presentation: ${l}`),this.formatResult({presentationId:l,objectId:t,textRange:u,fields:a})}catch(l){return this.formatError("slides.updateTextStyle",l)}};this.updateShapeProperties=async({presentationId:e,objectId:t,shapeProperties:s,fields:o})=>{m(`[SlidesService] Updating shape properties for object ${t} in presentation: ${e}`);try{let a=F(e)||e,l=await this.getSlidesClient(),d=this.parseJsonObject(s,"shapeProperties",'{"shapeBackgroundFill": {...}}');return await l.presentations.batchUpdate({presentationId:a,requestBody:{requests:[{updateShapeProperties:{objectId:t,shapeProperties:d,fields:o}}]}}),m(`[SlidesService] Updated shape properties for object ${t} in presentation: ${a}`),this.formatResult({presentationId:a,objectId:t,fields:o})}catch(a){return this.formatError("slides.updateShapeProperties",a)}};this.getSlideThumbnail=async({presentationId:e,slideObjectId:t,localPath:s})=>{m(`[SlidesService] Starting getSlideThumbnail for presentation: ${e}, slide: ${t} (localPath: ${s})`);try{let o=F(e)||e,d={...(await(await this.getSlidesClient()).presentations.pages.getThumbnail({presentationId:o,pageObjectId:t})).data};if(d.contentUrl)try{await this.downloadToLocal(d.contentUrl,s),d.localPath=s}catch(p){m(`[SlidesService] Failed to download thumbnail for slide ${t}: ${p}`),d.downloadError=String(p)}return m(`[SlidesService] Finished getSlideThumbnail for slide: ${t}`),{content:[{type:"text",text:JSON.stringify(d)}]}}catch(o){let a=o instanceof Error?o.message:String(o);return m(`[SlidesService] Error during slides.getSlideThumbnail: ${a}`),{content:[{type:"text",text:JSON.stringify({error:a})}]}}}}async getSlidesClient(){let e=await this.authManager.getAuthenticatedClient(),t={...W,auth:e};return _h.slides({version:"v1",...t})}extractTextFromTextContent(e){let t="";return e.textElements&&e.textElements.forEach(s=>{s.textRun&&s.textRun.content?t+=s.textRun.content:s.paragraphMarker&&(t+=`
78
- `)}),t}async downloadToLocal(e,t){if(m(`[SlidesService] Downloading from ${e} to ${t}`),!ir.isAbsolute(t))throw new Error("localPath must be an absolute path.");await fs.mkdir(ir.dirname(t),{recursive:!0});let s=await fu({url:e,responseType:"arraybuffer",...W});return await fs.writeFile(t,Buffer.from(s.data)),m(`[SlidesService] Downloaded successfully to ${t}`),t}parseJsonObject(e,t,s){let o;try{o=JSON.parse(e)}catch(a){let l=a instanceof Error?a.message:String(a);throw new Error(`Invalid JSON for ${t} parameter: ${l}. Expected a JSON string like '${s}'.`)}if(typeof o!="object"||o===null||Array.isArray(o)){let a=o===null?"null":Array.isArray(o)?"array":typeof o;throw new Error(`Invalid ${t} parameter: expected a JSON object, got ${a}.`)}return o}buildRange(e){if(!mu.includes(e.type))throw new Error(`Invalid range type "${e.type}". Expected one of: ${mu.join(", ")}.`);if(e.type==="FIXED_RANGE"){if(e.startIndex===void 0||e.endIndex===void 0)throw new Error("FIXED_RANGE requires both startIndex and endIndex.");return{type:e.type,startIndex:e.startIndex,endIndex:e.endIndex}}if(e.type==="FROM_START_INDEX"){if(e.startIndex===void 0)throw new Error("FROM_START_INDEX requires startIndex.");return{type:e.type,startIndex:e.startIndex}}return{type:e.type}}formatError(e,t){let s=t instanceof Error?t.message:String(t);return m(`[SlidesService] Error during ${e}: ${s}`),{isError:!0,content:[{type:"text",text:JSON.stringify({error:s})}]}}formatResult(e){return{content:[{type:"text",text:JSON.stringify(e)}]}}};var ps=["getText","getMetadata","getImages","create","addSlide","deleteSlide","duplicateSlide","reorderSlides","getSpeakerNotes","updateSpeakerNotes","replaceAllText","insertText","deleteText","addShape","addImage","addTable","updateTextStyle","updateShapeProperties","getSlideThumbnail"],hu=z(ds,ps,{bounds:Qa});import{google as Th}from"googleapis";var ms=class{constructor(e){this.authManager=e;this.listTaskLists=async(e={})=>{m("Listing task lists");try{let s=await(await this.getTasksClient()).tasklists.list({...e.maxResults!==void 0&&{maxResults:e.maxResults},...e.pageToken!==void 0&&{pageToken:e.pageToken}});return{content:[{type:"text",text:JSON.stringify(s.data)}]}}catch(t){let s=t instanceof Error?t.message:String(t);return m(`Error during tasks.listLists: ${s}`),{content:[{type:"text",text:JSON.stringify({error:s})}]}}};this.listTasks=async e=>{m(`Listing tasks in list: ${e.taskListId}`);try{let s=await(await this.getTasksClient()).tasks.list({tasklist:e.taskListId,...e.showCompleted!==void 0&&{showCompleted:e.showCompleted},...e.showDeleted!==void 0&&{showDeleted:e.showDeleted},...e.showHidden!==void 0&&{showHidden:e.showHidden},...e.showAssigned!==void 0&&{showAssigned:e.showAssigned},...e.maxResults!==void 0&&{maxResults:e.maxResults},...e.pageToken!==void 0&&{pageToken:e.pageToken},...e.dueMin!==void 0&&{dueMin:e.dueMin},...e.dueMax!==void 0&&{dueMax:e.dueMax}});return{content:[{type:"text",text:JSON.stringify(s.data)}]}}catch(t){let s=t instanceof Error?t.message:String(t);return m(`Error during tasks.list: ${s}`),{content:[{type:"text",text:JSON.stringify({error:s})}]}}};this.createTask=async e=>{m(`Creating task in list: ${e.taskListId}`);try{let t=await this.getTasksClient(),s={title:e.title,...e.notes!==void 0&&{notes:e.notes},...e.due!==void 0&&{due:e.due}},o=await t.tasks.insert({tasklist:e.taskListId,requestBody:s});return m(`Successfully created task: ${o.data.id}`),{content:[{type:"text",text:JSON.stringify(o.data)}]}}catch(t){let s=t instanceof Error?t.message:String(t);return m(`Error during tasks.create: ${s}`),{content:[{type:"text",text:JSON.stringify({error:s})}]}}};this.updateTask=async e=>{m(`Updating task ${e.taskId} in list: ${e.taskListId}`);try{let t=await this.getTasksClient(),s={...e.title!==void 0&&{title:e.title},...e.notes!==void 0&&{notes:e.notes},...e.status!==void 0&&{status:e.status},...e.due!==void 0&&{due:e.due}},o=await t.tasks.patch({tasklist:e.taskListId,task:e.taskId,requestBody:s});return m(`Successfully updated task: ${e.taskId}`),{content:[{type:"text",text:JSON.stringify(o.data)}]}}catch(t){let s=t instanceof Error?t.message:String(t);return m(`Error during tasks.update: ${s}`),{content:[{type:"text",text:JSON.stringify({error:s})}]}}};this.completeTask=async e=>this.updateTask({taskListId:e.taskListId,taskId:e.taskId,status:"completed"});this.deleteTask=async e=>{m(`Deleting task ${e.taskId} from list: ${e.taskListId}`);try{return await(await this.getTasksClient()).tasks.delete({tasklist:e.taskListId,task:e.taskId}),m(`Successfully deleted task: ${e.taskId}`),{content:[{type:"text",text:JSON.stringify({message:`Task ${e.taskId} deleted successfully from list ${e.taskListId}.`})}]}}catch(t){let s=t instanceof Error?t.message:String(t);return m(`Error during tasks.delete: ${s}`),{content:[{type:"text",text:JSON.stringify({error:s})}]}}}}async getTasksClient(){let e=await this.authManager.getAuthenticatedClient(),t={...W,auth:e};return Th.tasks({version:"v1",...t})}};var hs=["listTaskLists","listTasks","createTask","updateTask","completeTask","deleteTask"],gu=z(ms,hs,{pagination:{listTaskLists:"maxResults",listTasks:"maxResults"},bounds:nc});var gs=class{constructor(){this.getCurrentDate=async()=>(m("getCurrentDate called"),this.handleErrors(async()=>{let{now:e,timeZone:t}=this.getTimeContext();return{utc:e.toISOString().slice(0,10),local:e.toLocaleDateString("en-CA",{timeZone:t}),timeZone:t}}));this.getCurrentTime=async()=>(m("getCurrentTime called"),this.handleErrors(async()=>{let{now:e,timeZone:t}=this.getTimeContext();return{utc:e.toISOString().slice(11,19),local:e.toLocaleTimeString("en-GB",{hour12:!1,timeZone:t}),timeZone:t}}));this.getTimeZone=async()=>(m("getTimeZone called"),this.handleErrors(async()=>({timeZone:Intl.DateTimeFormat().resolvedOptions().timeZone})));m("TimeService initialized.")}async handleErrors(e){try{let t=await e();return{content:[{type:"text",text:JSON.stringify(t)}]}}catch(t){let s=t instanceof Error?t.message:String(t);return m(`Error in TimeService: ${s}`),{content:[{type:"text",text:JSON.stringify({error:s})}]}}}getTimeContext(){return{now:new Date,timeZone:Intl.DateTimeFormat().resolvedOptions().timeZone}}};var Zo=["getCurrentDate","getCurrentTime","getTimeZone"],yu=z(gs,Zo,{noAuth:!0});var ve=[{name:"docs",description:`Google Docs operations.
77
+ `}),m(`[SlidesService] Finished getText for presentation: ${t}`),{content:[{type:"text",text:a.trim()}]}}catch(t){let o=t instanceof Error?t.message:String(t);return m(`[SlidesService] Error during slides.getText: ${o}`),{content:[{type:"text",text:JSON.stringify({error:o})}]}}};this.getMetadata=async({presentationId:e})=>{m(`[SlidesService] Starting getMetadata for presentation: ${e}`);try{let t=F(e)||e,s=await(await this.getSlidesClient()).presentations.get({presentationId:t,fields:"presentationId,title,slides(objectId),pageSize,notesMaster,masters,layouts"}),a={presentationId:s.data.presentationId,title:s.data.title,slideCount:s.data.slides?.length||0,slides:s.data.slides?.map(({objectId:l})=>({objectId:l}))??[],pageSize:s.data.pageSize,hasMasters:!!s.data.masters?.length,hasLayouts:!!s.data.layouts?.length,hasNotesMaster:!!s.data.notesMaster};return m(`[SlidesService] Finished getMetadata for presentation: ${t}`),{content:[{type:"text",text:JSON.stringify(a)}]}}catch(t){let o=t instanceof Error?t.message:String(t);return m(`[SlidesService] Error during slides.getMetadata: ${o}`),{content:[{type:"text",text:JSON.stringify({error:o})}]}}};this.getImages=async({presentationId:e,localPath:t})=>{m(`[SlidesService] Starting getImages for presentation: ${e} (localPath: ${t})`);try{let o=F(e)||e,a=await(await this.getSlidesClient()).presentations.get({presentationId:o,fields:"slides(objectId,pageElements(objectId,title,description,image(contentUrl,sourceUrl)))"}),l=await Promise.all((a.data.slides??[]).flatMap((d,p)=>(d.pageElements??[]).filter(u=>u.image).map(async u=>{let f={slideIndex:p+1,slideObjectId:d.objectId,elementObjectId:u.objectId,title:u.title,description:u.description,contentUrl:u.image?.contentUrl,sourceUrl:u.image?.sourceUrl};if(f.contentUrl){let y=`slide_${f.slideIndex}_${u.objectId}.png`,g=ir.join(t,y);try{await this.downloadToLocal(f.contentUrl,g),f.localPath=g}catch(_){m(`[SlidesService] Failed to download image ${u.objectId}: ${_}`),f.downloadError=String(_)}}return f})));return m(`[SlidesService] Finished getImages for presentation: ${o}`),{content:[{type:"text",text:JSON.stringify({images:l})}]}}catch(o){let s=o instanceof Error?o.message:String(o);return m(`[SlidesService] Error during slides.getImages: ${s}`),{content:[{type:"text",text:JSON.stringify({error:s})}]}}};this.create=async({title:e})=>{m(`[SlidesService] Creating presentation: ${e}`);try{let o=await(await this.getSlidesClient()).presentations.create({requestBody:{title:e}}),s={presentationId:o.data.presentationId,title:o.data.title,url:`https://docs.google.com/presentation/d/${o.data.presentationId}/edit`};return m(`[SlidesService] Created presentation: ${s.presentationId}`),this.formatResult(s)}catch(t){return this.formatError("slides.create",t)}};this.addSlide=async({presentationId:e,insertionIndex:t,layoutId:o,predefinedLayout:s,objectId:a})=>{m(`[SlidesService] Adding slide to presentation: ${e}`);try{let l=F(e)||e,d=await this.getSlidesClient(),p={};if(t!==void 0&&(p.insertionIndex=t),a&&(p.objectId=a),o)p.slideLayoutReference={layoutId:o};else if(s){if(!pu.includes(s))throw new Error(`Invalid predefinedLayout "${s}". Expected one of: ${pu.join(", ")}.`);p.slideLayoutReference={predefinedLayout:s}}let f=(await d.presentations.batchUpdate({presentationId:l,requestBody:{requests:[{createSlide:p}]}})).data.replies?.[0]?.createSlide?.objectId;if(!f)throw new Error("createSlide returned no objectId; batchUpdate reply was empty or malformed.");return m(`[SlidesService] Added slide: ${f}`),this.formatResult({presentationId:l,slideObjectId:f})}catch(l){return this.formatError("slides.addSlide",l)}};this.deleteSlide=async({presentationId:e,slideObjectId:t})=>{m(`[SlidesService] Deleting slide ${t} from presentation: ${e}`);try{let o=F(e)||e;return await(await this.getSlidesClient()).presentations.batchUpdate({presentationId:o,requestBody:{requests:[{deleteObject:{objectId:t}}]}}),m(`[SlidesService] Deleted slide: ${t}`),this.formatResult({presentationId:o,deletedSlideObjectId:t})}catch(o){return this.formatError("slides.deleteSlide",o)}};this.duplicateSlide=async({presentationId:e,slideObjectId:t})=>{m(`[SlidesService] Duplicating slide ${t} in presentation: ${e}`);try{let o=F(e)||e,l=(await(await this.getSlidesClient()).presentations.batchUpdate({presentationId:o,requestBody:{requests:[{duplicateObject:{objectId:t}}]}})).data.replies?.[0]?.duplicateObject?.objectId;if(!l)throw new Error("duplicateObject returned no objectId; batchUpdate reply was empty or malformed.");return m(`[SlidesService] Duplicated slide to: ${l}`),this.formatResult({presentationId:o,sourceSlideObjectId:t,newSlideObjectId:l})}catch(o){return this.formatError("slides.duplicateSlide",o)}};this.reorderSlides=async({presentationId:e,slideObjectIds:t,insertionIndex:o})=>{m(`[SlidesService] Reordering slides in presentation: ${e}`);try{let s=F(e)||e;return await(await this.getSlidesClient()).presentations.batchUpdate({presentationId:s,requestBody:{requests:[{updateSlidesPosition:{slideObjectIds:t,insertionIndex:o}}]}}),m(`[SlidesService] Reordered slides in presentation: ${s}`),this.formatResult({presentationId:s,slideObjectIds:t,insertionIndex:o})}catch(s){return this.formatError("slides.reorderSlides",s)}};this.getSpeakerNotes=async({presentationId:e})=>{m(`[SlidesService] Getting speaker notes for presentation: ${e}`);try{let t=F(e)||e,a=((await(await this.getSlidesClient()).presentations.get({presentationId:t,fields:"slides(objectId,slideProperties(notesPage(notesProperties(speakerNotesObjectId),pageElements(objectId,shape(text)))))"})).data.slides??[]).map((l,d)=>{let p=l.slideProperties?.notesPage,u=p?.notesProperties?.speakerNotesObjectId,f="";if(u&&p?.pageElements){let y=p.pageElements.find(g=>g.objectId===u);y?.shape?.text&&(f=this.extractTextFromTextContent(y.shape.text).trim())}return{slideIndex:d,slideObjectId:l.objectId,speakerNotesObjectId:u,notes:f}});return m(`[SlidesService] Retrieved speaker notes for presentation: ${t}`),this.formatResult({presentationId:t,slides:a})}catch(t){return this.formatError("slides.getSpeakerNotes",t)}};this.updateSpeakerNotes=async({presentationId:e,slideObjectId:t,notes:o})=>{m(`[SlidesService] Updating speaker notes for slide ${t} in presentation: ${e}`);try{let s=F(e)||e,a=await this.getSlidesClient(),d=(await a.presentations.get({presentationId:s,fields:"slides(objectId,slideProperties(notesPage(notesProperties(speakerNotesObjectId),pageElements(objectId,shape(text)))))"})).data.slides?.find(g=>g.objectId===t);if(!d)throw new Error(`Slide not found: ${t}`);let p=d.slideProperties?.notesPage?.notesProperties?.speakerNotesObjectId;if(!p)throw new Error(`Speaker notes object not found for slide: ${t}`);let u=[];d.slideProperties?.notesPage?.pageElements?.find(g=>g.objectId===p)?.shape?.text?.textElements?.length&&u.push({deleteText:{objectId:p,textRange:{type:"ALL"}}}),o.length>0&&u.push({insertText:{objectId:p,insertionIndex:0,text:o}});let y=u.length===0;return y?m(`[SlidesService] updateSpeakerNotes is a no-op for slide ${t} (existing notes already match input).`):await a.presentations.batchUpdate({presentationId:s,requestBody:{requests:u}}),m(`[SlidesService] Updated speaker notes for slide: ${t}`),this.formatResult({presentationId:s,slideObjectId:t,speakerNotesObjectId:p,notes:o,noOp:y})}catch(s){return this.formatError("slides.updateSpeakerNotes",s)}};this.replaceAllText=async({presentationId:e,findText:t,replaceText:o,matchCase:s=!0})=>{m(`[SlidesService] Replacing all text in presentation: ${e}`);try{let a=F(e)||e,p=(await(await this.getSlidesClient()).presentations.batchUpdate({presentationId:a,requestBody:{requests:[{replaceAllText:{containsText:{text:t,matchCase:s},replaceText:o}}]}})).data.replies?.[0]?.replaceAllText;if(!p)throw new Error("replaceAllText returned no reply; batchUpdate reply was empty or malformed.");let u=p.occurrencesChanged??0;return m(`[SlidesService] Replaced ${u} occurrences in presentation: ${a}`),this.formatResult({presentationId:a,findText:t,replaceText:o,occurrencesChanged:u})}catch(a){return this.formatError("slides.replaceAllText",a)}};this.insertText=async({presentationId:e,objectId:t,text:o,insertionIndex:s=0})=>{m(`[SlidesService] Inserting text into object ${t} in presentation: ${e}`);try{let a=F(e)||e;return await(await this.getSlidesClient()).presentations.batchUpdate({presentationId:a,requestBody:{requests:[{insertText:{objectId:t,insertionIndex:s,text:o}}]}}),m(`[SlidesService] Inserted text into object ${t} in presentation: ${a}`),this.formatResult({presentationId:a,objectId:t,insertionIndex:s,textLength:o.length})}catch(a){return this.formatError("slides.insertText",a)}};this.deleteText=async({presentationId:e,objectId:t,range:o={type:"ALL"}})=>{m(`[SlidesService] Deleting text from object ${t} in presentation: ${e}`);try{let s=F(e)||e,a=await this.getSlidesClient(),l=this.buildRange(o);return await a.presentations.batchUpdate({presentationId:s,requestBody:{requests:[{deleteText:{objectId:t,textRange:l}}]}}),m(`[SlidesService] Deleted text from object ${t} in presentation: ${s}`),this.formatResult({presentationId:s,objectId:t,textRange:l})}catch(s){return this.formatError("slides.deleteText",s)}};this.addShape=async({presentationId:e,slideObjectId:t,shapeType:o,x:s,y:a,width:l,height:d,objectId:p})=>{m(`[SlidesService] Adding shape to slide ${t} in presentation: ${e}`);try{let u=F(e)||e,f=await this.getSlidesClient(),y={shapeType:o,elementProperties:{pageObjectId:t,size:{width:{magnitude:l,unit:"PT"},height:{magnitude:d,unit:"PT"}},transform:{scaleX:1,scaleY:1,translateX:s,translateY:a,unit:"PT"}}};p&&(y.objectId=p);let _=(await f.presentations.batchUpdate({presentationId:u,requestBody:{requests:[{createShape:y}]}})).data.replies?.[0]?.createShape?.objectId;if(!_)throw new Error("createShape returned no objectId; batchUpdate reply was empty or malformed.");return m(`[SlidesService] Added shape: ${_}`),this.formatResult({presentationId:u,slideObjectId:t,shapeObjectId:_,shapeType:o})}catch(u){return this.formatError("slides.addShape",u)}};this.addImage=async({presentationId:e,slideObjectId:t,imageUrl:o,x:s,y:a,width:l,height:d,objectId:p})=>{m(`[SlidesService] Adding image to slide ${t} in presentation: ${e}`);try{let u=F(e)||e,f=await this.getSlidesClient(),y={url:o,elementProperties:{pageObjectId:t,size:{width:{magnitude:l,unit:"PT"},height:{magnitude:d,unit:"PT"}},transform:{scaleX:1,scaleY:1,translateX:s,translateY:a,unit:"PT"}}};p&&(y.objectId=p);let _=(await f.presentations.batchUpdate({presentationId:u,requestBody:{requests:[{createImage:y}]}})).data.replies?.[0]?.createImage?.objectId;if(!_)throw new Error("createImage returned no objectId; batchUpdate reply was empty or malformed.");return m(`[SlidesService] Added image: ${_}`),this.formatResult({presentationId:u,slideObjectId:t,imageObjectId:_,imageUrl:o})}catch(u){return this.formatError("slides.addImage",u)}};this.addTable=async({presentationId:e,slideObjectId:t,rows:o,columns:s,x:a,y:l,width:d,height:p,objectId:u})=>{m(`[SlidesService] Adding table to slide ${t} in presentation: ${e}`);try{let f=F(e)||e,y=await this.getSlidesClient(),g={rows:o,columns:s,elementProperties:{pageObjectId:t,size:{width:{magnitude:d,unit:"PT"},height:{magnitude:p,unit:"PT"}},transform:{scaleX:1,scaleY:1,translateX:a,translateY:l,unit:"PT"}}};u&&(g.objectId=u);let S=(await y.presentations.batchUpdate({presentationId:f,requestBody:{requests:[{createTable:g}]}})).data.replies?.[0]?.createTable?.objectId;if(!S)throw new Error("createTable returned no objectId; batchUpdate reply was empty or malformed.");return m(`[SlidesService] Added table: ${S}`),this.formatResult({presentationId:f,slideObjectId:t,tableObjectId:S,rows:o,columns:s})}catch(f){return this.formatError("slides.addTable",f)}};this.updateTextStyle=async({presentationId:e,objectId:t,style:o,range:s={type:"ALL"},fields:a})=>{m(`[SlidesService] Updating text style for object ${t} in presentation: ${e}`);try{let l=F(e)||e,d=await this.getSlidesClient(),p=this.parseJsonObject(o,"style",'{"bold": true}'),u=this.buildRange(s);return await d.presentations.batchUpdate({presentationId:l,requestBody:{requests:[{updateTextStyle:{objectId:t,textRange:u,style:p,fields:a}}]}}),m(`[SlidesService] Updated text style for object ${t} in presentation: ${l}`),this.formatResult({presentationId:l,objectId:t,textRange:u,fields:a})}catch(l){return this.formatError("slides.updateTextStyle",l)}};this.updateShapeProperties=async({presentationId:e,objectId:t,shapeProperties:o,fields:s})=>{m(`[SlidesService] Updating shape properties for object ${t} in presentation: ${e}`);try{let a=F(e)||e,l=await this.getSlidesClient(),d=this.parseJsonObject(o,"shapeProperties",'{"shapeBackgroundFill": {...}}');return await l.presentations.batchUpdate({presentationId:a,requestBody:{requests:[{updateShapeProperties:{objectId:t,shapeProperties:d,fields:s}}]}}),m(`[SlidesService] Updated shape properties for object ${t} in presentation: ${a}`),this.formatResult({presentationId:a,objectId:t,fields:s})}catch(a){return this.formatError("slides.updateShapeProperties",a)}};this.getSlideThumbnail=async({presentationId:e,slideObjectId:t,localPath:o})=>{m(`[SlidesService] Starting getSlideThumbnail for presentation: ${e}, slide: ${t} (localPath: ${o})`);try{let s=F(e)||e,d={...(await(await this.getSlidesClient()).presentations.pages.getThumbnail({presentationId:s,pageObjectId:t})).data};if(d.contentUrl)try{await this.downloadToLocal(d.contentUrl,o),d.localPath=o}catch(p){m(`[SlidesService] Failed to download thumbnail for slide ${t}: ${p}`),d.downloadError=String(p)}return m(`[SlidesService] Finished getSlideThumbnail for slide: ${t}`),{content:[{type:"text",text:JSON.stringify(d)}]}}catch(s){let a=s instanceof Error?s.message:String(s);return m(`[SlidesService] Error during slides.getSlideThumbnail: ${a}`),{content:[{type:"text",text:JSON.stringify({error:a})}]}}}}async getSlidesClient(){let e=await this.authManager.getAuthenticatedClient(),t={...W,auth:e};return Th.slides({version:"v1",...t})}extractTextFromTextContent(e){let t="";return e.textElements&&e.textElements.forEach(o=>{o.textRun&&o.textRun.content?t+=o.textRun.content:o.paragraphMarker&&(t+=`
78
+ `)}),t}async downloadToLocal(e,t){if(m(`[SlidesService] Downloading from ${e} to ${t}`),!ir.isAbsolute(t))throw new Error("localPath must be an absolute path.");await po.mkdir(ir.dirname(t),{recursive:!0});let o=await fu({url:e,responseType:"arraybuffer",...W});return await po.writeFile(t,Buffer.from(o.data)),m(`[SlidesService] Downloaded successfully to ${t}`),t}parseJsonObject(e,t,o){let s;try{s=JSON.parse(e)}catch(a){let l=a instanceof Error?a.message:String(a);throw new Error(`Invalid JSON for ${t} parameter: ${l}. Expected a JSON string like '${o}'.`)}if(typeof s!="object"||s===null||Array.isArray(s)){let a=s===null?"null":Array.isArray(s)?"array":typeof s;throw new Error(`Invalid ${t} parameter: expected a JSON object, got ${a}.`)}return s}buildRange(e){if(!mu.includes(e.type))throw new Error(`Invalid range type "${e.type}". Expected one of: ${mu.join(", ")}.`);if(e.type==="FIXED_RANGE"){if(e.startIndex===void 0||e.endIndex===void 0)throw new Error("FIXED_RANGE requires both startIndex and endIndex.");return{type:e.type,startIndex:e.startIndex,endIndex:e.endIndex}}if(e.type==="FROM_START_INDEX"){if(e.startIndex===void 0)throw new Error("FROM_START_INDEX requires startIndex.");return{type:e.type,startIndex:e.startIndex}}return{type:e.type}}formatError(e,t){let o=t instanceof Error?t.message:String(t);return m(`[SlidesService] Error during ${e}: ${o}`),{isError:!0,content:[{type:"text",text:JSON.stringify({error:o})}]}}formatResult(e){return{content:[{type:"text",text:JSON.stringify(e)}]}}};var mo=["getText","getMetadata","getImages","create","addSlide","deleteSlide","duplicateSlide","reorderSlides","getSpeakerNotes","updateSpeakerNotes","replaceAllText","insertText","deleteText","addShape","addImage","addTable","updateTextStyle","updateShapeProperties","getSlideThumbnail"],hu=z(fo,mo,{bounds:Qa});import{google as Rh}from"googleapis";var ho=class{constructor(e){this.authManager=e;this.listTaskLists=async(e={})=>{m("Listing task lists");try{let o=await(await this.getTasksClient()).tasklists.list({...e.maxResults!==void 0&&{maxResults:e.maxResults},...e.pageToken!==void 0&&{pageToken:e.pageToken}});return{content:[{type:"text",text:JSON.stringify(o.data)}]}}catch(t){let o=t instanceof Error?t.message:String(t);return m(`Error during tasks.listLists: ${o}`),{content:[{type:"text",text:JSON.stringify({error:o})}]}}};this.listTasks=async e=>{m(`Listing tasks in list: ${e.taskListId}`);try{let o=await(await this.getTasksClient()).tasks.list({tasklist:e.taskListId,...e.showCompleted!==void 0&&{showCompleted:e.showCompleted},...e.showDeleted!==void 0&&{showDeleted:e.showDeleted},...e.showHidden!==void 0&&{showHidden:e.showHidden},...e.showAssigned!==void 0&&{showAssigned:e.showAssigned},...e.maxResults!==void 0&&{maxResults:e.maxResults},...e.pageToken!==void 0&&{pageToken:e.pageToken},...e.dueMin!==void 0&&{dueMin:e.dueMin},...e.dueMax!==void 0&&{dueMax:e.dueMax}});return{content:[{type:"text",text:JSON.stringify(o.data)}]}}catch(t){let o=t instanceof Error?t.message:String(t);return m(`Error during tasks.list: ${o}`),{content:[{type:"text",text:JSON.stringify({error:o})}]}}};this.createTask=async e=>{m(`Creating task in list: ${e.taskListId}`);try{let t=await this.getTasksClient(),o={title:e.title,...e.notes!==void 0&&{notes:e.notes},...e.due!==void 0&&{due:e.due}},s=await t.tasks.insert({tasklist:e.taskListId,requestBody:o});return m(`Successfully created task: ${s.data.id}`),{content:[{type:"text",text:JSON.stringify(s.data)}]}}catch(t){let o=t instanceof Error?t.message:String(t);return m(`Error during tasks.create: ${o}`),{content:[{type:"text",text:JSON.stringify({error:o})}]}}};this.updateTask=async e=>{m(`Updating task ${e.taskId} in list: ${e.taskListId}`);try{let t=await this.getTasksClient(),o={...e.title!==void 0&&{title:e.title},...e.notes!==void 0&&{notes:e.notes},...e.status!==void 0&&{status:e.status},...e.due!==void 0&&{due:e.due}},s=await t.tasks.patch({tasklist:e.taskListId,task:e.taskId,requestBody:o});return m(`Successfully updated task: ${e.taskId}`),{content:[{type:"text",text:JSON.stringify(s.data)}]}}catch(t){let o=t instanceof Error?t.message:String(t);return m(`Error during tasks.update: ${o}`),{content:[{type:"text",text:JSON.stringify({error:o})}]}}};this.completeTask=async e=>this.updateTask({taskListId:e.taskListId,taskId:e.taskId,status:"completed"});this.deleteTask=async e=>{m(`Deleting task ${e.taskId} from list: ${e.taskListId}`);try{return await(await this.getTasksClient()).tasks.delete({tasklist:e.taskListId,task:e.taskId}),m(`Successfully deleted task: ${e.taskId}`),{content:[{type:"text",text:JSON.stringify({message:`Task ${e.taskId} deleted successfully from list ${e.taskListId}.`})}]}}catch(t){let o=t instanceof Error?t.message:String(t);return m(`Error during tasks.delete: ${o}`),{content:[{type:"text",text:JSON.stringify({error:o})}]}}}}async getTasksClient(){let e=await this.authManager.getAuthenticatedClient(),t={...W,auth:e};return Rh.tasks({version:"v1",...t})}};var go=["listTaskLists","listTasks","createTask","updateTask","completeTask","deleteTask"],gu=z(ho,go,{pagination:{listTaskLists:"maxResults",listTasks:"maxResults"},bounds:nc});var yo=class{constructor(){this.getCurrentDate=async()=>(m("getCurrentDate called"),this.handleErrors(async()=>{let{now:e,timeZone:t}=this.getTimeContext();return{utc:e.toISOString().slice(0,10),local:e.toLocaleDateString("en-CA",{timeZone:t}),timeZone:t}}));this.getCurrentTime=async()=>(m("getCurrentTime called"),this.handleErrors(async()=>{let{now:e,timeZone:t}=this.getTimeContext();return{utc:e.toISOString().slice(11,19),local:e.toLocaleTimeString("en-GB",{hour12:!1,timeZone:t}),timeZone:t}}));this.getTimeZone=async()=>(m("getTimeZone called"),this.handleErrors(async()=>({timeZone:Intl.DateTimeFormat().resolvedOptions().timeZone})));m("TimeService initialized.")}async handleErrors(e){try{let t=await e();return{content:[{type:"text",text:JSON.stringify(t)}]}}catch(t){let o=t instanceof Error?t.message:String(t);return m(`Error in TimeService: ${o}`),{content:[{type:"text",text:JSON.stringify({error:o})}]}}}getTimeContext(){return{now:new Date,timeZone:Intl.DateTimeFormat().resolvedOptions().timeZone}}};var Zs=["getCurrentDate","getCurrentTime","getTimeZone"],yu=z(yo,Zs,{noAuth:!0});var ve=[{name:"docs",description:`Google Docs operations.
79
79
 
80
80
  Actions (required params -> optional):
81
81
  - getText (documentId -> tabId, limit, preview)
@@ -87,26 +87,26 @@ Actions (required params -> optional):
87
87
 
88
88
  getText defaults to 20,000 characters, accepts limit 1-100,000, and marks truncated output explicitly. preview defaults to 2,000 characters unless limit is provided. getSuggestions is bounded separately: 20,000 characters and 100 suggestions by default (max_chars 1-100,000, full:true for every entry). These bounds limit response size without changing document authorization.
89
89
 
90
- account = email of the Google account to use (default: primary).`,actions:So,inputProps:{documentId:{type:"string",description:"Google Doc ID or URL"},title:{type:"string",description:"Document title (for create)"},content:{type:"string",description:"Initial document content (for create)"},text:{type:"string",description:"Text to insert (for writeText)"},position:{type:"string",description:'Insert position for writeText: "beginning", "end" (default), or a positive integer index'},tabId:{type:"string",description:"Tab ID to target (optional, for multi-tab documents)"},limit:{type:"number",description:"Maximum Docs text characters for getText (1-100000; default 20000)"},preview:{type:"boolean",description:"Use a 2000-character getText preview unless limit is provided"},max_chars:{type:"number",description:"Maximum characters returned by getSuggestions (1-100000; default 20000)"},full:{type:"boolean",description:"Return every getSuggestions entry, bypassing the default 20000-character and 100-item bounds"},replaceText:{type:"string",description:"Replacement text (for replaceText)"},formats:{type:"array",items:{type:"object",properties:{startIndex:{type:"number"},endIndex:{type:"number"},style:{type:"string"},url:{type:"string"}},required:["startIndex","endIndex","style"]},description:"Formatting operations to apply (for formatText)"}},run:_c},{name:"time",description:`Local date/time/timezone helpers (no Google account needed).
90
+ account = email of the Google account to use (default: primary).`,actions:Ss,inputProps:{documentId:{type:"string",description:"Google Doc ID or URL"},title:{type:"string",description:"Document title (for create)"},content:{type:"string",description:"Initial document content (for create)"},text:{type:"string",description:"Text to insert (for writeText)"},position:{type:"string",description:'Insert position for writeText: "beginning", "end" (default), or a positive integer index'},tabId:{type:"string",description:"Tab ID to target (optional, for multi-tab documents)"},limit:{type:"number",description:"Maximum Docs text characters for getText (1-100000; default 20000)"},preview:{type:"boolean",description:"Use a 2000-character getText preview unless limit is provided"},max_chars:{type:"number",description:"Maximum characters returned by getSuggestions (1-100000; default 20000)"},full:{type:"boolean",description:"Return every getSuggestions entry, bypassing the default 20000-character and 100-item bounds"},replaceText:{type:"string",description:"Replacement text (for replaceText)"},formats:{type:"array",items:{type:"object",properties:{startIndex:{type:"number"},endIndex:{type:"number"},style:{type:"string"},url:{type:"string"}},required:["startIndex","endIndex","style"]},description:"Formatting operations to apply (for formatText)"}},run:_c},{name:"time",description:`Local date/time/timezone helpers (no Google account needed).
91
91
 
92
92
  Actions:
93
93
  - getCurrentDate
94
94
  - getCurrentTime
95
- - getTimeZone`,actions:Zo,inputProps:{},run:yu},{name:"drive",description:`Drive operations. See the action enum for operations available in this transport.
95
+ - getTimeZone`,actions:Zs,inputProps:{},run:yu},{name:"drive",description:`Drive operations. See the action enum for operations available in this transport.
96
96
 
97
- search, getComments and findFolder are bounded: 20,000 characters by default (max_chars 1-100,000, full:true for the complete payload). search and getComments page with pageSize and pageToken; findFolder caps at 50 name matches. Truncated output names its true size and how to fetch the rest. account = email of the Google account to use (default: primary).`,actions:_o,localOnlyActions:["downloadFile"],localOnlyInputProps:["localPath"],inputProps:{fileId:{type:"string"},folderId:{type:"string"},folderName:{type:"string"},query:{type:"string"},name:{type:"string"},newName:{type:"string"},parentId:{type:"string"},destinationFolderId:{type:"string"},pageSize:{type:"number",description:"Maximum search results per page (default 10)"},pageToken:{type:"string",description:"Continuation token from a previous search page"},corpus:{type:"string",enum:["user","domain"],description:"Drive search corpus"},unreadOnly:{type:"boolean",description:"Restrict search to unread files where supported"},max_chars:{type:"number",description:"Maximum characters returned by a bounded read action (1-100000; default 20000)"},full:{type:"boolean",description:"Return the complete payload, bypassing the default 20000-character and item bounds"},localPath:{type:"string",description:"Local destination path for downloadFile. This action is available only over local stdio transport."}},run:Tc},{name:"calendar",description:"Calendar operations. Actions: "+Cn.join(", ")+`.
97
+ search, getComments and findFolder are bounded: 20,000 characters by default (max_chars 1-100,000, full:true for the complete payload). search and getComments page with pageSize and pageToken; findFolder caps at 50 name matches. Truncated output names its true size and how to fetch the rest. account = email of the Google account to use (default: primary).`,actions:_s,localOnlyActions:["downloadFile"],localOnlyInputProps:["localPath"],inputProps:{fileId:{type:"string"},folderId:{type:"string"},folderName:{type:"string"},query:{type:"string"},name:{type:"string"},newName:{type:"string"},parentId:{type:"string"},destinationFolderId:{type:"string"},pageSize:{type:"number",description:"Maximum search results per page (default 10)"},pageToken:{type:"string",description:"Continuation token from a previous search page"},corpus:{type:"string",enum:["user","domain"],description:"Drive search corpus"},unreadOnly:{type:"boolean",description:"Restrict search to unread files where supported"},max_chars:{type:"number",description:"Maximum characters returned by a bounded read action (1-100000; default 20000)"},full:{type:"boolean",description:"Return the complete payload, bypassing the default 20000-character and item bounds"},localPath:{type:"string",description:"Local destination path for downloadFile. This action is available only over local stdio transport."}},run:Tc},{name:"calendar",description:"Calendar operations. Actions: "+Cn.join(", ")+`.
98
98
 
99
99
  listEvents, getEvent, listCalendars and findFreeTime are bounded: 20,000 characters by default (max_chars 1-100,000, full:true for the complete payload); listEvents pages with maxResults and pageToken and always returns its nextPageToken. Truncated output names its true size and how to fetch the rest. account = email of the Google account to use (default: primary).`,actions:Cn,inputProps:{calendarId:{type:"string"},eventId:{type:"string"},summary:{type:"string"},description:{type:"string"},start:{type:"string"},end:{type:"string"},attendees:{type:"array"},maxResults:{type:"number",description:"Maximum events per page (for listEvents; default 20)"},pageToken:{type:"string",description:"Continuation token from a previous listEvents page"},max_chars:{type:"number",description:"Maximum characters returned by a bounded read action (1-100000; default 20000)"},full:{type:"boolean",description:"Return the complete payload, bypassing the default 20000-character and item bounds"}},run:gc},{name:"chat",description:"Chat operations. Actions: "+Pn.join(", ")+`.
100
100
 
101
101
  listSpaces, getMessages, listThreads and findSpaceByName are bounded: 20,000 characters by default (max_chars 1-100,000, full:true for the complete payload). All three listings page with pageSize and pageToken and always return their nextPageToken; findSpaceByName caps at 50 matches. account = email of the Google account to use (default: primary).`,actions:Pn,inputProps:{spaceId:{type:"string"},displayName:{type:"string"},email:{type:"string"},text:{type:"string"},threadId:{type:"string"},pageSize:{type:"number",description:"Maximum spaces, messages, or threads per page"},pageToken:{type:"string",description:"Continuation token from a previous page"},unreadOnly:{type:"boolean",description:"Return only unread messages"},max_chars:{type:"number",description:"Maximum characters returned by a bounded read action (1-100000; default 20000)"},full:{type:"boolean",description:"Return the complete payload, bypassing the default 20000-character and item bounds"},orderBy:{type:"string",description:"Message ordering expression"},filter:{type:"string",description:"Chat message filter"}},run:bc},{name:"gmail",description:"Gmail operations. Actions: "+Fn.join(", ")+`.
102
102
 
103
- get, modify, modifyThread, search and listLabels are bounded: 20,000 characters by default (max_chars 1-100,000, full:true for the complete payload), so a long message body is cut with an explicit marker instead of flooding the response. search pages with maxResults and pageToken. account = email of the Google account to use (default: primary).`,actions:Fn,inputProps:{query:{type:"string"},messageId:{type:"string"},threadId:{type:"string"},to:{type:"string"},subject:{type:"string"},body:{type:"string"},draftId:{type:"string"},labelIds:{type:"array"},maxResults:{type:"number",description:"Maximum messages returned per page (bounded by Gmail)"},pageToken:{type:"string",description:"Continuation token from a previous search page"},includeSpamTrash:{type:"boolean",description:"Include spam and trash in search results"},max_chars:{type:"number",description:"Maximum characters returned by a bounded read action (1-100000; default 20000)"},full:{type:"boolean",description:"Return the complete payload, bypassing the default 20000-character and item bounds"},format:{type:"string",enum:["minimal","full","raw","metadata"],description:"Message payload detail"}},run:Cc},{name:"slides",description:"Slides operations. Actions: "+ps.join(", ")+`.
103
+ get, modify, modifyThread, search and listLabels are bounded: 20,000 characters by default (max_chars 1-100,000, full:true for the complete payload), so a long message body is cut with an explicit marker instead of flooding the response. search pages with maxResults and pageToken. account = email of the Google account to use (default: primary).`,actions:Fn,inputProps:{query:{type:"string"},messageId:{type:"string"},threadId:{type:"string"},to:{type:"string"},subject:{type:"string"},body:{type:"string"},draftId:{type:"string"},labelIds:{type:"array"},maxResults:{type:"number",description:"Maximum messages returned per page (bounded by Gmail)"},pageToken:{type:"string",description:"Continuation token from a previous search page"},includeSpamTrash:{type:"boolean",description:"Include spam and trash in search results"},max_chars:{type:"number",description:"Maximum characters returned by a bounded read action (1-100000; default 20000)"},full:{type:"boolean",description:"Return the complete payload, bypassing the default 20000-character and item bounds"},format:{type:"string",enum:["minimal","full","raw","metadata"],description:"Message payload detail"}},run:Cc},{name:"slides",description:"Slides operations. Actions: "+mo.join(", ")+`.
104
104
 
105
- getText, getMetadata, getImages and getSpeakerNotes are bounded: 20,000 characters by default (max_chars 1-100,000, full:true for the complete payload) and at most 100 slide or image entries. getSlideThumbnail returns one base64 image and is never cut. Truncated output names its true size and how to fetch the rest. account = email of the Google account to use (default: primary).`,actions:ps,inputProps:{presentationId:{type:"string"},title:{type:"string"},max_chars:{type:"number",description:"Maximum characters returned by a bounded read action (1-100000; default 20000)"},full:{type:"boolean",description:"Return the complete payload, bypassing the default 20000-character and item bounds"},slideId:{type:"string"},text:{type:"string"}},run:hu},{name:"sheets",description:"Sheets operations. Actions: "+jn.join(", ")+`.
105
+ getText, getMetadata, getImages and getSpeakerNotes are bounded: 20,000 characters by default (max_chars 1-100,000, full:true for the complete payload) and at most 100 slide or image entries. getSlideThumbnail returns one base64 image and is never cut. Truncated output names its true size and how to fetch the rest. account = email of the Google account to use (default: primary).`,actions:mo,inputProps:{presentationId:{type:"string"},title:{type:"string"},max_chars:{type:"number",description:"Maximum characters returned by a bounded read action (1-100000; default 20000)"},full:{type:"boolean",description:"Return the complete payload, bypassing the default 20000-character and item bounds"},slideId:{type:"string"},text:{type:"string"}},run:hu},{name:"sheets",description:"Sheets operations. Actions: "+jn.join(", ")+`.
106
106
 
107
- getText and getRange return at most 20,000 characters by default (max_chars 1-100,000) and mark truncated output explicitly with the true size and omitted count; pass full:true for the complete payload. account = email of the Google account to use (default: primary).`,actions:jn,inputProps:{spreadsheetId:{type:"string"},range:{type:"string"},max_chars:{type:"number",description:"Maximum characters returned by getText/getRange (1-100000; default 20000)"},full:{type:"boolean",description:"Return the complete getText/getRange payload, bypassing the default 20000-character bound"}},run:Ic},{name:"tasks",description:"Tasks operations. Actions: "+hs.join(", ")+`.
107
+ getText and getRange return at most 20,000 characters by default (max_chars 1-100,000) and mark truncated output explicitly with the true size and omitted count; pass full:true for the complete payload. account = email of the Google account to use (default: primary).`,actions:jn,inputProps:{spreadsheetId:{type:"string"},range:{type:"string"},max_chars:{type:"number",description:"Maximum characters returned by getText/getRange (1-100000; default 20000)"},full:{type:"boolean",description:"Return the complete getText/getRange payload, bypassing the default 20000-character bound"}},run:Ic},{name:"tasks",description:"Tasks operations. Actions: "+go.join(", ")+`.
108
108
 
109
- listTasks and listTaskLists are bounded: 20,000 characters by default (max_chars 1-100,000, full:true for the complete payload) and page with maxResults and pageToken. Truncated output names its true size and how to fetch the rest. account = email of the Google account to use (default: primary).`,actions:hs,inputProps:{taskListId:{type:"string"},taskId:{type:"string"},title:{type:"string"},notes:{type:"string"},due:{type:"string"},max_chars:{type:"number",description:"Maximum characters returned by a bounded read action (1-100000; default 20000)"},full:{type:"boolean",description:"Return the complete payload, bypassing the default 20000-character and item bounds"},maxResults:{type:"number",description:"Maximum task lists or tasks per page"},pageToken:{type:"string",description:"Continuation token from a previous page"}},run:gu},{name:"people",description:"People operations. Actions: "+Un.join(", ")+`.
109
+ listTasks and listTaskLists are bounded: 20,000 characters by default (max_chars 1-100,000, full:true for the complete payload) and page with maxResults and pageToken. Truncated output names its true size and how to fetch the rest. account = email of the Google account to use (default: primary).`,actions:go,inputProps:{taskListId:{type:"string"},taskId:{type:"string"},title:{type:"string"},notes:{type:"string"},due:{type:"string"},max_chars:{type:"number",description:"Maximum characters returned by a bounded read action (1-100000; default 20000)"},full:{type:"boolean",description:"Return the complete payload, bypassing the default 20000-character and item bounds"},maxResults:{type:"number",description:"Maximum task lists or tasks per page"},pageToken:{type:"string",description:"Continuation token from a previous page"}},run:gu},{name:"people",description:"People operations. Actions: "+Un.join(", ")+`.
110
110
 
111
111
  All three actions are bounded: 20,000 characters by default (max_chars 1-100,000, full:true for the complete payload), and getUserRelations keeps at most 50 relations. Truncated output names its true size and how to fetch the rest. account = email of the Google account to use (default: primary).`,actions:Un,inputProps:{max_chars:{type:"number",description:"Maximum characters returned by a bounded read action (1-100000; default 20000)"},full:{type:"boolean",description:"Return the complete payload, bypassing the default 20000-character and item bounds"},resourceName:{type:"string"}},run:Ac},{name:"forms",description:`Google Forms operations.
112
112
 
@@ -121,7 +121,7 @@ Questions are added with batchUpdate, not create. Responses are read-only (the F
121
121
 
122
122
  get, getResponse and listResponses are bounded: 20,000 characters by default (max_chars 1-100,000, full:true for the complete payload); listResponses pages with pageSize and pageToken.
123
123
 
124
- account = email of the Google account to use (default: primary).`,actions:To,inputProps:{formId:{type:"string",description:"Form ID, or the editor URL https://docs.google.com/forms/d/<formId>/edit"},title:{type:"string",description:"Form title shown to respondents (for create)"},documentTitle:{type:"string",description:"Drive file name, when it should differ from the title (for create)"},requests:{type:"array",items:{type:"object"},description:'Forms API batchUpdate requests, e.g. [{"createItem": {...}}] (for batchUpdate)'},responseId:{type:"string",description:"Response ID (for getResponse)"},pageSize:{type:"number",description:"Maximum responses to return (for listResponses)"},pageToken:{type:"string",description:"Page token from a previous listResponses call"},max_chars:{type:"number",description:"Maximum characters returned by a bounded read action (1-100000; default 20000)"},full:{type:"boolean",description:"Return the complete payload, bypassing the default 20000-character and item bounds"},filter:{type:"string",description:"Response filter, e.g. timestamp > 2026-01-01T00:00:00Z (for listResponses)"}},run:Rc}];var bu={config:!0,help:!0,time:!0},Ih=Ph(import.meta.url),Xo=xh(Ih),Lr=Xo.endsWith("bin")?Ko(Xo,"..","build","src","docs"):Ko(Xo,"..","docs"),Ot=[...ve.map(n=>n.name),"config","overview"],Oh=Object.fromEntries(Ot.map(n=>[n,!0])),wu=Ot.join(", "),kh=new Map(ve.map(n=>[n.name,n])),Su=[...ve.map(n=>n.name),"config","help"];function Qo(n){return{content:[{type:"text",text:n}],isError:!0}}async function $h(n){if(Oh[n]!==!0)throw new U(`Invalid topic: ${n}`,"VALIDATION_ERROR",`Valid topics: ${wu}`);let e=`${Eh(n)}.md`,t=Ko(Lr,e),s=Ch(Lr,t);if(s===".."||s.startsWith(`..${Ah}`)||vh(s))throw new U("Path traversal attempt detected","SECURITY_ERROR","Invalid topic");try{return{content:[{type:"text",text:await Rh(t,"utf-8")}]}}catch{throw new U(`Documentation not found for: ${n}`,"DOC_NOT_FOUND","Check topic")}}async function ys(n,e,{allowLocalFilesystem:t=!0}={}){if(!e)return Qo("Error: No arguments provided");if(bu[n]!==!0&&Ct()!=="configured"&&await ot(),bu[n]!==!0&&Ct()!=="configured")return Qo(`Google account not configured. Run \`${Gt()}\` on the host to complete the Google consent, or call config(action="setup_start") for instructions.`);try{let s=kh.get(n);if(s){let o=e.action;if(!t&&typeof o=="string"&&s.localOnlyActions?.includes(o)===!0)throw n==="drive"&&o==="downloadFile"?new U("downloadFile is only available in local stdio mode.","VALIDATION_ERROR","Use a local stdio server to download a Drive file to the local filesystem."):new U(`Action not available in this transport: ${o}`,"VALIDATION_ERROR","Use an action listed in the tool schema.");return await s.run(e)}switch(n){case"config":return await ja(e);case"help":{let o=e.topic;if(typeof o!="string")throw new U("help requires a topic","VALIDATION_ERROR",`Valid topics: ${wu}`);return await $h(o)}default:{let o=Ba(n,Su),a=o?` Did you mean '${o}'?`:"";throw new U(`Unknown tool: ${n}.${a}`,"UNKNOWN_TOOL",`Available tools: ${Su.join(", ")}`)}}}catch(s){let o=s instanceof U?s:new U(s.message,"TOOL_ERROR","Check the error details and try again");return Qo(Ua(o))}}import{readFile as Dh}from"node:fs/promises";import{basename as Lh,isAbsolute as Nh,join as Mh,relative as Fh,sep as Bh}from"node:path";import{CallToolRequestSchema as Uh,ListResourcesRequestSchema as qh,ListToolsRequestSchema as jh,ReadResourceRequestSchema as Wh}from"@modelcontextprotocol/sdk/types.js";var _u=n=>n.charAt(0).toUpperCase()+n.slice(1),ei=[...ve.map(n=>({uri:`workspace://docs/${n.name}`,name:`${_u(n.name)} Tool Docs`,file:`${n.name}.md`})),{uri:"workspace://docs/config",name:"Config Tool Docs",file:"config.md"},{uri:"workspace://docs/overview",name:"Overview Docs",file:"overview.md"}],zh=ei.map(n=>({uri:n.uri,name:n.name,mimeType:"text/markdown"})),Hh=new Map(ei.map(n=>[n.uri,n])),Gh=ei.map(n=>n.uri).join(", ");function Jh(n,e){return e||!n.localOnlyActions?n.actions:n.actions.filter(t=>!n.localOnlyActions.includes(t))}function Vh(n,e){return e||!n.localOnlyInputProps?n.inputProps:Object.fromEntries(Object.entries(n.inputProps).filter(([t])=>!n.localOnlyInputProps.includes(t)))}function Yh(n,e){let t=Jh(n,e);return{name:n.name,description:n.description,annotations:{title:_u(n.name),readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1},inputSchema:{type:"object",properties:{action:{type:"string",enum:[...t],description:"Action to perform"},account:{type:"string",description:'Google account email to act as. Defaults to the primary account (config action="account_list").'},...Vh(n,e)},required:["action"]}}}var ti=[{name:"config",description:`Manage server configuration, credential state, and the Google accounts this server can act as.
124
+ account = email of the Google account to use (default: primary).`,actions:Ts,inputProps:{formId:{type:"string",description:"Form ID, or the editor URL https://docs.google.com/forms/d/<formId>/edit"},title:{type:"string",description:"Form title shown to respondents (for create)"},documentTitle:{type:"string",description:"Drive file name, when it should differ from the title (for create)"},requests:{type:"array",items:{type:"object"},description:'Forms API batchUpdate requests, e.g. [{"createItem": {...}}] (for batchUpdate)'},responseId:{type:"string",description:"Response ID (for getResponse)"},pageSize:{type:"number",description:"Maximum responses to return (for listResponses)"},pageToken:{type:"string",description:"Page token from a previous listResponses call"},max_chars:{type:"number",description:"Maximum characters returned by a bounded read action (1-100000; default 20000)"},full:{type:"boolean",description:"Return the complete payload, bypassing the default 20000-character and item bounds"},filter:{type:"string",description:"Response filter, e.g. timestamp > 2026-01-01T00:00:00Z (for listResponses)"}},run:Rc}];var bu={config:!0,help:!0,time:!0},Oh=Ih(import.meta.url),Xs=vh(Oh),Lr=Xs.endsWith("bin")?Ks(Xs,"..","build","src","docs"):Ks(Xs,"..","docs"),Ot=[...ve.map(r=>r.name),"config","overview"],kh=Object.fromEntries(Ot.map(r=>[r,!0])),wu=Ot.join(", "),$h=new Map(ve.map(r=>[r.name,r])),Su=[...ve.map(r=>r.name),"config","help"];function Qs(r){return{content:[{type:"text",text:r}],isError:!0}}async function Dh(r){if(kh[r]!==!0)throw new U(`Invalid topic: ${r}`,"VALIDATION_ERROR",`Valid topics: ${wu}`);let e=`${xh(r)}.md`,t=Ks(Lr,e),o=Ah(Lr,t);if(o===".."||o.startsWith(`..${Ph}`)||Ch(o))throw new U("Path traversal attempt detected","SECURITY_ERROR","Invalid topic");try{return{content:[{type:"text",text:await Eh(t,"utf-8")}]}}catch{throw new U(`Documentation not found for: ${r}`,"DOC_NOT_FOUND","Check topic")}}async function bo(r,e,{allowLocalFilesystem:t=!0}={}){if(!e)return Qs("Error: No arguments provided");if(bu[r]!==!0&&Ct()!=="configured"&&await st(),bu[r]!==!0&&Ct()!=="configured")return Qs(`Google account not configured. Run \`${Gt()}\` on the host to complete the Google consent, or call config(action="setup_start") for instructions.`);try{let o=$h.get(r);if(o){let s=e.action;if(!t&&typeof s=="string"&&o.localOnlyActions?.includes(s)===!0)throw r==="drive"&&s==="downloadFile"?new U("downloadFile is only available in local stdio mode.","VALIDATION_ERROR","Use a local stdio server to download a Drive file to the local filesystem."):new U(`Action not available in this transport: ${s}`,"VALIDATION_ERROR","Use an action listed in the tool schema.");return await o.run(e)}switch(r){case"config":return await ja(e);case"help":{let s=e.topic;if(typeof s!="string")throw new U("help requires a topic","VALIDATION_ERROR",`Valid topics: ${wu}`);return await Dh(s)}default:{let s=Ba(r,Su),a=s?` Did you mean '${s}'?`:"";throw new U(`Unknown tool: ${r}.${a}`,"UNKNOWN_TOOL",`Available tools: ${Su.join(", ")}`)}}}catch(o){let s=o instanceof U?o:new U(o.message,"TOOL_ERROR","Check the error details and try again");return Qs(Ua(s))}}import{readFile as Lh}from"node:fs/promises";import{basename as Nh,isAbsolute as Mh,join as Fh,relative as Bh,sep as Uh}from"node:path";import{CallToolRequestSchema as qh,ListResourcesRequestSchema as jh,ListToolsRequestSchema as Wh,ReadResourceRequestSchema as zh}from"@modelcontextprotocol/sdk/types.js";var _u=r=>r.charAt(0).toUpperCase()+r.slice(1),ei=[...ve.map(r=>({uri:`workspace://docs/${r.name}`,name:`${_u(r.name)} Tool Docs`,file:`${r.name}.md`})),{uri:"workspace://docs/config",name:"Config Tool Docs",file:"config.md"},{uri:"workspace://docs/overview",name:"Overview Docs",file:"overview.md"}],Hh=ei.map(r=>({uri:r.uri,name:r.name,mimeType:"text/markdown"})),Gh=new Map(ei.map(r=>[r.uri,r])),Jh=ei.map(r=>r.uri).join(", ");function Vh(r,e){return e||!r.localOnlyActions?r.actions:r.actions.filter(t=>!r.localOnlyActions.includes(t))}function Yh(r,e){return e||!r.localOnlyInputProps?r.inputProps:Object.fromEntries(Object.entries(r.inputProps).filter(([t])=>!r.localOnlyInputProps.includes(t)))}function Zh(r,e){let t=Vh(r,e);return{name:r.name,description:r.description,annotations:{title:_u(r.name),readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1},inputSchema:{type:"object",properties:{action:{type:"string",enum:[...t],description:"Action to perform"},account:{type:"string",description:'Google account email to act as. Defaults to the primary account (config action="account_list").'},...Yh(r,e)},required:["action"]}}}var ti=[{name:"config",description:`Manage server configuration, credential state, and the Google accounts this server can act as.
125
125
 
126
126
  Actions:
127
127
  - status: current credential state plus the configured accounts and which is primary
@@ -133,12 +133,12 @@ Actions:
133
133
  - account_add: start the browser consent flow for one more account (stdio: returns a URL to open; HTTP: returns the \`workspace auth --user <namespace>\` command to run on the host)
134
134
  - account_list: list configured accounts and the primary one
135
135
  - account_remove (account): forget one account; a remaining account is promoted if it was primary
136
- - account_set_default (account): make one account the primary (used when a call omits account)`,annotations:{title:"Config",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1},inputSchema:{type:"object",properties:{action:{type:"string",enum:[...fo],description:"Action to perform"},key:{type:"string",description:"Setting key (for set action)"},value:{type:"string",description:"Setting value (for set action)"},account:{type:"string",description:"Account email (for account_remove / account_set_default / account_add)"}},required:["action"]}},{name:"help",description:"Get full documentation for a topic. Use when compressed tool descriptions are insufficient.",annotations:{title:"Help",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:{type:"object",properties:{topic:{type:"string",enum:[...Ot],description:"Topic to get documentation for"}},required:["topic"]}}];function Zh(n){return[...ve.map(e=>Yh(e,n)),...ti]}function bs(n,{allowLocalFilesystem:e=!0}={}){let t=Zh(e);n.setRequestHandler(jh,async()=>({tools:t})),n.setRequestHandler(qh,async()=>({resources:zh})),n.setRequestHandler(Wh,async s=>{let{uri:o}=s.params,a=Hh.get(o);if(!a)throw new U(`Resource not found: ${o}`,"RESOURCE_NOT_FOUND",`Available: ${Gh}`);let l=Mh(Lr,Lh(a.file)),d=Fh(Lr,l);if(d===".."||d.startsWith(`..${Bh}`)||Nh(d))throw new U("Path traversal attempt detected","SECURITY_ERROR","Invalid resource URI");try{let p=await Dh(l,"utf-8");return{contents:[{uri:o,mimeType:"text/markdown",text:p}]}}catch{throw new U(`Documentation not found for: ${a.name}`,"DOC_NOT_FOUND","Check resource URI")}}),n.setRequestHandler(Uh,async s=>{let{name:o,arguments:a}=s.params;return ys(o,a,{allowLocalFilesystem:e})})}import{readFileSync as Xh}from"node:fs";import{dirname as Qh,join as Kh}from"node:path";import{fileURLToPath as eg}from"node:url";function yt(){try{let n=Qh(eg(import.meta.url)),e=Kh(n,"..","package.json");return JSON.parse(Xh(e,"utf-8")).version??"0.0.0"}catch{return"0.0.0"}}var tg={out:n=>console.log(n),err:n=>console.error(n)},Tu=2,rg="--json",ng={"-h":!0,"--help":!0},sg={type:"string",description:"Google account email to act as. Defaults to the primary account."};function ri(n){if(typeof n!="object"||n===null)return{type:"string"};let e="type"in n&&typeof n.type=="string"?n.type:"string",t="description"in n&&typeof n.description=="string"?n.description:void 0,s="enum"in n&&Array.isArray(n.enum)?n.enum.filter(o=>typeof o=="string"):void 0;return{type:e,description:t,values:s}}function og(n){let e=ve.find(t=>t.name===n);if(e)return{tool:e.name,subcommand:e.name,description:e.description,actions:e.actions,props:{account:sg,...e.inputProps}}}var ar={tool:"help",subcommand:"help",description:"Full documentation for one tool (the MCP `help` tool).",actions:[],props:{topic:{type:"string",description:`Topic to read: ${Ot.join(", ")}`}}},ni={"config-tool":"config"};function xu(n,e){let t=ti.find(a=>a.name===e);if(!t)throw new Error(`subcommand '${n}' aliases the unknown MCP tool '${e}'`);let{action:s,...o}=t.inputSchema.properties;return{tool:e,subcommand:n,description:t.description,actions:ri(s).values??[],props:o}}var Ru=[{name:"auth",description:"add a Google account on the host (`--user <namespace>` for HTTP mode)"},{name:"config",description:"stored credential state: `config status` | `config delete --yes` (MCP `config` tool: `config-tool`)"},{name:"status",description:"alias of `config status`"},{name:"logout",description:"alias of `config delete`"},{name:"doctor",description:"environment and credential-backend checks"},{name:"token",description:"bearer-token helpers for HTTP mode"}],vu=[...ve.map(n=>n.name),ar.subcommand,...Object.keys(ni)];function ig(n){if(n===ar.subcommand)return ar;let e=ni[n];return e!==void 0?xu(n,e):og(n)}var Se=class extends Error{};function ag(n){let e=n.split(`
137
- `)[0]??n;return(e.split(". ")[0]??e).replace(/\.$/,"")}function cg(n,e=6){return n.length<=e?n.join(", "):`${n.slice(0,e).join(", ")}, \u2026 (+${n.length-e})`}function lg(n){if(n.subcommand===ar.subcommand)return["usage: workspace help [topic] [--json]","","Print full documentation for one topic, or the whole subcommand surface","when no topic is given.","","topics:",` ${Ot.join(", ")}`,"","options:"," --json Print the result as JSON on stdout"," -h, --help Show this help"].join(`
138
- `);let e=Object.entries(n.props).map(([t,s])=>{let o=ri(s),a=o.description?` ${o.description}`:"";return` --${t} <${o.type}>${a}`});return[`usage: workspace ${n.subcommand} <action> [--param <value>]... [--json]`,"",n.description,"","actions:",` ${n.actions.join(", ")}`,"","options:",...e," --json Print the result as JSON on stdout"," -h, --help Show this help"].join(`
139
- `)}function si(){let n=[...ve.map(a=>({label:a.name,description:a.description,actions:a.actions})),...Object.entries(ni).map(([a,l])=>{let d=xu(a,l);return{label:a,description:d.description,actions:d.actions}}),{label:ar.subcommand,description:"Full documentation for any tool",actions:[]}],e=[...n.map(a=>a.label),...Ru.map(a=>a.name)],t=Math.max(...e.map(a=>a.length))+2,s=n.map(a=>{let l=a.actions.length>0?` \u2014 ${cg(a.actions)}`:"";return` ${a.label.padEnd(t)}${ag(a.description)}${l}`}),o=Ru.map(a=>` ${a.name.padEnd(t)}${a.description}`);return[`workspace ${yt()} \u2014 Google Workspace MCP server`,"","usage:"," workspace start the MCP server (stdio)"," workspace --http start the MCP server (HTTP)"," workspace <tool> <action> [--param] call one tool from the terminal"," workspace help [topic] tool documentation","","tools (each is an MCP tool; the CLI runs the same handler):",...s,"","operator commands (not tools):",...o,"","examples:"," workspace time getCurrentTime --json",' workspace gmail search --query "is:unread" --maxResults 5'," workspace docs getText --documentId <document-id> --limit 2000"," workspace config-tool status --json"," workspace help tasks"].join(`
140
- `)}function ug(n,e){try{return JSON.parse(e)}catch{throw new Se(`--${n} expects JSON, got '${e}'`)}}function dg(n,e,t){switch(t.type){case"number":{let s=Number(e);if(!Number.isFinite(s))throw new Se(`--${n} expects a number, got '${e}'`);return s}case"boolean":{if(e==="true"||e==="")return!0;if(e==="false")return!1;throw new Se(`--${n} expects 'true' or 'false', got '${e}'`)}case"array":return e.startsWith("[")?ug(n,e):e.split(",").map(s=>s.trim()).filter(s=>s.length>0);default:return e}}function fg(n,e){let t=[],s={},o=!1;for(let a=0;a<e.length;a+=1){let l=e[a];if(l===rg){o=!0;continue}if(!l.startsWith("--")){t.push(l);continue}let[d,p]=l.slice(2).split(/=(.*)/s),u=d.startsWith("no-"),f=u?d.slice(3):d,y=n.props[f];if(y===void 0){let R=Object.keys(n.props).map(x=>`--${x}`).join(", ");throw new Se(`unknown option --${f} (valid: ${R})`)}let g=ri(y);if(u){if(g.type!=="boolean")throw new Se(`--no-${f} only applies to boolean options`);s[f]=!1;continue}let _=e[a+1],S=p!==void 0,E=!S&&_!==void 0&&!_.startsWith("--");if(!S&&!E){if(g.type==="boolean"){s[f]=!0;continue}throw new Se(`--${f} expects a value`)}E&&(a+=1),s[f]=dg(f,S?p:_,g)}return{positionals:t,params:s,json:o}}function Eu(n){return n.content.map(e=>e.type==="text"?e.text:"").filter(e=>e.length>0).join(`
141
- `)}function pg(n){try{return JSON.parse(n)}catch{return n}}async function mg(n,e,t=tg){let s=ig(n);if(!s)return t.err(`workspace: unknown tool '${n}' (expected one of: ${vu.join(", ")})`),Tu;let o=s.tool===ar.tool;if(e.some(u=>ng[u]===!0))return t.out(lg(s)),0;if(o&&!e.some(u=>!u.startsWith("-")))return t.out(si()),0;let a,l;try{if(a=fg(s,e),o){if(a.positionals.length>1)throw new Se(`help takes one topic, got ${a.positionals.length}`);l="help",a.positionals[0]!==void 0&&(a.params.topic=a.positionals[0])}else{let[u,...f]=a.positionals;if(u===void 0)throw new Se(`missing action (one of: ${s.actions.join(", ")})`);if(f.length>0)throw new Se(`unexpected argument '${f[0]}' (pass options as --name value)`);l=u,a.params.action=u}}catch(u){if(!(u instanceof Se))throw u;return t.err(`workspace ${n}: ${u.message}`),t.err(`run \`workspace ${n} --help\` for usage`),Tu}let d=await ys(s.tool,a.params);if(d.isError===!0){let u=Eu(d);return t.err(a.json?JSON.stringify({tool:s.tool,action:l,error:u}):u),1}let p=Eu(d);return a.json?(t.out(JSON.stringify({tool:s.tool,action:l,result:pg(p)},null,2)),0):(t.out(p),0)}function Cu(){return Object.fromEntries(vu.map(n=>[n,e=>mg(n,e)]))}import{homedir as _g}from"node:os";import{isAbsolute as Tg,join as rR,resolve as ii,sep as Rg}from"node:path";import{setHomeDirForTesting as Eg}from"@n24q02m/hull/storage";import{existsSync as ku,readdirSync as $u}from"node:fs";import{join as oi}from"node:path";import{isDeepStrictEqual as hg}from"node:util";import{credPath as gg,dataDirCandidates as Du,PerPluginStore as Au}from"@n24q02m/hull/storage";var kt=class extends Error{constructor(t,s){super(s);this.path=t;this.name="StoreMigrationError"}},yg=/^[A-Za-z0-9._-]+$/;function Ss(n){return n?.code??"unknown error"}function bg(n){try{return $u(n),!0}catch(e){let t=Ss(e);if(t==="ENOENT")return!1;throw new kt(n,`Cannot read the previous credential directory ${n} (${t}). Fix its permissions or move it aside, then start again: nothing was migrated and no credential was changed.`)}}function Sg(n){let e=oi(n,"subs"),t;try{t=$u(e,{withFileTypes:!0})}catch(s){let o=Ss(s);if(o==="ENOENT")return[];throw new kt(e,`Cannot read the previous credential directory ${e} (${o}). Fix its permissions or move it aside, then start again: nothing was migrated and no credential was changed.`)}return t.filter(s=>s.isDirectory()&&s.name!=="."&&s.name!==".."&&yg.test(s.name)).map(s=>s.name)}function Pu(n){for(let{dir:e}of Du(pn)){let t=n===null?oi(e,"config.json"):oi(e,"subs",n,"config.json");if(ku(t))return e}return null}async function Iu(n,e,t){let s=gg(We,n);if(ku(s)){t.kept.push(s);return}if(n!==null&&!process.env.CREDENTIAL_SECRET){t.deferred.push(n);return}let o;try{o=await new Au(pn,n).load()}catch(d){throw new kt(e,`Cannot read the saved credential in ${e} (${Ss(d)}). Nothing was migrated and the previous store was left untouched.`)}if(o===null)return;let a=new Au(We,n);try{await a.save(o)}catch(d){throw new kt(s,`Cannot write the migrated credential to ${s} (${Ss(d)}). The previous store in ${e} was left untouched.`)}let l=null;try{l=await a.load()}catch{l=null}if(!hg(l,o))throw new kt(s,`Wrote ${s} but reading it back did not return the migrated credential. The previous store in ${e} was left untouched.`);t.migrated.push({source:e,sub:n})}async function wg(){let n={migrated:[],kept:[],deferred:[]},e=Du(pn).map(o=>o.dir).filter(o=>bg(o));if(e.length===0)return n;let t=new Set;for(let o of e)for(let a of Sg(o))t.add(a);let s=Pu(null);s!==null&&await Iu(null,s,n);for(let o of[...t].sort()){let a=Pu(o);a!==null&&await Iu(o,a,n)}return n}var Ou=null;function Lu(){return Ou??=wg(),Ou}var ws="WORKSPACE_DATA_DIR",iR=`.${We}`,_s=class extends Error{constructor(e){super(e),this.name="DataDirEscapeError"}};function xg(n=process.env,e=_g()){let t=ii(e),s=n[ws]?.trim();if(!s)return t;if(s.includes("\0"))throw new _s(`${ws} must not contain a NUL byte`);if(Tg(s))return ii(s);let o=ii(t,s);if(o!==t&&!o.startsWith(t+Rg))throw new _s(`${ws}="${s}" escapes the base directory ${t}; use an absolute path to choose another directory`);return o}function vg(n=process.env){if(!n[ws]?.trim())return null;let e=xg(n);return Eg(e),e}async function ai(n=process.env){return vg(n),Lu()}import{Server as Cg}from"@modelcontextprotocol/sdk/server/index.js";import{runHttpServer as Ag}from"@n24q02m/hull/transport";var Pg="WORKSPACE_USERS_FILE";async function Nu(){if(!process.env.CREDENTIAL_SECRET)throw new Error("CREDENTIAL_SECRET is required for http mode: per-user credential stores derive their encryption key from it.");let n=process.env.PORT?Number.parseInt(process.env.PORT,10):0,e=process.env.HOST,t=await Ag(()=>{let s=new Cg({name:ce,version:yt()},{capabilities:{tools:{},resources:{}}});return bs(s,{allowLocalFilesystem:!1}),s},{serverName:ce,port:n,host:e,auth:{mode:"multi",usersFile:process.env[Pg]||void 0}});console.error(`[${ce}] http mode on http://${t.host}:${t.port}/mcp`),await new Promise(s=>{let o=async()=>{await t.close(),s()};process.once("SIGINT",o),process.once("SIGTERM",o)})}function Dg(n){let e=process.argv[1];if(!e)return!1;try{let t=Mu(Ig(n)),s=Mu(e);if(process.platform==="win32"){let o=a=>a.replace(/\\/g,"/").toLowerCase();return o(t)===o(s)}return t===s}catch{return!1}}function Lg(n=process.env,e=process.argv){return e.includes("--http")||n.MCP_TRANSPORT==="http"||n.TRANSPORT_MODE==="http"?"http":"stdio"}async function Ng(n){if(await ai(),process.env.BETTER_WORKSPACE_MCP_BOOTSTRAPPED){console.error(`[${ce}] Startup aborted: server already running in this process tree.`);return}if(process.env.BETTER_WORKSPACE_MCP_BOOTSTRAPPED="true",n==="http"){await Nu();return}await ot(),Ct()!=="configured"&&(await Da(),await ot());let e=new Og({name:ce,version:yt()},{capabilities:{tools:{},resources:{}}});bs(e);let t=new kg;await e.connect(t),console.error(`[${ce}] stdio mode ready (v${yt()})`)}var Mg=Lg();async function Fg(n=Mg){try{await Ng(n)}catch(e){console.error("Failed to start server:",e instanceof Error?e.message:String(e)),process.exit(1)}}async function Bg(n){if(await ai(),n[0]==="-h"||n[0]==="--help"){console.log(si()),process.exitCode=0;return}let e=$g(ce,{serve:()=>Fg(),extra:{auth:Na,...Cu()},version:yt(),pluginName:We});process.exitCode=await e(n)}Dg(import.meta.url)&&process.env.NODE_ENV!=="test"&&Bg(process.argv.slice(2));export{Fg as bootstrap,Lg as getTransportMode,Dg as isMain,Mg as mode,Bg as runCli,Ng as startServer};
136
+ - account_set_default (account): make one account the primary (used when a call omits account)`,annotations:{title:"Config",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1},inputSchema:{type:"object",properties:{action:{type:"string",enum:[...fs],description:"Action to perform"},key:{type:"string",description:"Setting key (for set action)"},value:{type:"string",description:"Setting value (for set action)"},account:{type:"string",description:"Account email (for account_remove / account_set_default / account_add)"}},required:["action"]}},{name:"help",description:"Get full documentation for a topic. Use when compressed tool descriptions are insufficient.",annotations:{title:"Help",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:{type:"object",properties:{topic:{type:"string",enum:[...Ot],description:"Topic to get documentation for"}},required:["topic"]}}];function Xh(r){return[...ve.map(e=>Zh(e,r)),...ti]}function So(r,{allowLocalFilesystem:e=!0}={}){let t=Xh(e);r.setRequestHandler(Wh,async()=>({tools:t})),r.setRequestHandler(jh,async()=>({resources:Hh})),r.setRequestHandler(zh,async o=>{let{uri:s}=o.params,a=Gh.get(s);if(!a)throw new U(`Resource not found: ${s}`,"RESOURCE_NOT_FOUND",`Available: ${Jh}`);let l=Fh(Lr,Nh(a.file)),d=Bh(Lr,l);if(d===".."||d.startsWith(`..${Uh}`)||Mh(d))throw new U("Path traversal attempt detected","SECURITY_ERROR","Invalid resource URI");try{let p=await Lh(l,"utf-8");return{contents:[{uri:s,mimeType:"text/markdown",text:p}]}}catch{throw new U(`Documentation not found for: ${a.name}`,"DOC_NOT_FOUND","Check resource URI")}}),r.setRequestHandler(qh,async o=>{let{name:s,arguments:a}=o.params;return bo(s,a,{allowLocalFilesystem:e})})}import{readFileSync as Qh}from"node:fs";import{dirname as Kh,join as eg}from"node:path";import{fileURLToPath as tg}from"node:url";function yt(){try{let r=Kh(tg(import.meta.url)),e=eg(r,"..","package.json");return JSON.parse(Qh(e,"utf-8")).version??"0.0.0"}catch{return"0.0.0"}}var rg={out:r=>console.log(r),err:r=>console.error(r)},Tu=2,ng="--json",og={"-h":!0,"--help":!0},sg={type:"string",description:"Google account email to act as. Defaults to the primary account."};function ri(r){if(typeof r!="object"||r===null)return{type:"string"};let e="type"in r&&typeof r.type=="string"?r.type:"string",t="description"in r&&typeof r.description=="string"?r.description:void 0,o="enum"in r&&Array.isArray(r.enum)?r.enum.filter(s=>typeof s=="string"):void 0;return{type:e,description:t,values:o}}function ig(r){let e=ve.find(t=>t.name===r);if(e)return{tool:e.name,subcommand:e.name,description:e.description,actions:e.actions,props:{account:sg,...e.inputProps}}}var ar={tool:"help",subcommand:"help",description:"Full documentation for one tool (the MCP `help` tool).",actions:[],props:{topic:{type:"string",description:`Topic to read: ${Ot.join(", ")}`}}},ni={"config-tool":"config"};function xu(r,e){let t=ti.find(a=>a.name===e);if(!t)throw new Error(`subcommand '${r}' aliases the unknown MCP tool '${e}'`);let{action:o,...s}=t.inputSchema.properties;return{tool:e,subcommand:r,description:t.description,actions:ri(o).values??[],props:s}}var Ru=[{name:"auth",description:"add a Google account on the host (`--user <namespace>` for HTTP mode)"},{name:"config",description:"stored credential state: `config status` | `config delete --yes` (MCP `config` tool: `config-tool`)"},{name:"status",description:"alias of `config status`"},{name:"logout",description:"alias of `config delete`"},{name:"doctor",description:"environment and credential-backend checks"},{name:"token",description:"bearer-token helpers for HTTP mode"}],vu=[...ve.map(r=>r.name),ar.subcommand,...Object.keys(ni)];function ag(r){if(r===ar.subcommand)return ar;let e=ni[r];return e!==void 0?xu(r,e):ig(r)}var Se=class extends Error{};function cg(r){let e=r.split(`
137
+ `)[0]??r;return(e.split(". ")[0]??e).replace(/\.$/,"")}function lg(r,e=6){return r.length<=e?r.join(", "):`${r.slice(0,e).join(", ")}, \u2026 (+${r.length-e})`}function ug(r){if(r.subcommand===ar.subcommand)return["usage: workspace help [topic] [--json]","","Print full documentation for one topic, or the whole subcommand surface","when no topic is given.","","topics:",` ${Ot.join(", ")}`,"","options:"," --json Print the result as JSON on stdout"," -h, --help Show this help"].join(`
138
+ `);let e=Object.entries(r.props).map(([t,o])=>{let s=ri(o),a=s.description?` ${s.description}`:"";return` --${t} <${s.type}>${a}`});return[`usage: workspace ${r.subcommand} <action> [--param <value>]... [--json]`,"",r.description,"","actions:",` ${r.actions.join(", ")}`,"","options:",...e," --json Print the result as JSON on stdout"," -h, --help Show this help"].join(`
139
+ `)}function oi(){let r=[...ve.map(a=>({label:a.name,description:a.description,actions:a.actions})),...Object.entries(ni).map(([a,l])=>{let d=xu(a,l);return{label:a,description:d.description,actions:d.actions}}),{label:ar.subcommand,description:"Full documentation for any tool",actions:[]}],e=[...r.map(a=>a.label),...Ru.map(a=>a.name)],t=Math.max(...e.map(a=>a.length))+2,o=r.map(a=>{let l=a.actions.length>0?` \u2014 ${lg(a.actions)}`:"";return` ${a.label.padEnd(t)}${cg(a.description)}${l}`}),s=Ru.map(a=>` ${a.name.padEnd(t)}${a.description}`);return[`workspace ${yt()} \u2014 Google Workspace MCP server`,"","usage:"," workspace start the MCP server (stdio)"," workspace --http start the MCP server (HTTP)"," workspace <tool> <action> [--param] call one tool from the terminal"," workspace help [topic] tool documentation","","tools (each is an MCP tool; the CLI runs the same handler):",...o,"","operator commands (not tools):",...s,"","examples:"," workspace time getCurrentTime --json",' workspace gmail search --query "is:unread" --maxResults 5'," workspace docs getText --documentId <document-id> --limit 2000"," workspace config-tool status --json"," workspace help tasks"].join(`
140
+ `)}function dg(r,e){try{return JSON.parse(e)}catch{throw new Se(`--${r} expects JSON, got '${e}'`)}}function fg(r,e,t){switch(t.type){case"number":{let o=Number(e);if(!Number.isFinite(o))throw new Se(`--${r} expects a number, got '${e}'`);return o}case"boolean":{if(e==="true"||e==="")return!0;if(e==="false")return!1;throw new Se(`--${r} expects 'true' or 'false', got '${e}'`)}case"array":return e.startsWith("[")?dg(r,e):e.split(",").map(o=>o.trim()).filter(o=>o.length>0);default:return e}}function pg(r,e){let t=[],o={},s=!1;for(let a=0;a<e.length;a+=1){let l=e[a];if(l===ng){s=!0;continue}if(!l.startsWith("--")){t.push(l);continue}let[d,p]=l.slice(2).split(/=(.*)/s),u=d.startsWith("no-"),f=u?d.slice(3):d,y=r.props[f];if(y===void 0){let R=Object.keys(r.props).map(x=>`--${x}`).join(", ");throw new Se(`unknown option --${f} (valid: ${R})`)}let g=ri(y);if(u){if(g.type!=="boolean")throw new Se(`--no-${f} only applies to boolean options`);o[f]=!1;continue}let _=e[a+1],S=p!==void 0,E=!S&&_!==void 0&&!_.startsWith("--");if(!S&&!E){if(g.type==="boolean"){o[f]=!0;continue}throw new Se(`--${f} expects a value`)}E&&(a+=1),o[f]=fg(f,S?p:_,g)}return{positionals:t,params:o,json:s}}function Eu(r){return r.content.map(e=>e.type==="text"?e.text:"").filter(e=>e.length>0).join(`
141
+ `)}function mg(r){try{return JSON.parse(r)}catch{return r}}async function hg(r,e,t=rg){let o=ag(r);if(!o)return t.err(`workspace: unknown tool '${r}' (expected one of: ${vu.join(", ")})`),Tu;let s=o.tool===ar.tool;if(e.some(u=>og[u]===!0))return t.out(ug(o)),0;if(s&&!e.some(u=>!u.startsWith("-")))return t.out(oi()),0;let a,l;try{if(a=pg(o,e),s){if(a.positionals.length>1)throw new Se(`help takes one topic, got ${a.positionals.length}`);l="help",a.positionals[0]!==void 0&&(a.params.topic=a.positionals[0])}else{let[u,...f]=a.positionals;if(u===void 0)throw new Se(`missing action (one of: ${o.actions.join(", ")})`);if(f.length>0)throw new Se(`unexpected argument '${f[0]}' (pass options as --name value)`);l=u,a.params.action=u}}catch(u){if(!(u instanceof Se))throw u;return t.err(`workspace ${r}: ${u.message}`),t.err(`run \`workspace ${r} --help\` for usage`),Tu}let d=await bo(o.tool,a.params);if(d.isError===!0){let u=Eu(d);return t.err(a.json?JSON.stringify({tool:o.tool,action:l,error:u}):u),1}let p=Eu(d);return a.json?(t.out(JSON.stringify({tool:o.tool,action:l,result:mg(p)},null,2)),0):(t.out(p),0)}function Cu(){return Object.fromEntries(vu.map(r=>[r,e=>hg(r,e)]))}import{homedir as Tg}from"node:os";import{isAbsolute as Rg,join as nR,resolve as ii,sep as Eg}from"node:path";import{setHomeDirForTesting as xg}from"@n24q02m/hull/storage";import{existsSync as ku,readdirSync as $u}from"node:fs";import{join as si}from"node:path";import{isDeepStrictEqual as gg}from"node:util";import{credPath as yg,dataDirCandidates as Du,PerPluginStore as Au}from"@n24q02m/hull/storage";var kt=class extends Error{constructor(t,o){super(o);this.path=t;this.name="StoreMigrationError"}},bg=/^[A-Za-z0-9._-]+$/;function wo(r){return r?.code??"unknown error"}function Sg(r){try{return $u(r),!0}catch(e){let t=wo(e);if(t==="ENOENT")return!1;throw new kt(r,`Cannot read the previous credential directory ${r} (${t}). Fix its permissions or move it aside, then start again: nothing was migrated and no credential was changed.`)}}function wg(r){let e=si(r,"subs"),t;try{t=$u(e,{withFileTypes:!0})}catch(o){let s=wo(o);if(s==="ENOENT")return[];throw new kt(e,`Cannot read the previous credential directory ${e} (${s}). Fix its permissions or move it aside, then start again: nothing was migrated and no credential was changed.`)}return t.filter(o=>o.isDirectory()&&o.name!=="."&&o.name!==".."&&bg.test(o.name)).map(o=>o.name)}function Pu(r){for(let{dir:e}of Du(pn)){let t=r===null?si(e,"config.json"):si(e,"subs",r,"config.json");if(ku(t))return e}return null}async function Iu(r,e,t){let o=yg(We,r);if(ku(o)){t.kept.push(o);return}if(r!==null&&!process.env.CREDENTIAL_SECRET){t.deferred.push(r);return}let s;try{s=await new Au(pn,r).load()}catch(d){throw new kt(e,`Cannot read the saved credential in ${e} (${wo(d)}). Nothing was migrated and the previous store was left untouched.`)}if(s===null)return;let a=new Au(We,r);try{await a.save(s)}catch(d){throw new kt(o,`Cannot write the migrated credential to ${o} (${wo(d)}). The previous store in ${e} was left untouched.`)}let l=null;try{l=await a.load()}catch{l=null}if(!gg(l,s))throw new kt(o,`Wrote ${o} but reading it back did not return the migrated credential. The previous store in ${e} was left untouched.`);t.migrated.push({source:e,sub:r})}async function _g(){let r={migrated:[],kept:[],deferred:[]},e=Du(pn).map(s=>s.dir).filter(s=>Sg(s));if(e.length===0)return r;let t=new Set;for(let s of e)for(let a of wg(s))t.add(a);let o=Pu(null);o!==null&&await Iu(null,o,r);for(let s of[...t].sort()){let a=Pu(s);a!==null&&await Iu(s,a,r)}return r}var Ou=null;function Lu(){return Ou??=_g(),Ou}var _o="WORKSPACE_DATA_DIR",aR=`.${We}`,To=class extends Error{constructor(e){super(e),this.name="DataDirEscapeError"}};function vg(r=process.env,e=Tg()){let t=ii(e),o=r[_o]?.trim();if(!o)return t;if(o.includes("\0"))throw new To(`${_o} must not contain a NUL byte`);if(Rg(o))return ii(o);let s=ii(t,o);if(s!==t&&!s.startsWith(t+Eg))throw new To(`${_o}="${o}" escapes the base directory ${t}; use an absolute path to choose another directory`);return s}function Cg(r=process.env){if(!r[_o]?.trim())return null;let e=vg(r);return xg(e),e}async function ai(r=process.env){return Cg(r),Lu()}import{Server as Ag}from"@modelcontextprotocol/sdk/server/index.js";import{runHttpServer as Pg}from"@n24q02m/hull/transport";var Ig="WORKSPACE_USERS_FILE";async function Nu(){if(!process.env.CREDENTIAL_SECRET)throw new Error("CREDENTIAL_SECRET is required for http mode: per-user credential stores derive their encryption key from it.");let r=process.env.PORT?Number.parseInt(process.env.PORT,10):0,e=process.env.HOST,t=await Pg(()=>{let o=new Ag({name:ce,version:yt()},{capabilities:{tools:{},resources:{}}});return So(o,{allowLocalFilesystem:!1}),o},{serverName:ce,port:r,host:e,auth:{mode:"multi",usersFile:process.env[Ig]||void 0}});console.error(`[${ce}] http mode on http://${t.host}:${t.port}/mcp`),await new Promise(o=>{let s=async()=>{await t.close(),o()};process.once("SIGINT",s),process.once("SIGTERM",s)})}function Lg(r){let e=process.argv[1];if(!e)return!1;try{let t=Mu(Og(r)),o=Mu(e);if(process.platform==="win32"){let s=a=>a.replace(/\\/g,"/").toLowerCase();return s(t)===s(o)}return t===o}catch{return!1}}function Ng(r=process.env,e=process.argv){return e.includes("--http")||r.MCP_TRANSPORT==="http"||r.TRANSPORT_MODE==="http"?"http":"stdio"}async function Mg(r){if(await ai(),process.env.BETTER_WORKSPACE_MCP_BOOTSTRAPPED){console.error(`[${ce}] Startup aborted: server already running in this process tree.`);return}if(process.env.BETTER_WORKSPACE_MCP_BOOTSTRAPPED="true",r==="http"){await Nu();return}await st(),Ct()!=="configured"&&(await Da(),await st());let e=new kg({name:ce,version:yt()},{capabilities:{tools:{},resources:{}}});So(e);let t=new $g;await e.connect(t),console.error(`[${ce}] stdio mode ready (v${yt()})`)}var Fg=Ng();async function Bg(r=Fg){try{await Mg(r)}catch(e){console.error("Failed to start server:",e instanceof Error?e.message:String(e)),process.exit(1)}}async function Ug(r){if(await ai(),r[0]==="-h"||r[0]==="--help"){console.log(oi()),process.exitCode=0;return}let e=Dg(ce,{serve:()=>Bg(),extra:{auth:Na,...Cu()},version:yt(),pluginName:We});process.exitCode=await e(r)}Lg(import.meta.url)&&process.env.NODE_ENV!=="test"&&Ug(process.argv.slice(2));export{Bg as bootstrap,Ng as getTransportMode,Lg as isMain,Fg as mode,Ug as runCli,Mg as startServer};
142
142
  /**
143
143
  * @license
144
144
  * Copyright 2025 Google LLC