@wengine-ai/llms 2.0.48 → 2.0.50
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/server.cjs +166 -166
- package/dist/cjs/server.cjs.map +4 -4
- package/dist/esm/server.mjs +165 -165
- package/dist/esm/server.mjs.map +4 -4
- package/dist/index.d.ts +46 -0
- package/package.json +1 -1
package/dist/esm/server.mjs
CHANGED
|
@@ -1,79 +1,79 @@
|
|
|
1
|
-
var F_=Object.create;var pu=Object.defineProperty;var P_=Object.getOwnPropertyDescriptor;var I_=Object.getOwnPropertyNames;var N_=Object.getPrototypeOf,B_=Object.prototype.hasOwnProperty;var Q=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof require<"u"?require:e)[r]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var je=(t,e)=>()=>(t&&(e=t(t=0)),e);var V=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Rd=(t,e)=>{for(var r in e)pu(t,r,{get:e[r],enumerable:!0})},j_=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of I_(e))!B_.call(t,s)&&s!==r&&pu(t,s,{get:()=>e[s],enumerable:!(n=P_(e,s))||n.enumerable});return t};var Pr=(t,e,r)=>(r=t!=null?F_(N_(t)):{},j_(e||!t||!t.__esModule?pu(r,"default",{value:t,enumerable:!0}):r,t));var Od=V((DD,Io)=>{Io.exports.Space_Separator=/[\u1680\u2000-\u200A\u202F\u205F\u3000]/;Io.exports.ID_Start=/[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u09FC\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF2D-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC00-\uDC34\uDC47-\uDC4A\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDE00\uDE0B-\uDE32\uDE3A\uDE50\uDE5C-\uDE83\uDE86-\uDE89\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC2E\uDC40\uDC72-\uDC8F\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD30\uDD46]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4\uDD00-\uDD43]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]/;Io.exports.ID_Continue=/[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u08D4-\u08E1\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u09FC\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9-\u0AFF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C80-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D00-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D54-\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1C80-\u1C88\u1CD0-\u1CD2\u1CD4-\u1CF9\u1D00-\u1DF9\u1DFB-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u2E2F\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099\u309A\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDDFD\uDE80-\uDE9C\uDEA0-\uDED0\uDEE0\uDF00-\uDF1F\uDF2D-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE38-\uDE3A\uDE3F\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE6\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDCA-\uDDCC\uDDD0-\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE37\uDE3E\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF00-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF50\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC00-\uDC4A\uDC50-\uDC59\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDDD8-\uDDDD\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9\uDF00-\uDF19\uDF1D-\uDF2B\uDF30-\uDF39]|\uD806[\uDCA0-\uDCE9\uDCFF\uDE00-\uDE3E\uDE47\uDE50-\uDE83\uDE86-\uDE99\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC36\uDC38-\uDC40\uDC50-\uDC59\uDC72-\uDC8F\uDC92-\uDCA7\uDCA9-\uDCB6\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD36\uDD3A\uDD3C\uDD3D\uDD3F-\uDD47\uDD50-\uDD59]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD836[\uDE00-\uDE36\uDE3B-\uDE6C\uDE75\uDE84\uDE9B-\uDE9F\uDEA1-\uDEAF]|\uD838[\uDC00-\uDC06\uDC08-\uDC18\uDC1B-\uDC21\uDC23\uDC24\uDC26-\uDC2A]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6\uDD00-\uDD4A\uDD50-\uDD59]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/});var gu=V((vD,xd)=>{var mu=Od();xd.exports={isSpaceSeparator(t){return typeof t=="string"&&mu.Space_Separator.test(t)},isIdStartChar(t){return typeof t=="string"&&(t>="a"&&t<="z"||t>="A"&&t<="Z"||t==="$"||t==="_"||mu.ID_Start.test(t))},isIdContinueChar(t){return typeof t=="string"&&(t>="a"&&t<="z"||t>="A"&&t<="Z"||t>="0"&&t<="9"||t==="$"||t==="_"||t==="\u200C"||t==="\u200D"||mu.ID_Continue.test(t))},isDigit(t){return typeof t=="string"&&/[0-9]/.test(t)},isHexDigit(t){return typeof t=="string"&&/[0-9A-Fa-f]/.test(t)}}});var Bd=V((RD,Nd)=>{var $e=gu(),_u,Ze,pr,Bo,Ir,Nt,ze,wu,bs;Nd.exports=function(e,r){_u=String(e),Ze="start",pr=[],Bo=0,Ir=1,Nt=0,ze=void 0,wu=void 0,bs=void 0;do ze=L_(),q_[Ze]();while(ze.type!=="eof");return typeof r=="function"?bu({"":bs},"",r):bs};function bu(t,e,r){let n=t[e];if(n!=null&&typeof n=="object")if(Array.isArray(n))for(let s=0;s<n.length;s++){let i=String(s),u=bu(n,i,r);u===void 0?delete n[i]:Object.defineProperty(n,i,{value:u,writable:!0,enumerable:!0,configurable:!0})}else for(let s in n){let i=bu(n,s,r);i===void 0?delete n[s]:Object.defineProperty(n,s,{value:i,writable:!0,enumerable:!0,configurable:!0})}return r.call(t,e,n)}var ge,he,_s,hr,Ce;function L_(){for(ge="default",he="",_s=!1,hr=1;;){Ce=mr();let t=Pd[ge]();if(t)return t}}function mr(){if(_u[Bo])return String.fromCodePoint(_u.codePointAt(Bo))}function H(){let t=mr();return t===`
|
|
2
|
-
`?(
|
|
3
|
-
`:case"\r":case"\u2028":case"\u2029":H();return;case"/":H(),ge="comment";return;case void 0:return H(),Pe("eof")}if($e.isSpaceSeparator(Ce)){H();return}return
|
|
4
|
-
`:case"\r":case"\u2028":case"\u2029":H(),ge="default";return;case void 0:return H(),Pe("eof")}H()},value(){switch(Ce){case"{":case"[":return Pe("punctuator",H());case"n":return H(),
|
|
5
|
-
`:case"\r":throw Ie(H());case"\u2028":case"\u2029"
|
|
6
|
-
`;case"r":return H(),"\r";case"t":return H()," ";case"v":return H(),"\v";case"0":if(H(),$e.isDigit(
|
|
7
|
-
`:case"\u2028":case"\u2029":return H(),"";case"\r":return H(),
|
|
8
|
-
`&&H(),"";case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":throw Ie(H());case void 0:throw Ie(H())}return H()}function
|
|
9
|
-
`+i;
|
|
10
|
-
`+i+
|
|
11
|
-
`+g+"}"}}return s.pop(),i=g,b}function
|
|
12
|
-
`+i,
|
|
13
|
-
`+i+
|
|
14
|
-
`+g+"]"}return s.pop(),i=g,
|
|
15
|
-
`)||n,code:i,status:s},e.data.error)}return Object.assign({message:n,code:i,status:s},e.data.error)}}return{message:n,code:e.status,status:e.statusText}}};wt.GaxiosError=Fu;function db(t,e){switch(t){case"stream":return e;case"json":return JSON.parse(JSON.stringify(e));case"arraybuffer":return JSON.parse(Buffer.from(e).toString("utf8"));case"blob":return JSON.parse(e.text());default:return e}}function dh(t){let e="<<REDACTED> - See `errorRedactor` option in `gaxios` for configuration>.";function r(i){i&&i.forEach((u,c)=>{(/^authentication$/i.test(c)||/^authorization$/i.test(c)||/secret/i.test(c))&&i.set(c,e)})}function n(i,u){if(typeof i=="object"&&i!==null&&typeof i[u]=="string"){let c=i[u];(/grant_type=/i.test(c)||/assertion=/i.test(c)||/secret/i.test(c))&&(i[u]=e)}}function s(i){!i||typeof i!="object"||(i instanceof FormData||i instanceof URLSearchParams||"forEach"in i&&"set"in i?i.forEach((u,c)=>{(["grant_type","assertion"].includes(c)||/secret/.test(c))&&i.set(c,e)}):("grant_type"in i&&(i.grant_type=e),"assertion"in i&&(i.assertion=e),"client_secret"in i&&(i.client_secret=e)))}return t.config&&(r(t.config.headers),n(t.config,"data"),s(t.config.data),n(t.config,"body"),s(t.config.body),t.config.url.searchParams.has("token")&&t.config.url.searchParams.set("token",e),t.config.url.searchParams.has("client_secret")&&t.config.url.searchParams.set("client_secret",e)),t.response&&(dh({config:t.response.config}),r(t.response.headers),t.response.bodyUsed&&(n(t.response,"data"),s(t.response.data))),t}});var ph=V(Iu=>{"use strict";Object.defineProperty(Iu,"__esModule",{value:!0});Iu.getRetryConfig=hb;async function hb(t){let e=hh(t);if(!t||!t.config||!e&&!t.config.retry)return{shouldRetry:!1};e=e||{},e.currentRetryAttempt=e.currentRetryAttempt||0,e.retry=e.retry===void 0||e.retry===null?3:e.retry,e.httpMethodsToRetry=e.httpMethodsToRetry||["GET","HEAD","PUT","OPTIONS","DELETE"],e.noResponseRetries=e.noResponseRetries===void 0||e.noResponseRetries===null?2:e.noResponseRetries,e.retryDelayMultiplier=e.retryDelayMultiplier?e.retryDelayMultiplier:2,e.timeOfFirstRequest=e.timeOfFirstRequest?e.timeOfFirstRequest:Date.now(),e.totalTimeout=e.totalTimeout?e.totalTimeout:Number.MAX_SAFE_INTEGER,e.maxRetryDelay=e.maxRetryDelay?e.maxRetryDelay:Number.MAX_SAFE_INTEGER;let r=[[100,199],[408,408],[429,429],[500,599]];if(e.statusCodesToRetry=e.statusCodesToRetry||r,t.config.retryConfig=e,!await(e.shouldRetry||pb)(t))return{shouldRetry:!1,config:t.config};let s=mb(e);t.config.retryConfig.currentRetryAttempt+=1;let i=e.retryBackoff?e.retryBackoff(t,s):new Promise(u=>{setTimeout(u,s)});return e.onRetryAttempt&&await e.onRetryAttempt(t),await i,{shouldRetry:!0,config:t.config}}function pb(t){let e=hh(t);if(t.config.signal?.aborted&&t.code!=="TimeoutError"||t.code==="AbortError"||!e||e.retry===0||!t.response&&(e.currentRetryAttempt||0)>=e.noResponseRetries||!e.httpMethodsToRetry||!e.httpMethodsToRetry.includes(t.config.method?.toUpperCase()||"GET"))return!1;if(t.response&&t.response.status){let r=!1;for(let[n,s]of e.statusCodesToRetry){let i=t.response.status;if(i>=n&&i<=s){r=!0;break}}if(!r)return!1}return e.currentRetryAttempt=e.currentRetryAttempt||0,!(e.currentRetryAttempt>=e.retry)}function hh(t){if(t&&t.config&&t.config.retryConfig)return t.config.retryConfig}function mb(t){let r=(t.currentRetryAttempt?0:t.retryDelay??100)+(Math.pow(t.retryDelayMultiplier,t.currentRetryAttempt)-1)/2*1e3,n=t.totalTimeout-(Date.now()-t.timeOfFirstRequest);return Math.min(r,n,t.maxRetryDelay)}});var Bu=V(Jo=>{"use strict";Object.defineProperty(Jo,"__esModule",{value:!0});Jo.GaxiosInterceptorManager=void 0;var Nu=class extends Set{};Jo.GaxiosInterceptorManager=Nu});var gh=V((Ev,mh)=>{var xn=1e3,Fn=xn*60,Pn=Fn*60,nn=Pn*24,gb=nn*7,yb=nn*365.25;mh.exports=function(t,e){e=e||{};var r=typeof t;if(r==="string"&&t.length>0)return _b(t);if(r==="number"&&isFinite(t))return e.long?Cb(t):bb(t);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(t))};function _b(t){if(t=String(t),!(t.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(t);if(e){var r=parseFloat(e[1]),n=(e[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return r*yb;case"weeks":case"week":case"w":return r*gb;case"days":case"day":case"d":return r*nn;case"hours":case"hour":case"hrs":case"hr":case"h":return r*Pn;case"minutes":case"minute":case"mins":case"min":case"m":return r*Fn;case"seconds":case"second":case"secs":case"sec":case"s":return r*xn;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return r;default:return}}}}function bb(t){var e=Math.abs(t);return e>=nn?Math.round(t/nn)+"d":e>=Pn?Math.round(t/Pn)+"h":e>=Fn?Math.round(t/Fn)+"m":e>=xn?Math.round(t/xn)+"s":t+"ms"}function Cb(t){var e=Math.abs(t);return e>=nn?Vo(t,e,nn,"day"):e>=Pn?Vo(t,e,Pn,"hour"):e>=Fn?Vo(t,e,Fn,"minute"):e>=xn?Vo(t,e,xn,"second"):t+" ms"}function Vo(t,e,r,n){var s=e>=r*1.5;return Math.round(t/r)+" "+n+(s?"s":"")}});var ju=V((Av,yh)=>{function wb(t){r.debug=r,r.default=r,r.coerce=l,r.disable=u,r.enable=s,r.enabled=c,r.humanize=gh(),r.destroy=h,Object.keys(t).forEach(d=>{r[d]=t[d]}),r.names=[],r.skips=[],r.formatters={};function e(d){let p=0;for(let A=0;A<d.length;A++)p=(p<<5)-p+d.charCodeAt(A),p|=0;return r.colors[Math.abs(p)%r.colors.length]}r.selectColor=e;function r(d){let p,A=null,v,S;function y(...g){if(!y.enabled)return;let m=y,k=Number(new Date),b=k-(p||k);m.diff=b,m.prev=p,m.curr=k,p=k,g[0]=r.coerce(g[0]),typeof g[0]!="string"&&g.unshift("%O");let E=0;g[0]=g[0].replace(/%([a-zA-Z%])/g,(F,$)=>{if(F==="%%")return"%";E++;let J=r.formatters[$];if(typeof J=="function"){let M=g[E];F=J.call(m,M),g.splice(E,1),E--}return F}),r.formatArgs.call(m,g),(m.log||r.log).apply(m,g)}return y.namespace=d,y.useColors=r.useColors(),y.color=r.selectColor(d),y.extend=n,y.destroy=r.destroy,Object.defineProperty(y,"enabled",{enumerable:!0,configurable:!1,get:()=>A!==null?A:(v!==r.namespaces&&(v=r.namespaces,S=r.enabled(d)),S),set:g=>{A=g}}),typeof r.init=="function"&&r.init(y),y}function n(d,p){let A=r(this.namespace+(typeof p>"u"?":":p)+d);return A.log=this.log,A}function s(d){r.save(d),r.namespaces=d,r.names=[],r.skips=[];let p=(typeof d=="string"?d:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(let A of p)A[0]==="-"?r.skips.push(A.slice(1)):r.names.push(A)}function i(d,p){let A=0,v=0,S=-1,y=0;for(;A<d.length;)if(v<p.length&&(p[v]===d[A]||p[v]==="*"))p[v]==="*"?(S=v,y=A,v++):(A++,v++);else if(S!==-1)v=S+1,y++,A=y;else return!1;for(;v<p.length&&p[v]==="*";)v++;return v===p.length}function u(){let d=[...r.names,...r.skips.map(p=>"-"+p)].join(",");return r.enable(""),d}function c(d){for(let p of r.skips)if(i(d,p))return!1;for(let p of r.names)if(i(d,p))return!0;return!1}function l(d){return d instanceof Error?d.stack||d.message:d}function h(){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 r.enable(r.load()),r}yh.exports=wb});var _h=V((st,Ko)=>{st.formatArgs=Ab;st.save=Sb;st.load=kb;st.useColors=Eb;st.storage=Tb();st.destroy=(()=>{let t=!1;return()=>{t||(t=!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`."))}})();st.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 Eb(){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 t;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&&(t=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(t[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function Ab(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+Ko.exports.humanize(this.diff),!this.useColors)return;let e="color: "+this.color;t.splice(1,0,e,"color: inherit");let r=0,n=0;t[0].replace(/%[a-zA-Z%]/g,s=>{s!=="%%"&&(r++,s==="%c"&&(n=r))}),t.splice(n,0,e)}st.log=console.debug||console.log||(()=>{});function Sb(t){try{t?st.storage.setItem("debug",t):st.storage.removeItem("debug")}catch{}}function kb(){let t;try{t=st.storage.getItem("debug")||st.storage.getItem("DEBUG")}catch{}return!t&&typeof process<"u"&&"env"in process&&(t=process.env.DEBUG),t}function Tb(){try{return localStorage}catch{}}Ko.exports=ju()(st);var{formatters:Db}=Ko.exports;Db.j=function(t){try{return JSON.stringify(t)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var Ch=V((Sv,bh)=>{"use strict";bh.exports=(t,e=process.argv)=>{let r=t.startsWith("-")?"":t.length===1?"-":"--",n=e.indexOf(r+t),s=e.indexOf("--");return n!==-1&&(s===-1||n<s)}});var Ah=V((kv,Eh)=>{"use strict";var vb=Q("os"),wh=Q("tty"),Et=Ch(),{env:He}=process,Nr;Et("no-color")||Et("no-colors")||Et("color=false")||Et("color=never")?Nr=0:(Et("color")||Et("colors")||Et("color=true")||Et("color=always"))&&(Nr=1);"FORCE_COLOR"in He&&(He.FORCE_COLOR==="true"?Nr=1:He.FORCE_COLOR==="false"?Nr=0:Nr=He.FORCE_COLOR.length===0?1:Math.min(parseInt(He.FORCE_COLOR,10),3));function Lu(t){return t===0?!1:{level:t,hasBasic:!0,has256:t>=2,has16m:t>=3}}function Mu(t,e){if(Nr===0)return 0;if(Et("color=16m")||Et("color=full")||Et("color=truecolor"))return 3;if(Et("color=256"))return 2;if(t&&!e&&Nr===void 0)return 0;let r=Nr||0;if(He.TERM==="dumb")return r;if(process.platform==="win32"){let n=vb.release().split(".");return Number(n[0])>=10&&Number(n[2])>=10586?Number(n[2])>=14931?3:2:1}if("CI"in He)return["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE"].some(n=>n in He)||He.CI_NAME==="codeship"?1:r;if("TEAMCITY_VERSION"in He)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(He.TEAMCITY_VERSION)?1:0;if(He.COLORTERM==="truecolor")return 3;if("TERM_PROGRAM"in He){let n=parseInt((He.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(He.TERM_PROGRAM){case"iTerm.app":return n>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(He.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(He.TERM)||"COLORTERM"in He?1:r}function Rb(t){let e=Mu(t,t&&t.isTTY);return Lu(e)}Eh.exports={supportsColor:Rb,stdout:Lu(Mu(!0,wh.isatty(1))),stderr:Lu(Mu(!0,wh.isatty(2)))}});var kh=V((We,Xo)=>{var Ob=Q("tty"),Yo=Q("util");We.init=jb;We.log=Ib;We.formatArgs=Fb;We.save=Nb;We.load=Bb;We.useColors=xb;We.destroy=Yo.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");We.colors=[6,2,3,4,5,1];try{let t=Ah();t&&(t.stderr||t).level>=2&&(We.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{}We.inspectOpts=Object.keys(process.env).filter(t=>/^debug_/i.test(t)).reduce((t,e)=>{let r=e.substring(6).toLowerCase().replace(/_([a-z])/g,(s,i)=>i.toUpperCase()),n=process.env[e];return/^(yes|on|true|enabled)$/i.test(n)?n=!0:/^(no|off|false|disabled)$/i.test(n)?n=!1:n==="null"?n=null:n=Number(n),t[r]=n,t},{});function xb(){return"colors"in We.inspectOpts?!!We.inspectOpts.colors:Ob.isatty(process.stderr.fd)}function Fb(t){let{namespace:e,useColors:r}=this;if(r){let n=this.color,s="\x1B[3"+(n<8?n:"8;5;"+n),i=` ${s};1m${e} \x1B[0m`;t[0]=i+t[0].split(`
|
|
1
|
+
var K_=Object.create;var bu=Object.defineProperty;var Y_=Object.getOwnPropertyDescriptor;var Q_=Object.getOwnPropertyNames;var X_=Object.getPrototypeOf,Z_=Object.prototype.hasOwnProperty;var X=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof require<"u"?require:e)[r]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var je=(t,e)=>()=>(t&&(e=t(t=0)),e);var V=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),zf=(t,e)=>{for(var r in e)bu(t,r,{get:e[r],enumerable:!0})},eb=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Q_(e))!Z_.call(t,s)&&s!==r&&bu(t,s,{get:()=>e[s],enumerable:!(n=Y_(e,s))||n.enumerable});return t};var Nr=(t,e,r)=>(r=t!=null?K_(X_(t)):{},eb(e||!t||!t.__esModule?bu(r,"default",{value:t,enumerable:!0}):r,t));var Hf=V((sD,Lo)=>{Lo.exports.Space_Separator=/[\u1680\u2000-\u200A\u202F\u205F\u3000]/;Lo.exports.ID_Start=/[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u09FC\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF2D-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC00-\uDC34\uDC47-\uDC4A\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDE00\uDE0B-\uDE32\uDE3A\uDE50\uDE5C-\uDE83\uDE86-\uDE89\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC2E\uDC40\uDC72-\uDC8F\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD30\uDD46]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4\uDD00-\uDD43]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]/;Lo.exports.ID_Continue=/[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u08D4-\u08E1\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u09FC\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9-\u0AFF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C80-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D00-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D54-\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1C80-\u1C88\u1CD0-\u1CD2\u1CD4-\u1CF9\u1D00-\u1DF9\u1DFB-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u2E2F\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099\u309A\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDDFD\uDE80-\uDE9C\uDEA0-\uDED0\uDEE0\uDF00-\uDF1F\uDF2D-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE38-\uDE3A\uDE3F\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE6\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDCA-\uDDCC\uDDD0-\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE37\uDE3E\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF00-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF50\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC00-\uDC4A\uDC50-\uDC59\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDDD8-\uDDDD\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9\uDF00-\uDF19\uDF1D-\uDF2B\uDF30-\uDF39]|\uD806[\uDCA0-\uDCE9\uDCFF\uDE00-\uDE3E\uDE47\uDE50-\uDE83\uDE86-\uDE99\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC36\uDC38-\uDC40\uDC50-\uDC59\uDC72-\uDC8F\uDC92-\uDCA7\uDCA9-\uDCB6\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD36\uDD3A\uDD3C\uDD3D\uDD3F-\uDD47\uDD50-\uDD59]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD836[\uDE00-\uDE36\uDE3B-\uDE6C\uDE75\uDE84\uDE9B-\uDE9F\uDEA1-\uDEAF]|\uD838[\uDC00-\uDC06\uDC08-\uDC18\uDC1B-\uDC21\uDC23\uDC24\uDC26-\uDC2A]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6\uDD00-\uDD4A\uDD50-\uDD59]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/});var wu=V((oD,Wf)=>{var Cu=Hf();Wf.exports={isSpaceSeparator(t){return typeof t=="string"&&Cu.Space_Separator.test(t)},isIdStartChar(t){return typeof t=="string"&&(t>="a"&&t<="z"||t>="A"&&t<="Z"||t==="$"||t==="_"||Cu.ID_Start.test(t))},isIdContinueChar(t){return typeof t=="string"&&(t>="a"&&t<="z"||t>="A"&&t<="Z"||t>="0"&&t<="9"||t==="$"||t==="_"||t==="\u200C"||t==="\u200D"||Cu.ID_Continue.test(t))},isDigit(t){return typeof t=="string"&&/[0-9]/.test(t)},isHexDigit(t){return typeof t=="string"&&/[0-9A-Fa-f]/.test(t)}}});var Yf=V((iD,Kf)=>{var $e=wu(),Au,Ze,gr,Uo,Br,Nt,ze,ku,ws;Kf.exports=function(e,r){Au=String(e),Ze="start",gr=[],Uo=0,Br=1,Nt=0,ze=void 0,ku=void 0,ws=void 0;do ze=tb(),sb[Ze]();while(ze.type!=="eof");return typeof r=="function"?Su({"":ws},"",r):ws};function Su(t,e,r){let n=t[e];if(n!=null&&typeof n=="object")if(Array.isArray(n))for(let s=0;s<n.length;s++){let i=String(s),u=Su(n,i,r);u===void 0?delete n[i]:Object.defineProperty(n,i,{value:u,writable:!0,enumerable:!0,configurable:!0})}else for(let s in n){let i=Su(n,s,r);i===void 0?delete n[s]:Object.defineProperty(n,s,{value:i,writable:!0,enumerable:!0,configurable:!0})}return r.call(t,e,n)}var ge,he,Cs,mr,Ce;function tb(){for(ge="default",he="",Cs=!1,mr=1;;){Ce=yr();let t=Jf[ge]();if(t)return t}}function yr(){if(Au[Uo])return String.fromCodePoint(Au.codePointAt(Uo))}function H(){let t=yr();return t===`
|
|
2
|
+
`?(Br++,Nt=0):t?Nt+=t.length:Nt++,t&&(Uo+=t.length),t}var Jf={default(){switch(Ce){case" ":case"\v":case"\f":case" ":case"\xA0":case"\uFEFF":case`
|
|
3
|
+
`:case"\r":case"\u2028":case"\u2029":H();return;case"/":H(),ge="comment";return;case void 0:return H(),Pe("eof")}if($e.isSpaceSeparator(Ce)){H();return}return Jf[Ze]()},comment(){switch(Ce){case"*":H(),ge="multiLineComment";return;case"/":H(),ge="singleLineComment";return}throw Ie(H())},multiLineComment(){switch(Ce){case"*":H(),ge="multiLineCommentAsterisk";return;case void 0:throw Ie(H())}H()},multiLineCommentAsterisk(){switch(Ce){case"*":H();return;case"/":H(),ge="default";return;case void 0:throw Ie(H())}H(),ge="multiLineComment"},singleLineComment(){switch(Ce){case`
|
|
4
|
+
`:case"\r":case"\u2028":case"\u2029":H(),ge="default";return;case void 0:return H(),Pe("eof")}H()},value(){switch(Ce){case"{":case"[":return Pe("punctuator",H());case"n":return H(),sn("ull"),Pe("null",null);case"t":return H(),sn("rue"),Pe("boolean",!0);case"f":return H(),sn("alse"),Pe("boolean",!1);case"-":case"+":H()==="-"&&(mr=-1),ge="sign";return;case".":he=H(),ge="decimalPointLeading";return;case"0":he=H(),ge="zero";return;case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":he=H(),ge="decimalInteger";return;case"I":return H(),sn("nfinity"),Pe("numeric",1/0);case"N":return H(),sn("aN"),Pe("numeric",NaN);case'"':case"'":Cs=H()==='"',he="",ge="string";return}throw Ie(H())},identifierNameStartEscape(){if(Ce!=="u")throw Ie(H());H();let t=vu();switch(t){case"$":case"_":break;default:if(!$e.isIdStartChar(t))throw Gf();break}he+=t,ge="identifierName"},identifierName(){switch(Ce){case"$":case"_":case"\u200C":case"\u200D":he+=H();return;case"\\":H(),ge="identifierNameEscape";return}if($e.isIdContinueChar(Ce)){he+=H();return}return Pe("identifier",he)},identifierNameEscape(){if(Ce!=="u")throw Ie(H());H();let t=vu();switch(t){case"$":case"_":case"\u200C":case"\u200D":break;default:if(!$e.isIdContinueChar(t))throw Gf();break}he+=t,ge="identifierName"},sign(){switch(Ce){case".":he=H(),ge="decimalPointLeading";return;case"0":he=H(),ge="zero";return;case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":he=H(),ge="decimalInteger";return;case"I":return H(),sn("nfinity"),Pe("numeric",mr*(1/0));case"N":return H(),sn("aN"),Pe("numeric",NaN)}throw Ie(H())},zero(){switch(Ce){case".":he+=H(),ge="decimalPoint";return;case"e":case"E":he+=H(),ge="decimalExponent";return;case"x":case"X":he+=H(),ge="hexadecimal";return}return Pe("numeric",mr*0)},decimalInteger(){switch(Ce){case".":he+=H(),ge="decimalPoint";return;case"e":case"E":he+=H(),ge="decimalExponent";return}if($e.isDigit(Ce)){he+=H();return}return Pe("numeric",mr*Number(he))},decimalPointLeading(){if($e.isDigit(Ce)){he+=H(),ge="decimalFraction";return}throw Ie(H())},decimalPoint(){switch(Ce){case"e":case"E":he+=H(),ge="decimalExponent";return}if($e.isDigit(Ce)){he+=H(),ge="decimalFraction";return}return Pe("numeric",mr*Number(he))},decimalFraction(){switch(Ce){case"e":case"E":he+=H(),ge="decimalExponent";return}if($e.isDigit(Ce)){he+=H();return}return Pe("numeric",mr*Number(he))},decimalExponent(){switch(Ce){case"+":case"-":he+=H(),ge="decimalExponentSign";return}if($e.isDigit(Ce)){he+=H(),ge="decimalExponentInteger";return}throw Ie(H())},decimalExponentSign(){if($e.isDigit(Ce)){he+=H(),ge="decimalExponentInteger";return}throw Ie(H())},decimalExponentInteger(){if($e.isDigit(Ce)){he+=H();return}return Pe("numeric",mr*Number(he))},hexadecimal(){if($e.isHexDigit(Ce)){he+=H(),ge="hexadecimalInteger";return}throw Ie(H())},hexadecimalInteger(){if($e.isHexDigit(Ce)){he+=H();return}return Pe("numeric",mr*Number(he))},string(){switch(Ce){case"\\":H(),he+=rb();return;case'"':if(Cs)return H(),Pe("string",he);he+=H();return;case"'":if(!Cs)return H(),Pe("string",he);he+=H();return;case`
|
|
5
|
+
`:case"\r":throw Ie(H());case"\u2028":case"\u2029":ob(Ce);break;case void 0:throw Ie(H())}he+=H()},start(){switch(Ce){case"{":case"[":return Pe("punctuator",H())}ge="value"},beforePropertyName(){switch(Ce){case"$":case"_":he=H(),ge="identifierName";return;case"\\":H(),ge="identifierNameStartEscape";return;case"}":return Pe("punctuator",H());case'"':case"'":Cs=H()==='"',ge="string";return}if($e.isIdStartChar(Ce)){he+=H(),ge="identifierName";return}throw Ie(H())},afterPropertyName(){if(Ce===":")return Pe("punctuator",H());throw Ie(H())},beforePropertyValue(){ge="value"},afterPropertyValue(){switch(Ce){case",":case"}":return Pe("punctuator",H())}throw Ie(H())},beforeArrayValue(){if(Ce==="]")return Pe("punctuator",H());ge="value"},afterArrayValue(){switch(Ce){case",":case"]":return Pe("punctuator",H())}throw Ie(H())},end(){throw Ie(H())}};function Pe(t,e){return{type:t,value:e,line:Br,column:Nt}}function sn(t){for(let e of t){if(yr()!==e)throw Ie(H());H()}}function rb(){switch(yr()){case"b":return H(),"\b";case"f":return H(),"\f";case"n":return H(),`
|
|
6
|
+
`;case"r":return H(),"\r";case"t":return H()," ";case"v":return H(),"\v";case"0":if(H(),$e.isDigit(yr()))throw Ie(H());return"\0";case"x":return H(),nb();case"u":return H(),vu();case`
|
|
7
|
+
`:case"\u2028":case"\u2029":return H(),"";case"\r":return H(),yr()===`
|
|
8
|
+
`&&H(),"";case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":throw Ie(H());case void 0:throw Ie(H())}return H()}function nb(){let t="",e=yr();if(!$e.isHexDigit(e)||(t+=H(),e=yr(),!$e.isHexDigit(e)))throw Ie(H());return t+=H(),String.fromCodePoint(parseInt(t,16))}function vu(){let t="",e=4;for(;e-- >0;){let r=yr();if(!$e.isHexDigit(r))throw Ie(H());t+=H()}return String.fromCodePoint(parseInt(t,16))}var sb={start(){if(ze.type==="eof")throw on();Eu()},beforePropertyName(){switch(ze.type){case"identifier":case"string":ku=ze.value,Ze="afterPropertyName";return;case"punctuator":Mo();return;case"eof":throw on()}},afterPropertyName(){if(ze.type==="eof")throw on();Ze="beforePropertyValue"},beforePropertyValue(){if(ze.type==="eof")throw on();Eu()},beforeArrayValue(){if(ze.type==="eof")throw on();if(ze.type==="punctuator"&&ze.value==="]"){Mo();return}Eu()},afterPropertyValue(){if(ze.type==="eof")throw on();switch(ze.value){case",":Ze="beforePropertyName";return;case"}":Mo()}},afterArrayValue(){if(ze.type==="eof")throw on();switch(ze.value){case",":Ze="beforeArrayValue";return;case"]":Mo()}},end(){}};function Eu(){let t;switch(ze.type){case"punctuator":switch(ze.value){case"{":t={};break;case"[":t=[];break}break;case"null":case"boolean":case"numeric":case"string":t=ze.value;break}if(ws===void 0)ws=t;else{let e=gr[gr.length-1];Array.isArray(e)?e.push(t):Object.defineProperty(e,ku,{value:t,writable:!0,enumerable:!0,configurable:!0})}if(t!==null&&typeof t=="object")gr.push(t),Array.isArray(t)?Ze="beforeArrayValue":Ze="beforePropertyName";else{let e=gr[gr.length-1];e==null?Ze="end":Array.isArray(e)?Ze="afterArrayValue":Ze="afterPropertyValue"}}function Mo(){gr.pop();let t=gr[gr.length-1];t==null?Ze="end":Array.isArray(t)?Ze="afterArrayValue":Ze="afterPropertyValue"}function Ie(t){return qo(t===void 0?`JSON5: invalid end of input at ${Br}:${Nt}`:`JSON5: invalid character '${Vf(t)}' at ${Br}:${Nt}`)}function on(){return qo(`JSON5: invalid end of input at ${Br}:${Nt}`)}function Gf(){return Nt-=5,qo(`JSON5: invalid identifier character at ${Br}:${Nt}`)}function ob(t){console.warn(`JSON5: '${Vf(t)}' in strings is not valid ECMAScript; consider escaping`)}function Vf(t){let e={"'":"\\'",'"':'\\"',"\\":"\\\\","\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r"," ":"\\t","\v":"\\v","\0":"\\0","\u2028":"\\u2028","\u2029":"\\u2029"};if(e[t])return e[t];if(t<" "){let r=t.charCodeAt(0).toString(16);return"\\x"+("00"+r).substring(r.length)}return t}function qo(t){let e=new SyntaxError(t);return e.lineNumber=Br,e.columnNumber=Nt,e}});var Xf=V((aD,Qf)=>{var Tu=wu();Qf.exports=function(e,r,n){let s=[],i="",u,c,l="",h;if(r!=null&&typeof r=="object"&&!Array.isArray(r)&&(n=r.space,h=r.quote,r=r.replacer),typeof r=="function")c=r;else if(Array.isArray(r)){u=[];for(let y of r){let g;typeof y=="string"?g=y:(typeof y=="number"||y instanceof String||y instanceof Number)&&(g=String(y)),g!==void 0&&u.indexOf(g)<0&&u.push(g)}}return n instanceof Number?n=Number(n):n instanceof String&&(n=String(n)),typeof n=="number"?n>0&&(n=Math.min(10,Math.floor(n)),l=" ".substr(0,n)):typeof n=="string"&&(l=n.substr(0,10)),d("",{"":e});function d(y,g){let m=g[y];switch(m!=null&&(typeof m.toJSON5=="function"?m=m.toJSON5(y):typeof m.toJSON=="function"&&(m=m.toJSON(y))),c&&(m=c.call(g,y,m)),m instanceof Number?m=Number(m):m instanceof String?m=String(m):m instanceof Boolean&&(m=m.valueOf()),m){case null:return"null";case!0:return"true";case!1:return"false"}if(typeof m=="string")return p(m,!1);if(typeof m=="number")return String(m);if(typeof m=="object")return Array.isArray(m)?S(m):w(m)}function p(y){let g={"'":.1,'"':.2},m={"'":"\\'",'"':'\\"',"\\":"\\\\","\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r"," ":"\\t","\v":"\\v","\0":"\\0","\u2028":"\\u2028","\u2029":"\\u2029"},v="";for(let A=0;A<y.length;A++){let R=y[A];switch(R){case"'":case'"':g[R]++,v+=R;continue;case"\0":if(Tu.isDigit(y[A+1])){v+="\\x00";continue}}if(m[R]){v+=m[R];continue}if(R<" "){let F=R.charCodeAt(0).toString(16);v+="\\x"+("00"+F).substring(F.length);continue}v+=R}let b=h||Object.keys(g).reduce((A,R)=>g[A]<g[R]?A:R);return v=v.replace(new RegExp(b,"g"),m[b]),b+v+b}function w(y){if(s.indexOf(y)>=0)throw TypeError("Converting circular structure to JSON5");s.push(y);let g=i;i=i+l;let m=u||Object.keys(y),v=[];for(let A of m){let R=d(A,y);if(R!==void 0){let F=T(A)+":";l!==""&&(F+=" "),F+=R,v.push(F)}}let b;if(v.length===0)b="{}";else{let A;if(l==="")A=v.join(","),b="{"+A+"}";else{let R=`,
|
|
9
|
+
`+i;A=v.join(R),b=`{
|
|
10
|
+
`+i+A+`,
|
|
11
|
+
`+g+"}"}}return s.pop(),i=g,b}function T(y){if(y.length===0)return p(y,!0);let g=String.fromCodePoint(y.codePointAt(0));if(!Tu.isIdStartChar(g))return p(y,!0);for(let m=g.length;m<y.length;m++)if(!Tu.isIdContinueChar(String.fromCodePoint(y.codePointAt(m))))return p(y,!0);return y}function S(y){if(s.indexOf(y)>=0)throw TypeError("Converting circular structure to JSON5");s.push(y);let g=i;i=i+l;let m=[];for(let b=0;b<y.length;b++){let A=d(String(b),y);m.push(A!==void 0?A:"null")}let v;if(m.length===0)v="[]";else if(l==="")v="["+m.join(",")+"]";else{let b=`,
|
|
12
|
+
`+i,A=m.join(b);v=`[
|
|
13
|
+
`+i+A+`,
|
|
14
|
+
`+g+"]"}return s.pop(),i=g,v}}});var Du=V((uD,Zf)=>{var ib=Yf(),ab=Xf(),ub={parse:ib,stringify:ab};Zf.exports=ub});var Nu=V((JD,wh)=>{"use strict";var Yo=Object.prototype.hasOwnProperty,Ch=Object.prototype.toString,ph=Object.defineProperty,mh=Object.getOwnPropertyDescriptor,gh=function(e){return typeof Array.isArray=="function"?Array.isArray(e):Ch.call(e)==="[object Array]"},yh=function(e){if(!e||Ch.call(e)!=="[object Object]")return!1;var r=Yo.call(e,"constructor"),n=e.constructor&&e.constructor.prototype&&Yo.call(e.constructor.prototype,"isPrototypeOf");if(e.constructor&&!r&&!n)return!1;var s;for(s in e);return typeof s>"u"||Yo.call(e,s)},_h=function(e,r){ph&&r.name==="__proto__"?ph(e,r.name,{enumerable:!0,configurable:!0,value:r.newValue,writable:!0}):e[r.name]=r.newValue},bh=function(e,r){if(r==="__proto__")if(Yo.call(e,r)){if(mh)return mh(e,r).value}else return;return e[r]};wh.exports=function t(){var e,r,n,s,i,u,c=arguments[0],l=1,h=arguments.length,d=!1;for(typeof c=="boolean"&&(d=c,c=arguments[1]||{},l=2),(c==null||typeof c!="object"&&typeof c!="function")&&(c={});l<h;++l)if(e=arguments[l],e!=null)for(r in e)n=bh(c,r),s=bh(e,r),c!==s&&(d&&s&&(yh(s)||(i=gh(s)))?(i?(i=!1,u=n&&gh(n)?n:[]):u=n&&yh(n)?n:{},_h(c,{name:r,newValue:t(d,u,s)})):typeof s<"u"&&_h(c,{name:r,newValue:s}));return c}});var Eh=V((VD,xb)=>{xb.exports={name:"gaxios",version:"7.1.2",description:"A simple common HTTP client specifically for Google APIs and services.",main:"build/cjs/src/index.js",types:"build/cjs/src/index.d.ts",files:["build/"],exports:{".":{import:{types:"./build/esm/src/index.d.ts",default:"./build/esm/src/index.js"},require:{types:"./build/cjs/src/index.d.ts",default:"./build/cjs/src/index.js"}}},scripts:{lint:"gts check --no-inline-config",test:"c8 mocha build/esm/test","presystem-test":"npm run compile","system-test":"mocha build/esm/system-test --timeout 80000",compile:"tsc -b ./tsconfig.json ./tsconfig.cjs.json && node utils/enable-esm.mjs",fix:"gts fix",prepare:"npm run compile",pretest:"npm run compile",webpack:"webpack","prebrowser-test":"npm run compile","browser-test":"node build/browser-test/browser-test-runner.js",docs:"jsdoc -c .jsdoc.js","docs-test":"linkinator docs","predocs-test":"npm run docs","samples-test":"cd samples/ && npm link ../ && npm test && cd ../",prelint:"cd samples; npm link ../; npm install",clean:"gts clean"},repository:"googleapis/gaxios",keywords:["google"],engines:{node:">=18"},author:"Google, LLC",license:"Apache-2.0",devDependencies:{"@babel/plugin-proposal-private-methods":"^7.18.6","@types/cors":"^2.8.6","@types/express":"^5.0.0","@types/extend":"^3.0.1","@types/mocha":"^10.0.10","@types/multiparty":"4.2.1","@types/mv":"^2.1.0","@types/ncp":"^2.0.1","@types/node":"^22.0.0","@types/sinon":"^17.0.0","@types/tmp":"0.2.6",assert:"^2.0.0",browserify:"^17.0.0",c8:"^10.0.0",cors:"^2.8.5",express:"^5.0.0",gts:"^6.0.0","is-docker":"^3.0.0",jsdoc:"^4.0.0","jsdoc-fresh":"^4.0.0","jsdoc-region-tag":"^3.0.0",karma:"^6.0.0","karma-chrome-launcher":"^3.0.0","karma-coverage":"^2.0.0","karma-firefox-launcher":"^2.0.0","karma-mocha":"^2.0.0","karma-remap-coverage":"^0.1.5","karma-sourcemap-loader":"^0.4.0","karma-webpack":"^5.0.1",linkinator:"^6.1.2",mocha:"^11.1.0",multiparty:"^4.2.1",mv:"^2.1.1",ncp:"^2.0.0",nock:"^14.0.0-beta.13","null-loader":"^4.0.0","pack-n-play":"^3.0.0",puppeteer:"^24.0.0",sinon:"^21.0.0","stream-browserify":"^3.0.0",tmp:"0.2.5","ts-loader":"^9.5.2",typescript:"^5.8.3",webpack:"^5.35.0","webpack-cli":"^6.0.1"},dependencies:{extend:"^3.0.2","https-proxy-agent":"^7.0.1","node-fetch":"^3.3.2"}}});var Sh=V((KD,Ah)=>{"use strict";var Ob=Eh();Ah.exports={pkg:Ob}});var Lu=V(wt=>{"use strict";var kh=wt&&wt.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(wt,"__esModule",{value:!0});wt.GaxiosError=wt.GAXIOS_ERROR_SYMBOL=void 0;wt.defaultErrorRedactor=Th;var vh=kh(Nu()),Fb=kh(Sh()),Bu=Fb.default.pkg;wt.GAXIOS_ERROR_SYMBOL=Symbol.for(`${Bu.name}-gaxios-error`);var ju=class t extends Error{config;response;code;status;error;[wt.GAXIOS_ERROR_SYMBOL]=Bu.version;static[Symbol.hasInstance](e){return e&&typeof e=="object"&&wt.GAXIOS_ERROR_SYMBOL in e&&e[wt.GAXIOS_ERROR_SYMBOL]===Bu.version?!0:Function.prototype[Symbol.hasInstance].call(t,e)}constructor(e,r,n,s){if(super(e,{cause:s}),this.config=r,this.response=n,this.error=s instanceof Error?s:void 0,this.config=(0,vh.default)(!0,{},r),this.response&&(this.response.config=(0,vh.default)(!0,{},this.response.config)),this.response){try{this.response.data=Pb(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,r="The request failed"){let n=r;if(typeof e.data=="string"&&(n=e.data),e.data&&typeof e.data=="object"&&"error"in e.data&&e.data.error&&!e.ok){if(typeof e.data.error=="string")return{message:e.data.error,code:e.status,status:e.statusText};if(typeof e.data.error=="object"){n="message"in e.data.error&&typeof e.data.error.message=="string"?e.data.error.message:n;let s="status"in e.data.error&&typeof e.data.error.status=="string"?e.data.error.status:e.statusText,i="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 u=[];for(let c of e.data.error.errors)typeof c=="object"&&"message"in c&&typeof c.message=="string"&&u.push(c.message);return Object.assign({message:u.join(`
|
|
15
|
+
`)||n,code:i,status:s},e.data.error)}return Object.assign({message:n,code:i,status:s},e.data.error)}}return{message:n,code:e.status,status:e.statusText}}};wt.GaxiosError=ju;function Pb(t,e){switch(t){case"stream":return e;case"json":return JSON.parse(JSON.stringify(e));case"arraybuffer":return JSON.parse(Buffer.from(e).toString("utf8"));case"blob":return JSON.parse(e.text());default:return e}}function Th(t){let e="<<REDACTED> - See `errorRedactor` option in `gaxios` for configuration>.";function r(i){i&&i.forEach((u,c)=>{(/^authentication$/i.test(c)||/^authorization$/i.test(c)||/secret/i.test(c))&&i.set(c,e)})}function n(i,u){if(typeof i=="object"&&i!==null&&typeof i[u]=="string"){let c=i[u];(/grant_type=/i.test(c)||/assertion=/i.test(c)||/secret/i.test(c))&&(i[u]=e)}}function s(i){!i||typeof i!="object"||(i instanceof FormData||i instanceof URLSearchParams||"forEach"in i&&"set"in i?i.forEach((u,c)=>{(["grant_type","assertion"].includes(c)||/secret/.test(c))&&i.set(c,e)}):("grant_type"in i&&(i.grant_type=e),"assertion"in i&&(i.assertion=e),"client_secret"in i&&(i.client_secret=e)))}return t.config&&(r(t.config.headers),n(t.config,"data"),s(t.config.data),n(t.config,"body"),s(t.config.body),t.config.url.searchParams.has("token")&&t.config.url.searchParams.set("token",e),t.config.url.searchParams.has("client_secret")&&t.config.url.searchParams.set("client_secret",e)),t.response&&(Th({config:t.response.config}),r(t.response.headers),t.response.bodyUsed&&(n(t.response,"data"),s(t.response.data))),t}});var Rh=V(Mu=>{"use strict";Object.defineProperty(Mu,"__esModule",{value:!0});Mu.getRetryConfig=Ib;async function Ib(t){let e=Dh(t);if(!t||!t.config||!e&&!t.config.retry)return{shouldRetry:!1};e=e||{},e.currentRetryAttempt=e.currentRetryAttempt||0,e.retry=e.retry===void 0||e.retry===null?3:e.retry,e.httpMethodsToRetry=e.httpMethodsToRetry||["GET","HEAD","PUT","OPTIONS","DELETE"],e.noResponseRetries=e.noResponseRetries===void 0||e.noResponseRetries===null?2:e.noResponseRetries,e.retryDelayMultiplier=e.retryDelayMultiplier?e.retryDelayMultiplier:2,e.timeOfFirstRequest=e.timeOfFirstRequest?e.timeOfFirstRequest:Date.now(),e.totalTimeout=e.totalTimeout?e.totalTimeout:Number.MAX_SAFE_INTEGER,e.maxRetryDelay=e.maxRetryDelay?e.maxRetryDelay:Number.MAX_SAFE_INTEGER;let r=[[100,199],[408,408],[429,429],[500,599]];if(e.statusCodesToRetry=e.statusCodesToRetry||r,t.config.retryConfig=e,!await(e.shouldRetry||Nb)(t))return{shouldRetry:!1,config:t.config};let s=Bb(e);t.config.retryConfig.currentRetryAttempt+=1;let i=e.retryBackoff?e.retryBackoff(t,s):new Promise(u=>{setTimeout(u,s)});return e.onRetryAttempt&&await e.onRetryAttempt(t),await i,{shouldRetry:!0,config:t.config}}function Nb(t){let e=Dh(t);if(t.config.signal?.aborted&&t.code!=="TimeoutError"||t.code==="AbortError"||!e||e.retry===0||!t.response&&(e.currentRetryAttempt||0)>=e.noResponseRetries||!e.httpMethodsToRetry||!e.httpMethodsToRetry.includes(t.config.method?.toUpperCase()||"GET"))return!1;if(t.response&&t.response.status){let r=!1;for(let[n,s]of e.statusCodesToRetry){let i=t.response.status;if(i>=n&&i<=s){r=!0;break}}if(!r)return!1}return e.currentRetryAttempt=e.currentRetryAttempt||0,!(e.currentRetryAttempt>=e.retry)}function Dh(t){if(t&&t.config&&t.config.retryConfig)return t.config.retryConfig}function Bb(t){let r=(t.currentRetryAttempt?0:t.retryDelay??100)+(Math.pow(t.retryDelayMultiplier,t.currentRetryAttempt)-1)/2*1e3,n=t.totalTimeout-(Date.now()-t.timeOfFirstRequest);return Math.min(r,n,t.maxRetryDelay)}});var qu=V(Qo=>{"use strict";Object.defineProperty(Qo,"__esModule",{value:!0});Qo.GaxiosInterceptorManager=void 0;var Uu=class extends Set{};Qo.GaxiosInterceptorManager=Uu});var Oh=V((ZD,xh)=>{var Pn=1e3,In=Pn*60,Nn=In*60,an=Nn*24,jb=an*7,Lb=an*365.25;xh.exports=function(t,e){e=e||{};var r=typeof t;if(r==="string"&&t.length>0)return Mb(t);if(r==="number"&&isFinite(t))return e.long?qb(t):Ub(t);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(t))};function Mb(t){if(t=String(t),!(t.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(t);if(e){var r=parseFloat(e[1]),n=(e[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return r*Lb;case"weeks":case"week":case"w":return r*jb;case"days":case"day":case"d":return r*an;case"hours":case"hour":case"hrs":case"hr":case"h":return r*Nn;case"minutes":case"minute":case"mins":case"min":case"m":return r*In;case"seconds":case"second":case"secs":case"sec":case"s":return r*Pn;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return r;default:return}}}}function Ub(t){var e=Math.abs(t);return e>=an?Math.round(t/an)+"d":e>=Nn?Math.round(t/Nn)+"h":e>=In?Math.round(t/In)+"m":e>=Pn?Math.round(t/Pn)+"s":t+"ms"}function qb(t){var e=Math.abs(t);return e>=an?Xo(t,e,an,"day"):e>=Nn?Xo(t,e,Nn,"hour"):e>=In?Xo(t,e,In,"minute"):e>=Pn?Xo(t,e,Pn,"second"):t+" ms"}function Xo(t,e,r,n){var s=e>=r*1.5;return Math.round(t/r)+" "+n+(s?"s":"")}});var $u=V((eR,Fh)=>{function $b(t){r.debug=r,r.default=r,r.coerce=l,r.disable=u,r.enable=s,r.enabled=c,r.humanize=Oh(),r.destroy=h,Object.keys(t).forEach(d=>{r[d]=t[d]}),r.names=[],r.skips=[],r.formatters={};function e(d){let p=0;for(let w=0;w<d.length;w++)p=(p<<5)-p+d.charCodeAt(w),p|=0;return r.colors[Math.abs(p)%r.colors.length]}r.selectColor=e;function r(d){let p,w=null,T,S;function y(...g){if(!y.enabled)return;let m=y,v=Number(new Date),b=v-(p||v);m.diff=b,m.prev=p,m.curr=v,p=v,g[0]=r.coerce(g[0]),typeof g[0]!="string"&&g.unshift("%O");let A=0;g[0]=g[0].replace(/%([a-zA-Z%])/g,(F,$)=>{if(F==="%%")return"%";A++;let J=r.formatters[$];if(typeof J=="function"){let M=g[A];F=J.call(m,M),g.splice(A,1),A--}return F}),r.formatArgs.call(m,g),(m.log||r.log).apply(m,g)}return y.namespace=d,y.useColors=r.useColors(),y.color=r.selectColor(d),y.extend=n,y.destroy=r.destroy,Object.defineProperty(y,"enabled",{enumerable:!0,configurable:!1,get:()=>w!==null?w:(T!==r.namespaces&&(T=r.namespaces,S=r.enabled(d)),S),set:g=>{w=g}}),typeof r.init=="function"&&r.init(y),y}function n(d,p){let w=r(this.namespace+(typeof p>"u"?":":p)+d);return w.log=this.log,w}function s(d){r.save(d),r.namespaces=d,r.names=[],r.skips=[];let p=(typeof d=="string"?d:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(let w of p)w[0]==="-"?r.skips.push(w.slice(1)):r.names.push(w)}function i(d,p){let w=0,T=0,S=-1,y=0;for(;w<d.length;)if(T<p.length&&(p[T]===d[w]||p[T]==="*"))p[T]==="*"?(S=T,y=w,T++):(w++,T++);else if(S!==-1)T=S+1,y++,w=y;else return!1;for(;T<p.length&&p[T]==="*";)T++;return T===p.length}function u(){let d=[...r.names,...r.skips.map(p=>"-"+p)].join(",");return r.enable(""),d}function c(d){for(let p of r.skips)if(i(d,p))return!1;for(let p of r.names)if(i(d,p))return!0;return!1}function l(d){return d instanceof Error?d.stack||d.message:d}function h(){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 r.enable(r.load()),r}Fh.exports=$b});var Ph=V((st,Zo)=>{st.formatArgs=Hb;st.save=Wb;st.load=Gb;st.useColors=zb;st.storage=Jb();st.destroy=(()=>{let t=!1;return()=>{t||(t=!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`."))}})();st.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 zb(){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 t;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&&(t=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(t[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function Hb(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+Zo.exports.humanize(this.diff),!this.useColors)return;let e="color: "+this.color;t.splice(1,0,e,"color: inherit");let r=0,n=0;t[0].replace(/%[a-zA-Z%]/g,s=>{s!=="%%"&&(r++,s==="%c"&&(n=r))}),t.splice(n,0,e)}st.log=console.debug||console.log||(()=>{});function Wb(t){try{t?st.storage.setItem("debug",t):st.storage.removeItem("debug")}catch{}}function Gb(){let t;try{t=st.storage.getItem("debug")||st.storage.getItem("DEBUG")}catch{}return!t&&typeof process<"u"&&"env"in process&&(t=process.env.DEBUG),t}function Jb(){try{return localStorage}catch{}}Zo.exports=$u()(st);var{formatters:Vb}=Zo.exports;Vb.j=function(t){try{return JSON.stringify(t)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var Nh=V((tR,Ih)=>{"use strict";Ih.exports=(t,e=process.argv)=>{let r=t.startsWith("-")?"":t.length===1?"-":"--",n=e.indexOf(r+t),s=e.indexOf("--");return n!==-1&&(s===-1||n<s)}});var Lh=V((rR,jh)=>{"use strict";var Kb=X("os"),Bh=X("tty"),Et=Nh(),{env:He}=process,jr;Et("no-color")||Et("no-colors")||Et("color=false")||Et("color=never")?jr=0:(Et("color")||Et("colors")||Et("color=true")||Et("color=always"))&&(jr=1);"FORCE_COLOR"in He&&(He.FORCE_COLOR==="true"?jr=1:He.FORCE_COLOR==="false"?jr=0:jr=He.FORCE_COLOR.length===0?1:Math.min(parseInt(He.FORCE_COLOR,10),3));function zu(t){return t===0?!1:{level:t,hasBasic:!0,has256:t>=2,has16m:t>=3}}function Hu(t,e){if(jr===0)return 0;if(Et("color=16m")||Et("color=full")||Et("color=truecolor"))return 3;if(Et("color=256"))return 2;if(t&&!e&&jr===void 0)return 0;let r=jr||0;if(He.TERM==="dumb")return r;if(process.platform==="win32"){let n=Kb.release().split(".");return Number(n[0])>=10&&Number(n[2])>=10586?Number(n[2])>=14931?3:2:1}if("CI"in He)return["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE"].some(n=>n in He)||He.CI_NAME==="codeship"?1:r;if("TEAMCITY_VERSION"in He)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(He.TEAMCITY_VERSION)?1:0;if(He.COLORTERM==="truecolor")return 3;if("TERM_PROGRAM"in He){let n=parseInt((He.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(He.TERM_PROGRAM){case"iTerm.app":return n>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(He.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(He.TERM)||"COLORTERM"in He?1:r}function Yb(t){let e=Hu(t,t&&t.isTTY);return zu(e)}jh.exports={supportsColor:Yb,stdout:zu(Hu(!0,Bh.isatty(1))),stderr:zu(Hu(!0,Bh.isatty(2)))}});var Uh=V((We,ti)=>{var Qb=X("tty"),ei=X("util");We.init=sC;We.log=tC;We.formatArgs=Zb;We.save=rC;We.load=nC;We.useColors=Xb;We.destroy=ei.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");We.colors=[6,2,3,4,5,1];try{let t=Lh();t&&(t.stderr||t).level>=2&&(We.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{}We.inspectOpts=Object.keys(process.env).filter(t=>/^debug_/i.test(t)).reduce((t,e)=>{let r=e.substring(6).toLowerCase().replace(/_([a-z])/g,(s,i)=>i.toUpperCase()),n=process.env[e];return/^(yes|on|true|enabled)$/i.test(n)?n=!0:/^(no|off|false|disabled)$/i.test(n)?n=!1:n==="null"?n=null:n=Number(n),t[r]=n,t},{});function Xb(){return"colors"in We.inspectOpts?!!We.inspectOpts.colors:Qb.isatty(process.stderr.fd)}function Zb(t){let{namespace:e,useColors:r}=this;if(r){let n=this.color,s="\x1B[3"+(n<8?n:"8;5;"+n),i=` ${s};1m${e} \x1B[0m`;t[0]=i+t[0].split(`
|
|
16
16
|
`).join(`
|
|
17
|
-
`+i),t.push(s+"m+"+
|
|
18
|
-
`)}function
|
|
19
|
-
`).map(e=>e.trim()).join(" ")};
|
|
20
|
-
`).some(n=>n.indexOf("(https.js:")!==-1||n.indexOf("node:https:")!==-1)}incrementSockets(e){if(this.maxSockets===1/0&&this.maxTotalSockets===1/0)return null;this.sockets[e]||(this.sockets[e]=[]);let r=new
|
|
17
|
+
`+i),t.push(s+"m+"+ti.exports.humanize(this.diff)+"\x1B[0m")}else t[0]=eC()+e+" "+t[0]}function eC(){return We.inspectOpts.hideDate?"":new Date().toISOString()+" "}function tC(...t){return process.stderr.write(ei.formatWithOptions(We.inspectOpts,...t)+`
|
|
18
|
+
`)}function rC(t){t?process.env.DEBUG=t:delete process.env.DEBUG}function nC(){return process.env.DEBUG}function sC(t){t.inspectOpts={};let e=Object.keys(We.inspectOpts);for(let r=0;r<e.length;r++)t.inspectOpts[e[r]]=We.inspectOpts[e[r]]}ti.exports=$u()(We);var{formatters:Mh}=ti.exports;Mh.o=function(t){return this.inspectOpts.colors=this.useColors,ei.inspect(t,this.inspectOpts).split(`
|
|
19
|
+
`).map(e=>e.trim()).join(" ")};Mh.O=function(t){return this.inspectOpts.colors=this.useColors,ei.inspect(t,this.inspectOpts)}});var Gu=V((nR,Wu)=>{typeof process>"u"||process.type==="renderer"||process.browser===!0||process.__nwjs?Wu.exports=Ph():Wu.exports=Uh()});var zh=V(ot=>{"use strict";var oC=ot&&ot.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,s)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),iC=ot&&ot.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),qh=ot&&ot.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&oC(e,t,r);return iC(e,t),e};Object.defineProperty(ot,"__esModule",{value:!0});ot.req=ot.json=ot.toBuffer=void 0;var aC=qh(X("http")),uC=qh(X("https"));async function $h(t){let e=0,r=[];for await(let n of t)e+=n.length,r.push(n);return Buffer.concat(r,e)}ot.toBuffer=$h;async function cC(t){let r=(await $h(t)).toString("utf8");try{return JSON.parse(r)}catch(n){let s=n;throw s.message+=` (input: ${r})`,s}}ot.json=cC;function lC(t,e={}){let n=((typeof t=="string"?t:t.href).startsWith("https:")?uC:aC).request(t,e),s=new Promise((i,u)=>{n.once("response",i).once("error",u).end()});return n.then=s.then.bind(s),n}ot.req=lC});var Jh=V(lt=>{"use strict";var Wh=lt&<.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,s)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),dC=lt&<.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),Gh=lt&<.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Wh(e,t,r);return dC(e,t),e},fC=lt&<.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&Wh(e,t,r)};Object.defineProperty(lt,"__esModule",{value:!0});lt.Agent=void 0;var hC=Gh(X("net")),Hh=Gh(X("http")),pC=X("https");fC(zh(),lt);var Vt=Symbol("AgentBaseInternalState"),Ju=class extends Hh.Agent{constructor(e){super(e),this[Vt]={}}isSecureEndpoint(e){if(e){if(typeof e.secureEndpoint=="boolean")return e.secureEndpoint;if(typeof e.protocol=="string")return e.protocol==="https:"}let{stack:r}=new Error;return typeof r!="string"?!1:r.split(`
|
|
20
|
+
`).some(n=>n.indexOf("(https.js:")!==-1||n.indexOf("node:https:")!==-1)}incrementSockets(e){if(this.maxSockets===1/0&&this.maxTotalSockets===1/0)return null;this.sockets[e]||(this.sockets[e]=[]);let r=new hC.Socket({writable:!1});return this.sockets[e].push(r),this.totalSocketCount++,r}decrementSockets(e,r){if(!this.sockets[e]||r===null)return;let n=this.sockets[e],s=n.indexOf(r);s!==-1&&(n.splice(s,1),this.totalSocketCount--,n.length===0&&delete this.sockets[e])}getName(e){return this.isSecureEndpoint(e)?pC.Agent.prototype.getName.call(this,e):super.getName(e)}createSocket(e,r,n){let s={...r,secureEndpoint:this.isSecureEndpoint(r)},i=this.getName(s),u=this.incrementSockets(i);Promise.resolve().then(()=>this.connect(e,s)).then(c=>{if(this.decrementSockets(i,u),c instanceof Hh.Agent)try{return c.addRequest(e,s)}catch(l){return n(l)}this[Vt].currentSocket=c,super.createSocket(e,r,n)},c=>{this.decrementSockets(i,u),n(c)})}createConnection(){let e=this[Vt].currentSocket;if(this[Vt].currentSocket=void 0,!e)throw new Error("No socket was returned in the `connect()` function");return e}get defaultPort(){return this[Vt].defaultPort??(this.protocol==="https:"?443:80)}set defaultPort(e){this[Vt]&&(this[Vt].defaultPort=e)}get protocol(){return this[Vt].protocol??(this.isSecureEndpoint()?"https:":"http:")}set protocol(e){this[Vt]&&(this[Vt].protocol=e)}};lt.Agent=Ju});var Vh=V(Bn=>{"use strict";var mC=Bn&&Bn.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Bn,"__esModule",{value:!0});Bn.parseProxyResponse=void 0;var gC=mC(Gu()),ri=(0,gC.default)("https-proxy-agent:parse-proxy-response");function yC(t){return new Promise((e,r)=>{let n=0,s=[];function i(){let d=t.read();d?h(d):t.once("readable",i)}function u(){t.removeListener("end",c),t.removeListener("error",l),t.removeListener("readable",i)}function c(){u(),ri("onend"),r(new Error("Proxy connection ended before receiving CONNECT response"))}function l(d){u(),ri("onerror %o",d),r(d)}function h(d){s.push(d),n+=d.length;let p=Buffer.concat(s,n),w=p.indexOf(`\r
|
|
21
21
|
\r
|
|
22
|
-
`);if(
|
|
23
|
-
`),S=
|
|
24
|
-
`;if(n.username||n.password){let
|
|
25
|
-
`;let l=(0,
|
|
26
|
-
`);let{connect:h,buffered:d}=await l;if(e.emit("proxyConnect",h),this.emit("proxyConnect",h,e),h.statusCode===200)return e.once("socket",sC),r.secureEndpoint?(ws("Upgrading socket connection to TLS"),Ih.connect({...Bh(Nh(r),"host","path","port"),socket:s})):s;s.destroy();let p=new Zo.Socket({writable:!1});return p.readable=!0,e.once("socket",A=>{ws("Replaying proxy buffer for failed request"),(0,Zb.default)(A.listenerCount("data")>0),A.push(d),A.push(null)}),p}};ei.protocols=["http","https"];At.HttpsProxyAgent=ei;function sC(t){t.resume()}function Bh(t,...e){let r={},n;for(n in t)e.includes(n)||(r[n]=t[n]);return r}});function oC(t){if(!/^data:/i.test(t))throw new TypeError('`uri` does not appear to be a Data URI (must begin with "data:")');t=t.replace(/\r?\n/g,"");let e=t.indexOf(",");if(e===-1||e<=4)throw new TypeError("malformed data: URI");let r=t.substring(5,e).split(";"),n="",s=!1,i=r[0]||"text/plain",u=i;for(let d=1;d<r.length;d++)r[d]==="base64"?s=!0:r[d]&&(u+=`;${r[d]}`,r[d].indexOf("charset=")===0&&(n=r[d].substring(8)));!r[0]&&!n.length&&(u+=";charset=US-ASCII",n="US-ASCII");let c=s?"base64":"ascii",l=unescape(t.substring(e+1)),h=Buffer.from(l,c);return h.type=i,h.typeFull=u,h.charset=n,h}var Uh,qh=je(()=>{Uh=oC});var zh=V((ti,$h)=>{(function(t,e){typeof ti=="object"&&typeof $h<"u"?e(ti):typeof define=="function"&&define.amd?define(["exports"],e):(t=typeof globalThis<"u"?globalThis:t||self,e(t.WebStreamsPolyfill={}))})(ti,(function(t){"use strict";function e(){}function r(o){return typeof o=="object"&&o!==null||typeof o=="function"}let n=e;function s(o,a){try{Object.defineProperty(o,"name",{value:a,configurable:!0})}catch{}}let i=Promise,u=Promise.prototype.then,c=Promise.reject.bind(i);function l(o){return new i(o)}function h(o){return l(a=>a(o))}function d(o){return c(o)}function p(o,a,f){return u.call(o,a,f)}function A(o,a,f){p(p(o,a,f),void 0,n)}function v(o,a){A(o,a)}function S(o,a){A(o,void 0,a)}function y(o,a,f){return p(o,a,f)}function g(o){p(o,void 0,n)}let m=o=>{if(typeof queueMicrotask=="function")m=queueMicrotask;else{let a=h(void 0);m=f=>p(a,f)}return m(o)};function k(o,a,f){if(typeof o!="function")throw new TypeError("Argument is not a function");return Function.prototype.apply.call(o,a,f)}function b(o,a,f){try{return h(k(o,a,f))}catch(C){return d(C)}}let E=16384;class R{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(a){let f=this._back,C=f;f._elements.length===E-1&&(C={_elements:[],_next:void 0}),f._elements.push(a),C!==f&&(this._back=C,f._next=C),++this._size}shift(){let a=this._front,f=a,C=this._cursor,D=C+1,L=a._elements,q=L[C];return D===E&&(f=a._next,D=0),--this._size,this._cursor=D,a!==f&&(this._front=f),L[C]=void 0,q}forEach(a){let f=this._cursor,C=this._front,D=C._elements;for(;(f!==D.length||C._next!==void 0)&&!(f===D.length&&(C=C._next,D=C._elements,f=0,D.length===0));)a(D[f]),++f}peek(){let a=this._front,f=this._cursor;return a._elements[f]}}let F=Symbol("[[AbortSteps]]"),$=Symbol("[[ErrorSteps]]"),J=Symbol("[[CancelSteps]]"),M=Symbol("[[PullSteps]]"),X=Symbol("[[ReleaseSteps]]");function ue(o,a){o._ownerReadableStream=a,a._reader=o,a._state==="readable"?Ae(o):a._state==="closed"?me(o):oe(o,a._storedError)}function re(o,a){let f=o._ownerReadableStream;return Pt(f,a)}function fe(o){let a=o._ownerReadableStream;a._state==="readable"?G(o,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")):K(o,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")),a._readableStreamController[X](),a._reader=void 0,o._ownerReadableStream=void 0}function pe(o){return new TypeError("Cannot "+o+" a stream using a released reader")}function Ae(o){o._closedPromise=l((a,f)=>{o._closedPromise_resolve=a,o._closedPromise_reject=f})}function oe(o,a){Ae(o),G(o,a)}function me(o){Ae(o),ae(o)}function G(o,a){o._closedPromise_reject!==void 0&&(g(o._closedPromise),o._closedPromise_reject(a),o._closedPromise_resolve=void 0,o._closedPromise_reject=void 0)}function K(o,a){oe(o,a)}function ae(o){o._closedPromise_resolve!==void 0&&(o._closedPromise_resolve(void 0),o._closedPromise_resolve=void 0,o._closedPromise_reject=void 0)}let qe=Number.isFinite||function(o){return typeof o=="number"&&isFinite(o)},De=Math.trunc||function(o){return o<0?Math.ceil(o):Math.floor(o)};function W(o){return typeof o=="object"||typeof o=="function"}function le(o,a){if(o!==void 0&&!W(o))throw new TypeError(`${a} is not an object.`)}function _e(o,a){if(typeof o!="function")throw new TypeError(`${a} is not a function.`)}function xt(o){return typeof o=="object"&&o!==null||typeof o=="function"}function Re(o,a){if(!xt(o))throw new TypeError(`${a} is not an object.`)}function Be(o,a,f){if(o===void 0)throw new TypeError(`Parameter ${a} is required in '${f}'.`)}function _(o,a,f){if(o===void 0)throw new TypeError(`${a} is required in '${f}'.`)}function w(o){return Number(o)}function T(o){return o===0?0:o}function B(o){return T(De(o))}function x(o,a){let C=Number.MAX_SAFE_INTEGER,D=Number(o);if(D=T(D),!qe(D))throw new TypeError(`${a} is not a finite number`);if(D=B(D),D<0||D>C)throw new TypeError(`${a} is outside the accepted range of 0 to ${C}, inclusive`);return!qe(D)||D===0?0:D}function I(o,a){if(!Rr(o))throw new TypeError(`${a} is not a ReadableStream.`)}function U(o){return new z(o)}function O(o,a){o._reader._readRequests.push(a)}function P(o,a,f){let D=o._reader._readRequests.shift();f?D._closeSteps():D._chunkSteps(a)}function j(o){return o._reader._readRequests.length}function N(o){let a=o._reader;return!(a===void 0||!Z(a))}class z{constructor(a){if(Be(a,1,"ReadableStreamDefaultReader"),I(a,"First parameter"),Or(a))throw new TypeError("This stream has already been locked for exclusive reading by another reader");ue(this,a),this._readRequests=new R}get closed(){return Z(this)?this._closedPromise:d(Ne("closed"))}cancel(a=void 0){return Z(this)?this._ownerReadableStream===void 0?d(pe("cancel")):re(this,a):d(Ne("cancel"))}read(){if(!Z(this))return d(Ne("read"));if(this._ownerReadableStream===void 0)return d(pe("read from"));let a,f,C=l((L,q)=>{a=L,f=q});return ee(this,{_chunkSteps:L=>a({value:L,done:!1}),_closeSteps:()=>a({value:void 0,done:!0}),_errorSteps:L=>f(L)}),C}releaseLock(){if(!Z(this))throw Ne("releaseLock");this._ownerReadableStream!==void 0&&Ee(this)}}Object.defineProperties(z.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),s(z.prototype.cancel,"cancel"),s(z.prototype.read,"read"),s(z.prototype.releaseLock,"releaseLock"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(z.prototype,Symbol.toStringTag,{value:"ReadableStreamDefaultReader",configurable:!0});function Z(o){return!r(o)||!Object.prototype.hasOwnProperty.call(o,"_readRequests")?!1:o instanceof z}function ee(o,a){let f=o._ownerReadableStream;f._disturbed=!0,f._state==="closed"?a._closeSteps():f._state==="errored"?a._errorSteps(f._storedError):f._readableStreamController[M](a)}function Ee(o){fe(o);let a=new TypeError("Reader was released");Fe(o,a)}function Fe(o,a){let f=o._readRequests;o._readRequests=new R,f.forEach(C=>{C._errorSteps(a)})}function Ne(o){return new TypeError(`ReadableStreamDefaultReader.prototype.${o} can only be used on a ReadableStreamDefaultReader`)}let we=Object.getPrototypeOf(Object.getPrototypeOf(async function*(){}).prototype);class Se{constructor(a,f){this._ongoingPromise=void 0,this._isFinished=!1,this._reader=a,this._preventCancel=f}next(){let a=()=>this._nextSteps();return this._ongoingPromise=this._ongoingPromise?y(this._ongoingPromise,a,a):a(),this._ongoingPromise}return(a){let f=()=>this._returnSteps(a);return this._ongoingPromise?y(this._ongoingPromise,f,f):f()}_nextSteps(){if(this._isFinished)return Promise.resolve({value:void 0,done:!0});let a=this._reader,f,C,D=l((q,Y)=>{f=q,C=Y});return ee(a,{_chunkSteps:q=>{this._ongoingPromise=void 0,m(()=>f({value:q,done:!1}))},_closeSteps:()=>{this._ongoingPromise=void 0,this._isFinished=!0,fe(a),f({value:void 0,done:!0})},_errorSteps:q=>{this._ongoingPromise=void 0,this._isFinished=!0,fe(a),C(q)}}),D}_returnSteps(a){if(this._isFinished)return Promise.resolve({value:a,done:!0});this._isFinished=!0;let f=this._reader;if(!this._preventCancel){let C=re(f,a);return fe(f),y(C,()=>({value:a,done:!0}))}return fe(f),h({value:a,done:!0})}}let Me={next(){return pn(this)?this._asyncIteratorImpl.next():d(mn("next"))},return(o){return pn(this)?this._asyncIteratorImpl.return(o):d(mn("return"))}};Object.setPrototypeOf(Me,we);function hn(o,a){let f=U(o),C=new Se(f,a),D=Object.create(Me);return D._asyncIteratorImpl=C,D}function pn(o){if(!r(o)||!Object.prototype.hasOwnProperty.call(o,"_asyncIteratorImpl"))return!1;try{return o._asyncIteratorImpl instanceof Se}catch{return!1}}function mn(o){return new TypeError(`ReadableStreamAsyncIterator.${o} can only be used on a ReadableSteamAsyncIterator`)}let ut=Number.isNaN||function(o){return o!==o};var ir,Ke,Ue;function ke(o){return o.slice()}function Df(o,a,f,C,D){new Uint8Array(o).set(new Uint8Array(f,C,D),a)}let ar=o=>(typeof o.transfer=="function"?ar=a=>a.transfer():typeof structuredClone=="function"?ar=a=>structuredClone(a,{transfer:[a]}):ar=a=>a,ar(o)),kr=o=>(typeof o.detached=="boolean"?kr=a=>a.detached:kr=a=>a.byteLength===0,kr(o));function vf(o,a,f){if(o.slice)return o.slice(a,f);let C=f-a,D=new ArrayBuffer(C);return Df(D,0,o,a,C),D}function io(o,a){let f=o[a];if(f!=null){if(typeof f!="function")throw new TypeError(`${String(a)} is not a function`);return f}}function Xy(o){let a={[Symbol.iterator]:()=>o.iterator},f=(async function*(){return yield*a})(),C=f.next;return{iterator:f,nextMethod:C,done:!1}}let qa=(Ue=(ir=Symbol.asyncIterator)!==null&&ir!==void 0?ir:(Ke=Symbol.for)===null||Ke===void 0?void 0:Ke.call(Symbol,"Symbol.asyncIterator"))!==null&&Ue!==void 0?Ue:"@@asyncIterator";function Rf(o,a="sync",f){if(f===void 0)if(a==="async"){if(f=io(o,qa),f===void 0){let L=io(o,Symbol.iterator),q=Rf(o,"sync",L);return Xy(q)}}else f=io(o,Symbol.iterator);if(f===void 0)throw new TypeError("The object is not iterable");let C=k(f,o,[]);if(!r(C))throw new TypeError("The iterator method must return an object");let D=C.next;return{iterator:C,nextMethod:D,done:!1}}function Qy(o){let a=k(o.nextMethod,o.iterator,[]);if(!r(a))throw new TypeError("The iterator.next() method must return an object");return a}function Zy(o){return!!o.done}function e0(o){return o.value}function t0(o){return!(typeof o!="number"||ut(o)||o<0)}function Of(o){let a=vf(o.buffer,o.byteOffset,o.byteOffset+o.byteLength);return new Uint8Array(a)}function $a(o){let a=o._queue.shift();return o._queueTotalSize-=a.size,o._queueTotalSize<0&&(o._queueTotalSize=0),a.value}function za(o,a,f){if(!t0(f)||f===1/0)throw new RangeError("Size must be a finite, non-NaN, non-negative number.");o._queue.push({value:a,size:f}),o._queueTotalSize+=f}function r0(o){return o._queue.peek().value}function Tr(o){o._queue=new R,o._queueTotalSize=0}function xf(o){return o===DataView}function n0(o){return xf(o.constructor)}function s0(o){return xf(o)?1:o.BYTES_PER_ELEMENT}class Jr{constructor(){throw new TypeError("Illegal constructor")}get view(){if(!Ha(this))throw Ka("view");return this._view}respond(a){if(!Ha(this))throw Ka("respond");if(Be(a,1,"respond"),a=x(a,"First parameter"),this._associatedReadableByteStreamController===void 0)throw new TypeError("This BYOB request has been invalidated");if(kr(this._view.buffer))throw new TypeError("The BYOB request's buffer has been detached and so cannot be used as a response");lo(this._associatedReadableByteStreamController,a)}respondWithNewView(a){if(!Ha(this))throw Ka("respondWithNewView");if(Be(a,1,"respondWithNewView"),!ArrayBuffer.isView(a))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(kr(a.buffer))throw new TypeError("The given view's buffer has been detached and so cannot be used as a response");fo(this._associatedReadableByteStreamController,a)}}Object.defineProperties(Jr.prototype,{respond:{enumerable:!0},respondWithNewView:{enumerable:!0},view:{enumerable:!0}}),s(Jr.prototype.respond,"respond"),s(Jr.prototype.respondWithNewView,"respondWithNewView"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Jr.prototype,Symbol.toStringTag,{value:"ReadableStreamBYOBRequest",configurable:!0});class ur{constructor(){throw new TypeError("Illegal constructor")}get byobRequest(){if(!Vr(this))throw fs("byobRequest");return Va(this)}get desiredSize(){if(!Vr(this))throw fs("desiredSize");return qf(this)}close(){if(!Vr(this))throw fs("close");if(this._closeRequested)throw new TypeError("The stream has already been closed; do not close it again!");let a=this._controlledReadableByteStream._state;if(a!=="readable")throw new TypeError(`The stream (in ${a} state) is not in the readable state and cannot be closed`);ls(this)}enqueue(a){if(!Vr(this))throw fs("enqueue");if(Be(a,1,"enqueue"),!ArrayBuffer.isView(a))throw new TypeError("chunk must be an array buffer view");if(a.byteLength===0)throw new TypeError("chunk must have non-zero byteLength");if(a.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 f=this._controlledReadableByteStream._state;if(f!=="readable")throw new TypeError(`The stream (in ${f} state) is not in the readable state and cannot be enqueued to`);co(this,a)}error(a=void 0){if(!Vr(this))throw fs("error");bt(this,a)}[J](a){Ff(this),Tr(this);let f=this._cancelAlgorithm(a);return uo(this),f}[M](a){let f=this._controlledReadableByteStream;if(this._queueTotalSize>0){Uf(this,a);return}let C=this._autoAllocateChunkSize;if(C!==void 0){let D;try{D=new ArrayBuffer(C)}catch(q){a._errorSteps(q);return}let L={buffer:D,bufferByteLength:C,byteOffset:0,byteLength:C,bytesFilled:0,minimumFill:1,elementSize:1,viewConstructor:Uint8Array,readerType:"default"};this._pendingPullIntos.push(L)}O(f,a),Kr(this)}[X](){if(this._pendingPullIntos.length>0){let a=this._pendingPullIntos.peek();a.readerType="none",this._pendingPullIntos=new R,this._pendingPullIntos.push(a)}}}Object.defineProperties(ur.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},byobRequest:{enumerable:!0},desiredSize:{enumerable:!0}}),s(ur.prototype.close,"close"),s(ur.prototype.enqueue,"enqueue"),s(ur.prototype.error,"error"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(ur.prototype,Symbol.toStringTag,{value:"ReadableByteStreamController",configurable:!0});function Vr(o){return!r(o)||!Object.prototype.hasOwnProperty.call(o,"_controlledReadableByteStream")?!1:o instanceof ur}function Ha(o){return!r(o)||!Object.prototype.hasOwnProperty.call(o,"_associatedReadableByteStreamController")?!1:o instanceof Jr}function Kr(o){if(!c0(o))return;if(o._pulling){o._pullAgain=!0;return}o._pulling=!0;let f=o._pullAlgorithm();A(f,()=>(o._pulling=!1,o._pullAgain&&(o._pullAgain=!1,Kr(o)),null),C=>(bt(o,C),null))}function Ff(o){Ga(o),o._pendingPullIntos=new R}function Wa(o,a){let f=!1;o._state==="closed"&&(f=!0);let C=Pf(a);a.readerType==="default"?P(o,C,f):m0(o,C,f)}function Pf(o){let a=o.bytesFilled,f=o.elementSize;return new o.viewConstructor(o.buffer,o.byteOffset,a/f)}function ao(o,a,f,C){o._queue.push({buffer:a,byteOffset:f,byteLength:C}),o._queueTotalSize+=C}function If(o,a,f,C){let D;try{D=vf(a,f,f+C)}catch(L){throw bt(o,L),L}ao(o,D,0,C)}function Nf(o,a){a.bytesFilled>0&&If(o,a.buffer,a.byteOffset,a.bytesFilled),gn(o)}function Bf(o,a){let f=Math.min(o._queueTotalSize,a.byteLength-a.bytesFilled),C=a.bytesFilled+f,D=f,L=!1,q=C%a.elementSize,Y=C-q;Y>=a.minimumFill&&(D=Y-a.bytesFilled,L=!0);let ce=o._queue;for(;D>0;){let ne=ce.peek(),de=Math.min(D,ne.byteLength),ye=a.byteOffset+a.bytesFilled;Df(a.buffer,ye,ne.buffer,ne.byteOffset,de),ne.byteLength===de?ce.shift():(ne.byteOffset+=de,ne.byteLength-=de),o._queueTotalSize-=de,jf(o,de,a),D-=de}return L}function jf(o,a,f){f.bytesFilled+=a}function Lf(o){o._queueTotalSize===0&&o._closeRequested?(uo(o),ys(o._controlledReadableByteStream)):Kr(o)}function Ga(o){o._byobRequest!==null&&(o._byobRequest._associatedReadableByteStreamController=void 0,o._byobRequest._view=null,o._byobRequest=null)}function Ja(o){for(;o._pendingPullIntos.length>0;){if(o._queueTotalSize===0)return;let a=o._pendingPullIntos.peek();Bf(o,a)&&(gn(o),Wa(o._controlledReadableByteStream,a))}}function o0(o){let a=o._controlledReadableByteStream._reader;for(;a._readRequests.length>0;){if(o._queueTotalSize===0)return;let f=a._readRequests.shift();Uf(o,f)}}function i0(o,a,f,C){let D=o._controlledReadableByteStream,L=a.constructor,q=s0(L),{byteOffset:Y,byteLength:ce}=a,ne=f*q,de;try{de=ar(a.buffer)}catch(ve){C._errorSteps(ve);return}let ye={buffer:de,bufferByteLength:de.byteLength,byteOffset:Y,byteLength:ce,bytesFilled:0,minimumFill:ne,elementSize:q,viewConstructor:L,readerType:"byob"};if(o._pendingPullIntos.length>0){o._pendingPullIntos.push(ye),Hf(D,C);return}if(D._state==="closed"){let ve=new L(ye.buffer,ye.byteOffset,0);C._closeSteps(ve);return}if(o._queueTotalSize>0){if(Bf(o,ye)){let ve=Pf(ye);Lf(o),C._chunkSteps(ve);return}if(o._closeRequested){let ve=new TypeError("Insufficient bytes to fill elements in the given buffer");bt(o,ve),C._errorSteps(ve);return}}o._pendingPullIntos.push(ye),Hf(D,C),Kr(o)}function a0(o,a){a.readerType==="none"&&gn(o);let f=o._controlledReadableByteStream;if(Ya(f))for(;Wf(f)>0;){let C=gn(o);Wa(f,C)}}function u0(o,a,f){if(jf(o,a,f),f.readerType==="none"){Nf(o,f),Ja(o);return}if(f.bytesFilled<f.minimumFill)return;gn(o);let C=f.bytesFilled%f.elementSize;if(C>0){let D=f.byteOffset+f.bytesFilled;If(o,f.buffer,D-C,C)}f.bytesFilled-=C,Wa(o._controlledReadableByteStream,f),Ja(o)}function Mf(o,a){let f=o._pendingPullIntos.peek();Ga(o),o._controlledReadableByteStream._state==="closed"?a0(o,f):u0(o,a,f),Kr(o)}function gn(o){return o._pendingPullIntos.shift()}function c0(o){let a=o._controlledReadableByteStream;return a._state!=="readable"||o._closeRequested||!o._started?!1:!!(N(a)&&j(a)>0||Ya(a)&&Wf(a)>0||qf(o)>0)}function uo(o){o._pullAlgorithm=void 0,o._cancelAlgorithm=void 0}function ls(o){let a=o._controlledReadableByteStream;if(!(o._closeRequested||a._state!=="readable")){if(o._queueTotalSize>0){o._closeRequested=!0;return}if(o._pendingPullIntos.length>0){let f=o._pendingPullIntos.peek();if(f.bytesFilled%f.elementSize!==0){let C=new TypeError("Insufficient bytes to fill elements in the given buffer");throw bt(o,C),C}}uo(o),ys(a)}}function co(o,a){let f=o._controlledReadableByteStream;if(o._closeRequested||f._state!=="readable")return;let{buffer:C,byteOffset:D,byteLength:L}=a;if(kr(C))throw new TypeError("chunk's buffer is detached and so cannot be enqueued");let q=ar(C);if(o._pendingPullIntos.length>0){let Y=o._pendingPullIntos.peek();if(kr(Y.buffer))throw new TypeError("The BYOB request's buffer has been detached and so cannot be filled with an enqueued chunk");Ga(o),Y.buffer=ar(Y.buffer),Y.readerType==="none"&&Nf(o,Y)}if(N(f))if(o0(o),j(f)===0)ao(o,q,D,L);else{o._pendingPullIntos.length>0&&gn(o);let Y=new Uint8Array(q,D,L);P(f,Y,!1)}else Ya(f)?(ao(o,q,D,L),Ja(o)):ao(o,q,D,L);Kr(o)}function bt(o,a){let f=o._controlledReadableByteStream;f._state==="readable"&&(Ff(o),Tr(o),uo(o),md(f,a))}function Uf(o,a){let f=o._queue.shift();o._queueTotalSize-=f.byteLength,Lf(o);let C=new Uint8Array(f.buffer,f.byteOffset,f.byteLength);a._chunkSteps(C)}function Va(o){if(o._byobRequest===null&&o._pendingPullIntos.length>0){let a=o._pendingPullIntos.peek(),f=new Uint8Array(a.buffer,a.byteOffset+a.bytesFilled,a.byteLength-a.bytesFilled),C=Object.create(Jr.prototype);f0(C,o,f),o._byobRequest=C}return o._byobRequest}function qf(o){let a=o._controlledReadableByteStream._state;return a==="errored"?null:a==="closed"?0:o._strategyHWM-o._queueTotalSize}function lo(o,a){let f=o._pendingPullIntos.peek();if(o._controlledReadableByteStream._state==="closed"){if(a!==0)throw new TypeError("bytesWritten must be 0 when calling respond() on a closed stream")}else{if(a===0)throw new TypeError("bytesWritten must be greater than 0 when calling respond() on a readable stream");if(f.bytesFilled+a>f.byteLength)throw new RangeError("bytesWritten out of range")}f.buffer=ar(f.buffer),Mf(o,a)}function fo(o,a){let f=o._pendingPullIntos.peek();if(o._controlledReadableByteStream._state==="closed"){if(a.byteLength!==0)throw new TypeError("The view's length must be 0 when calling respondWithNewView() on a closed stream")}else if(a.byteLength===0)throw new TypeError("The view's length must be greater than 0 when calling respondWithNewView() on a readable stream");if(f.byteOffset+f.bytesFilled!==a.byteOffset)throw new RangeError("The region specified by view does not match byobRequest");if(f.bufferByteLength!==a.buffer.byteLength)throw new RangeError("The buffer of view has different capacity than byobRequest");if(f.bytesFilled+a.byteLength>f.byteLength)throw new RangeError("The region specified by view is larger than byobRequest");let D=a.byteLength;f.buffer=ar(a.buffer),Mf(o,D)}function $f(o,a,f,C,D,L,q){a._controlledReadableByteStream=o,a._pullAgain=!1,a._pulling=!1,a._byobRequest=null,a._queue=a._queueTotalSize=void 0,Tr(a),a._closeRequested=!1,a._started=!1,a._strategyHWM=L,a._pullAlgorithm=C,a._cancelAlgorithm=D,a._autoAllocateChunkSize=q,a._pendingPullIntos=new R,o._readableStreamController=a;let Y=f();A(h(Y),()=>(a._started=!0,Kr(a),null),ce=>(bt(a,ce),null))}function l0(o,a,f){let C=Object.create(ur.prototype),D,L,q;a.start!==void 0?D=()=>a.start(C):D=()=>{},a.pull!==void 0?L=()=>a.pull(C):L=()=>h(void 0),a.cancel!==void 0?q=ce=>a.cancel(ce):q=()=>h(void 0);let Y=a.autoAllocateChunkSize;if(Y===0)throw new TypeError("autoAllocateChunkSize must be greater than 0");$f(o,C,D,L,q,f,Y)}function f0(o,a,f){o._associatedReadableByteStreamController=a,o._view=f}function Ka(o){return new TypeError(`ReadableStreamBYOBRequest.prototype.${o} can only be used on a ReadableStreamBYOBRequest`)}function fs(o){return new TypeError(`ReadableByteStreamController.prototype.${o} can only be used on a ReadableByteStreamController`)}function d0(o,a){le(o,a);let f=o?.mode;return{mode:f===void 0?void 0:h0(f,`${a} has member 'mode' that`)}}function h0(o,a){if(o=`${o}`,o!=="byob")throw new TypeError(`${a} '${o}' is not a valid enumeration value for ReadableStreamReaderMode`);return o}function p0(o,a){var f;le(o,a);let C=(f=o?.min)!==null&&f!==void 0?f:1;return{min:x(C,`${a} has member 'min' that`)}}function zf(o){return new Dr(o)}function Hf(o,a){o._reader._readIntoRequests.push(a)}function m0(o,a,f){let D=o._reader._readIntoRequests.shift();f?D._closeSteps(a):D._chunkSteps(a)}function Wf(o){return o._reader._readIntoRequests.length}function Ya(o){let a=o._reader;return!(a===void 0||!Yr(a))}class Dr{constructor(a){if(Be(a,1,"ReadableStreamBYOBReader"),I(a,"First parameter"),Or(a))throw new TypeError("This stream has already been locked for exclusive reading by another reader");if(!Vr(a._readableStreamController))throw new TypeError("Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte source");ue(this,a),this._readIntoRequests=new R}get closed(){return Yr(this)?this._closedPromise:d(ho("closed"))}cancel(a=void 0){return Yr(this)?this._ownerReadableStream===void 0?d(pe("cancel")):re(this,a):d(ho("cancel"))}read(a,f={}){if(!Yr(this))return d(ho("read"));if(!ArrayBuffer.isView(a))return d(new TypeError("view must be an array buffer view"));if(a.byteLength===0)return d(new TypeError("view must have non-zero byteLength"));if(a.buffer.byteLength===0)return d(new TypeError("view's buffer must have non-zero byteLength"));if(kr(a.buffer))return d(new TypeError("view's buffer has been detached"));let C;try{C=p0(f,"options")}catch(ne){return d(ne)}let D=C.min;if(D===0)return d(new TypeError("options.min must be greater than 0"));if(n0(a)){if(D>a.byteLength)return d(new RangeError("options.min must be less than or equal to view's byteLength"))}else if(D>a.length)return d(new RangeError("options.min must be less than or equal to view's length"));if(this._ownerReadableStream===void 0)return d(pe("read from"));let L,q,Y=l((ne,de)=>{L=ne,q=de});return Gf(this,a,D,{_chunkSteps:ne=>L({value:ne,done:!1}),_closeSteps:ne=>L({value:ne,done:!0}),_errorSteps:ne=>q(ne)}),Y}releaseLock(){if(!Yr(this))throw ho("releaseLock");this._ownerReadableStream!==void 0&&g0(this)}}Object.defineProperties(Dr.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),s(Dr.prototype.cancel,"cancel"),s(Dr.prototype.read,"read"),s(Dr.prototype.releaseLock,"releaseLock"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Dr.prototype,Symbol.toStringTag,{value:"ReadableStreamBYOBReader",configurable:!0});function Yr(o){return!r(o)||!Object.prototype.hasOwnProperty.call(o,"_readIntoRequests")?!1:o instanceof Dr}function Gf(o,a,f,C){let D=o._ownerReadableStream;D._disturbed=!0,D._state==="errored"?C._errorSteps(D._storedError):i0(D._readableStreamController,a,f,C)}function g0(o){fe(o);let a=new TypeError("Reader was released");Jf(o,a)}function Jf(o,a){let f=o._readIntoRequests;o._readIntoRequests=new R,f.forEach(C=>{C._errorSteps(a)})}function ho(o){return new TypeError(`ReadableStreamBYOBReader.prototype.${o} can only be used on a ReadableStreamBYOBReader`)}function ds(o,a){let{highWaterMark:f}=o;if(f===void 0)return a;if(ut(f)||f<0)throw new RangeError("Invalid highWaterMark");return f}function po(o){let{size:a}=o;return a||(()=>1)}function mo(o,a){le(o,a);let f=o?.highWaterMark,C=o?.size;return{highWaterMark:f===void 0?void 0:w(f),size:C===void 0?void 0:y0(C,`${a} has member 'size' that`)}}function y0(o,a){return _e(o,a),f=>w(o(f))}function _0(o,a){le(o,a);let f=o?.abort,C=o?.close,D=o?.start,L=o?.type,q=o?.write;return{abort:f===void 0?void 0:b0(f,o,`${a} has member 'abort' that`),close:C===void 0?void 0:C0(C,o,`${a} has member 'close' that`),start:D===void 0?void 0:w0(D,o,`${a} has member 'start' that`),write:q===void 0?void 0:E0(q,o,`${a} has member 'write' that`),type:L}}function b0(o,a,f){return _e(o,f),C=>b(o,a,[C])}function C0(o,a,f){return _e(o,f),()=>b(o,a,[])}function w0(o,a,f){return _e(o,f),C=>k(o,a,[C])}function E0(o,a,f){return _e(o,f),(C,D)=>b(o,a,[C,D])}function Vf(o,a){if(!yn(o))throw new TypeError(`${a} is not a WritableStream.`)}function A0(o){if(typeof o!="object"||o===null)return!1;try{return typeof o.aborted=="boolean"}catch{return!1}}let S0=typeof AbortController=="function";function k0(){if(S0)return new AbortController}class vr{constructor(a={},f={}){a===void 0?a=null:Re(a,"First parameter");let C=mo(f,"Second parameter"),D=_0(a,"First parameter");if(Yf(this),D.type!==void 0)throw new RangeError("Invalid type is specified");let q=po(C),Y=ds(C,1);M0(this,D,Y,q)}get locked(){if(!yn(this))throw Co("locked");return _n(this)}abort(a=void 0){return yn(this)?_n(this)?d(new TypeError("Cannot abort a stream that already has a writer")):go(this,a):d(Co("abort"))}close(){return yn(this)?_n(this)?d(new TypeError("Cannot close a stream that already has a writer")):Wt(this)?d(new TypeError("Cannot close an already-closing stream")):Xf(this):d(Co("close"))}getWriter(){if(!yn(this))throw Co("getWriter");return Kf(this)}}Object.defineProperties(vr.prototype,{abort:{enumerable:!0},close:{enumerable:!0},getWriter:{enumerable:!0},locked:{enumerable:!0}}),s(vr.prototype.abort,"abort"),s(vr.prototype.close,"close"),s(vr.prototype.getWriter,"getWriter"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(vr.prototype,Symbol.toStringTag,{value:"WritableStream",configurable:!0});function Kf(o){return new cr(o)}function T0(o,a,f,C,D=1,L=()=>1){let q=Object.create(vr.prototype);Yf(q);let Y=Object.create(bn.prototype);return nd(q,Y,o,a,f,C,D,L),q}function Yf(o){o._state="writable",o._storedError=void 0,o._writer=void 0,o._writableStreamController=void 0,o._writeRequests=new R,o._inFlightWriteRequest=void 0,o._closeRequest=void 0,o._inFlightCloseRequest=void 0,o._pendingAbortRequest=void 0,o._backpressure=!1}function yn(o){return!r(o)||!Object.prototype.hasOwnProperty.call(o,"_writableStreamController")?!1:o instanceof vr}function _n(o){return o._writer!==void 0}function go(o,a){var f;if(o._state==="closed"||o._state==="errored")return h(void 0);o._writableStreamController._abortReason=a,(f=o._writableStreamController._abortController)===null||f===void 0||f.abort(a);let C=o._state;if(C==="closed"||C==="errored")return h(void 0);if(o._pendingAbortRequest!==void 0)return o._pendingAbortRequest._promise;let D=!1;C==="erroring"&&(D=!0,a=void 0);let L=l((q,Y)=>{o._pendingAbortRequest={_promise:void 0,_resolve:q,_reject:Y,_reason:a,_wasAlreadyErroring:D}});return o._pendingAbortRequest._promise=L,D||Qa(o,a),L}function Xf(o){let a=o._state;if(a==="closed"||a==="errored")return d(new TypeError(`The stream (in ${a} state) is not in the writable state and cannot be closed`));let f=l((D,L)=>{let q={_resolve:D,_reject:L};o._closeRequest=q}),C=o._writer;return C!==void 0&&o._backpressure&&a==="writable"&&iu(C),U0(o._writableStreamController),f}function D0(o){return l((f,C)=>{let D={_resolve:f,_reject:C};o._writeRequests.push(D)})}function Xa(o,a){if(o._state==="writable"){Qa(o,a);return}Za(o)}function Qa(o,a){let f=o._writableStreamController;o._state="erroring",o._storedError=a;let C=o._writer;C!==void 0&&Zf(C,a),!F0(o)&&f._started&&Za(o)}function Za(o){o._state="errored",o._writableStreamController[$]();let a=o._storedError;if(o._writeRequests.forEach(D=>{D._reject(a)}),o._writeRequests=new R,o._pendingAbortRequest===void 0){yo(o);return}let f=o._pendingAbortRequest;if(o._pendingAbortRequest=void 0,f._wasAlreadyErroring){f._reject(a),yo(o);return}let C=o._writableStreamController[F](f._reason);A(C,()=>(f._resolve(),yo(o),null),D=>(f._reject(D),yo(o),null))}function v0(o){o._inFlightWriteRequest._resolve(void 0),o._inFlightWriteRequest=void 0}function R0(o,a){o._inFlightWriteRequest._reject(a),o._inFlightWriteRequest=void 0,Xa(o,a)}function O0(o){o._inFlightCloseRequest._resolve(void 0),o._inFlightCloseRequest=void 0,o._state==="erroring"&&(o._storedError=void 0,o._pendingAbortRequest!==void 0&&(o._pendingAbortRequest._resolve(),o._pendingAbortRequest=void 0)),o._state="closed";let f=o._writer;f!==void 0&&ad(f)}function x0(o,a){o._inFlightCloseRequest._reject(a),o._inFlightCloseRequest=void 0,o._pendingAbortRequest!==void 0&&(o._pendingAbortRequest._reject(a),o._pendingAbortRequest=void 0),Xa(o,a)}function Wt(o){return!(o._closeRequest===void 0&&o._inFlightCloseRequest===void 0)}function F0(o){return!(o._inFlightWriteRequest===void 0&&o._inFlightCloseRequest===void 0)}function P0(o){o._inFlightCloseRequest=o._closeRequest,o._closeRequest=void 0}function I0(o){o._inFlightWriteRequest=o._writeRequests.shift()}function yo(o){o._closeRequest!==void 0&&(o._closeRequest._reject(o._storedError),o._closeRequest=void 0);let a=o._writer;a!==void 0&&su(a,o._storedError)}function eu(o,a){let f=o._writer;f!==void 0&&a!==o._backpressure&&(a?J0(f):iu(f)),o._backpressure=a}class cr{constructor(a){if(Be(a,1,"WritableStreamDefaultWriter"),Vf(a,"First parameter"),_n(a))throw new TypeError("This stream has already been locked for exclusive writing by another writer");this._ownerWritableStream=a,a._writer=this;let f=a._state;if(f==="writable")!Wt(a)&&a._backpressure?Eo(this):ud(this),wo(this);else if(f==="erroring")ou(this,a._storedError),wo(this);else if(f==="closed")ud(this),W0(this);else{let C=a._storedError;ou(this,C),id(this,C)}}get closed(){return Xr(this)?this._closedPromise:d(Qr("closed"))}get desiredSize(){if(!Xr(this))throw Qr("desiredSize");if(this._ownerWritableStream===void 0)throw ps("desiredSize");return L0(this)}get ready(){return Xr(this)?this._readyPromise:d(Qr("ready"))}abort(a=void 0){return Xr(this)?this._ownerWritableStream===void 0?d(ps("abort")):N0(this,a):d(Qr("abort"))}close(){if(!Xr(this))return d(Qr("close"));let a=this._ownerWritableStream;return a===void 0?d(ps("close")):Wt(a)?d(new TypeError("Cannot close an already-closing stream")):Qf(this)}releaseLock(){if(!Xr(this))throw Qr("releaseLock");this._ownerWritableStream!==void 0&&ed(this)}write(a=void 0){return Xr(this)?this._ownerWritableStream===void 0?d(ps("write to")):td(this,a):d(Qr("write"))}}Object.defineProperties(cr.prototype,{abort:{enumerable:!0},close:{enumerable:!0},releaseLock:{enumerable:!0},write:{enumerable:!0},closed:{enumerable:!0},desiredSize:{enumerable:!0},ready:{enumerable:!0}}),s(cr.prototype.abort,"abort"),s(cr.prototype.close,"close"),s(cr.prototype.releaseLock,"releaseLock"),s(cr.prototype.write,"write"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(cr.prototype,Symbol.toStringTag,{value:"WritableStreamDefaultWriter",configurable:!0});function Xr(o){return!r(o)||!Object.prototype.hasOwnProperty.call(o,"_ownerWritableStream")?!1:o instanceof cr}function N0(o,a){let f=o._ownerWritableStream;return go(f,a)}function Qf(o){let a=o._ownerWritableStream;return Xf(a)}function B0(o){let a=o._ownerWritableStream,f=a._state;return Wt(a)||f==="closed"?h(void 0):f==="errored"?d(a._storedError):Qf(o)}function j0(o,a){o._closedPromiseState==="pending"?su(o,a):G0(o,a)}function Zf(o,a){o._readyPromiseState==="pending"?cd(o,a):V0(o,a)}function L0(o){let a=o._ownerWritableStream,f=a._state;return f==="errored"||f==="erroring"?null:f==="closed"?0:sd(a._writableStreamController)}function ed(o){let a=o._ownerWritableStream,f=new TypeError("Writer was released and can no longer be used to monitor the stream's closedness");Zf(o,f),j0(o,f),a._writer=void 0,o._ownerWritableStream=void 0}function td(o,a){let f=o._ownerWritableStream,C=f._writableStreamController,D=q0(C,a);if(f!==o._ownerWritableStream)return d(ps("write to"));let L=f._state;if(L==="errored")return d(f._storedError);if(Wt(f)||L==="closed")return d(new TypeError("The stream is closing or closed and cannot be written to"));if(L==="erroring")return d(f._storedError);let q=D0(f);return $0(C,a,D),q}let rd={};class bn{constructor(){throw new TypeError("Illegal constructor")}get abortReason(){if(!tu(this))throw nu("abortReason");return this._abortReason}get signal(){if(!tu(this))throw nu("signal");if(this._abortController===void 0)throw new TypeError("WritableStreamDefaultController.prototype.signal is not supported");return this._abortController.signal}error(a=void 0){if(!tu(this))throw nu("error");this._controlledWritableStream._state==="writable"&&od(this,a)}[F](a){let f=this._abortAlgorithm(a);return _o(this),f}[$](){Tr(this)}}Object.defineProperties(bn.prototype,{abortReason:{enumerable:!0},signal:{enumerable:!0},error:{enumerable:!0}}),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(bn.prototype,Symbol.toStringTag,{value:"WritableStreamDefaultController",configurable:!0});function tu(o){return!r(o)||!Object.prototype.hasOwnProperty.call(o,"_controlledWritableStream")?!1:o instanceof bn}function nd(o,a,f,C,D,L,q,Y){a._controlledWritableStream=o,o._writableStreamController=a,a._queue=void 0,a._queueTotalSize=void 0,Tr(a),a._abortReason=void 0,a._abortController=k0(),a._started=!1,a._strategySizeAlgorithm=Y,a._strategyHWM=q,a._writeAlgorithm=C,a._closeAlgorithm=D,a._abortAlgorithm=L;let ce=ru(a);eu(o,ce);let ne=f(),de=h(ne);A(de,()=>(a._started=!0,bo(a),null),ye=>(a._started=!0,Xa(o,ye),null))}function M0(o,a,f,C){let D=Object.create(bn.prototype),L,q,Y,ce;a.start!==void 0?L=()=>a.start(D):L=()=>{},a.write!==void 0?q=ne=>a.write(ne,D):q=()=>h(void 0),a.close!==void 0?Y=()=>a.close():Y=()=>h(void 0),a.abort!==void 0?ce=ne=>a.abort(ne):ce=()=>h(void 0),nd(o,D,L,q,Y,ce,f,C)}function _o(o){o._writeAlgorithm=void 0,o._closeAlgorithm=void 0,o._abortAlgorithm=void 0,o._strategySizeAlgorithm=void 0}function U0(o){za(o,rd,0),bo(o)}function q0(o,a){try{return o._strategySizeAlgorithm(a)}catch(f){return hs(o,f),1}}function sd(o){return o._strategyHWM-o._queueTotalSize}function $0(o,a,f){try{za(o,a,f)}catch(D){hs(o,D);return}let C=o._controlledWritableStream;if(!Wt(C)&&C._state==="writable"){let D=ru(o);eu(C,D)}bo(o)}function bo(o){let a=o._controlledWritableStream;if(!o._started||a._inFlightWriteRequest!==void 0)return;if(a._state==="erroring"){Za(a);return}if(o._queue.length===0)return;let C=r0(o);C===rd?z0(o):H0(o,C)}function hs(o,a){o._controlledWritableStream._state==="writable"&&od(o,a)}function z0(o){let a=o._controlledWritableStream;P0(a),$a(o);let f=o._closeAlgorithm();_o(o),A(f,()=>(O0(a),null),C=>(x0(a,C),null))}function H0(o,a){let f=o._controlledWritableStream;I0(f);let C=o._writeAlgorithm(a);A(C,()=>{v0(f);let D=f._state;if($a(o),!Wt(f)&&D==="writable"){let L=ru(o);eu(f,L)}return bo(o),null},D=>(f._state==="writable"&&_o(o),R0(f,D),null))}function ru(o){return sd(o)<=0}function od(o,a){let f=o._controlledWritableStream;_o(o),Qa(f,a)}function Co(o){return new TypeError(`WritableStream.prototype.${o} can only be used on a WritableStream`)}function nu(o){return new TypeError(`WritableStreamDefaultController.prototype.${o} can only be used on a WritableStreamDefaultController`)}function Qr(o){return new TypeError(`WritableStreamDefaultWriter.prototype.${o} can only be used on a WritableStreamDefaultWriter`)}function ps(o){return new TypeError("Cannot "+o+" a stream using a released writer")}function wo(o){o._closedPromise=l((a,f)=>{o._closedPromise_resolve=a,o._closedPromise_reject=f,o._closedPromiseState="pending"})}function id(o,a){wo(o),su(o,a)}function W0(o){wo(o),ad(o)}function su(o,a){o._closedPromise_reject!==void 0&&(g(o._closedPromise),o._closedPromise_reject(a),o._closedPromise_resolve=void 0,o._closedPromise_reject=void 0,o._closedPromiseState="rejected")}function G0(o,a){id(o,a)}function ad(o){o._closedPromise_resolve!==void 0&&(o._closedPromise_resolve(void 0),o._closedPromise_resolve=void 0,o._closedPromise_reject=void 0,o._closedPromiseState="resolved")}function Eo(o){o._readyPromise=l((a,f)=>{o._readyPromise_resolve=a,o._readyPromise_reject=f}),o._readyPromiseState="pending"}function ou(o,a){Eo(o),cd(o,a)}function ud(o){Eo(o),iu(o)}function cd(o,a){o._readyPromise_reject!==void 0&&(g(o._readyPromise),o._readyPromise_reject(a),o._readyPromise_resolve=void 0,o._readyPromise_reject=void 0,o._readyPromiseState="rejected")}function J0(o){Eo(o)}function V0(o,a){ou(o,a)}function iu(o){o._readyPromise_resolve!==void 0&&(o._readyPromise_resolve(void 0),o._readyPromise_resolve=void 0,o._readyPromise_reject=void 0,o._readyPromiseState="fulfilled")}function K0(){if(typeof globalThis<"u")return globalThis;if(typeof self<"u")return self;if(typeof global<"u")return global}let au=K0();function Y0(o){if(!(typeof o=="function"||typeof o=="object")||o.name!=="DOMException")return!1;try{return new o,!0}catch{return!1}}function X0(){let o=au?.DOMException;return Y0(o)?o:void 0}function Q0(){let o=function(f,C){this.message=f||"",this.name=C||"Error",Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)};return s(o,"DOMException"),o.prototype=Object.create(Error.prototype),Object.defineProperty(o.prototype,"constructor",{value:o,writable:!0,configurable:!0}),o}let Z0=X0()||Q0();function ld(o,a,f,C,D,L){let q=U(o),Y=Kf(a);o._disturbed=!0;let ce=!1,ne=h(void 0);return l((de,ye)=>{let ve;if(L!==void 0){if(ve=()=>{let se=L.reason!==void 0?L.reason:new Z0("Aborted","AbortError"),be=[];C||be.push(()=>a._state==="writable"?go(a,se):h(void 0)),D||be.push(()=>o._state==="readable"?Pt(o,se):h(void 0)),rt(()=>Promise.all(be.map(Oe=>Oe())),!0,se)},L.aborted){ve();return}L.addEventListener("abort",ve)}function It(){return l((se,be)=>{function Oe(ct){ct?se():p(An(),Oe,be)}Oe(!1)})}function An(){return ce?h(!0):p(Y._readyPromise,()=>l((se,be)=>{ee(q,{_chunkSteps:Oe=>{ne=p(td(Y,Oe),void 0,e),se(!1)},_closeSteps:()=>se(!0),_errorSteps:be})}))}if(fr(o,q._closedPromise,se=>(C?Ct(!0,se):rt(()=>go(a,se),!0,se),null)),fr(a,Y._closedPromise,se=>(D?Ct(!0,se):rt(()=>Pt(o,se),!0,se),null)),Qe(o,q._closedPromise,()=>(f?Ct():rt(()=>B0(Y)),null)),Wt(a)||a._state==="closed"){let se=new TypeError("the destination writable stream closed before all data could be piped to it");D?Ct(!0,se):rt(()=>Pt(o,se),!0,se)}g(It());function Fr(){let se=ne;return p(ne,()=>se!==ne?Fr():void 0)}function fr(se,be,Oe){se._state==="errored"?Oe(se._storedError):S(be,Oe)}function Qe(se,be,Oe){se._state==="closed"?Oe():v(be,Oe)}function rt(se,be,Oe){if(ce)return;ce=!0,a._state==="writable"&&!Wt(a)?v(Fr(),ct):ct();function ct(){return A(se(),()=>dr(be,Oe),Sn=>dr(!0,Sn)),null}}function Ct(se,be){ce||(ce=!0,a._state==="writable"&&!Wt(a)?v(Fr(),()=>dr(se,be)):dr(se,be))}function dr(se,be){return ed(Y),fe(q),L!==void 0&&L.removeEventListener("abort",ve),se?ye(be):de(void 0),null}})}class lr{constructor(){throw new TypeError("Illegal constructor")}get desiredSize(){if(!Ao(this))throw ko("desiredSize");return uu(this)}close(){if(!Ao(this))throw ko("close");if(!wn(this))throw new TypeError("The stream is not in a state that permits close");Zr(this)}enqueue(a=void 0){if(!Ao(this))throw ko("enqueue");if(!wn(this))throw new TypeError("The stream is not in a state that permits enqueue");return Cn(this,a)}error(a=void 0){if(!Ao(this))throw ko("error");Ft(this,a)}[J](a){Tr(this);let f=this._cancelAlgorithm(a);return So(this),f}[M](a){let f=this._controlledReadableStream;if(this._queue.length>0){let C=$a(this);this._closeRequested&&this._queue.length===0?(So(this),ys(f)):ms(this),a._chunkSteps(C)}else O(f,a),ms(this)}[X](){}}Object.defineProperties(lr.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},desiredSize:{enumerable:!0}}),s(lr.prototype.close,"close"),s(lr.prototype.enqueue,"enqueue"),s(lr.prototype.error,"error"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(lr.prototype,Symbol.toStringTag,{value:"ReadableStreamDefaultController",configurable:!0});function Ao(o){return!r(o)||!Object.prototype.hasOwnProperty.call(o,"_controlledReadableStream")?!1:o instanceof lr}function ms(o){if(!fd(o))return;if(o._pulling){o._pullAgain=!0;return}o._pulling=!0;let f=o._pullAlgorithm();A(f,()=>(o._pulling=!1,o._pullAgain&&(o._pullAgain=!1,ms(o)),null),C=>(Ft(o,C),null))}function fd(o){let a=o._controlledReadableStream;return!wn(o)||!o._started?!1:!!(Or(a)&&j(a)>0||uu(o)>0)}function So(o){o._pullAlgorithm=void 0,o._cancelAlgorithm=void 0,o._strategySizeAlgorithm=void 0}function Zr(o){if(!wn(o))return;let a=o._controlledReadableStream;o._closeRequested=!0,o._queue.length===0&&(So(o),ys(a))}function Cn(o,a){if(!wn(o))return;let f=o._controlledReadableStream;if(Or(f)&&j(f)>0)P(f,a,!1);else{let C;try{C=o._strategySizeAlgorithm(a)}catch(D){throw Ft(o,D),D}try{za(o,a,C)}catch(D){throw Ft(o,D),D}}ms(o)}function Ft(o,a){let f=o._controlledReadableStream;f._state==="readable"&&(Tr(o),So(o),md(f,a))}function uu(o){let a=o._controlledReadableStream._state;return a==="errored"?null:a==="closed"?0:o._strategyHWM-o._queueTotalSize}function e_(o){return!fd(o)}function wn(o){let a=o._controlledReadableStream._state;return!o._closeRequested&&a==="readable"}function dd(o,a,f,C,D,L,q){a._controlledReadableStream=o,a._queue=void 0,a._queueTotalSize=void 0,Tr(a),a._started=!1,a._closeRequested=!1,a._pullAgain=!1,a._pulling=!1,a._strategySizeAlgorithm=q,a._strategyHWM=L,a._pullAlgorithm=C,a._cancelAlgorithm=D,o._readableStreamController=a;let Y=f();A(h(Y),()=>(a._started=!0,ms(a),null),ce=>(Ft(a,ce),null))}function t_(o,a,f,C){let D=Object.create(lr.prototype),L,q,Y;a.start!==void 0?L=()=>a.start(D):L=()=>{},a.pull!==void 0?q=()=>a.pull(D):q=()=>h(void 0),a.cancel!==void 0?Y=ce=>a.cancel(ce):Y=()=>h(void 0),dd(o,D,L,q,Y,f,C)}function ko(o){return new TypeError(`ReadableStreamDefaultController.prototype.${o} can only be used on a ReadableStreamDefaultController`)}function r_(o,a){return Vr(o._readableStreamController)?s_(o):n_(o)}function n_(o,a){let f=U(o),C=!1,D=!1,L=!1,q=!1,Y,ce,ne,de,ye,ve=l(Qe=>{ye=Qe});function It(){return C?(D=!0,h(void 0)):(C=!0,ee(f,{_chunkSteps:rt=>{m(()=>{D=!1;let Ct=rt,dr=rt;L||Cn(ne._readableStreamController,Ct),q||Cn(de._readableStreamController,dr),C=!1,D&&It()})},_closeSteps:()=>{C=!1,L||Zr(ne._readableStreamController),q||Zr(de._readableStreamController),(!L||!q)&&ye(void 0)},_errorSteps:()=>{C=!1}}),h(void 0))}function An(Qe){if(L=!0,Y=Qe,q){let rt=ke([Y,ce]),Ct=Pt(o,rt);ye(Ct)}return ve}function Fr(Qe){if(q=!0,ce=Qe,L){let rt=ke([Y,ce]),Ct=Pt(o,rt);ye(Ct)}return ve}function fr(){}return ne=gs(fr,It,An),de=gs(fr,It,Fr),S(f._closedPromise,Qe=>(Ft(ne._readableStreamController,Qe),Ft(de._readableStreamController,Qe),(!L||!q)&&ye(void 0),null)),[ne,de]}function s_(o){let a=U(o),f=!1,C=!1,D=!1,L=!1,q=!1,Y,ce,ne,de,ye,ve=l(se=>{ye=se});function It(se){S(se._closedPromise,be=>(se!==a||(bt(ne._readableStreamController,be),bt(de._readableStreamController,be),(!L||!q)&&ye(void 0)),null))}function An(){Yr(a)&&(fe(a),a=U(o),It(a)),ee(a,{_chunkSteps:be=>{m(()=>{C=!1,D=!1;let Oe=be,ct=be;if(!L&&!q)try{ct=Of(be)}catch(Sn){bt(ne._readableStreamController,Sn),bt(de._readableStreamController,Sn),ye(Pt(o,Sn));return}L||co(ne._readableStreamController,Oe),q||co(de._readableStreamController,ct),f=!1,C?fr():D&&Qe()})},_closeSteps:()=>{f=!1,L||ls(ne._readableStreamController),q||ls(de._readableStreamController),ne._readableStreamController._pendingPullIntos.length>0&&lo(ne._readableStreamController,0),de._readableStreamController._pendingPullIntos.length>0&&lo(de._readableStreamController,0),(!L||!q)&&ye(void 0)},_errorSteps:()=>{f=!1}})}function Fr(se,be){Z(a)&&(fe(a),a=zf(o),It(a));let Oe=be?de:ne,ct=be?ne:de;Gf(a,se,1,{_chunkSteps:kn=>{m(()=>{C=!1,D=!1;let Tn=be?q:L;if(be?L:q)Tn||fo(Oe._readableStreamController,kn);else{let vd;try{vd=Of(kn)}catch(hu){bt(Oe._readableStreamController,hu),bt(ct._readableStreamController,hu),ye(Pt(o,hu));return}Tn||fo(Oe._readableStreamController,kn),co(ct._readableStreamController,vd)}f=!1,C?fr():D&&Qe()})},_closeSteps:kn=>{f=!1;let Tn=be?q:L,Po=be?L:q;Tn||ls(Oe._readableStreamController),Po||ls(ct._readableStreamController),kn!==void 0&&(Tn||fo(Oe._readableStreamController,kn),!Po&&ct._readableStreamController._pendingPullIntos.length>0&&lo(ct._readableStreamController,0)),(!Tn||!Po)&&ye(void 0)},_errorSteps:()=>{f=!1}})}function fr(){if(f)return C=!0,h(void 0);f=!0;let se=Va(ne._readableStreamController);return se===null?An():Fr(se._view,!1),h(void 0)}function Qe(){if(f)return D=!0,h(void 0);f=!0;let se=Va(de._readableStreamController);return se===null?An():Fr(se._view,!0),h(void 0)}function rt(se){if(L=!0,Y=se,q){let be=ke([Y,ce]),Oe=Pt(o,be);ye(Oe)}return ve}function Ct(se){if(q=!0,ce=se,L){let be=ke([Y,ce]),Oe=Pt(o,be);ye(Oe)}return ve}function dr(){}return ne=pd(dr,fr,rt),de=pd(dr,Qe,Ct),It(a),[ne,de]}function o_(o){return r(o)&&typeof o.getReader<"u"}function i_(o){return o_(o)?u_(o.getReader()):a_(o)}function a_(o){let a,f=Rf(o,"async"),C=e;function D(){let q;try{q=Qy(f)}catch(ce){return d(ce)}let Y=h(q);return y(Y,ce=>{if(!r(ce))throw new TypeError("The promise returned by the iterator.next() method must fulfill with an object");if(Zy(ce))Zr(a._readableStreamController);else{let de=e0(ce);Cn(a._readableStreamController,de)}})}function L(q){let Y=f.iterator,ce;try{ce=io(Y,"return")}catch(ye){return d(ye)}if(ce===void 0)return h(void 0);let ne;try{ne=k(ce,Y,[q])}catch(ye){return d(ye)}let de=h(ne);return y(de,ye=>{if(!r(ye))throw new TypeError("The promise returned by the iterator.return() method must fulfill with an object")})}return a=gs(C,D,L,0),a}function u_(o){let a,f=e;function C(){let L;try{L=o.read()}catch(q){return d(q)}return y(L,q=>{if(!r(q))throw new TypeError("The promise returned by the reader.read() method must fulfill with an object");if(q.done)Zr(a._readableStreamController);else{let Y=q.value;Cn(a._readableStreamController,Y)}})}function D(L){try{return h(o.cancel(L))}catch(q){return d(q)}}return a=gs(f,C,D,0),a}function c_(o,a){le(o,a);let f=o,C=f?.autoAllocateChunkSize,D=f?.cancel,L=f?.pull,q=f?.start,Y=f?.type;return{autoAllocateChunkSize:C===void 0?void 0:x(C,`${a} has member 'autoAllocateChunkSize' that`),cancel:D===void 0?void 0:l_(D,f,`${a} has member 'cancel' that`),pull:L===void 0?void 0:f_(L,f,`${a} has member 'pull' that`),start:q===void 0?void 0:d_(q,f,`${a} has member 'start' that`),type:Y===void 0?void 0:h_(Y,`${a} has member 'type' that`)}}function l_(o,a,f){return _e(o,f),C=>b(o,a,[C])}function f_(o,a,f){return _e(o,f),C=>b(o,a,[C])}function d_(o,a,f){return _e(o,f),C=>k(o,a,[C])}function h_(o,a){if(o=`${o}`,o!=="bytes")throw new TypeError(`${a} '${o}' is not a valid enumeration value for ReadableStreamType`);return o}function p_(o,a){return le(o,a),{preventCancel:!!o?.preventCancel}}function hd(o,a){le(o,a);let f=o?.preventAbort,C=o?.preventCancel,D=o?.preventClose,L=o?.signal;return L!==void 0&&m_(L,`${a} has member 'signal' that`),{preventAbort:!!f,preventCancel:!!C,preventClose:!!D,signal:L}}function m_(o,a){if(!A0(o))throw new TypeError(`${a} is not an AbortSignal.`)}function g_(o,a){le(o,a);let f=o?.readable;_(f,"readable","ReadableWritablePair"),I(f,`${a} has member 'readable' that`);let C=o?.writable;return _(C,"writable","ReadableWritablePair"),Vf(C,`${a} has member 'writable' that`),{readable:f,writable:C}}class Ye{constructor(a={},f={}){a===void 0?a=null:Re(a,"First parameter");let C=mo(f,"Second parameter"),D=c_(a,"First parameter");if(cu(this),D.type==="bytes"){if(C.size!==void 0)throw new RangeError("The strategy for a byte stream cannot have a size function");let L=ds(C,0);l0(this,D,L)}else{let L=po(C),q=ds(C,1);t_(this,D,q,L)}}get locked(){if(!Rr(this))throw en("locked");return Or(this)}cancel(a=void 0){return Rr(this)?Or(this)?d(new TypeError("Cannot cancel a stream that already has a reader")):Pt(this,a):d(en("cancel"))}getReader(a=void 0){if(!Rr(this))throw en("getReader");return d0(a,"First parameter").mode===void 0?U(this):zf(this)}pipeThrough(a,f={}){if(!Rr(this))throw en("pipeThrough");Be(a,1,"pipeThrough");let C=g_(a,"First parameter"),D=hd(f,"Second parameter");if(Or(this))throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream");if(_n(C.writable))throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream");let L=ld(this,C.writable,D.preventClose,D.preventAbort,D.preventCancel,D.signal);return g(L),C.readable}pipeTo(a,f={}){if(!Rr(this))return d(en("pipeTo"));if(a===void 0)return d("Parameter 1 is required in 'pipeTo'.");if(!yn(a))return d(new TypeError("ReadableStream.prototype.pipeTo's first argument must be a WritableStream"));let C;try{C=hd(f,"Second parameter")}catch(D){return d(D)}return Or(this)?d(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream")):_n(a)?d(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream")):ld(this,a,C.preventClose,C.preventAbort,C.preventCancel,C.signal)}tee(){if(!Rr(this))throw en("tee");let a=r_(this);return ke(a)}values(a=void 0){if(!Rr(this))throw en("values");let f=p_(a,"First parameter");return hn(this,f.preventCancel)}[qa](a){return this.values(a)}static from(a){return i_(a)}}Object.defineProperties(Ye,{from:{enumerable:!0}}),Object.defineProperties(Ye.prototype,{cancel:{enumerable:!0},getReader:{enumerable:!0},pipeThrough:{enumerable:!0},pipeTo:{enumerable:!0},tee:{enumerable:!0},values:{enumerable:!0},locked:{enumerable:!0}}),s(Ye.from,"from"),s(Ye.prototype.cancel,"cancel"),s(Ye.prototype.getReader,"getReader"),s(Ye.prototype.pipeThrough,"pipeThrough"),s(Ye.prototype.pipeTo,"pipeTo"),s(Ye.prototype.tee,"tee"),s(Ye.prototype.values,"values"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Ye.prototype,Symbol.toStringTag,{value:"ReadableStream",configurable:!0}),Object.defineProperty(Ye.prototype,qa,{value:Ye.prototype.values,writable:!0,configurable:!0});function gs(o,a,f,C=1,D=()=>1){let L=Object.create(Ye.prototype);cu(L);let q=Object.create(lr.prototype);return dd(L,q,o,a,f,C,D),L}function pd(o,a,f){let C=Object.create(Ye.prototype);cu(C);let D=Object.create(ur.prototype);return $f(C,D,o,a,f,0,void 0),C}function cu(o){o._state="readable",o._reader=void 0,o._storedError=void 0,o._disturbed=!1}function Rr(o){return!r(o)||!Object.prototype.hasOwnProperty.call(o,"_readableStreamController")?!1:o instanceof Ye}function Or(o){return o._reader!==void 0}function Pt(o,a){if(o._disturbed=!0,o._state==="closed")return h(void 0);if(o._state==="errored")return d(o._storedError);ys(o);let f=o._reader;if(f!==void 0&&Yr(f)){let D=f._readIntoRequests;f._readIntoRequests=new R,D.forEach(L=>{L._closeSteps(void 0)})}let C=o._readableStreamController[J](a);return y(C,e)}function ys(o){o._state="closed";let a=o._reader;if(a!==void 0&&(ae(a),Z(a))){let f=a._readRequests;a._readRequests=new R,f.forEach(C=>{C._closeSteps()})}}function md(o,a){o._state="errored",o._storedError=a;let f=o._reader;f!==void 0&&(G(f,a),Z(f)?Fe(f,a):Jf(f,a))}function en(o){return new TypeError(`ReadableStream.prototype.${o} can only be used on a ReadableStream`)}function gd(o,a){le(o,a);let f=o?.highWaterMark;return _(f,"highWaterMark","QueuingStrategyInit"),{highWaterMark:w(f)}}let yd=o=>o.byteLength;s(yd,"size");class To{constructor(a){Be(a,1,"ByteLengthQueuingStrategy"),a=gd(a,"First parameter"),this._byteLengthQueuingStrategyHighWaterMark=a.highWaterMark}get highWaterMark(){if(!bd(this))throw _d("highWaterMark");return this._byteLengthQueuingStrategyHighWaterMark}get size(){if(!bd(this))throw _d("size");return yd}}Object.defineProperties(To.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(To.prototype,Symbol.toStringTag,{value:"ByteLengthQueuingStrategy",configurable:!0});function _d(o){return new TypeError(`ByteLengthQueuingStrategy.prototype.${o} can only be used on a ByteLengthQueuingStrategy`)}function bd(o){return!r(o)||!Object.prototype.hasOwnProperty.call(o,"_byteLengthQueuingStrategyHighWaterMark")?!1:o instanceof To}let Cd=()=>1;s(Cd,"size");class Do{constructor(a){Be(a,1,"CountQueuingStrategy"),a=gd(a,"First parameter"),this._countQueuingStrategyHighWaterMark=a.highWaterMark}get highWaterMark(){if(!Ed(this))throw wd("highWaterMark");return this._countQueuingStrategyHighWaterMark}get size(){if(!Ed(this))throw wd("size");return Cd}}Object.defineProperties(Do.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Do.prototype,Symbol.toStringTag,{value:"CountQueuingStrategy",configurable:!0});function wd(o){return new TypeError(`CountQueuingStrategy.prototype.${o} can only be used on a CountQueuingStrategy`)}function Ed(o){return!r(o)||!Object.prototype.hasOwnProperty.call(o,"_countQueuingStrategyHighWaterMark")?!1:o instanceof Do}function y_(o,a){le(o,a);let f=o?.cancel,C=o?.flush,D=o?.readableType,L=o?.start,q=o?.transform,Y=o?.writableType;return{cancel:f===void 0?void 0:w_(f,o,`${a} has member 'cancel' that`),flush:C===void 0?void 0:__(C,o,`${a} has member 'flush' that`),readableType:D,start:L===void 0?void 0:b_(L,o,`${a} has member 'start' that`),transform:q===void 0?void 0:C_(q,o,`${a} has member 'transform' that`),writableType:Y}}function __(o,a,f){return _e(o,f),C=>b(o,a,[C])}function b_(o,a,f){return _e(o,f),C=>k(o,a,[C])}function C_(o,a,f){return _e(o,f),(C,D)=>b(o,a,[C,D])}function w_(o,a,f){return _e(o,f),C=>b(o,a,[C])}class vo{constructor(a={},f={},C={}){a===void 0&&(a=null);let D=mo(f,"Second parameter"),L=mo(C,"Third parameter"),q=y_(a,"First parameter");if(q.readableType!==void 0)throw new RangeError("Invalid readableType specified");if(q.writableType!==void 0)throw new RangeError("Invalid writableType specified");let Y=ds(L,0),ce=po(L),ne=ds(D,1),de=po(D),ye,ve=l(It=>{ye=It});E_(this,ve,ne,de,Y,ce),S_(this,q),q.start!==void 0?ye(q.start(this._transformStreamController)):ye(void 0)}get readable(){if(!Ad(this))throw Dd("readable");return this._readable}get writable(){if(!Ad(this))throw Dd("writable");return this._writable}}Object.defineProperties(vo.prototype,{readable:{enumerable:!0},writable:{enumerable:!0}}),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(vo.prototype,Symbol.toStringTag,{value:"TransformStream",configurable:!0});function E_(o,a,f,C,D,L){function q(){return a}function Y(ve){return D_(o,ve)}function ce(ve){return v_(o,ve)}function ne(){return R_(o)}o._writable=T0(q,Y,ne,ce,f,C);function de(){return O_(o)}function ye(ve){return x_(o,ve)}o._readable=gs(q,de,ye,D,L),o._backpressure=void 0,o._backpressureChangePromise=void 0,o._backpressureChangePromise_resolve=void 0,Ro(o,!0),o._transformStreamController=void 0}function Ad(o){return!r(o)||!Object.prototype.hasOwnProperty.call(o,"_transformStreamController")?!1:o instanceof vo}function Sd(o,a){Ft(o._readable._readableStreamController,a),lu(o,a)}function lu(o,a){xo(o._transformStreamController),hs(o._writable._writableStreamController,a),fu(o)}function fu(o){o._backpressure&&Ro(o,!1)}function Ro(o,a){o._backpressureChangePromise!==void 0&&o._backpressureChangePromise_resolve(),o._backpressureChangePromise=l(f=>{o._backpressureChangePromise_resolve=f}),o._backpressure=a}class xr{constructor(){throw new TypeError("Illegal constructor")}get desiredSize(){if(!Oo(this))throw Fo("desiredSize");let a=this._controlledTransformStream._readable._readableStreamController;return uu(a)}enqueue(a=void 0){if(!Oo(this))throw Fo("enqueue");kd(this,a)}error(a=void 0){if(!Oo(this))throw Fo("error");k_(this,a)}terminate(){if(!Oo(this))throw Fo("terminate");T_(this)}}Object.defineProperties(xr.prototype,{enqueue:{enumerable:!0},error:{enumerable:!0},terminate:{enumerable:!0},desiredSize:{enumerable:!0}}),s(xr.prototype.enqueue,"enqueue"),s(xr.prototype.error,"error"),s(xr.prototype.terminate,"terminate"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(xr.prototype,Symbol.toStringTag,{value:"TransformStreamDefaultController",configurable:!0});function Oo(o){return!r(o)||!Object.prototype.hasOwnProperty.call(o,"_controlledTransformStream")?!1:o instanceof xr}function A_(o,a,f,C,D){a._controlledTransformStream=o,o._transformStreamController=a,a._transformAlgorithm=f,a._flushAlgorithm=C,a._cancelAlgorithm=D,a._finishPromise=void 0,a._finishPromise_resolve=void 0,a._finishPromise_reject=void 0}function S_(o,a){let f=Object.create(xr.prototype),C,D,L;a.transform!==void 0?C=q=>a.transform(q,f):C=q=>{try{return kd(f,q),h(void 0)}catch(Y){return d(Y)}},a.flush!==void 0?D=()=>a.flush(f):D=()=>h(void 0),a.cancel!==void 0?L=q=>a.cancel(q):L=()=>h(void 0),A_(o,f,C,D,L)}function xo(o){o._transformAlgorithm=void 0,o._flushAlgorithm=void 0,o._cancelAlgorithm=void 0}function kd(o,a){let f=o._controlledTransformStream,C=f._readable._readableStreamController;if(!wn(C))throw new TypeError("Readable side is not in a state that permits enqueue");try{Cn(C,a)}catch(L){throw lu(f,L),f._readable._storedError}e_(C)!==f._backpressure&&Ro(f,!0)}function k_(o,a){Sd(o._controlledTransformStream,a)}function Td(o,a){let f=o._transformAlgorithm(a);return y(f,void 0,C=>{throw Sd(o._controlledTransformStream,C),C})}function T_(o){let a=o._controlledTransformStream,f=a._readable._readableStreamController;Zr(f);let C=new TypeError("TransformStream terminated");lu(a,C)}function D_(o,a){let f=o._transformStreamController;if(o._backpressure){let C=o._backpressureChangePromise;return y(C,()=>{let D=o._writable;if(D._state==="erroring")throw D._storedError;return Td(f,a)})}return Td(f,a)}function v_(o,a){let f=o._transformStreamController;if(f._finishPromise!==void 0)return f._finishPromise;let C=o._readable;f._finishPromise=l((L,q)=>{f._finishPromise_resolve=L,f._finishPromise_reject=q});let D=f._cancelAlgorithm(a);return xo(f),A(D,()=>(C._state==="errored"?En(f,C._storedError):(Ft(C._readableStreamController,a),du(f)),null),L=>(Ft(C._readableStreamController,L),En(f,L),null)),f._finishPromise}function R_(o){let a=o._transformStreamController;if(a._finishPromise!==void 0)return a._finishPromise;let f=o._readable;a._finishPromise=l((D,L)=>{a._finishPromise_resolve=D,a._finishPromise_reject=L});let C=a._flushAlgorithm();return xo(a),A(C,()=>(f._state==="errored"?En(a,f._storedError):(Zr(f._readableStreamController),du(a)),null),D=>(Ft(f._readableStreamController,D),En(a,D),null)),a._finishPromise}function O_(o){return Ro(o,!1),o._backpressureChangePromise}function x_(o,a){let f=o._transformStreamController;if(f._finishPromise!==void 0)return f._finishPromise;let C=o._writable;f._finishPromise=l((L,q)=>{f._finishPromise_resolve=L,f._finishPromise_reject=q});let D=f._cancelAlgorithm(a);return xo(f),A(D,()=>(C._state==="errored"?En(f,C._storedError):(hs(C._writableStreamController,a),fu(o),du(f)),null),L=>(hs(C._writableStreamController,L),fu(o),En(f,L),null)),f._finishPromise}function Fo(o){return new TypeError(`TransformStreamDefaultController.prototype.${o} can only be used on a TransformStreamDefaultController`)}function du(o){o._finishPromise_resolve!==void 0&&(o._finishPromise_resolve(),o._finishPromise_resolve=void 0,o._finishPromise_reject=void 0)}function En(o,a){o._finishPromise_reject!==void 0&&(g(o._finishPromise),o._finishPromise_reject(a),o._finishPromise_resolve=void 0,o._finishPromise_reject=void 0)}function Dd(o){return new TypeError(`TransformStream.prototype.${o} can only be used on a TransformStream`)}t.ByteLengthQueuingStrategy=To,t.CountQueuingStrategy=Do,t.ReadableByteStreamController=ur,t.ReadableStream=Ye,t.ReadableStreamBYOBReader=Dr,t.ReadableStreamBYOBRequest=Jr,t.ReadableStreamDefaultController=lr,t.ReadableStreamDefaultReader=z,t.TransformStream=vo,t.TransformStreamDefaultController=xr,t.WritableStream=vr,t.WritableStreamDefaultController=bn,t.WritableStreamDefaultWriter=cr}))});var Hh=V(()=>{if(!globalThis.ReadableStream)try{let t=Q("node:process"),{emitWarning:e}=t;try{t.emitWarning=()=>{},Object.assign(globalThis,Q("node:stream/web")),t.emitWarning=e}catch(r){throw t.emitWarning=e,r}}catch{Object.assign(globalThis,zh())}try{let{Blob:t}=Q("buffer");t&&!t.prototype.stream&&(t.prototype.stream=function(r){let n=0,s=this;return new ReadableStream({type:"bytes",async pull(i){let c=await s.slice(n,Math.min(s.size,n+65536)).arrayBuffer();n+=c.byteLength,i.enqueue(new Uint8Array(c)),n===s.size&&i.close()}})})}catch{}});async function*zu(t,e=!0){for(let r of t)if("stream"in r)yield*r.stream();else if(ArrayBuffer.isView(r))if(e){let n=r.byteOffset,s=r.byteOffset+r.byteLength;for(;n!==s;){let i=Math.min(s-n,Wh),u=r.buffer.slice(n,n+i);n+=u.byteLength,yield new Uint8Array(u)}}else yield r;else{let n=0,s=r;for(;n!==s.size;){let u=await s.slice(n,Math.min(s.size,n+Wh)).arrayBuffer();n+=u.byteLength,yield new Uint8Array(u)}}}var Iv,Wh,Gh,iC,Bt,Es=je(()=>{Iv=Pr(Hh(),1);Wh=65536;Gh=class Hu{#e=[];#t="";#r=0;#n="transparent";constructor(e=[],r={}){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 r!="object"&&typeof r!="function")throw new TypeError("Failed to construct 'Blob': parameter 2 cannot convert to dictionary.");r===null&&(r={});let n=new TextEncoder;for(let i of e){let u;ArrayBuffer.isView(i)?u=new Uint8Array(i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength)):i instanceof ArrayBuffer?u=new Uint8Array(i.slice(0)):i instanceof Hu?u=i:u=n.encode(`${i}`),this.#r+=ArrayBuffer.isView(u)?u.byteLength:u.size,this.#e.push(u)}this.#n=`${r.endings===void 0?"transparent":r.endings}`;let s=r.type===void 0?"":String(r.type);this.#t=/^[\x20-\x7E]*$/.test(s)?s:""}get size(){return this.#r}get type(){return this.#t}async text(){let e=new TextDecoder,r="";for await(let n of zu(this.#e,!1))r+=e.decode(n,{stream:!0});return r+=e.decode(),r}async arrayBuffer(){let e=new Uint8Array(this.size),r=0;for await(let n of zu(this.#e,!1))e.set(n,r),r+=n.length;return e.buffer}stream(){let e=zu(this.#e,!0);return new globalThis.ReadableStream({type:"bytes",async pull(r){let n=await e.next();n.done?r.close():r.enqueue(n.value)},async cancel(){await e.return()}})}slice(e=0,r=this.size,n=""){let{size:s}=this,i=e<0?Math.max(s+e,0):Math.min(e,s),u=r<0?Math.max(s+r,0):Math.min(r,s),c=Math.max(u-i,0),l=this.#e,h=[],d=0;for(let A of l){if(d>=c)break;let v=ArrayBuffer.isView(A)?A.byteLength:A.size;if(i&&v<=i)i-=v,u-=v;else{let S;ArrayBuffer.isView(A)?(S=A.subarray(i,Math.min(v,u)),d+=S.byteLength):(S=A.slice(i,Math.min(v,u)),d+=S.size),u-=v,h.push(S),i=0}}let p=new Hu([],{type:String(n).toLowerCase()});return p.#r=c,p.#e=h,p}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(Gh.prototype,{size:{enumerable:!0},type:{enumerable:!0},slice:{enumerable:!0}});iC=Gh,Bt=iC});var aC,uC,Br,Wu=je(()=>{Es();aC=class extends Bt{#e=0;#t="";constructor(e,r,n={}){if(arguments.length<2)throw new TypeError(`Failed to construct 'File': 2 arguments required, but only ${arguments.length} present.`);super(e,n),n===null&&(n={});let s=n.lastModified===void 0?Date.now():Number(n.lastModified);Number.isNaN(s)||(this.#e=s),this.#t=String(r)}get name(){return this.#t}get lastModified(){return this.#e}get[Symbol.toStringTag](){return"File"}static[Symbol.hasInstance](e){return!!e&&e instanceof Bt&&/^(File)$/.test(e[Symbol.toStringTag])}},uC=aC,Br=uC});function Kh(t,e=Bt){var r=`${Jh()}${Jh()}`.replace(/\./g,"").slice(-28).padStart(32,"-"),n=[],s=`--${r}\r
|
|
27
|
-
Content-Disposition: form-data; name="`;return t.forEach((i,u)=>typeof i=="string"?n.push(s+
|
|
22
|
+
`);if(w===-1){ri("have not received end of HTTP headers yet..."),i();return}let T=p.slice(0,w).toString("ascii").split(`\r
|
|
23
|
+
`),S=T.shift();if(!S)return t.destroy(),r(new Error("No header received from proxy CONNECT response"));let y=S.split(" "),g=+y[1],m=y.slice(2).join(" "),v={};for(let b of T){if(!b)continue;let A=b.indexOf(":");if(A===-1)return t.destroy(),r(new Error(`Invalid header from proxy CONNECT response: "${b}"`));let R=b.slice(0,A).toLowerCase(),F=b.slice(A+1).trimStart(),$=v[R];typeof $=="string"?v[R]=[$,F]:Array.isArray($)?$.push(F):v[R]=F}ri("got proxy server response: %o %o",S,v),u(),e({connect:{statusCode:g,statusText:m,headers:v},buffered:p})}t.on("error",l),t.on("end",c),i()})}Bn.parseProxyResponse=yC});var ep=V(At=>{"use strict";var _C=At&&At.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,s)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),bC=At&&At.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),Xh=At&&At.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&_C(e,t,r);return bC(e,t),e},Zh=At&&At.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(At,"__esModule",{value:!0});At.HttpsProxyAgent=void 0;var ni=Xh(X("net")),Kh=Xh(X("tls")),CC=Zh(X("assert")),wC=Zh(Gu()),EC=Jh(),AC=X("url"),SC=Vh(),Ss=(0,wC.default)("https-proxy-agent"),Yh=t=>t.servername===void 0&&t.host&&!ni.isIP(t.host)?{...t,servername:t.host}:t,si=class extends EC.Agent{constructor(e,r){super(r),this.options={path:void 0},this.proxy=typeof e=="string"?new AC.URL(e):e,this.proxyHeaders=r?.headers??{},Ss("Creating new HttpsProxyAgent instance: %o",this.proxy.href);let n=(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"],...r?Qh(r,"headers"):null,host:n,port:s}}async connect(e,r){let{proxy:n}=this;if(!r.host)throw new TypeError('No "host" provided');let s;n.protocol==="https:"?(Ss("Creating `tls.Socket`: %o",this.connectOpts),s=Kh.connect(Yh(this.connectOpts))):(Ss("Creating `net.Socket`: %o",this.connectOpts),s=ni.connect(this.connectOpts));let i=typeof this.proxyHeaders=="function"?this.proxyHeaders():{...this.proxyHeaders},u=ni.isIPv6(r.host)?`[${r.host}]`:r.host,c=`CONNECT ${u}:${r.port} HTTP/1.1\r
|
|
24
|
+
`;if(n.username||n.password){let w=`${decodeURIComponent(n.username)}:${decodeURIComponent(n.password)}`;i["Proxy-Authorization"]=`Basic ${Buffer.from(w).toString("base64")}`}i.Host=`${u}:${r.port}`,i["Proxy-Connection"]||(i["Proxy-Connection"]=this.keepAlive?"Keep-Alive":"close");for(let w of Object.keys(i))c+=`${w}: ${i[w]}\r
|
|
25
|
+
`;let l=(0,SC.parseProxyResponse)(s);s.write(`${c}\r
|
|
26
|
+
`);let{connect:h,buffered:d}=await l;if(e.emit("proxyConnect",h),this.emit("proxyConnect",h,e),h.statusCode===200)return e.once("socket",vC),r.secureEndpoint?(Ss("Upgrading socket connection to TLS"),Kh.connect({...Qh(Yh(r),"host","path","port"),socket:s})):s;s.destroy();let p=new ni.Socket({writable:!1});return p.readable=!0,e.once("socket",w=>{Ss("Replaying proxy buffer for failed request"),(0,CC.default)(w.listenerCount("data")>0),w.push(d),w.push(null)}),p}};si.protocols=["http","https"];At.HttpsProxyAgent=si;function vC(t){t.resume()}function Qh(t,...e){let r={},n;for(n in t)e.includes(n)||(r[n]=t[n]);return r}});function kC(t){if(!/^data:/i.test(t))throw new TypeError('`uri` does not appear to be a Data URI (must begin with "data:")');t=t.replace(/\r?\n/g,"");let e=t.indexOf(",");if(e===-1||e<=4)throw new TypeError("malformed data: URI");let r=t.substring(5,e).split(";"),n="",s=!1,i=r[0]||"text/plain",u=i;for(let d=1;d<r.length;d++)r[d]==="base64"?s=!0:r[d]&&(u+=`;${r[d]}`,r[d].indexOf("charset=")===0&&(n=r[d].substring(8)));!r[0]&&!n.length&&(u+=";charset=US-ASCII",n="US-ASCII");let c=s?"base64":"ascii",l=unescape(t.substring(e+1)),h=Buffer.from(l,c);return h.type=i,h.typeFull=u,h.charset=n,h}var tp,rp=je(()=>{tp=kC});var sp=V((oi,np)=>{(function(t,e){typeof oi=="object"&&typeof np<"u"?e(oi):typeof define=="function"&&define.amd?define(["exports"],e):(t=typeof globalThis<"u"?globalThis:t||self,e(t.WebStreamsPolyfill={}))})(oi,(function(t){"use strict";function e(){}function r(o){return typeof o=="object"&&o!==null||typeof o=="function"}let n=e;function s(o,a){try{Object.defineProperty(o,"name",{value:a,configurable:!0})}catch{}}let i=Promise,u=Promise.prototype.then,c=Promise.reject.bind(i);function l(o){return new i(o)}function h(o){return l(a=>a(o))}function d(o){return c(o)}function p(o,a,f){return u.call(o,a,f)}function w(o,a,f){p(p(o,a,f),void 0,n)}function T(o,a){w(o,a)}function S(o,a){w(o,void 0,a)}function y(o,a,f){return p(o,a,f)}function g(o){p(o,void 0,n)}let m=o=>{if(typeof queueMicrotask=="function")m=queueMicrotask;else{let a=h(void 0);m=f=>p(a,f)}return m(o)};function v(o,a,f){if(typeof o!="function")throw new TypeError("Argument is not a function");return Function.prototype.apply.call(o,a,f)}function b(o,a,f){try{return h(v(o,a,f))}catch(C){return d(C)}}let A=16384;class R{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(a){let f=this._back,C=f;f._elements.length===A-1&&(C={_elements:[],_next:void 0}),f._elements.push(a),C!==f&&(this._back=C,f._next=C),++this._size}shift(){let a=this._front,f=a,C=this._cursor,D=C+1,L=a._elements,q=L[C];return D===A&&(f=a._next,D=0),--this._size,this._cursor=D,a!==f&&(this._front=f),L[C]=void 0,q}forEach(a){let f=this._cursor,C=this._front,D=C._elements;for(;(f!==D.length||C._next!==void 0)&&!(f===D.length&&(C=C._next,D=C._elements,f=0,D.length===0));)a(D[f]),++f}peek(){let a=this._front,f=this._cursor;return a._elements[f]}}let F=Symbol("[[AbortSteps]]"),$=Symbol("[[ErrorSteps]]"),J=Symbol("[[CancelSteps]]"),M=Symbol("[[PullSteps]]"),Q=Symbol("[[ReleaseSteps]]");function ue(o,a){o._ownerReadableStream=a,a._reader=o,a._state==="readable"?Ae(o):a._state==="closed"?me(o):oe(o,a._storedError)}function re(o,a){let f=o._ownerReadableStream;return Pt(f,a)}function de(o){let a=o._ownerReadableStream;a._state==="readable"?G(o,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")):K(o,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")),a._readableStreamController[Q](),a._reader=void 0,o._ownerReadableStream=void 0}function pe(o){return new TypeError("Cannot "+o+" a stream using a released reader")}function Ae(o){o._closedPromise=l((a,f)=>{o._closedPromise_resolve=a,o._closedPromise_reject=f})}function oe(o,a){Ae(o),G(o,a)}function me(o){Ae(o),ae(o)}function G(o,a){o._closedPromise_reject!==void 0&&(g(o._closedPromise),o._closedPromise_reject(a),o._closedPromise_resolve=void 0,o._closedPromise_reject=void 0)}function K(o,a){oe(o,a)}function ae(o){o._closedPromise_resolve!==void 0&&(o._closedPromise_resolve(void 0),o._closedPromise_resolve=void 0,o._closedPromise_reject=void 0)}let qe=Number.isFinite||function(o){return typeof o=="number"&&isFinite(o)},Te=Math.trunc||function(o){return o<0?Math.ceil(o):Math.floor(o)};function W(o){return typeof o=="object"||typeof o=="function"}function le(o,a){if(o!==void 0&&!W(o))throw new TypeError(`${a} is not an object.`)}function _e(o,a){if(typeof o!="function")throw new TypeError(`${a} is not a function.`)}function Ot(o){return typeof o=="object"&&o!==null||typeof o=="function"}function Re(o,a){if(!Ot(o))throw new TypeError(`${a} is not an object.`)}function Be(o,a,f){if(o===void 0)throw new TypeError(`Parameter ${a} is required in '${f}'.`)}function _(o,a,f){if(o===void 0)throw new TypeError(`${a} is required in '${f}'.`)}function E(o){return Number(o)}function k(o){return o===0?0:o}function B(o){return k(Te(o))}function O(o,a){let C=Number.MAX_SAFE_INTEGER,D=Number(o);if(D=k(D),!qe(D))throw new TypeError(`${a} is not a finite number`);if(D=B(D),D<0||D>C)throw new TypeError(`${a} is outside the accepted range of 0 to ${C}, inclusive`);return!qe(D)||D===0?0:D}function I(o,a){if(!Or(o))throw new TypeError(`${a} is not a ReadableStream.`)}function U(o){return new z(o)}function x(o,a){o._reader._readRequests.push(a)}function P(o,a,f){let D=o._reader._readRequests.shift();f?D._closeSteps():D._chunkSteps(a)}function j(o){return o._reader._readRequests.length}function N(o){let a=o._reader;return!(a===void 0||!Z(a))}class z{constructor(a){if(Be(a,1,"ReadableStreamDefaultReader"),I(a,"First parameter"),Fr(a))throw new TypeError("This stream has already been locked for exclusive reading by another reader");ue(this,a),this._readRequests=new R}get closed(){return Z(this)?this._closedPromise:d(Ne("closed"))}cancel(a=void 0){return Z(this)?this._ownerReadableStream===void 0?d(pe("cancel")):re(this,a):d(Ne("cancel"))}read(){if(!Z(this))return d(Ne("read"));if(this._ownerReadableStream===void 0)return d(pe("read from"));let a,f,C=l((L,q)=>{a=L,f=q});return ee(this,{_chunkSteps:L=>a({value:L,done:!1}),_closeSteps:()=>a({value:void 0,done:!0}),_errorSteps:L=>f(L)}),C}releaseLock(){if(!Z(this))throw Ne("releaseLock");this._ownerReadableStream!==void 0&&Ee(this)}}Object.defineProperties(z.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),s(z.prototype.cancel,"cancel"),s(z.prototype.read,"read"),s(z.prototype.releaseLock,"releaseLock"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(z.prototype,Symbol.toStringTag,{value:"ReadableStreamDefaultReader",configurable:!0});function Z(o){return!r(o)||!Object.prototype.hasOwnProperty.call(o,"_readRequests")?!1:o instanceof z}function ee(o,a){let f=o._ownerReadableStream;f._disturbed=!0,f._state==="closed"?a._closeSteps():f._state==="errored"?a._errorSteps(f._storedError):f._readableStreamController[M](a)}function Ee(o){de(o);let a=new TypeError("Reader was released");Fe(o,a)}function Fe(o,a){let f=o._readRequests;o._readRequests=new R,f.forEach(C=>{C._errorSteps(a)})}function Ne(o){return new TypeError(`ReadableStreamDefaultReader.prototype.${o} can only be used on a ReadableStreamDefaultReader`)}let we=Object.getPrototypeOf(Object.getPrototypeOf(async function*(){}).prototype);class Se{constructor(a,f){this._ongoingPromise=void 0,this._isFinished=!1,this._reader=a,this._preventCancel=f}next(){let a=()=>this._nextSteps();return this._ongoingPromise=this._ongoingPromise?y(this._ongoingPromise,a,a):a(),this._ongoingPromise}return(a){let f=()=>this._returnSteps(a);return this._ongoingPromise?y(this._ongoingPromise,f,f):f()}_nextSteps(){if(this._isFinished)return Promise.resolve({value:void 0,done:!0});let a=this._reader,f,C,D=l((q,Y)=>{f=q,C=Y});return ee(a,{_chunkSteps:q=>{this._ongoingPromise=void 0,m(()=>f({value:q,done:!1}))},_closeSteps:()=>{this._ongoingPromise=void 0,this._isFinished=!0,de(a),f({value:void 0,done:!0})},_errorSteps:q=>{this._ongoingPromise=void 0,this._isFinished=!0,de(a),C(q)}}),D}_returnSteps(a){if(this._isFinished)return Promise.resolve({value:a,done:!0});this._isFinished=!0;let f=this._reader;if(!this._preventCancel){let C=re(f,a);return de(f),y(C,()=>({value:a,done:!0}))}return de(f),h({value:a,done:!0})}}let Me={next(){return yn(this)?this._asyncIteratorImpl.next():d(_n("next"))},return(o){return yn(this)?this._asyncIteratorImpl.return(o):d(_n("return"))}};Object.setPrototypeOf(Me,we);function gn(o,a){let f=U(o),C=new Se(f,a),D=Object.create(Me);return D._asyncIteratorImpl=C,D}function yn(o){if(!r(o)||!Object.prototype.hasOwnProperty.call(o,"_asyncIteratorImpl"))return!1;try{return o._asyncIteratorImpl instanceof Se}catch{return!1}}function _n(o){return new TypeError(`ReadableStreamAsyncIterator.${o} can only be used on a ReadableSteamAsyncIterator`)}let ut=Number.isNaN||function(o){return o!==o};var ur,Ke,Ue;function ve(o){return o.slice()}function Ud(o,a,f,C,D){new Uint8Array(o).set(new Uint8Array(f,C,D),a)}let cr=o=>(typeof o.transfer=="function"?cr=a=>a.transfer():typeof structuredClone=="function"?cr=a=>structuredClone(a,{transfer:[a]}):cr=a=>a,cr(o)),Tr=o=>(typeof o.detached=="boolean"?Tr=a=>a.detached:Tr=a=>a.byteLength===0,Tr(o));function qd(o,a,f){if(o.slice)return o.slice(a,f);let C=f-a,D=new ArrayBuffer(C);return Ud(D,0,o,a,C),D}function lo(o,a){let f=o[a];if(f!=null){if(typeof f!="function")throw new TypeError(`${String(a)} is not a function`);return f}}function p0(o){let a={[Symbol.iterator]:()=>o.iterator},f=(async function*(){return yield*a})(),C=f.next;return{iterator:f,nextMethod:C,done:!1}}let Ga=(Ue=(ur=Symbol.asyncIterator)!==null&&ur!==void 0?ur:(Ke=Symbol.for)===null||Ke===void 0?void 0:Ke.call(Symbol,"Symbol.asyncIterator"))!==null&&Ue!==void 0?Ue:"@@asyncIterator";function $d(o,a="sync",f){if(f===void 0)if(a==="async"){if(f=lo(o,Ga),f===void 0){let L=lo(o,Symbol.iterator),q=$d(o,"sync",L);return p0(q)}}else f=lo(o,Symbol.iterator);if(f===void 0)throw new TypeError("The object is not iterable");let C=v(f,o,[]);if(!r(C))throw new TypeError("The iterator method must return an object");let D=C.next;return{iterator:C,nextMethod:D,done:!1}}function m0(o){let a=v(o.nextMethod,o.iterator,[]);if(!r(a))throw new TypeError("The iterator.next() method must return an object");return a}function g0(o){return!!o.done}function y0(o){return o.value}function _0(o){return!(typeof o!="number"||ut(o)||o<0)}function zd(o){let a=qd(o.buffer,o.byteOffset,o.byteOffset+o.byteLength);return new Uint8Array(a)}function Ja(o){let a=o._queue.shift();return o._queueTotalSize-=a.size,o._queueTotalSize<0&&(o._queueTotalSize=0),a.value}function Va(o,a,f){if(!_0(f)||f===1/0)throw new RangeError("Size must be a finite, non-NaN, non-negative number.");o._queue.push({value:a,size:f}),o._queueTotalSize+=f}function b0(o){return o._queue.peek().value}function Dr(o){o._queue=new R,o._queueTotalSize=0}function Hd(o){return o===DataView}function C0(o){return Hd(o.constructor)}function w0(o){return Hd(o)?1:o.BYTES_PER_ELEMENT}class Yr{constructor(){throw new TypeError("Illegal constructor")}get view(){if(!Ka(this))throw eu("view");return this._view}respond(a){if(!Ka(this))throw eu("respond");if(Be(a,1,"respond"),a=O(a,"First parameter"),this._associatedReadableByteStreamController===void 0)throw new TypeError("This BYOB request has been invalidated");if(Tr(this._view.buffer))throw new TypeError("The BYOB request's buffer has been detached and so cannot be used as a response");mo(this._associatedReadableByteStreamController,a)}respondWithNewView(a){if(!Ka(this))throw eu("respondWithNewView");if(Be(a,1,"respondWithNewView"),!ArrayBuffer.isView(a))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(Tr(a.buffer))throw new TypeError("The given view's buffer has been detached and so cannot be used as a response");go(this._associatedReadableByteStreamController,a)}}Object.defineProperties(Yr.prototype,{respond:{enumerable:!0},respondWithNewView:{enumerable:!0},view:{enumerable:!0}}),s(Yr.prototype.respond,"respond"),s(Yr.prototype.respondWithNewView,"respondWithNewView"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Yr.prototype,Symbol.toStringTag,{value:"ReadableStreamBYOBRequest",configurable:!0});class lr{constructor(){throw new TypeError("Illegal constructor")}get byobRequest(){if(!Qr(this))throw hs("byobRequest");return Za(this)}get desiredSize(){if(!Qr(this))throw hs("desiredSize");return ef(this)}close(){if(!Qr(this))throw hs("close");if(this._closeRequested)throw new TypeError("The stream has already been closed; do not close it again!");let a=this._controlledReadableByteStream._state;if(a!=="readable")throw new TypeError(`The stream (in ${a} state) is not in the readable state and cannot be closed`);fs(this)}enqueue(a){if(!Qr(this))throw hs("enqueue");if(Be(a,1,"enqueue"),!ArrayBuffer.isView(a))throw new TypeError("chunk must be an array buffer view");if(a.byteLength===0)throw new TypeError("chunk must have non-zero byteLength");if(a.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 f=this._controlledReadableByteStream._state;if(f!=="readable")throw new TypeError(`The stream (in ${f} state) is not in the readable state and cannot be enqueued to`);po(this,a)}error(a=void 0){if(!Qr(this))throw hs("error");bt(this,a)}[J](a){Wd(this),Dr(this);let f=this._cancelAlgorithm(a);return ho(this),f}[M](a){let f=this._controlledReadableByteStream;if(this._queueTotalSize>0){Zd(this,a);return}let C=this._autoAllocateChunkSize;if(C!==void 0){let D;try{D=new ArrayBuffer(C)}catch(q){a._errorSteps(q);return}let L={buffer:D,bufferByteLength:C,byteOffset:0,byteLength:C,bytesFilled:0,minimumFill:1,elementSize:1,viewConstructor:Uint8Array,readerType:"default"};this._pendingPullIntos.push(L)}x(f,a),Xr(this)}[Q](){if(this._pendingPullIntos.length>0){let a=this._pendingPullIntos.peek();a.readerType="none",this._pendingPullIntos=new R,this._pendingPullIntos.push(a)}}}Object.defineProperties(lr.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},byobRequest:{enumerable:!0},desiredSize:{enumerable:!0}}),s(lr.prototype.close,"close"),s(lr.prototype.enqueue,"enqueue"),s(lr.prototype.error,"error"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(lr.prototype,Symbol.toStringTag,{value:"ReadableByteStreamController",configurable:!0});function Qr(o){return!r(o)||!Object.prototype.hasOwnProperty.call(o,"_controlledReadableByteStream")?!1:o instanceof lr}function Ka(o){return!r(o)||!Object.prototype.hasOwnProperty.call(o,"_associatedReadableByteStreamController")?!1:o instanceof Yr}function Xr(o){if(!k0(o))return;if(o._pulling){o._pullAgain=!0;return}o._pulling=!0;let f=o._pullAlgorithm();w(f,()=>(o._pulling=!1,o._pullAgain&&(o._pullAgain=!1,Xr(o)),null),C=>(bt(o,C),null))}function Wd(o){Qa(o),o._pendingPullIntos=new R}function Ya(o,a){let f=!1;o._state==="closed"&&(f=!0);let C=Gd(a);a.readerType==="default"?P(o,C,f):F0(o,C,f)}function Gd(o){let a=o.bytesFilled,f=o.elementSize;return new o.viewConstructor(o.buffer,o.byteOffset,a/f)}function fo(o,a,f,C){o._queue.push({buffer:a,byteOffset:f,byteLength:C}),o._queueTotalSize+=C}function Jd(o,a,f,C){let D;try{D=qd(a,f,f+C)}catch(L){throw bt(o,L),L}fo(o,D,0,C)}function Vd(o,a){a.bytesFilled>0&&Jd(o,a.buffer,a.byteOffset,a.bytesFilled),bn(o)}function Kd(o,a){let f=Math.min(o._queueTotalSize,a.byteLength-a.bytesFilled),C=a.bytesFilled+f,D=f,L=!1,q=C%a.elementSize,Y=C-q;Y>=a.minimumFill&&(D=Y-a.bytesFilled,L=!0);let ce=o._queue;for(;D>0;){let ne=ce.peek(),fe=Math.min(D,ne.byteLength),ye=a.byteOffset+a.bytesFilled;Ud(a.buffer,ye,ne.buffer,ne.byteOffset,fe),ne.byteLength===fe?ce.shift():(ne.byteOffset+=fe,ne.byteLength-=fe),o._queueTotalSize-=fe,Yd(o,fe,a),D-=fe}return L}function Yd(o,a,f){f.bytesFilled+=a}function Qd(o){o._queueTotalSize===0&&o._closeRequested?(ho(o),bs(o._controlledReadableByteStream)):Xr(o)}function Qa(o){o._byobRequest!==null&&(o._byobRequest._associatedReadableByteStreamController=void 0,o._byobRequest._view=null,o._byobRequest=null)}function Xa(o){for(;o._pendingPullIntos.length>0;){if(o._queueTotalSize===0)return;let a=o._pendingPullIntos.peek();Kd(o,a)&&(bn(o),Ya(o._controlledReadableByteStream,a))}}function E0(o){let a=o._controlledReadableByteStream._reader;for(;a._readRequests.length>0;){if(o._queueTotalSize===0)return;let f=a._readRequests.shift();Zd(o,f)}}function A0(o,a,f,C){let D=o._controlledReadableByteStream,L=a.constructor,q=w0(L),{byteOffset:Y,byteLength:ce}=a,ne=f*q,fe;try{fe=cr(a.buffer)}catch(De){C._errorSteps(De);return}let ye={buffer:fe,bufferByteLength:fe.byteLength,byteOffset:Y,byteLength:ce,bytesFilled:0,minimumFill:ne,elementSize:q,viewConstructor:L,readerType:"byob"};if(o._pendingPullIntos.length>0){o._pendingPullIntos.push(ye),nf(D,C);return}if(D._state==="closed"){let De=new L(ye.buffer,ye.byteOffset,0);C._closeSteps(De);return}if(o._queueTotalSize>0){if(Kd(o,ye)){let De=Gd(ye);Qd(o),C._chunkSteps(De);return}if(o._closeRequested){let De=new TypeError("Insufficient bytes to fill elements in the given buffer");bt(o,De),C._errorSteps(De);return}}o._pendingPullIntos.push(ye),nf(D,C),Xr(o)}function S0(o,a){a.readerType==="none"&&bn(o);let f=o._controlledReadableByteStream;if(tu(f))for(;sf(f)>0;){let C=bn(o);Ya(f,C)}}function v0(o,a,f){if(Yd(o,a,f),f.readerType==="none"){Vd(o,f),Xa(o);return}if(f.bytesFilled<f.minimumFill)return;bn(o);let C=f.bytesFilled%f.elementSize;if(C>0){let D=f.byteOffset+f.bytesFilled;Jd(o,f.buffer,D-C,C)}f.bytesFilled-=C,Ya(o._controlledReadableByteStream,f),Xa(o)}function Xd(o,a){let f=o._pendingPullIntos.peek();Qa(o),o._controlledReadableByteStream._state==="closed"?S0(o,f):v0(o,a,f),Xr(o)}function bn(o){return o._pendingPullIntos.shift()}function k0(o){let a=o._controlledReadableByteStream;return a._state!=="readable"||o._closeRequested||!o._started?!1:!!(N(a)&&j(a)>0||tu(a)&&sf(a)>0||ef(o)>0)}function ho(o){o._pullAlgorithm=void 0,o._cancelAlgorithm=void 0}function fs(o){let a=o._controlledReadableByteStream;if(!(o._closeRequested||a._state!=="readable")){if(o._queueTotalSize>0){o._closeRequested=!0;return}if(o._pendingPullIntos.length>0){let f=o._pendingPullIntos.peek();if(f.bytesFilled%f.elementSize!==0){let C=new TypeError("Insufficient bytes to fill elements in the given buffer");throw bt(o,C),C}}ho(o),bs(a)}}function po(o,a){let f=o._controlledReadableByteStream;if(o._closeRequested||f._state!=="readable")return;let{buffer:C,byteOffset:D,byteLength:L}=a;if(Tr(C))throw new TypeError("chunk's buffer is detached and so cannot be enqueued");let q=cr(C);if(o._pendingPullIntos.length>0){let Y=o._pendingPullIntos.peek();if(Tr(Y.buffer))throw new TypeError("The BYOB request's buffer has been detached and so cannot be filled with an enqueued chunk");Qa(o),Y.buffer=cr(Y.buffer),Y.readerType==="none"&&Vd(o,Y)}if(N(f))if(E0(o),j(f)===0)fo(o,q,D,L);else{o._pendingPullIntos.length>0&&bn(o);let Y=new Uint8Array(q,D,L);P(f,Y,!1)}else tu(f)?(fo(o,q,D,L),Xa(o)):fo(o,q,D,L);Xr(o)}function bt(o,a){let f=o._controlledReadableByteStream;f._state==="readable"&&(Wd(o),Dr(o),ho(o),Rf(f,a))}function Zd(o,a){let f=o._queue.shift();o._queueTotalSize-=f.byteLength,Qd(o);let C=new Uint8Array(f.buffer,f.byteOffset,f.byteLength);a._chunkSteps(C)}function Za(o){if(o._byobRequest===null&&o._pendingPullIntos.length>0){let a=o._pendingPullIntos.peek(),f=new Uint8Array(a.buffer,a.byteOffset+a.bytesFilled,a.byteLength-a.bytesFilled),C=Object.create(Yr.prototype);D0(C,o,f),o._byobRequest=C}return o._byobRequest}function ef(o){let a=o._controlledReadableByteStream._state;return a==="errored"?null:a==="closed"?0:o._strategyHWM-o._queueTotalSize}function mo(o,a){let f=o._pendingPullIntos.peek();if(o._controlledReadableByteStream._state==="closed"){if(a!==0)throw new TypeError("bytesWritten must be 0 when calling respond() on a closed stream")}else{if(a===0)throw new TypeError("bytesWritten must be greater than 0 when calling respond() on a readable stream");if(f.bytesFilled+a>f.byteLength)throw new RangeError("bytesWritten out of range")}f.buffer=cr(f.buffer),Xd(o,a)}function go(o,a){let f=o._pendingPullIntos.peek();if(o._controlledReadableByteStream._state==="closed"){if(a.byteLength!==0)throw new TypeError("The view's length must be 0 when calling respondWithNewView() on a closed stream")}else if(a.byteLength===0)throw new TypeError("The view's length must be greater than 0 when calling respondWithNewView() on a readable stream");if(f.byteOffset+f.bytesFilled!==a.byteOffset)throw new RangeError("The region specified by view does not match byobRequest");if(f.bufferByteLength!==a.buffer.byteLength)throw new RangeError("The buffer of view has different capacity than byobRequest");if(f.bytesFilled+a.byteLength>f.byteLength)throw new RangeError("The region specified by view is larger than byobRequest");let D=a.byteLength;f.buffer=cr(a.buffer),Xd(o,D)}function tf(o,a,f,C,D,L,q){a._controlledReadableByteStream=o,a._pullAgain=!1,a._pulling=!1,a._byobRequest=null,a._queue=a._queueTotalSize=void 0,Dr(a),a._closeRequested=!1,a._started=!1,a._strategyHWM=L,a._pullAlgorithm=C,a._cancelAlgorithm=D,a._autoAllocateChunkSize=q,a._pendingPullIntos=new R,o._readableStreamController=a;let Y=f();w(h(Y),()=>(a._started=!0,Xr(a),null),ce=>(bt(a,ce),null))}function T0(o,a,f){let C=Object.create(lr.prototype),D,L,q;a.start!==void 0?D=()=>a.start(C):D=()=>{},a.pull!==void 0?L=()=>a.pull(C):L=()=>h(void 0),a.cancel!==void 0?q=ce=>a.cancel(ce):q=()=>h(void 0);let Y=a.autoAllocateChunkSize;if(Y===0)throw new TypeError("autoAllocateChunkSize must be greater than 0");tf(o,C,D,L,q,f,Y)}function D0(o,a,f){o._associatedReadableByteStreamController=a,o._view=f}function eu(o){return new TypeError(`ReadableStreamBYOBRequest.prototype.${o} can only be used on a ReadableStreamBYOBRequest`)}function hs(o){return new TypeError(`ReadableByteStreamController.prototype.${o} can only be used on a ReadableByteStreamController`)}function R0(o,a){le(o,a);let f=o?.mode;return{mode:f===void 0?void 0:x0(f,`${a} has member 'mode' that`)}}function x0(o,a){if(o=`${o}`,o!=="byob")throw new TypeError(`${a} '${o}' is not a valid enumeration value for ReadableStreamReaderMode`);return o}function O0(o,a){var f;le(o,a);let C=(f=o?.min)!==null&&f!==void 0?f:1;return{min:O(C,`${a} has member 'min' that`)}}function rf(o){return new Rr(o)}function nf(o,a){o._reader._readIntoRequests.push(a)}function F0(o,a,f){let D=o._reader._readIntoRequests.shift();f?D._closeSteps(a):D._chunkSteps(a)}function sf(o){return o._reader._readIntoRequests.length}function tu(o){let a=o._reader;return!(a===void 0||!Zr(a))}class Rr{constructor(a){if(Be(a,1,"ReadableStreamBYOBReader"),I(a,"First parameter"),Fr(a))throw new TypeError("This stream has already been locked for exclusive reading by another reader");if(!Qr(a._readableStreamController))throw new TypeError("Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte source");ue(this,a),this._readIntoRequests=new R}get closed(){return Zr(this)?this._closedPromise:d(yo("closed"))}cancel(a=void 0){return Zr(this)?this._ownerReadableStream===void 0?d(pe("cancel")):re(this,a):d(yo("cancel"))}read(a,f={}){if(!Zr(this))return d(yo("read"));if(!ArrayBuffer.isView(a))return d(new TypeError("view must be an array buffer view"));if(a.byteLength===0)return d(new TypeError("view must have non-zero byteLength"));if(a.buffer.byteLength===0)return d(new TypeError("view's buffer must have non-zero byteLength"));if(Tr(a.buffer))return d(new TypeError("view's buffer has been detached"));let C;try{C=O0(f,"options")}catch(ne){return d(ne)}let D=C.min;if(D===0)return d(new TypeError("options.min must be greater than 0"));if(C0(a)){if(D>a.byteLength)return d(new RangeError("options.min must be less than or equal to view's byteLength"))}else if(D>a.length)return d(new RangeError("options.min must be less than or equal to view's length"));if(this._ownerReadableStream===void 0)return d(pe("read from"));let L,q,Y=l((ne,fe)=>{L=ne,q=fe});return of(this,a,D,{_chunkSteps:ne=>L({value:ne,done:!1}),_closeSteps:ne=>L({value:ne,done:!0}),_errorSteps:ne=>q(ne)}),Y}releaseLock(){if(!Zr(this))throw yo("releaseLock");this._ownerReadableStream!==void 0&&P0(this)}}Object.defineProperties(Rr.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),s(Rr.prototype.cancel,"cancel"),s(Rr.prototype.read,"read"),s(Rr.prototype.releaseLock,"releaseLock"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Rr.prototype,Symbol.toStringTag,{value:"ReadableStreamBYOBReader",configurable:!0});function Zr(o){return!r(o)||!Object.prototype.hasOwnProperty.call(o,"_readIntoRequests")?!1:o instanceof Rr}function of(o,a,f,C){let D=o._ownerReadableStream;D._disturbed=!0,D._state==="errored"?C._errorSteps(D._storedError):A0(D._readableStreamController,a,f,C)}function P0(o){de(o);let a=new TypeError("Reader was released");af(o,a)}function af(o,a){let f=o._readIntoRequests;o._readIntoRequests=new R,f.forEach(C=>{C._errorSteps(a)})}function yo(o){return new TypeError(`ReadableStreamBYOBReader.prototype.${o} can only be used on a ReadableStreamBYOBReader`)}function ps(o,a){let{highWaterMark:f}=o;if(f===void 0)return a;if(ut(f)||f<0)throw new RangeError("Invalid highWaterMark");return f}function _o(o){let{size:a}=o;return a||(()=>1)}function bo(o,a){le(o,a);let f=o?.highWaterMark,C=o?.size;return{highWaterMark:f===void 0?void 0:E(f),size:C===void 0?void 0:I0(C,`${a} has member 'size' that`)}}function I0(o,a){return _e(o,a),f=>E(o(f))}function N0(o,a){le(o,a);let f=o?.abort,C=o?.close,D=o?.start,L=o?.type,q=o?.write;return{abort:f===void 0?void 0:B0(f,o,`${a} has member 'abort' that`),close:C===void 0?void 0:j0(C,o,`${a} has member 'close' that`),start:D===void 0?void 0:L0(D,o,`${a} has member 'start' that`),write:q===void 0?void 0:M0(q,o,`${a} has member 'write' that`),type:L}}function B0(o,a,f){return _e(o,f),C=>b(o,a,[C])}function j0(o,a,f){return _e(o,f),()=>b(o,a,[])}function L0(o,a,f){return _e(o,f),C=>v(o,a,[C])}function M0(o,a,f){return _e(o,f),(C,D)=>b(o,a,[C,D])}function uf(o,a){if(!Cn(o))throw new TypeError(`${a} is not a WritableStream.`)}function U0(o){if(typeof o!="object"||o===null)return!1;try{return typeof o.aborted=="boolean"}catch{return!1}}let q0=typeof AbortController=="function";function $0(){if(q0)return new AbortController}class xr{constructor(a={},f={}){a===void 0?a=null:Re(a,"First parameter");let C=bo(f,"Second parameter"),D=N0(a,"First parameter");if(lf(this),D.type!==void 0)throw new RangeError("Invalid type is specified");let q=_o(C),Y=ps(C,1);r_(this,D,Y,q)}get locked(){if(!Cn(this))throw So("locked");return wn(this)}abort(a=void 0){return Cn(this)?wn(this)?d(new TypeError("Cannot abort a stream that already has a writer")):Co(this,a):d(So("abort"))}close(){return Cn(this)?wn(this)?d(new TypeError("Cannot close a stream that already has a writer")):Wt(this)?d(new TypeError("Cannot close an already-closing stream")):df(this):d(So("close"))}getWriter(){if(!Cn(this))throw So("getWriter");return cf(this)}}Object.defineProperties(xr.prototype,{abort:{enumerable:!0},close:{enumerable:!0},getWriter:{enumerable:!0},locked:{enumerable:!0}}),s(xr.prototype.abort,"abort"),s(xr.prototype.close,"close"),s(xr.prototype.getWriter,"getWriter"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(xr.prototype,Symbol.toStringTag,{value:"WritableStream",configurable:!0});function cf(o){return new dr(o)}function z0(o,a,f,C,D=1,L=()=>1){let q=Object.create(xr.prototype);lf(q);let Y=Object.create(En.prototype);return yf(q,Y,o,a,f,C,D,L),q}function lf(o){o._state="writable",o._storedError=void 0,o._writer=void 0,o._writableStreamController=void 0,o._writeRequests=new R,o._inFlightWriteRequest=void 0,o._closeRequest=void 0,o._inFlightCloseRequest=void 0,o._pendingAbortRequest=void 0,o._backpressure=!1}function Cn(o){return!r(o)||!Object.prototype.hasOwnProperty.call(o,"_writableStreamController")?!1:o instanceof xr}function wn(o){return o._writer!==void 0}function Co(o,a){var f;if(o._state==="closed"||o._state==="errored")return h(void 0);o._writableStreamController._abortReason=a,(f=o._writableStreamController._abortController)===null||f===void 0||f.abort(a);let C=o._state;if(C==="closed"||C==="errored")return h(void 0);if(o._pendingAbortRequest!==void 0)return o._pendingAbortRequest._promise;let D=!1;C==="erroring"&&(D=!0,a=void 0);let L=l((q,Y)=>{o._pendingAbortRequest={_promise:void 0,_resolve:q,_reject:Y,_reason:a,_wasAlreadyErroring:D}});return o._pendingAbortRequest._promise=L,D||nu(o,a),L}function df(o){let a=o._state;if(a==="closed"||a==="errored")return d(new TypeError(`The stream (in ${a} state) is not in the writable state and cannot be closed`));let f=l((D,L)=>{let q={_resolve:D,_reject:L};o._closeRequest=q}),C=o._writer;return C!==void 0&&o._backpressure&&a==="writable"&&du(C),n_(o._writableStreamController),f}function H0(o){return l((f,C)=>{let D={_resolve:f,_reject:C};o._writeRequests.push(D)})}function ru(o,a){if(o._state==="writable"){nu(o,a);return}su(o)}function nu(o,a){let f=o._writableStreamController;o._state="erroring",o._storedError=a;let C=o._writer;C!==void 0&&hf(C,a),!K0(o)&&f._started&&su(o)}function su(o){o._state="errored",o._writableStreamController[$]();let a=o._storedError;if(o._writeRequests.forEach(D=>{D._reject(a)}),o._writeRequests=new R,o._pendingAbortRequest===void 0){wo(o);return}let f=o._pendingAbortRequest;if(o._pendingAbortRequest=void 0,f._wasAlreadyErroring){f._reject(a),wo(o);return}let C=o._writableStreamController[F](f._reason);w(C,()=>(f._resolve(),wo(o),null),D=>(f._reject(D),wo(o),null))}function W0(o){o._inFlightWriteRequest._resolve(void 0),o._inFlightWriteRequest=void 0}function G0(o,a){o._inFlightWriteRequest._reject(a),o._inFlightWriteRequest=void 0,ru(o,a)}function J0(o){o._inFlightCloseRequest._resolve(void 0),o._inFlightCloseRequest=void 0,o._state==="erroring"&&(o._storedError=void 0,o._pendingAbortRequest!==void 0&&(o._pendingAbortRequest._resolve(),o._pendingAbortRequest=void 0)),o._state="closed";let f=o._writer;f!==void 0&&wf(f)}function V0(o,a){o._inFlightCloseRequest._reject(a),o._inFlightCloseRequest=void 0,o._pendingAbortRequest!==void 0&&(o._pendingAbortRequest._reject(a),o._pendingAbortRequest=void 0),ru(o,a)}function Wt(o){return!(o._closeRequest===void 0&&o._inFlightCloseRequest===void 0)}function K0(o){return!(o._inFlightWriteRequest===void 0&&o._inFlightCloseRequest===void 0)}function Y0(o){o._inFlightCloseRequest=o._closeRequest,o._closeRequest=void 0}function Q0(o){o._inFlightWriteRequest=o._writeRequests.shift()}function wo(o){o._closeRequest!==void 0&&(o._closeRequest._reject(o._storedError),o._closeRequest=void 0);let a=o._writer;a!==void 0&&cu(a,o._storedError)}function ou(o,a){let f=o._writer;f!==void 0&&a!==o._backpressure&&(a?l_(f):du(f)),o._backpressure=a}class dr{constructor(a){if(Be(a,1,"WritableStreamDefaultWriter"),uf(a,"First parameter"),wn(a))throw new TypeError("This stream has already been locked for exclusive writing by another writer");this._ownerWritableStream=a,a._writer=this;let f=a._state;if(f==="writable")!Wt(a)&&a._backpressure?ko(this):Ef(this),vo(this);else if(f==="erroring")lu(this,a._storedError),vo(this);else if(f==="closed")Ef(this),u_(this);else{let C=a._storedError;lu(this,C),Cf(this,C)}}get closed(){return en(this)?this._closedPromise:d(tn("closed"))}get desiredSize(){if(!en(this))throw tn("desiredSize");if(this._ownerWritableStream===void 0)throw gs("desiredSize");return t_(this)}get ready(){return en(this)?this._readyPromise:d(tn("ready"))}abort(a=void 0){return en(this)?this._ownerWritableStream===void 0?d(gs("abort")):X0(this,a):d(tn("abort"))}close(){if(!en(this))return d(tn("close"));let a=this._ownerWritableStream;return a===void 0?d(gs("close")):Wt(a)?d(new TypeError("Cannot close an already-closing stream")):ff(this)}releaseLock(){if(!en(this))throw tn("releaseLock");this._ownerWritableStream!==void 0&&pf(this)}write(a=void 0){return en(this)?this._ownerWritableStream===void 0?d(gs("write to")):mf(this,a):d(tn("write"))}}Object.defineProperties(dr.prototype,{abort:{enumerable:!0},close:{enumerable:!0},releaseLock:{enumerable:!0},write:{enumerable:!0},closed:{enumerable:!0},desiredSize:{enumerable:!0},ready:{enumerable:!0}}),s(dr.prototype.abort,"abort"),s(dr.prototype.close,"close"),s(dr.prototype.releaseLock,"releaseLock"),s(dr.prototype.write,"write"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(dr.prototype,Symbol.toStringTag,{value:"WritableStreamDefaultWriter",configurable:!0});function en(o){return!r(o)||!Object.prototype.hasOwnProperty.call(o,"_ownerWritableStream")?!1:o instanceof dr}function X0(o,a){let f=o._ownerWritableStream;return Co(f,a)}function ff(o){let a=o._ownerWritableStream;return df(a)}function Z0(o){let a=o._ownerWritableStream,f=a._state;return Wt(a)||f==="closed"?h(void 0):f==="errored"?d(a._storedError):ff(o)}function e_(o,a){o._closedPromiseState==="pending"?cu(o,a):c_(o,a)}function hf(o,a){o._readyPromiseState==="pending"?Af(o,a):d_(o,a)}function t_(o){let a=o._ownerWritableStream,f=a._state;return f==="errored"||f==="erroring"?null:f==="closed"?0:_f(a._writableStreamController)}function pf(o){let a=o._ownerWritableStream,f=new TypeError("Writer was released and can no longer be used to monitor the stream's closedness");hf(o,f),e_(o,f),a._writer=void 0,o._ownerWritableStream=void 0}function mf(o,a){let f=o._ownerWritableStream,C=f._writableStreamController,D=s_(C,a);if(f!==o._ownerWritableStream)return d(gs("write to"));let L=f._state;if(L==="errored")return d(f._storedError);if(Wt(f)||L==="closed")return d(new TypeError("The stream is closing or closed and cannot be written to"));if(L==="erroring")return d(f._storedError);let q=H0(f);return o_(C,a,D),q}let gf={};class En{constructor(){throw new TypeError("Illegal constructor")}get abortReason(){if(!iu(this))throw uu("abortReason");return this._abortReason}get signal(){if(!iu(this))throw uu("signal");if(this._abortController===void 0)throw new TypeError("WritableStreamDefaultController.prototype.signal is not supported");return this._abortController.signal}error(a=void 0){if(!iu(this))throw uu("error");this._controlledWritableStream._state==="writable"&&bf(this,a)}[F](a){let f=this._abortAlgorithm(a);return Eo(this),f}[$](){Dr(this)}}Object.defineProperties(En.prototype,{abortReason:{enumerable:!0},signal:{enumerable:!0},error:{enumerable:!0}}),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(En.prototype,Symbol.toStringTag,{value:"WritableStreamDefaultController",configurable:!0});function iu(o){return!r(o)||!Object.prototype.hasOwnProperty.call(o,"_controlledWritableStream")?!1:o instanceof En}function yf(o,a,f,C,D,L,q,Y){a._controlledWritableStream=o,o._writableStreamController=a,a._queue=void 0,a._queueTotalSize=void 0,Dr(a),a._abortReason=void 0,a._abortController=$0(),a._started=!1,a._strategySizeAlgorithm=Y,a._strategyHWM=q,a._writeAlgorithm=C,a._closeAlgorithm=D,a._abortAlgorithm=L;let ce=au(a);ou(o,ce);let ne=f(),fe=h(ne);w(fe,()=>(a._started=!0,Ao(a),null),ye=>(a._started=!0,ru(o,ye),null))}function r_(o,a,f,C){let D=Object.create(En.prototype),L,q,Y,ce;a.start!==void 0?L=()=>a.start(D):L=()=>{},a.write!==void 0?q=ne=>a.write(ne,D):q=()=>h(void 0),a.close!==void 0?Y=()=>a.close():Y=()=>h(void 0),a.abort!==void 0?ce=ne=>a.abort(ne):ce=()=>h(void 0),yf(o,D,L,q,Y,ce,f,C)}function Eo(o){o._writeAlgorithm=void 0,o._closeAlgorithm=void 0,o._abortAlgorithm=void 0,o._strategySizeAlgorithm=void 0}function n_(o){Va(o,gf,0),Ao(o)}function s_(o,a){try{return o._strategySizeAlgorithm(a)}catch(f){return ms(o,f),1}}function _f(o){return o._strategyHWM-o._queueTotalSize}function o_(o,a,f){try{Va(o,a,f)}catch(D){ms(o,D);return}let C=o._controlledWritableStream;if(!Wt(C)&&C._state==="writable"){let D=au(o);ou(C,D)}Ao(o)}function Ao(o){let a=o._controlledWritableStream;if(!o._started||a._inFlightWriteRequest!==void 0)return;if(a._state==="erroring"){su(a);return}if(o._queue.length===0)return;let C=b0(o);C===gf?i_(o):a_(o,C)}function ms(o,a){o._controlledWritableStream._state==="writable"&&bf(o,a)}function i_(o){let a=o._controlledWritableStream;Y0(a),Ja(o);let f=o._closeAlgorithm();Eo(o),w(f,()=>(J0(a),null),C=>(V0(a,C),null))}function a_(o,a){let f=o._controlledWritableStream;Q0(f);let C=o._writeAlgorithm(a);w(C,()=>{W0(f);let D=f._state;if(Ja(o),!Wt(f)&&D==="writable"){let L=au(o);ou(f,L)}return Ao(o),null},D=>(f._state==="writable"&&Eo(o),G0(f,D),null))}function au(o){return _f(o)<=0}function bf(o,a){let f=o._controlledWritableStream;Eo(o),nu(f,a)}function So(o){return new TypeError(`WritableStream.prototype.${o} can only be used on a WritableStream`)}function uu(o){return new TypeError(`WritableStreamDefaultController.prototype.${o} can only be used on a WritableStreamDefaultController`)}function tn(o){return new TypeError(`WritableStreamDefaultWriter.prototype.${o} can only be used on a WritableStreamDefaultWriter`)}function gs(o){return new TypeError("Cannot "+o+" a stream using a released writer")}function vo(o){o._closedPromise=l((a,f)=>{o._closedPromise_resolve=a,o._closedPromise_reject=f,o._closedPromiseState="pending"})}function Cf(o,a){vo(o),cu(o,a)}function u_(o){vo(o),wf(o)}function cu(o,a){o._closedPromise_reject!==void 0&&(g(o._closedPromise),o._closedPromise_reject(a),o._closedPromise_resolve=void 0,o._closedPromise_reject=void 0,o._closedPromiseState="rejected")}function c_(o,a){Cf(o,a)}function wf(o){o._closedPromise_resolve!==void 0&&(o._closedPromise_resolve(void 0),o._closedPromise_resolve=void 0,o._closedPromise_reject=void 0,o._closedPromiseState="resolved")}function ko(o){o._readyPromise=l((a,f)=>{o._readyPromise_resolve=a,o._readyPromise_reject=f}),o._readyPromiseState="pending"}function lu(o,a){ko(o),Af(o,a)}function Ef(o){ko(o),du(o)}function Af(o,a){o._readyPromise_reject!==void 0&&(g(o._readyPromise),o._readyPromise_reject(a),o._readyPromise_resolve=void 0,o._readyPromise_reject=void 0,o._readyPromiseState="rejected")}function l_(o){ko(o)}function d_(o,a){lu(o,a)}function du(o){o._readyPromise_resolve!==void 0&&(o._readyPromise_resolve(void 0),o._readyPromise_resolve=void 0,o._readyPromise_reject=void 0,o._readyPromiseState="fulfilled")}function f_(){if(typeof globalThis<"u")return globalThis;if(typeof self<"u")return self;if(typeof global<"u")return global}let fu=f_();function h_(o){if(!(typeof o=="function"||typeof o=="object")||o.name!=="DOMException")return!1;try{return new o,!0}catch{return!1}}function p_(){let o=fu?.DOMException;return h_(o)?o:void 0}function m_(){let o=function(f,C){this.message=f||"",this.name=C||"Error",Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)};return s(o,"DOMException"),o.prototype=Object.create(Error.prototype),Object.defineProperty(o.prototype,"constructor",{value:o,writable:!0,configurable:!0}),o}let g_=p_()||m_();function Sf(o,a,f,C,D,L){let q=U(o),Y=cf(a);o._disturbed=!0;let ce=!1,ne=h(void 0);return l((fe,ye)=>{let De;if(L!==void 0){if(De=()=>{let se=L.reason!==void 0?L.reason:new g_("Aborted","AbortError"),be=[];C||be.push(()=>a._state==="writable"?Co(a,se):h(void 0)),D||be.push(()=>o._state==="readable"?Pt(o,se):h(void 0)),rt(()=>Promise.all(be.map(xe=>xe())),!0,se)},L.aborted){De();return}L.addEventListener("abort",De)}function It(){return l((se,be)=>{function xe(ct){ct?se():p(kn(),xe,be)}xe(!1)})}function kn(){return ce?h(!0):p(Y._readyPromise,()=>l((se,be)=>{ee(q,{_chunkSteps:xe=>{ne=p(mf(Y,xe),void 0,e),se(!1)},_closeSteps:()=>se(!0),_errorSteps:be})}))}if(hr(o,q._closedPromise,se=>(C?Ct(!0,se):rt(()=>Co(a,se),!0,se),null)),hr(a,Y._closedPromise,se=>(D?Ct(!0,se):rt(()=>Pt(o,se),!0,se),null)),Xe(o,q._closedPromise,()=>(f?Ct():rt(()=>Z0(Y)),null)),Wt(a)||a._state==="closed"){let se=new TypeError("the destination writable stream closed before all data could be piped to it");D?Ct(!0,se):rt(()=>Pt(o,se),!0,se)}g(It());function Ir(){let se=ne;return p(ne,()=>se!==ne?Ir():void 0)}function hr(se,be,xe){se._state==="errored"?xe(se._storedError):S(be,xe)}function Xe(se,be,xe){se._state==="closed"?xe():T(be,xe)}function rt(se,be,xe){if(ce)return;ce=!0,a._state==="writable"&&!Wt(a)?T(Ir(),ct):ct();function ct(){return w(se(),()=>pr(be,xe),Tn=>pr(!0,Tn)),null}}function Ct(se,be){ce||(ce=!0,a._state==="writable"&&!Wt(a)?T(Ir(),()=>pr(se,be)):pr(se,be))}function pr(se,be){return pf(Y),de(q),L!==void 0&&L.removeEventListener("abort",De),se?ye(be):fe(void 0),null}})}class fr{constructor(){throw new TypeError("Illegal constructor")}get desiredSize(){if(!To(this))throw Ro("desiredSize");return hu(this)}close(){if(!To(this))throw Ro("close");if(!Sn(this))throw new TypeError("The stream is not in a state that permits close");rn(this)}enqueue(a=void 0){if(!To(this))throw Ro("enqueue");if(!Sn(this))throw new TypeError("The stream is not in a state that permits enqueue");return An(this,a)}error(a=void 0){if(!To(this))throw Ro("error");Ft(this,a)}[J](a){Dr(this);let f=this._cancelAlgorithm(a);return Do(this),f}[M](a){let f=this._controlledReadableStream;if(this._queue.length>0){let C=Ja(this);this._closeRequested&&this._queue.length===0?(Do(this),bs(f)):ys(this),a._chunkSteps(C)}else x(f,a),ys(this)}[Q](){}}Object.defineProperties(fr.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},desiredSize:{enumerable:!0}}),s(fr.prototype.close,"close"),s(fr.prototype.enqueue,"enqueue"),s(fr.prototype.error,"error"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(fr.prototype,Symbol.toStringTag,{value:"ReadableStreamDefaultController",configurable:!0});function To(o){return!r(o)||!Object.prototype.hasOwnProperty.call(o,"_controlledReadableStream")?!1:o instanceof fr}function ys(o){if(!vf(o))return;if(o._pulling){o._pullAgain=!0;return}o._pulling=!0;let f=o._pullAlgorithm();w(f,()=>(o._pulling=!1,o._pullAgain&&(o._pullAgain=!1,ys(o)),null),C=>(Ft(o,C),null))}function vf(o){let a=o._controlledReadableStream;return!Sn(o)||!o._started?!1:!!(Fr(a)&&j(a)>0||hu(o)>0)}function Do(o){o._pullAlgorithm=void 0,o._cancelAlgorithm=void 0,o._strategySizeAlgorithm=void 0}function rn(o){if(!Sn(o))return;let a=o._controlledReadableStream;o._closeRequested=!0,o._queue.length===0&&(Do(o),bs(a))}function An(o,a){if(!Sn(o))return;let f=o._controlledReadableStream;if(Fr(f)&&j(f)>0)P(f,a,!1);else{let C;try{C=o._strategySizeAlgorithm(a)}catch(D){throw Ft(o,D),D}try{Va(o,a,C)}catch(D){throw Ft(o,D),D}}ys(o)}function Ft(o,a){let f=o._controlledReadableStream;f._state==="readable"&&(Dr(o),Do(o),Rf(f,a))}function hu(o){let a=o._controlledReadableStream._state;return a==="errored"?null:a==="closed"?0:o._strategyHWM-o._queueTotalSize}function y_(o){return!vf(o)}function Sn(o){let a=o._controlledReadableStream._state;return!o._closeRequested&&a==="readable"}function kf(o,a,f,C,D,L,q){a._controlledReadableStream=o,a._queue=void 0,a._queueTotalSize=void 0,Dr(a),a._started=!1,a._closeRequested=!1,a._pullAgain=!1,a._pulling=!1,a._strategySizeAlgorithm=q,a._strategyHWM=L,a._pullAlgorithm=C,a._cancelAlgorithm=D,o._readableStreamController=a;let Y=f();w(h(Y),()=>(a._started=!0,ys(a),null),ce=>(Ft(a,ce),null))}function __(o,a,f,C){let D=Object.create(fr.prototype),L,q,Y;a.start!==void 0?L=()=>a.start(D):L=()=>{},a.pull!==void 0?q=()=>a.pull(D):q=()=>h(void 0),a.cancel!==void 0?Y=ce=>a.cancel(ce):Y=()=>h(void 0),kf(o,D,L,q,Y,f,C)}function Ro(o){return new TypeError(`ReadableStreamDefaultController.prototype.${o} can only be used on a ReadableStreamDefaultController`)}function b_(o,a){return Qr(o._readableStreamController)?w_(o):C_(o)}function C_(o,a){let f=U(o),C=!1,D=!1,L=!1,q=!1,Y,ce,ne,fe,ye,De=l(Xe=>{ye=Xe});function It(){return C?(D=!0,h(void 0)):(C=!0,ee(f,{_chunkSteps:rt=>{m(()=>{D=!1;let Ct=rt,pr=rt;L||An(ne._readableStreamController,Ct),q||An(fe._readableStreamController,pr),C=!1,D&&It()})},_closeSteps:()=>{C=!1,L||rn(ne._readableStreamController),q||rn(fe._readableStreamController),(!L||!q)&&ye(void 0)},_errorSteps:()=>{C=!1}}),h(void 0))}function kn(Xe){if(L=!0,Y=Xe,q){let rt=ve([Y,ce]),Ct=Pt(o,rt);ye(Ct)}return De}function Ir(Xe){if(q=!0,ce=Xe,L){let rt=ve([Y,ce]),Ct=Pt(o,rt);ye(Ct)}return De}function hr(){}return ne=_s(hr,It,kn),fe=_s(hr,It,Ir),S(f._closedPromise,Xe=>(Ft(ne._readableStreamController,Xe),Ft(fe._readableStreamController,Xe),(!L||!q)&&ye(void 0),null)),[ne,fe]}function w_(o){let a=U(o),f=!1,C=!1,D=!1,L=!1,q=!1,Y,ce,ne,fe,ye,De=l(se=>{ye=se});function It(se){S(se._closedPromise,be=>(se!==a||(bt(ne._readableStreamController,be),bt(fe._readableStreamController,be),(!L||!q)&&ye(void 0)),null))}function kn(){Zr(a)&&(de(a),a=U(o),It(a)),ee(a,{_chunkSteps:be=>{m(()=>{C=!1,D=!1;let xe=be,ct=be;if(!L&&!q)try{ct=zd(be)}catch(Tn){bt(ne._readableStreamController,Tn),bt(fe._readableStreamController,Tn),ye(Pt(o,Tn));return}L||po(ne._readableStreamController,xe),q||po(fe._readableStreamController,ct),f=!1,C?hr():D&&Xe()})},_closeSteps:()=>{f=!1,L||fs(ne._readableStreamController),q||fs(fe._readableStreamController),ne._readableStreamController._pendingPullIntos.length>0&&mo(ne._readableStreamController,0),fe._readableStreamController._pendingPullIntos.length>0&&mo(fe._readableStreamController,0),(!L||!q)&&ye(void 0)},_errorSteps:()=>{f=!1}})}function Ir(se,be){Z(a)&&(de(a),a=rf(o),It(a));let xe=be?fe:ne,ct=be?ne:fe;of(a,se,1,{_chunkSteps:Dn=>{m(()=>{C=!1,D=!1;let Rn=be?q:L;if(be?L:q)Rn||go(xe._readableStreamController,Dn);else{let $f;try{$f=zd(Dn)}catch(_u){bt(xe._readableStreamController,_u),bt(ct._readableStreamController,_u),ye(Pt(o,_u));return}Rn||go(xe._readableStreamController,Dn),po(ct._readableStreamController,$f)}f=!1,C?hr():D&&Xe()})},_closeSteps:Dn=>{f=!1;let Rn=be?q:L,jo=be?L:q;Rn||fs(xe._readableStreamController),jo||fs(ct._readableStreamController),Dn!==void 0&&(Rn||go(xe._readableStreamController,Dn),!jo&&ct._readableStreamController._pendingPullIntos.length>0&&mo(ct._readableStreamController,0)),(!Rn||!jo)&&ye(void 0)},_errorSteps:()=>{f=!1}})}function hr(){if(f)return C=!0,h(void 0);f=!0;let se=Za(ne._readableStreamController);return se===null?kn():Ir(se._view,!1),h(void 0)}function Xe(){if(f)return D=!0,h(void 0);f=!0;let se=Za(fe._readableStreamController);return se===null?kn():Ir(se._view,!0),h(void 0)}function rt(se){if(L=!0,Y=se,q){let be=ve([Y,ce]),xe=Pt(o,be);ye(xe)}return De}function Ct(se){if(q=!0,ce=se,L){let be=ve([Y,ce]),xe=Pt(o,be);ye(xe)}return De}function pr(){}return ne=Df(pr,hr,rt),fe=Df(pr,Xe,Ct),It(a),[ne,fe]}function E_(o){return r(o)&&typeof o.getReader<"u"}function A_(o){return E_(o)?v_(o.getReader()):S_(o)}function S_(o){let a,f=$d(o,"async"),C=e;function D(){let q;try{q=m0(f)}catch(ce){return d(ce)}let Y=h(q);return y(Y,ce=>{if(!r(ce))throw new TypeError("The promise returned by the iterator.next() method must fulfill with an object");if(g0(ce))rn(a._readableStreamController);else{let fe=y0(ce);An(a._readableStreamController,fe)}})}function L(q){let Y=f.iterator,ce;try{ce=lo(Y,"return")}catch(ye){return d(ye)}if(ce===void 0)return h(void 0);let ne;try{ne=v(ce,Y,[q])}catch(ye){return d(ye)}let fe=h(ne);return y(fe,ye=>{if(!r(ye))throw new TypeError("The promise returned by the iterator.return() method must fulfill with an object")})}return a=_s(C,D,L,0),a}function v_(o){let a,f=e;function C(){let L;try{L=o.read()}catch(q){return d(q)}return y(L,q=>{if(!r(q))throw new TypeError("The promise returned by the reader.read() method must fulfill with an object");if(q.done)rn(a._readableStreamController);else{let Y=q.value;An(a._readableStreamController,Y)}})}function D(L){try{return h(o.cancel(L))}catch(q){return d(q)}}return a=_s(f,C,D,0),a}function k_(o,a){le(o,a);let f=o,C=f?.autoAllocateChunkSize,D=f?.cancel,L=f?.pull,q=f?.start,Y=f?.type;return{autoAllocateChunkSize:C===void 0?void 0:O(C,`${a} has member 'autoAllocateChunkSize' that`),cancel:D===void 0?void 0:T_(D,f,`${a} has member 'cancel' that`),pull:L===void 0?void 0:D_(L,f,`${a} has member 'pull' that`),start:q===void 0?void 0:R_(q,f,`${a} has member 'start' that`),type:Y===void 0?void 0:x_(Y,`${a} has member 'type' that`)}}function T_(o,a,f){return _e(o,f),C=>b(o,a,[C])}function D_(o,a,f){return _e(o,f),C=>b(o,a,[C])}function R_(o,a,f){return _e(o,f),C=>v(o,a,[C])}function x_(o,a){if(o=`${o}`,o!=="bytes")throw new TypeError(`${a} '${o}' is not a valid enumeration value for ReadableStreamType`);return o}function O_(o,a){return le(o,a),{preventCancel:!!o?.preventCancel}}function Tf(o,a){le(o,a);let f=o?.preventAbort,C=o?.preventCancel,D=o?.preventClose,L=o?.signal;return L!==void 0&&F_(L,`${a} has member 'signal' that`),{preventAbort:!!f,preventCancel:!!C,preventClose:!!D,signal:L}}function F_(o,a){if(!U0(o))throw new TypeError(`${a} is not an AbortSignal.`)}function P_(o,a){le(o,a);let f=o?.readable;_(f,"readable","ReadableWritablePair"),I(f,`${a} has member 'readable' that`);let C=o?.writable;return _(C,"writable","ReadableWritablePair"),uf(C,`${a} has member 'writable' that`),{readable:f,writable:C}}class Ye{constructor(a={},f={}){a===void 0?a=null:Re(a,"First parameter");let C=bo(f,"Second parameter"),D=k_(a,"First parameter");if(pu(this),D.type==="bytes"){if(C.size!==void 0)throw new RangeError("The strategy for a byte stream cannot have a size function");let L=ps(C,0);T0(this,D,L)}else{let L=_o(C),q=ps(C,1);__(this,D,q,L)}}get locked(){if(!Or(this))throw nn("locked");return Fr(this)}cancel(a=void 0){return Or(this)?Fr(this)?d(new TypeError("Cannot cancel a stream that already has a reader")):Pt(this,a):d(nn("cancel"))}getReader(a=void 0){if(!Or(this))throw nn("getReader");return R0(a,"First parameter").mode===void 0?U(this):rf(this)}pipeThrough(a,f={}){if(!Or(this))throw nn("pipeThrough");Be(a,1,"pipeThrough");let C=P_(a,"First parameter"),D=Tf(f,"Second parameter");if(Fr(this))throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream");if(wn(C.writable))throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream");let L=Sf(this,C.writable,D.preventClose,D.preventAbort,D.preventCancel,D.signal);return g(L),C.readable}pipeTo(a,f={}){if(!Or(this))return d(nn("pipeTo"));if(a===void 0)return d("Parameter 1 is required in 'pipeTo'.");if(!Cn(a))return d(new TypeError("ReadableStream.prototype.pipeTo's first argument must be a WritableStream"));let C;try{C=Tf(f,"Second parameter")}catch(D){return d(D)}return Fr(this)?d(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream")):wn(a)?d(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream")):Sf(this,a,C.preventClose,C.preventAbort,C.preventCancel,C.signal)}tee(){if(!Or(this))throw nn("tee");let a=b_(this);return ve(a)}values(a=void 0){if(!Or(this))throw nn("values");let f=O_(a,"First parameter");return gn(this,f.preventCancel)}[Ga](a){return this.values(a)}static from(a){return A_(a)}}Object.defineProperties(Ye,{from:{enumerable:!0}}),Object.defineProperties(Ye.prototype,{cancel:{enumerable:!0},getReader:{enumerable:!0},pipeThrough:{enumerable:!0},pipeTo:{enumerable:!0},tee:{enumerable:!0},values:{enumerable:!0},locked:{enumerable:!0}}),s(Ye.from,"from"),s(Ye.prototype.cancel,"cancel"),s(Ye.prototype.getReader,"getReader"),s(Ye.prototype.pipeThrough,"pipeThrough"),s(Ye.prototype.pipeTo,"pipeTo"),s(Ye.prototype.tee,"tee"),s(Ye.prototype.values,"values"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Ye.prototype,Symbol.toStringTag,{value:"ReadableStream",configurable:!0}),Object.defineProperty(Ye.prototype,Ga,{value:Ye.prototype.values,writable:!0,configurable:!0});function _s(o,a,f,C=1,D=()=>1){let L=Object.create(Ye.prototype);pu(L);let q=Object.create(fr.prototype);return kf(L,q,o,a,f,C,D),L}function Df(o,a,f){let C=Object.create(Ye.prototype);pu(C);let D=Object.create(lr.prototype);return tf(C,D,o,a,f,0,void 0),C}function pu(o){o._state="readable",o._reader=void 0,o._storedError=void 0,o._disturbed=!1}function Or(o){return!r(o)||!Object.prototype.hasOwnProperty.call(o,"_readableStreamController")?!1:o instanceof Ye}function Fr(o){return o._reader!==void 0}function Pt(o,a){if(o._disturbed=!0,o._state==="closed")return h(void 0);if(o._state==="errored")return d(o._storedError);bs(o);let f=o._reader;if(f!==void 0&&Zr(f)){let D=f._readIntoRequests;f._readIntoRequests=new R,D.forEach(L=>{L._closeSteps(void 0)})}let C=o._readableStreamController[J](a);return y(C,e)}function bs(o){o._state="closed";let a=o._reader;if(a!==void 0&&(ae(a),Z(a))){let f=a._readRequests;a._readRequests=new R,f.forEach(C=>{C._closeSteps()})}}function Rf(o,a){o._state="errored",o._storedError=a;let f=o._reader;f!==void 0&&(G(f,a),Z(f)?Fe(f,a):af(f,a))}function nn(o){return new TypeError(`ReadableStream.prototype.${o} can only be used on a ReadableStream`)}function xf(o,a){le(o,a);let f=o?.highWaterMark;return _(f,"highWaterMark","QueuingStrategyInit"),{highWaterMark:E(f)}}let Of=o=>o.byteLength;s(Of,"size");class xo{constructor(a){Be(a,1,"ByteLengthQueuingStrategy"),a=xf(a,"First parameter"),this._byteLengthQueuingStrategyHighWaterMark=a.highWaterMark}get highWaterMark(){if(!Pf(this))throw Ff("highWaterMark");return this._byteLengthQueuingStrategyHighWaterMark}get size(){if(!Pf(this))throw Ff("size");return Of}}Object.defineProperties(xo.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(xo.prototype,Symbol.toStringTag,{value:"ByteLengthQueuingStrategy",configurable:!0});function Ff(o){return new TypeError(`ByteLengthQueuingStrategy.prototype.${o} can only be used on a ByteLengthQueuingStrategy`)}function Pf(o){return!r(o)||!Object.prototype.hasOwnProperty.call(o,"_byteLengthQueuingStrategyHighWaterMark")?!1:o instanceof xo}let If=()=>1;s(If,"size");class Oo{constructor(a){Be(a,1,"CountQueuingStrategy"),a=xf(a,"First parameter"),this._countQueuingStrategyHighWaterMark=a.highWaterMark}get highWaterMark(){if(!Bf(this))throw Nf("highWaterMark");return this._countQueuingStrategyHighWaterMark}get size(){if(!Bf(this))throw Nf("size");return If}}Object.defineProperties(Oo.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Oo.prototype,Symbol.toStringTag,{value:"CountQueuingStrategy",configurable:!0});function Nf(o){return new TypeError(`CountQueuingStrategy.prototype.${o} can only be used on a CountQueuingStrategy`)}function Bf(o){return!r(o)||!Object.prototype.hasOwnProperty.call(o,"_countQueuingStrategyHighWaterMark")?!1:o instanceof Oo}function I_(o,a){le(o,a);let f=o?.cancel,C=o?.flush,D=o?.readableType,L=o?.start,q=o?.transform,Y=o?.writableType;return{cancel:f===void 0?void 0:L_(f,o,`${a} has member 'cancel' that`),flush:C===void 0?void 0:N_(C,o,`${a} has member 'flush' that`),readableType:D,start:L===void 0?void 0:B_(L,o,`${a} has member 'start' that`),transform:q===void 0?void 0:j_(q,o,`${a} has member 'transform' that`),writableType:Y}}function N_(o,a,f){return _e(o,f),C=>b(o,a,[C])}function B_(o,a,f){return _e(o,f),C=>v(o,a,[C])}function j_(o,a,f){return _e(o,f),(C,D)=>b(o,a,[C,D])}function L_(o,a,f){return _e(o,f),C=>b(o,a,[C])}class Fo{constructor(a={},f={},C={}){a===void 0&&(a=null);let D=bo(f,"Second parameter"),L=bo(C,"Third parameter"),q=I_(a,"First parameter");if(q.readableType!==void 0)throw new RangeError("Invalid readableType specified");if(q.writableType!==void 0)throw new RangeError("Invalid writableType specified");let Y=ps(L,0),ce=_o(L),ne=ps(D,1),fe=_o(D),ye,De=l(It=>{ye=It});M_(this,De,ne,fe,Y,ce),q_(this,q),q.start!==void 0?ye(q.start(this._transformStreamController)):ye(void 0)}get readable(){if(!jf(this))throw qf("readable");return this._readable}get writable(){if(!jf(this))throw qf("writable");return this._writable}}Object.defineProperties(Fo.prototype,{readable:{enumerable:!0},writable:{enumerable:!0}}),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Fo.prototype,Symbol.toStringTag,{value:"TransformStream",configurable:!0});function M_(o,a,f,C,D,L){function q(){return a}function Y(De){return H_(o,De)}function ce(De){return W_(o,De)}function ne(){return G_(o)}o._writable=z0(q,Y,ne,ce,f,C);function fe(){return J_(o)}function ye(De){return V_(o,De)}o._readable=_s(q,fe,ye,D,L),o._backpressure=void 0,o._backpressureChangePromise=void 0,o._backpressureChangePromise_resolve=void 0,Po(o,!0),o._transformStreamController=void 0}function jf(o){return!r(o)||!Object.prototype.hasOwnProperty.call(o,"_transformStreamController")?!1:o instanceof Fo}function Lf(o,a){Ft(o._readable._readableStreamController,a),mu(o,a)}function mu(o,a){No(o._transformStreamController),ms(o._writable._writableStreamController,a),gu(o)}function gu(o){o._backpressure&&Po(o,!1)}function Po(o,a){o._backpressureChangePromise!==void 0&&o._backpressureChangePromise_resolve(),o._backpressureChangePromise=l(f=>{o._backpressureChangePromise_resolve=f}),o._backpressure=a}class Pr{constructor(){throw new TypeError("Illegal constructor")}get desiredSize(){if(!Io(this))throw Bo("desiredSize");let a=this._controlledTransformStream._readable._readableStreamController;return hu(a)}enqueue(a=void 0){if(!Io(this))throw Bo("enqueue");Mf(this,a)}error(a=void 0){if(!Io(this))throw Bo("error");$_(this,a)}terminate(){if(!Io(this))throw Bo("terminate");z_(this)}}Object.defineProperties(Pr.prototype,{enqueue:{enumerable:!0},error:{enumerable:!0},terminate:{enumerable:!0},desiredSize:{enumerable:!0}}),s(Pr.prototype.enqueue,"enqueue"),s(Pr.prototype.error,"error"),s(Pr.prototype.terminate,"terminate"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Pr.prototype,Symbol.toStringTag,{value:"TransformStreamDefaultController",configurable:!0});function Io(o){return!r(o)||!Object.prototype.hasOwnProperty.call(o,"_controlledTransformStream")?!1:o instanceof Pr}function U_(o,a,f,C,D){a._controlledTransformStream=o,o._transformStreamController=a,a._transformAlgorithm=f,a._flushAlgorithm=C,a._cancelAlgorithm=D,a._finishPromise=void 0,a._finishPromise_resolve=void 0,a._finishPromise_reject=void 0}function q_(o,a){let f=Object.create(Pr.prototype),C,D,L;a.transform!==void 0?C=q=>a.transform(q,f):C=q=>{try{return Mf(f,q),h(void 0)}catch(Y){return d(Y)}},a.flush!==void 0?D=()=>a.flush(f):D=()=>h(void 0),a.cancel!==void 0?L=q=>a.cancel(q):L=()=>h(void 0),U_(o,f,C,D,L)}function No(o){o._transformAlgorithm=void 0,o._flushAlgorithm=void 0,o._cancelAlgorithm=void 0}function Mf(o,a){let f=o._controlledTransformStream,C=f._readable._readableStreamController;if(!Sn(C))throw new TypeError("Readable side is not in a state that permits enqueue");try{An(C,a)}catch(L){throw mu(f,L),f._readable._storedError}y_(C)!==f._backpressure&&Po(f,!0)}function $_(o,a){Lf(o._controlledTransformStream,a)}function Uf(o,a){let f=o._transformAlgorithm(a);return y(f,void 0,C=>{throw Lf(o._controlledTransformStream,C),C})}function z_(o){let a=o._controlledTransformStream,f=a._readable._readableStreamController;rn(f);let C=new TypeError("TransformStream terminated");mu(a,C)}function H_(o,a){let f=o._transformStreamController;if(o._backpressure){let C=o._backpressureChangePromise;return y(C,()=>{let D=o._writable;if(D._state==="erroring")throw D._storedError;return Uf(f,a)})}return Uf(f,a)}function W_(o,a){let f=o._transformStreamController;if(f._finishPromise!==void 0)return f._finishPromise;let C=o._readable;f._finishPromise=l((L,q)=>{f._finishPromise_resolve=L,f._finishPromise_reject=q});let D=f._cancelAlgorithm(a);return No(f),w(D,()=>(C._state==="errored"?vn(f,C._storedError):(Ft(C._readableStreamController,a),yu(f)),null),L=>(Ft(C._readableStreamController,L),vn(f,L),null)),f._finishPromise}function G_(o){let a=o._transformStreamController;if(a._finishPromise!==void 0)return a._finishPromise;let f=o._readable;a._finishPromise=l((D,L)=>{a._finishPromise_resolve=D,a._finishPromise_reject=L});let C=a._flushAlgorithm();return No(a),w(C,()=>(f._state==="errored"?vn(a,f._storedError):(rn(f._readableStreamController),yu(a)),null),D=>(Ft(f._readableStreamController,D),vn(a,D),null)),a._finishPromise}function J_(o){return Po(o,!1),o._backpressureChangePromise}function V_(o,a){let f=o._transformStreamController;if(f._finishPromise!==void 0)return f._finishPromise;let C=o._writable;f._finishPromise=l((L,q)=>{f._finishPromise_resolve=L,f._finishPromise_reject=q});let D=f._cancelAlgorithm(a);return No(f),w(D,()=>(C._state==="errored"?vn(f,C._storedError):(ms(C._writableStreamController,a),gu(o),yu(f)),null),L=>(ms(C._writableStreamController,L),gu(o),vn(f,L),null)),f._finishPromise}function Bo(o){return new TypeError(`TransformStreamDefaultController.prototype.${o} can only be used on a TransformStreamDefaultController`)}function yu(o){o._finishPromise_resolve!==void 0&&(o._finishPromise_resolve(),o._finishPromise_resolve=void 0,o._finishPromise_reject=void 0)}function vn(o,a){o._finishPromise_reject!==void 0&&(g(o._finishPromise),o._finishPromise_reject(a),o._finishPromise_resolve=void 0,o._finishPromise_reject=void 0)}function qf(o){return new TypeError(`TransformStream.prototype.${o} can only be used on a TransformStream`)}t.ByteLengthQueuingStrategy=xo,t.CountQueuingStrategy=Oo,t.ReadableByteStreamController=lr,t.ReadableStream=Ye,t.ReadableStreamBYOBReader=Rr,t.ReadableStreamBYOBRequest=Yr,t.ReadableStreamDefaultController=fr,t.ReadableStreamDefaultReader=z,t.TransformStream=Fo,t.TransformStreamDefaultController=Pr,t.WritableStream=xr,t.WritableStreamDefaultController=En,t.WritableStreamDefaultWriter=dr}))});var op=V(()=>{if(!globalThis.ReadableStream)try{let t=X("node:process"),{emitWarning:e}=t;try{t.emitWarning=()=>{},Object.assign(globalThis,X("node:stream/web")),t.emitWarning=e}catch(r){throw t.emitWarning=e,r}}catch{Object.assign(globalThis,sp())}try{let{Blob:t}=X("buffer");t&&!t.prototype.stream&&(t.prototype.stream=function(r){let n=0,s=this;return new ReadableStream({type:"bytes",async pull(i){let c=await s.slice(n,Math.min(s.size,n+65536)).arrayBuffer();n+=c.byteLength,i.enqueue(new Uint8Array(c)),n===s.size&&i.close()}})})}catch{}});async function*Vu(t,e=!0){for(let r of t)if("stream"in r)yield*r.stream();else if(ArrayBuffer.isView(r))if(e){let n=r.byteOffset,s=r.byteOffset+r.byteLength;for(;n!==s;){let i=Math.min(s-n,ip),u=r.buffer.slice(n,n+i);n+=u.byteLength,yield new Uint8Array(u)}}else yield r;else{let n=0,s=r;for(;n!==s.size;){let u=await s.slice(n,Math.min(s.size,n+ip)).arrayBuffer();n+=u.byteLength,yield new Uint8Array(u)}}}var dR,ip,ap,TC,Bt,vs=je(()=>{dR=Nr(op(),1);ip=65536;ap=class Ku{#e=[];#t="";#r=0;#n="transparent";constructor(e=[],r={}){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 r!="object"&&typeof r!="function")throw new TypeError("Failed to construct 'Blob': parameter 2 cannot convert to dictionary.");r===null&&(r={});let n=new TextEncoder;for(let i of e){let u;ArrayBuffer.isView(i)?u=new Uint8Array(i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength)):i instanceof ArrayBuffer?u=new Uint8Array(i.slice(0)):i instanceof Ku?u=i:u=n.encode(`${i}`),this.#r+=ArrayBuffer.isView(u)?u.byteLength:u.size,this.#e.push(u)}this.#n=`${r.endings===void 0?"transparent":r.endings}`;let s=r.type===void 0?"":String(r.type);this.#t=/^[\x20-\x7E]*$/.test(s)?s:""}get size(){return this.#r}get type(){return this.#t}async text(){let e=new TextDecoder,r="";for await(let n of Vu(this.#e,!1))r+=e.decode(n,{stream:!0});return r+=e.decode(),r}async arrayBuffer(){let e=new Uint8Array(this.size),r=0;for await(let n of Vu(this.#e,!1))e.set(n,r),r+=n.length;return e.buffer}stream(){let e=Vu(this.#e,!0);return new globalThis.ReadableStream({type:"bytes",async pull(r){let n=await e.next();n.done?r.close():r.enqueue(n.value)},async cancel(){await e.return()}})}slice(e=0,r=this.size,n=""){let{size:s}=this,i=e<0?Math.max(s+e,0):Math.min(e,s),u=r<0?Math.max(s+r,0):Math.min(r,s),c=Math.max(u-i,0),l=this.#e,h=[],d=0;for(let w of l){if(d>=c)break;let T=ArrayBuffer.isView(w)?w.byteLength:w.size;if(i&&T<=i)i-=T,u-=T;else{let S;ArrayBuffer.isView(w)?(S=w.subarray(i,Math.min(T,u)),d+=S.byteLength):(S=w.slice(i,Math.min(T,u)),d+=S.size),u-=T,h.push(S),i=0}}let p=new Ku([],{type:String(n).toLowerCase()});return p.#r=c,p.#e=h,p}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(ap.prototype,{size:{enumerable:!0},type:{enumerable:!0},slice:{enumerable:!0}});TC=ap,Bt=TC});var DC,RC,Lr,Yu=je(()=>{vs();DC=class extends Bt{#e=0;#t="";constructor(e,r,n={}){if(arguments.length<2)throw new TypeError(`Failed to construct 'File': 2 arguments required, but only ${arguments.length} present.`);super(e,n),n===null&&(n={});let s=n.lastModified===void 0?Date.now():Number(n.lastModified);Number.isNaN(s)||(this.#e=s),this.#t=String(r)}get name(){return this.#t}get lastModified(){return this.#e}get[Symbol.toStringTag](){return"File"}static[Symbol.hasInstance](e){return!!e&&e instanceof Bt&&/^(File)$/.test(e[Symbol.toStringTag])}},RC=DC,Lr=RC});function lp(t,e=Bt){var r=`${up()}${up()}`.replace(/\./g,"").slice(-28).padStart(32,"-"),n=[],s=`--${r}\r
|
|
27
|
+
Content-Disposition: form-data; name="`;return t.forEach((i,u)=>typeof i=="string"?n.push(s+Qu(u)+`"\r
|
|
28
28
|
\r
|
|
29
29
|
${i.replace(/\r(?!\n)|(?<!\r)\n/g,`\r
|
|
30
30
|
`)}\r
|
|
31
|
-
`):n.push(s+
|
|
31
|
+
`):n.push(s+Qu(u)+`"; filename="${Qu(i.name,1)}"\r
|
|
32
32
|
Content-Type: ${i.type||"application/octet-stream"}\r
|
|
33
33
|
\r
|
|
34
34
|
`,i,`\r
|
|
35
|
-
`)),n.push(`--${r}--`),new e(n,{type:"multipart/form-data; boundary="+r})}var
|
|
36
|
-
`)).replace(/\n/g,"%0A").replace(/\r/g,"%0D").replace(/"/g,"%22"),
|
|
37
|
-
--`+e;let r=new Uint8Array(e.length);for(let n=0;n<e.length;n++)r[n]=e.charCodeAt(n),this.boundaryChars[r[n]]=!0;this.boundary=r,this.lookbehind=new Uint8Array(this.boundary.length+8),this.state=xe.START_BOUNDARY}write(e){let r=0,n=e.length,s=this.index,{lookbehind:i,boundary:u,boundaryChars:c,index:l,state:h,flags:d}=this,p=this.boundary.length,A=p-1,v=e.length,S,y,g=E=>{this[E+"Mark"]=r},m=E=>{delete this[E+"Mark"]},k=(E,R,F,$)=>{(R===void 0||R!==F)&&this[E]($&&$.subarray(R,F))},b=(E,R)=>{let F=E+"Mark";F in this&&(R?(k(E,this[F],r,e),delete this[F]):(k(E,this[F],e.length,e),this[F]=0))};for(r=0;r<n;r++)switch(S=e[r],h){case xe.START_BOUNDARY:if(l===u.length-2){if(S===ks)d|=Lr.LAST_BOUNDARY;else if(S!==ui)return;l++;break}else if(l-1===u.length-2){if(d&Lr.LAST_BOUNDARY&&S===ks)h=xe.END,d=0;else if(!(d&Lr.LAST_BOUNDARY)&&S===ai)l=0,k("onPartBegin"),h=xe.HEADER_FIELD_START;else return;break}S!==u[l+2]&&(l=-2),S===u[l+2]&&l++;break;case xe.HEADER_FIELD_START:h=xe.HEADER_FIELD,g("onHeaderField"),l=0;case xe.HEADER_FIELD:if(S===ui){m("onHeaderField"),h=xe.HEADERS_ALMOST_DONE;break}if(l++,S===ks)break;if(S===gC){if(l===1)return;b("onHeaderField",!0),h=xe.HEADER_VALUE_START;break}if(y=bC(S),y<yC||y>_C)return;break;case xe.HEADER_VALUE_START:if(S===mC)break;g("onHeaderValue"),h=xe.HEADER_VALUE;case xe.HEADER_VALUE:S===ui&&(b("onHeaderValue",!0),k("onHeaderEnd"),h=xe.HEADER_VALUE_ALMOST_DONE);break;case xe.HEADER_VALUE_ALMOST_DONE:if(S!==ai)return;h=xe.HEADER_FIELD_START;break;case xe.HEADERS_ALMOST_DONE:if(S!==ai)return;k("onHeadersEnd"),h=xe.PART_DATA_START;break;case xe.PART_DATA_START:h=xe.PART_DATA,g("onPartData");case xe.PART_DATA:if(s=l,l===0){for(r+=A;r<v&&!(e[r]in c);)r+=p;r-=A,S=e[r]}if(l<u.length)u[l]===S?(l===0&&b("onPartData",!0),l++):l=0;else if(l===u.length)l++,S===ui?d|=Lr.PART_BOUNDARY:S===ks?d|=Lr.LAST_BOUNDARY:l=0;else if(l-1===u.length)if(d&Lr.PART_BOUNDARY){if(l=0,S===ai){d&=~Lr.PART_BOUNDARY,k("onPartEnd"),k("onPartBegin"),h=xe.HEADER_FIELD_START;break}}else d&Lr.LAST_BOUNDARY&&S===ks?(k("onPartEnd"),h=xe.END,d=0):l=0;if(l>0)i[l-1]=S;else if(s>0){let E=new Uint8Array(i.buffer,i.byteOffset,i.byteLength);k("onPartData",0,s,E),s=0,g("onPartData"),r--}break;case xe.END:break;default:throw new Error(`Unexpected state entered: ${h}`)}b("onHeaderField"),b("onHeaderValue"),b("onPartData"),this.index=l,this.state=h,this.flags=d}end(){if(this.state===xe.HEADER_FIELD_START&&this.index===0||this.state===xe.PART_DATA&&this.index===this.boundary.length)this.onPartEnd();else if(this.state!==xe.END)throw new Error("MultipartParser.end(): stream ended unexpectedly")}}});import Mr,{PassThrough as dp}from"node:stream";import{types as hp,deprecate as Zu,promisify as EC}from"node:util";import{Buffer as St}from"node:buffer";async function Qu(t){if(t[it].disturbed)throw new TypeError(`body used already for: ${t.url}`);if(t[it].disturbed=!0,t[it].error)throw t[it].error;let{body:e}=t;if(e===null)return St.alloc(0);if(!(e instanceof Mr))return St.alloc(0);let r=[],n=0;try{for await(let s of e){if(t.size>0&&n+s.length>t.size){let i=new et(`content size at ${t.url} over limit: ${t.size}`,"max-size");throw e.destroy(i),i}n+=s.length,r.push(s)}}catch(s){throw s instanceof gr?s:new et(`Invalid response body while trying to fetch ${t.url}: ${s.message}`,"system",s)}if(e.readableEnded===!0||e._readableState.ended===!0)try{return r.every(s=>typeof s=="string")?St.from(r.join("")):St.concat(r,n)}catch(s){throw new et(`Could not create Buffer from response body for ${t.url}: ${s.message}`,"system",s)}else throw new et(`Premature close of server response while trying to fetch ${t.url}`)}var AC,it,Kt,Nn,SC,ci,pp,mp,li=je(()=>{Es();ri();Ju();ni();oi();AC=EC(Mr.pipeline),it=Symbol("Body internals"),Kt=class{constructor(e,{size:r=0}={}){let n=null;e===null?e=null:Vu(e)?e=St.from(e.toString()):Ss(e)||St.isBuffer(e)||(hp.isAnyArrayBuffer(e)?e=St.from(e):ArrayBuffer.isView(e)?e=St.from(e.buffer,e.byteOffset,e.byteLength):e instanceof Mr||(e instanceof jr?(e=Kh(e),n=e.type.split("=")[1]):e=St.from(String(e))));let s=e;St.isBuffer(e)?s=Mr.Readable.from(e):Ss(e)&&(s=Mr.Readable.from(e.stream())),this[it]={body:e,stream:s,boundary:n,disturbed:!1,error:null},this.size=r,e instanceof Mr&&e.on("error",i=>{let u=i instanceof gr?i:new et(`Invalid response body while trying to fetch ${this.url}: ${i.message}`,"system",i);this[it].error=u})}get body(){return this[it].stream}get bodyUsed(){return this[it].disturbed}async arrayBuffer(){let{buffer:e,byteOffset:r,byteLength:n}=await Qu(this);return e.slice(r,r+n)}async formData(){let e=this.headers.get("content-type");if(e.startsWith("application/x-www-form-urlencoded")){let n=new jr,s=new URLSearchParams(await this.text());for(let[i,u]of s)n.append(i,u);return n}let{toFormData:r}=await Promise.resolve().then(()=>(fp(),lp));return r(this.body,e)}async blob(){let e=this.headers&&this.headers.get("content-type")||this[it].body&&this[it].body.type||"",r=await this.arrayBuffer();return new Bt([r],{type:e})}async json(){let e=await this.text();return JSON.parse(e)}async text(){let e=await Qu(this);return new TextDecoder().decode(e)}buffer(){return Qu(this)}};Kt.prototype.buffer=Zu(Kt.prototype.buffer,"Please use 'response.arrayBuffer()' instead of 'response.buffer()'","node-fetch#buffer");Object.defineProperties(Kt.prototype,{body:{enumerable:!0},bodyUsed:{enumerable:!0},arrayBuffer:{enumerable:!0},blob:{enumerable:!0},json:{enumerable:!0},text:{enumerable:!0},data:{get:Zu(()=>{},"data doesn't exist, use json(), text(), arrayBuffer(), or body instead","https://github.com/node-fetch/node-fetch/issues/1000 (response)")}});Nn=(t,e)=>{let r,n,{body:s}=t[it];if(t.bodyUsed)throw new Error("cannot clone body after it is used");return s instanceof Mr&&typeof s.getBoundary!="function"&&(r=new dp({highWaterMark:e}),n=new dp({highWaterMark:e}),s.pipe(r),s.pipe(n),t[it].stream=r,s=n),s},SC=Zu(t=>t.getBoundary(),"form-data doesn't follow the spec and requires special treatment. Use alternative package","https://github.com/node-fetch/node-fetch/issues/1167"),ci=(t,e)=>t===null?null:typeof t=="string"?"text/plain;charset=UTF-8":Vu(t)?"application/x-www-form-urlencoded;charset=UTF-8":Ss(t)?t.type||null:St.isBuffer(t)||hp.isAnyArrayBuffer(t)||ArrayBuffer.isView(t)?null:t instanceof jr?`multipart/form-data; boundary=${e[it].boundary}`:t&&typeof t.getBoundary=="function"?`multipart/form-data;boundary=${SC(t)}`:t instanceof Mr?null:"text/plain;charset=UTF-8",pp=t=>{let{body:e}=t[it];return e===null?0:Ss(e)?e.size:St.isBuffer(e)?e.length:e&&typeof e.getLengthSync=="function"&&e.hasKnownLength&&e.hasKnownLength()?e.getLengthSync():null},mp=async(t,{body:e})=>{e===null?t.end():await AC(e,t)}});import{types as gp}from"node:util";import di from"node:http";function yp(t=[]){return new at(t.reduce((e,r,n,s)=>(n%2===0&&e.push(s.slice(n,n+2)),e),[]).filter(([e,r])=>{try{return fi(e),ec(e,String(r)),!0}catch{return!1}}))}var fi,ec,at,hi=je(()=>{fi=typeof di.validateHeaderName=="function"?di.validateHeaderName:t=>{if(!/^[\^`\-\w!#$%&'*+.|~]+$/.test(t)){let e=new TypeError(`Header name must be a valid HTTP token [${t}]`);throw Object.defineProperty(e,"code",{value:"ERR_INVALID_HTTP_TOKEN"}),e}},ec=typeof di.validateHeaderValue=="function"?di.validateHeaderValue:(t,e)=>{if(/[^\t\u0020-\u007E\u0080-\u00FF]/.test(e)){let r=new TypeError(`Invalid character in header content ["${t}"]`);throw Object.defineProperty(r,"code",{value:"ERR_INVALID_CHAR"}),r}},at=class t extends URLSearchParams{constructor(e){let r=[];if(e instanceof t){let n=e.raw();for(let[s,i]of Object.entries(n))r.push(...i.map(u=>[s,u]))}else if(e!=null)if(typeof e=="object"&&!gp.isBoxedPrimitive(e)){let n=e[Symbol.iterator];if(n==null)r.push(...Object.entries(e));else{if(typeof n!="function")throw new TypeError("Header pairs must be iterable");r=[...e].map(s=>{if(typeof s!="object"||gp.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 r=r.length>0?r.map(([n,s])=>(fi(n),ec(n,String(s)),[String(n).toLowerCase(),String(s)])):void 0,super(r),new Proxy(this,{get(n,s,i){switch(s){case"append":case"set":return(u,c)=>(fi(u),ec(u,String(c)),URLSearchParams.prototype[s].call(n,String(u).toLowerCase(),String(c)));case"delete":case"has":case"getAll":return u=>(fi(u),URLSearchParams.prototype[s].call(n,String(u).toLowerCase()));case"keys":return()=>(n.sort(),new Set(URLSearchParams.prototype.keys.call(n)).keys());default:return Reflect.get(n,s,i)}}})}get[Symbol.toStringTag](){return this.constructor.name}toString(){return Object.prototype.toString.call(this)}get(e){let r=this.getAll(e);if(r.length===0)return null;let n=r.join(", ");return/^content-encoding$/i.test(e)&&(n=n.toLowerCase()),n}forEach(e,r=void 0){for(let n of this.keys())Reflect.apply(e,r,[this.get(n),n,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,r)=>(e[r]=this.getAll(r),e),{})}[Symbol.for("nodejs.util.inspect.custom")](){return[...this.keys()].reduce((e,r)=>{let n=this.getAll(r);return r==="host"?e[r]=n[0]:e[r]=n.length>1?n:n[0],e},{})}};Object.defineProperties(at.prototype,["get","entries","forEach","values"].reduce((t,e)=>(t[e]={enumerable:!0},t),{}))});var kC,Ts,tc=je(()=>{kC=new Set([301,302,303,307,308]),Ts=t=>kC.has(t)});var jt,ft,_p=je(()=>{hi();li();tc();jt=Symbol("Response internals"),ft=class t extends Kt{constructor(e=null,r={}){super(e,r);let n=r.status!=null?r.status:200,s=new at(r.headers);if(e!==null&&!s.has("Content-Type")){let i=ci(e,this);i&&s.append("Content-Type",i)}this[jt]={type:"default",url:r.url,status:n,statusText:r.statusText||"",headers:s,counter:r.counter,highWaterMark:r.highWaterMark}}get type(){return this[jt].type}get url(){return this[jt].url||""}get status(){return this[jt].status}get ok(){return this[jt].status>=200&&this[jt].status<300}get redirected(){return this[jt].counter>0}get statusText(){return this[jt].statusText}get headers(){return this[jt].headers}get highWaterMark(){return this[jt].highWaterMark}clone(){return new t(Nn(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,r=302){if(!Ts(r))throw new RangeError('Failed to execute "redirect" on "response": Invalid status code');return new t(null,{headers:{location:new URL(e).toString()},status:r})}static error(){let e=new t(null,{status:0,statusText:""});return e[jt].type="error",e}static json(e=void 0,r={}){let n=JSON.stringify(e);if(n===void 0)throw new TypeError("data is not JSON serializable");let s=new at(r&&r.headers);return s.has("content-type")||s.set("content-type","application/json"),new t(n,{...r,headers:s})}get[Symbol.toStringTag](){return"Response"}};Object.defineProperties(ft.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 bp,Cp=je(()=>{bp=t=>{if(t.search)return t.search;let e=t.href.length-1,r=t.hash||(t.href[e]==="#"?"#":"");return t.href[e-r.length]==="?"?"?":""}});import{isIP as TC}from"node:net";function wp(t,e=!1){return t==null||(t=new URL(t),/^(about|blob|data):$/.test(t.protocol))?"no-referrer":(t.username="",t.password="",t.hash="",e&&(t.pathname="",t.search=""),t)}function Sp(t){if(!Ep.has(t))throw new TypeError(`Invalid referrerPolicy: ${t}`);return t}function DC(t){if(/^(http|ws)s:$/.test(t.protocol))return!0;let e=t.host.replace(/(^\[)|(]$)/g,""),r=TC(e);return r===4&&/^127\./.test(e)||r===6&&/^(((0+:){7})|(::(0+:){0,6}))0*1$/.test(e)?!0:t.host==="localhost"||t.host.endsWith(".localhost")?!1:t.protocol==="file:"}function Bn(t){return/^about:(blank|srcdoc)$/.test(t)||t.protocol==="data:"||/^(blob|filesystem):$/.test(t.protocol)?!0:DC(t)}function kp(t,{referrerURLCallback:e,referrerOriginCallback:r}={}){if(t.referrer==="no-referrer"||t.referrerPolicy==="")return null;let n=t.referrerPolicy;if(t.referrer==="about:client")return"no-referrer";let s=t.referrer,i=wp(s),u=wp(s,!0);i.toString().length>4096&&(i=u),e&&(i=e(i)),r&&(u=r(u));let c=new URL(t.url);switch(n){case"no-referrer":return"no-referrer";case"origin":return u;case"unsafe-url":return i;case"strict-origin":return Bn(i)&&!Bn(c)?"no-referrer":u.toString();case"strict-origin-when-cross-origin":return i.origin===c.origin?i:Bn(i)&&!Bn(c)?"no-referrer":u;case"same-origin":return i.origin===c.origin?i:"no-referrer";case"origin-when-cross-origin":return i.origin===c.origin?i:u;case"no-referrer-when-downgrade":return Bn(i)&&!Bn(c)?"no-referrer":i;default:throw new TypeError(`Invalid referrerPolicy: ${n}`)}}function Tp(t){let e=(t.get("referrer-policy")||"").split(/[,\s]+/),r="";for(let n of e)n&&Ep.has(n)&&(r=n);return r}var Ep,Ap,rc=je(()=>{Ep=new Set(["","no-referrer","no-referrer-when-downgrade","same-origin","origin","strict-origin","origin-when-cross-origin","strict-origin-when-cross-origin","unsafe-url"]),Ap="strict-origin-when-cross-origin"});import{format as vC}from"node:url";import{deprecate as RC}from"node:util";var Ge,Ds,OC,Ur,Dp,vp=je(()=>{hi();li();oi();Cp();rc();Ge=Symbol("Request internals"),Ds=t=>typeof t=="object"&&typeof t[Ge]=="object",OC=RC(()=>{},".data is not a valid RequestInit property, use .body instead","https://github.com/node-fetch/node-fetch/issues/1000 (request)"),Ur=class t extends Kt{constructor(e,r={}){let n;if(Ds(e)?n=new URL(e.url):(n=new URL(e),e={}),n.username!==""||n.password!=="")throw new TypeError(`${n} is an url with embedded credentials.`);let s=r.method||e.method||"GET";if(/^(delete|get|head|options|post|put)$/i.test(s)&&(s=s.toUpperCase()),!Ds(r)&&"data"in r&&OC(),(r.body!=null||Ds(e)&&e.body!==null)&&(s==="GET"||s==="HEAD"))throw new TypeError("Request with GET/HEAD method cannot have body");let i=r.body?r.body:Ds(e)&&e.body!==null?Nn(e):null;super(i,{size:r.size||e.size||0});let u=new at(r.headers||e.headers||{});if(i!==null&&!u.has("Content-Type")){let h=ci(i,this);h&&u.set("Content-Type",h)}let c=Ds(e)?e.signal:null;if("signal"in r&&(c=r.signal),c!=null&&!Yh(c))throw new TypeError("Expected signal to be an instanceof AbortSignal or EventTarget");let l=r.referrer==null?e.referrer:r.referrer;if(l==="")l="no-referrer";else if(l){let h=new URL(l);l=/^about:(\/\/)?client$/.test(h)?"client":h}else l=void 0;this[Ge]={method:s,redirect:r.redirect||e.redirect||"follow",headers:u,parsedURL:n,signal:c,referrer:l},this.follow=r.follow===void 0?e.follow===void 0?20:e.follow:r.follow,this.compress=r.compress===void 0?e.compress===void 0?!0:e.compress:r.compress,this.counter=r.counter||e.counter||0,this.agent=r.agent||e.agent,this.highWaterMark=r.highWaterMark||e.highWaterMark||16384,this.insecureHTTPParser=r.insecureHTTPParser||e.insecureHTTPParser||!1,this.referrerPolicy=r.referrerPolicy||e.referrerPolicy||""}get method(){return this[Ge].method}get url(){return vC(this[Ge].parsedURL)}get headers(){return this[Ge].headers}get redirect(){return this[Ge].redirect}get signal(){return this[Ge].signal}get referrer(){if(this[Ge].referrer==="no-referrer")return"";if(this[Ge].referrer==="client")return"about:client";if(this[Ge].referrer)return this[Ge].referrer.toString()}get referrerPolicy(){return this[Ge].referrerPolicy}set referrerPolicy(e){this[Ge].referrerPolicy=Sp(e)}clone(){return new t(this)}get[Symbol.toStringTag](){return"Request"}};Object.defineProperties(Ur.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}});Dp=t=>{let{parsedURL:e}=t[Ge],r=new at(t[Ge].headers);r.has("Accept")||r.set("Accept","*/*");let n=null;if(t.body===null&&/^(post|put)$/i.test(t.method)&&(n="0"),t.body!==null){let c=pp(t);typeof c=="number"&&!Number.isNaN(c)&&(n=String(c))}n&&r.set("Content-Length",n),t.referrerPolicy===""&&(t.referrerPolicy=Ap),t.referrer&&t.referrer!=="no-referrer"?t[Ge].referrer=kp(t):t[Ge].referrer="no-referrer",t[Ge].referrer instanceof URL&&r.set("Referer",t.referrer),r.has("User-Agent")||r.set("User-Agent","node-fetch"),t.compress&&!r.has("Accept-Encoding")&&r.set("Accept-Encoding","gzip, deflate, br");let{agent:s}=t;typeof s=="function"&&(s=s(e));let i=bp(e),u={path:e.pathname+i,method:t.method,headers:r[Symbol.for("nodejs.util.inspect.custom")](),insecureHTTPParser:t.insecureHTTPParser,agent:s};return{parsedURL:e,options:u}}});var vs,Rp=je(()=>{ni();vs=class extends gr{constructor(e,r="aborted"){super(e,r)}}});var Fp={};Rd(Fp,{AbortError:()=>vs,Blob:()=>Bt,FetchError:()=>et,File:()=>Br,FormData:()=>jr,Headers:()=>at,Request:()=>Ur,Response:()=>ft,blobFrom:()=>sp,blobFromSync:()=>np,default:()=>nc,fileFrom:()=>op,fileFromSync:()=>ip,isRedirect:()=>Ts});import xC from"node:http";import FC from"node:https";import jn from"node:zlib";import Op,{PassThrough as xp,pipeline as Ln}from"node:stream";import{Buffer as pi}from"node:buffer";async function nc(t,e){return new Promise((r,n)=>{let s=new Ur(t,e),{parsedURL:i,options:u}=Dp(s);if(!PC.has(i.protocol))throw new TypeError(`node-fetch cannot load ${t}. URL scheme "${i.protocol.replace(/:$/,"")}" is not supported.`);if(i.protocol==="data:"){let S=Uh(s.url),y=new ft(S,{headers:{"Content-Type":S.typeFull}});r(y);return}let c=(i.protocol==="https:"?FC:xC).request,{signal:l}=s,h=null,d=()=>{let S=new vs("The operation was aborted.");n(S),s.body&&s.body instanceof Op.Readable&&s.body.destroy(S),!(!h||!h.body)&&h.body.emit("error",S)};if(l&&l.aborted){d();return}let p=()=>{d(),v()},A=c(i.toString(),u);l&&l.addEventListener("abort",p);let v=()=>{A.abort(),l&&l.removeEventListener("abort",p)};A.on("error",S=>{n(new et(`request to ${s.url} failed, reason: ${S.message}`,"system",S)),v()}),IC(A,S=>{h&&h.body&&h.body.destroy(S)}),process.version<"v14"&&A.on("socket",S=>{let y;S.prependListener("end",()=>{y=S._eventsCount}),S.prependListener("close",g=>{if(h&&y<S._eventsCount&&!g){let m=new Error("Premature close");m.code="ERR_STREAM_PREMATURE_CLOSE",h.body.emit("error",m)}})}),A.on("response",S=>{A.setTimeout(0);let y=yp(S.rawHeaders);if(Ts(S.statusCode)){let E=y.get("Location"),R=null;try{R=E===null?null:new URL(E,s.url)}catch{if(s.redirect!=="manual"){n(new et(`uri requested responds with an invalid redirect URL: ${E}`,"invalid-redirect")),v();return}}switch(s.redirect){case"error":n(new et(`uri requested responds with a redirect, redirect mode is set to error: ${s.url}`,"no-redirect")),v();return;case"manual":break;case"follow":{if(R===null)break;if(s.counter>=s.follow){n(new et(`maximum redirect reached at: ${s.url}`,"max-redirect")),v();return}let F={headers:new at(s.headers),follow:s.follow,counter:s.counter+1,agent:s.agent,compress:s.compress,method:s.method,body:Nn(s),signal:s.signal,size:s.size,referrer:s.referrer,referrerPolicy:s.referrerPolicy};if(!Xh(s.url,R)||!Qh(s.url,R))for(let J of["authorization","www-authenticate","cookie","cookie2"])F.headers.delete(J);if(S.statusCode!==303&&s.body&&e.body instanceof Op.Readable){n(new et("Cannot follow redirect with body being a readable stream","unsupported-redirect")),v();return}(S.statusCode===303||(S.statusCode===301||S.statusCode===302)&&s.method==="POST")&&(F.method="GET",F.body=void 0,F.headers.delete("content-length"));let $=Tp(y);$&&(F.referrerPolicy=$),r(nc(new Ur(R,F))),v();return}default:return n(new TypeError(`Redirect option '${s.redirect}' is not a valid value of RequestRedirect`))}}l&&S.once("end",()=>{l.removeEventListener("abort",p)});let g=Ln(S,new xp,E=>{E&&n(E)});process.version<"v12.10"&&S.on("aborted",p);let m={url:s.url,status:S.statusCode,statusText:S.statusMessage,headers:y,size:s.size,counter:s.counter,highWaterMark:s.highWaterMark},k=y.get("Content-Encoding");if(!s.compress||s.method==="HEAD"||k===null||S.statusCode===204||S.statusCode===304){h=new ft(g,m),r(h);return}let b={flush:jn.Z_SYNC_FLUSH,finishFlush:jn.Z_SYNC_FLUSH};if(k==="gzip"||k==="x-gzip"){g=Ln(g,jn.createGunzip(b),E=>{E&&n(E)}),h=new ft(g,m),r(h);return}if(k==="deflate"||k==="x-deflate"){let E=Ln(S,new xp,R=>{R&&n(R)});E.once("data",R=>{(R[0]&15)===8?g=Ln(g,jn.createInflate(),F=>{F&&n(F)}):g=Ln(g,jn.createInflateRaw(),F=>{F&&n(F)}),h=new ft(g,m),r(h)}),E.once("end",()=>{h||(h=new ft(g,m),r(h))});return}if(k==="br"){g=Ln(g,jn.createBrotliDecompress(),E=>{E&&n(E)}),h=new ft(g,m),r(h);return}h=new ft(g,m),r(h)}),mp(A,s).catch(n)})}function IC(t,e){let r=pi.from(`0\r
|
|
35
|
+
`)),n.push(`--${r}--`),new e(n,{type:"multipart/form-data; boundary="+r})}var ks,xC,OC,up,FC,cp,Qu,un,Mr,ii=je(()=>{vs();Yu();({toStringTag:ks,iterator:xC,hasInstance:OC}=Symbol),up=Math.random,FC="append,set,get,getAll,delete,keys,values,entries,forEach,constructor".split(","),cp=(t,e,r)=>(t+="",/^(Blob|File)$/.test(e&&e[ks])?[(r=r!==void 0?r+"":e[ks]=="File"?e.name:"blob",t),e.name!==r||e[ks]=="blob"?new Lr([e],r,e):e]:[t,e+""]),Qu=(t,e)=>(e?t:t.replace(/\r?\n|\r/g,`\r
|
|
36
|
+
`)).replace(/\n/g,"%0A").replace(/\r/g,"%0D").replace(/"/g,"%22"),un=(t,e,r)=>{if(e.length<r)throw new TypeError(`Failed to execute '${t}' on 'FormData': ${r} arguments required, but only ${e.length} present.`)},Mr=class{#e=[];constructor(...e){if(e.length)throw new TypeError("Failed to construct 'FormData': parameter 1 is not of type 'HTMLFormElement'.")}get[ks](){return"FormData"}[xC](){return this.entries()}static[OC](e){return e&&typeof e=="object"&&e[ks]==="FormData"&&!FC.some(r=>typeof e[r]!="function")}append(...e){un("append",arguments,2),this.#e.push(cp(...e))}delete(e){un("delete",arguments,1),e+="",this.#e=this.#e.filter(([r])=>r!==e)}get(e){un("get",arguments,1),e+="";for(var r=this.#e,n=r.length,s=0;s<n;s++)if(r[s][0]===e)return r[s][1];return null}getAll(e,r){return un("getAll",arguments,1),r=[],e+="",this.#e.forEach(n=>n[0]===e&&r.push(n[1])),r}has(e){return un("has",arguments,1),e+="",this.#e.some(r=>r[0]===e)}forEach(e,r){un("forEach",arguments,1);for(var[n,s]of this)e.call(r,s,n,this)}set(...e){un("set",arguments,2);var r=[],n=!0;e=cp(...e),this.#e.forEach(s=>{s[0]===e[0]?n&&(n=!r.push(e)):r.push(s)}),n&&r.push(e),this.#e=r}*entries(){yield*this.#e}*keys(){for(var[e]of this)yield e}*values(){for(var[,e]of this)yield e}}});var _r,ai=je(()=>{_r=class extends Error{constructor(e,r){super(e),Error.captureStackTrace(this,this.constructor),this.type=r}get name(){return this.constructor.name}get[Symbol.toStringTag](){return this.constructor.name}}});var et,Xu=je(()=>{ai();et=class extends _r{constructor(e,r,n){super(e,r),n&&(this.code=this.errno=n.code,this.erroredSysCall=n.syscall)}}});var ui,Zu,Ts,dp,fp,hp,ci=je(()=>{ui=Symbol.toStringTag,Zu=t=>typeof t=="object"&&typeof t.append=="function"&&typeof t.delete=="function"&&typeof t.get=="function"&&typeof t.getAll=="function"&&typeof t.has=="function"&&typeof t.set=="function"&&typeof t.sort=="function"&&t[ui]==="URLSearchParams",Ts=t=>t&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&typeof t.constructor=="function"&&/^(Blob|File)$/.test(t[ui]),dp=t=>typeof t=="object"&&(t[ui]==="AbortSignal"||t[ui]==="EventTarget"),fp=(t,e)=>{let r=new URL(e).hostname,n=new URL(t).hostname;return r===n||r.endsWith(`.${n}`)},hp=(t,e)=>{let r=new URL(e).protocol,n=new URL(t).protocol;return r===n}});var mp=V((SR,pp)=>{if(!globalThis.DOMException)try{let{MessageChannel:t}=X("worker_threads"),e=new t().port1,r=new ArrayBuffer;e.postMessage(r,[r,r])}catch(t){t.constructor.name==="DOMException"&&(globalThis.DOMException=t.constructor)}pp.exports=globalThis.DOMException});import{statSync as gp,createReadStream as PC,promises as IC}from"node:fs";import{basename as NC}from"node:path";var yp,ec,_p,bp,Cp,wp,Ep,Ap,li,tc=je(()=>{yp=Nr(mp(),1);Yu();vs();({stat:ec}=IC),_p=(t,e)=>Ep(gp(t),t,e),bp=(t,e)=>ec(t).then(r=>Ep(r,t,e)),Cp=(t,e)=>ec(t).then(r=>Ap(r,t,e)),wp=(t,e)=>Ap(gp(t),t,e),Ep=(t,e,r="")=>new Bt([new li({path:e,size:t.size,lastModified:t.mtimeMs,start:0})],{type:r}),Ap=(t,e,r="")=>new Lr([new li({path:e,size:t.size,lastModified:t.mtimeMs,start:0})],NC(e),{type:r,lastModified:t.mtimeMs}),li=class t{#e;#t;constructor(e){this.#e=e.path,this.#t=e.start,this.size=e.size,this.lastModified=e.lastModified}slice(e,r){return new t({path:this.#e,lastModified:this.lastModified,size:r-e,start:this.#t+e})}async*stream(){let{mtimeMs:e}=await ec(this.#e);if(e>this.lastModified)throw new yp.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*PC(this.#e,{start:this.#t,end:this.#t+this.size-1})}get[Symbol.toStringTag](){return"Blob"}}});var vp={};zf(vp,{toFormData:()=>$C});function qC(t){let e=t.match(/\bfilename=("(.*?)"|([^()<>@,;:\\"/[\]?={}\s\t]+))($|;\s)/i);if(!e)return;let r=e[2]||e[3]||"",n=r.slice(r.lastIndexOf("\\")+1);return n=n.replace(/%22/g,'"'),n=n.replace(/&#(\d{4});/g,(s,i)=>String.fromCharCode(i)),n}async function $C(t,e){if(!/multipart/i.test(e))throw new TypeError("Failed to fetch");let r=e.match(/boundary=(?:"([^"]+)"|([^;]+))/i);if(!r)throw new TypeError("no or bad content-type header, no multipart boundary");let n=new rc(r[1]||r[2]),s,i,u,c,l,h,d=[],p=new Mr,w=m=>{u+=g.decode(m,{stream:!0})},T=m=>{d.push(m)},S=()=>{let m=new Lr(d,h,{type:l});p.append(c,m)},y=()=>{p.append(c,u)},g=new TextDecoder("utf-8");g.decode(),n.onPartBegin=function(){n.onPartData=w,n.onPartEnd=y,s="",i="",u="",c="",l="",h=null,d.length=0},n.onHeaderField=function(m){s+=g.decode(m,{stream:!0})},n.onHeaderValue=function(m){i+=g.decode(m,{stream:!0})},n.onHeaderEnd=function(){if(i+=g.decode(),s=s.toLowerCase(),s==="content-disposition"){let m=i.match(/\bname=("([^"]*)"|([^()<>@,;:\\"/[\]?={}\s\t]+))/i);m&&(c=m[2]||m[3]||""),h=qC(i),h&&(n.onPartData=T,n.onPartEnd=S)}else s==="content-type"&&(l=i);i="",s=""};for await(let m of t)n.write(m);return n.end(),p}var Kt,Oe,Sp,Ur,di,fi,BC,Ds,jC,LC,MC,UC,cn,rc,kp=je(()=>{tc();ii();Kt=0,Oe={START_BOUNDARY:Kt++,HEADER_FIELD_START:Kt++,HEADER_FIELD:Kt++,HEADER_VALUE_START:Kt++,HEADER_VALUE:Kt++,HEADER_VALUE_ALMOST_DONE:Kt++,HEADERS_ALMOST_DONE:Kt++,PART_DATA_START:Kt++,PART_DATA:Kt++,END:Kt++},Sp=1,Ur={PART_BOUNDARY:Sp,LAST_BOUNDARY:Sp*=2},di=10,fi=13,BC=32,Ds=45,jC=58,LC=97,MC=122,UC=t=>t|32,cn=()=>{},rc=class{constructor(e){this.index=0,this.flags=0,this.onHeaderEnd=cn,this.onHeaderField=cn,this.onHeadersEnd=cn,this.onHeaderValue=cn,this.onPartBegin=cn,this.onPartData=cn,this.onPartEnd=cn,this.boundaryChars={},e=`\r
|
|
37
|
+
--`+e;let r=new Uint8Array(e.length);for(let n=0;n<e.length;n++)r[n]=e.charCodeAt(n),this.boundaryChars[r[n]]=!0;this.boundary=r,this.lookbehind=new Uint8Array(this.boundary.length+8),this.state=Oe.START_BOUNDARY}write(e){let r=0,n=e.length,s=this.index,{lookbehind:i,boundary:u,boundaryChars:c,index:l,state:h,flags:d}=this,p=this.boundary.length,w=p-1,T=e.length,S,y,g=A=>{this[A+"Mark"]=r},m=A=>{delete this[A+"Mark"]},v=(A,R,F,$)=>{(R===void 0||R!==F)&&this[A]($&&$.subarray(R,F))},b=(A,R)=>{let F=A+"Mark";F in this&&(R?(v(A,this[F],r,e),delete this[F]):(v(A,this[F],e.length,e),this[F]=0))};for(r=0;r<n;r++)switch(S=e[r],h){case Oe.START_BOUNDARY:if(l===u.length-2){if(S===Ds)d|=Ur.LAST_BOUNDARY;else if(S!==fi)return;l++;break}else if(l-1===u.length-2){if(d&Ur.LAST_BOUNDARY&&S===Ds)h=Oe.END,d=0;else if(!(d&Ur.LAST_BOUNDARY)&&S===di)l=0,v("onPartBegin"),h=Oe.HEADER_FIELD_START;else return;break}S!==u[l+2]&&(l=-2),S===u[l+2]&&l++;break;case Oe.HEADER_FIELD_START:h=Oe.HEADER_FIELD,g("onHeaderField"),l=0;case Oe.HEADER_FIELD:if(S===fi){m("onHeaderField"),h=Oe.HEADERS_ALMOST_DONE;break}if(l++,S===Ds)break;if(S===jC){if(l===1)return;b("onHeaderField",!0),h=Oe.HEADER_VALUE_START;break}if(y=UC(S),y<LC||y>MC)return;break;case Oe.HEADER_VALUE_START:if(S===BC)break;g("onHeaderValue"),h=Oe.HEADER_VALUE;case Oe.HEADER_VALUE:S===fi&&(b("onHeaderValue",!0),v("onHeaderEnd"),h=Oe.HEADER_VALUE_ALMOST_DONE);break;case Oe.HEADER_VALUE_ALMOST_DONE:if(S!==di)return;h=Oe.HEADER_FIELD_START;break;case Oe.HEADERS_ALMOST_DONE:if(S!==di)return;v("onHeadersEnd"),h=Oe.PART_DATA_START;break;case Oe.PART_DATA_START:h=Oe.PART_DATA,g("onPartData");case Oe.PART_DATA:if(s=l,l===0){for(r+=w;r<T&&!(e[r]in c);)r+=p;r-=w,S=e[r]}if(l<u.length)u[l]===S?(l===0&&b("onPartData",!0),l++):l=0;else if(l===u.length)l++,S===fi?d|=Ur.PART_BOUNDARY:S===Ds?d|=Ur.LAST_BOUNDARY:l=0;else if(l-1===u.length)if(d&Ur.PART_BOUNDARY){if(l=0,S===di){d&=~Ur.PART_BOUNDARY,v("onPartEnd"),v("onPartBegin"),h=Oe.HEADER_FIELD_START;break}}else d&Ur.LAST_BOUNDARY&&S===Ds?(v("onPartEnd"),h=Oe.END,d=0):l=0;if(l>0)i[l-1]=S;else if(s>0){let A=new Uint8Array(i.buffer,i.byteOffset,i.byteLength);v("onPartData",0,s,A),s=0,g("onPartData"),r--}break;case Oe.END:break;default:throw new Error(`Unexpected state entered: ${h}`)}b("onHeaderField"),b("onHeaderValue"),b("onPartData"),this.index=l,this.state=h,this.flags=d}end(){if(this.state===Oe.HEADER_FIELD_START&&this.index===0||this.state===Oe.PART_DATA&&this.index===this.boundary.length)this.onPartEnd();else if(this.state!==Oe.END)throw new Error("MultipartParser.end(): stream ended unexpectedly")}}});import qr,{PassThrough as Tp}from"node:stream";import{types as Dp,deprecate as sc,promisify as zC}from"node:util";import{Buffer as St}from"node:buffer";async function nc(t){if(t[it].disturbed)throw new TypeError(`body used already for: ${t.url}`);if(t[it].disturbed=!0,t[it].error)throw t[it].error;let{body:e}=t;if(e===null)return St.alloc(0);if(!(e instanceof qr))return St.alloc(0);let r=[],n=0;try{for await(let s of e){if(t.size>0&&n+s.length>t.size){let i=new et(`content size at ${t.url} over limit: ${t.size}`,"max-size");throw e.destroy(i),i}n+=s.length,r.push(s)}}catch(s){throw s instanceof _r?s:new et(`Invalid response body while trying to fetch ${t.url}: ${s.message}`,"system",s)}if(e.readableEnded===!0||e._readableState.ended===!0)try{return r.every(s=>typeof s=="string")?St.from(r.join("")):St.concat(r,n)}catch(s){throw new et(`Could not create Buffer from response body for ${t.url}: ${s.message}`,"system",s)}else throw new et(`Premature close of server response while trying to fetch ${t.url}`)}var HC,it,Yt,jn,WC,hi,Rp,xp,pi=je(()=>{vs();ii();Xu();ai();ci();HC=zC(qr.pipeline),it=Symbol("Body internals"),Yt=class{constructor(e,{size:r=0}={}){let n=null;e===null?e=null:Zu(e)?e=St.from(e.toString()):Ts(e)||St.isBuffer(e)||(Dp.isAnyArrayBuffer(e)?e=St.from(e):ArrayBuffer.isView(e)?e=St.from(e.buffer,e.byteOffset,e.byteLength):e instanceof qr||(e instanceof Mr?(e=lp(e),n=e.type.split("=")[1]):e=St.from(String(e))));let s=e;St.isBuffer(e)?s=qr.Readable.from(e):Ts(e)&&(s=qr.Readable.from(e.stream())),this[it]={body:e,stream:s,boundary:n,disturbed:!1,error:null},this.size=r,e instanceof qr&&e.on("error",i=>{let u=i instanceof _r?i:new et(`Invalid response body while trying to fetch ${this.url}: ${i.message}`,"system",i);this[it].error=u})}get body(){return this[it].stream}get bodyUsed(){return this[it].disturbed}async arrayBuffer(){let{buffer:e,byteOffset:r,byteLength:n}=await nc(this);return e.slice(r,r+n)}async formData(){let e=this.headers.get("content-type");if(e.startsWith("application/x-www-form-urlencoded")){let n=new Mr,s=new URLSearchParams(await this.text());for(let[i,u]of s)n.append(i,u);return n}let{toFormData:r}=await Promise.resolve().then(()=>(kp(),vp));return r(this.body,e)}async blob(){let e=this.headers&&this.headers.get("content-type")||this[it].body&&this[it].body.type||"",r=await this.arrayBuffer();return new Bt([r],{type:e})}async json(){let e=await this.text();return JSON.parse(e)}async text(){let e=await nc(this);return new TextDecoder().decode(e)}buffer(){return nc(this)}};Yt.prototype.buffer=sc(Yt.prototype.buffer,"Please use 'response.arrayBuffer()' instead of 'response.buffer()'","node-fetch#buffer");Object.defineProperties(Yt.prototype,{body:{enumerable:!0},bodyUsed:{enumerable:!0},arrayBuffer:{enumerable:!0},blob:{enumerable:!0},json:{enumerable:!0},text:{enumerable:!0},data:{get:sc(()=>{},"data doesn't exist, use json(), text(), arrayBuffer(), or body instead","https://github.com/node-fetch/node-fetch/issues/1000 (response)")}});jn=(t,e)=>{let r,n,{body:s}=t[it];if(t.bodyUsed)throw new Error("cannot clone body after it is used");return s instanceof qr&&typeof s.getBoundary!="function"&&(r=new Tp({highWaterMark:e}),n=new Tp({highWaterMark:e}),s.pipe(r),s.pipe(n),t[it].stream=r,s=n),s},WC=sc(t=>t.getBoundary(),"form-data doesn't follow the spec and requires special treatment. Use alternative package","https://github.com/node-fetch/node-fetch/issues/1167"),hi=(t,e)=>t===null?null:typeof t=="string"?"text/plain;charset=UTF-8":Zu(t)?"application/x-www-form-urlencoded;charset=UTF-8":Ts(t)?t.type||null:St.isBuffer(t)||Dp.isAnyArrayBuffer(t)||ArrayBuffer.isView(t)?null:t instanceof Mr?`multipart/form-data; boundary=${e[it].boundary}`:t&&typeof t.getBoundary=="function"?`multipart/form-data;boundary=${WC(t)}`:t instanceof qr?null:"text/plain;charset=UTF-8",Rp=t=>{let{body:e}=t[it];return e===null?0:Ts(e)?e.size:St.isBuffer(e)?e.length:e&&typeof e.getLengthSync=="function"&&e.hasKnownLength&&e.hasKnownLength()?e.getLengthSync():null},xp=async(t,{body:e})=>{e===null?t.end():await HC(e,t)}});import{types as Op}from"node:util";import gi from"node:http";function Fp(t=[]){return new at(t.reduce((e,r,n,s)=>(n%2===0&&e.push(s.slice(n,n+2)),e),[]).filter(([e,r])=>{try{return mi(e),oc(e,String(r)),!0}catch{return!1}}))}var mi,oc,at,yi=je(()=>{mi=typeof gi.validateHeaderName=="function"?gi.validateHeaderName:t=>{if(!/^[\^`\-\w!#$%&'*+.|~]+$/.test(t)){let e=new TypeError(`Header name must be a valid HTTP token [${t}]`);throw Object.defineProperty(e,"code",{value:"ERR_INVALID_HTTP_TOKEN"}),e}},oc=typeof gi.validateHeaderValue=="function"?gi.validateHeaderValue:(t,e)=>{if(/[^\t\u0020-\u007E\u0080-\u00FF]/.test(e)){let r=new TypeError(`Invalid character in header content ["${t}"]`);throw Object.defineProperty(r,"code",{value:"ERR_INVALID_CHAR"}),r}},at=class t extends URLSearchParams{constructor(e){let r=[];if(e instanceof t){let n=e.raw();for(let[s,i]of Object.entries(n))r.push(...i.map(u=>[s,u]))}else if(e!=null)if(typeof e=="object"&&!Op.isBoxedPrimitive(e)){let n=e[Symbol.iterator];if(n==null)r.push(...Object.entries(e));else{if(typeof n!="function")throw new TypeError("Header pairs must be iterable");r=[...e].map(s=>{if(typeof s!="object"||Op.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 r=r.length>0?r.map(([n,s])=>(mi(n),oc(n,String(s)),[String(n).toLowerCase(),String(s)])):void 0,super(r),new Proxy(this,{get(n,s,i){switch(s){case"append":case"set":return(u,c)=>(mi(u),oc(u,String(c)),URLSearchParams.prototype[s].call(n,String(u).toLowerCase(),String(c)));case"delete":case"has":case"getAll":return u=>(mi(u),URLSearchParams.prototype[s].call(n,String(u).toLowerCase()));case"keys":return()=>(n.sort(),new Set(URLSearchParams.prototype.keys.call(n)).keys());default:return Reflect.get(n,s,i)}}})}get[Symbol.toStringTag](){return this.constructor.name}toString(){return Object.prototype.toString.call(this)}get(e){let r=this.getAll(e);if(r.length===0)return null;let n=r.join(", ");return/^content-encoding$/i.test(e)&&(n=n.toLowerCase()),n}forEach(e,r=void 0){for(let n of this.keys())Reflect.apply(e,r,[this.get(n),n,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,r)=>(e[r]=this.getAll(r),e),{})}[Symbol.for("nodejs.util.inspect.custom")](){return[...this.keys()].reduce((e,r)=>{let n=this.getAll(r);return r==="host"?e[r]=n[0]:e[r]=n.length>1?n:n[0],e},{})}};Object.defineProperties(at.prototype,["get","entries","forEach","values"].reduce((t,e)=>(t[e]={enumerable:!0},t),{}))});var GC,Rs,ic=je(()=>{GC=new Set([301,302,303,307,308]),Rs=t=>GC.has(t)});var jt,dt,Pp=je(()=>{yi();pi();ic();jt=Symbol("Response internals"),dt=class t extends Yt{constructor(e=null,r={}){super(e,r);let n=r.status!=null?r.status:200,s=new at(r.headers);if(e!==null&&!s.has("Content-Type")){let i=hi(e,this);i&&s.append("Content-Type",i)}this[jt]={type:"default",url:r.url,status:n,statusText:r.statusText||"",headers:s,counter:r.counter,highWaterMark:r.highWaterMark}}get type(){return this[jt].type}get url(){return this[jt].url||""}get status(){return this[jt].status}get ok(){return this[jt].status>=200&&this[jt].status<300}get redirected(){return this[jt].counter>0}get statusText(){return this[jt].statusText}get headers(){return this[jt].headers}get highWaterMark(){return this[jt].highWaterMark}clone(){return new t(jn(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,r=302){if(!Rs(r))throw new RangeError('Failed to execute "redirect" on "response": Invalid status code');return new t(null,{headers:{location:new URL(e).toString()},status:r})}static error(){let e=new t(null,{status:0,statusText:""});return e[jt].type="error",e}static json(e=void 0,r={}){let n=JSON.stringify(e);if(n===void 0)throw new TypeError("data is not JSON serializable");let s=new at(r&&r.headers);return s.has("content-type")||s.set("content-type","application/json"),new t(n,{...r,headers:s})}get[Symbol.toStringTag](){return"Response"}};Object.defineProperties(dt.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 Ip,Np=je(()=>{Ip=t=>{if(t.search)return t.search;let e=t.href.length-1,r=t.hash||(t.href[e]==="#"?"#":"");return t.href[e-r.length]==="?"?"?":""}});import{isIP as JC}from"node:net";function Bp(t,e=!1){return t==null||(t=new URL(t),/^(about|blob|data):$/.test(t.protocol))?"no-referrer":(t.username="",t.password="",t.hash="",e&&(t.pathname="",t.search=""),t)}function Mp(t){if(!jp.has(t))throw new TypeError(`Invalid referrerPolicy: ${t}`);return t}function VC(t){if(/^(http|ws)s:$/.test(t.protocol))return!0;let e=t.host.replace(/(^\[)|(]$)/g,""),r=JC(e);return r===4&&/^127\./.test(e)||r===6&&/^(((0+:){7})|(::(0+:){0,6}))0*1$/.test(e)?!0:t.host==="localhost"||t.host.endsWith(".localhost")?!1:t.protocol==="file:"}function Ln(t){return/^about:(blank|srcdoc)$/.test(t)||t.protocol==="data:"||/^(blob|filesystem):$/.test(t.protocol)?!0:VC(t)}function Up(t,{referrerURLCallback:e,referrerOriginCallback:r}={}){if(t.referrer==="no-referrer"||t.referrerPolicy==="")return null;let n=t.referrerPolicy;if(t.referrer==="about:client")return"no-referrer";let s=t.referrer,i=Bp(s),u=Bp(s,!0);i.toString().length>4096&&(i=u),e&&(i=e(i)),r&&(u=r(u));let c=new URL(t.url);switch(n){case"no-referrer":return"no-referrer";case"origin":return u;case"unsafe-url":return i;case"strict-origin":return Ln(i)&&!Ln(c)?"no-referrer":u.toString();case"strict-origin-when-cross-origin":return i.origin===c.origin?i:Ln(i)&&!Ln(c)?"no-referrer":u;case"same-origin":return i.origin===c.origin?i:"no-referrer";case"origin-when-cross-origin":return i.origin===c.origin?i:u;case"no-referrer-when-downgrade":return Ln(i)&&!Ln(c)?"no-referrer":i;default:throw new TypeError(`Invalid referrerPolicy: ${n}`)}}function qp(t){let e=(t.get("referrer-policy")||"").split(/[,\s]+/),r="";for(let n of e)n&&jp.has(n)&&(r=n);return r}var jp,Lp,ac=je(()=>{jp=new Set(["","no-referrer","no-referrer-when-downgrade","same-origin","origin","strict-origin","origin-when-cross-origin","strict-origin-when-cross-origin","unsafe-url"]),Lp="strict-origin-when-cross-origin"});import{format as KC}from"node:url";import{deprecate as YC}from"node:util";var Ge,xs,QC,$r,$p,zp=je(()=>{yi();pi();ci();Np();ac();Ge=Symbol("Request internals"),xs=t=>typeof t=="object"&&typeof t[Ge]=="object",QC=YC(()=>{},".data is not a valid RequestInit property, use .body instead","https://github.com/node-fetch/node-fetch/issues/1000 (request)"),$r=class t extends Yt{constructor(e,r={}){let n;if(xs(e)?n=new URL(e.url):(n=new URL(e),e={}),n.username!==""||n.password!=="")throw new TypeError(`${n} is an url with embedded credentials.`);let s=r.method||e.method||"GET";if(/^(delete|get|head|options|post|put)$/i.test(s)&&(s=s.toUpperCase()),!xs(r)&&"data"in r&&QC(),(r.body!=null||xs(e)&&e.body!==null)&&(s==="GET"||s==="HEAD"))throw new TypeError("Request with GET/HEAD method cannot have body");let i=r.body?r.body:xs(e)&&e.body!==null?jn(e):null;super(i,{size:r.size||e.size||0});let u=new at(r.headers||e.headers||{});if(i!==null&&!u.has("Content-Type")){let h=hi(i,this);h&&u.set("Content-Type",h)}let c=xs(e)?e.signal:null;if("signal"in r&&(c=r.signal),c!=null&&!dp(c))throw new TypeError("Expected signal to be an instanceof AbortSignal or EventTarget");let l=r.referrer==null?e.referrer:r.referrer;if(l==="")l="no-referrer";else if(l){let h=new URL(l);l=/^about:(\/\/)?client$/.test(h)?"client":h}else l=void 0;this[Ge]={method:s,redirect:r.redirect||e.redirect||"follow",headers:u,parsedURL:n,signal:c,referrer:l},this.follow=r.follow===void 0?e.follow===void 0?20:e.follow:r.follow,this.compress=r.compress===void 0?e.compress===void 0?!0:e.compress:r.compress,this.counter=r.counter||e.counter||0,this.agent=r.agent||e.agent,this.highWaterMark=r.highWaterMark||e.highWaterMark||16384,this.insecureHTTPParser=r.insecureHTTPParser||e.insecureHTTPParser||!1,this.referrerPolicy=r.referrerPolicy||e.referrerPolicy||""}get method(){return this[Ge].method}get url(){return KC(this[Ge].parsedURL)}get headers(){return this[Ge].headers}get redirect(){return this[Ge].redirect}get signal(){return this[Ge].signal}get referrer(){if(this[Ge].referrer==="no-referrer")return"";if(this[Ge].referrer==="client")return"about:client";if(this[Ge].referrer)return this[Ge].referrer.toString()}get referrerPolicy(){return this[Ge].referrerPolicy}set referrerPolicy(e){this[Ge].referrerPolicy=Mp(e)}clone(){return new t(this)}get[Symbol.toStringTag](){return"Request"}};Object.defineProperties($r.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}});$p=t=>{let{parsedURL:e}=t[Ge],r=new at(t[Ge].headers);r.has("Accept")||r.set("Accept","*/*");let n=null;if(t.body===null&&/^(post|put)$/i.test(t.method)&&(n="0"),t.body!==null){let c=Rp(t);typeof c=="number"&&!Number.isNaN(c)&&(n=String(c))}n&&r.set("Content-Length",n),t.referrerPolicy===""&&(t.referrerPolicy=Lp),t.referrer&&t.referrer!=="no-referrer"?t[Ge].referrer=Up(t):t[Ge].referrer="no-referrer",t[Ge].referrer instanceof URL&&r.set("Referer",t.referrer),r.has("User-Agent")||r.set("User-Agent","node-fetch"),t.compress&&!r.has("Accept-Encoding")&&r.set("Accept-Encoding","gzip, deflate, br");let{agent:s}=t;typeof s=="function"&&(s=s(e));let i=Ip(e),u={path:e.pathname+i,method:t.method,headers:r[Symbol.for("nodejs.util.inspect.custom")](),insecureHTTPParser:t.insecureHTTPParser,agent:s};return{parsedURL:e,options:u}}});var Os,Hp=je(()=>{ai();Os=class extends _r{constructor(e,r="aborted"){super(e,r)}}});var Jp={};zf(Jp,{AbortError:()=>Os,Blob:()=>Bt,FetchError:()=>et,File:()=>Lr,FormData:()=>Mr,Headers:()=>at,Request:()=>$r,Response:()=>dt,blobFrom:()=>bp,blobFromSync:()=>_p,default:()=>uc,fileFrom:()=>Cp,fileFromSync:()=>wp,isRedirect:()=>Rs});import XC from"node:http";import ZC from"node:https";import Mn from"node:zlib";import Wp,{PassThrough as Gp,pipeline as Un}from"node:stream";import{Buffer as _i}from"node:buffer";async function uc(t,e){return new Promise((r,n)=>{let s=new $r(t,e),{parsedURL:i,options:u}=$p(s);if(!ew.has(i.protocol))throw new TypeError(`node-fetch cannot load ${t}. URL scheme "${i.protocol.replace(/:$/,"")}" is not supported.`);if(i.protocol==="data:"){let S=tp(s.url),y=new dt(S,{headers:{"Content-Type":S.typeFull}});r(y);return}let c=(i.protocol==="https:"?ZC:XC).request,{signal:l}=s,h=null,d=()=>{let S=new Os("The operation was aborted.");n(S),s.body&&s.body instanceof Wp.Readable&&s.body.destroy(S),!(!h||!h.body)&&h.body.emit("error",S)};if(l&&l.aborted){d();return}let p=()=>{d(),T()},w=c(i.toString(),u);l&&l.addEventListener("abort",p);let T=()=>{w.abort(),l&&l.removeEventListener("abort",p)};w.on("error",S=>{n(new et(`request to ${s.url} failed, reason: ${S.message}`,"system",S)),T()}),tw(w,S=>{h&&h.body&&h.body.destroy(S)}),process.version<"v14"&&w.on("socket",S=>{let y;S.prependListener("end",()=>{y=S._eventsCount}),S.prependListener("close",g=>{if(h&&y<S._eventsCount&&!g){let m=new Error("Premature close");m.code="ERR_STREAM_PREMATURE_CLOSE",h.body.emit("error",m)}})}),w.on("response",S=>{w.setTimeout(0);let y=Fp(S.rawHeaders);if(Rs(S.statusCode)){let A=y.get("Location"),R=null;try{R=A===null?null:new URL(A,s.url)}catch{if(s.redirect!=="manual"){n(new et(`uri requested responds with an invalid redirect URL: ${A}`,"invalid-redirect")),T();return}}switch(s.redirect){case"error":n(new et(`uri requested responds with a redirect, redirect mode is set to error: ${s.url}`,"no-redirect")),T();return;case"manual":break;case"follow":{if(R===null)break;if(s.counter>=s.follow){n(new et(`maximum redirect reached at: ${s.url}`,"max-redirect")),T();return}let F={headers:new at(s.headers),follow:s.follow,counter:s.counter+1,agent:s.agent,compress:s.compress,method:s.method,body:jn(s),signal:s.signal,size:s.size,referrer:s.referrer,referrerPolicy:s.referrerPolicy};if(!fp(s.url,R)||!hp(s.url,R))for(let J of["authorization","www-authenticate","cookie","cookie2"])F.headers.delete(J);if(S.statusCode!==303&&s.body&&e.body instanceof Wp.Readable){n(new et("Cannot follow redirect with body being a readable stream","unsupported-redirect")),T();return}(S.statusCode===303||(S.statusCode===301||S.statusCode===302)&&s.method==="POST")&&(F.method="GET",F.body=void 0,F.headers.delete("content-length"));let $=qp(y);$&&(F.referrerPolicy=$),r(uc(new $r(R,F))),T();return}default:return n(new TypeError(`Redirect option '${s.redirect}' is not a valid value of RequestRedirect`))}}l&&S.once("end",()=>{l.removeEventListener("abort",p)});let g=Un(S,new Gp,A=>{A&&n(A)});process.version<"v12.10"&&S.on("aborted",p);let m={url:s.url,status:S.statusCode,statusText:S.statusMessage,headers:y,size:s.size,counter:s.counter,highWaterMark:s.highWaterMark},v=y.get("Content-Encoding");if(!s.compress||s.method==="HEAD"||v===null||S.statusCode===204||S.statusCode===304){h=new dt(g,m),r(h);return}let b={flush:Mn.Z_SYNC_FLUSH,finishFlush:Mn.Z_SYNC_FLUSH};if(v==="gzip"||v==="x-gzip"){g=Un(g,Mn.createGunzip(b),A=>{A&&n(A)}),h=new dt(g,m),r(h);return}if(v==="deflate"||v==="x-deflate"){let A=Un(S,new Gp,R=>{R&&n(R)});A.once("data",R=>{(R[0]&15)===8?g=Un(g,Mn.createInflate(),F=>{F&&n(F)}):g=Un(g,Mn.createInflateRaw(),F=>{F&&n(F)}),h=new dt(g,m),r(h)}),A.once("end",()=>{h||(h=new dt(g,m),r(h))});return}if(v==="br"){g=Un(g,Mn.createBrotliDecompress(),A=>{A&&n(A)}),h=new dt(g,m),r(h);return}h=new dt(g,m),r(h)}),xp(w,s).catch(n)})}function tw(t,e){let r=_i.from(`0\r
|
|
38
38
|
\r
|
|
39
|
-
`),n=!1,s=!1,i;t.on("response",u=>{let{headers:c}=u;n=c["transfer-encoding"]==="chunked"&&!c["content-length"]}),t.on("socket",u=>{let c=()=>{if(n&&!s){let h=new Error("Premature close");h.code="ERR_STREAM_PREMATURE_CLOSE",e(h)}},l=h=>{s=
|
|
39
|
+
`),n=!1,s=!1,i;t.on("response",u=>{let{headers:c}=u;n=c["transfer-encoding"]==="chunked"&&!c["content-length"]}),t.on("socket",u=>{let c=()=>{if(n&&!s){let h=new Error("Premature close");h.code="ERR_STREAM_PREMATURE_CLOSE",e(h)}},l=h=>{s=_i.compare(h.slice(-5),r)===0,!s&&i&&(s=_i.compare(i.slice(-3),r.slice(0,3))===0&&_i.compare(h.slice(-2),r.slice(3))===0),i=h};u.prependListener("close",c),u.on("data",l),t.on("close",()=>{u.removeListener("close",c),u.removeListener("data",l)})})}var ew,Vp=je(()=>{rp();pi();Pp();yi();zp();Xu();Hp();ic();ii();ci();ac();tc();ew=new Set(["data:","http:","https:"])});var Qp=V($n=>{"use strict";var rw=$n&&$n.__importDefault||function(t){return t&&t.__esModule?t:{default:t}},qn;Object.defineProperty($n,"__esModule",{value:!0});$n.Gaxios=void 0;var nw=rw(Nu()),sw=X("https"),ln=Lu(),ow=Rh(),Kp=X("stream"),Yp=qu(),iw=async()=>globalThis.crypto?.randomUUID()||(await import("crypto")).randomUUID(),bi=class{agentCache=new Map;defaults;interceptors;constructor(e){this.defaults=e||{},this.interceptors={request:new Yp.GaxiosInterceptorManager,response:new Yp.GaxiosInterceptorManager}}fetch(...e){let r=e[0],n=e[1],s,i=new Headers;return typeof r=="string"?s=new URL(r):r instanceof URL?s=r:r&&r.url&&(s=new URL(r.url)),r&&typeof r=="object"&&"headers"in r&&qn.mergeHeaders(i,r.headers),n&&qn.mergeHeaders(i,new Headers(n.headers)),typeof r=="object"&&!(r instanceof URL)?this.request({...n,...r,headers:i,url:s}):this.request({...n,headers:i,url:s})}async request(e={}){let r=await this.#n(e);return r=await this.#t(r),this.#r(this._request(r))}async _defaultAdapter(e){let r=e.fetchImplementation||this.defaults.fetchImplementation||await qn.#u(),n={...e};delete n.data;let s=await r(e.url,n),i=await this.getResponseData(e,s);return Object.getOwnPropertyDescriptor(s,"data")?.configurable||Object.defineProperties(s,{data:{configurable:!0,writable:!0,enumerable:!0,value:i}}),Object.assign(s,{config:e,data:i})}async _request(e){try{let r;if(e.adapter?r=await e.adapter(e,this._defaultAdapter.bind(this)):r=await this._defaultAdapter(e),!e.validateStatus(r.status)){if(e.responseType==="stream"){let s=[];for await(let i of r.data)s.push(i);r.data=s.toString()}let n=ln.GaxiosError.extractAPIErrorFromResponse(r,`Request failed with status code ${r.status}`);throw new ln.GaxiosError(n?.message,e,r,n)}return r}catch(r){let n;r instanceof ln.GaxiosError?n=r:r instanceof Error?n=new ln.GaxiosError(r.message,e,void 0,r):n=new ln.GaxiosError("Unexpected Gaxios Error",e,void 0,r);let{shouldRetry:s,config:i}=await(0,ow.getRetryConfig)(n);if(s&&i)return n.config.retryConfig.currentRetryAttempt=i.retryConfig.currentRetryAttempt,e.retryConfig=n.config?.retryConfig,this.#s(e),this._request(e);throw e.errorRedactor&&e.errorRedactor(n),n}}async getResponseData(e,r){if(e.maxContentLength&&r.headers.has("content-length")&&e.maxContentLength<Number.parseInt(r.headers?.get("content-length")||""))throw new ln.GaxiosError("Response's `Content-Length` is over the limit.",e,Object.assign(r,{config:e}));switch(e.responseType){case"stream":return r.body;case"json":return r.json();case"arraybuffer":return r.arrayBuffer();case"blob":return r.blob();case"text":return r.text();default:return this.getResponseDataFromContentType(r)}}#e(e,r=[]){let n=new URL(e),s=[...r],i=(process.env.NO_PROXY??process.env.no_proxy)?.split(",")||[];for(let u of i)s.push(u.trim());for(let u of s)if(u instanceof RegExp){if(u.test(n.toString()))return!1}else if(u instanceof URL){if(u.origin===n.origin)return!1}else if(u.startsWith("*.")||u.startsWith(".")){let c=u.replace(/^\*\./,".");if(n.hostname.endsWith(c))return!1}else if(u===n.origin||u===n.hostname||u===n.href)return!1;return!0}async#t(e){let r=Promise.resolve(e);for(let n of this.interceptors.request.values())n&&(r=r.then(n.resolved,n.rejected));return r}async#r(e){let r=Promise.resolve(e);for(let n of this.interceptors.response.values())n&&(r=r.then(n.resolved,n.rejected));return r}async#n(e){let r=new Headers(this.defaults.headers);qn.mergeHeaders(r,e.headers);let n=(0,nw.default)(!0,{},this.defaults,e);if(!n.url)throw new Error("URL is required.");if(n.baseURL&&(n.url=new URL(n.url,n.baseURL)),n.url=new URL(n.url),n.params)if(n.paramsSerializer){let u=n.paramsSerializer(n.params);u.startsWith("?")&&(u=u.slice(1));let c=n.url.toString().includes("?")?"&":"?";n.url=n.url+c+u}else{let u=n.url instanceof URL?n.url:new URL(n.url);for(let[c,l]of new URLSearchParams(n.params))u.searchParams.append(c,l);n.url=u}typeof e.maxContentLength=="number"&&(n.size=e.maxContentLength),typeof e.maxRedirects=="number"&&(n.follow=e.maxRedirects);let s=typeof n.data=="string"||n.data instanceof ArrayBuffer||n.data instanceof Blob||globalThis.File&&n.data instanceof File||n.data instanceof FormData||n.data instanceof Kp.Readable||n.data instanceof ReadableStream||n.data instanceof String||n.data instanceof URLSearchParams||ArrayBuffer.isView(n.data)||["Blob","File","FormData"].includes(n.data?.constructor?.name||"");if(n.multipart?.length){let u=await iw();r.set("content-type",`multipart/related; boundary=${u}`),n.body=Kp.Readable.from(this.getMultipartRequest(n.multipart,u))}else s?n.body=n.data:typeof n.data=="object"?r.get("Content-Type")==="application/x-www-form-urlencoded"?n.body=n.paramsSerializer?n.paramsSerializer(n.data):new URLSearchParams(n.data):(r.has("content-type")||r.set("content-type","application/json"),n.body=JSON.stringify(n.data)):n.data&&(n.body=n.data);n.validateStatus=n.validateStatus||this.validateStatus,n.responseType=n.responseType||"unknown",!r.has("accept")&&n.responseType==="json"&&r.set("accept","application/json");let i=n.proxy||process?.env?.HTTPS_PROXY||process?.env?.https_proxy||process?.env?.HTTP_PROXY||process?.env?.http_proxy;if(!n.agent)if(i&&this.#e(n.url,n.noProxy)){let u=await qn.#a();this.agentCache.has(i)?n.agent=this.agentCache.get(i):(n.agent=new u(i,{cert:n.cert,key:n.key}),this.agentCache.set(i,n.agent))}else n.cert&&n.key&&(this.agentCache.has(n.key)?n.agent=this.agentCache.get(n.key):(n.agent=new sw.Agent({cert:n.cert,key:n.key}),this.agentCache.set(n.key,n.agent)));return typeof n.errorRedactor!="function"&&n.errorRedactor!==!1&&(n.errorRedactor=ln.defaultErrorRedactor),n.body&&!("duplex"in n)&&(n.duplex="half"),this.#s(n),Object.assign(n,{headers:r,url:n.url instanceof URL?n.url:new URL(n.url)})}#s(e){if(e.timeout){let r=AbortSignal.timeout(e.timeout);e.signal&&!e.signal.aborted?e.signal=AbortSignal.any([e.signal,r]):e.signal=r}}validateStatus(e){return e>=200&&e<300}async getResponseDataFromContentType(e){let r=e.headers.get("Content-Type");if(r===null)return e.text();if(r=r.toLowerCase(),r.includes("application/json")){let n=await e.text();try{n=JSON.parse(n)}catch{}return n}else return r.match(/^text\//)?e.text():e.blob()}async*getMultipartRequest(e,r){let n=`--${r}--`;for(let s of e){let i=s.headers.get("Content-Type")||"application/octet-stream";yield`--${r}\r
|
|
40
40
|
Content-Type: ${i}\r
|
|
41
41
|
\r
|
|
42
42
|
`,typeof s.content=="string"?yield s.content:yield*s.content,yield`\r
|
|
43
|
-
`}yield n}static#o;static#i;static async#a(){return this.#o||=(await Promise.resolve().then(()=>Pr(Mh()))).HttpsProxyAgent,this.#o}static async#u(){let e=typeof window<"u"&&!!window;return this.#i||=e?window.fetch:(await Promise.resolve().then(()=>(Pp(),Fp))).default,this.#i}static mergeHeaders(e,...r){e=e instanceof Headers?e:new Headers(e);for(let n of r)(n instanceof Headers?n:new Headers(n)).forEach((i,u)=>{u==="set-cookie"?e.append(u,i):e.set(u,i)});return e}};Un.Gaxios=mi;Mn=mi});var Ve=V(tt=>{"use strict";var UC=tt&&tt.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,s)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),qC=tt&&tt.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&UC(e,t,r)};Object.defineProperty(tt,"__esModule",{value:!0});tt.instance=tt.Gaxios=tt.GaxiosError=void 0;tt.request=zC;var jp=Bp();Object.defineProperty(tt,"Gaxios",{enumerable:!0,get:function(){return jp.Gaxios}});var $C=Pu();Object.defineProperty(tt,"GaxiosError",{enumerable:!0,get:function(){return $C.GaxiosError}});qC(Bu(),tt);tt.instance=new jp.Gaxios;async function zC(t){return tt.instance.request(t)}});var sc=V((Lp,gi)=>{(function(t){"use strict";var e,r=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,n=Math.ceil,s=Math.floor,i="[BigNumber Error] ",u=i+"Number primitive has more than 15 significant digits: ",c=1e14,l=14,h=9007199254740991,d=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],p=1e7,A=1e9;function v(R){var F,$,J,M=W.prototype={constructor:W,toString:null,valueOf:null},X=new W(1),ue=20,re=4,fe=-7,pe=21,Ae=-1e7,oe=1e7,me=!1,G=1,K=0,ae={prefix:"",groupSize:3,secondaryGroupSize:0,groupSeparator:",",decimalSeparator:".",fractionGroupSize:0,fractionGroupSeparator:"\xA0",suffix:""},qe="0123456789abcdefghijklmnopqrstuvwxyz",De=!0;function W(_,w){var T,B,x,I,U,O,P,j,N=this;if(!(N instanceof W))return new W(_,w);if(w==null){if(_&&_._isBigNumber===!0){N.s=_.s,!_.c||_.e>oe?N.c=N.e=null:_.e<Ae?N.c=[N.e=0]:(N.e=_.e,N.c=_.c.slice());return}if((O=typeof _=="number")&&_*0==0){if(N.s=1/_<0?(_=-_,-1):1,_===~~_){for(I=0,U=_;U>=10;U/=10,I++);I>oe?N.c=N.e=null:(N.e=I,N.c=[_]);return}j=String(_)}else{if(!r.test(j=String(_)))return J(N,j,O);N.s=j.charCodeAt(0)==45?(j=j.slice(1),-1):1}(I=j.indexOf("."))>-1&&(j=j.replace(".","")),(U=j.search(/e/i))>0?(I<0&&(I=U),I+=+j.slice(U+1),j=j.substring(0,U)):I<0&&(I=j.length)}else{if(m(w,2,qe.length,"Base"),w==10&&De)return N=new W(_),Re(N,ue+N.e+1,re);if(j=String(_),O=typeof _=="number"){if(_*0!=0)return J(N,j,O,w);if(N.s=1/_<0?(j=j.slice(1),-1):1,W.DEBUG&&j.replace(/^0\.0*|\./,"").length>15)throw Error(u+_)}else N.s=j.charCodeAt(0)===45?(j=j.slice(1),-1):1;for(T=qe.slice(0,w),I=U=0,P=j.length;U<P;U++)if(T.indexOf(B=j.charAt(U))<0){if(B=="."){if(U>I){I=P;continue}}else if(!x&&(j==j.toUpperCase()&&(j=j.toLowerCase())||j==j.toLowerCase()&&(j=j.toUpperCase()))){x=!0,U=-1,I=0;continue}return J(N,String(_),O,w)}O=!1,j=$(j,w,10,N.s),(I=j.indexOf("."))>-1?j=j.replace(".",""):I=j.length}for(U=0;j.charCodeAt(U)===48;U++);for(P=j.length;j.charCodeAt(--P)===48;);if(j=j.slice(U,++P)){if(P-=U,O&&W.DEBUG&&P>15&&(_>h||_!==s(_)))throw Error(u+N.s*_);if((I=I-U-1)>oe)N.c=N.e=null;else if(I<Ae)N.c=[N.e=0];else{if(N.e=I,N.c=[],U=(I+1)%l,I<0&&(U+=l),U<P){for(U&&N.c.push(+j.slice(0,U)),P-=l;U<P;)N.c.push(+j.slice(U,U+=l));U=l-(j=j.slice(U)).length}else U-=P;for(;U--;j+="0");N.c.push(+j)}}else N.c=[N.e=0]}W.clone=v,W.ROUND_UP=0,W.ROUND_DOWN=1,W.ROUND_CEIL=2,W.ROUND_FLOOR=3,W.ROUND_HALF_UP=4,W.ROUND_HALF_DOWN=5,W.ROUND_HALF_EVEN=6,W.ROUND_HALF_CEIL=7,W.ROUND_HALF_FLOOR=8,W.EUCLID=9,W.config=W.set=function(_){var w,T;if(_!=null)if(typeof _=="object"){if(_.hasOwnProperty(w="DECIMAL_PLACES")&&(T=_[w],m(T,0,A,w),ue=T),_.hasOwnProperty(w="ROUNDING_MODE")&&(T=_[w],m(T,0,8,w),re=T),_.hasOwnProperty(w="EXPONENTIAL_AT")&&(T=_[w],T&&T.pop?(m(T[0],-A,0,w),m(T[1],0,A,w),fe=T[0],pe=T[1]):(m(T,-A,A,w),fe=-(pe=T<0?-T:T))),_.hasOwnProperty(w="RANGE"))if(T=_[w],T&&T.pop)m(T[0],-A,-1,w),m(T[1],1,A,w),Ae=T[0],oe=T[1];else if(m(T,-A,A,w),T)Ae=-(oe=T<0?-T:T);else throw Error(i+w+" cannot be zero: "+T);if(_.hasOwnProperty(w="CRYPTO"))if(T=_[w],T===!!T)if(T)if(typeof crypto<"u"&&crypto&&(crypto.getRandomValues||crypto.randomBytes))me=T;else throw me=!T,Error(i+"crypto unavailable");else me=T;else throw Error(i+w+" not true or false: "+T);if(_.hasOwnProperty(w="MODULO_MODE")&&(T=_[w],m(T,0,9,w),G=T),_.hasOwnProperty(w="POW_PRECISION")&&(T=_[w],m(T,0,A,w),K=T),_.hasOwnProperty(w="FORMAT"))if(T=_[w],typeof T=="object")ae=T;else throw Error(i+w+" not an object: "+T);if(_.hasOwnProperty(w="ALPHABET"))if(T=_[w],typeof T=="string"&&!/^.?$|[+\-.\s]|(.).*\1/.test(T))De=T.slice(0,10)=="0123456789",qe=T;else throw Error(i+w+" invalid: "+T)}else throw Error(i+"Object expected: "+_);return{DECIMAL_PLACES:ue,ROUNDING_MODE:re,EXPONENTIAL_AT:[fe,pe],RANGE:[Ae,oe],CRYPTO:me,MODULO_MODE:G,POW_PRECISION:K,FORMAT:ae,ALPHABET:qe}},W.isBigNumber=function(_){if(!_||_._isBigNumber!==!0)return!1;if(!W.DEBUG)return!0;var w,T,B=_.c,x=_.e,I=_.s;e:if({}.toString.call(B)=="[object Array]"){if((I===1||I===-1)&&x>=-A&&x<=A&&x===s(x)){if(B[0]===0){if(x===0&&B.length===1)return!0;break e}if(w=(x+1)%l,w<1&&(w+=l),String(B[0]).length==w){for(w=0;w<B.length;w++)if(T=B[w],T<0||T>=c||T!==s(T))break e;if(T!==0)return!0}}}else if(B===null&&x===null&&(I===null||I===1||I===-1))return!0;throw Error(i+"Invalid BigNumber: "+_)},W.maximum=W.max=function(){return _e(arguments,-1)},W.minimum=W.min=function(){return _e(arguments,1)},W.random=(function(){var _=9007199254740992,w=Math.random()*_&2097151?function(){return s(Math.random()*_)}:function(){return(Math.random()*1073741824|0)*8388608+(Math.random()*8388608|0)};return function(T){var B,x,I,U,O,P=0,j=[],N=new W(X);if(T==null?T=ue:m(T,0,A),U=n(T/l),me)if(crypto.getRandomValues){for(B=crypto.getRandomValues(new Uint32Array(U*=2));P<U;)O=B[P]*131072+(B[P+1]>>>11),O>=9e15?(x=crypto.getRandomValues(new Uint32Array(2)),B[P]=x[0],B[P+1]=x[1]):(j.push(O%1e14),P+=2);P=U/2}else if(crypto.randomBytes){for(B=crypto.randomBytes(U*=7);P<U;)O=(B[P]&31)*281474976710656+B[P+1]*1099511627776+B[P+2]*4294967296+B[P+3]*16777216+(B[P+4]<<16)+(B[P+5]<<8)+B[P+6],O>=9e15?crypto.randomBytes(7).copy(B,P):(j.push(O%1e14),P+=7);P=U/7}else throw me=!1,Error(i+"crypto unavailable");if(!me)for(;P<U;)O=w(),O<9e15&&(j[P++]=O%1e14);for(U=j[--P],T%=l,U&&T&&(O=d[l-T],j[P]=s(U/O)*O);j[P]===0;j.pop(),P--);if(P<0)j=[I=0];else{for(I=-1;j[0]===0;j.splice(0,1),I-=l);for(P=1,O=j[0];O>=10;O/=10,P++);P<l&&(I-=l-P)}return N.e=I,N.c=j,N}})(),W.sum=function(){for(var _=1,w=arguments,T=new W(w[0]);_<w.length;)T=T.plus(w[_++]);return T},$=(function(){var _="0123456789";function w(T,B,x,I){for(var U,O=[0],P,j=0,N=T.length;j<N;){for(P=O.length;P--;O[P]*=B);for(O[0]+=I.indexOf(T.charAt(j++)),U=0;U<O.length;U++)O[U]>x-1&&(O[U+1]==null&&(O[U+1]=0),O[U+1]+=O[U]/x|0,O[U]%=x)}return O.reverse()}return function(T,B,x,I,U){var O,P,j,N,z,Z,ee,Ee,Fe=T.indexOf("."),Ne=ue,we=re;for(Fe>=0&&(N=K,K=0,T=T.replace(".",""),Ee=new W(B),Z=Ee.pow(T.length-Fe),K=N,Ee.c=w(E(y(Z.c),Z.e,"0"),10,x,_),Ee.e=Ee.c.length),ee=w(T,B,x,U?(O=qe,_):(O=_,qe)),j=N=ee.length;ee[--N]==0;ee.pop());if(!ee[0])return O.charAt(0);if(Fe<0?--j:(Z.c=ee,Z.e=j,Z.s=I,Z=F(Z,Ee,Ne,we,x),ee=Z.c,z=Z.r,j=Z.e),P=j+Ne+1,Fe=ee[P],N=x/2,z=z||P<0||ee[P+1]!=null,z=we<4?(Fe!=null||z)&&(we==0||we==(Z.s<0?3:2)):Fe>N||Fe==N&&(we==4||z||we==6&&ee[P-1]&1||we==(Z.s<0?8:7)),P<1||!ee[0])T=z?E(O.charAt(1),-Ne,O.charAt(0)):O.charAt(0);else{if(ee.length=P,z)for(--x;++ee[--P]>x;)ee[P]=0,P||(++j,ee=[1].concat(ee));for(N=ee.length;!ee[--N];);for(Fe=0,T="";Fe<=N;T+=O.charAt(ee[Fe++]));T=E(T,j,O.charAt(0))}return T}})(),F=(function(){function _(B,x,I){var U,O,P,j,N=0,z=B.length,Z=x%p,ee=x/p|0;for(B=B.slice();z--;)P=B[z]%p,j=B[z]/p|0,U=ee*P+j*Z,O=Z*P+U%p*p+N,N=(O/I|0)+(U/p|0)+ee*j,B[z]=O%I;return N&&(B=[N].concat(B)),B}function w(B,x,I,U){var O,P;if(I!=U)P=I>U?1:-1;else for(O=P=0;O<I;O++)if(B[O]!=x[O]){P=B[O]>x[O]?1:-1;break}return P}function T(B,x,I,U){for(var O=0;I--;)B[I]-=O,O=B[I]<x[I]?1:0,B[I]=O*U+B[I]-x[I];for(;!B[0]&&B.length>1;B.splice(0,1));}return function(B,x,I,U,O){var P,j,N,z,Z,ee,Ee,Fe,Ne,we,Se,Me,hn,pn,mn,ut,ir,Ke=B.s==x.s?1:-1,Ue=B.c,ke=x.c;if(!Ue||!Ue[0]||!ke||!ke[0])return new W(!B.s||!x.s||(Ue?ke&&Ue[0]==ke[0]:!ke)?NaN:Ue&&Ue[0]==0||!ke?Ke*0:Ke/0);for(Fe=new W(Ke),Ne=Fe.c=[],j=B.e-x.e,Ke=I+j+1,O||(O=c,j=S(B.e/l)-S(x.e/l),Ke=Ke/l|0),N=0;ke[N]==(Ue[N]||0);N++);if(ke[N]>(Ue[N]||0)&&j--,Ke<0)Ne.push(1),z=!0;else{for(pn=Ue.length,ut=ke.length,N=0,Ke+=2,Z=s(O/(ke[0]+1)),Z>1&&(ke=_(ke,Z,O),Ue=_(Ue,Z,O),ut=ke.length,pn=Ue.length),hn=ut,we=Ue.slice(0,ut),Se=we.length;Se<ut;we[Se++]=0);ir=ke.slice(),ir=[0].concat(ir),mn=ke[0],ke[1]>=O/2&&mn++;do{if(Z=0,P=w(ke,we,ut,Se),P<0){if(Me=we[0],ut!=Se&&(Me=Me*O+(we[1]||0)),Z=s(Me/mn),Z>1)for(Z>=O&&(Z=O-1),ee=_(ke,Z,O),Ee=ee.length,Se=we.length;w(ee,we,Ee,Se)==1;)Z--,T(ee,ut<Ee?ir:ke,Ee,O),Ee=ee.length,P=1;else Z==0&&(P=Z=1),ee=ke.slice(),Ee=ee.length;if(Ee<Se&&(ee=[0].concat(ee)),T(we,ee,Se,O),Se=we.length,P==-1)for(;w(ke,we,ut,Se)<1;)Z++,T(we,ut<Se?ir:ke,Se,O),Se=we.length}else P===0&&(Z++,we=[0]);Ne[N++]=Z,we[0]?we[Se++]=Ue[hn]||0:(we=[Ue[hn]],Se=1)}while((hn++<pn||we[0]!=null)&&Ke--);z=we[0]!=null,Ne[0]||Ne.splice(0,1)}if(O==c){for(N=1,Ke=Ne[0];Ke>=10;Ke/=10,N++);Re(Fe,I+(Fe.e=N+j*l-1)+1,U,z)}else Fe.e=j,Fe.r=+z;return Fe}})();function le(_,w,T,B){var x,I,U,O,P;if(T==null?T=re:m(T,0,8),!_.c)return _.toString();if(x=_.c[0],U=_.e,w==null)P=y(_.c),P=B==1||B==2&&(U<=fe||U>=pe)?b(P,U):E(P,U,"0");else if(_=Re(new W(_),w,T),I=_.e,P=y(_.c),O=P.length,B==1||B==2&&(w<=I||I<=fe)){for(;O<w;P+="0",O++);P=b(P,I)}else if(w-=U+(B===2&&I>U),P=E(P,I,"0"),I+1>O){if(--w>0)for(P+=".";w--;P+="0");}else if(w+=I-O,w>0)for(I+1==O&&(P+=".");w--;P+="0");return _.s<0&&x?"-"+P:P}function _e(_,w){for(var T,B,x=1,I=new W(_[0]);x<_.length;x++)B=new W(_[x]),(!B.s||(T=g(I,B))===w||T===0&&I.s===w)&&(I=B);return I}function xt(_,w,T){for(var B=1,x=w.length;!w[--x];w.pop());for(x=w[0];x>=10;x/=10,B++);return(T=B+T*l-1)>oe?_.c=_.e=null:T<Ae?_.c=[_.e=0]:(_.e=T,_.c=w),_}J=(function(){var _=/^(-?)0([xbo])(?=\w[\w.]*$)/i,w=/^([^.]+)\.$/,T=/^\.([^.]+)$/,B=/^-?(Infinity|NaN)$/,x=/^\s*\+(?=[\w.])|^\s+|\s+$/g;return function(I,U,O,P){var j,N=O?U:U.replace(x,"");if(B.test(N))I.s=isNaN(N)?null:N<0?-1:1;else{if(!O&&(N=N.replace(_,function(z,Z,ee){return j=(ee=ee.toLowerCase())=="x"?16:ee=="b"?2:8,!P||P==j?Z:z}),P&&(j=P,N=N.replace(w,"$1").replace(T,"0.$1")),U!=N))return new W(N,j);if(W.DEBUG)throw Error(i+"Not a"+(P?" base "+P:"")+" number: "+U);I.s=null}I.c=I.e=null}})();function Re(_,w,T,B){var x,I,U,O,P,j,N,z=_.c,Z=d;if(z){e:{for(x=1,O=z[0];O>=10;O/=10,x++);if(I=w-x,I<0)I+=l,U=w,P=z[j=0],N=s(P/Z[x-U-1]%10);else if(j=n((I+1)/l),j>=z.length)if(B){for(;z.length<=j;z.push(0));P=N=0,x=1,I%=l,U=I-l+1}else break e;else{for(P=O=z[j],x=1;O>=10;O/=10,x++);I%=l,U=I-l+x,N=U<0?0:s(P/Z[x-U-1]%10)}if(B=B||w<0||z[j+1]!=null||(U<0?P:P%Z[x-U-1]),B=T<4?(N||B)&&(T==0||T==(_.s<0?3:2)):N>5||N==5&&(T==4||B||T==6&&(I>0?U>0?P/Z[x-U]:0:z[j-1])%10&1||T==(_.s<0?8:7)),w<1||!z[0])return z.length=0,B?(w-=_.e+1,z[0]=Z[(l-w%l)%l],_.e=-w||0):z[0]=_.e=0,_;if(I==0?(z.length=j,O=1,j--):(z.length=j+1,O=Z[l-I],z[j]=U>0?s(P/Z[x-U]%Z[U])*O:0),B)for(;;)if(j==0){for(I=1,U=z[0];U>=10;U/=10,I++);for(U=z[0]+=O,O=1;U>=10;U/=10,O++);I!=O&&(_.e++,z[0]==c&&(z[0]=1));break}else{if(z[j]+=O,z[j]!=c)break;z[j--]=0,O=1}for(I=z.length;z[--I]===0;z.pop());}_.e>oe?_.c=_.e=null:_.e<Ae&&(_.c=[_.e=0])}return _}function Be(_){var w,T=_.e;return T===null?_.toString():(w=y(_.c),w=T<=fe||T>=pe?b(w,T):E(w,T,"0"),_.s<0?"-"+w:w)}return M.absoluteValue=M.abs=function(){var _=new W(this);return _.s<0&&(_.s=1),_},M.comparedTo=function(_,w){return g(this,new W(_,w))},M.decimalPlaces=M.dp=function(_,w){var T,B,x,I=this;if(_!=null)return m(_,0,A),w==null?w=re:m(w,0,8),Re(new W(I),_+I.e+1,w);if(!(T=I.c))return null;if(B=((x=T.length-1)-S(this.e/l))*l,x=T[x])for(;x%10==0;x/=10,B--);return B<0&&(B=0),B},M.dividedBy=M.div=function(_,w){return F(this,new W(_,w),ue,re)},M.dividedToIntegerBy=M.idiv=function(_,w){return F(this,new W(_,w),0,1)},M.exponentiatedBy=M.pow=function(_,w){var T,B,x,I,U,O,P,j,N,z=this;if(_=new W(_),_.c&&!_.isInteger())throw Error(i+"Exponent not an integer: "+Be(_));if(w!=null&&(w=new W(w)),O=_.e>14,!z.c||!z.c[0]||z.c[0]==1&&!z.e&&z.c.length==1||!_.c||!_.c[0])return N=new W(Math.pow(+Be(z),O?_.s*(2-k(_)):+Be(_))),w?N.mod(w):N;if(P=_.s<0,w){if(w.c?!w.c[0]:!w.s)return new W(NaN);B=!P&&z.isInteger()&&w.isInteger(),B&&(z=z.mod(w))}else{if(_.e>9&&(z.e>0||z.e<-1||(z.e==0?z.c[0]>1||O&&z.c[1]>=24e7:z.c[0]<8e13||O&&z.c[0]<=9999975e7)))return I=z.s<0&&k(_)?-0:0,z.e>-1&&(I=1/I),new W(P?1/I:I);K&&(I=n(K/l+2))}for(O?(T=new W(.5),P&&(_.s=1),j=k(_)):(x=Math.abs(+Be(_)),j=x%2),N=new W(X);;){if(j){if(N=N.times(z),!N.c)break;I?N.c.length>I&&(N.c.length=I):B&&(N=N.mod(w))}if(x){if(x=s(x/2),x===0)break;j=x%2}else if(_=_.times(T),Re(_,_.e+1,1),_.e>14)j=k(_);else{if(x=+Be(_),x===0)break;j=x%2}z=z.times(z),I?z.c&&z.c.length>I&&(z.c.length=I):B&&(z=z.mod(w))}return B?N:(P&&(N=X.div(N)),w?N.mod(w):I?Re(N,K,re,U):N)},M.integerValue=function(_){var w=new W(this);return _==null?_=re:m(_,0,8),Re(w,w.e+1,_)},M.isEqualTo=M.eq=function(_,w){return g(this,new W(_,w))===0},M.isFinite=function(){return!!this.c},M.isGreaterThan=M.gt=function(_,w){return g(this,new W(_,w))>0},M.isGreaterThanOrEqualTo=M.gte=function(_,w){return(w=g(this,new W(_,w)))===1||w===0},M.isInteger=function(){return!!this.c&&S(this.e/l)>this.c.length-2},M.isLessThan=M.lt=function(_,w){return g(this,new W(_,w))<0},M.isLessThanOrEqualTo=M.lte=function(_,w){return(w=g(this,new W(_,w)))===-1||w===0},M.isNaN=function(){return!this.s},M.isNegative=function(){return this.s<0},M.isPositive=function(){return this.s>0},M.isZero=function(){return!!this.c&&this.c[0]==0},M.minus=function(_,w){var T,B,x,I,U=this,O=U.s;if(_=new W(_,w),w=_.s,!O||!w)return new W(NaN);if(O!=w)return _.s=-w,U.plus(_);var P=U.e/l,j=_.e/l,N=U.c,z=_.c;if(!P||!j){if(!N||!z)return N?(_.s=-w,_):new W(z?U:NaN);if(!N[0]||!z[0])return z[0]?(_.s=-w,_):new W(N[0]?U:re==3?-0:0)}if(P=S(P),j=S(j),N=N.slice(),O=P-j){for((I=O<0)?(O=-O,x=N):(j=P,x=z),x.reverse(),w=O;w--;x.push(0));x.reverse()}else for(B=(I=(O=N.length)<(w=z.length))?O:w,O=w=0;w<B;w++)if(N[w]!=z[w]){I=N[w]<z[w];break}if(I&&(x=N,N=z,z=x,_.s=-_.s),w=(B=z.length)-(T=N.length),w>0)for(;w--;N[T++]=0);for(w=c-1;B>O;){if(N[--B]<z[B]){for(T=B;T&&!N[--T];N[T]=w);--N[T],N[B]+=c}N[B]-=z[B]}for(;N[0]==0;N.splice(0,1),--j);return N[0]?xt(_,N,j):(_.s=re==3?-1:1,_.c=[_.e=0],_)},M.modulo=M.mod=function(_,w){var T,B,x=this;return _=new W(_,w),!x.c||!_.s||_.c&&!_.c[0]?new W(NaN):!_.c||x.c&&!x.c[0]?new W(x):(G==9?(B=_.s,_.s=1,T=F(x,_,0,3),_.s=B,T.s*=B):T=F(x,_,0,G),_=x.minus(T.times(_)),!_.c[0]&&G==1&&(_.s=x.s),_)},M.multipliedBy=M.times=function(_,w){var T,B,x,I,U,O,P,j,N,z,Z,ee,Ee,Fe,Ne,we=this,Se=we.c,Me=(_=new W(_,w)).c;if(!Se||!Me||!Se[0]||!Me[0])return!we.s||!_.s||Se&&!Se[0]&&!Me||Me&&!Me[0]&&!Se?_.c=_.e=_.s=null:(_.s*=we.s,!Se||!Me?_.c=_.e=null:(_.c=[0],_.e=0)),_;for(B=S(we.e/l)+S(_.e/l),_.s*=we.s,P=Se.length,z=Me.length,P<z&&(Ee=Se,Se=Me,Me=Ee,x=P,P=z,z=x),x=P+z,Ee=[];x--;Ee.push(0));for(Fe=c,Ne=p,x=z;--x>=0;){for(T=0,Z=Me[x]%Ne,ee=Me[x]/Ne|0,U=P,I=x+U;I>x;)j=Se[--U]%Ne,N=Se[U]/Ne|0,O=ee*j+N*Z,j=Z*j+O%Ne*Ne+Ee[I]+T,T=(j/Fe|0)+(O/Ne|0)+ee*N,Ee[I--]=j%Fe;Ee[I]=T}return T?++B:Ee.splice(0,1),xt(_,Ee,B)},M.negated=function(){var _=new W(this);return _.s=-_.s||null,_},M.plus=function(_,w){var T,B=this,x=B.s;if(_=new W(_,w),w=_.s,!x||!w)return new W(NaN);if(x!=w)return _.s=-w,B.minus(_);var I=B.e/l,U=_.e/l,O=B.c,P=_.c;if(!I||!U){if(!O||!P)return new W(x/0);if(!O[0]||!P[0])return P[0]?_:new W(O[0]?B:x*0)}if(I=S(I),U=S(U),O=O.slice(),x=I-U){for(x>0?(U=I,T=P):(x=-x,T=O),T.reverse();x--;T.push(0));T.reverse()}for(x=O.length,w=P.length,x-w<0&&(T=P,P=O,O=T,w=x),x=0;w;)x=(O[--w]=O[w]+P[w]+x)/c|0,O[w]=c===O[w]?0:O[w]%c;return x&&(O=[x].concat(O),++U),xt(_,O,U)},M.precision=M.sd=function(_,w){var T,B,x,I=this;if(_!=null&&_!==!!_)return m(_,1,A),w==null?w=re:m(w,0,8),Re(new W(I),_,w);if(!(T=I.c))return null;if(x=T.length-1,B=x*l+1,x=T[x]){for(;x%10==0;x/=10,B--);for(x=T[0];x>=10;x/=10,B++);}return _&&I.e+1>B&&(B=I.e+1),B},M.shiftedBy=function(_){return m(_,-h,h),this.times("1e"+_)},M.squareRoot=M.sqrt=function(){var _,w,T,B,x,I=this,U=I.c,O=I.s,P=I.e,j=ue+4,N=new W("0.5");if(O!==1||!U||!U[0])return new W(!O||O<0&&(!U||U[0])?NaN:U?I:1/0);if(O=Math.sqrt(+Be(I)),O==0||O==1/0?(w=y(U),(w.length+P)%2==0&&(w+="0"),O=Math.sqrt(+w),P=S((P+1)/2)-(P<0||P%2),O==1/0?w="5e"+P:(w=O.toExponential(),w=w.slice(0,w.indexOf("e")+1)+P),T=new W(w)):T=new W(O+""),T.c[0]){for(P=T.e,O=P+j,O<3&&(O=0);;)if(x=T,T=N.times(x.plus(F(I,x,j,1))),y(x.c).slice(0,O)===(w=y(T.c)).slice(0,O))if(T.e<P&&--O,w=w.slice(O-3,O+1),w=="9999"||!B&&w=="4999"){if(!B&&(Re(x,x.e+ue+2,0),x.times(x).eq(I))){T=x;break}j+=4,O+=4,B=1}else{(!+w||!+w.slice(1)&&w.charAt(0)=="5")&&(Re(T,T.e+ue+2,1),_=!T.times(T).eq(I));break}}return Re(T,T.e+ue+1,re,_)},M.toExponential=function(_,w){return _!=null&&(m(_,0,A),_++),le(this,_,w,1)},M.toFixed=function(_,w){return _!=null&&(m(_,0,A),_=_+this.e+1),le(this,_,w)},M.toFormat=function(_,w,T){var B,x=this;if(T==null)_!=null&&w&&typeof w=="object"?(T=w,w=null):_&&typeof _=="object"?(T=_,_=w=null):T=ae;else if(typeof T!="object")throw Error(i+"Argument not an object: "+T);if(B=x.toFixed(_,w),x.c){var I,U=B.split("."),O=+T.groupSize,P=+T.secondaryGroupSize,j=T.groupSeparator||"",N=U[0],z=U[1],Z=x.s<0,ee=Z?N.slice(1):N,Ee=ee.length;if(P&&(I=O,O=P,P=I,Ee-=I),O>0&&Ee>0){for(I=Ee%O||O,N=ee.substr(0,I);I<Ee;I+=O)N+=j+ee.substr(I,O);P>0&&(N+=j+ee.slice(I)),Z&&(N="-"+N)}B=z?N+(T.decimalSeparator||"")+((P=+T.fractionGroupSize)?z.replace(new RegExp("\\d{"+P+"}\\B","g"),"$&"+(T.fractionGroupSeparator||"")):z):N}return(T.prefix||"")+B+(T.suffix||"")},M.toFraction=function(_){var w,T,B,x,I,U,O,P,j,N,z,Z,ee=this,Ee=ee.c;if(_!=null&&(O=new W(_),!O.isInteger()&&(O.c||O.s!==1)||O.lt(X)))throw Error(i+"Argument "+(O.isInteger()?"out of range: ":"not an integer: ")+Be(O));if(!Ee)return new W(ee);for(w=new W(X),j=T=new W(X),B=P=new W(X),Z=y(Ee),I=w.e=Z.length-ee.e-1,w.c[0]=d[(U=I%l)<0?l+U:U],_=!_||O.comparedTo(w)>0?I>0?w:j:O,U=oe,oe=1/0,O=new W(Z),P.c[0]=0;N=F(O,w,0,1),x=T.plus(N.times(B)),x.comparedTo(_)!=1;)T=B,B=x,j=P.plus(N.times(x=j)),P=x,w=O.minus(N.times(x=w)),O=x;return x=F(_.minus(T),B,0,1),P=P.plus(x.times(j)),T=T.plus(x.times(B)),P.s=j.s=ee.s,I=I*2,z=F(j,B,I,re).minus(ee).abs().comparedTo(F(P,T,I,re).minus(ee).abs())<1?[j,B]:[P,T],oe=U,z},M.toNumber=function(){return+Be(this)},M.toPrecision=function(_,w){return _!=null&&m(_,1,A),le(this,_,w,2)},M.toString=function(_){var w,T=this,B=T.s,x=T.e;return x===null?B?(w="Infinity",B<0&&(w="-"+w)):w="NaN":(_==null?w=x<=fe||x>=pe?b(y(T.c),x):E(y(T.c),x,"0"):_===10&&De?(T=Re(new W(T),ue+x+1,re),w=E(y(T.c),T.e,"0")):(m(_,2,qe.length,"Base"),w=$(E(y(T.c),x,"0"),10,_,B,!0)),B<0&&T.c[0]&&(w="-"+w)),w},M.valueOf=M.toJSON=function(){return Be(this)},M._isBigNumber=!0,R!=null&&W.set(R),W}function S(R){var F=R|0;return R>0||R===F?F:F-1}function y(R){for(var F,$,J=1,M=R.length,X=R[0]+"";J<M;){for(F=R[J++]+"",$=l-F.length;$--;F="0"+F);X+=F}for(M=X.length;X.charCodeAt(--M)===48;);return X.slice(0,M+1||1)}function g(R,F){var $,J,M=R.c,X=F.c,ue=R.s,re=F.s,fe=R.e,pe=F.e;if(!ue||!re)return null;if($=M&&!M[0],J=X&&!X[0],$||J)return $?J?0:-re:ue;if(ue!=re)return ue;if($=ue<0,J=fe==pe,!M||!X)return J?0:!M^$?1:-1;if(!J)return fe>pe^$?1:-1;for(re=(fe=M.length)<(pe=X.length)?fe:pe,ue=0;ue<re;ue++)if(M[ue]!=X[ue])return M[ue]>X[ue]^$?1:-1;return fe==pe?0:fe>pe^$?1:-1}function m(R,F,$,J){if(R<F||R>$||R!==s(R))throw Error(i+(J||"Argument")+(typeof R=="number"?R<F||R>$?" out of range: ":" not an integer: ":" not a primitive number: ")+String(R))}function k(R){var F=R.c.length-1;return S(R.e/l)==F&&R.c[F]%2!=0}function b(R,F){return(R.length>1?R.charAt(0)+"."+R.slice(1):R)+(F<0?"e":"e+")+F}function E(R,F,$){var J,M;if(F<0){for(M=$+".";++F;M+=$);R=M+R}else if(J=R.length,++F>J){for(M=$,F-=J;--F;M+=$);R+=M}else F<J&&(R=R.slice(0,F)+"."+R.slice(F));return R}e=v(),e.default=e.BigNumber=e,typeof define=="function"&&define.amd?define(function(){return e}):typeof gi<"u"&&gi.exports?gi.exports=e:(t||(t=typeof self<"u"&&self?self:window),t.BigNumber=e)})(Lp)});var $p=V((YR,qp)=>{var Mp=sc(),Up=qp.exports;(function(){"use strict";function t(h){return h<10?"0"+h:h}var e=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,r=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,n,s,i={"\b":"\\b"," ":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"},u;function c(h){return r.lastIndex=0,r.test(h)?'"'+h.replace(r,function(d){var p=i[d];return typeof p=="string"?p:"\\u"+("0000"+d.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+h+'"'}function l(h,d){var p,A,v,S,y=n,g,m=d[h],k=m!=null&&(m instanceof Mp||Mp.isBigNumber(m));switch(m&&typeof m=="object"&&typeof m.toJSON=="function"&&(m=m.toJSON(h)),typeof u=="function"&&(m=u.call(d,h,m)),typeof m){case"string":return k?m:c(m);case"number":return isFinite(m)?String(m):"null";case"boolean":case"null":case"bigint":return String(m);case"object":if(!m)return"null";if(n+=s,g=[],Object.prototype.toString.apply(m)==="[object Array]"){for(S=m.length,p=0;p<S;p+=1)g[p]=l(p,m)||"null";return v=g.length===0?"[]":n?`[
|
|
43
|
+
`}yield n}static#o;static#i;static async#a(){return this.#o||=(await Promise.resolve().then(()=>Nr(ep()))).HttpsProxyAgent,this.#o}static async#u(){let e=typeof window<"u"&&!!window;return this.#i||=e?window.fetch:(await Promise.resolve().then(()=>(Vp(),Jp))).default,this.#i}static mergeHeaders(e,...r){e=e instanceof Headers?e:new Headers(e);for(let n of r)(n instanceof Headers?n:new Headers(n)).forEach((i,u)=>{u==="set-cookie"?e.append(u,i):e.set(u,i)});return e}};$n.Gaxios=bi;qn=bi});var Ve=V(tt=>{"use strict";var aw=tt&&tt.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,s)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),uw=tt&&tt.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&aw(e,t,r)};Object.defineProperty(tt,"__esModule",{value:!0});tt.instance=tt.Gaxios=tt.GaxiosError=void 0;tt.request=lw;var Xp=Qp();Object.defineProperty(tt,"Gaxios",{enumerable:!0,get:function(){return Xp.Gaxios}});var cw=Lu();Object.defineProperty(tt,"GaxiosError",{enumerable:!0,get:function(){return cw.GaxiosError}});uw(qu(),tt);tt.instance=new Xp.Gaxios;async function lw(t){return tt.instance.request(t)}});var cc=V((Zp,Ci)=>{(function(t){"use strict";var e,r=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,n=Math.ceil,s=Math.floor,i="[BigNumber Error] ",u=i+"Number primitive has more than 15 significant digits: ",c=1e14,l=14,h=9007199254740991,d=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],p=1e7,w=1e9;function T(R){var F,$,J,M=W.prototype={constructor:W,toString:null,valueOf:null},Q=new W(1),ue=20,re=4,de=-7,pe=21,Ae=-1e7,oe=1e7,me=!1,G=1,K=0,ae={prefix:"",groupSize:3,secondaryGroupSize:0,groupSeparator:",",decimalSeparator:".",fractionGroupSize:0,fractionGroupSeparator:"\xA0",suffix:""},qe="0123456789abcdefghijklmnopqrstuvwxyz",Te=!0;function W(_,E){var k,B,O,I,U,x,P,j,N=this;if(!(N instanceof W))return new W(_,E);if(E==null){if(_&&_._isBigNumber===!0){N.s=_.s,!_.c||_.e>oe?N.c=N.e=null:_.e<Ae?N.c=[N.e=0]:(N.e=_.e,N.c=_.c.slice());return}if((x=typeof _=="number")&&_*0==0){if(N.s=1/_<0?(_=-_,-1):1,_===~~_){for(I=0,U=_;U>=10;U/=10,I++);I>oe?N.c=N.e=null:(N.e=I,N.c=[_]);return}j=String(_)}else{if(!r.test(j=String(_)))return J(N,j,x);N.s=j.charCodeAt(0)==45?(j=j.slice(1),-1):1}(I=j.indexOf("."))>-1&&(j=j.replace(".","")),(U=j.search(/e/i))>0?(I<0&&(I=U),I+=+j.slice(U+1),j=j.substring(0,U)):I<0&&(I=j.length)}else{if(m(E,2,qe.length,"Base"),E==10&&Te)return N=new W(_),Re(N,ue+N.e+1,re);if(j=String(_),x=typeof _=="number"){if(_*0!=0)return J(N,j,x,E);if(N.s=1/_<0?(j=j.slice(1),-1):1,W.DEBUG&&j.replace(/^0\.0*|\./,"").length>15)throw Error(u+_)}else N.s=j.charCodeAt(0)===45?(j=j.slice(1),-1):1;for(k=qe.slice(0,E),I=U=0,P=j.length;U<P;U++)if(k.indexOf(B=j.charAt(U))<0){if(B=="."){if(U>I){I=P;continue}}else if(!O&&(j==j.toUpperCase()&&(j=j.toLowerCase())||j==j.toLowerCase()&&(j=j.toUpperCase()))){O=!0,U=-1,I=0;continue}return J(N,String(_),x,E)}x=!1,j=$(j,E,10,N.s),(I=j.indexOf("."))>-1?j=j.replace(".",""):I=j.length}for(U=0;j.charCodeAt(U)===48;U++);for(P=j.length;j.charCodeAt(--P)===48;);if(j=j.slice(U,++P)){if(P-=U,x&&W.DEBUG&&P>15&&(_>h||_!==s(_)))throw Error(u+N.s*_);if((I=I-U-1)>oe)N.c=N.e=null;else if(I<Ae)N.c=[N.e=0];else{if(N.e=I,N.c=[],U=(I+1)%l,I<0&&(U+=l),U<P){for(U&&N.c.push(+j.slice(0,U)),P-=l;U<P;)N.c.push(+j.slice(U,U+=l));U=l-(j=j.slice(U)).length}else U-=P;for(;U--;j+="0");N.c.push(+j)}}else N.c=[N.e=0]}W.clone=T,W.ROUND_UP=0,W.ROUND_DOWN=1,W.ROUND_CEIL=2,W.ROUND_FLOOR=3,W.ROUND_HALF_UP=4,W.ROUND_HALF_DOWN=5,W.ROUND_HALF_EVEN=6,W.ROUND_HALF_CEIL=7,W.ROUND_HALF_FLOOR=8,W.EUCLID=9,W.config=W.set=function(_){var E,k;if(_!=null)if(typeof _=="object"){if(_.hasOwnProperty(E="DECIMAL_PLACES")&&(k=_[E],m(k,0,w,E),ue=k),_.hasOwnProperty(E="ROUNDING_MODE")&&(k=_[E],m(k,0,8,E),re=k),_.hasOwnProperty(E="EXPONENTIAL_AT")&&(k=_[E],k&&k.pop?(m(k[0],-w,0,E),m(k[1],0,w,E),de=k[0],pe=k[1]):(m(k,-w,w,E),de=-(pe=k<0?-k:k))),_.hasOwnProperty(E="RANGE"))if(k=_[E],k&&k.pop)m(k[0],-w,-1,E),m(k[1],1,w,E),Ae=k[0],oe=k[1];else if(m(k,-w,w,E),k)Ae=-(oe=k<0?-k:k);else throw Error(i+E+" cannot be zero: "+k);if(_.hasOwnProperty(E="CRYPTO"))if(k=_[E],k===!!k)if(k)if(typeof crypto<"u"&&crypto&&(crypto.getRandomValues||crypto.randomBytes))me=k;else throw me=!k,Error(i+"crypto unavailable");else me=k;else throw Error(i+E+" not true or false: "+k);if(_.hasOwnProperty(E="MODULO_MODE")&&(k=_[E],m(k,0,9,E),G=k),_.hasOwnProperty(E="POW_PRECISION")&&(k=_[E],m(k,0,w,E),K=k),_.hasOwnProperty(E="FORMAT"))if(k=_[E],typeof k=="object")ae=k;else throw Error(i+E+" not an object: "+k);if(_.hasOwnProperty(E="ALPHABET"))if(k=_[E],typeof k=="string"&&!/^.?$|[+\-.\s]|(.).*\1/.test(k))Te=k.slice(0,10)=="0123456789",qe=k;else throw Error(i+E+" invalid: "+k)}else throw Error(i+"Object expected: "+_);return{DECIMAL_PLACES:ue,ROUNDING_MODE:re,EXPONENTIAL_AT:[de,pe],RANGE:[Ae,oe],CRYPTO:me,MODULO_MODE:G,POW_PRECISION:K,FORMAT:ae,ALPHABET:qe}},W.isBigNumber=function(_){if(!_||_._isBigNumber!==!0)return!1;if(!W.DEBUG)return!0;var E,k,B=_.c,O=_.e,I=_.s;e:if({}.toString.call(B)=="[object Array]"){if((I===1||I===-1)&&O>=-w&&O<=w&&O===s(O)){if(B[0]===0){if(O===0&&B.length===1)return!0;break e}if(E=(O+1)%l,E<1&&(E+=l),String(B[0]).length==E){for(E=0;E<B.length;E++)if(k=B[E],k<0||k>=c||k!==s(k))break e;if(k!==0)return!0}}}else if(B===null&&O===null&&(I===null||I===1||I===-1))return!0;throw Error(i+"Invalid BigNumber: "+_)},W.maximum=W.max=function(){return _e(arguments,-1)},W.minimum=W.min=function(){return _e(arguments,1)},W.random=(function(){var _=9007199254740992,E=Math.random()*_&2097151?function(){return s(Math.random()*_)}:function(){return(Math.random()*1073741824|0)*8388608+(Math.random()*8388608|0)};return function(k){var B,O,I,U,x,P=0,j=[],N=new W(Q);if(k==null?k=ue:m(k,0,w),U=n(k/l),me)if(crypto.getRandomValues){for(B=crypto.getRandomValues(new Uint32Array(U*=2));P<U;)x=B[P]*131072+(B[P+1]>>>11),x>=9e15?(O=crypto.getRandomValues(new Uint32Array(2)),B[P]=O[0],B[P+1]=O[1]):(j.push(x%1e14),P+=2);P=U/2}else if(crypto.randomBytes){for(B=crypto.randomBytes(U*=7);P<U;)x=(B[P]&31)*281474976710656+B[P+1]*1099511627776+B[P+2]*4294967296+B[P+3]*16777216+(B[P+4]<<16)+(B[P+5]<<8)+B[P+6],x>=9e15?crypto.randomBytes(7).copy(B,P):(j.push(x%1e14),P+=7);P=U/7}else throw me=!1,Error(i+"crypto unavailable");if(!me)for(;P<U;)x=E(),x<9e15&&(j[P++]=x%1e14);for(U=j[--P],k%=l,U&&k&&(x=d[l-k],j[P]=s(U/x)*x);j[P]===0;j.pop(),P--);if(P<0)j=[I=0];else{for(I=-1;j[0]===0;j.splice(0,1),I-=l);for(P=1,x=j[0];x>=10;x/=10,P++);P<l&&(I-=l-P)}return N.e=I,N.c=j,N}})(),W.sum=function(){for(var _=1,E=arguments,k=new W(E[0]);_<E.length;)k=k.plus(E[_++]);return k},$=(function(){var _="0123456789";function E(k,B,O,I){for(var U,x=[0],P,j=0,N=k.length;j<N;){for(P=x.length;P--;x[P]*=B);for(x[0]+=I.indexOf(k.charAt(j++)),U=0;U<x.length;U++)x[U]>O-1&&(x[U+1]==null&&(x[U+1]=0),x[U+1]+=x[U]/O|0,x[U]%=O)}return x.reverse()}return function(k,B,O,I,U){var x,P,j,N,z,Z,ee,Ee,Fe=k.indexOf("."),Ne=ue,we=re;for(Fe>=0&&(N=K,K=0,k=k.replace(".",""),Ee=new W(B),Z=Ee.pow(k.length-Fe),K=N,Ee.c=E(A(y(Z.c),Z.e,"0"),10,O,_),Ee.e=Ee.c.length),ee=E(k,B,O,U?(x=qe,_):(x=_,qe)),j=N=ee.length;ee[--N]==0;ee.pop());if(!ee[0])return x.charAt(0);if(Fe<0?--j:(Z.c=ee,Z.e=j,Z.s=I,Z=F(Z,Ee,Ne,we,O),ee=Z.c,z=Z.r,j=Z.e),P=j+Ne+1,Fe=ee[P],N=O/2,z=z||P<0||ee[P+1]!=null,z=we<4?(Fe!=null||z)&&(we==0||we==(Z.s<0?3:2)):Fe>N||Fe==N&&(we==4||z||we==6&&ee[P-1]&1||we==(Z.s<0?8:7)),P<1||!ee[0])k=z?A(x.charAt(1),-Ne,x.charAt(0)):x.charAt(0);else{if(ee.length=P,z)for(--O;++ee[--P]>O;)ee[P]=0,P||(++j,ee=[1].concat(ee));for(N=ee.length;!ee[--N];);for(Fe=0,k="";Fe<=N;k+=x.charAt(ee[Fe++]));k=A(k,j,x.charAt(0))}return k}})(),F=(function(){function _(B,O,I){var U,x,P,j,N=0,z=B.length,Z=O%p,ee=O/p|0;for(B=B.slice();z--;)P=B[z]%p,j=B[z]/p|0,U=ee*P+j*Z,x=Z*P+U%p*p+N,N=(x/I|0)+(U/p|0)+ee*j,B[z]=x%I;return N&&(B=[N].concat(B)),B}function E(B,O,I,U){var x,P;if(I!=U)P=I>U?1:-1;else for(x=P=0;x<I;x++)if(B[x]!=O[x]){P=B[x]>O[x]?1:-1;break}return P}function k(B,O,I,U){for(var x=0;I--;)B[I]-=x,x=B[I]<O[I]?1:0,B[I]=x*U+B[I]-O[I];for(;!B[0]&&B.length>1;B.splice(0,1));}return function(B,O,I,U,x){var P,j,N,z,Z,ee,Ee,Fe,Ne,we,Se,Me,gn,yn,_n,ut,ur,Ke=B.s==O.s?1:-1,Ue=B.c,ve=O.c;if(!Ue||!Ue[0]||!ve||!ve[0])return new W(!B.s||!O.s||(Ue?ve&&Ue[0]==ve[0]:!ve)?NaN:Ue&&Ue[0]==0||!ve?Ke*0:Ke/0);for(Fe=new W(Ke),Ne=Fe.c=[],j=B.e-O.e,Ke=I+j+1,x||(x=c,j=S(B.e/l)-S(O.e/l),Ke=Ke/l|0),N=0;ve[N]==(Ue[N]||0);N++);if(ve[N]>(Ue[N]||0)&&j--,Ke<0)Ne.push(1),z=!0;else{for(yn=Ue.length,ut=ve.length,N=0,Ke+=2,Z=s(x/(ve[0]+1)),Z>1&&(ve=_(ve,Z,x),Ue=_(Ue,Z,x),ut=ve.length,yn=Ue.length),gn=ut,we=Ue.slice(0,ut),Se=we.length;Se<ut;we[Se++]=0);ur=ve.slice(),ur=[0].concat(ur),_n=ve[0],ve[1]>=x/2&&_n++;do{if(Z=0,P=E(ve,we,ut,Se),P<0){if(Me=we[0],ut!=Se&&(Me=Me*x+(we[1]||0)),Z=s(Me/_n),Z>1)for(Z>=x&&(Z=x-1),ee=_(ve,Z,x),Ee=ee.length,Se=we.length;E(ee,we,Ee,Se)==1;)Z--,k(ee,ut<Ee?ur:ve,Ee,x),Ee=ee.length,P=1;else Z==0&&(P=Z=1),ee=ve.slice(),Ee=ee.length;if(Ee<Se&&(ee=[0].concat(ee)),k(we,ee,Se,x),Se=we.length,P==-1)for(;E(ve,we,ut,Se)<1;)Z++,k(we,ut<Se?ur:ve,Se,x),Se=we.length}else P===0&&(Z++,we=[0]);Ne[N++]=Z,we[0]?we[Se++]=Ue[gn]||0:(we=[Ue[gn]],Se=1)}while((gn++<yn||we[0]!=null)&&Ke--);z=we[0]!=null,Ne[0]||Ne.splice(0,1)}if(x==c){for(N=1,Ke=Ne[0];Ke>=10;Ke/=10,N++);Re(Fe,I+(Fe.e=N+j*l-1)+1,U,z)}else Fe.e=j,Fe.r=+z;return Fe}})();function le(_,E,k,B){var O,I,U,x,P;if(k==null?k=re:m(k,0,8),!_.c)return _.toString();if(O=_.c[0],U=_.e,E==null)P=y(_.c),P=B==1||B==2&&(U<=de||U>=pe)?b(P,U):A(P,U,"0");else if(_=Re(new W(_),E,k),I=_.e,P=y(_.c),x=P.length,B==1||B==2&&(E<=I||I<=de)){for(;x<E;P+="0",x++);P=b(P,I)}else if(E-=U+(B===2&&I>U),P=A(P,I,"0"),I+1>x){if(--E>0)for(P+=".";E--;P+="0");}else if(E+=I-x,E>0)for(I+1==x&&(P+=".");E--;P+="0");return _.s<0&&O?"-"+P:P}function _e(_,E){for(var k,B,O=1,I=new W(_[0]);O<_.length;O++)B=new W(_[O]),(!B.s||(k=g(I,B))===E||k===0&&I.s===E)&&(I=B);return I}function Ot(_,E,k){for(var B=1,O=E.length;!E[--O];E.pop());for(O=E[0];O>=10;O/=10,B++);return(k=B+k*l-1)>oe?_.c=_.e=null:k<Ae?_.c=[_.e=0]:(_.e=k,_.c=E),_}J=(function(){var _=/^(-?)0([xbo])(?=\w[\w.]*$)/i,E=/^([^.]+)\.$/,k=/^\.([^.]+)$/,B=/^-?(Infinity|NaN)$/,O=/^\s*\+(?=[\w.])|^\s+|\s+$/g;return function(I,U,x,P){var j,N=x?U:U.replace(O,"");if(B.test(N))I.s=isNaN(N)?null:N<0?-1:1;else{if(!x&&(N=N.replace(_,function(z,Z,ee){return j=(ee=ee.toLowerCase())=="x"?16:ee=="b"?2:8,!P||P==j?Z:z}),P&&(j=P,N=N.replace(E,"$1").replace(k,"0.$1")),U!=N))return new W(N,j);if(W.DEBUG)throw Error(i+"Not a"+(P?" base "+P:"")+" number: "+U);I.s=null}I.c=I.e=null}})();function Re(_,E,k,B){var O,I,U,x,P,j,N,z=_.c,Z=d;if(z){e:{for(O=1,x=z[0];x>=10;x/=10,O++);if(I=E-O,I<0)I+=l,U=E,P=z[j=0],N=s(P/Z[O-U-1]%10);else if(j=n((I+1)/l),j>=z.length)if(B){for(;z.length<=j;z.push(0));P=N=0,O=1,I%=l,U=I-l+1}else break e;else{for(P=x=z[j],O=1;x>=10;x/=10,O++);I%=l,U=I-l+O,N=U<0?0:s(P/Z[O-U-1]%10)}if(B=B||E<0||z[j+1]!=null||(U<0?P:P%Z[O-U-1]),B=k<4?(N||B)&&(k==0||k==(_.s<0?3:2)):N>5||N==5&&(k==4||B||k==6&&(I>0?U>0?P/Z[O-U]:0:z[j-1])%10&1||k==(_.s<0?8:7)),E<1||!z[0])return z.length=0,B?(E-=_.e+1,z[0]=Z[(l-E%l)%l],_.e=-E||0):z[0]=_.e=0,_;if(I==0?(z.length=j,x=1,j--):(z.length=j+1,x=Z[l-I],z[j]=U>0?s(P/Z[O-U]%Z[U])*x:0),B)for(;;)if(j==0){for(I=1,U=z[0];U>=10;U/=10,I++);for(U=z[0]+=x,x=1;U>=10;U/=10,x++);I!=x&&(_.e++,z[0]==c&&(z[0]=1));break}else{if(z[j]+=x,z[j]!=c)break;z[j--]=0,x=1}for(I=z.length;z[--I]===0;z.pop());}_.e>oe?_.c=_.e=null:_.e<Ae&&(_.c=[_.e=0])}return _}function Be(_){var E,k=_.e;return k===null?_.toString():(E=y(_.c),E=k<=de||k>=pe?b(E,k):A(E,k,"0"),_.s<0?"-"+E:E)}return M.absoluteValue=M.abs=function(){var _=new W(this);return _.s<0&&(_.s=1),_},M.comparedTo=function(_,E){return g(this,new W(_,E))},M.decimalPlaces=M.dp=function(_,E){var k,B,O,I=this;if(_!=null)return m(_,0,w),E==null?E=re:m(E,0,8),Re(new W(I),_+I.e+1,E);if(!(k=I.c))return null;if(B=((O=k.length-1)-S(this.e/l))*l,O=k[O])for(;O%10==0;O/=10,B--);return B<0&&(B=0),B},M.dividedBy=M.div=function(_,E){return F(this,new W(_,E),ue,re)},M.dividedToIntegerBy=M.idiv=function(_,E){return F(this,new W(_,E),0,1)},M.exponentiatedBy=M.pow=function(_,E){var k,B,O,I,U,x,P,j,N,z=this;if(_=new W(_),_.c&&!_.isInteger())throw Error(i+"Exponent not an integer: "+Be(_));if(E!=null&&(E=new W(E)),x=_.e>14,!z.c||!z.c[0]||z.c[0]==1&&!z.e&&z.c.length==1||!_.c||!_.c[0])return N=new W(Math.pow(+Be(z),x?_.s*(2-v(_)):+Be(_))),E?N.mod(E):N;if(P=_.s<0,E){if(E.c?!E.c[0]:!E.s)return new W(NaN);B=!P&&z.isInteger()&&E.isInteger(),B&&(z=z.mod(E))}else{if(_.e>9&&(z.e>0||z.e<-1||(z.e==0?z.c[0]>1||x&&z.c[1]>=24e7:z.c[0]<8e13||x&&z.c[0]<=9999975e7)))return I=z.s<0&&v(_)?-0:0,z.e>-1&&(I=1/I),new W(P?1/I:I);K&&(I=n(K/l+2))}for(x?(k=new W(.5),P&&(_.s=1),j=v(_)):(O=Math.abs(+Be(_)),j=O%2),N=new W(Q);;){if(j){if(N=N.times(z),!N.c)break;I?N.c.length>I&&(N.c.length=I):B&&(N=N.mod(E))}if(O){if(O=s(O/2),O===0)break;j=O%2}else if(_=_.times(k),Re(_,_.e+1,1),_.e>14)j=v(_);else{if(O=+Be(_),O===0)break;j=O%2}z=z.times(z),I?z.c&&z.c.length>I&&(z.c.length=I):B&&(z=z.mod(E))}return B?N:(P&&(N=Q.div(N)),E?N.mod(E):I?Re(N,K,re,U):N)},M.integerValue=function(_){var E=new W(this);return _==null?_=re:m(_,0,8),Re(E,E.e+1,_)},M.isEqualTo=M.eq=function(_,E){return g(this,new W(_,E))===0},M.isFinite=function(){return!!this.c},M.isGreaterThan=M.gt=function(_,E){return g(this,new W(_,E))>0},M.isGreaterThanOrEqualTo=M.gte=function(_,E){return(E=g(this,new W(_,E)))===1||E===0},M.isInteger=function(){return!!this.c&&S(this.e/l)>this.c.length-2},M.isLessThan=M.lt=function(_,E){return g(this,new W(_,E))<0},M.isLessThanOrEqualTo=M.lte=function(_,E){return(E=g(this,new W(_,E)))===-1||E===0},M.isNaN=function(){return!this.s},M.isNegative=function(){return this.s<0},M.isPositive=function(){return this.s>0},M.isZero=function(){return!!this.c&&this.c[0]==0},M.minus=function(_,E){var k,B,O,I,U=this,x=U.s;if(_=new W(_,E),E=_.s,!x||!E)return new W(NaN);if(x!=E)return _.s=-E,U.plus(_);var P=U.e/l,j=_.e/l,N=U.c,z=_.c;if(!P||!j){if(!N||!z)return N?(_.s=-E,_):new W(z?U:NaN);if(!N[0]||!z[0])return z[0]?(_.s=-E,_):new W(N[0]?U:re==3?-0:0)}if(P=S(P),j=S(j),N=N.slice(),x=P-j){for((I=x<0)?(x=-x,O=N):(j=P,O=z),O.reverse(),E=x;E--;O.push(0));O.reverse()}else for(B=(I=(x=N.length)<(E=z.length))?x:E,x=E=0;E<B;E++)if(N[E]!=z[E]){I=N[E]<z[E];break}if(I&&(O=N,N=z,z=O,_.s=-_.s),E=(B=z.length)-(k=N.length),E>0)for(;E--;N[k++]=0);for(E=c-1;B>x;){if(N[--B]<z[B]){for(k=B;k&&!N[--k];N[k]=E);--N[k],N[B]+=c}N[B]-=z[B]}for(;N[0]==0;N.splice(0,1),--j);return N[0]?Ot(_,N,j):(_.s=re==3?-1:1,_.c=[_.e=0],_)},M.modulo=M.mod=function(_,E){var k,B,O=this;return _=new W(_,E),!O.c||!_.s||_.c&&!_.c[0]?new W(NaN):!_.c||O.c&&!O.c[0]?new W(O):(G==9?(B=_.s,_.s=1,k=F(O,_,0,3),_.s=B,k.s*=B):k=F(O,_,0,G),_=O.minus(k.times(_)),!_.c[0]&&G==1&&(_.s=O.s),_)},M.multipliedBy=M.times=function(_,E){var k,B,O,I,U,x,P,j,N,z,Z,ee,Ee,Fe,Ne,we=this,Se=we.c,Me=(_=new W(_,E)).c;if(!Se||!Me||!Se[0]||!Me[0])return!we.s||!_.s||Se&&!Se[0]&&!Me||Me&&!Me[0]&&!Se?_.c=_.e=_.s=null:(_.s*=we.s,!Se||!Me?_.c=_.e=null:(_.c=[0],_.e=0)),_;for(B=S(we.e/l)+S(_.e/l),_.s*=we.s,P=Se.length,z=Me.length,P<z&&(Ee=Se,Se=Me,Me=Ee,O=P,P=z,z=O),O=P+z,Ee=[];O--;Ee.push(0));for(Fe=c,Ne=p,O=z;--O>=0;){for(k=0,Z=Me[O]%Ne,ee=Me[O]/Ne|0,U=P,I=O+U;I>O;)j=Se[--U]%Ne,N=Se[U]/Ne|0,x=ee*j+N*Z,j=Z*j+x%Ne*Ne+Ee[I]+k,k=(j/Fe|0)+(x/Ne|0)+ee*N,Ee[I--]=j%Fe;Ee[I]=k}return k?++B:Ee.splice(0,1),Ot(_,Ee,B)},M.negated=function(){var _=new W(this);return _.s=-_.s||null,_},M.plus=function(_,E){var k,B=this,O=B.s;if(_=new W(_,E),E=_.s,!O||!E)return new W(NaN);if(O!=E)return _.s=-E,B.minus(_);var I=B.e/l,U=_.e/l,x=B.c,P=_.c;if(!I||!U){if(!x||!P)return new W(O/0);if(!x[0]||!P[0])return P[0]?_:new W(x[0]?B:O*0)}if(I=S(I),U=S(U),x=x.slice(),O=I-U){for(O>0?(U=I,k=P):(O=-O,k=x),k.reverse();O--;k.push(0));k.reverse()}for(O=x.length,E=P.length,O-E<0&&(k=P,P=x,x=k,E=O),O=0;E;)O=(x[--E]=x[E]+P[E]+O)/c|0,x[E]=c===x[E]?0:x[E]%c;return O&&(x=[O].concat(x),++U),Ot(_,x,U)},M.precision=M.sd=function(_,E){var k,B,O,I=this;if(_!=null&&_!==!!_)return m(_,1,w),E==null?E=re:m(E,0,8),Re(new W(I),_,E);if(!(k=I.c))return null;if(O=k.length-1,B=O*l+1,O=k[O]){for(;O%10==0;O/=10,B--);for(O=k[0];O>=10;O/=10,B++);}return _&&I.e+1>B&&(B=I.e+1),B},M.shiftedBy=function(_){return m(_,-h,h),this.times("1e"+_)},M.squareRoot=M.sqrt=function(){var _,E,k,B,O,I=this,U=I.c,x=I.s,P=I.e,j=ue+4,N=new W("0.5");if(x!==1||!U||!U[0])return new W(!x||x<0&&(!U||U[0])?NaN:U?I:1/0);if(x=Math.sqrt(+Be(I)),x==0||x==1/0?(E=y(U),(E.length+P)%2==0&&(E+="0"),x=Math.sqrt(+E),P=S((P+1)/2)-(P<0||P%2),x==1/0?E="5e"+P:(E=x.toExponential(),E=E.slice(0,E.indexOf("e")+1)+P),k=new W(E)):k=new W(x+""),k.c[0]){for(P=k.e,x=P+j,x<3&&(x=0);;)if(O=k,k=N.times(O.plus(F(I,O,j,1))),y(O.c).slice(0,x)===(E=y(k.c)).slice(0,x))if(k.e<P&&--x,E=E.slice(x-3,x+1),E=="9999"||!B&&E=="4999"){if(!B&&(Re(O,O.e+ue+2,0),O.times(O).eq(I))){k=O;break}j+=4,x+=4,B=1}else{(!+E||!+E.slice(1)&&E.charAt(0)=="5")&&(Re(k,k.e+ue+2,1),_=!k.times(k).eq(I));break}}return Re(k,k.e+ue+1,re,_)},M.toExponential=function(_,E){return _!=null&&(m(_,0,w),_++),le(this,_,E,1)},M.toFixed=function(_,E){return _!=null&&(m(_,0,w),_=_+this.e+1),le(this,_,E)},M.toFormat=function(_,E,k){var B,O=this;if(k==null)_!=null&&E&&typeof E=="object"?(k=E,E=null):_&&typeof _=="object"?(k=_,_=E=null):k=ae;else if(typeof k!="object")throw Error(i+"Argument not an object: "+k);if(B=O.toFixed(_,E),O.c){var I,U=B.split("."),x=+k.groupSize,P=+k.secondaryGroupSize,j=k.groupSeparator||"",N=U[0],z=U[1],Z=O.s<0,ee=Z?N.slice(1):N,Ee=ee.length;if(P&&(I=x,x=P,P=I,Ee-=I),x>0&&Ee>0){for(I=Ee%x||x,N=ee.substr(0,I);I<Ee;I+=x)N+=j+ee.substr(I,x);P>0&&(N+=j+ee.slice(I)),Z&&(N="-"+N)}B=z?N+(k.decimalSeparator||"")+((P=+k.fractionGroupSize)?z.replace(new RegExp("\\d{"+P+"}\\B","g"),"$&"+(k.fractionGroupSeparator||"")):z):N}return(k.prefix||"")+B+(k.suffix||"")},M.toFraction=function(_){var E,k,B,O,I,U,x,P,j,N,z,Z,ee=this,Ee=ee.c;if(_!=null&&(x=new W(_),!x.isInteger()&&(x.c||x.s!==1)||x.lt(Q)))throw Error(i+"Argument "+(x.isInteger()?"out of range: ":"not an integer: ")+Be(x));if(!Ee)return new W(ee);for(E=new W(Q),j=k=new W(Q),B=P=new W(Q),Z=y(Ee),I=E.e=Z.length-ee.e-1,E.c[0]=d[(U=I%l)<0?l+U:U],_=!_||x.comparedTo(E)>0?I>0?E:j:x,U=oe,oe=1/0,x=new W(Z),P.c[0]=0;N=F(x,E,0,1),O=k.plus(N.times(B)),O.comparedTo(_)!=1;)k=B,B=O,j=P.plus(N.times(O=j)),P=O,E=x.minus(N.times(O=E)),x=O;return O=F(_.minus(k),B,0,1),P=P.plus(O.times(j)),k=k.plus(O.times(B)),P.s=j.s=ee.s,I=I*2,z=F(j,B,I,re).minus(ee).abs().comparedTo(F(P,k,I,re).minus(ee).abs())<1?[j,B]:[P,k],oe=U,z},M.toNumber=function(){return+Be(this)},M.toPrecision=function(_,E){return _!=null&&m(_,1,w),le(this,_,E,2)},M.toString=function(_){var E,k=this,B=k.s,O=k.e;return O===null?B?(E="Infinity",B<0&&(E="-"+E)):E="NaN":(_==null?E=O<=de||O>=pe?b(y(k.c),O):A(y(k.c),O,"0"):_===10&&Te?(k=Re(new W(k),ue+O+1,re),E=A(y(k.c),k.e,"0")):(m(_,2,qe.length,"Base"),E=$(A(y(k.c),O,"0"),10,_,B,!0)),B<0&&k.c[0]&&(E="-"+E)),E},M.valueOf=M.toJSON=function(){return Be(this)},M._isBigNumber=!0,R!=null&&W.set(R),W}function S(R){var F=R|0;return R>0||R===F?F:F-1}function y(R){for(var F,$,J=1,M=R.length,Q=R[0]+"";J<M;){for(F=R[J++]+"",$=l-F.length;$--;F="0"+F);Q+=F}for(M=Q.length;Q.charCodeAt(--M)===48;);return Q.slice(0,M+1||1)}function g(R,F){var $,J,M=R.c,Q=F.c,ue=R.s,re=F.s,de=R.e,pe=F.e;if(!ue||!re)return null;if($=M&&!M[0],J=Q&&!Q[0],$||J)return $?J?0:-re:ue;if(ue!=re)return ue;if($=ue<0,J=de==pe,!M||!Q)return J?0:!M^$?1:-1;if(!J)return de>pe^$?1:-1;for(re=(de=M.length)<(pe=Q.length)?de:pe,ue=0;ue<re;ue++)if(M[ue]!=Q[ue])return M[ue]>Q[ue]^$?1:-1;return de==pe?0:de>pe^$?1:-1}function m(R,F,$,J){if(R<F||R>$||R!==s(R))throw Error(i+(J||"Argument")+(typeof R=="number"?R<F||R>$?" out of range: ":" not an integer: ":" not a primitive number: ")+String(R))}function v(R){var F=R.c.length-1;return S(R.e/l)==F&&R.c[F]%2!=0}function b(R,F){return(R.length>1?R.charAt(0)+"."+R.slice(1):R)+(F<0?"e":"e+")+F}function A(R,F,$){var J,M;if(F<0){for(M=$+".";++F;M+=$);R=M+R}else if(J=R.length,++F>J){for(M=$,F-=J;--F;M+=$);R+=M}else F<J&&(R=R.slice(0,F)+"."+R.slice(F));return R}e=T(),e.default=e.BigNumber=e,typeof define=="function"&&define.amd?define(function(){return e}):typeof Ci<"u"&&Ci.exports?Ci.exports=e:(t||(t=typeof self<"u"&&self?self:window),t.BigNumber=e)})(Zp)});var nm=V((T1,rm)=>{var em=cc(),tm=rm.exports;(function(){"use strict";function t(h){return h<10?"0"+h:h}var e=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,r=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,n,s,i={"\b":"\\b"," ":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"},u;function c(h){return r.lastIndex=0,r.test(h)?'"'+h.replace(r,function(d){var p=i[d];return typeof p=="string"?p:"\\u"+("0000"+d.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+h+'"'}function l(h,d){var p,w,T,S,y=n,g,m=d[h],v=m!=null&&(m instanceof em||em.isBigNumber(m));switch(m&&typeof m=="object"&&typeof m.toJSON=="function"&&(m=m.toJSON(h)),typeof u=="function"&&(m=u.call(d,h,m)),typeof m){case"string":return v?m:c(m);case"number":return isFinite(m)?String(m):"null";case"boolean":case"null":case"bigint":return String(m);case"object":if(!m)return"null";if(n+=s,g=[],Object.prototype.toString.apply(m)==="[object Array]"){for(S=m.length,p=0;p<S;p+=1)g[p]=l(p,m)||"null";return T=g.length===0?"[]":n?`[
|
|
44
44
|
`+n+g.join(`,
|
|
45
45
|
`+n)+`
|
|
46
|
-
`+y+"]":"["+g.join(",")+"]",n=y,
|
|
46
|
+
`+y+"]":"["+g.join(",")+"]",n=y,T}if(u&&typeof u=="object")for(S=u.length,p=0;p<S;p+=1)typeof u[p]=="string"&&(w=u[p],T=l(w,m),T&&g.push(c(w)+(n?": ":":")+T));else Object.keys(m).forEach(function(b){var A=l(b,m);A&&g.push(c(b)+(n?": ":":")+A)});return T=g.length===0?"{}":n?`{
|
|
47
47
|
`+n+g.join(`,
|
|
48
48
|
`+n)+`
|
|
49
|
-
`+y+"}":"{"+g.join(",")+"}",n=y,
|
|
50
|
-
`,r:"\r",t:" "},i,u=function(y){throw{name:"SyntaxError",message:y,at:r,text:i}},c=function(y){return y&&y!==n&&u("Expected '"+y+"' instead of '"+n+"'"),n=i.charAt(r),r+=1,n},l=function(){var y,g="";for(n==="-"&&(g="-",c("-"));n>="0"&&n<="9";)g+=n,c();if(n===".")for(g+=".";c()&&n>="0"&&n<="9";)g+=n;if(n==="e"||n==="E")for(g+=n,c(),(n==="-"||n==="+")&&(g+=n,c());n>="0"&&n<="9";)g+=n,c();if(y=+g,!isFinite(y))u("Bad number");else return yi==null&&(yi=sc()),g.length>15?e.storeAsString?g:e.useNativeBigInt?BigInt(g):new yi(g):e.alwaysParseAsBig?e.useNativeBigInt?BigInt(y):new yi(y):y},h=function(){var y,g,m="",k;if(n==='"')for(var b=r;c();){if(n==='"')return r-1>b&&(m+=i.substring(b,r-1)),c(),m;if(n==="\\"){if(r-1>b&&(m+=i.substring(b,r-1)),c(),n==="u"){for(k=0,g=0;g<4&&(y=parseInt(c(),16),!!isFinite(y));g+=1)k=k*16+y;m+=String.fromCharCode(k)}else if(typeof s[n]=="string")m+=s[n];else break;b=r}}u("Bad string")},d=function(){for(;n&&n<=" ";)c()},p=function(){switch(n){case"t":return c("t"),c("r"),c("u"),c("e"),!0;case"f":return c("f"),c("a"),c("l"),c("s"),c("e"),!1;case"n":return c("n"),c("u"),c("l"),c("l"),null}u("Unexpected '"+n+"'")},A,v=function(){var y=[];if(n==="["){if(c("["),d(),n==="]")return c("]"),y;for(;n;){if(y.push(A()),d(),n==="]")return c("]"),y;c(","),d()}}u("Bad array")},S=function(){var y,g=Object.create(null);if(n==="{"){if(c("{"),d(),n==="}")return c("}"),g;for(;n;){if(y=h(),d(),c(":"),e.strict===!0&&Object.hasOwnProperty.call(g,y)&&u('Duplicate key "'+y+'"'),HC.test(y)===!0?e.protoAction==="error"?u("Object contains forbidden prototype property"):e.protoAction==="ignore"?A():g[y]=A():WC.test(y)===!0?e.constructorAction==="error"?u("Object contains forbidden constructor property"):e.constructorAction==="ignore"?A():g[y]=A():g[y]=A(),d(),n==="}")return c("}"),g;c(","),d()}}u("Bad object")};return A=function(){switch(d(),n){case"{":return S();case"[":return v();case'"':return h();case"-":return l();default:return n>="0"&&n<="9"?l():p()}},function(y,g){var m;return i=y+"",r=0,n=" ",m=A(),d(),n&&u("Syntax error"),typeof g=="function"?(function k(b,E){var R,F,$=b[E];return $&&typeof $=="object"&&Object.keys($).forEach(function(J){F=k($,J),F!==void 0?$[J]=F:delete $[J]}),g.call(b,E,$)})({"":m},""):m}};zp.exports=GC});var Jp=V((QR,_i)=>{var Wp=$p().stringify,Gp=Hp();_i.exports=function(t){return{parse:Gp(t),stringify:Wp}};_i.exports.parse=Gp();_i.exports.stringify=Wp});var oc=V(Lt=>{"use strict";Object.defineProperty(Lt,"__esModule",{value:!0});Lt.GCE_LINUX_BIOS_PATHS=void 0;Lt.isGoogleCloudServerless=Yp;Lt.isGoogleComputeEngineLinux=Xp;Lt.isGoogleComputeEngineMACAddress=Qp;Lt.isGoogleComputeEngine=Zp;Lt.detectGCPResidency=VC;var Vp=Q("fs"),Kp=Q("os");Lt.GCE_LINUX_BIOS_PATHS={BIOS_DATE:"/sys/class/dmi/id/bios_date",BIOS_VENDOR:"/sys/class/dmi/id/bios_vendor"};var JC=/^42:01/;function Yp(){return!!(process.env.CLOUD_RUN_JOB||process.env.FUNCTION_NAME||process.env.K_SERVICE)}function Xp(){if((0,Kp.platform)()!=="linux")return!1;try{(0,Vp.statSync)(Lt.GCE_LINUX_BIOS_PATHS.BIOS_DATE);let t=(0,Vp.readFileSync)(Lt.GCE_LINUX_BIOS_PATHS.BIOS_VENDOR,"utf8");return/Google/.test(t)}catch{return!1}}function Qp(){let t=(0,Kp.networkInterfaces)();for(let e of Object.values(t))if(e){for(let{mac:r}of e)if(JC.test(r))return!0}return!1}function Zp(){return Xp()||Qp()}function VC(){return Yp()||Zp()}});var em=V(bi=>{"use strict";Object.defineProperty(bi,"__esModule",{value:!0});bi.Colours=void 0;var Xe=class t{static isEnabled(e){return e&&e.isTTY&&(typeof e.getColorDepth=="function"?e.getColorDepth()>2:!0)}static refresh(){t.enabled=t.isEnabled(process==null?void 0:process.stderr),this.enabled?(t.reset="\x1B[0m",t.bright="\x1B[1m",t.dim="\x1B[2m",t.red="\x1B[31m",t.green="\x1B[32m",t.yellow="\x1B[33m",t.blue="\x1B[34m",t.magenta="\x1B[35m",t.cyan="\x1B[36m",t.white="\x1B[37m",t.grey="\x1B[90m"):(t.reset="",t.bright="",t.dim="",t.red="",t.green="",t.yellow="",t.blue="",t.magenta="",t.cyan="",t.white="",t.grey="")}};bi.Colours=Xe;Xe.enabled=!1;Xe.reset="";Xe.bright="";Xe.dim="";Xe.red="";Xe.green="";Xe.yellow="";Xe.blue="";Xe.magenta="";Xe.cyan="";Xe.white="";Xe.grey="";Xe.refresh()});var sm=V(Te=>{"use strict";var KC=Te&&Te.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,s)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),YC=Te&&Te.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),tm=Te&&Te.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(r){var n=[];for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&(n[n.length]=s);return n},t(e)};return function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var n=t(e),s=0;s<n.length;s++)n[s]!=="default"&&KC(r,e,n[s]);return YC(r,e),r}})();Object.defineProperty(Te,"__esModule",{value:!0});Te.env=Te.DebugLogBackendBase=Te.placeholder=Te.AdhocDebugLogger=Te.LogSeverity=void 0;Te.getNodeBackend=ac;Te.getDebugBackend=QC;Te.getStructuredBackend=ZC;Te.setBackend=ew;Te.log=nm;var XC=Q("events"),Rs=tm(Q("process")),rm=tm(Q("util")),dt=em(),Mt;(function(t){t.DEFAULT="DEFAULT",t.DEBUG="DEBUG",t.INFO="INFO",t.WARNING="WARNING",t.ERROR="ERROR"})(Mt||(Te.LogSeverity=Mt={}));var Os=class extends XC.EventEmitter{constructor(e,r){super(),this.namespace=e,this.upstream=r,this.func=Object.assign(this.invoke.bind(this),{instance:this,on:(n,s)=>this.on(n,s)}),this.func.debug=(...n)=>this.invokeSeverity(Mt.DEBUG,...n),this.func.info=(...n)=>this.invokeSeverity(Mt.INFO,...n),this.func.warn=(...n)=>this.invokeSeverity(Mt.WARNING,...n),this.func.error=(...n)=>this.invokeSeverity(Mt.ERROR,...n),this.func.sublog=n=>nm(n,this.func)}invoke(e,...r){if(this.upstream)try{this.upstream(e,...r)}catch{}try{this.emit("log",e,r)}catch{}}invokeSeverity(e,...r){this.invoke({severity:e},...r)}};Te.AdhocDebugLogger=Os;Te.placeholder=new Os("",()=>{}).func;var qn=class{constructor(){var e;this.cached=new Map,this.filters=[],this.filtersSet=!1;let r=(e=Rs.env[Te.env.nodeEnables])!==null&&e!==void 0?e:"*";r==="all"&&(r="*"),this.filters=r.split(",")}log(e,r,...n){try{this.filtersSet||(this.setFilters(),this.filtersSet=!0);let s=this.cached.get(e);s||(s=this.makeLogger(e),this.cached.set(e,s)),s(r,...n)}catch(s){console.error(s)}}};Te.DebugLogBackendBase=qn;var ic=class extends qn{constructor(){super(...arguments),this.enabledRegexp=/.*/g}isEnabled(e){return this.enabledRegexp.test(e)}makeLogger(e){return this.enabledRegexp.test(e)?(r,...n)=>{var s;let i=`${dt.Colours.green}${e}${dt.Colours.reset}`,u=`${dt.Colours.yellow}${Rs.pid}${dt.Colours.reset}`,c;switch(r.severity){case Mt.ERROR:c=`${dt.Colours.red}${r.severity}${dt.Colours.reset}`;break;case Mt.INFO:c=`${dt.Colours.magenta}${r.severity}${dt.Colours.reset}`;break;case Mt.WARNING:c=`${dt.Colours.yellow}${r.severity}${dt.Colours.reset}`;break;default:c=(s=r.severity)!==null&&s!==void 0?s:Mt.DEFAULT;break}let l=rm.formatWithOptions({colors:dt.Colours.enabled},...n),h=Object.assign({},r);delete h.severity;let d=Object.getOwnPropertyNames(h).length?JSON.stringify(h):"",p=d?`${dt.Colours.grey}${d}${dt.Colours.reset}`:"";console.error("%s [%s|%s] %s%s",u,i,c,l,d?` ${p}`:"")}:()=>{}}setFilters(){let r=this.filters.join(",").replace(/[|\\{}()[\]^$+?.]/g,"\\$&").replace(/\*/g,".*").replace(/,/g,"$|^");this.enabledRegexp=new RegExp(`^${r}$`,"i")}};function ac(){return new ic}var uc=class extends qn{constructor(e){super(),this.debugPkg=e}makeLogger(e){let r=this.debugPkg(e);return(n,...s)=>{r(s[0],...s.slice(1))}}setFilters(){var e;let r=(e=Rs.env.NODE_DEBUG)!==null&&e!==void 0?e:"";Rs.env.NODE_DEBUG=`${r}${r?",":""}${this.filters.join(",")}`}};function QC(t){return new uc(t)}var cc=class extends qn{constructor(e){var r;super(),this.upstream=(r=e)!==null&&r!==void 0?r:void 0}makeLogger(e){var r;let n=(r=this.upstream)===null||r===void 0?void 0:r.makeLogger(e);return(s,...i)=>{var u;let c=(u=s.severity)!==null&&u!==void 0?u:Mt.INFO,l=Object.assign({severity:c,message:rm.format(...i)},s),h=JSON.stringify(l);n?n(s,h):console.log("%s",h)}}setFilters(){var e;(e=this.upstream)===null||e===void 0||e.setFilters()}};function ZC(t){return new cc(t)}Te.env={nodeEnables:"GOOGLE_SDK_NODE_LOGGING"};var lc=new Map,ht;function ew(t){ht=t,lc.clear()}function nm(t,e){if(!ht&&!Rs.env[Te.env.nodeEnables]||!t)return Te.placeholder;e&&(t=`${e.instance.namespace}:${t}`);let r=lc.get(t);if(r)return r.func;if(ht===null)return Te.placeholder;ht===void 0&&(ht=ac());let n=(()=>{let s;return new Os(t,(u,...c)=>{if(s!==ht){if(ht===null)return;ht===void 0&&(ht=ac()),s=ht}ht?.log(t,u,...c)})})();return lc.set(t,n),n.func}});var fc=V(un=>{"use strict";var tw=un&&un.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,s)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),rw=un&&un.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&tw(e,t,r)};Object.defineProperty(un,"__esModule",{value:!0});rw(sm(),un)});var Fs=V(ie=>{"use strict";var im=ie&&ie.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,s)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),nw=ie&&ie.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),sw=ie&&ie.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(r){var n=[];for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&(n[n.length]=s);return n},t(e)};return function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var n=t(e),s=0;s<n.length;s++)n[s]!=="default"&&im(r,e,n[s]);return nw(r,e),r}})(),ow=ie&&ie.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&im(e,t,r)};Object.defineProperty(ie,"__esModule",{value:!0});ie.gcpResidencyCache=ie.METADATA_SERVER_DETECTION=ie.HEADERS=ie.HEADER_VALUE=ie.HEADER_NAME=ie.SECONDARY_HOST_ADDRESS=ie.HOST_ADDRESS=ie.BASE_PATH=void 0;ie.instance=fw;ie.project=dw;ie.universe=hw;ie.bulk=pw;ie.isAvailable=gw;ie.resetIsAvailableCache=yw;ie.getGCPResidency=pc;ie.setGCPResidency=am;ie.requestTimeout=um;var dc=Ve(),iw=Jp(),aw=oc(),uw=sw(fc());ie.BASE_PATH="/computeMetadata/v1";ie.HOST_ADDRESS="http://169.254.169.254";ie.SECONDARY_HOST_ADDRESS="http://metadata.google.internal.";ie.HEADER_NAME="Metadata-Flavor";ie.HEADER_VALUE="Google";ie.HEADERS=Object.freeze({[ie.HEADER_NAME]:ie.HEADER_VALUE});var om=uw.log("gcp-metadata");ie.METADATA_SERVER_DETECTION=Object.freeze({"assume-present":"don't try to ping the metadata server, but assume it's present",none:"don't try to ping the metadata server, but don't try to use it either","bios-only":"treat the result of a BIOS probe as canonical (don't fall back to pinging)","ping-only":"skip the BIOS probe, and go straight to pinging"});function hc(t){return t||(t=process.env.GCE_METADATA_IP||process.env.GCE_METADATA_HOST||ie.HOST_ADDRESS),/^https?:\/\//.test(t)||(t=`http://${t}`),new URL(ie.BASE_PATH,t).href}function cw(t){Object.keys(t).forEach(e=>{switch(e){case"params":case"property":case"headers":break;case"qs":throw new Error("'qs' is not a valid configuration option. Please use 'params' instead.");default:throw new Error(`'${e}' is not a valid configuration option.`)}})}async function xs(t,e={},r=3,n=!1){let s=new Headers(ie.HEADERS),i="",u={};if(typeof t=="object"){let p=t;new Headers(p.headers).forEach((A,v)=>s.set(v,A)),i=p.metadataKey,u=p.params||u,r=p.noResponseRetries||r,n=p.fastFail||n}else i=t;typeof e=="string"?i+=`/${e}`:(cw(e),e.property&&(i+=`/${e.property}`),new Headers(e.headers).forEach((p,A)=>s.set(A,p)),u=e.params||u);let c=n?lw:dc.request,l={url:`${hc()}/${i}`,headers:s,retryConfig:{noResponseRetries:r},params:u,responseType:"text",timeout:um()};om.info("instance request %j",l);let h=await c(l);om.info("instance metadata is %s",h.data);let d=h.headers.get(ie.HEADER_NAME);if(d!==ie.HEADER_VALUE)throw new RangeError(`Invalid response from metadata service: incorrect ${ie.HEADER_NAME} header. Expected '${ie.HEADER_VALUE}', got ${d?`'${d}'`:"no header"}`);if(typeof h.data=="string")try{return iw.parse(h.data)}catch{}return h.data}async function lw(t){let e={...t,url:t.url?.toString().replace(hc(),hc(ie.SECONDARY_HOST_ADDRESS))},r=(0,dc.request)(t),n=(0,dc.request)(e);return Promise.any([r,n])}function fw(t){return xs("instance",t)}function dw(t){return xs("project",t)}function hw(t){return xs("universe",t)}async function pw(t){let e={};return await Promise.all(t.map(r=>(async()=>{let n=await xs(r),s=r.metadataKey;e[s]=n})())),e}function mw(){return process.env.DETECT_GCP_RETRIES?Number(process.env.DETECT_GCP_RETRIES):0}var Ci;async function gw(){if(process.env.METADATA_SERVER_DETECTION){let t=process.env.METADATA_SERVER_DETECTION.trim().toLocaleLowerCase();if(!(t in ie.METADATA_SERVER_DETECTION))throw new RangeError(`Unknown \`METADATA_SERVER_DETECTION\` env variable. Got \`${t}\`, but it should be \`${Object.keys(ie.METADATA_SERVER_DETECTION).join("`, `")}\`, or unset`);switch(t){case"assume-present":return!0;case"none":return!1;case"bios-only":return pc();case"ping-only":}}try{return Ci===void 0&&(Ci=xs("instance",void 0,mw(),!(process.env.GCE_METADATA_IP||process.env.GCE_METADATA_HOST))),await Ci,!0}catch(t){let e=t;if(process.env.DEBUG_AUTH&&console.info(e),e.type==="request-timeout"||e.response&&e.response.status===404)return!1;if(!(e.response&&e.response.status===404)&&(!e.code||!["EHOSTDOWN","EHOSTUNREACH","ENETUNREACH","ENOENT","ENOTFOUND","ECONNREFUSED"].includes(e.code.toString()))){let r="UNKNOWN";e.code&&(r=e.code.toString()),process.emitWarning(`received unexpected error = ${e.message} code = ${r}`,"MetadataLookupWarning")}return!1}}function yw(){Ci=void 0}ie.gcpResidencyCache=null;function pc(){return ie.gcpResidencyCache===null&&am(),ie.gcpResidencyCache}function am(t=null){ie.gcpResidencyCache=t!==null?t:(0,aw.detectGCPResidency)()}function um(){return pc()?0:3e3}ow(oc(),ie)});var fm=V(wi=>{"use strict";wi.byteLength=bw;wi.toByteArray=ww;wi.fromByteArray=Sw;var Yt=[],kt=[],_w=typeof Uint8Array<"u"?Uint8Array:Array,mc="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(cn=0,cm=mc.length;cn<cm;++cn)Yt[cn]=mc[cn],kt[mc.charCodeAt(cn)]=cn;var cn,cm;kt[45]=62;kt[95]=63;function lm(t){var e=t.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var r=t.indexOf("=");r===-1&&(r=e);var n=r===e?0:4-r%4;return[r,n]}function bw(t){var e=lm(t),r=e[0],n=e[1];return(r+n)*3/4-n}function Cw(t,e,r){return(e+r)*3/4-r}function ww(t){var e,r=lm(t),n=r[0],s=r[1],i=new _w(Cw(t,n,s)),u=0,c=s>0?n-4:n,l;for(l=0;l<c;l+=4)e=kt[t.charCodeAt(l)]<<18|kt[t.charCodeAt(l+1)]<<12|kt[t.charCodeAt(l+2)]<<6|kt[t.charCodeAt(l+3)],i[u++]=e>>16&255,i[u++]=e>>8&255,i[u++]=e&255;return s===2&&(e=kt[t.charCodeAt(l)]<<2|kt[t.charCodeAt(l+1)]>>4,i[u++]=e&255),s===1&&(e=kt[t.charCodeAt(l)]<<10|kt[t.charCodeAt(l+1)]<<4|kt[t.charCodeAt(l+2)]>>2,i[u++]=e>>8&255,i[u++]=e&255),i}function Ew(t){return Yt[t>>18&63]+Yt[t>>12&63]+Yt[t>>6&63]+Yt[t&63]}function Aw(t,e,r){for(var n,s=[],i=e;i<r;i+=3)n=(t[i]<<16&16711680)+(t[i+1]<<8&65280)+(t[i+2]&255),s.push(Ew(n));return s.join("")}function Sw(t){for(var e,r=t.length,n=r%3,s=[],i=16383,u=0,c=r-n;u<c;u+=i)s.push(Aw(t,u,u+i>c?c:u+i));return n===1?(e=t[r-1],s.push(Yt[e>>2]+Yt[e<<4&63]+"==")):n===2&&(e=(t[r-2]<<8)+t[r-1],s.push(Yt[e>>10]+Yt[e>>4&63]+Yt[e<<2&63]+"=")),s.join("")}});var yc=V(gc=>{"use strict";Object.defineProperty(gc,"__esModule",{value:!0});gc.fromArrayBufferToHex=kw;function kw(t){return Array.from(new Uint8Array(t)).map(r=>r.toString(16).padStart(2,"0")).join("")}});var dm=V(Ei=>{"use strict";Object.defineProperty(Ei,"__esModule",{value:!0});Ei.BrowserCrypto=void 0;var $n=fm(),Tw=yc(),_c=class t{constructor(){if(typeof window>"u"||window.crypto===void 0||window.crypto.subtle===void 0)throw new Error("SubtleCrypto not found. Make sure it's an https:// website.")}async sha256DigestBase64(e){let r=new TextEncoder().encode(e),n=await window.crypto.subtle.digest("SHA-256",r);return $n.fromByteArray(new Uint8Array(n))}randomBytesBase64(e){let r=new Uint8Array(e);return window.crypto.getRandomValues(r),$n.fromByteArray(r)}static padBase64(e){for(;e.length%4!==0;)e+="=";return e}async verify(e,r,n){let s={name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},i=new TextEncoder().encode(r),u=$n.toByteArray(t.padBase64(n)),c=await window.crypto.subtle.importKey("jwk",e,s,!0,["verify"]);return await window.crypto.subtle.verify(s,c,u,i)}async sign(e,r){let n={name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},s=new TextEncoder().encode(r),i=await window.crypto.subtle.importKey("jwk",e,n,!0,["sign"]),u=await window.crypto.subtle.sign(n,i,s);return $n.fromByteArray(new Uint8Array(u))}decodeBase64StringUtf8(e){let r=$n.toByteArray(t.padBase64(e));return new TextDecoder().decode(r)}encodeBase64StringUtf8(e){let r=new TextEncoder().encode(e);return $n.fromByteArray(r)}async sha256DigestHex(e){let r=new TextEncoder().encode(e),n=await window.crypto.subtle.digest("SHA-256",r);return(0,Tw.fromArrayBufferToHex)(n)}async signWithHmacSha256(e,r){let n=typeof e=="string"?e:String.fromCharCode(...new Uint16Array(e)),s=new TextEncoder,i=await window.crypto.subtle.importKey("raw",s.encode(n),{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return window.crypto.subtle.sign("HMAC",i,s.encode(r))}};Ei.BrowserCrypto=_c});var hm=V(Ai=>{"use strict";Object.defineProperty(Ai,"__esModule",{value:!0});Ai.NodeCrypto=void 0;var zn=Q("crypto"),bc=class{async sha256DigestBase64(e){return zn.createHash("sha256").update(e).digest("base64")}randomBytesBase64(e){return zn.randomBytes(e).toString("base64")}async verify(e,r,n){let s=zn.createVerify("RSA-SHA256");return s.update(r),s.end(),s.verify(e,n,"base64")}async sign(e,r){let n=zn.createSign("RSA-SHA256");return n.update(r),n.end(),n.sign(e,"base64")}decodeBase64StringUtf8(e){return Buffer.from(e,"base64").toString("utf-8")}encodeBase64StringUtf8(e){return Buffer.from(e,"utf-8").toString("base64")}async sha256DigestHex(e){return zn.createHash("sha256").update(e).digest("hex")}async signWithHmacSha256(e,r){let n=typeof e=="string"?e:vw(e);return Dw(zn.createHmac("sha256",n).update(r).digest())}};Ai.NodeCrypto=bc;function Dw(t){return t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength)}function vw(t){return Buffer.from(t)}});var Ps=V(yr=>{"use strict";var Rw=yr&&yr.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,s)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),Ow=yr&&yr.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&Rw(e,t,r)};Object.defineProperty(yr,"__esModule",{value:!0});yr.createCrypto=Pw;yr.hasBrowserCrypto=pm;var xw=dm(),Fw=hm();Ow(yc(),yr);function Pw(){return pm()?new xw.BrowserCrypto:new Fw.NodeCrypto}function pm(){return typeof window<"u"&&typeof window.crypto<"u"&&typeof window.crypto.subtle<"u"}});var Hn=V((Cc,gm)=>{var Si=Q("buffer"),Xt=Si.Buffer;function mm(t,e){for(var r in t)e[r]=t[r]}Xt.from&&Xt.alloc&&Xt.allocUnsafe&&Xt.allocUnsafeSlow?gm.exports=Si:(mm(Si,Cc),Cc.Buffer=ln);function ln(t,e,r){return Xt(t,e,r)}ln.prototype=Object.create(Xt.prototype);mm(Xt,ln);ln.from=function(t,e,r){if(typeof t=="number")throw new TypeError("Argument must not be a number");return Xt(t,e,r)};ln.alloc=function(t,e,r){if(typeof t!="number")throw new TypeError("Argument must be a number");var n=Xt(t);return e!==void 0?typeof r=="string"?n.fill(e,r):n.fill(e):n.fill(0),n};ln.allocUnsafe=function(t){if(typeof t!="number")throw new TypeError("Argument must be a number");return Xt(t)};ln.allocUnsafeSlow=function(t){if(typeof t!="number")throw new TypeError("Argument must be a number");return Si.SlowBuffer(t)}});var _m=V((c1,ym)=>{"use strict";function wc(t){var e=(t/8|0)+(t%8===0?0:1);return e}var Iw={ES256:wc(256),ES384:wc(384),ES512:wc(521)};function Nw(t){var e=Iw[t];if(e)return e;throw new Error('Unknown algorithm "'+t+'"')}ym.exports=Nw});var Ec=V((l1,Sm)=>{"use strict";var ki=Hn().Buffer,Cm=_m(),Ti=128,wm=0,Bw=32,jw=16,Lw=2,Em=jw|Bw|wm<<6,Di=Lw|wm<<6;function Mw(t){return t.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function Am(t){if(ki.isBuffer(t))return t;if(typeof t=="string")return ki.from(t,"base64");throw new TypeError("ECDSA signature must be a Base64 string or a Buffer")}function Uw(t,e){t=Am(t);var r=Cm(e),n=r+1,s=t.length,i=0;if(t[i++]!==Em)throw new Error('Could not find expected "seq"');var u=t[i++];if(u===(Ti|1)&&(u=t[i++]),s-i<u)throw new Error('"seq" specified length of "'+u+'", only "'+(s-i)+'" remaining');if(t[i++]!==Di)throw new Error('Could not find expected "int" for "r"');var c=t[i++];if(s-i-2<c)throw new Error('"r" specified length of "'+c+'", only "'+(s-i-2)+'" available');if(n<c)throw new Error('"r" specified length of "'+c+'", max of "'+n+'" is acceptable');var l=i;if(i+=c,t[i++]!==Di)throw new Error('Could not find expected "int" for "s"');var h=t[i++];if(s-i!==h)throw new Error('"s" specified length of "'+h+'", expected "'+(s-i)+'"');if(n<h)throw new Error('"s" specified length of "'+h+'", max of "'+n+'" is acceptable');var d=i;if(i+=h,i!==s)throw new Error('Expected to consume entire buffer, but "'+(s-i)+'" bytes remain');var p=r-c,A=r-h,v=ki.allocUnsafe(p+c+A+h);for(i=0;i<p;++i)v[i]=0;t.copy(v,i,l+Math.max(-p,0),l+c),i=r;for(var S=i;i<S+A;++i)v[i]=0;return t.copy(v,i,d+Math.max(-A,0),d+h),v=v.toString("base64"),v=Mw(v),v}function bm(t,e,r){for(var n=0;e+n<r&&t[e+n]===0;)++n;var s=t[e+n]>=Ti;return s&&--n,n}function qw(t,e){t=Am(t);var r=Cm(e),n=t.length;if(n!==r*2)throw new TypeError('"'+e+'" signatures must be "'+r*2+'" bytes, saw "'+n+'"');var s=bm(t,0,r),i=bm(t,r,t.length),u=r-s,c=r-i,l=2+u+1+1+c,h=l<Ti,d=ki.allocUnsafe((h?2:3)+l),p=0;return d[p++]=Em,h?d[p++]=l:(d[p++]=Ti|1,d[p++]=l&255),d[p++]=Di,d[p++]=u,s<0?(d[p++]=0,p+=t.copy(d,p,0,r)):p+=t.copy(d,p,s,r),d[p++]=Di,d[p++]=c,i<0?(d[p++]=0,t.copy(d,p,r)):t.copy(d,p,r+i),d}Sm.exports={derToJose:Uw,joseToDer:qw}});var Ut=V(_r=>{"use strict";Object.defineProperty(_r,"__esModule",{value:!0});_r.LRUCache=void 0;_r.snakeToCamel=Tm;_r.originalOrCamelOptions=Ww;_r.removeUndefinedValuesInObject=Gw;_r.isValidFile=Jw;_r.getWellKnownCertificateConfigFileLocation=Vw;var $w=Q("fs"),zw=Q("os"),Ac=Q("path"),Hw="certificate_config.json",km="gcloud";function Tm(t){return t.replace(/([_][^_])/g,e=>e.slice(1).toUpperCase())}function Ww(t){function e(r){let n=t||{};return n[r]??n[Tm(r)]}return{get:e}}var Sc=class{capacity;#e=new Map;maxAge;constructor(e){this.capacity=e.capacity,this.maxAge=e.maxAge}#t(e,r){this.#e.delete(e),this.#e.set(e,{value:r,lastAccessed:Date.now()})}set(e,r){this.#t(e,r),this.#r()}get(e){let r=this.#e.get(e);if(r)return this.#t(e,r.value),this.#r(),r.value}#r(){let e=this.maxAge?Date.now()-this.maxAge:0,r=this.#e.entries().next();for(;!r.done&&(this.#e.size>this.capacity||r.value[1].lastAccessed<e);)this.#e.delete(r.value[0]),r=this.#e.entries().next()}};_r.LRUCache=Sc;function Gw(t){return Object.entries(t).forEach(([e,r])=>{(r===void 0||r==="undefined")&&delete t[e]}),t}async function Jw(t){try{return(await $w.promises.lstat(t)).isFile()}catch{return!1}}function Vw(){let t=process.env.CLOUDSDK_CONFIG||(Kw()?Ac.join(process.env.APPDATA||"",km):Ac.join(process.env.HOME||"",".config",km));return Ac.join(t,Hw)}function Kw(){return zw.platform().startsWith("win")}});var Dm=V((d1,Yw)=>{Yw.exports={name:"google-auth-library",version:"10.4.0",author:"Google Inc.",description:"Google APIs Authentication Client Library for Node.js",engines:{node:">=18"},main:"./build/src/index.js",types:"./build/src/index.d.ts",repository:"googleapis/google-auth-library-nodejs.git",keywords:["google","api","google apis","client","client library"],dependencies:{"base64-js":"^1.3.0","ecdsa-sig-formatter":"^1.0.11",gaxios:"^7.0.0","gcp-metadata":"^7.0.0","google-logging-utils":"^1.0.0",gtoken:"^8.0.0",jws:"^4.0.0"},devDependencies:{"@types/base64-js":"^1.2.5","@types/jws":"^3.1.0","@types/mocha":"^10.0.10","@types/mv":"^2.1.0","@types/ncp":"^2.0.1","@types/node":"^22.0.0","@types/sinon":"^17.0.0","assert-rejects":"^1.0.0",c8:"^10.0.0",codecov:"^3.0.2",gts:"^6.0.0","is-docker":"^3.0.0",jsdoc:"^4.0.0","jsdoc-fresh":"^4.0.0","jsdoc-region-tag":"^3.0.0",karma:"^6.0.0","karma-chrome-launcher":"^3.0.0","karma-coverage":"^2.0.0","karma-firefox-launcher":"^2.0.0","karma-mocha":"^2.0.0","karma-sourcemap-loader":"^0.4.0","karma-webpack":"^5.0.1",keypair:"^1.0.4",linkinator:"^6.1.2",mocha:"^11.1.0",mv:"^2.1.1",ncp:"^2.0.0",nock:"^14.0.5","null-loader":"^4.0.0",puppeteer:"^24.0.0",sinon:"^21.0.0","ts-loader":"^8.0.0",typescript:"5.8.2",webpack:"^5.21.2","webpack-cli":"^4.0.0"},files:["build/src","!build/src/**/*.map"],scripts:{test:"c8 mocha build/test",clean:"gts clean",prepare:"npm run compile",lint:"gts check --no-inline-config",compile:"tsc -p .",fix:"gts fix",pretest:"npm run compile -- --sourceMap",docs:"jsdoc -c .jsdoc.js","samples-setup":"cd samples/ && npm link ../ && npm run setup && cd ../","samples-test":"cd samples/ && npm link ../ && npm test && cd ../","system-test":"mocha build/system-test --timeout 60000","presystem-test":"npm run compile -- --sourceMap",webpack:"webpack","browser-test":"karma start","docs-test":"linkinator docs","predocs-test":"npm run docs",prelint:"cd samples; npm link ../; npm install"},license:"Apache-2.0"}});var kc=V(qr=>{"use strict";Object.defineProperty(qr,"__esModule",{value:!0});qr.USER_AGENT=qr.PRODUCT_NAME=qr.pkg=void 0;var vm=Dm();qr.pkg=vm;var Rm="google-api-nodejs-client";qr.PRODUCT_NAME=Rm;var Xw=`${Rm}/${vm.version}`;qr.USER_AGENT=Xw});var pt=V(qt=>{"use strict";Object.defineProperty(qt,"__esModule",{value:!0});qt.AuthClient=qt.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS=qt.DEFAULT_UNIVERSE=void 0;var Qw=Q("events"),Tc=Ve(),Zw=Ut(),eE=fc(),Dc=kc();qt.DEFAULT_UNIVERSE="googleapis.com";qt.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS=300*1e3;var vc=class t extends Qw.EventEmitter{apiKey;projectId;quotaProjectId;transporter;credentials={};eagerRefreshThresholdMillis=qt.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS;forceRefreshOnFailure=!1;universeDomain=qt.DEFAULT_UNIVERSE;static RequestMethodNameSymbol=Symbol("request method name");static RequestLogIdSymbol=Symbol("request log id");constructor(e={}){super();let r=(0,Zw.originalOrCamelOptions)(e);this.apiKey=e.apiKey,this.projectId=r.get("project_id")??null,this.quotaProjectId=r.get("quota_project_id"),this.credentials=r.get("credentials")??{},this.universeDomain=r.get("universe_domain")??qt.DEFAULT_UNIVERSE,this.transporter=e.transporter??new Tc.Gaxios(e.transporterOptions),r.get("useAuthRequestParameters")!==!1&&(this.transporter.interceptors.request.add(t.DEFAULT_REQUEST_INTERCEPTOR),this.transporter.interceptors.response.add(t.DEFAULT_RESPONSE_INTERCEPTOR)),e.eagerRefreshThresholdMillis&&(this.eagerRefreshThresholdMillis=e.eagerRefreshThresholdMillis),this.forceRefreshOnFailure=e.forceRefreshOnFailure??!1}fetch(...e){let r=e[0],n=e[1],s,i=new Headers;return typeof r=="string"?s=new URL(r):r instanceof URL?s=r:r&&r.url&&(s=new URL(r.url)),r&&typeof r=="object"&&"headers"in r&&Tc.Gaxios.mergeHeaders(i,r.headers),n&&Tc.Gaxios.mergeHeaders(i,new Headers(n.headers)),typeof r=="object"&&!(r instanceof URL)?this.request({...n,...r,headers:i,url:s}):this.request({...n,headers:i,url:s})}setCredentials(e){this.credentials=e}addSharedMetadataHeaders(e){return!e.has("x-goog-user-project")&&this.quotaProjectId&&e.set("x-goog-user-project",this.quotaProjectId),e}addUserProjectAndAuthHeaders(e,r){let n=r.get("x-goog-user-project"),s=r.get("authorization");return n&&e.set("x-goog-user-project",n),s&&e.set("authorization",s),e}static log=(0,eE.log)("auth");static DEFAULT_REQUEST_INTERCEPTOR={resolved:async e=>{if(!e.headers.has("x-goog-api-client")){let n=process.version.replace(/^v/,"");e.headers.set("x-goog-api-client",`gl-node/${n}`)}let r=e.headers.get("User-Agent");r?r.includes(`${Dc.PRODUCT_NAME}/`)||e.headers.set("User-Agent",`${r} ${Dc.USER_AGENT}`):e.headers.set("User-Agent",Dc.USER_AGENT);try{let n=e,s=n[t.RequestMethodNameSymbol],i=`${Math.floor(Math.random()*1e3)}`;n[t.RequestLogIdSymbol]=i;let u={url:e.url,headers:e.headers};s?t.log.info("%s [%s] request %j",s,i,u):t.log.info("[%s] request %j",i,u)}catch{}return e}};static DEFAULT_RESPONSE_INTERCEPTOR={resolved:async e=>{try{let r=e.config,n=r[t.RequestMethodNameSymbol],s=r[t.RequestLogIdSymbol];n?t.log.info("%s [%s] response %j",n,s,e.data):t.log.info("[%s] response %j",s,e.data)}catch{}return e},rejected:async e=>{try{let r=e.config,n=r[t.RequestMethodNameSymbol],s=r[t.RequestLogIdSymbol];n?t.log.info("%s [%s] error %j",n,s,e.response?.data):t.log.error("[%s] error %j",s,e.response?.data)}catch{}throw e}};static setMethodName(e,r){try{let n=e;n[t.RequestMethodNameSymbol]=r}catch{}}static get RETRY_CONFIG(){return{retry:!0,retryConfig:{httpMethodsToRetry:["GET","PUT","POST","HEAD","OPTIONS","DELETE"]}}}};qt.AuthClient=vc});var Oc=V(vi=>{"use strict";Object.defineProperty(vi,"__esModule",{value:!0});vi.LoginTicket=void 0;var Rc=class{envelope;payload;constructor(e,r){this.envelope=e,this.payload=r}getEnvelope(){return this.envelope}getPayload(){return this.payload}getUserId(){let e=this.getPayload();return e&&e.sub?e.sub:null}getAttributes(){return{envelope:this.getEnvelope(),payload:this.getPayload()}}};vi.LoginTicket=Rc});var fn=V(Qt=>{"use strict";Object.defineProperty(Qt,"__esModule",{value:!0});Qt.OAuth2Client=Qt.ClientAuthentication=Qt.CertificateFormat=Qt.CodeChallengeMethod=void 0;var Om=Ve(),tE=Q("querystring"),rE=Q("stream"),nE=Ec(),xm=Ut(),xc=Ps(),Wn=pt(),sE=Oc(),Fm;(function(t){t.Plain="plain",t.S256="S256"})(Fm||(Qt.CodeChallengeMethod=Fm={}));var br;(function(t){t.PEM="PEM",t.JWK="JWK"})(br||(Qt.CertificateFormat=br={}));var Is;(function(t){t.ClientSecretPost="ClientSecretPost",t.ClientSecretBasic="ClientSecretBasic",t.None="None"})(Is||(Qt.ClientAuthentication=Is={}));var Fc=class t extends Wn.AuthClient{redirectUri;certificateCache={};certificateExpiry=null;certificateCacheFormat=br.PEM;refreshTokenPromises=new Map;endpoints;issuers;clientAuthentication;_clientId;_clientSecret;refreshHandler;constructor(e={},r,n){super(typeof e=="object"?e:{}),typeof e!="object"&&(e={clientId:e,clientSecret:r,redirectUri:n}),this._clientId=e.clientId||e.client_id,this._clientSecret=e.clientSecret||e.client_secret,this.redirectUri=e.redirectUri||e.redirect_uris?.[0],this.endpoints={tokenInfoUrl:"https://oauth2.googleapis.com/tokeninfo",oauth2AuthBaseUrl:"https://accounts.google.com/o/oauth2/v2/auth",oauth2TokenUrl:"https://oauth2.googleapis.com/token",oauth2RevokeUrl:"https://oauth2.googleapis.com/revoke",oauth2FederatedSignonPemCertsUrl:"https://www.googleapis.com/oauth2/v1/certs",oauth2FederatedSignonJwkCertsUrl:"https://www.googleapis.com/oauth2/v3/certs",oauth2IapPublicKeyUrl:"https://www.gstatic.com/iap/verify/public_key",...e.endpoints},this.clientAuthentication=e.clientAuthentication||Is.ClientSecretPost,this.issuers=e.issuers||["accounts.google.com","https://accounts.google.com",this.universeDomain]}static GOOGLE_TOKEN_INFO_URL="https://oauth2.googleapis.com/tokeninfo";static CLOCK_SKEW_SECS_=300;static DEFAULT_MAX_TOKEN_LIFETIME_SECS_=86400;generateAuthUrl(e={}){if(e.code_challenge_method&&!e.code_challenge)throw new Error("If a code_challenge_method is provided, code_challenge must be included.");return e.response_type=e.response_type||"code",e.client_id=e.client_id||this._clientId,e.redirect_uri=e.redirect_uri||this.redirectUri,Array.isArray(e.scope)&&(e.scope=e.scope.join(" ")),this.endpoints.oauth2AuthBaseUrl.toString()+"?"+tE.stringify(e)}generateCodeVerifier(){throw new Error("generateCodeVerifier is removed, please use generateCodeVerifierAsync instead.")}async generateCodeVerifierAsync(){let e=(0,xc.createCrypto)(),n=e.randomBytesBase64(96).replace(/\+/g,"~").replace(/=/g,"_").replace(/\//g,"-"),i=(await e.sha256DigestBase64(n)).split("=")[0].replace(/\+/g,"-").replace(/\//g,"_");return{codeVerifier:n,codeChallenge:i}}getToken(e,r){let n=typeof e=="string"?{code:e}:e;if(r)this.getTokenAsync(n).then(s=>r(null,s.tokens,s.res),s=>r(s,null,s.response));else return this.getTokenAsync(n)}async getTokenAsync(e){let r=this.endpoints.oauth2TokenUrl.toString(),n=new Headers,s={client_id:e.client_id||this._clientId,code_verifier:e.codeVerifier,code:e.code,grant_type:"authorization_code",redirect_uri:e.redirect_uri||this.redirectUri};if(this.clientAuthentication===Is.ClientSecretBasic){let l=Buffer.from(`${this._clientId}:${this._clientSecret}`);n.set("authorization",`Basic ${l.toString("base64")}`)}this.clientAuthentication===Is.ClientSecretPost&&(s.client_secret=this._clientSecret);let i={...t.RETRY_CONFIG,method:"POST",url:r,data:new URLSearchParams((0,xm.removeUndefinedValuesInObject)(s)),headers:n};Wn.AuthClient.setMethodName(i,"getTokenAsync");let u=await this.transporter.request(i),c=u.data;return u.data&&u.data.expires_in&&(c.expiry_date=new Date().getTime()+u.data.expires_in*1e3,delete c.expires_in),this.emit("tokens",c),{tokens:c,res:u}}async refreshToken(e){if(!e)return this.refreshTokenNoCache(e);if(this.refreshTokenPromises.has(e))return this.refreshTokenPromises.get(e);let r=this.refreshTokenNoCache(e).then(n=>(this.refreshTokenPromises.delete(e),n),n=>{throw this.refreshTokenPromises.delete(e),n});return this.refreshTokenPromises.set(e,r),r}async refreshTokenNoCache(e){if(!e)throw new Error("No refresh token is set.");let r=this.endpoints.oauth2TokenUrl.toString(),n={refresh_token:e,client_id:this._clientId,client_secret:this._clientSecret,grant_type:"refresh_token"},s;try{let u={...t.RETRY_CONFIG,method:"POST",url:r,data:new URLSearchParams((0,xm.removeUndefinedValuesInObject)(n))};Wn.AuthClient.setMethodName(u,"refreshTokenNoCache"),s=await this.transporter.request(u)}catch(u){throw u instanceof Om.GaxiosError&&u.message==="invalid_grant"&&u.response?.data&&/ReAuth/i.test(u.response.data.error_description)&&(u.message=JSON.stringify(u.response.data)),u}let i=s.data;return s.data&&s.data.expires_in&&(i.expiry_date=new Date().getTime()+s.data.expires_in*1e3,delete i.expires_in),this.emit("tokens",i),{tokens:i,res:s}}refreshAccessToken(e){if(e)this.refreshAccessTokenAsync().then(r=>e(null,r.credentials,r.res),e);else return this.refreshAccessTokenAsync()}async refreshAccessTokenAsync(){let e=await this.refreshToken(this.credentials.refresh_token),r=e.tokens;return r.refresh_token=this.credentials.refresh_token,this.credentials=r,{credentials:this.credentials,res:e.res}}getAccessToken(e){if(e)this.getAccessTokenAsync().then(r=>e(null,r.token,r.res),e);else return this.getAccessTokenAsync()}async getAccessTokenAsync(){if(!this.credentials.access_token||this.isTokenExpiring()){if(!this.credentials.refresh_token)if(this.refreshHandler){let n=await this.processAndValidateRefreshHandler();if(n?.access_token)return this.setCredentials(n),{token:this.credentials.access_token}}else throw new Error("No refresh token or refresh handler callback is set.");let r=await this.refreshAccessTokenAsync();if(!r.credentials||r.credentials&&!r.credentials.access_token)throw new Error("Could not refresh access token.");return{token:r.credentials.access_token,res:r.res}}else return{token:this.credentials.access_token}}async getRequestHeaders(e){return(await this.getRequestMetadataAsync(e)).headers}async getRequestMetadataAsync(e){let r=this.credentials;if(!r.access_token&&!r.refresh_token&&!this.apiKey&&!this.refreshHandler)throw new Error("No access, refresh token, API key or refresh handler callback is set.");if(r.access_token&&!this.isTokenExpiring()){r.token_type=r.token_type||"Bearer";let c=new Headers({authorization:r.token_type+" "+r.access_token});return{headers:this.addSharedMetadataHeaders(c)}}if(this.refreshHandler){let c=await this.processAndValidateRefreshHandler();if(c?.access_token){this.setCredentials(c);let l=new Headers({authorization:"Bearer "+this.credentials.access_token});return{headers:this.addSharedMetadataHeaders(l)}}}if(this.apiKey)return{headers:new Headers({"X-Goog-Api-Key":this.apiKey})};let n=null,s=null;try{n=await this.refreshToken(r.refresh_token),s=n.tokens}catch(c){let l=c;throw l.response&&(l.response.status===403||l.response.status===404)&&(l.message=`Could not refresh access token: ${l.message}`),l}let i=this.credentials;i.token_type=i.token_type||"Bearer",s.refresh_token=i.refresh_token,this.credentials=s;let u=new Headers({authorization:i.token_type+" "+s.access_token});return{headers:this.addSharedMetadataHeaders(u),res:n.res}}static getRevokeTokenUrl(e){return new t().getRevokeTokenURL(e).toString()}getRevokeTokenURL(e){let r=new URL(this.endpoints.oauth2RevokeUrl);return r.searchParams.append("token",e),r}revokeToken(e,r){let n={...t.RETRY_CONFIG,url:this.getRevokeTokenURL(e).toString(),method:"POST"};if(Wn.AuthClient.setMethodName(n,"revokeToken"),r)this.transporter.request(n).then(s=>r(null,s),r);else return this.transporter.request(n)}revokeCredentials(e){if(e)this.revokeCredentialsAsync().then(r=>e(null,r),e);else return this.revokeCredentialsAsync()}async revokeCredentialsAsync(){let e=this.credentials.access_token;if(this.credentials={},e)return this.revokeToken(e);throw new Error("No access token to revoke.")}request(e,r){if(r)this.requestAsync(e).then(n=>r(null,n),n=>r(n,n.response));else return this.requestAsync(e)}async requestAsync(e,r=!1){try{let n=await this.getRequestMetadataAsync();return e.headers=Om.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,n.headers),this.apiKey&&e.headers.set("X-Goog-Api-Key",this.apiKey),await this.transporter.request(e)}catch(n){let s=n.response;if(s){let i=s.status,u=this.credentials&&this.credentials.access_token&&this.credentials.refresh_token&&(!this.credentials.expiry_date||this.forceRefreshOnFailure),c=this.credentials&&this.credentials.access_token&&!this.credentials.refresh_token&&(!this.credentials.expiry_date||this.forceRefreshOnFailure)&&this.refreshHandler,l=s.config.data instanceof rE.Readable,h=i===401||i===403;if(!r&&h&&!l&&u)return await this.refreshAccessTokenAsync(),this.requestAsync(e,!0);if(!r&&h&&!l&&c){let d=await this.processAndValidateRefreshHandler();return d?.access_token&&this.setCredentials(d),this.requestAsync(e,!0)}}throw n}}verifyIdToken(e,r){if(r&&typeof r!="function")throw new Error("This method accepts an options object as the first parameter, which includes the idToken, audience, and maxExpiry.");if(r)this.verifyIdTokenAsync(e).then(n=>r(null,n),r);else return this.verifyIdTokenAsync(e)}async verifyIdTokenAsync(e){if(!e.idToken)throw new Error("The verifyIdToken method requires an ID Token");let r=await this.getFederatedSignonCertsAsync();return await this.verifySignedJwtWithCertsAsync(e.idToken,r.certs,e.audience,this.issuers,e.maxExpiry)}async getTokenInfo(e){let{data:r}=await this.transporter.request({...t.RETRY_CONFIG,method:"POST",headers:{"content-type":"application/x-www-form-urlencoded;charset=UTF-8",authorization:`Bearer ${e}`},url:this.endpoints.tokenInfoUrl.toString()}),n=Object.assign({expiry_date:new Date().getTime()+r.expires_in*1e3,scopes:r.scope.split(" ")},r);return delete n.expires_in,delete n.scope,n}getFederatedSignonCerts(e){if(e)this.getFederatedSignonCertsAsync().then(r=>e(null,r.certs,r.res),e);else return this.getFederatedSignonCertsAsync()}async getFederatedSignonCertsAsync(){let e=new Date().getTime(),r=(0,xc.hasBrowserCrypto)()?br.JWK:br.PEM;if(this.certificateExpiry&&e<this.certificateExpiry.getTime()&&this.certificateCacheFormat===r)return{certs:this.certificateCache,format:r};let n,s;switch(r){case br.PEM:s=this.endpoints.oauth2FederatedSignonPemCertsUrl.toString();break;case br.JWK:s=this.endpoints.oauth2FederatedSignonJwkCertsUrl.toString();break;default:throw new Error(`Unsupported certificate format ${r}`)}try{let h={...t.RETRY_CONFIG,url:s};Wn.AuthClient.setMethodName(h,"getFederatedSignonCertsAsync"),n=await this.transporter.request(h)}catch(h){throw h instanceof Error&&(h.message=`Failed to retrieve verification certificates: ${h.message}`),h}let i=n?.headers.get("cache-control"),u=-1;if(i){let h=/max-age=(?<maxAge>[0-9]+)/.exec(i)?.groups?.maxAge;h&&(u=Number(h)*1e3)}let c={};switch(r){case br.PEM:c=n.data;break;case br.JWK:for(let h of n.data.keys)c[h.kid]=h;break;default:throw new Error(`Unsupported certificate format ${r}`)}let l=new Date;return this.certificateExpiry=u===-1?null:new Date(l.getTime()+u),this.certificateCache=c,this.certificateCacheFormat=r,{certs:c,format:r,res:n}}getIapPublicKeys(e){if(e)this.getIapPublicKeysAsync().then(r=>e(null,r.pubkeys,r.res),e);else return this.getIapPublicKeysAsync()}async getIapPublicKeysAsync(){let e,r=this.endpoints.oauth2IapPublicKeyUrl.toString();try{let n={...t.RETRY_CONFIG,url:r};Wn.AuthClient.setMethodName(n,"getIapPublicKeysAsync"),e=await this.transporter.request(n)}catch(n){throw n instanceof Error&&(n.message=`Failed to retrieve verification certificates: ${n.message}`),n}return{pubkeys:e.data,res:e}}verifySignedJwtWithCerts(){throw new Error("verifySignedJwtWithCerts is removed, please use verifySignedJwtWithCertsAsync instead.")}async verifySignedJwtWithCertsAsync(e,r,n,s,i){let u=(0,xc.createCrypto)();i||(i=t.DEFAULT_MAX_TOKEN_LIFETIME_SECS_);let c=e.split(".");if(c.length!==3)throw new Error("Wrong number of segments in token: "+e);let l=c[0]+"."+c[1],h=c[2],d,p;try{d=JSON.parse(u.decodeBase64StringUtf8(c[0]))}catch(b){throw b instanceof Error&&(b.message=`Can't parse token envelope: ${c[0]}': ${b.message}`),b}if(!d)throw new Error("Can't parse token envelope: "+c[0]);try{p=JSON.parse(u.decodeBase64StringUtf8(c[1]))}catch(b){throw b instanceof Error&&(b.message=`Can't parse token payload '${c[0]}`),b}if(!p)throw new Error("Can't parse token payload: "+c[1]);if(!Object.prototype.hasOwnProperty.call(r,d.kid))throw new Error("No pem found for envelope: "+JSON.stringify(d));let A=r[d.kid];if(d.alg==="ES256"&&(h=nE.joseToDer(h,"ES256").toString("base64")),!await u.verify(A,l,h))throw new Error("Invalid token signature: "+e);if(!p.iat)throw new Error("No issue time in token: "+JSON.stringify(p));if(!p.exp)throw new Error("No expiration time in token: "+JSON.stringify(p));let S=Number(p.iat);if(isNaN(S))throw new Error("iat field using invalid format");let y=Number(p.exp);if(isNaN(y))throw new Error("exp field using invalid format");let g=new Date().getTime()/1e3;if(y>=g+i)throw new Error("Expiration time too far in future: "+JSON.stringify(p));let m=S-t.CLOCK_SKEW_SECS_,k=y+t.CLOCK_SKEW_SECS_;if(g<m)throw new Error("Token used too early, "+g+" < "+m+": "+JSON.stringify(p));if(g>k)throw new Error("Token used too late, "+g+" > "+k+": "+JSON.stringify(p));if(s&&s.indexOf(p.iss)<0)throw new Error("Invalid issuer, expected one of ["+s+"], but got "+p.iss);if(typeof n<"u"&&n!==null){let b=p.aud,E=!1;if(n.constructor===Array?E=n.indexOf(b)>-1:E=b===n,!E)throw new Error("Wrong recipient, payload audience != requiredAudience")}return new sE.LoginTicket(d,p)}async processAndValidateRefreshHandler(){if(this.refreshHandler){let e=await this.refreshHandler();if(!e.access_token)throw new Error("No access token is returned by the refreshHandler callback.");return e}}isTokenExpiring(){let e=this.credentials.expiry_date;return e?e<=new Date().getTime()+this.eagerRefreshThresholdMillis:!1}};Qt.OAuth2Client=Fc});var Ic=V(Ri=>{"use strict";Object.defineProperty(Ri,"__esModule",{value:!0});Ri.Compute=void 0;var oE=Ve(),Pm=Fs(),iE=fn(),Pc=class extends iE.OAuth2Client{serviceAccountEmail;scopes;constructor(e={}){super(e),this.credentials={expiry_date:1,refresh_token:"compute-placeholder"},this.serviceAccountEmail=e.serviceAccountEmail||"default",this.scopes=Array.isArray(e.scopes)?e.scopes:e.scopes?[e.scopes]:[]}async refreshTokenNoCache(){let e=`service-accounts/${this.serviceAccountEmail}/token`,r;try{let s={property:e};this.scopes.length>0&&(s.params={scopes:this.scopes.join(",")}),r=await Pm.instance(s)}catch(s){throw s instanceof oE.GaxiosError&&(s.message=`Could not refresh access token: ${s.message}`,this.wrapError(s)),s}let n=r;return r&&r.expires_in&&(n.expiry_date=new Date().getTime()+r.expires_in*1e3,delete n.expires_in),this.emit("tokens",n),{tokens:n,res:null}}async fetchIdToken(e){let r=`service-accounts/${this.serviceAccountEmail}/identity?format=full&audience=${e}`,n;try{let s={property:r};n=await Pm.instance(s)}catch(s){throw s instanceof Error&&(s.message=`Could not fetch ID token: ${s.message}`),s}return n}wrapError(e){let r=e.response;r&&r.status&&(e.status=r.status,r.status===403?e.message="A Forbidden error was returned while attempting to retrieve an access token for the Compute Engine built-in service account. This may be because the Compute Engine instance does not have the correct permission scopes specified: "+e.message:r.status===404&&(e.message="A Not Found error was returned while attempting to retrieve an accesstoken for the Compute Engine built-in service account. This may be because the Compute Engine instance does not have any permission scopes specified: "+e.message))}};Ri.Compute=Pc});var Bc=V(Oi=>{"use strict";Object.defineProperty(Oi,"__esModule",{value:!0});Oi.IdTokenClient=void 0;var aE=fn(),Nc=class extends aE.OAuth2Client{targetAudience;idTokenProvider;constructor(e){super(e),this.targetAudience=e.targetAudience,this.idTokenProvider=e.idTokenProvider}async getRequestMetadataAsync(){if(!this.credentials.id_token||!this.credentials.expiry_date||this.isTokenExpiring()){let r=await this.idTokenProvider.fetchIdToken(this.targetAudience);this.credentials={id_token:r,expiry_date:this.getIdTokenExpiryDate(r)}}return{headers:new Headers({authorization:"Bearer "+this.credentials.id_token})}}getIdTokenExpiryDate(e){let r=e.split(".")[1];if(r)return JSON.parse(Buffer.from(r,"base64").toString("ascii")).exp*1e3}};Oi.IdTokenClient=Nc});var jc=V(Gn=>{"use strict";Object.defineProperty(Gn,"__esModule",{value:!0});Gn.GCPEnv=void 0;Gn.clear=uE;Gn.getEnv=cE;var Im=Fs(),Zt;(function(t){t.APP_ENGINE="APP_ENGINE",t.KUBERNETES_ENGINE="KUBERNETES_ENGINE",t.CLOUD_FUNCTIONS="CLOUD_FUNCTIONS",t.COMPUTE_ENGINE="COMPUTE_ENGINE",t.CLOUD_RUN="CLOUD_RUN",t.CLOUD_RUN_JOBS="CLOUD_RUN_JOBS",t.NONE="NONE"})(Zt||(Gn.GCPEnv=Zt={}));var Ns;function uE(){Ns=void 0}async function cE(){return Ns||(Ns=lE(),Ns)}async function lE(){let t=Zt.NONE;return fE()?t=Zt.APP_ENGINE:dE()?t=Zt.CLOUD_FUNCTIONS:await gE()?await mE()?t=Zt.KUBERNETES_ENGINE:hE()?t=Zt.CLOUD_RUN:pE()?t=Zt.CLOUD_RUN_JOBS:t=Zt.COMPUTE_ENGINE:t=Zt.NONE,t}function fE(){return!!(process.env.GAE_SERVICE||process.env.GAE_MODULE_NAME)}function dE(){return!!(process.env.FUNCTION_NAME||process.env.FUNCTION_TARGET)}function hE(){return!!process.env.K_CONFIGURATION}function pE(){return!!process.env.CLOUD_RUN_JOB}async function mE(){try{return await Im.instance("attributes/cluster-name"),!0}catch{return!1}}async function gE(){return Im.isAvailable()}});var Lc=V((C1,Nm)=>{var xi=Hn().Buffer,yE=Q("stream"),_E=Q("util");function Fi(t){if(this.buffer=null,this.writable=!0,this.readable=!0,!t)return this.buffer=xi.alloc(0),this;if(typeof t.pipe=="function")return this.buffer=xi.alloc(0),t.pipe(this),this;if(t.length||typeof t=="object")return this.buffer=t,this.writable=!1,process.nextTick(function(){this.emit("end",t),this.readable=!1,this.emit("close")}.bind(this)),this;throw new TypeError("Unexpected data type ("+typeof t+")")}_E.inherits(Fi,yE);Fi.prototype.write=function(e){this.buffer=xi.concat([this.buffer,xi.from(e)]),this.emit("data",e)};Fi.prototype.end=function(e){e&&this.write(e),this.emit("end",e),this.emit("close"),this.writable=!1,this.readable=!1};Nm.exports=Fi});var jm=V((w1,Bm)=>{"use strict";var Bs=Q("buffer").Buffer,Mc=Q("buffer").SlowBuffer;Bm.exports=Pi;function Pi(t,e){if(!Bs.isBuffer(t)||!Bs.isBuffer(e)||t.length!==e.length)return!1;for(var r=0,n=0;n<t.length;n++)r|=t[n]^e[n];return r===0}Pi.install=function(){Bs.prototype.equal=Mc.prototype.equal=function(e){return Pi(this,e)}};var bE=Bs.prototype.equal,CE=Mc.prototype.equal;Pi.restore=function(){Bs.prototype.equal=bE,Mc.prototype.equal=CE}});var zc=V((E1,Gm)=>{var Vn=Hn().Buffer,Tt=Q("crypto"),Mm=Ec(),Lm=Q("util"),wE=`"%s" is not a valid algorithm.
|
|
49
|
+
`+y+"}":"{"+g.join(",")+"}",n=y,T}}typeof tm.stringify!="function"&&(tm.stringify=function(h,d,p){var w;if(n="",s="",typeof p=="number")for(w=0;w<p;w+=1)s+=" ";else typeof p=="string"&&(s=p);if(u=d,d&&typeof d!="function"&&(typeof d!="object"||typeof d.length!="number"))throw new Error("JSON.stringify");return l("",{"":h})})})()});var om=V((D1,sm)=>{var wi=null,dw=/(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])/,fw=/(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)/,hw=function(t){"use strict";var e={strict:!1,storeAsString:!1,alwaysParseAsBig:!1,useNativeBigInt:!1,protoAction:"error",constructorAction:"error"};if(t!=null){if(t.strict===!0&&(e.strict=!0),t.storeAsString===!0&&(e.storeAsString=!0),e.alwaysParseAsBig=t.alwaysParseAsBig===!0?t.alwaysParseAsBig:!1,e.useNativeBigInt=t.useNativeBigInt===!0?t.useNativeBigInt:!1,typeof t.constructorAction<"u")if(t.constructorAction==="error"||t.constructorAction==="ignore"||t.constructorAction==="preserve")e.constructorAction=t.constructorAction;else throw new Error(`Incorrect value for constructorAction option, must be "error", "ignore" or undefined but passed ${t.constructorAction}`);if(typeof t.protoAction<"u")if(t.protoAction==="error"||t.protoAction==="ignore"||t.protoAction==="preserve")e.protoAction=t.protoAction;else throw new Error(`Incorrect value for protoAction option, must be "error", "ignore" or undefined but passed ${t.protoAction}`)}var r,n,s={'"':'"',"\\":"\\","/":"/",b:"\b",f:"\f",n:`
|
|
50
|
+
`,r:"\r",t:" "},i,u=function(y){throw{name:"SyntaxError",message:y,at:r,text:i}},c=function(y){return y&&y!==n&&u("Expected '"+y+"' instead of '"+n+"'"),n=i.charAt(r),r+=1,n},l=function(){var y,g="";for(n==="-"&&(g="-",c("-"));n>="0"&&n<="9";)g+=n,c();if(n===".")for(g+=".";c()&&n>="0"&&n<="9";)g+=n;if(n==="e"||n==="E")for(g+=n,c(),(n==="-"||n==="+")&&(g+=n,c());n>="0"&&n<="9";)g+=n,c();if(y=+g,!isFinite(y))u("Bad number");else return wi==null&&(wi=cc()),g.length>15?e.storeAsString?g:e.useNativeBigInt?BigInt(g):new wi(g):e.alwaysParseAsBig?e.useNativeBigInt?BigInt(y):new wi(y):y},h=function(){var y,g,m="",v;if(n==='"')for(var b=r;c();){if(n==='"')return r-1>b&&(m+=i.substring(b,r-1)),c(),m;if(n==="\\"){if(r-1>b&&(m+=i.substring(b,r-1)),c(),n==="u"){for(v=0,g=0;g<4&&(y=parseInt(c(),16),!!isFinite(y));g+=1)v=v*16+y;m+=String.fromCharCode(v)}else if(typeof s[n]=="string")m+=s[n];else break;b=r}}u("Bad string")},d=function(){for(;n&&n<=" ";)c()},p=function(){switch(n){case"t":return c("t"),c("r"),c("u"),c("e"),!0;case"f":return c("f"),c("a"),c("l"),c("s"),c("e"),!1;case"n":return c("n"),c("u"),c("l"),c("l"),null}u("Unexpected '"+n+"'")},w,T=function(){var y=[];if(n==="["){if(c("["),d(),n==="]")return c("]"),y;for(;n;){if(y.push(w()),d(),n==="]")return c("]"),y;c(","),d()}}u("Bad array")},S=function(){var y,g=Object.create(null);if(n==="{"){if(c("{"),d(),n==="}")return c("}"),g;for(;n;){if(y=h(),d(),c(":"),e.strict===!0&&Object.hasOwnProperty.call(g,y)&&u('Duplicate key "'+y+'"'),dw.test(y)===!0?e.protoAction==="error"?u("Object contains forbidden prototype property"):e.protoAction==="ignore"?w():g[y]=w():fw.test(y)===!0?e.constructorAction==="error"?u("Object contains forbidden constructor property"):e.constructorAction==="ignore"?w():g[y]=w():g[y]=w(),d(),n==="}")return c("}"),g;c(","),d()}}u("Bad object")};return w=function(){switch(d(),n){case"{":return S();case"[":return T();case'"':return h();case"-":return l();default:return n>="0"&&n<="9"?l():p()}},function(y,g){var m;return i=y+"",r=0,n=" ",m=w(),d(),n&&u("Syntax error"),typeof g=="function"?(function v(b,A){var R,F,$=b[A];return $&&typeof $=="object"&&Object.keys($).forEach(function(J){F=v($,J),F!==void 0?$[J]=F:delete $[J]}),g.call(b,A,$)})({"":m},""):m}};sm.exports=hw});var um=V((R1,Ei)=>{var im=nm().stringify,am=om();Ei.exports=function(t){return{parse:am(t),stringify:im}};Ei.exports.parse=am();Ei.exports.stringify=im});var lc=V(Lt=>{"use strict";Object.defineProperty(Lt,"__esModule",{value:!0});Lt.GCE_LINUX_BIOS_PATHS=void 0;Lt.isGoogleCloudServerless=dm;Lt.isGoogleComputeEngineLinux=fm;Lt.isGoogleComputeEngineMACAddress=hm;Lt.isGoogleComputeEngine=pm;Lt.detectGCPResidency=mw;var cm=X("fs"),lm=X("os");Lt.GCE_LINUX_BIOS_PATHS={BIOS_DATE:"/sys/class/dmi/id/bios_date",BIOS_VENDOR:"/sys/class/dmi/id/bios_vendor"};var pw=/^42:01/;function dm(){return!!(process.env.CLOUD_RUN_JOB||process.env.FUNCTION_NAME||process.env.K_SERVICE)}function fm(){if((0,lm.platform)()!=="linux")return!1;try{(0,cm.statSync)(Lt.GCE_LINUX_BIOS_PATHS.BIOS_DATE);let t=(0,cm.readFileSync)(Lt.GCE_LINUX_BIOS_PATHS.BIOS_VENDOR,"utf8");return/Google/.test(t)}catch{return!1}}function hm(){let t=(0,lm.networkInterfaces)();for(let e of Object.values(t))if(e){for(let{mac:r}of e)if(pw.test(r))return!0}return!1}function pm(){return fm()||hm()}function mw(){return dm()||pm()}});var mm=V(Ai=>{"use strict";Object.defineProperty(Ai,"__esModule",{value:!0});Ai.Colours=void 0;var Qe=class t{static isEnabled(e){return e&&e.isTTY&&(typeof e.getColorDepth=="function"?e.getColorDepth()>2:!0)}static refresh(){t.enabled=t.isEnabled(process==null?void 0:process.stderr),this.enabled?(t.reset="\x1B[0m",t.bright="\x1B[1m",t.dim="\x1B[2m",t.red="\x1B[31m",t.green="\x1B[32m",t.yellow="\x1B[33m",t.blue="\x1B[34m",t.magenta="\x1B[35m",t.cyan="\x1B[36m",t.white="\x1B[37m",t.grey="\x1B[90m"):(t.reset="",t.bright="",t.dim="",t.red="",t.green="",t.yellow="",t.blue="",t.magenta="",t.cyan="",t.white="",t.grey="")}};Ai.Colours=Qe;Qe.enabled=!1;Qe.reset="";Qe.bright="";Qe.dim="";Qe.red="";Qe.green="";Qe.yellow="";Qe.blue="";Qe.magenta="";Qe.cyan="";Qe.white="";Qe.grey="";Qe.refresh()});var bm=V(ke=>{"use strict";var gw=ke&&ke.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,s)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),yw=ke&&ke.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),gm=ke&&ke.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(r){var n=[];for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&(n[n.length]=s);return n},t(e)};return function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var n=t(e),s=0;s<n.length;s++)n[s]!=="default"&&gw(r,e,n[s]);return yw(r,e),r}})();Object.defineProperty(ke,"__esModule",{value:!0});ke.env=ke.DebugLogBackendBase=ke.placeholder=ke.AdhocDebugLogger=ke.LogSeverity=void 0;ke.getNodeBackend=fc;ke.getDebugBackend=bw;ke.getStructuredBackend=Cw;ke.setBackend=ww;ke.log=_m;var _w=X("events"),Fs=gm(X("process")),ym=gm(X("util")),ft=mm(),Mt;(function(t){t.DEFAULT="DEFAULT",t.DEBUG="DEBUG",t.INFO="INFO",t.WARNING="WARNING",t.ERROR="ERROR"})(Mt||(ke.LogSeverity=Mt={}));var Ps=class extends _w.EventEmitter{constructor(e,r){super(),this.namespace=e,this.upstream=r,this.func=Object.assign(this.invoke.bind(this),{instance:this,on:(n,s)=>this.on(n,s)}),this.func.debug=(...n)=>this.invokeSeverity(Mt.DEBUG,...n),this.func.info=(...n)=>this.invokeSeverity(Mt.INFO,...n),this.func.warn=(...n)=>this.invokeSeverity(Mt.WARNING,...n),this.func.error=(...n)=>this.invokeSeverity(Mt.ERROR,...n),this.func.sublog=n=>_m(n,this.func)}invoke(e,...r){if(this.upstream)try{this.upstream(e,...r)}catch{}try{this.emit("log",e,r)}catch{}}invokeSeverity(e,...r){this.invoke({severity:e},...r)}};ke.AdhocDebugLogger=Ps;ke.placeholder=new Ps("",()=>{}).func;var zn=class{constructor(){var e;this.cached=new Map,this.filters=[],this.filtersSet=!1;let r=(e=Fs.env[ke.env.nodeEnables])!==null&&e!==void 0?e:"*";r==="all"&&(r="*"),this.filters=r.split(",")}log(e,r,...n){try{this.filtersSet||(this.setFilters(),this.filtersSet=!0);let s=this.cached.get(e);s||(s=this.makeLogger(e),this.cached.set(e,s)),s(r,...n)}catch(s){console.error(s)}}};ke.DebugLogBackendBase=zn;var dc=class extends zn{constructor(){super(...arguments),this.enabledRegexp=/.*/g}isEnabled(e){return this.enabledRegexp.test(e)}makeLogger(e){return this.enabledRegexp.test(e)?(r,...n)=>{var s;let i=`${ft.Colours.green}${e}${ft.Colours.reset}`,u=`${ft.Colours.yellow}${Fs.pid}${ft.Colours.reset}`,c;switch(r.severity){case Mt.ERROR:c=`${ft.Colours.red}${r.severity}${ft.Colours.reset}`;break;case Mt.INFO:c=`${ft.Colours.magenta}${r.severity}${ft.Colours.reset}`;break;case Mt.WARNING:c=`${ft.Colours.yellow}${r.severity}${ft.Colours.reset}`;break;default:c=(s=r.severity)!==null&&s!==void 0?s:Mt.DEFAULT;break}let l=ym.formatWithOptions({colors:ft.Colours.enabled},...n),h=Object.assign({},r);delete h.severity;let d=Object.getOwnPropertyNames(h).length?JSON.stringify(h):"",p=d?`${ft.Colours.grey}${d}${ft.Colours.reset}`:"";console.error("%s [%s|%s] %s%s",u,i,c,l,d?` ${p}`:"")}:()=>{}}setFilters(){let r=this.filters.join(",").replace(/[|\\{}()[\]^$+?.]/g,"\\$&").replace(/\*/g,".*").replace(/,/g,"$|^");this.enabledRegexp=new RegExp(`^${r}$`,"i")}};function fc(){return new dc}var hc=class extends zn{constructor(e){super(),this.debugPkg=e}makeLogger(e){let r=this.debugPkg(e);return(n,...s)=>{r(s[0],...s.slice(1))}}setFilters(){var e;let r=(e=Fs.env.NODE_DEBUG)!==null&&e!==void 0?e:"";Fs.env.NODE_DEBUG=`${r}${r?",":""}${this.filters.join(",")}`}};function bw(t){return new hc(t)}var pc=class extends zn{constructor(e){var r;super(),this.upstream=(r=e)!==null&&r!==void 0?r:void 0}makeLogger(e){var r;let n=(r=this.upstream)===null||r===void 0?void 0:r.makeLogger(e);return(s,...i)=>{var u;let c=(u=s.severity)!==null&&u!==void 0?u:Mt.INFO,l=Object.assign({severity:c,message:ym.format(...i)},s),h=JSON.stringify(l);n?n(s,h):console.log("%s",h)}}setFilters(){var e;(e=this.upstream)===null||e===void 0||e.setFilters()}};function Cw(t){return new pc(t)}ke.env={nodeEnables:"GOOGLE_SDK_NODE_LOGGING"};var mc=new Map,ht;function ww(t){ht=t,mc.clear()}function _m(t,e){if(!ht&&!Fs.env[ke.env.nodeEnables]||!t)return ke.placeholder;e&&(t=`${e.instance.namespace}:${t}`);let r=mc.get(t);if(r)return r.func;if(ht===null)return ke.placeholder;ht===void 0&&(ht=fc());let n=(()=>{let s;return new Ps(t,(u,...c)=>{if(s!==ht){if(ht===null)return;ht===void 0&&(ht=fc()),s=ht}ht?.log(t,u,...c)})})();return mc.set(t,n),n.func}});var gc=V(dn=>{"use strict";var Ew=dn&&dn.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,s)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),Aw=dn&&dn.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&Ew(e,t,r)};Object.defineProperty(dn,"__esModule",{value:!0});Aw(bm(),dn)});var Ns=V(ie=>{"use strict";var wm=ie&&ie.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,s)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),Sw=ie&&ie.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),vw=ie&&ie.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(r){var n=[];for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&(n[n.length]=s);return n},t(e)};return function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var n=t(e),s=0;s<n.length;s++)n[s]!=="default"&&wm(r,e,n[s]);return Sw(r,e),r}})(),kw=ie&&ie.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&wm(e,t,r)};Object.defineProperty(ie,"__esModule",{value:!0});ie.gcpResidencyCache=ie.METADATA_SERVER_DETECTION=ie.HEADERS=ie.HEADER_VALUE=ie.HEADER_NAME=ie.SECONDARY_HOST_ADDRESS=ie.HOST_ADDRESS=ie.BASE_PATH=void 0;ie.instance=Fw;ie.project=Pw;ie.universe=Iw;ie.bulk=Nw;ie.isAvailable=jw;ie.resetIsAvailableCache=Lw;ie.getGCPResidency=bc;ie.setGCPResidency=Em;ie.requestTimeout=Am;var yc=Ve(),Tw=um(),Dw=lc(),Rw=vw(gc());ie.BASE_PATH="/computeMetadata/v1";ie.HOST_ADDRESS="http://169.254.169.254";ie.SECONDARY_HOST_ADDRESS="http://metadata.google.internal.";ie.HEADER_NAME="Metadata-Flavor";ie.HEADER_VALUE="Google";ie.HEADERS=Object.freeze({[ie.HEADER_NAME]:ie.HEADER_VALUE});var Cm=Rw.log("gcp-metadata");ie.METADATA_SERVER_DETECTION=Object.freeze({"assume-present":"don't try to ping the metadata server, but assume it's present",none:"don't try to ping the metadata server, but don't try to use it either","bios-only":"treat the result of a BIOS probe as canonical (don't fall back to pinging)","ping-only":"skip the BIOS probe, and go straight to pinging"});function _c(t){return t||(t=process.env.GCE_METADATA_IP||process.env.GCE_METADATA_HOST||ie.HOST_ADDRESS),/^https?:\/\//.test(t)||(t=`http://${t}`),new URL(ie.BASE_PATH,t).href}function xw(t){Object.keys(t).forEach(e=>{switch(e){case"params":case"property":case"headers":break;case"qs":throw new Error("'qs' is not a valid configuration option. Please use 'params' instead.");default:throw new Error(`'${e}' is not a valid configuration option.`)}})}async function Is(t,e={},r=3,n=!1){let s=new Headers(ie.HEADERS),i="",u={};if(typeof t=="object"){let p=t;new Headers(p.headers).forEach((w,T)=>s.set(T,w)),i=p.metadataKey,u=p.params||u,r=p.noResponseRetries||r,n=p.fastFail||n}else i=t;typeof e=="string"?i+=`/${e}`:(xw(e),e.property&&(i+=`/${e.property}`),new Headers(e.headers).forEach((p,w)=>s.set(w,p)),u=e.params||u);let c=n?Ow:yc.request,l={url:`${_c()}/${i}`,headers:s,retryConfig:{noResponseRetries:r},params:u,responseType:"text",timeout:Am()};Cm.info("instance request %j",l);let h=await c(l);Cm.info("instance metadata is %s",h.data);let d=h.headers.get(ie.HEADER_NAME);if(d!==ie.HEADER_VALUE)throw new RangeError(`Invalid response from metadata service: incorrect ${ie.HEADER_NAME} header. Expected '${ie.HEADER_VALUE}', got ${d?`'${d}'`:"no header"}`);if(typeof h.data=="string")try{return Tw.parse(h.data)}catch{}return h.data}async function Ow(t){let e={...t,url:t.url?.toString().replace(_c(),_c(ie.SECONDARY_HOST_ADDRESS))},r=(0,yc.request)(t),n=(0,yc.request)(e);return Promise.any([r,n])}function Fw(t){return Is("instance",t)}function Pw(t){return Is("project",t)}function Iw(t){return Is("universe",t)}async function Nw(t){let e={};return await Promise.all(t.map(r=>(async()=>{let n=await Is(r),s=r.metadataKey;e[s]=n})())),e}function Bw(){return process.env.DETECT_GCP_RETRIES?Number(process.env.DETECT_GCP_RETRIES):0}var Si;async function jw(){if(process.env.METADATA_SERVER_DETECTION){let t=process.env.METADATA_SERVER_DETECTION.trim().toLocaleLowerCase();if(!(t in ie.METADATA_SERVER_DETECTION))throw new RangeError(`Unknown \`METADATA_SERVER_DETECTION\` env variable. Got \`${t}\`, but it should be \`${Object.keys(ie.METADATA_SERVER_DETECTION).join("`, `")}\`, or unset`);switch(t){case"assume-present":return!0;case"none":return!1;case"bios-only":return bc();case"ping-only":}}try{return Si===void 0&&(Si=Is("instance",void 0,Bw(),!(process.env.GCE_METADATA_IP||process.env.GCE_METADATA_HOST))),await Si,!0}catch(t){let e=t;if(process.env.DEBUG_AUTH&&console.info(e),e.type==="request-timeout"||e.response&&e.response.status===404)return!1;if(!(e.response&&e.response.status===404)&&(!e.code||!["EHOSTDOWN","EHOSTUNREACH","ENETUNREACH","ENOENT","ENOTFOUND","ECONNREFUSED"].includes(e.code.toString()))){let r="UNKNOWN";e.code&&(r=e.code.toString()),process.emitWarning(`received unexpected error = ${e.message} code = ${r}`,"MetadataLookupWarning")}return!1}}function Lw(){Si=void 0}ie.gcpResidencyCache=null;function bc(){return ie.gcpResidencyCache===null&&Em(),ie.gcpResidencyCache}function Em(t=null){ie.gcpResidencyCache=t!==null?t:(0,Dw.detectGCPResidency)()}function Am(){return bc()?0:3e3}kw(lc(),ie)});var km=V(vi=>{"use strict";vi.byteLength=Uw;vi.toByteArray=$w;vi.fromByteArray=Ww;var Qt=[],vt=[],Mw=typeof Uint8Array<"u"?Uint8Array:Array,Cc="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(fn=0,Sm=Cc.length;fn<Sm;++fn)Qt[fn]=Cc[fn],vt[Cc.charCodeAt(fn)]=fn;var fn,Sm;vt[45]=62;vt[95]=63;function vm(t){var e=t.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var r=t.indexOf("=");r===-1&&(r=e);var n=r===e?0:4-r%4;return[r,n]}function Uw(t){var e=vm(t),r=e[0],n=e[1];return(r+n)*3/4-n}function qw(t,e,r){return(e+r)*3/4-r}function $w(t){var e,r=vm(t),n=r[0],s=r[1],i=new Mw(qw(t,n,s)),u=0,c=s>0?n-4:n,l;for(l=0;l<c;l+=4)e=vt[t.charCodeAt(l)]<<18|vt[t.charCodeAt(l+1)]<<12|vt[t.charCodeAt(l+2)]<<6|vt[t.charCodeAt(l+3)],i[u++]=e>>16&255,i[u++]=e>>8&255,i[u++]=e&255;return s===2&&(e=vt[t.charCodeAt(l)]<<2|vt[t.charCodeAt(l+1)]>>4,i[u++]=e&255),s===1&&(e=vt[t.charCodeAt(l)]<<10|vt[t.charCodeAt(l+1)]<<4|vt[t.charCodeAt(l+2)]>>2,i[u++]=e>>8&255,i[u++]=e&255),i}function zw(t){return Qt[t>>18&63]+Qt[t>>12&63]+Qt[t>>6&63]+Qt[t&63]}function Hw(t,e,r){for(var n,s=[],i=e;i<r;i+=3)n=(t[i]<<16&16711680)+(t[i+1]<<8&65280)+(t[i+2]&255),s.push(zw(n));return s.join("")}function Ww(t){for(var e,r=t.length,n=r%3,s=[],i=16383,u=0,c=r-n;u<c;u+=i)s.push(Hw(t,u,u+i>c?c:u+i));return n===1?(e=t[r-1],s.push(Qt[e>>2]+Qt[e<<4&63]+"==")):n===2&&(e=(t[r-2]<<8)+t[r-1],s.push(Qt[e>>10]+Qt[e>>4&63]+Qt[e<<2&63]+"=")),s.join("")}});var Ec=V(wc=>{"use strict";Object.defineProperty(wc,"__esModule",{value:!0});wc.fromArrayBufferToHex=Gw;function Gw(t){return Array.from(new Uint8Array(t)).map(r=>r.toString(16).padStart(2,"0")).join("")}});var Tm=V(ki=>{"use strict";Object.defineProperty(ki,"__esModule",{value:!0});ki.BrowserCrypto=void 0;var Hn=km(),Jw=Ec(),Ac=class t{constructor(){if(typeof window>"u"||window.crypto===void 0||window.crypto.subtle===void 0)throw new Error("SubtleCrypto not found. Make sure it's an https:// website.")}async sha256DigestBase64(e){let r=new TextEncoder().encode(e),n=await window.crypto.subtle.digest("SHA-256",r);return Hn.fromByteArray(new Uint8Array(n))}randomBytesBase64(e){let r=new Uint8Array(e);return window.crypto.getRandomValues(r),Hn.fromByteArray(r)}static padBase64(e){for(;e.length%4!==0;)e+="=";return e}async verify(e,r,n){let s={name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},i=new TextEncoder().encode(r),u=Hn.toByteArray(t.padBase64(n)),c=await window.crypto.subtle.importKey("jwk",e,s,!0,["verify"]);return await window.crypto.subtle.verify(s,c,u,i)}async sign(e,r){let n={name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},s=new TextEncoder().encode(r),i=await window.crypto.subtle.importKey("jwk",e,n,!0,["sign"]),u=await window.crypto.subtle.sign(n,i,s);return Hn.fromByteArray(new Uint8Array(u))}decodeBase64StringUtf8(e){let r=Hn.toByteArray(t.padBase64(e));return new TextDecoder().decode(r)}encodeBase64StringUtf8(e){let r=new TextEncoder().encode(e);return Hn.fromByteArray(r)}async sha256DigestHex(e){let r=new TextEncoder().encode(e),n=await window.crypto.subtle.digest("SHA-256",r);return(0,Jw.fromArrayBufferToHex)(n)}async signWithHmacSha256(e,r){let n=typeof e=="string"?e:String.fromCharCode(...new Uint16Array(e)),s=new TextEncoder,i=await window.crypto.subtle.importKey("raw",s.encode(n),{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return window.crypto.subtle.sign("HMAC",i,s.encode(r))}};ki.BrowserCrypto=Ac});var Dm=V(Ti=>{"use strict";Object.defineProperty(Ti,"__esModule",{value:!0});Ti.NodeCrypto=void 0;var Wn=X("crypto"),Sc=class{async sha256DigestBase64(e){return Wn.createHash("sha256").update(e).digest("base64")}randomBytesBase64(e){return Wn.randomBytes(e).toString("base64")}async verify(e,r,n){let s=Wn.createVerify("RSA-SHA256");return s.update(r),s.end(),s.verify(e,n,"base64")}async sign(e,r){let n=Wn.createSign("RSA-SHA256");return n.update(r),n.end(),n.sign(e,"base64")}decodeBase64StringUtf8(e){return Buffer.from(e,"base64").toString("utf-8")}encodeBase64StringUtf8(e){return Buffer.from(e,"utf-8").toString("base64")}async sha256DigestHex(e){return Wn.createHash("sha256").update(e).digest("hex")}async signWithHmacSha256(e,r){let n=typeof e=="string"?e:Kw(e);return Vw(Wn.createHmac("sha256",n).update(r).digest())}};Ti.NodeCrypto=Sc;function Vw(t){return t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength)}function Kw(t){return Buffer.from(t)}});var Bs=V(br=>{"use strict";var Yw=br&&br.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,s)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),Qw=br&&br.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&Yw(e,t,r)};Object.defineProperty(br,"__esModule",{value:!0});br.createCrypto=eE;br.hasBrowserCrypto=Rm;var Xw=Tm(),Zw=Dm();Qw(Ec(),br);function eE(){return Rm()?new Xw.BrowserCrypto:new Zw.NodeCrypto}function Rm(){return typeof window<"u"&&typeof window.crypto<"u"&&typeof window.crypto.subtle<"u"}});var Gn=V((vc,Om)=>{var Di=X("buffer"),Xt=Di.Buffer;function xm(t,e){for(var r in t)e[r]=t[r]}Xt.from&&Xt.alloc&&Xt.allocUnsafe&&Xt.allocUnsafeSlow?Om.exports=Di:(xm(Di,vc),vc.Buffer=hn);function hn(t,e,r){return Xt(t,e,r)}hn.prototype=Object.create(Xt.prototype);xm(Xt,hn);hn.from=function(t,e,r){if(typeof t=="number")throw new TypeError("Argument must not be a number");return Xt(t,e,r)};hn.alloc=function(t,e,r){if(typeof t!="number")throw new TypeError("Argument must be a number");var n=Xt(t);return e!==void 0?typeof r=="string"?n.fill(e,r):n.fill(e):n.fill(0),n};hn.allocUnsafe=function(t){if(typeof t!="number")throw new TypeError("Argument must be a number");return Xt(t)};hn.allocUnsafeSlow=function(t){if(typeof t!="number")throw new TypeError("Argument must be a number");return Di.SlowBuffer(t)}});var Pm=V((U1,Fm)=>{"use strict";function kc(t){var e=(t/8|0)+(t%8===0?0:1);return e}var tE={ES256:kc(256),ES384:kc(384),ES512:kc(521)};function rE(t){var e=tE[t];if(e)return e;throw new Error('Unknown algorithm "'+t+'"')}Fm.exports=rE});var Tc=V((q1,Mm)=>{"use strict";var Ri=Gn().Buffer,Nm=Pm(),xi=128,Bm=0,nE=32,sE=16,oE=2,jm=sE|nE|Bm<<6,Oi=oE|Bm<<6;function iE(t){return t.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function Lm(t){if(Ri.isBuffer(t))return t;if(typeof t=="string")return Ri.from(t,"base64");throw new TypeError("ECDSA signature must be a Base64 string or a Buffer")}function aE(t,e){t=Lm(t);var r=Nm(e),n=r+1,s=t.length,i=0;if(t[i++]!==jm)throw new Error('Could not find expected "seq"');var u=t[i++];if(u===(xi|1)&&(u=t[i++]),s-i<u)throw new Error('"seq" specified length of "'+u+'", only "'+(s-i)+'" remaining');if(t[i++]!==Oi)throw new Error('Could not find expected "int" for "r"');var c=t[i++];if(s-i-2<c)throw new Error('"r" specified length of "'+c+'", only "'+(s-i-2)+'" available');if(n<c)throw new Error('"r" specified length of "'+c+'", max of "'+n+'" is acceptable');var l=i;if(i+=c,t[i++]!==Oi)throw new Error('Could not find expected "int" for "s"');var h=t[i++];if(s-i!==h)throw new Error('"s" specified length of "'+h+'", expected "'+(s-i)+'"');if(n<h)throw new Error('"s" specified length of "'+h+'", max of "'+n+'" is acceptable');var d=i;if(i+=h,i!==s)throw new Error('Expected to consume entire buffer, but "'+(s-i)+'" bytes remain');var p=r-c,w=r-h,T=Ri.allocUnsafe(p+c+w+h);for(i=0;i<p;++i)T[i]=0;t.copy(T,i,l+Math.max(-p,0),l+c),i=r;for(var S=i;i<S+w;++i)T[i]=0;return t.copy(T,i,d+Math.max(-w,0),d+h),T=T.toString("base64"),T=iE(T),T}function Im(t,e,r){for(var n=0;e+n<r&&t[e+n]===0;)++n;var s=t[e+n]>=xi;return s&&--n,n}function uE(t,e){t=Lm(t);var r=Nm(e),n=t.length;if(n!==r*2)throw new TypeError('"'+e+'" signatures must be "'+r*2+'" bytes, saw "'+n+'"');var s=Im(t,0,r),i=Im(t,r,t.length),u=r-s,c=r-i,l=2+u+1+1+c,h=l<xi,d=Ri.allocUnsafe((h?2:3)+l),p=0;return d[p++]=jm,h?d[p++]=l:(d[p++]=xi|1,d[p++]=l&255),d[p++]=Oi,d[p++]=u,s<0?(d[p++]=0,p+=t.copy(d,p,0,r)):p+=t.copy(d,p,s,r),d[p++]=Oi,d[p++]=c,i<0?(d[p++]=0,t.copy(d,p,r)):t.copy(d,p,r+i),d}Mm.exports={derToJose:aE,joseToDer:uE}});var Ut=V(Cr=>{"use strict";Object.defineProperty(Cr,"__esModule",{value:!0});Cr.LRUCache=void 0;Cr.snakeToCamel=qm;Cr.originalOrCamelOptions=fE;Cr.removeUndefinedValuesInObject=hE;Cr.isValidFile=pE;Cr.getWellKnownCertificateConfigFileLocation=mE;var cE=X("fs"),lE=X("os"),Dc=X("path"),dE="certificate_config.json",Um="gcloud";function qm(t){return t.replace(/([_][^_])/g,e=>e.slice(1).toUpperCase())}function fE(t){function e(r){let n=t||{};return n[r]??n[qm(r)]}return{get:e}}var Rc=class{capacity;#e=new Map;maxAge;constructor(e){this.capacity=e.capacity,this.maxAge=e.maxAge}#t(e,r){this.#e.delete(e),this.#e.set(e,{value:r,lastAccessed:Date.now()})}set(e,r){this.#t(e,r),this.#r()}get(e){let r=this.#e.get(e);if(r)return this.#t(e,r.value),this.#r(),r.value}#r(){let e=this.maxAge?Date.now()-this.maxAge:0,r=this.#e.entries().next();for(;!r.done&&(this.#e.size>this.capacity||r.value[1].lastAccessed<e);)this.#e.delete(r.value[0]),r=this.#e.entries().next()}};Cr.LRUCache=Rc;function hE(t){return Object.entries(t).forEach(([e,r])=>{(r===void 0||r==="undefined")&&delete t[e]}),t}async function pE(t){try{return(await cE.promises.lstat(t)).isFile()}catch{return!1}}function mE(){let t=process.env.CLOUDSDK_CONFIG||(gE()?Dc.join(process.env.APPDATA||"",Um):Dc.join(process.env.HOME||"",".config",Um));return Dc.join(t,dE)}function gE(){return lE.platform().startsWith("win")}});var $m=V((z1,yE)=>{yE.exports={name:"google-auth-library",version:"10.4.0",author:"Google Inc.",description:"Google APIs Authentication Client Library for Node.js",engines:{node:">=18"},main:"./build/src/index.js",types:"./build/src/index.d.ts",repository:"googleapis/google-auth-library-nodejs.git",keywords:["google","api","google apis","client","client library"],dependencies:{"base64-js":"^1.3.0","ecdsa-sig-formatter":"^1.0.11",gaxios:"^7.0.0","gcp-metadata":"^7.0.0","google-logging-utils":"^1.0.0",gtoken:"^8.0.0",jws:"^4.0.0"},devDependencies:{"@types/base64-js":"^1.2.5","@types/jws":"^3.1.0","@types/mocha":"^10.0.10","@types/mv":"^2.1.0","@types/ncp":"^2.0.1","@types/node":"^22.0.0","@types/sinon":"^17.0.0","assert-rejects":"^1.0.0",c8:"^10.0.0",codecov:"^3.0.2",gts:"^6.0.0","is-docker":"^3.0.0",jsdoc:"^4.0.0","jsdoc-fresh":"^4.0.0","jsdoc-region-tag":"^3.0.0",karma:"^6.0.0","karma-chrome-launcher":"^3.0.0","karma-coverage":"^2.0.0","karma-firefox-launcher":"^2.0.0","karma-mocha":"^2.0.0","karma-sourcemap-loader":"^0.4.0","karma-webpack":"^5.0.1",keypair:"^1.0.4",linkinator:"^6.1.2",mocha:"^11.1.0",mv:"^2.1.1",ncp:"^2.0.0",nock:"^14.0.5","null-loader":"^4.0.0",puppeteer:"^24.0.0",sinon:"^21.0.0","ts-loader":"^8.0.0",typescript:"5.8.2",webpack:"^5.21.2","webpack-cli":"^4.0.0"},files:["build/src","!build/src/**/*.map"],scripts:{test:"c8 mocha build/test",clean:"gts clean",prepare:"npm run compile",lint:"gts check --no-inline-config",compile:"tsc -p .",fix:"gts fix",pretest:"npm run compile -- --sourceMap",docs:"jsdoc -c .jsdoc.js","samples-setup":"cd samples/ && npm link ../ && npm run setup && cd ../","samples-test":"cd samples/ && npm link ../ && npm test && cd ../","system-test":"mocha build/system-test --timeout 60000","presystem-test":"npm run compile -- --sourceMap",webpack:"webpack","browser-test":"karma start","docs-test":"linkinator docs","predocs-test":"npm run docs",prelint:"cd samples; npm link ../; npm install"},license:"Apache-2.0"}});var xc=V(zr=>{"use strict";Object.defineProperty(zr,"__esModule",{value:!0});zr.USER_AGENT=zr.PRODUCT_NAME=zr.pkg=void 0;var zm=$m();zr.pkg=zm;var Hm="google-api-nodejs-client";zr.PRODUCT_NAME=Hm;var _E=`${Hm}/${zm.version}`;zr.USER_AGENT=_E});var pt=V(qt=>{"use strict";Object.defineProperty(qt,"__esModule",{value:!0});qt.AuthClient=qt.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS=qt.DEFAULT_UNIVERSE=void 0;var bE=X("events"),Oc=Ve(),CE=Ut(),wE=gc(),Fc=xc();qt.DEFAULT_UNIVERSE="googleapis.com";qt.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS=300*1e3;var Pc=class t extends bE.EventEmitter{apiKey;projectId;quotaProjectId;transporter;credentials={};eagerRefreshThresholdMillis=qt.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS;forceRefreshOnFailure=!1;universeDomain=qt.DEFAULT_UNIVERSE;static RequestMethodNameSymbol=Symbol("request method name");static RequestLogIdSymbol=Symbol("request log id");constructor(e={}){super();let r=(0,CE.originalOrCamelOptions)(e);this.apiKey=e.apiKey,this.projectId=r.get("project_id")??null,this.quotaProjectId=r.get("quota_project_id"),this.credentials=r.get("credentials")??{},this.universeDomain=r.get("universe_domain")??qt.DEFAULT_UNIVERSE,this.transporter=e.transporter??new Oc.Gaxios(e.transporterOptions),r.get("useAuthRequestParameters")!==!1&&(this.transporter.interceptors.request.add(t.DEFAULT_REQUEST_INTERCEPTOR),this.transporter.interceptors.response.add(t.DEFAULT_RESPONSE_INTERCEPTOR)),e.eagerRefreshThresholdMillis&&(this.eagerRefreshThresholdMillis=e.eagerRefreshThresholdMillis),this.forceRefreshOnFailure=e.forceRefreshOnFailure??!1}fetch(...e){let r=e[0],n=e[1],s,i=new Headers;return typeof r=="string"?s=new URL(r):r instanceof URL?s=r:r&&r.url&&(s=new URL(r.url)),r&&typeof r=="object"&&"headers"in r&&Oc.Gaxios.mergeHeaders(i,r.headers),n&&Oc.Gaxios.mergeHeaders(i,new Headers(n.headers)),typeof r=="object"&&!(r instanceof URL)?this.request({...n,...r,headers:i,url:s}):this.request({...n,headers:i,url:s})}setCredentials(e){this.credentials=e}addSharedMetadataHeaders(e){return!e.has("x-goog-user-project")&&this.quotaProjectId&&e.set("x-goog-user-project",this.quotaProjectId),e}addUserProjectAndAuthHeaders(e,r){let n=r.get("x-goog-user-project"),s=r.get("authorization");return n&&e.set("x-goog-user-project",n),s&&e.set("authorization",s),e}static log=(0,wE.log)("auth");static DEFAULT_REQUEST_INTERCEPTOR={resolved:async e=>{if(!e.headers.has("x-goog-api-client")){let n=process.version.replace(/^v/,"");e.headers.set("x-goog-api-client",`gl-node/${n}`)}let r=e.headers.get("User-Agent");r?r.includes(`${Fc.PRODUCT_NAME}/`)||e.headers.set("User-Agent",`${r} ${Fc.USER_AGENT}`):e.headers.set("User-Agent",Fc.USER_AGENT);try{let n=e,s=n[t.RequestMethodNameSymbol],i=`${Math.floor(Math.random()*1e3)}`;n[t.RequestLogIdSymbol]=i;let u={url:e.url,headers:e.headers};s?t.log.info("%s [%s] request %j",s,i,u):t.log.info("[%s] request %j",i,u)}catch{}return e}};static DEFAULT_RESPONSE_INTERCEPTOR={resolved:async e=>{try{let r=e.config,n=r[t.RequestMethodNameSymbol],s=r[t.RequestLogIdSymbol];n?t.log.info("%s [%s] response %j",n,s,e.data):t.log.info("[%s] response %j",s,e.data)}catch{}return e},rejected:async e=>{try{let r=e.config,n=r[t.RequestMethodNameSymbol],s=r[t.RequestLogIdSymbol];n?t.log.info("%s [%s] error %j",n,s,e.response?.data):t.log.error("[%s] error %j",s,e.response?.data)}catch{}throw e}};static setMethodName(e,r){try{let n=e;n[t.RequestMethodNameSymbol]=r}catch{}}static get RETRY_CONFIG(){return{retry:!0,retryConfig:{httpMethodsToRetry:["GET","PUT","POST","HEAD","OPTIONS","DELETE"]}}}};qt.AuthClient=Pc});var Nc=V(Fi=>{"use strict";Object.defineProperty(Fi,"__esModule",{value:!0});Fi.LoginTicket=void 0;var Ic=class{envelope;payload;constructor(e,r){this.envelope=e,this.payload=r}getEnvelope(){return this.envelope}getPayload(){return this.payload}getUserId(){let e=this.getPayload();return e&&e.sub?e.sub:null}getAttributes(){return{envelope:this.getEnvelope(),payload:this.getPayload()}}};Fi.LoginTicket=Ic});var pn=V(Zt=>{"use strict";Object.defineProperty(Zt,"__esModule",{value:!0});Zt.OAuth2Client=Zt.ClientAuthentication=Zt.CertificateFormat=Zt.CodeChallengeMethod=void 0;var Wm=Ve(),EE=X("querystring"),AE=X("stream"),SE=Tc(),Gm=Ut(),Bc=Bs(),Jn=pt(),vE=Nc(),Jm;(function(t){t.Plain="plain",t.S256="S256"})(Jm||(Zt.CodeChallengeMethod=Jm={}));var wr;(function(t){t.PEM="PEM",t.JWK="JWK"})(wr||(Zt.CertificateFormat=wr={}));var js;(function(t){t.ClientSecretPost="ClientSecretPost",t.ClientSecretBasic="ClientSecretBasic",t.None="None"})(js||(Zt.ClientAuthentication=js={}));var jc=class t extends Jn.AuthClient{redirectUri;certificateCache={};certificateExpiry=null;certificateCacheFormat=wr.PEM;refreshTokenPromises=new Map;endpoints;issuers;clientAuthentication;_clientId;_clientSecret;refreshHandler;constructor(e={},r,n){super(typeof e=="object"?e:{}),typeof e!="object"&&(e={clientId:e,clientSecret:r,redirectUri:n}),this._clientId=e.clientId||e.client_id,this._clientSecret=e.clientSecret||e.client_secret,this.redirectUri=e.redirectUri||e.redirect_uris?.[0],this.endpoints={tokenInfoUrl:"https://oauth2.googleapis.com/tokeninfo",oauth2AuthBaseUrl:"https://accounts.google.com/o/oauth2/v2/auth",oauth2TokenUrl:"https://oauth2.googleapis.com/token",oauth2RevokeUrl:"https://oauth2.googleapis.com/revoke",oauth2FederatedSignonPemCertsUrl:"https://www.googleapis.com/oauth2/v1/certs",oauth2FederatedSignonJwkCertsUrl:"https://www.googleapis.com/oauth2/v3/certs",oauth2IapPublicKeyUrl:"https://www.gstatic.com/iap/verify/public_key",...e.endpoints},this.clientAuthentication=e.clientAuthentication||js.ClientSecretPost,this.issuers=e.issuers||["accounts.google.com","https://accounts.google.com",this.universeDomain]}static GOOGLE_TOKEN_INFO_URL="https://oauth2.googleapis.com/tokeninfo";static CLOCK_SKEW_SECS_=300;static DEFAULT_MAX_TOKEN_LIFETIME_SECS_=86400;generateAuthUrl(e={}){if(e.code_challenge_method&&!e.code_challenge)throw new Error("If a code_challenge_method is provided, code_challenge must be included.");return e.response_type=e.response_type||"code",e.client_id=e.client_id||this._clientId,e.redirect_uri=e.redirect_uri||this.redirectUri,Array.isArray(e.scope)&&(e.scope=e.scope.join(" ")),this.endpoints.oauth2AuthBaseUrl.toString()+"?"+EE.stringify(e)}generateCodeVerifier(){throw new Error("generateCodeVerifier is removed, please use generateCodeVerifierAsync instead.")}async generateCodeVerifierAsync(){let e=(0,Bc.createCrypto)(),n=e.randomBytesBase64(96).replace(/\+/g,"~").replace(/=/g,"_").replace(/\//g,"-"),i=(await e.sha256DigestBase64(n)).split("=")[0].replace(/\+/g,"-").replace(/\//g,"_");return{codeVerifier:n,codeChallenge:i}}getToken(e,r){let n=typeof e=="string"?{code:e}:e;if(r)this.getTokenAsync(n).then(s=>r(null,s.tokens,s.res),s=>r(s,null,s.response));else return this.getTokenAsync(n)}async getTokenAsync(e){let r=this.endpoints.oauth2TokenUrl.toString(),n=new Headers,s={client_id:e.client_id||this._clientId,code_verifier:e.codeVerifier,code:e.code,grant_type:"authorization_code",redirect_uri:e.redirect_uri||this.redirectUri};if(this.clientAuthentication===js.ClientSecretBasic){let l=Buffer.from(`${this._clientId}:${this._clientSecret}`);n.set("authorization",`Basic ${l.toString("base64")}`)}this.clientAuthentication===js.ClientSecretPost&&(s.client_secret=this._clientSecret);let i={...t.RETRY_CONFIG,method:"POST",url:r,data:new URLSearchParams((0,Gm.removeUndefinedValuesInObject)(s)),headers:n};Jn.AuthClient.setMethodName(i,"getTokenAsync");let u=await this.transporter.request(i),c=u.data;return u.data&&u.data.expires_in&&(c.expiry_date=new Date().getTime()+u.data.expires_in*1e3,delete c.expires_in),this.emit("tokens",c),{tokens:c,res:u}}async refreshToken(e){if(!e)return this.refreshTokenNoCache(e);if(this.refreshTokenPromises.has(e))return this.refreshTokenPromises.get(e);let r=this.refreshTokenNoCache(e).then(n=>(this.refreshTokenPromises.delete(e),n),n=>{throw this.refreshTokenPromises.delete(e),n});return this.refreshTokenPromises.set(e,r),r}async refreshTokenNoCache(e){if(!e)throw new Error("No refresh token is set.");let r=this.endpoints.oauth2TokenUrl.toString(),n={refresh_token:e,client_id:this._clientId,client_secret:this._clientSecret,grant_type:"refresh_token"},s;try{let u={...t.RETRY_CONFIG,method:"POST",url:r,data:new URLSearchParams((0,Gm.removeUndefinedValuesInObject)(n))};Jn.AuthClient.setMethodName(u,"refreshTokenNoCache"),s=await this.transporter.request(u)}catch(u){throw u instanceof Wm.GaxiosError&&u.message==="invalid_grant"&&u.response?.data&&/ReAuth/i.test(u.response.data.error_description)&&(u.message=JSON.stringify(u.response.data)),u}let i=s.data;return s.data&&s.data.expires_in&&(i.expiry_date=new Date().getTime()+s.data.expires_in*1e3,delete i.expires_in),this.emit("tokens",i),{tokens:i,res:s}}refreshAccessToken(e){if(e)this.refreshAccessTokenAsync().then(r=>e(null,r.credentials,r.res),e);else return this.refreshAccessTokenAsync()}async refreshAccessTokenAsync(){let e=await this.refreshToken(this.credentials.refresh_token),r=e.tokens;return r.refresh_token=this.credentials.refresh_token,this.credentials=r,{credentials:this.credentials,res:e.res}}getAccessToken(e){if(e)this.getAccessTokenAsync().then(r=>e(null,r.token,r.res),e);else return this.getAccessTokenAsync()}async getAccessTokenAsync(){if(!this.credentials.access_token||this.isTokenExpiring()){if(!this.credentials.refresh_token)if(this.refreshHandler){let n=await this.processAndValidateRefreshHandler();if(n?.access_token)return this.setCredentials(n),{token:this.credentials.access_token}}else throw new Error("No refresh token or refresh handler callback is set.");let r=await this.refreshAccessTokenAsync();if(!r.credentials||r.credentials&&!r.credentials.access_token)throw new Error("Could not refresh access token.");return{token:r.credentials.access_token,res:r.res}}else return{token:this.credentials.access_token}}async getRequestHeaders(e){return(await this.getRequestMetadataAsync(e)).headers}async getRequestMetadataAsync(e){let r=this.credentials;if(!r.access_token&&!r.refresh_token&&!this.apiKey&&!this.refreshHandler)throw new Error("No access, refresh token, API key or refresh handler callback is set.");if(r.access_token&&!this.isTokenExpiring()){r.token_type=r.token_type||"Bearer";let c=new Headers({authorization:r.token_type+" "+r.access_token});return{headers:this.addSharedMetadataHeaders(c)}}if(this.refreshHandler){let c=await this.processAndValidateRefreshHandler();if(c?.access_token){this.setCredentials(c);let l=new Headers({authorization:"Bearer "+this.credentials.access_token});return{headers:this.addSharedMetadataHeaders(l)}}}if(this.apiKey)return{headers:new Headers({"X-Goog-Api-Key":this.apiKey})};let n=null,s=null;try{n=await this.refreshToken(r.refresh_token),s=n.tokens}catch(c){let l=c;throw l.response&&(l.response.status===403||l.response.status===404)&&(l.message=`Could not refresh access token: ${l.message}`),l}let i=this.credentials;i.token_type=i.token_type||"Bearer",s.refresh_token=i.refresh_token,this.credentials=s;let u=new Headers({authorization:i.token_type+" "+s.access_token});return{headers:this.addSharedMetadataHeaders(u),res:n.res}}static getRevokeTokenUrl(e){return new t().getRevokeTokenURL(e).toString()}getRevokeTokenURL(e){let r=new URL(this.endpoints.oauth2RevokeUrl);return r.searchParams.append("token",e),r}revokeToken(e,r){let n={...t.RETRY_CONFIG,url:this.getRevokeTokenURL(e).toString(),method:"POST"};if(Jn.AuthClient.setMethodName(n,"revokeToken"),r)this.transporter.request(n).then(s=>r(null,s),r);else return this.transporter.request(n)}revokeCredentials(e){if(e)this.revokeCredentialsAsync().then(r=>e(null,r),e);else return this.revokeCredentialsAsync()}async revokeCredentialsAsync(){let e=this.credentials.access_token;if(this.credentials={},e)return this.revokeToken(e);throw new Error("No access token to revoke.")}request(e,r){if(r)this.requestAsync(e).then(n=>r(null,n),n=>r(n,n.response));else return this.requestAsync(e)}async requestAsync(e,r=!1){try{let n=await this.getRequestMetadataAsync();return e.headers=Wm.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,n.headers),this.apiKey&&e.headers.set("X-Goog-Api-Key",this.apiKey),await this.transporter.request(e)}catch(n){let s=n.response;if(s){let i=s.status,u=this.credentials&&this.credentials.access_token&&this.credentials.refresh_token&&(!this.credentials.expiry_date||this.forceRefreshOnFailure),c=this.credentials&&this.credentials.access_token&&!this.credentials.refresh_token&&(!this.credentials.expiry_date||this.forceRefreshOnFailure)&&this.refreshHandler,l=s.config.data instanceof AE.Readable,h=i===401||i===403;if(!r&&h&&!l&&u)return await this.refreshAccessTokenAsync(),this.requestAsync(e,!0);if(!r&&h&&!l&&c){let d=await this.processAndValidateRefreshHandler();return d?.access_token&&this.setCredentials(d),this.requestAsync(e,!0)}}throw n}}verifyIdToken(e,r){if(r&&typeof r!="function")throw new Error("This method accepts an options object as the first parameter, which includes the idToken, audience, and maxExpiry.");if(r)this.verifyIdTokenAsync(e).then(n=>r(null,n),r);else return this.verifyIdTokenAsync(e)}async verifyIdTokenAsync(e){if(!e.idToken)throw new Error("The verifyIdToken method requires an ID Token");let r=await this.getFederatedSignonCertsAsync();return await this.verifySignedJwtWithCertsAsync(e.idToken,r.certs,e.audience,this.issuers,e.maxExpiry)}async getTokenInfo(e){let{data:r}=await this.transporter.request({...t.RETRY_CONFIG,method:"POST",headers:{"content-type":"application/x-www-form-urlencoded;charset=UTF-8",authorization:`Bearer ${e}`},url:this.endpoints.tokenInfoUrl.toString()}),n=Object.assign({expiry_date:new Date().getTime()+r.expires_in*1e3,scopes:r.scope.split(" ")},r);return delete n.expires_in,delete n.scope,n}getFederatedSignonCerts(e){if(e)this.getFederatedSignonCertsAsync().then(r=>e(null,r.certs,r.res),e);else return this.getFederatedSignonCertsAsync()}async getFederatedSignonCertsAsync(){let e=new Date().getTime(),r=(0,Bc.hasBrowserCrypto)()?wr.JWK:wr.PEM;if(this.certificateExpiry&&e<this.certificateExpiry.getTime()&&this.certificateCacheFormat===r)return{certs:this.certificateCache,format:r};let n,s;switch(r){case wr.PEM:s=this.endpoints.oauth2FederatedSignonPemCertsUrl.toString();break;case wr.JWK:s=this.endpoints.oauth2FederatedSignonJwkCertsUrl.toString();break;default:throw new Error(`Unsupported certificate format ${r}`)}try{let h={...t.RETRY_CONFIG,url:s};Jn.AuthClient.setMethodName(h,"getFederatedSignonCertsAsync"),n=await this.transporter.request(h)}catch(h){throw h instanceof Error&&(h.message=`Failed to retrieve verification certificates: ${h.message}`),h}let i=n?.headers.get("cache-control"),u=-1;if(i){let h=/max-age=(?<maxAge>[0-9]+)/.exec(i)?.groups?.maxAge;h&&(u=Number(h)*1e3)}let c={};switch(r){case wr.PEM:c=n.data;break;case wr.JWK:for(let h of n.data.keys)c[h.kid]=h;break;default:throw new Error(`Unsupported certificate format ${r}`)}let l=new Date;return this.certificateExpiry=u===-1?null:new Date(l.getTime()+u),this.certificateCache=c,this.certificateCacheFormat=r,{certs:c,format:r,res:n}}getIapPublicKeys(e){if(e)this.getIapPublicKeysAsync().then(r=>e(null,r.pubkeys,r.res),e);else return this.getIapPublicKeysAsync()}async getIapPublicKeysAsync(){let e,r=this.endpoints.oauth2IapPublicKeyUrl.toString();try{let n={...t.RETRY_CONFIG,url:r};Jn.AuthClient.setMethodName(n,"getIapPublicKeysAsync"),e=await this.transporter.request(n)}catch(n){throw n instanceof Error&&(n.message=`Failed to retrieve verification certificates: ${n.message}`),n}return{pubkeys:e.data,res:e}}verifySignedJwtWithCerts(){throw new Error("verifySignedJwtWithCerts is removed, please use verifySignedJwtWithCertsAsync instead.")}async verifySignedJwtWithCertsAsync(e,r,n,s,i){let u=(0,Bc.createCrypto)();i||(i=t.DEFAULT_MAX_TOKEN_LIFETIME_SECS_);let c=e.split(".");if(c.length!==3)throw new Error("Wrong number of segments in token: "+e);let l=c[0]+"."+c[1],h=c[2],d,p;try{d=JSON.parse(u.decodeBase64StringUtf8(c[0]))}catch(b){throw b instanceof Error&&(b.message=`Can't parse token envelope: ${c[0]}': ${b.message}`),b}if(!d)throw new Error("Can't parse token envelope: "+c[0]);try{p=JSON.parse(u.decodeBase64StringUtf8(c[1]))}catch(b){throw b instanceof Error&&(b.message=`Can't parse token payload '${c[0]}`),b}if(!p)throw new Error("Can't parse token payload: "+c[1]);if(!Object.prototype.hasOwnProperty.call(r,d.kid))throw new Error("No pem found for envelope: "+JSON.stringify(d));let w=r[d.kid];if(d.alg==="ES256"&&(h=SE.joseToDer(h,"ES256").toString("base64")),!await u.verify(w,l,h))throw new Error("Invalid token signature: "+e);if(!p.iat)throw new Error("No issue time in token: "+JSON.stringify(p));if(!p.exp)throw new Error("No expiration time in token: "+JSON.stringify(p));let S=Number(p.iat);if(isNaN(S))throw new Error("iat field using invalid format");let y=Number(p.exp);if(isNaN(y))throw new Error("exp field using invalid format");let g=new Date().getTime()/1e3;if(y>=g+i)throw new Error("Expiration time too far in future: "+JSON.stringify(p));let m=S-t.CLOCK_SKEW_SECS_,v=y+t.CLOCK_SKEW_SECS_;if(g<m)throw new Error("Token used too early, "+g+" < "+m+": "+JSON.stringify(p));if(g>v)throw new Error("Token used too late, "+g+" > "+v+": "+JSON.stringify(p));if(s&&s.indexOf(p.iss)<0)throw new Error("Invalid issuer, expected one of ["+s+"], but got "+p.iss);if(typeof n<"u"&&n!==null){let b=p.aud,A=!1;if(n.constructor===Array?A=n.indexOf(b)>-1:A=b===n,!A)throw new Error("Wrong recipient, payload audience != requiredAudience")}return new vE.LoginTicket(d,p)}async processAndValidateRefreshHandler(){if(this.refreshHandler){let e=await this.refreshHandler();if(!e.access_token)throw new Error("No access token is returned by the refreshHandler callback.");return e}}isTokenExpiring(){let e=this.credentials.expiry_date;return e?e<=new Date().getTime()+this.eagerRefreshThresholdMillis:!1}};Zt.OAuth2Client=jc});var Mc=V(Pi=>{"use strict";Object.defineProperty(Pi,"__esModule",{value:!0});Pi.Compute=void 0;var kE=Ve(),Vm=Ns(),TE=pn(),Lc=class extends TE.OAuth2Client{serviceAccountEmail;scopes;constructor(e={}){super(e),this.credentials={expiry_date:1,refresh_token:"compute-placeholder"},this.serviceAccountEmail=e.serviceAccountEmail||"default",this.scopes=Array.isArray(e.scopes)?e.scopes:e.scopes?[e.scopes]:[]}async refreshTokenNoCache(){let e=`service-accounts/${this.serviceAccountEmail}/token`,r;try{let s={property:e};this.scopes.length>0&&(s.params={scopes:this.scopes.join(",")}),r=await Vm.instance(s)}catch(s){throw s instanceof kE.GaxiosError&&(s.message=`Could not refresh access token: ${s.message}`,this.wrapError(s)),s}let n=r;return r&&r.expires_in&&(n.expiry_date=new Date().getTime()+r.expires_in*1e3,delete n.expires_in),this.emit("tokens",n),{tokens:n,res:null}}async fetchIdToken(e){let r=`service-accounts/${this.serviceAccountEmail}/identity?format=full&audience=${e}`,n;try{let s={property:r};n=await Vm.instance(s)}catch(s){throw s instanceof Error&&(s.message=`Could not fetch ID token: ${s.message}`),s}return n}wrapError(e){let r=e.response;r&&r.status&&(e.status=r.status,r.status===403?e.message="A Forbidden error was returned while attempting to retrieve an access token for the Compute Engine built-in service account. This may be because the Compute Engine instance does not have the correct permission scopes specified: "+e.message:r.status===404&&(e.message="A Not Found error was returned while attempting to retrieve an accesstoken for the Compute Engine built-in service account. This may be because the Compute Engine instance does not have any permission scopes specified: "+e.message))}};Pi.Compute=Lc});var qc=V(Ii=>{"use strict";Object.defineProperty(Ii,"__esModule",{value:!0});Ii.IdTokenClient=void 0;var DE=pn(),Uc=class extends DE.OAuth2Client{targetAudience;idTokenProvider;constructor(e){super(e),this.targetAudience=e.targetAudience,this.idTokenProvider=e.idTokenProvider}async getRequestMetadataAsync(){if(!this.credentials.id_token||!this.credentials.expiry_date||this.isTokenExpiring()){let r=await this.idTokenProvider.fetchIdToken(this.targetAudience);this.credentials={id_token:r,expiry_date:this.getIdTokenExpiryDate(r)}}return{headers:new Headers({authorization:"Bearer "+this.credentials.id_token})}}getIdTokenExpiryDate(e){let r=e.split(".")[1];if(r)return JSON.parse(Buffer.from(r,"base64").toString("ascii")).exp*1e3}};Ii.IdTokenClient=Uc});var $c=V(Vn=>{"use strict";Object.defineProperty(Vn,"__esModule",{value:!0});Vn.GCPEnv=void 0;Vn.clear=RE;Vn.getEnv=xE;var Km=Ns(),er;(function(t){t.APP_ENGINE="APP_ENGINE",t.KUBERNETES_ENGINE="KUBERNETES_ENGINE",t.CLOUD_FUNCTIONS="CLOUD_FUNCTIONS",t.COMPUTE_ENGINE="COMPUTE_ENGINE",t.CLOUD_RUN="CLOUD_RUN",t.CLOUD_RUN_JOBS="CLOUD_RUN_JOBS",t.NONE="NONE"})(er||(Vn.GCPEnv=er={}));var Ls;function RE(){Ls=void 0}async function xE(){return Ls||(Ls=OE(),Ls)}async function OE(){let t=er.NONE;return FE()?t=er.APP_ENGINE:PE()?t=er.CLOUD_FUNCTIONS:await jE()?await BE()?t=er.KUBERNETES_ENGINE:IE()?t=er.CLOUD_RUN:NE()?t=er.CLOUD_RUN_JOBS:t=er.COMPUTE_ENGINE:t=er.NONE,t}function FE(){return!!(process.env.GAE_SERVICE||process.env.GAE_MODULE_NAME)}function PE(){return!!(process.env.FUNCTION_NAME||process.env.FUNCTION_TARGET)}function IE(){return!!process.env.K_CONFIGURATION}function NE(){return!!process.env.CLOUD_RUN_JOB}async function BE(){try{return await Km.instance("attributes/cluster-name"),!0}catch{return!1}}async function jE(){return Km.isAvailable()}});var zc=V((Q1,Ym)=>{var Ni=Gn().Buffer,LE=X("stream"),ME=X("util");function Bi(t){if(this.buffer=null,this.writable=!0,this.readable=!0,!t)return this.buffer=Ni.alloc(0),this;if(typeof t.pipe=="function")return this.buffer=Ni.alloc(0),t.pipe(this),this;if(t.length||typeof t=="object")return this.buffer=t,this.writable=!1,process.nextTick(function(){this.emit("end",t),this.readable=!1,this.emit("close")}.bind(this)),this;throw new TypeError("Unexpected data type ("+typeof t+")")}ME.inherits(Bi,LE);Bi.prototype.write=function(e){this.buffer=Ni.concat([this.buffer,Ni.from(e)]),this.emit("data",e)};Bi.prototype.end=function(e){e&&this.write(e),this.emit("end",e),this.emit("close"),this.writable=!1,this.readable=!1};Ym.exports=Bi});var Xm=V((X1,Qm)=>{"use strict";var Ms=X("buffer").Buffer,Hc=X("buffer").SlowBuffer;Qm.exports=ji;function ji(t,e){if(!Ms.isBuffer(t)||!Ms.isBuffer(e)||t.length!==e.length)return!1;for(var r=0,n=0;n<t.length;n++)r|=t[n]^e[n];return r===0}ji.install=function(){Ms.prototype.equal=Hc.prototype.equal=function(e){return ji(this,e)}};var UE=Ms.prototype.equal,qE=Hc.prototype.equal;ji.restore=function(){Ms.prototype.equal=UE,Hc.prototype.equal=qE}});var Vc=V((Z1,ag)=>{var Yn=Gn().Buffer,kt=X("crypto"),eg=Tc(),Zm=X("util"),$E=`"%s" is not a valid algorithm.
|
|
51
51
|
Supported algorithms are:
|
|
52
|
-
"HS256", "HS384", "HS512", "RS256", "RS384", "RS512", "PS256", "PS384", "PS512", "ES256", "ES384", "ES512" and "none".`,js="secret must be a string or buffer",Jn="key must be a string or a buffer",EE="key must be a string, a buffer or an object",qc=typeof Tt.createPublicKey=="function";qc&&(Jn+=" or a KeyObject",js+="or a KeyObject");function Um(t){if(!Vn.isBuffer(t)&&typeof t!="string"&&(!qc||typeof t!="object"||typeof t.type!="string"||typeof t.asymmetricKeyType!="string"||typeof t.export!="function"))throw $t(Jn)}function qm(t){if(!Vn.isBuffer(t)&&typeof t!="string"&&typeof t!="object")throw $t(EE)}function AE(t){if(!Vn.isBuffer(t)){if(typeof t=="string")return t;if(!qc||typeof t!="object"||t.type!=="secret"||typeof t.export!="function")throw $t(js)}}function $c(t){return t.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function $m(t){t=t.toString();var e=4-t.length%4;if(e!==4)for(var r=0;r<e;++r)t+="=";return t.replace(/\-/g,"+").replace(/_/g,"/")}function $t(t){var e=[].slice.call(arguments,1),r=Lm.format.bind(Lm,t).apply(null,e);return new TypeError(r)}function SE(t){return Vn.isBuffer(t)||typeof t=="string"}function Ls(t){return SE(t)||(t=JSON.stringify(t)),t}function zm(t){return function(r,n){AE(n),r=Ls(r);var s=Tt.createHmac("sha"+t,n),i=(s.update(r),s.digest("base64"));return $c(i)}}var Uc,kE="timingSafeEqual"in Tt?function(e,r){return e.byteLength!==r.byteLength?!1:Tt.timingSafeEqual(e,r)}:function(e,r){return Uc||(Uc=jm()),Uc(e,r)};function TE(t){return function(r,n,s){var i=zm(t)(r,s);return kE(Vn.from(n),Vn.from(i))}}function Hm(t){return function(r,n){qm(n),r=Ls(r);var s=Tt.createSign("RSA-SHA"+t),i=(s.update(r),s.sign(n,"base64"));return $c(i)}}function Wm(t){return function(r,n,s){Um(s),r=Ls(r),n=$m(n);var i=Tt.createVerify("RSA-SHA"+t);return i.update(r),i.verify(s,n,"base64")}}function DE(t){return function(r,n){qm(n),r=Ls(r);var s=Tt.createSign("RSA-SHA"+t),i=(s.update(r),s.sign({key:n,padding:Tt.constants.RSA_PKCS1_PSS_PADDING,saltLength:Tt.constants.RSA_PSS_SALTLEN_DIGEST},"base64"));return $c(i)}}function vE(t){return function(r,n,s){Um(s),r=Ls(r),n=$m(n);var i=Tt.createVerify("RSA-SHA"+t);return i.update(r),i.verify({key:s,padding:Tt.constants.RSA_PKCS1_PSS_PADDING,saltLength:Tt.constants.RSA_PSS_SALTLEN_DIGEST},n,"base64")}}function RE(t){var e=Hm(t);return function(){var n=e.apply(null,arguments);return n=Mm.derToJose(n,"ES"+t),n}}function OE(t){var e=Wm(t);return function(n,s,i){s=Mm.joseToDer(s,"ES"+t).toString("base64");var u=e(n,s,i);return u}}function xE(){return function(){return""}}function FE(){return function(e,r){return r===""}}Gm.exports=function(e){var r={hs:zm,rs:Hm,ps:DE,es:RE,none:xE},n={hs:TE,rs:Wm,ps:vE,es:OE,none:FE},s=e.match(/^(RS|PS|ES|HS)(256|384|512)$|^(none)$/);if(!s)throw $t(wE,e);var i=(s[1]||s[3]).toLowerCase(),u=s[2];return{sign:r[i](u),verify:n[i](u)}}});var Hc=V((A1,Jm)=>{var PE=Q("buffer").Buffer;Jm.exports=function(e){return typeof e=="string"?e:typeof e=="number"||PE.isBuffer(e)?e.toString():JSON.stringify(e)}});var Zm=V((S1,Qm)=>{var IE=Hn().Buffer,Vm=Lc(),NE=zc(),BE=Q("stream"),Km=Hc(),Wc=Q("util");function Ym(t,e){return IE.from(t,e).toString("base64").replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function jE(t,e,r){r=r||"utf8";var n=Ym(Km(t),"binary"),s=Ym(Km(e),r);return Wc.format("%s.%s",n,s)}function Xm(t){var e=t.header,r=t.payload,n=t.secret||t.privateKey,s=t.encoding,i=NE(e.alg),u=jE(e,r,s),c=i.sign(u,n);return Wc.format("%s.%s",u,c)}function Ii(t){var e=t.secret||t.privateKey||t.key,r=new Vm(e);this.readable=!0,this.header=t.header,this.encoding=t.encoding,this.secret=this.privateKey=this.key=r,this.payload=new Vm(t.payload),this.secret.once("close",function(){!this.payload.writable&&this.readable&&this.sign()}.bind(this)),this.payload.once("close",function(){!this.secret.writable&&this.readable&&this.sign()}.bind(this))}Wc.inherits(Ii,BE);Ii.prototype.sign=function(){try{var e=Xm({header:this.header,payload:this.payload.buffer,secret:this.secret.buffer,encoding:this.encoding});return this.emit("done",e),this.emit("data",e),this.emit("end"),this.readable=!1,e}catch(r){this.readable=!1,this.emit("error",r),this.emit("close")}};Ii.sign=Xm;Qm.exports=Ii});var cg=V((k1,ug)=>{var tg=Hn().Buffer,eg=Lc(),LE=zc(),ME=Q("stream"),rg=Hc(),UE=Q("util"),qE=/^[a-zA-Z0-9\-_]+?\.[a-zA-Z0-9\-_]+?\.([a-zA-Z0-9\-_]+)?$/;function $E(t){return Object.prototype.toString.call(t)==="[object Object]"}function zE(t){if($E(t))return t;try{return JSON.parse(t)}catch{return}}function ng(t){var e=t.split(".",1)[0];return zE(tg.from(e,"base64").toString("binary"))}function HE(t){return t.split(".",2).join(".")}function sg(t){return t.split(".")[2]}function WE(t,e){e=e||"utf8";var r=t.split(".")[1];return tg.from(r,"base64").toString(e)}function og(t){return qE.test(t)&&!!ng(t)}function ig(t,e,r){if(!e){var n=new Error("Missing algorithm parameter for jws.verify");throw n.code="MISSING_ALGORITHM",n}t=rg(t);var s=sg(t),i=HE(t),u=LE(e);return u.verify(i,s,r)}function ag(t,e){if(e=e||{},t=rg(t),!og(t))return null;var r=ng(t);if(!r)return null;var n=WE(t);return(r.typ==="JWT"||e.json)&&(n=JSON.parse(n,e.encoding)),{header:r,payload:n,signature:sg(t)}}function Kn(t){t=t||{};var e=t.secret||t.publicKey||t.key,r=new eg(e);this.readable=!0,this.algorithm=t.algorithm,this.encoding=t.encoding,this.secret=this.publicKey=this.key=r,this.signature=new eg(t.signature),this.secret.once("close",function(){!this.signature.writable&&this.readable&&this.verify()}.bind(this)),this.signature.once("close",function(){!this.secret.writable&&this.readable&&this.verify()}.bind(this))}UE.inherits(Kn,ME);Kn.prototype.verify=function(){try{var e=ig(this.signature.buffer,this.algorithm,this.key.buffer),r=ag(this.signature.buffer,this.encoding);return this.emit("done",e,r),this.emit("data",e),this.emit("end"),this.readable=!1,e}catch(n){this.readable=!1,this.emit("error",n),this.emit("close")}};Kn.decode=ag;Kn.isValid=og;Kn.verify=ig;ug.exports=Kn});var Gc=V($r=>{var lg=Zm(),Ni=cg(),GE=["HS256","HS384","HS512","RS256","RS384","RS512","PS256","PS384","PS512","ES256","ES384","ES512"];$r.ALGORITHMS=GE;$r.sign=lg.sign;$r.verify=Ni.verify;$r.decode=Ni.decode;$r.isValid=Ni.isValid;$r.createSign=function(e){return new lg(e)};$r.createVerify=function(e){return new Ni(e)}});var kg=V(ji=>{"use strict";Object.defineProperty(ji,"__esModule",{value:!0});ji.GoogleToken=void 0;var fg=Bi(Q("fs")),JE=Ve(),VE=Bi(Gc()),KE=Bi(Q("path")),YE=Q("util");function Bi(t,e){if(typeof WeakMap=="function")var r=new WeakMap,n=new WeakMap;return(Bi=function(i,u){if(!u&&i&&i.__esModule)return i;var c,l,h={__proto__:null,default:i};if(i===null||Cr(i)!="object"&&typeof i!="function")return h;if(c=u?n:r){if(c.has(i))return c.get(i);c.set(i,h)}for(var d in i)d!=="default"&&{}.hasOwnProperty.call(i,d)&&((l=(c=Object.defineProperty)&&Object.getOwnPropertyDescriptor(i,d))&&(l.get||l.set)?c(h,d,l):h[d]=i[d]);return h})(t,e)}function Cr(t){"@babel/helpers - typeof";return Cr=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Cr(t)}function XE(t,e){Cg(t,e),e.add(t)}function QE(t,e,r){Cg(t,e),e.set(t,r)}function Cg(t,e){if(e.has(t))throw new TypeError("Cannot initialize the same private elements twice on an object")}function dg(t,e,r){return t.set(zt(t,e),r),r}function hg(t,e){return t.get(zt(t,e))}function zt(t,e,r){if(typeof t=="function"?t===e:t.has(e))return arguments.length<3?e:r;throw new TypeError("Private element is not present on this object")}function pg(t,e){for(var r=0;r<e.length;r++){var n=e[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(t,Ag(n.key),n)}}function wg(t,e,r){return e&&pg(t.prototype,e),r&&pg(t,r),Object.defineProperty(t,"prototype",{writable:!1}),t}function Eg(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function ZE(t,e,r){return e=$s(e),eA(t,Qc()?Reflect.construct(e,r||[],$s(t).constructor):e.apply(t,r))}function eA(t,e){if(e&&(Cr(e)=="object"||typeof e=="function"))return e;if(e!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return tA(t)}function tA(t){if(t===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}function rA(t,e){if(typeof e!="function"&&e!==null)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),Object.defineProperty(t,"prototype",{writable:!1}),e&&qs(t,e)}function Jc(t){var e=typeof Map=="function"?new Map:void 0;return Jc=function(n){if(n===null||!sA(n))return n;if(typeof n!="function")throw new TypeError("Super expression must either be null or a function");if(e!==void 0){if(e.has(n))return e.get(n);e.set(n,s)}function s(){return nA(n,arguments,$s(this).constructor)}return s.prototype=Object.create(n.prototype,{constructor:{value:s,enumerable:!1,writable:!0,configurable:!0}}),qs(s,n)},Jc(t)}function nA(t,e,r){if(Qc())return Reflect.construct.apply(null,arguments);var n=[null];n.push.apply(n,e);var s=new(t.bind.apply(t,n));return r&&qs(s,r.prototype),s}function Qc(){try{var t=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(Qc=function(){return!!t})()}function sA(t){try{return Function.toString.call(t).indexOf("[native code]")!==-1}catch{return typeof t=="function"}}function qs(t,e){return qs=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(r,n){return r.__proto__=n,r},qs(t,e)}function $s(t){return $s=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},$s(t)}function mt(t,e,r){return(e=Ag(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function Ag(t){var e=oA(t,"string");return Cr(e)=="symbol"?e:e+""}function oA(t,e){if(Cr(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var n=r.call(t,e||"default");if(Cr(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function yt(){var t,e,r=typeof Symbol=="function"?Symbol:{},n=r.iterator||"@@iterator",s=r.toStringTag||"@@toStringTag";function i(v,S,y,g){var m=S&&S.prototype instanceof c?S:c,k=Object.create(m.prototype);return gt(k,"_invoke",(function(b,E,R){var F,$,J,M=0,X=R||[],ue=!1,re={p:0,n:0,v:t,a:fe,f:fe.bind(t,4),d:function(Ae,oe){return F=Ae,$=0,J=t,re.n=oe,u}};function fe(pe,Ae){for($=pe,J=Ae,e=0;!ue&&M&&!oe&&e<X.length;e++){var oe,me=X[e],G=re.p,K=me[2];pe>3?(oe=K===Ae)&&(J=me[($=me[4])?5:($=3,3)],me[4]=me[5]=t):me[0]<=G&&((oe=pe<2&&G<me[1])?($=0,re.v=Ae,re.n=me[1]):G<K&&(oe=pe<3||me[0]>Ae||Ae>K)&&(me[4]=pe,me[5]=Ae,re.n=K,$=0))}if(oe||pe>1)return u;throw ue=!0,Ae}return function(pe,Ae,oe){if(M>1)throw TypeError("Generator is already running");for(ue&&Ae===1&&fe(Ae,oe),$=Ae,J=oe;(e=$<2?t:J)||!ue;){F||($?$<3?($>1&&(re.n=-1),fe($,J)):re.n=J:re.v=J);try{if(M=2,F){if($||(pe="next"),e=F[pe]){if(!(e=e.call(F,J)))throw TypeError("iterator result is not an object");if(!e.done)return e;J=e.value,$<2&&($=0)}else $===1&&(e=F.return)&&e.call(F),$<2&&(J=TypeError("The iterator does not provide a '"+pe+"' method"),$=1);F=t}else if((e=(ue=re.n<0)?J:b.call(E,re))!==u)break}catch(me){F=t,$=1,J=me}finally{M=1}}return{value:e,done:ue}}})(v,y,g),!0),k}var u={};function c(){}function l(){}function h(){}e=Object.getPrototypeOf;var d=[][n]?e(e([][n]())):(gt(e={},n,function(){return this}),e),p=h.prototype=c.prototype=Object.create(d);function A(v){return Object.setPrototypeOf?Object.setPrototypeOf(v,h):(v.__proto__=h,gt(v,s,"GeneratorFunction")),v.prototype=Object.create(p),v}return l.prototype=h,gt(p,"constructor",h),gt(h,"constructor",l),l.displayName="GeneratorFunction",gt(h,s,"GeneratorFunction"),gt(p),gt(p,s,"Generator"),gt(p,n,function(){return this}),gt(p,"toString",function(){return"[object Generator]"}),(yt=function(){return{w:i,m:A}})()}function gt(t,e,r,n){var s=Object.defineProperty;try{s({},"",{})}catch{s=0}gt=function(u,c,l,h){if(c)s?s(u,c,{value:l,enumerable:!h,configurable:!h,writable:!h}):u[c]=l;else{var d=function(A,v){gt(u,A,function(S){return this._invoke(A,v,S)})};d("next",0),d("throw",1),d("return",2)}},gt(t,e,r,n)}function mg(t,e,r,n,s,i,u){try{var c=t[i](u),l=c.value}catch(h){return void r(h)}c.done?e(l):Promise.resolve(l).then(n,s)}function Yn(t){return function(){var e=this,r=arguments;return new Promise(function(n,s){var i=t.apply(e,r);function u(l){mg(i,n,s,u,c,"next",l)}function c(l){mg(i,n,s,u,c,"throw",l)}u(void 0)})}}var gg=fg.readFile?(0,YE.promisify)(fg.readFile):Yn(yt().m(function t(){return yt().w(function(e){for(;;)switch(e.n){case 0:throw new Us("use key rather than keyFile.","MISSING_CREDENTIALS");case 1:return e.a(2)}},t)})),yg="https://oauth2.googleapis.com/token",iA="https://oauth2.googleapis.com/revoke?token=",Us=(function(t){function e(r,n){var s;return Eg(this,e),s=ZE(this,e,[r]),mt(s,"code",void 0),s.code=n,s}return rA(e,t),wg(e)})(Jc(Error)),Ms=new WeakMap,er=new WeakSet,D1=ji.GoogleToken=(function(){function t(e){Eg(this,t),XE(this,er),mt(this,"expiresAt",void 0),mt(this,"key",void 0),mt(this,"keyFile",void 0),mt(this,"iss",void 0),mt(this,"sub",void 0),mt(this,"scope",void 0),mt(this,"rawToken",void 0),mt(this,"tokenExpires",void 0),mt(this,"email",void 0),mt(this,"additionalClaims",void 0),mt(this,"eagerRefreshThresholdMillis",void 0),mt(this,"transporter",{request:function(n){return(0,JE.request)(n)}}),QE(this,Ms,void 0),zt(er,this,Sg).call(this,e)}return wg(t,[{key:"accessToken",get:function(){return this.rawToken?this.rawToken.access_token:void 0}},{key:"idToken",get:function(){return this.rawToken?this.rawToken.id_token:void 0}},{key:"tokenType",get:function(){return this.rawToken?this.rawToken.token_type:void 0}},{key:"refreshToken",get:function(){return this.rawToken?this.rawToken.refresh_token:void 0}},{key:"hasExpired",value:function(){var r=new Date().getTime();return this.rawToken&&this.expiresAt?r>=this.expiresAt:!0}},{key:"isTokenExpiring",value:function(){var r,n=new Date().getTime(),s=(r=this.eagerRefreshThresholdMillis)!==null&&r!==void 0?r:0;return this.rawToken&&this.expiresAt?this.expiresAt<=n+s:!0}},{key:"getToken",value:function(r){var n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(Cr(r)==="object"&&(n=r,r=void 0),n=Object.assign({forceRefresh:!1},n),r){var s=r;zt(er,this,_g).call(this,n).then(function(i){return s(null,i)},r);return}return zt(er,this,_g).call(this,n)}},{key:"getCredentials",value:(function(){var e=Yn(yt().m(function n(s){var i,u,c,l,h,d,p;return yt().w(function(A){for(;;)switch(A.n){case 0:i=KE.extname(s),p=i,A.n=p===".json"?1:p===".der"||p===".crt"||p===".pem"?4:p===".p12"||p===".pfx"?6:7;break;case 1:return A.n=2,gg(s,"utf8");case 2:if(u=A.v,c=JSON.parse(u),l=c.private_key,h=c.client_email,!(!l||!h)){A.n=3;break}throw new Us("private_key and client_email are required.","MISSING_CREDENTIALS");case 3:return A.a(2,{privateKey:l,clientEmail:h});case 4:return A.n=5,gg(s,"utf8");case 5:return d=A.v,A.a(2,{privateKey:d});case 6:throw new Us("*.p12 certificates are not supported after v6.1.2. Consider utilizing *.json format or converting *.p12 to *.pem using the OpenSSL CLI.","UNKNOWN_CERTIFICATE_TYPE");case 7:throw new Us("Unknown certificate type. Type is determined based on file extension. Current supported extensions are *.json, and *.pem.","UNKNOWN_CERTIFICATE_TYPE");case 8:return A.a(2)}},n)}));function r(n){return e.apply(this,arguments)}return r})()},{key:"revokeToken",value:function(r){if(r){zt(er,this,bg).call(this).then(function(){return r()},r);return}return zt(er,this,bg).call(this)}}])})();function _g(t){return Vc.apply(this,arguments)}function Vc(){return Vc=Yn(yt().m(function t(e){return yt().w(function(r){for(;;)switch(r.n){case 0:if(!(hg(Ms,this)&&!e.forceRefresh)){r.n=1;break}return r.a(2,hg(Ms,this));case 1:return r.p=1,r.n=2,dg(Ms,this,zt(er,this,aA).call(this,e));case 2:return r.a(2,r.v);case 3:return r.p=3,dg(Ms,this,void 0),r.f(3);case 4:return r.a(2)}},t,this,[[1,,3,4]])})),Vc.apply(this,arguments)}function aA(t){return Kc.apply(this,arguments)}function Kc(){return Kc=Yn(yt().m(function t(e){var r;return yt().w(function(n){for(;;)switch(n.n){case 0:if(!(this.isTokenExpiring()===!1&&e.forceRefresh===!1)){n.n=1;break}return n.a(2,Promise.resolve(this.rawToken));case 1:if(!(!this.key&&!this.keyFile)){n.n=2;break}throw new Error("No key or keyFile set.");case 2:if(!(!this.key&&this.keyFile)){n.n=4;break}return n.n=3,this.getCredentials(this.keyFile);case 3:r=n.v,this.key=r.privateKey,this.iss=r.clientEmail||this.iss,r.clientEmail||zt(er,this,uA).call(this);case 4:return n.a(2,zt(er,this,cA).call(this))}},t,this)})),Kc.apply(this,arguments)}function uA(){if(!this.iss)throw new Us("email is required.","MISSING_CREDENTIALS")}function bg(){return Yc.apply(this,arguments)}function Yc(){return Yc=Yn(yt().m(function t(){var e;return yt().w(function(r){for(;;)switch(r.n){case 0:if(this.accessToken){r.n=1;break}throw new Error("No token to revoke.");case 1:return e=iA+this.accessToken,r.n=2,this.transporter.request({url:e,retry:!0});case 2:zt(er,this,Sg).call(this,{email:this.iss,sub:this.sub,key:this.key,keyFile:this.keyFile,scope:this.scope,additionalClaims:this.additionalClaims});case 3:return r.a(2)}},t,this)})),Yc.apply(this,arguments)}function Sg(){var t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};this.keyFile=t.keyFile,this.key=t.key,this.rawToken=void 0,this.iss=t.email||t.iss,this.sub=t.sub,this.additionalClaims=t.additionalClaims,Cr(t.scope)==="object"?this.scope=t.scope.join(" "):this.scope=t.scope,this.eagerRefreshThresholdMillis=t.eagerRefreshThresholdMillis,t.transporter&&(this.transporter=t.transporter)}function cA(){return Xc.apply(this,arguments)}function Xc(){return Xc=Yn(yt().m(function t(){var e,r,n,s,i,u,c,l,h,d;return yt().w(function(p){for(;;)switch(p.n){case 0:return e=Math.floor(new Date().getTime()/1e3),r=this.additionalClaims||{},n=Object.assign({iss:this.iss,scope:this.scope,aud:yg,exp:e+3600,iat:e,sub:this.sub},r),s=VE.sign({header:{alg:"RS256"},payload:n,secret:this.key}),p.p=1,p.n=2,this.transporter.request({method:"POST",url:yg,data:new URLSearchParams({grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:s}),responseType:"json",retryConfig:{httpMethodsToRetry:["POST"]}});case 2:return i=p.v,this.rawToken=i.data,this.expiresAt=i.data.expires_in===null||i.data.expires_in===void 0?void 0:(e+i.data.expires_in)*1e3,p.a(2,this.rawToken);case 3:throw p.p=3,d=p.v,this.rawToken=void 0,this.tokenExpires=void 0,l=d.response&&(u=d.response)!==null&&u!==void 0&&u.data?(c=d.response)===null||c===void 0?void 0:c.data:{},l.error&&(h=l.error_description?": ".concat(l.error_description):"",d.message="".concat(l.error).concat(h)),d;case 4:return p.a(2)}},t,this,[[1,3]])})),Xc.apply(this,arguments)}});var el=V(Li=>{"use strict";Object.defineProperty(Li,"__esModule",{value:!0});Li.JWTAccess=void 0;var lA=Gc(),fA=Ut(),Tg={alg:"RS256",typ:"JWT"},Zc=class t{email;key;keyId;projectId;eagerRefreshThresholdMillis;cache=new fA.LRUCache({capacity:500,maxAge:3600*1e3});constructor(e,r,n,s){this.email=e,this.key=r,this.keyId=n,this.eagerRefreshThresholdMillis=s??300*1e3}getCachedKey(e,r){let n=e;if(r&&Array.isArray(r)&&r.length?n=e?`${e}_${r.join("_")}`:`${r.join("_")}`:typeof r=="string"&&(n=e?`${e}_${r}`:r),!n)throw Error("Scopes or url must be provided");return n}getRequestHeaders(e,r,n){let s=this.getCachedKey(e,n),i=this.cache.get(s),u=Date.now();if(i&&i.expiration-u>this.eagerRefreshThresholdMillis)return new Headers(i.headers);let c=Math.floor(Date.now()/1e3),l=t.getExpirationTime(c),h;if(Array.isArray(n)&&(n=n.join(" ")),n?h={iss:this.email,sub:this.email,scope:n,exp:l,iat:c}:h={iss:this.email,sub:this.email,aud:e,exp:l,iat:c},r){for(let S in h)if(r[S])throw new Error(`The '${S}' property is not allowed when passing additionalClaims. This claim is included in the JWT by default.`)}let d=this.keyId?{...Tg,kid:this.keyId}:Tg,p=Object.assign(h,r),A=lA.sign({header:d,payload:p,secret:this.key}),v=new Headers({authorization:`Bearer ${A}`});return this.cache.set(s,{expiration:l*1e3,headers:v}),v}static getExpirationTime(e){return e+3600}fromJSON(e){if(!e)throw new Error("Must pass in a JSON object containing the service account auth settings.");if(!e.client_email)throw new Error("The incoming JSON object does not contain a client_email field");if(!e.private_key)throw new Error("The incoming JSON object does not contain a private_key field");this.email=e.client_email,this.key=e.private_key,this.keyId=e.private_key_id,this.projectId=e.project_id}fromStream(e,r){if(r)this.fromStreamAsync(e).then(()=>r(),r);else return this.fromStreamAsync(e)}fromStreamAsync(e){return new Promise((r,n)=>{e||n(new Error("Must pass in a stream containing the service account auth settings."));let s="";e.setEncoding("utf8").on("data",i=>s+=i).on("error",n).on("end",()=>{try{let i=JSON.parse(s);this.fromJSON(i),r()}catch(i){n(i)}})})}};Li.JWTAccess=Zc});var rl=V(Ui=>{"use strict";Object.defineProperty(Ui,"__esModule",{value:!0});Ui.JWT=void 0;var Dg=kg(),dA=el(),hA=fn(),Mi=pt(),tl=class t extends hA.OAuth2Client{email;keyFile;key;keyId;defaultScopes;scopes;scope;subject;gtoken;additionalClaims;useJWTAccessWithScope;defaultServicePath;access;constructor(e={}){super(e),this.email=e.email,this.keyFile=e.keyFile,this.key=e.key,this.keyId=e.keyId,this.scopes=e.scopes,this.subject=e.subject,this.additionalClaims=e.additionalClaims,this.credentials={refresh_token:"jwt-placeholder",expiry_date:1}}createScoped(e){let r=new t(this);return r.scopes=e,r}async getRequestMetadataAsync(e){e=this.defaultServicePath?`https://${this.defaultServicePath}/`:e;let r=!this.hasUserScopes()&&e||this.useJWTAccessWithScope&&this.hasAnyScopes()||this.universeDomain!==Mi.DEFAULT_UNIVERSE;if(this.subject&&this.universeDomain!==Mi.DEFAULT_UNIVERSE)throw new RangeError(`Service Account user is configured for the credential. Domain-wide delegation is not supported in universes other than ${Mi.DEFAULT_UNIVERSE}`);if(!this.apiKey&&r)if(this.additionalClaims&&this.additionalClaims.target_audience){let{tokens:n}=await this.refreshToken();return{headers:this.addSharedMetadataHeaders(new Headers({authorization:`Bearer ${n.id_token}`}))}}else{this.access||(this.access=new dA.JWTAccess(this.email,this.key,this.keyId,this.eagerRefreshThresholdMillis));let n;this.hasUserScopes()?n=this.scopes:e||(n=this.defaultScopes);let s=this.useJWTAccessWithScope||this.universeDomain!==Mi.DEFAULT_UNIVERSE,i=await this.access.getRequestHeaders(e??void 0,this.additionalClaims,s?n:void 0);return{headers:this.addSharedMetadataHeaders(i)}}else return this.hasAnyScopes()||this.apiKey?super.getRequestMetadataAsync(e):{headers:new Headers}}async fetchIdToken(e){let r=new Dg.GoogleToken({iss:this.email,sub:this.subject,scope:this.scopes||this.defaultScopes,keyFile:this.keyFile,key:this.key,additionalClaims:{target_audience:e},transporter:this.transporter});if(await r.getToken({forceRefresh:!0}),!r.idToken)throw new Error("Unknown error: Failed to fetch ID token");return r.idToken}hasUserScopes(){return this.scopes?this.scopes.length>0:!1}hasAnyScopes(){return!!(this.scopes&&this.scopes.length>0||this.defaultScopes&&this.defaultScopes.length>0)}authorize(e){if(e)this.authorizeAsync().then(r=>e(null,r),e);else return this.authorizeAsync()}async authorizeAsync(){let e=await this.refreshToken();if(!e)throw new Error("No result returned");return this.credentials=e.tokens,this.credentials.refresh_token="jwt-placeholder",this.key=this.gtoken.key,this.email=this.gtoken.iss,e.tokens}async refreshTokenNoCache(){let e=this.createGToken(),n={access_token:(await e.getToken({forceRefresh:this.isTokenExpiring()})).access_token,token_type:"Bearer",expiry_date:e.expiresAt,id_token:e.idToken};return this.emit("tokens",n),{res:null,tokens:n}}createGToken(){return this.gtoken||(this.gtoken=new Dg.GoogleToken({iss:this.email,sub:this.subject,scope:this.scopes||this.defaultScopes,keyFile:this.keyFile,key:this.key,additionalClaims:this.additionalClaims,transporter:this.transporter})),this.gtoken}fromJSON(e){if(!e)throw new Error("Must pass in a JSON object containing the service account auth settings.");if(!e.client_email)throw new Error("The incoming JSON object does not contain a client_email field");if(!e.private_key)throw new Error("The incoming JSON object does not contain a private_key field");this.email=e.client_email,this.key=e.private_key,this.keyId=e.private_key_id,this.projectId=e.project_id,this.quotaProjectId=e.quota_project_id,this.universeDomain=e.universe_domain||this.universeDomain}fromStream(e,r){if(r)this.fromStreamAsync(e).then(()=>r(),r);else return this.fromStreamAsync(e)}fromStreamAsync(e){return new Promise((r,n)=>{if(!e)throw new Error("Must pass in a stream containing the service account auth settings.");let s="";e.setEncoding("utf8").on("error",n).on("data",i=>s+=i).on("end",()=>{try{let i=JSON.parse(s);this.fromJSON(i),r()}catch(i){n(i)}})})}fromAPIKey(e){if(typeof e!="string")throw new Error("Must provide an API Key string.");this.apiKey=e}async getCredentials(){if(this.key)return{private_key:this.key,client_email:this.email};if(this.keyFile){let r=await this.createGToken().getCredentials(this.keyFile);return{private_key:r.privateKey,client_email:r.clientEmail}}throw new Error("A key or a keyFile must be provided to getCredentials.")}};Ui.JWT=tl});var sl=V(Xn=>{"use strict";Object.defineProperty(Xn,"__esModule",{value:!0});Xn.UserRefreshClient=Xn.USER_REFRESH_ACCOUNT_TYPE=void 0;var pA=fn(),mA=pt();Xn.USER_REFRESH_ACCOUNT_TYPE="authorized_user";var nl=class t extends pA.OAuth2Client{_refreshToken;constructor(e,r,n,s,i){let u=e&&typeof e=="object"?e:{clientId:e,clientSecret:r,refreshToken:n,eagerRefreshThresholdMillis:s,forceRefreshOnFailure:i};super(u),this._refreshToken=u.refreshToken,this.credentials.refresh_token=u.refreshToken}async refreshTokenNoCache(){return super.refreshTokenNoCache(this._refreshToken)}async fetchIdToken(e){let r={...t.RETRY_CONFIG,url:this.endpoints.oauth2TokenUrl,method:"POST",data:new URLSearchParams({client_id:this._clientId,client_secret:this._clientSecret,grant_type:"refresh_token",refresh_token:this._refreshToken,target_audience:e})};return mA.AuthClient.setMethodName(r,"fetchIdToken"),(await this.transporter.request(r)).data.id_token}fromJSON(e){if(!e)throw new Error("Must pass in a JSON object containing the user refresh token");if(e.type!=="authorized_user")throw new Error('The incoming JSON object does not have the "authorized_user" type');if(!e.client_id)throw new Error("The incoming JSON object does not contain a client_id field");if(!e.client_secret)throw new Error("The incoming JSON object does not contain a client_secret field");if(!e.refresh_token)throw new Error("The incoming JSON object does not contain a refresh_token field");this._clientId=e.client_id,this._clientSecret=e.client_secret,this._refreshToken=e.refresh_token,this.credentials.refresh_token=e.refresh_token,this.quotaProjectId=e.quota_project_id,this.universeDomain=e.universe_domain||this.universeDomain}fromStream(e,r){if(r)this.fromStreamAsync(e).then(()=>r(),r);else return this.fromStreamAsync(e)}async fromStreamAsync(e){return new Promise((r,n)=>{if(!e)return n(new Error("Must pass in a stream containing the user refresh token."));let s="";e.setEncoding("utf8").on("error",n).on("data",i=>s+=i).on("end",()=>{try{let i=JSON.parse(s);return this.fromJSON(i),r()}catch(i){return n(i)}})})}static fromJSON(e){let r=new t;return r.fromJSON(e),r}};Xn.UserRefreshClient=nl});var il=V(Qn=>{"use strict";Object.defineProperty(Qn,"__esModule",{value:!0});Qn.Impersonated=Qn.IMPERSONATED_ACCOUNT_TYPE=void 0;var vg=fn(),gA=Ve(),yA=Ut();Qn.IMPERSONATED_ACCOUNT_TYPE="impersonated_service_account";var ol=class t extends vg.OAuth2Client{sourceClient;targetPrincipal;targetScopes;delegates;lifetime;endpoint;constructor(e={}){if(super(e),console.warn("The `Impersonated` constructor does not validate the credential configuration. A security risk occurs when a credential configuration configured with malicious URLs is used. When the credential configuration is accepted from an untrusted source, you should validate it before using it with this method. For more details, see https://cloud.google.com/docs/authentication/external/externally-sourced-credentials."),this.credentials={expiry_date:1,refresh_token:"impersonated-placeholder"},this.sourceClient=e.sourceClient??new vg.OAuth2Client,this.targetPrincipal=e.targetPrincipal??"",this.delegates=e.delegates??[],this.targetScopes=e.targetScopes??[],this.lifetime=e.lifetime??3600,!!!(0,yA.originalOrCamelOptions)(e).get("universe_domain"))this.universeDomain=this.sourceClient.universeDomain;else if(this.sourceClient.universeDomain!==this.universeDomain)throw new RangeError(`Universe domain ${this.sourceClient.universeDomain} in source credentials does not match ${this.universeDomain} universe domain set for impersonated credentials.`);this.endpoint=e.endpoint??`https://iamcredentials.${this.universeDomain}`}async sign(e){await this.sourceClient.getAccessToken();let r=`projects/-/serviceAccounts/${this.targetPrincipal}`,n=`${this.endpoint}/v1/${r}:signBlob`,s={delegates:this.delegates,payload:Buffer.from(e).toString("base64")};return(await this.sourceClient.request({...t.RETRY_CONFIG,url:n,data:s,method:"POST"})).data}getTargetPrincipal(){return this.targetPrincipal}async refreshToken(){try{await this.sourceClient.getAccessToken();let e="projects/-/serviceAccounts/"+this.targetPrincipal,r=`${this.endpoint}/v1/${e}:generateAccessToken`,n={delegates:this.delegates,scope:this.targetScopes,lifetime:this.lifetime+"s"},s=await this.sourceClient.request({...t.RETRY_CONFIG,url:r,data:n,method:"POST"}),i=s.data;return this.credentials.access_token=i.accessToken,this.credentials.expiry_date=Date.parse(i.expireTime),{tokens:this.credentials,res:s}}catch(e){if(!(e instanceof Error))throw e;let r=0,n="";throw e instanceof gA.GaxiosError&&(r=e?.response?.data?.error?.status,n=e?.response?.data?.error?.message),r&&n?(e.message=`${r}: unable to impersonate: ${n}`,e):(e.message=`unable to impersonate: ${e}`,e)}}async fetchIdToken(e,r){await this.sourceClient.getAccessToken();let n=`projects/-/serviceAccounts/${this.targetPrincipal}`,s=`${this.endpoint}/v1/${n}:generateIdToken`,i={delegates:this.delegates,audience:e,includeEmail:r?.includeEmail??!0,useEmailAzp:r?.includeEmail??!0};return(await this.sourceClient.request({...t.RETRY_CONFIG,url:s,data:i,method:"POST"})).data.token}};Qn.Impersonated=ol});var ul=V(zs=>{"use strict";Object.defineProperty(zs,"__esModule",{value:!0});zs.OAuthClientAuthHandler=void 0;zs.getErrorFromOAuthErrorResponse=CA;var Zn=Ve(),_A=Ps(),bA=["PUT","POST","PATCH"],al=class{#e=(0,_A.createCrypto)();#t;transporter;constructor(e){e&&"clientId"in e?(this.#t=e,this.transporter=new Zn.Gaxios):(this.#t=e?.clientAuthentication,this.transporter=e?.transporter||new Zn.Gaxios)}applyClientAuthenticationOptions(e,r){e.headers=Zn.Gaxios.mergeHeaders(e.headers),this.injectAuthenticatedHeaders(e,r),r||this.injectAuthenticatedRequestBody(e)}injectAuthenticatedHeaders(e,r){if(r)e.headers=Zn.Gaxios.mergeHeaders(e.headers,{authorization:`Bearer ${r}`});else if(this.#t?.confidentialClientType==="basic"){e.headers=Zn.Gaxios.mergeHeaders(e.headers);let n=this.#t.clientId,s=this.#t.clientSecret||"",i=this.#e.encodeBase64StringUtf8(`${n}:${s}`);Zn.Gaxios.mergeHeaders(e.headers,{authorization:`Basic ${i}`})}}injectAuthenticatedRequestBody(e){if(this.#t?.confidentialClientType==="request-body"){let r=(e.method||"GET").toUpperCase();if(!bA.includes(r))throw new Error(`${r} HTTP method does not support ${this.#t.confidentialClientType} client authentication`);let s=new Headers(e.headers).get("content-type");if(s?.startsWith("application/x-www-form-urlencoded")||e.data instanceof URLSearchParams){let i=new URLSearchParams(e.data??"");i.append("client_id",this.#t.clientId),i.append("client_secret",this.#t.clientSecret||""),e.data=i}else if(s?.startsWith("application/json"))e.data=e.data||{},Object.assign(e.data,{client_id:this.#t.clientId,client_secret:this.#t.clientSecret||""});else throw new Error(`${s} content-types are not supported with ${this.#t.confidentialClientType} client authentication`)}}static get RETRY_CONFIG(){return{retry:!0,retryConfig:{httpMethodsToRetry:["GET","PUT","POST","HEAD","OPTIONS","DELETE"]}}}};zs.OAuthClientAuthHandler=al;function CA(t,e){let r=t.error,n=t.error_description,s=t.error_uri,i=`Error code ${r}`;typeof n<"u"&&(i+=`: ${n}`),typeof s<"u"&&(i+=` - ${s}`);let u=new Error(i);if(e){let c=Object.keys(e);e.stack&&c.push("stack"),c.forEach(l=>{l!=="message"&&Object.defineProperty(u,l,{value:e[l],writable:!1,enumerable:!0})})}return u}});var $i=V(qi=>{"use strict";Object.defineProperty(qi,"__esModule",{value:!0});qi.StsCredentials=void 0;var wA=Ve(),EA=pt(),Rg=ul(),AA=Ut(),cl=class t extends Rg.OAuthClientAuthHandler{#e;constructor(e={tokenExchangeEndpoint:""},r){(typeof e!="object"||e instanceof URL)&&(e={tokenExchangeEndpoint:e,clientAuthentication:r}),super(e),this.#e=e.tokenExchangeEndpoint}async exchangeToken(e,r,n){let s={grant_type:e.grantType,resource:e.resource,audience:e.audience,scope:e.scope?.join(" "),requested_token_type:e.requestedTokenType,subject_token:e.subjectToken,subject_token_type:e.subjectTokenType,actor_token:e.actingParty?.actorToken,actor_token_type:e.actingParty?.actorTokenType,options:n&&JSON.stringify(n)},i={...t.RETRY_CONFIG,url:this.#e.toString(),method:"POST",headers:r,data:new URLSearchParams((0,AA.removeUndefinedValuesInObject)(s))};EA.AuthClient.setMethodName(i,"exchangeToken"),this.applyClientAuthenticationOptions(i);try{let u=await this.transporter.request(i),c=u.data;return c.res=u,c}catch(u){throw u instanceof wA.GaxiosError&&u.response?(0,Rg.getErrorFromOAuthErrorResponse)(u.response.data,u):u}}};qi.StsCredentials=cl});var zr=V(Dt=>{"use strict";Object.defineProperty(Dt,"__esModule",{value:!0});Dt.BaseExternalAccountClient=Dt.CLOUD_RESOURCE_MANAGER=Dt.EXTERNAL_ACCOUNT_TYPE=Dt.EXPIRATION_TIME_OFFSET=void 0;var SA=Ve(),kA=Q("stream"),ll=pt(),TA=$i(),Og=Ut(),DA=kc(),vA="urn:ietf:params:oauth:grant-type:token-exchange",RA="urn:ietf:params:oauth:token-type:access_token",fl="https://www.googleapis.com/auth/cloud-platform",OA=3600;Dt.EXPIRATION_TIME_OFFSET=300*1e3;Dt.EXTERNAL_ACCOUNT_TYPE="external_account";Dt.CLOUD_RESOURCE_MANAGER="https://cloudresourcemanager.googleapis.com/v1/projects/";var xA="//iam\\.googleapis\\.com/locations/[^/]+/workforcePools/[^/]+/providers/.+",FA="https://sts.{universeDomain}/v1/token",dl=class t extends ll.AuthClient{scopes;projectNumber;audience;subjectTokenType;stsCredential;clientAuth;credentialSourceType;cachedAccessToken;serviceAccountImpersonationUrl;serviceAccountImpersonationLifetime;workforcePoolUserProject;configLifetimeRequested;tokenUrl;cloudResourceManagerURL;supplierContext;#e=null;constructor(e){super(e);let r=(0,Og.originalOrCamelOptions)(e),n=r.get("type");if(n&&n!==Dt.EXTERNAL_ACCOUNT_TYPE)throw new Error(`Expected "${Dt.EXTERNAL_ACCOUNT_TYPE}" type but received "${e.type}"`);let s=r.get("client_id"),i=r.get("client_secret");this.tokenUrl=r.get("token_url")??FA.replace("{universeDomain}",this.universeDomain);let u=r.get("subject_token_type"),c=r.get("workforce_pool_user_project"),l=r.get("service_account_impersonation_url"),h=r.get("service_account_impersonation"),d=(0,Og.originalOrCamelOptions)(h).get("token_lifetime_seconds");this.cloudResourceManagerURL=new URL(r.get("cloud_resource_manager_url")||`https://cloudresourcemanager.${this.universeDomain}/v1/projects/`),s&&(this.clientAuth={confidentialClientType:"basic",clientId:s,clientSecret:i}),this.stsCredential=new TA.StsCredentials({tokenExchangeEndpoint:this.tokenUrl,clientAuthentication:this.clientAuth}),this.scopes=r.get("scopes")||[fl],this.cachedAccessToken=null,this.audience=r.get("audience"),this.subjectTokenType=u,this.workforcePoolUserProject=c;let p=new RegExp(xA);if(this.workforcePoolUserProject&&!this.audience.match(p))throw new Error("workforcePoolUserProject should not be set for non-workforce pool credentials.");this.serviceAccountImpersonationUrl=l,this.serviceAccountImpersonationLifetime=d,this.serviceAccountImpersonationLifetime?this.configLifetimeRequested=!0:(this.configLifetimeRequested=!1,this.serviceAccountImpersonationLifetime=OA),this.projectNumber=this.getProjectNumber(this.audience),this.supplierContext={audience:this.audience,subjectTokenType:this.subjectTokenType,transporter:this.transporter}}getServiceAccountEmail(){if(this.serviceAccountImpersonationUrl){if(this.serviceAccountImpersonationUrl.length>256)throw new RangeError(`URL is too long: ${this.serviceAccountImpersonationUrl}`);return/serviceAccounts\/(?<email>[^:]+):generateAccessToken$/.exec(this.serviceAccountImpersonationUrl)?.groups?.email||null}return null}setCredentials(e){super.setCredentials(e),this.cachedAccessToken=e}async getAccessToken(){return(!this.cachedAccessToken||this.isExpired(this.cachedAccessToken))&&await this.refreshAccessTokenAsync(),{token:this.cachedAccessToken.access_token,res:this.cachedAccessToken.res}}async getRequestHeaders(){let e=await this.getAccessToken(),r=new Headers({authorization:`Bearer ${e.token}`});return this.addSharedMetadataHeaders(r)}request(e,r){if(r)this.requestAsync(e).then(n=>r(null,n),n=>r(n,n.response));else return this.requestAsync(e)}async getProjectId(){let e=this.projectNumber||this.workforcePoolUserProject;if(this.projectId)return this.projectId;if(e){let r=await this.getRequestHeaders(),n={...t.RETRY_CONFIG,headers:r,url:`${this.cloudResourceManagerURL.toString()}${e}`};ll.AuthClient.setMethodName(n,"getProjectId");let s=await this.transporter.request(n);return this.projectId=s.data.projectId,this.projectId}return null}async requestAsync(e,r=!1){let n;try{let s=await this.getRequestHeaders();e.headers=SA.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,s),n=await this.transporter.request(e)}catch(s){let i=s.response;if(i){let u=i.status,c=i.config.data instanceof kA.Readable;if(!r&&(u===401||u===403)&&!c&&this.forceRefreshOnFailure)return await this.refreshAccessTokenAsync(),await this.requestAsync(e,!0)}throw s}return n}async refreshAccessTokenAsync(){this.#e=this.#e||this.#t();try{return await this.#e}finally{this.#e=null}}async#t(){let e=await this.retrieveSubjectToken(),r={grantType:vA,audience:this.audience,requestedTokenType:RA,subjectToken:e,subjectTokenType:this.subjectTokenType,scope:this.serviceAccountImpersonationUrl?[fl]:this.getScopesArray()},n=!this.clientAuth&&this.workforcePoolUserProject?{userProject:this.workforcePoolUserProject}:void 0,s=new Headers({"x-goog-api-client":this.getMetricsHeaderValue()}),i=await this.stsCredential.exchangeToken(r,s,n);return this.serviceAccountImpersonationUrl?this.cachedAccessToken=await this.getImpersonatedAccessToken(i.access_token):i.expires_in?this.cachedAccessToken={access_token:i.access_token,expiry_date:new Date().getTime()+i.expires_in*1e3,res:i.res}:this.cachedAccessToken={access_token:i.access_token,res:i.res},this.credentials={},Object.assign(this.credentials,this.cachedAccessToken),delete this.credentials.res,this.emit("tokens",{refresh_token:null,expiry_date:this.cachedAccessToken.expiry_date,access_token:this.cachedAccessToken.access_token,token_type:"Bearer",id_token:null}),this.cachedAccessToken}getProjectNumber(e){let r=e.match(/\/projects\/([^/]+)/);return r?r[1]:null}async getImpersonatedAccessToken(e){let r={...t.RETRY_CONFIG,url:this.serviceAccountImpersonationUrl,method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e}`},data:{scope:this.getScopesArray(),lifetime:this.serviceAccountImpersonationLifetime+"s"}};ll.AuthClient.setMethodName(r,"getImpersonatedAccessToken");let n=await this.transporter.request(r),s=n.data;return{access_token:s.accessToken,expiry_date:new Date(s.expireTime).getTime(),res:n}}isExpired(e){let r=new Date().getTime();return e.expiry_date?r>=e.expiry_date-this.eagerRefreshThresholdMillis:!1}getScopesArray(){return typeof this.scopes=="string"?[this.scopes]:this.scopes||[fl]}getMetricsHeaderValue(){let e=process.version.replace(/^v/,""),r=this.serviceAccountImpersonationUrl!==void 0,n=this.credentialSourceType?this.credentialSourceType:"unknown";return`gl-node/${e} auth/${DA.pkg.version} google-byoid-sdk source/${n} sa-impersonation/${r} config-lifetime/${this.configLifetimeRequested}`}getTokenUrl(){return this.tokenUrl}};Dt.BaseExternalAccountClient=dl});var xg=V(zi=>{"use strict";Object.defineProperty(zi,"__esModule",{value:!0});zi.FileSubjectTokenSupplier=void 0;var pl=Q("util"),ml=Q("fs"),PA=(0,pl.promisify)(ml.readFile??(()=>{})),IA=(0,pl.promisify)(ml.realpath??(()=>{})),NA=(0,pl.promisify)(ml.lstat??(()=>{})),hl=class{filePath;formatType;subjectTokenFieldName;constructor(e){this.filePath=e.filePath,this.formatType=e.formatType,this.subjectTokenFieldName=e.subjectTokenFieldName}async getSubjectToken(){let e=this.filePath;try{if(e=await IA(e),!(await NA(e)).isFile())throw new Error}catch(s){throw s instanceof Error&&(s.message=`The file at ${e} does not exist, or it is not a file. ${s.message}`),s}let r,n=await PA(e,{encoding:"utf8"});if(this.formatType==="text"?r=n:this.formatType==="json"&&this.subjectTokenFieldName&&(r=JSON.parse(n)[this.subjectTokenFieldName]),!r)throw new Error("Unable to parse the subject_token from the credential_source file");return r}};zi.FileSubjectTokenSupplier=hl});var Fg=V(Hi=>{"use strict";Object.defineProperty(Hi,"__esModule",{value:!0});Hi.UrlSubjectTokenSupplier=void 0;var BA=pt(),gl=class{url;headers;formatType;subjectTokenFieldName;additionalGaxiosOptions;constructor(e){this.url=e.url,this.formatType=e.formatType,this.subjectTokenFieldName=e.subjectTokenFieldName,this.headers=e.headers,this.additionalGaxiosOptions=e.additionalGaxiosOptions}async getSubjectToken(e){let r={...this.additionalGaxiosOptions,url:this.url,method:"GET",headers:this.headers};BA.AuthClient.setMethodName(r,"getSubjectToken");let n;if(this.formatType==="text"?n=(await e.transporter.request(r)).data:this.formatType==="json"&&this.subjectTokenFieldName&&(n=(await e.transporter.request(r)).data[this.subjectTokenFieldName]),!n)throw new Error("Unable to parse the subject_token from the credential_source URL");return n}};Hi.UrlSubjectTokenSupplier=gl});var Pg=V(_t=>{"use strict";Object.defineProperty(_t,"__esModule",{value:!0});_t.CertificateSubjectTokenSupplier=_t.InvalidConfigurationError=_t.CertificateSourceUnavailableError=_t.CERTIFICATE_CONFIGURATION_ENV_VARIABLE=void 0;var Wi=Ut(),Gi=Q("fs"),Ji=Q("crypto"),jA=Q("https");_t.CERTIFICATE_CONFIGURATION_ENV_VARIABLE="GOOGLE_API_CERTIFICATE_CONFIG";var tr=class extends Error{constructor(e){super(e),this.name="CertificateSourceUnavailableError"}};_t.CertificateSourceUnavailableError=tr;var vt=class extends Error{constructor(e){super(e),this.name="InvalidConfigurationError"}};_t.InvalidConfigurationError=vt;var yl=class{certificateConfigPath;trustChainPath;cert;key;constructor(e){if(!e.useDefaultCertificateConfig&&!e.certificateConfigLocation)throw new vt("Either `useDefaultCertificateConfig` must be true or a `certificateConfigLocation` must be provided.");if(e.useDefaultCertificateConfig&&e.certificateConfigLocation)throw new vt("Both `useDefaultCertificateConfig` and `certificateConfigLocation` cannot be provided.");this.trustChainPath=e.trustChainPath,this.certificateConfigPath=e.certificateConfigLocation??""}async createMtlsHttpsAgent(){if(!this.key||!this.cert)throw new vt("Cannot create mTLS Agent with missing certificate or key");return new jA.Agent({key:this.key,cert:this.cert})}async getSubjectToken(){this.certificateConfigPath=await this.#e();let{certPath:e,keyPath:r}=await this.#t();return{cert:this.cert,key:this.key}=await this.#r(e,r),await this.#n(this.cert)}async#e(){let e=this.certificateConfigPath;if(e){if(await(0,Wi.isValidFile)(e))return e;throw new tr(`Provided certificate config path is invalid: ${e}`)}let r=process.env[_t.CERTIFICATE_CONFIGURATION_ENV_VARIABLE];if(r){if(await(0,Wi.isValidFile)(r))return r;throw new tr(`Path from environment variable "${_t.CERTIFICATE_CONFIGURATION_ENV_VARIABLE}" is invalid: ${r}`)}let n=(0,Wi.getWellKnownCertificateConfigFileLocation)();if(await(0,Wi.isValidFile)(n))return n;throw new tr(`Could not find certificate configuration file. Searched override path, the "${_t.CERTIFICATE_CONFIGURATION_ENV_VARIABLE}" env var, and the gcloud path (${n}).`)}async#t(){let e=this.certificateConfigPath,r;try{r=await Gi.promises.readFile(e,"utf8")}catch{throw new tr(`Failed to read certificate config file at: ${e}`)}try{let n=JSON.parse(r),s=n?.cert_configs?.workload?.cert_path,i=n?.cert_configs?.workload?.key_path;if(!s||!i)throw new vt(`Certificate config file (${e}) is missing required "cert_path" or "key_path" in the workload config.`);return{certPath:s,keyPath:i}}catch(n){throw n instanceof vt?n:new vt(`Failed to parse certificate config from ${e}: ${n.message}`)}}async#r(e,r){let n,s;try{n=await Gi.promises.readFile(e),new Ji.X509Certificate(n)}catch(i){let u=i instanceof Error?i.message:String(i);throw new tr(`Failed to read certificate file at ${e}: ${u}`)}try{s=await Gi.promises.readFile(r),(0,Ji.createPrivateKey)(s)}catch(i){let u=i instanceof Error?i.message:String(i);throw new tr(`Failed to read private key file at ${r}: ${u}`)}return{cert:n,key:s}}async#n(e){let r=new Ji.X509Certificate(e);if(!this.trustChainPath)return JSON.stringify([r.raw.toString("base64")]);try{let i=((await Gi.promises.readFile(this.trustChainPath,"utf8")).match(/-----BEGIN CERTIFICATE-----[^-]+-----END CERTIFICATE-----/g)??[]).map((l,h)=>{try{return new Ji.X509Certificate(l)}catch(d){let p=d instanceof Error?d.message:String(d);throw new vt(`Failed to parse certificate at index ${h} in trust chain file ${this.trustChainPath}: ${p}`)}}),u=i.findIndex(l=>r.raw.equals(l.raw)),c;if(u===-1)c=[r,...i];else if(u===0)c=i;else throw new vt(`Leaf certificate exists in the trust chain but is not the first entry (found at index ${u}).`);return JSON.stringify(c.map(l=>l.raw.toString("base64")))}catch(n){if(n instanceof vt)throw n;let s=n instanceof Error?n.message:String(n);throw new tr(`Failed to process certificate chain from ${this.trustChainPath}: ${s}`)}}};_t.CertificateSubjectTokenSupplier=yl});var Cl=V(Vi=>{"use strict";Object.defineProperty(Vi,"__esModule",{value:!0});Vi.IdentityPoolClient=void 0;var LA=zr(),_l=Ut(),MA=xg(),UA=Fg(),Ig=Pg(),qA=$i(),Ng=Ve(),bl=class t extends LA.BaseExternalAccountClient{subjectTokenSupplier;constructor(e){super(e);let r=(0,_l.originalOrCamelOptions)(e),n=r.get("credential_source"),s=r.get("subject_token_supplier");if(!n&&!s)throw new Error("A credential source or subject token supplier must be specified.");if(n&&s)throw new Error("Only one of credential source or subject token supplier can be specified.");if(s)this.subjectTokenSupplier=s,this.credentialSourceType="programmatic";else{let i=(0,_l.originalOrCamelOptions)(n),u=(0,_l.originalOrCamelOptions)(i.get("format")),c=u.get("type")||"text",l=u.get("subject_token_field_name");if(c!=="json"&&c!=="text")throw new Error(`Invalid credential_source format "${c}"`);if(c==="json"&&!l)throw new Error("Missing subject_token_field_name for JSON credential_source format");let h=i.get("file"),d=i.get("url"),p=i.get("certificate"),A=i.get("headers");if(h&&d||d&&p||h&&p)throw new Error('No valid Identity Pool "credential_source" provided, must be either file, url, or certificate.');if(h)this.credentialSourceType="file",this.subjectTokenSupplier=new MA.FileSubjectTokenSupplier({filePath:h,formatType:c,subjectTokenFieldName:l});else if(d)this.credentialSourceType="url",this.subjectTokenSupplier=new UA.UrlSubjectTokenSupplier({url:d,formatType:c,subjectTokenFieldName:l,headers:A,additionalGaxiosOptions:t.RETRY_CONFIG});else if(p){this.credentialSourceType="certificate";let v=new Ig.CertificateSubjectTokenSupplier({useDefaultCertificateConfig:p.use_default_certificate_config,certificateConfigLocation:p.certificate_config_location,trustChainPath:p.trust_chain_path});this.subjectTokenSupplier=v}else throw new Error('No valid Identity Pool "credential_source" provided, must be either file, url, or certificate.')}}async retrieveSubjectToken(){let e=await this.subjectTokenSupplier.getSubjectToken(this.supplierContext);if(this.subjectTokenSupplier instanceof Ig.CertificateSubjectTokenSupplier){let r=await this.subjectTokenSupplier.createMtlsHttpsAgent();this.stsCredential=new qA.StsCredentials({tokenExchangeEndpoint:this.getTokenUrl(),clientAuthentication:this.clientAuth,transporter:new Ng.Gaxios({agent:r})}),this.transporter=new Ng.Gaxios({...this.transporter.defaults||{},agent:r})}return e}};Vi.IdentityPoolClient=bl});var El=V(Yi=>{"use strict";Object.defineProperty(Yi,"__esModule",{value:!0});Yi.AwsRequestSigner=void 0;var Ki=Ve(),jg=Ps(),Bg="AWS4-HMAC-SHA256",$A="aws4_request",wl=class{getCredentials;region;crypto;constructor(e,r){this.getCredentials=e,this.region=r,this.crypto=(0,jg.createCrypto)()}async getRequestOptions(e){if(!e.url)throw new RangeError('"url" is required in "amzOptions"');let r=typeof e.data=="object"?JSON.stringify(e.data):e.data,n=e.url,s=e.method||"GET",i=e.body||r,u=e.headers,c=await this.getCredentials(),l=new URL(n);if(typeof i!="string"&&i!==void 0)throw new TypeError(`'requestPayload' is expected to be a string if provided. Got: ${i}`);let h=await HA({crypto:this.crypto,host:l.host,canonicalUri:l.pathname,canonicalQuerystring:l.search.slice(1),method:s,region:this.region,securityCredentials:c,requestPayload:i,additionalAmzHeaders:u}),d=Ki.Gaxios.mergeHeaders(h.amzDate?{"x-amz-date":h.amzDate}:{},{authorization:h.authorizationHeader,host:l.host},u||{});c.token&&Ki.Gaxios.mergeHeaders(d,{"x-amz-security-token":c.token});let p={url:n,method:s,headers:d};return i!==void 0&&(p.body=i),p}};Yi.AwsRequestSigner=wl;async function Hs(t,e,r){return await t.signWithHmacSha256(e,r)}async function zA(t,e,r,n,s){let i=await Hs(t,`AWS4${e}`,r),u=await Hs(t,i,n),c=await Hs(t,u,s);return await Hs(t,c,"aws4_request")}async function HA(t){let e=Ki.Gaxios.mergeHeaders(t.additionalAmzHeaders),r=t.requestPayload||"",n=t.host.split(".")[0],s=new Date,i=s.toISOString().replace(/[-:]/g,"").replace(/\.[0-9]+/,""),u=s.toISOString().replace(/[-]/g,"").replace(/T.*/,"");t.securityCredentials.token&&e.set("x-amz-security-token",t.securityCredentials.token);let c=Ki.Gaxios.mergeHeaders({host:t.host},e.has("date")?{}:{"x-amz-date":i},e),l="",h=[...c.keys()].sort();h.forEach(k=>{l+=`${k}:${c.get(k)}
|
|
53
|
-
`});let d=h.join(";"),p=await t.crypto.sha256DigestHex(r),
|
|
52
|
+
"HS256", "HS384", "HS512", "RS256", "RS384", "RS512", "PS256", "PS384", "PS512", "ES256", "ES384", "ES512" and "none".`,Us="secret must be a string or buffer",Kn="key must be a string or a buffer",zE="key must be a string, a buffer or an object",Gc=typeof kt.createPublicKey=="function";Gc&&(Kn+=" or a KeyObject",Us+="or a KeyObject");function tg(t){if(!Yn.isBuffer(t)&&typeof t!="string"&&(!Gc||typeof t!="object"||typeof t.type!="string"||typeof t.asymmetricKeyType!="string"||typeof t.export!="function"))throw $t(Kn)}function rg(t){if(!Yn.isBuffer(t)&&typeof t!="string"&&typeof t!="object")throw $t(zE)}function HE(t){if(!Yn.isBuffer(t)){if(typeof t=="string")return t;if(!Gc||typeof t!="object"||t.type!=="secret"||typeof t.export!="function")throw $t(Us)}}function Jc(t){return t.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function ng(t){t=t.toString();var e=4-t.length%4;if(e!==4)for(var r=0;r<e;++r)t+="=";return t.replace(/\-/g,"+").replace(/_/g,"/")}function $t(t){var e=[].slice.call(arguments,1),r=Zm.format.bind(Zm,t).apply(null,e);return new TypeError(r)}function WE(t){return Yn.isBuffer(t)||typeof t=="string"}function qs(t){return WE(t)||(t=JSON.stringify(t)),t}function sg(t){return function(r,n){HE(n),r=qs(r);var s=kt.createHmac("sha"+t,n),i=(s.update(r),s.digest("base64"));return Jc(i)}}var Wc,GE="timingSafeEqual"in kt?function(e,r){return e.byteLength!==r.byteLength?!1:kt.timingSafeEqual(e,r)}:function(e,r){return Wc||(Wc=Xm()),Wc(e,r)};function JE(t){return function(r,n,s){var i=sg(t)(r,s);return GE(Yn.from(n),Yn.from(i))}}function og(t){return function(r,n){rg(n),r=qs(r);var s=kt.createSign("RSA-SHA"+t),i=(s.update(r),s.sign(n,"base64"));return Jc(i)}}function ig(t){return function(r,n,s){tg(s),r=qs(r),n=ng(n);var i=kt.createVerify("RSA-SHA"+t);return i.update(r),i.verify(s,n,"base64")}}function VE(t){return function(r,n){rg(n),r=qs(r);var s=kt.createSign("RSA-SHA"+t),i=(s.update(r),s.sign({key:n,padding:kt.constants.RSA_PKCS1_PSS_PADDING,saltLength:kt.constants.RSA_PSS_SALTLEN_DIGEST},"base64"));return Jc(i)}}function KE(t){return function(r,n,s){tg(s),r=qs(r),n=ng(n);var i=kt.createVerify("RSA-SHA"+t);return i.update(r),i.verify({key:s,padding:kt.constants.RSA_PKCS1_PSS_PADDING,saltLength:kt.constants.RSA_PSS_SALTLEN_DIGEST},n,"base64")}}function YE(t){var e=og(t);return function(){var n=e.apply(null,arguments);return n=eg.derToJose(n,"ES"+t),n}}function QE(t){var e=ig(t);return function(n,s,i){s=eg.joseToDer(s,"ES"+t).toString("base64");var u=e(n,s,i);return u}}function XE(){return function(){return""}}function ZE(){return function(e,r){return r===""}}ag.exports=function(e){var r={hs:sg,rs:og,ps:VE,es:YE,none:XE},n={hs:JE,rs:ig,ps:KE,es:QE,none:ZE},s=e.match(/^(RS|PS|ES|HS)(256|384|512)$|^(none)$/);if(!s)throw $t($E,e);var i=(s[1]||s[3]).toLowerCase(),u=s[2];return{sign:r[i](u),verify:n[i](u)}}});var Kc=V((ex,ug)=>{var eA=X("buffer").Buffer;ug.exports=function(e){return typeof e=="string"?e:typeof e=="number"||eA.isBuffer(e)?e.toString():JSON.stringify(e)}});var pg=V((tx,hg)=>{var tA=Gn().Buffer,cg=zc(),rA=Vc(),nA=X("stream"),lg=Kc(),Yc=X("util");function dg(t,e){return tA.from(t,e).toString("base64").replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function sA(t,e,r){r=r||"utf8";var n=dg(lg(t),"binary"),s=dg(lg(e),r);return Yc.format("%s.%s",n,s)}function fg(t){var e=t.header,r=t.payload,n=t.secret||t.privateKey,s=t.encoding,i=rA(e.alg),u=sA(e,r,s),c=i.sign(u,n);return Yc.format("%s.%s",u,c)}function Li(t){var e=t.secret||t.privateKey||t.key,r=new cg(e);this.readable=!0,this.header=t.header,this.encoding=t.encoding,this.secret=this.privateKey=this.key=r,this.payload=new cg(t.payload),this.secret.once("close",function(){!this.payload.writable&&this.readable&&this.sign()}.bind(this)),this.payload.once("close",function(){!this.secret.writable&&this.readable&&this.sign()}.bind(this))}Yc.inherits(Li,nA);Li.prototype.sign=function(){try{var e=fg({header:this.header,payload:this.payload.buffer,secret:this.secret.buffer,encoding:this.encoding});return this.emit("done",e),this.emit("data",e),this.emit("end"),this.readable=!1,e}catch(r){this.readable=!1,this.emit("error",r),this.emit("close")}};Li.sign=fg;hg.exports=Li});var Sg=V((rx,Ag)=>{var gg=Gn().Buffer,mg=zc(),oA=Vc(),iA=X("stream"),yg=Kc(),aA=X("util"),uA=/^[a-zA-Z0-9\-_]+?\.[a-zA-Z0-9\-_]+?\.([a-zA-Z0-9\-_]+)?$/;function cA(t){return Object.prototype.toString.call(t)==="[object Object]"}function lA(t){if(cA(t))return t;try{return JSON.parse(t)}catch{return}}function _g(t){var e=t.split(".",1)[0];return lA(gg.from(e,"base64").toString("binary"))}function dA(t){return t.split(".",2).join(".")}function bg(t){return t.split(".")[2]}function fA(t,e){e=e||"utf8";var r=t.split(".")[1];return gg.from(r,"base64").toString(e)}function Cg(t){return uA.test(t)&&!!_g(t)}function wg(t,e,r){if(!e){var n=new Error("Missing algorithm parameter for jws.verify");throw n.code="MISSING_ALGORITHM",n}t=yg(t);var s=bg(t),i=dA(t),u=oA(e);return u.verify(i,s,r)}function Eg(t,e){if(e=e||{},t=yg(t),!Cg(t))return null;var r=_g(t);if(!r)return null;var n=fA(t);return(r.typ==="JWT"||e.json)&&(n=JSON.parse(n,e.encoding)),{header:r,payload:n,signature:bg(t)}}function Qn(t){t=t||{};var e=t.secret||t.publicKey||t.key,r=new mg(e);this.readable=!0,this.algorithm=t.algorithm,this.encoding=t.encoding,this.secret=this.publicKey=this.key=r,this.signature=new mg(t.signature),this.secret.once("close",function(){!this.signature.writable&&this.readable&&this.verify()}.bind(this)),this.signature.once("close",function(){!this.secret.writable&&this.readable&&this.verify()}.bind(this))}aA.inherits(Qn,iA);Qn.prototype.verify=function(){try{var e=wg(this.signature.buffer,this.algorithm,this.key.buffer),r=Eg(this.signature.buffer,this.encoding);return this.emit("done",e,r),this.emit("data",e),this.emit("end"),this.readable=!1,e}catch(n){this.readable=!1,this.emit("error",n),this.emit("close")}};Qn.decode=Eg;Qn.isValid=Cg;Qn.verify=wg;Ag.exports=Qn});var Qc=V(Hr=>{var vg=pg(),Mi=Sg(),hA=["HS256","HS384","HS512","RS256","RS384","RS512","PS256","PS384","PS512","ES256","ES384","ES512"];Hr.ALGORITHMS=hA;Hr.sign=vg.sign;Hr.verify=Mi.verify;Hr.decode=Mi.decode;Hr.isValid=Mi.isValid;Hr.createSign=function(e){return new vg(e)};Hr.createVerify=function(e){return new Mi(e)}});var Ug=V(qi=>{"use strict";Object.defineProperty(qi,"__esModule",{value:!0});qi.GoogleToken=void 0;var kg=Ui(X("fs")),pA=Ve(),mA=Ui(Qc()),gA=Ui(X("path")),yA=X("util");function Ui(t,e){if(typeof WeakMap=="function")var r=new WeakMap,n=new WeakMap;return(Ui=function(i,u){if(!u&&i&&i.__esModule)return i;var c,l,h={__proto__:null,default:i};if(i===null||Er(i)!="object"&&typeof i!="function")return h;if(c=u?n:r){if(c.has(i))return c.get(i);c.set(i,h)}for(var d in i)d!=="default"&&{}.hasOwnProperty.call(i,d)&&((l=(c=Object.defineProperty)&&Object.getOwnPropertyDescriptor(i,d))&&(l.get||l.set)?c(h,d,l):h[d]=i[d]);return h})(t,e)}function Er(t){"@babel/helpers - typeof";return Er=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Er(t)}function _A(t,e){Ng(t,e),e.add(t)}function bA(t,e,r){Ng(t,e),e.set(t,r)}function Ng(t,e){if(e.has(t))throw new TypeError("Cannot initialize the same private elements twice on an object")}function Tg(t,e,r){return t.set(zt(t,e),r),r}function Dg(t,e){return t.get(zt(t,e))}function zt(t,e,r){if(typeof t=="function"?t===e:t.has(e))return arguments.length<3?e:r;throw new TypeError("Private element is not present on this object")}function Rg(t,e){for(var r=0;r<e.length;r++){var n=e[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(t,Lg(n.key),n)}}function Bg(t,e,r){return e&&Rg(t.prototype,e),r&&Rg(t,r),Object.defineProperty(t,"prototype",{writable:!1}),t}function jg(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function CA(t,e,r){return e=Ws(e),wA(t,nl()?Reflect.construct(e,r||[],Ws(t).constructor):e.apply(t,r))}function wA(t,e){if(e&&(Er(e)=="object"||typeof e=="function"))return e;if(e!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return EA(t)}function EA(t){if(t===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}function AA(t,e){if(typeof e!="function"&&e!==null)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),Object.defineProperty(t,"prototype",{writable:!1}),e&&Hs(t,e)}function Xc(t){var e=typeof Map=="function"?new Map:void 0;return Xc=function(n){if(n===null||!vA(n))return n;if(typeof n!="function")throw new TypeError("Super expression must either be null or a function");if(e!==void 0){if(e.has(n))return e.get(n);e.set(n,s)}function s(){return SA(n,arguments,Ws(this).constructor)}return s.prototype=Object.create(n.prototype,{constructor:{value:s,enumerable:!1,writable:!0,configurable:!0}}),Hs(s,n)},Xc(t)}function SA(t,e,r){if(nl())return Reflect.construct.apply(null,arguments);var n=[null];n.push.apply(n,e);var s=new(t.bind.apply(t,n));return r&&Hs(s,r.prototype),s}function nl(){try{var t=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(nl=function(){return!!t})()}function vA(t){try{return Function.toString.call(t).indexOf("[native code]")!==-1}catch{return typeof t=="function"}}function Hs(t,e){return Hs=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(r,n){return r.__proto__=n,r},Hs(t,e)}function Ws(t){return Ws=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},Ws(t)}function mt(t,e,r){return(e=Lg(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function Lg(t){var e=kA(t,"string");return Er(e)=="symbol"?e:e+""}function kA(t,e){if(Er(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var n=r.call(t,e||"default");if(Er(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function yt(){var t,e,r=typeof Symbol=="function"?Symbol:{},n=r.iterator||"@@iterator",s=r.toStringTag||"@@toStringTag";function i(T,S,y,g){var m=S&&S.prototype instanceof c?S:c,v=Object.create(m.prototype);return gt(v,"_invoke",(function(b,A,R){var F,$,J,M=0,Q=R||[],ue=!1,re={p:0,n:0,v:t,a:de,f:de.bind(t,4),d:function(Ae,oe){return F=Ae,$=0,J=t,re.n=oe,u}};function de(pe,Ae){for($=pe,J=Ae,e=0;!ue&&M&&!oe&&e<Q.length;e++){var oe,me=Q[e],G=re.p,K=me[2];pe>3?(oe=K===Ae)&&(J=me[($=me[4])?5:($=3,3)],me[4]=me[5]=t):me[0]<=G&&((oe=pe<2&&G<me[1])?($=0,re.v=Ae,re.n=me[1]):G<K&&(oe=pe<3||me[0]>Ae||Ae>K)&&(me[4]=pe,me[5]=Ae,re.n=K,$=0))}if(oe||pe>1)return u;throw ue=!0,Ae}return function(pe,Ae,oe){if(M>1)throw TypeError("Generator is already running");for(ue&&Ae===1&&de(Ae,oe),$=Ae,J=oe;(e=$<2?t:J)||!ue;){F||($?$<3?($>1&&(re.n=-1),de($,J)):re.n=J:re.v=J);try{if(M=2,F){if($||(pe="next"),e=F[pe]){if(!(e=e.call(F,J)))throw TypeError("iterator result is not an object");if(!e.done)return e;J=e.value,$<2&&($=0)}else $===1&&(e=F.return)&&e.call(F),$<2&&(J=TypeError("The iterator does not provide a '"+pe+"' method"),$=1);F=t}else if((e=(ue=re.n<0)?J:b.call(A,re))!==u)break}catch(me){F=t,$=1,J=me}finally{M=1}}return{value:e,done:ue}}})(T,y,g),!0),v}var u={};function c(){}function l(){}function h(){}e=Object.getPrototypeOf;var d=[][n]?e(e([][n]())):(gt(e={},n,function(){return this}),e),p=h.prototype=c.prototype=Object.create(d);function w(T){return Object.setPrototypeOf?Object.setPrototypeOf(T,h):(T.__proto__=h,gt(T,s,"GeneratorFunction")),T.prototype=Object.create(p),T}return l.prototype=h,gt(p,"constructor",h),gt(h,"constructor",l),l.displayName="GeneratorFunction",gt(h,s,"GeneratorFunction"),gt(p),gt(p,s,"Generator"),gt(p,n,function(){return this}),gt(p,"toString",function(){return"[object Generator]"}),(yt=function(){return{w:i,m:w}})()}function gt(t,e,r,n){var s=Object.defineProperty;try{s({},"",{})}catch{s=0}gt=function(u,c,l,h){if(c)s?s(u,c,{value:l,enumerable:!h,configurable:!h,writable:!h}):u[c]=l;else{var d=function(w,T){gt(u,w,function(S){return this._invoke(w,T,S)})};d("next",0),d("throw",1),d("return",2)}},gt(t,e,r,n)}function xg(t,e,r,n,s,i,u){try{var c=t[i](u),l=c.value}catch(h){return void r(h)}c.done?e(l):Promise.resolve(l).then(n,s)}function Xn(t){return function(){var e=this,r=arguments;return new Promise(function(n,s){var i=t.apply(e,r);function u(l){xg(i,n,s,u,c,"next",l)}function c(l){xg(i,n,s,u,c,"throw",l)}u(void 0)})}}var Og=kg.readFile?(0,yA.promisify)(kg.readFile):Xn(yt().m(function t(){return yt().w(function(e){for(;;)switch(e.n){case 0:throw new zs("use key rather than keyFile.","MISSING_CREDENTIALS");case 1:return e.a(2)}},t)})),Fg="https://oauth2.googleapis.com/token",TA="https://oauth2.googleapis.com/revoke?token=",zs=(function(t){function e(r,n){var s;return jg(this,e),s=CA(this,e,[r]),mt(s,"code",void 0),s.code=n,s}return AA(e,t),Bg(e)})(Xc(Error)),$s=new WeakMap,tr=new WeakSet,sx=qi.GoogleToken=(function(){function t(e){jg(this,t),_A(this,tr),mt(this,"expiresAt",void 0),mt(this,"key",void 0),mt(this,"keyFile",void 0),mt(this,"iss",void 0),mt(this,"sub",void 0),mt(this,"scope",void 0),mt(this,"rawToken",void 0),mt(this,"tokenExpires",void 0),mt(this,"email",void 0),mt(this,"additionalClaims",void 0),mt(this,"eagerRefreshThresholdMillis",void 0),mt(this,"transporter",{request:function(n){return(0,pA.request)(n)}}),bA(this,$s,void 0),zt(tr,this,Mg).call(this,e)}return Bg(t,[{key:"accessToken",get:function(){return this.rawToken?this.rawToken.access_token:void 0}},{key:"idToken",get:function(){return this.rawToken?this.rawToken.id_token:void 0}},{key:"tokenType",get:function(){return this.rawToken?this.rawToken.token_type:void 0}},{key:"refreshToken",get:function(){return this.rawToken?this.rawToken.refresh_token:void 0}},{key:"hasExpired",value:function(){var r=new Date().getTime();return this.rawToken&&this.expiresAt?r>=this.expiresAt:!0}},{key:"isTokenExpiring",value:function(){var r,n=new Date().getTime(),s=(r=this.eagerRefreshThresholdMillis)!==null&&r!==void 0?r:0;return this.rawToken&&this.expiresAt?this.expiresAt<=n+s:!0}},{key:"getToken",value:function(r){var n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(Er(r)==="object"&&(n=r,r=void 0),n=Object.assign({forceRefresh:!1},n),r){var s=r;zt(tr,this,Pg).call(this,n).then(function(i){return s(null,i)},r);return}return zt(tr,this,Pg).call(this,n)}},{key:"getCredentials",value:(function(){var e=Xn(yt().m(function n(s){var i,u,c,l,h,d,p;return yt().w(function(w){for(;;)switch(w.n){case 0:i=gA.extname(s),p=i,w.n=p===".json"?1:p===".der"||p===".crt"||p===".pem"?4:p===".p12"||p===".pfx"?6:7;break;case 1:return w.n=2,Og(s,"utf8");case 2:if(u=w.v,c=JSON.parse(u),l=c.private_key,h=c.client_email,!(!l||!h)){w.n=3;break}throw new zs("private_key and client_email are required.","MISSING_CREDENTIALS");case 3:return w.a(2,{privateKey:l,clientEmail:h});case 4:return w.n=5,Og(s,"utf8");case 5:return d=w.v,w.a(2,{privateKey:d});case 6:throw new zs("*.p12 certificates are not supported after v6.1.2. Consider utilizing *.json format or converting *.p12 to *.pem using the OpenSSL CLI.","UNKNOWN_CERTIFICATE_TYPE");case 7:throw new zs("Unknown certificate type. Type is determined based on file extension. Current supported extensions are *.json, and *.pem.","UNKNOWN_CERTIFICATE_TYPE");case 8:return w.a(2)}},n)}));function r(n){return e.apply(this,arguments)}return r})()},{key:"revokeToken",value:function(r){if(r){zt(tr,this,Ig).call(this).then(function(){return r()},r);return}return zt(tr,this,Ig).call(this)}}])})();function Pg(t){return Zc.apply(this,arguments)}function Zc(){return Zc=Xn(yt().m(function t(e){return yt().w(function(r){for(;;)switch(r.n){case 0:if(!(Dg($s,this)&&!e.forceRefresh)){r.n=1;break}return r.a(2,Dg($s,this));case 1:return r.p=1,r.n=2,Tg($s,this,zt(tr,this,DA).call(this,e));case 2:return r.a(2,r.v);case 3:return r.p=3,Tg($s,this,void 0),r.f(3);case 4:return r.a(2)}},t,this,[[1,,3,4]])})),Zc.apply(this,arguments)}function DA(t){return el.apply(this,arguments)}function el(){return el=Xn(yt().m(function t(e){var r;return yt().w(function(n){for(;;)switch(n.n){case 0:if(!(this.isTokenExpiring()===!1&&e.forceRefresh===!1)){n.n=1;break}return n.a(2,Promise.resolve(this.rawToken));case 1:if(!(!this.key&&!this.keyFile)){n.n=2;break}throw new Error("No key or keyFile set.");case 2:if(!(!this.key&&this.keyFile)){n.n=4;break}return n.n=3,this.getCredentials(this.keyFile);case 3:r=n.v,this.key=r.privateKey,this.iss=r.clientEmail||this.iss,r.clientEmail||zt(tr,this,RA).call(this);case 4:return n.a(2,zt(tr,this,xA).call(this))}},t,this)})),el.apply(this,arguments)}function RA(){if(!this.iss)throw new zs("email is required.","MISSING_CREDENTIALS")}function Ig(){return tl.apply(this,arguments)}function tl(){return tl=Xn(yt().m(function t(){var e;return yt().w(function(r){for(;;)switch(r.n){case 0:if(this.accessToken){r.n=1;break}throw new Error("No token to revoke.");case 1:return e=TA+this.accessToken,r.n=2,this.transporter.request({url:e,retry:!0});case 2:zt(tr,this,Mg).call(this,{email:this.iss,sub:this.sub,key:this.key,keyFile:this.keyFile,scope:this.scope,additionalClaims:this.additionalClaims});case 3:return r.a(2)}},t,this)})),tl.apply(this,arguments)}function Mg(){var t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};this.keyFile=t.keyFile,this.key=t.key,this.rawToken=void 0,this.iss=t.email||t.iss,this.sub=t.sub,this.additionalClaims=t.additionalClaims,Er(t.scope)==="object"?this.scope=t.scope.join(" "):this.scope=t.scope,this.eagerRefreshThresholdMillis=t.eagerRefreshThresholdMillis,t.transporter&&(this.transporter=t.transporter)}function xA(){return rl.apply(this,arguments)}function rl(){return rl=Xn(yt().m(function t(){var e,r,n,s,i,u,c,l,h,d;return yt().w(function(p){for(;;)switch(p.n){case 0:return e=Math.floor(new Date().getTime()/1e3),r=this.additionalClaims||{},n=Object.assign({iss:this.iss,scope:this.scope,aud:Fg,exp:e+3600,iat:e,sub:this.sub},r),s=mA.sign({header:{alg:"RS256"},payload:n,secret:this.key}),p.p=1,p.n=2,this.transporter.request({method:"POST",url:Fg,data:new URLSearchParams({grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:s}),responseType:"json",retryConfig:{httpMethodsToRetry:["POST"]}});case 2:return i=p.v,this.rawToken=i.data,this.expiresAt=i.data.expires_in===null||i.data.expires_in===void 0?void 0:(e+i.data.expires_in)*1e3,p.a(2,this.rawToken);case 3:throw p.p=3,d=p.v,this.rawToken=void 0,this.tokenExpires=void 0,l=d.response&&(u=d.response)!==null&&u!==void 0&&u.data?(c=d.response)===null||c===void 0?void 0:c.data:{},l.error&&(h=l.error_description?": ".concat(l.error_description):"",d.message="".concat(l.error).concat(h)),d;case 4:return p.a(2)}},t,this,[[1,3]])})),rl.apply(this,arguments)}});var ol=V($i=>{"use strict";Object.defineProperty($i,"__esModule",{value:!0});$i.JWTAccess=void 0;var OA=Qc(),FA=Ut(),qg={alg:"RS256",typ:"JWT"},sl=class t{email;key;keyId;projectId;eagerRefreshThresholdMillis;cache=new FA.LRUCache({capacity:500,maxAge:3600*1e3});constructor(e,r,n,s){this.email=e,this.key=r,this.keyId=n,this.eagerRefreshThresholdMillis=s??300*1e3}getCachedKey(e,r){let n=e;if(r&&Array.isArray(r)&&r.length?n=e?`${e}_${r.join("_")}`:`${r.join("_")}`:typeof r=="string"&&(n=e?`${e}_${r}`:r),!n)throw Error("Scopes or url must be provided");return n}getRequestHeaders(e,r,n){let s=this.getCachedKey(e,n),i=this.cache.get(s),u=Date.now();if(i&&i.expiration-u>this.eagerRefreshThresholdMillis)return new Headers(i.headers);let c=Math.floor(Date.now()/1e3),l=t.getExpirationTime(c),h;if(Array.isArray(n)&&(n=n.join(" ")),n?h={iss:this.email,sub:this.email,scope:n,exp:l,iat:c}:h={iss:this.email,sub:this.email,aud:e,exp:l,iat:c},r){for(let S in h)if(r[S])throw new Error(`The '${S}' property is not allowed when passing additionalClaims. This claim is included in the JWT by default.`)}let d=this.keyId?{...qg,kid:this.keyId}:qg,p=Object.assign(h,r),w=OA.sign({header:d,payload:p,secret:this.key}),T=new Headers({authorization:`Bearer ${w}`});return this.cache.set(s,{expiration:l*1e3,headers:T}),T}static getExpirationTime(e){return e+3600}fromJSON(e){if(!e)throw new Error("Must pass in a JSON object containing the service account auth settings.");if(!e.client_email)throw new Error("The incoming JSON object does not contain a client_email field");if(!e.private_key)throw new Error("The incoming JSON object does not contain a private_key field");this.email=e.client_email,this.key=e.private_key,this.keyId=e.private_key_id,this.projectId=e.project_id}fromStream(e,r){if(r)this.fromStreamAsync(e).then(()=>r(),r);else return this.fromStreamAsync(e)}fromStreamAsync(e){return new Promise((r,n)=>{e||n(new Error("Must pass in a stream containing the service account auth settings."));let s="";e.setEncoding("utf8").on("data",i=>s+=i).on("error",n).on("end",()=>{try{let i=JSON.parse(s);this.fromJSON(i),r()}catch(i){n(i)}})})}};$i.JWTAccess=sl});var al=V(Hi=>{"use strict";Object.defineProperty(Hi,"__esModule",{value:!0});Hi.JWT=void 0;var $g=Ug(),PA=ol(),IA=pn(),zi=pt(),il=class t extends IA.OAuth2Client{email;keyFile;key;keyId;defaultScopes;scopes;scope;subject;gtoken;additionalClaims;useJWTAccessWithScope;defaultServicePath;access;constructor(e={}){super(e),this.email=e.email,this.keyFile=e.keyFile,this.key=e.key,this.keyId=e.keyId,this.scopes=e.scopes,this.subject=e.subject,this.additionalClaims=e.additionalClaims,this.credentials={refresh_token:"jwt-placeholder",expiry_date:1}}createScoped(e){let r=new t(this);return r.scopes=e,r}async getRequestMetadataAsync(e){e=this.defaultServicePath?`https://${this.defaultServicePath}/`:e;let r=!this.hasUserScopes()&&e||this.useJWTAccessWithScope&&this.hasAnyScopes()||this.universeDomain!==zi.DEFAULT_UNIVERSE;if(this.subject&&this.universeDomain!==zi.DEFAULT_UNIVERSE)throw new RangeError(`Service Account user is configured for the credential. Domain-wide delegation is not supported in universes other than ${zi.DEFAULT_UNIVERSE}`);if(!this.apiKey&&r)if(this.additionalClaims&&this.additionalClaims.target_audience){let{tokens:n}=await this.refreshToken();return{headers:this.addSharedMetadataHeaders(new Headers({authorization:`Bearer ${n.id_token}`}))}}else{this.access||(this.access=new PA.JWTAccess(this.email,this.key,this.keyId,this.eagerRefreshThresholdMillis));let n;this.hasUserScopes()?n=this.scopes:e||(n=this.defaultScopes);let s=this.useJWTAccessWithScope||this.universeDomain!==zi.DEFAULT_UNIVERSE,i=await this.access.getRequestHeaders(e??void 0,this.additionalClaims,s?n:void 0);return{headers:this.addSharedMetadataHeaders(i)}}else return this.hasAnyScopes()||this.apiKey?super.getRequestMetadataAsync(e):{headers:new Headers}}async fetchIdToken(e){let r=new $g.GoogleToken({iss:this.email,sub:this.subject,scope:this.scopes||this.defaultScopes,keyFile:this.keyFile,key:this.key,additionalClaims:{target_audience:e},transporter:this.transporter});if(await r.getToken({forceRefresh:!0}),!r.idToken)throw new Error("Unknown error: Failed to fetch ID token");return r.idToken}hasUserScopes(){return this.scopes?this.scopes.length>0:!1}hasAnyScopes(){return!!(this.scopes&&this.scopes.length>0||this.defaultScopes&&this.defaultScopes.length>0)}authorize(e){if(e)this.authorizeAsync().then(r=>e(null,r),e);else return this.authorizeAsync()}async authorizeAsync(){let e=await this.refreshToken();if(!e)throw new Error("No result returned");return this.credentials=e.tokens,this.credentials.refresh_token="jwt-placeholder",this.key=this.gtoken.key,this.email=this.gtoken.iss,e.tokens}async refreshTokenNoCache(){let e=this.createGToken(),n={access_token:(await e.getToken({forceRefresh:this.isTokenExpiring()})).access_token,token_type:"Bearer",expiry_date:e.expiresAt,id_token:e.idToken};return this.emit("tokens",n),{res:null,tokens:n}}createGToken(){return this.gtoken||(this.gtoken=new $g.GoogleToken({iss:this.email,sub:this.subject,scope:this.scopes||this.defaultScopes,keyFile:this.keyFile,key:this.key,additionalClaims:this.additionalClaims,transporter:this.transporter})),this.gtoken}fromJSON(e){if(!e)throw new Error("Must pass in a JSON object containing the service account auth settings.");if(!e.client_email)throw new Error("The incoming JSON object does not contain a client_email field");if(!e.private_key)throw new Error("The incoming JSON object does not contain a private_key field");this.email=e.client_email,this.key=e.private_key,this.keyId=e.private_key_id,this.projectId=e.project_id,this.quotaProjectId=e.quota_project_id,this.universeDomain=e.universe_domain||this.universeDomain}fromStream(e,r){if(r)this.fromStreamAsync(e).then(()=>r(),r);else return this.fromStreamAsync(e)}fromStreamAsync(e){return new Promise((r,n)=>{if(!e)throw new Error("Must pass in a stream containing the service account auth settings.");let s="";e.setEncoding("utf8").on("error",n).on("data",i=>s+=i).on("end",()=>{try{let i=JSON.parse(s);this.fromJSON(i),r()}catch(i){n(i)}})})}fromAPIKey(e){if(typeof e!="string")throw new Error("Must provide an API Key string.");this.apiKey=e}async getCredentials(){if(this.key)return{private_key:this.key,client_email:this.email};if(this.keyFile){let r=await this.createGToken().getCredentials(this.keyFile);return{private_key:r.privateKey,client_email:r.clientEmail}}throw new Error("A key or a keyFile must be provided to getCredentials.")}};Hi.JWT=il});var cl=V(Zn=>{"use strict";Object.defineProperty(Zn,"__esModule",{value:!0});Zn.UserRefreshClient=Zn.USER_REFRESH_ACCOUNT_TYPE=void 0;var NA=pn(),BA=pt();Zn.USER_REFRESH_ACCOUNT_TYPE="authorized_user";var ul=class t extends NA.OAuth2Client{_refreshToken;constructor(e,r,n,s,i){let u=e&&typeof e=="object"?e:{clientId:e,clientSecret:r,refreshToken:n,eagerRefreshThresholdMillis:s,forceRefreshOnFailure:i};super(u),this._refreshToken=u.refreshToken,this.credentials.refresh_token=u.refreshToken}async refreshTokenNoCache(){return super.refreshTokenNoCache(this._refreshToken)}async fetchIdToken(e){let r={...t.RETRY_CONFIG,url:this.endpoints.oauth2TokenUrl,method:"POST",data:new URLSearchParams({client_id:this._clientId,client_secret:this._clientSecret,grant_type:"refresh_token",refresh_token:this._refreshToken,target_audience:e})};return BA.AuthClient.setMethodName(r,"fetchIdToken"),(await this.transporter.request(r)).data.id_token}fromJSON(e){if(!e)throw new Error("Must pass in a JSON object containing the user refresh token");if(e.type!=="authorized_user")throw new Error('The incoming JSON object does not have the "authorized_user" type');if(!e.client_id)throw new Error("The incoming JSON object does not contain a client_id field");if(!e.client_secret)throw new Error("The incoming JSON object does not contain a client_secret field");if(!e.refresh_token)throw new Error("The incoming JSON object does not contain a refresh_token field");this._clientId=e.client_id,this._clientSecret=e.client_secret,this._refreshToken=e.refresh_token,this.credentials.refresh_token=e.refresh_token,this.quotaProjectId=e.quota_project_id,this.universeDomain=e.universe_domain||this.universeDomain}fromStream(e,r){if(r)this.fromStreamAsync(e).then(()=>r(),r);else return this.fromStreamAsync(e)}async fromStreamAsync(e){return new Promise((r,n)=>{if(!e)return n(new Error("Must pass in a stream containing the user refresh token."));let s="";e.setEncoding("utf8").on("error",n).on("data",i=>s+=i).on("end",()=>{try{let i=JSON.parse(s);return this.fromJSON(i),r()}catch(i){return n(i)}})})}static fromJSON(e){let r=new t;return r.fromJSON(e),r}};Zn.UserRefreshClient=ul});var dl=V(es=>{"use strict";Object.defineProperty(es,"__esModule",{value:!0});es.Impersonated=es.IMPERSONATED_ACCOUNT_TYPE=void 0;var zg=pn(),jA=Ve(),LA=Ut();es.IMPERSONATED_ACCOUNT_TYPE="impersonated_service_account";var ll=class t extends zg.OAuth2Client{sourceClient;targetPrincipal;targetScopes;delegates;lifetime;endpoint;constructor(e={}){if(super(e),console.warn("The `Impersonated` constructor does not validate the credential configuration. A security risk occurs when a credential configuration configured with malicious URLs is used. When the credential configuration is accepted from an untrusted source, you should validate it before using it with this method. For more details, see https://cloud.google.com/docs/authentication/external/externally-sourced-credentials."),this.credentials={expiry_date:1,refresh_token:"impersonated-placeholder"},this.sourceClient=e.sourceClient??new zg.OAuth2Client,this.targetPrincipal=e.targetPrincipal??"",this.delegates=e.delegates??[],this.targetScopes=e.targetScopes??[],this.lifetime=e.lifetime??3600,!!!(0,LA.originalOrCamelOptions)(e).get("universe_domain"))this.universeDomain=this.sourceClient.universeDomain;else if(this.sourceClient.universeDomain!==this.universeDomain)throw new RangeError(`Universe domain ${this.sourceClient.universeDomain} in source credentials does not match ${this.universeDomain} universe domain set for impersonated credentials.`);this.endpoint=e.endpoint??`https://iamcredentials.${this.universeDomain}`}async sign(e){await this.sourceClient.getAccessToken();let r=`projects/-/serviceAccounts/${this.targetPrincipal}`,n=`${this.endpoint}/v1/${r}:signBlob`,s={delegates:this.delegates,payload:Buffer.from(e).toString("base64")};return(await this.sourceClient.request({...t.RETRY_CONFIG,url:n,data:s,method:"POST"})).data}getTargetPrincipal(){return this.targetPrincipal}async refreshToken(){try{await this.sourceClient.getAccessToken();let e="projects/-/serviceAccounts/"+this.targetPrincipal,r=`${this.endpoint}/v1/${e}:generateAccessToken`,n={delegates:this.delegates,scope:this.targetScopes,lifetime:this.lifetime+"s"},s=await this.sourceClient.request({...t.RETRY_CONFIG,url:r,data:n,method:"POST"}),i=s.data;return this.credentials.access_token=i.accessToken,this.credentials.expiry_date=Date.parse(i.expireTime),{tokens:this.credentials,res:s}}catch(e){if(!(e instanceof Error))throw e;let r=0,n="";throw e instanceof jA.GaxiosError&&(r=e?.response?.data?.error?.status,n=e?.response?.data?.error?.message),r&&n?(e.message=`${r}: unable to impersonate: ${n}`,e):(e.message=`unable to impersonate: ${e}`,e)}}async fetchIdToken(e,r){await this.sourceClient.getAccessToken();let n=`projects/-/serviceAccounts/${this.targetPrincipal}`,s=`${this.endpoint}/v1/${n}:generateIdToken`,i={delegates:this.delegates,audience:e,includeEmail:r?.includeEmail??!0,useEmailAzp:r?.includeEmail??!0};return(await this.sourceClient.request({...t.RETRY_CONFIG,url:s,data:i,method:"POST"})).data.token}};es.Impersonated=ll});var hl=V(Gs=>{"use strict";Object.defineProperty(Gs,"__esModule",{value:!0});Gs.OAuthClientAuthHandler=void 0;Gs.getErrorFromOAuthErrorResponse=qA;var ts=Ve(),MA=Bs(),UA=["PUT","POST","PATCH"],fl=class{#e=(0,MA.createCrypto)();#t;transporter;constructor(e){e&&"clientId"in e?(this.#t=e,this.transporter=new ts.Gaxios):(this.#t=e?.clientAuthentication,this.transporter=e?.transporter||new ts.Gaxios)}applyClientAuthenticationOptions(e,r){e.headers=ts.Gaxios.mergeHeaders(e.headers),this.injectAuthenticatedHeaders(e,r),r||this.injectAuthenticatedRequestBody(e)}injectAuthenticatedHeaders(e,r){if(r)e.headers=ts.Gaxios.mergeHeaders(e.headers,{authorization:`Bearer ${r}`});else if(this.#t?.confidentialClientType==="basic"){e.headers=ts.Gaxios.mergeHeaders(e.headers);let n=this.#t.clientId,s=this.#t.clientSecret||"",i=this.#e.encodeBase64StringUtf8(`${n}:${s}`);ts.Gaxios.mergeHeaders(e.headers,{authorization:`Basic ${i}`})}}injectAuthenticatedRequestBody(e){if(this.#t?.confidentialClientType==="request-body"){let r=(e.method||"GET").toUpperCase();if(!UA.includes(r))throw new Error(`${r} HTTP method does not support ${this.#t.confidentialClientType} client authentication`);let s=new Headers(e.headers).get("content-type");if(s?.startsWith("application/x-www-form-urlencoded")||e.data instanceof URLSearchParams){let i=new URLSearchParams(e.data??"");i.append("client_id",this.#t.clientId),i.append("client_secret",this.#t.clientSecret||""),e.data=i}else if(s?.startsWith("application/json"))e.data=e.data||{},Object.assign(e.data,{client_id:this.#t.clientId,client_secret:this.#t.clientSecret||""});else throw new Error(`${s} content-types are not supported with ${this.#t.confidentialClientType} client authentication`)}}static get RETRY_CONFIG(){return{retry:!0,retryConfig:{httpMethodsToRetry:["GET","PUT","POST","HEAD","OPTIONS","DELETE"]}}}};Gs.OAuthClientAuthHandler=fl;function qA(t,e){let r=t.error,n=t.error_description,s=t.error_uri,i=`Error code ${r}`;typeof n<"u"&&(i+=`: ${n}`),typeof s<"u"&&(i+=` - ${s}`);let u=new Error(i);if(e){let c=Object.keys(e);e.stack&&c.push("stack"),c.forEach(l=>{l!=="message"&&Object.defineProperty(u,l,{value:e[l],writable:!1,enumerable:!0})})}return u}});var Gi=V(Wi=>{"use strict";Object.defineProperty(Wi,"__esModule",{value:!0});Wi.StsCredentials=void 0;var $A=Ve(),zA=pt(),Hg=hl(),HA=Ut(),pl=class t extends Hg.OAuthClientAuthHandler{#e;constructor(e={tokenExchangeEndpoint:""},r){(typeof e!="object"||e instanceof URL)&&(e={tokenExchangeEndpoint:e,clientAuthentication:r}),super(e),this.#e=e.tokenExchangeEndpoint}async exchangeToken(e,r,n){let s={grant_type:e.grantType,resource:e.resource,audience:e.audience,scope:e.scope?.join(" "),requested_token_type:e.requestedTokenType,subject_token:e.subjectToken,subject_token_type:e.subjectTokenType,actor_token:e.actingParty?.actorToken,actor_token_type:e.actingParty?.actorTokenType,options:n&&JSON.stringify(n)},i={...t.RETRY_CONFIG,url:this.#e.toString(),method:"POST",headers:r,data:new URLSearchParams((0,HA.removeUndefinedValuesInObject)(s))};zA.AuthClient.setMethodName(i,"exchangeToken"),this.applyClientAuthenticationOptions(i);try{let u=await this.transporter.request(i),c=u.data;return c.res=u,c}catch(u){throw u instanceof $A.GaxiosError&&u.response?(0,Hg.getErrorFromOAuthErrorResponse)(u.response.data,u):u}}};Wi.StsCredentials=pl});var Wr=V(Tt=>{"use strict";Object.defineProperty(Tt,"__esModule",{value:!0});Tt.BaseExternalAccountClient=Tt.CLOUD_RESOURCE_MANAGER=Tt.EXTERNAL_ACCOUNT_TYPE=Tt.EXPIRATION_TIME_OFFSET=void 0;var WA=Ve(),GA=X("stream"),ml=pt(),JA=Gi(),Wg=Ut(),VA=xc(),KA="urn:ietf:params:oauth:grant-type:token-exchange",YA="urn:ietf:params:oauth:token-type:access_token",gl="https://www.googleapis.com/auth/cloud-platform",QA=3600;Tt.EXPIRATION_TIME_OFFSET=300*1e3;Tt.EXTERNAL_ACCOUNT_TYPE="external_account";Tt.CLOUD_RESOURCE_MANAGER="https://cloudresourcemanager.googleapis.com/v1/projects/";var XA="//iam\\.googleapis\\.com/locations/[^/]+/workforcePools/[^/]+/providers/.+",ZA="https://sts.{universeDomain}/v1/token",yl=class t extends ml.AuthClient{scopes;projectNumber;audience;subjectTokenType;stsCredential;clientAuth;credentialSourceType;cachedAccessToken;serviceAccountImpersonationUrl;serviceAccountImpersonationLifetime;workforcePoolUserProject;configLifetimeRequested;tokenUrl;cloudResourceManagerURL;supplierContext;#e=null;constructor(e){super(e);let r=(0,Wg.originalOrCamelOptions)(e),n=r.get("type");if(n&&n!==Tt.EXTERNAL_ACCOUNT_TYPE)throw new Error(`Expected "${Tt.EXTERNAL_ACCOUNT_TYPE}" type but received "${e.type}"`);let s=r.get("client_id"),i=r.get("client_secret");this.tokenUrl=r.get("token_url")??ZA.replace("{universeDomain}",this.universeDomain);let u=r.get("subject_token_type"),c=r.get("workforce_pool_user_project"),l=r.get("service_account_impersonation_url"),h=r.get("service_account_impersonation"),d=(0,Wg.originalOrCamelOptions)(h).get("token_lifetime_seconds");this.cloudResourceManagerURL=new URL(r.get("cloud_resource_manager_url")||`https://cloudresourcemanager.${this.universeDomain}/v1/projects/`),s&&(this.clientAuth={confidentialClientType:"basic",clientId:s,clientSecret:i}),this.stsCredential=new JA.StsCredentials({tokenExchangeEndpoint:this.tokenUrl,clientAuthentication:this.clientAuth}),this.scopes=r.get("scopes")||[gl],this.cachedAccessToken=null,this.audience=r.get("audience"),this.subjectTokenType=u,this.workforcePoolUserProject=c;let p=new RegExp(XA);if(this.workforcePoolUserProject&&!this.audience.match(p))throw new Error("workforcePoolUserProject should not be set for non-workforce pool credentials.");this.serviceAccountImpersonationUrl=l,this.serviceAccountImpersonationLifetime=d,this.serviceAccountImpersonationLifetime?this.configLifetimeRequested=!0:(this.configLifetimeRequested=!1,this.serviceAccountImpersonationLifetime=QA),this.projectNumber=this.getProjectNumber(this.audience),this.supplierContext={audience:this.audience,subjectTokenType:this.subjectTokenType,transporter:this.transporter}}getServiceAccountEmail(){if(this.serviceAccountImpersonationUrl){if(this.serviceAccountImpersonationUrl.length>256)throw new RangeError(`URL is too long: ${this.serviceAccountImpersonationUrl}`);return/serviceAccounts\/(?<email>[^:]+):generateAccessToken$/.exec(this.serviceAccountImpersonationUrl)?.groups?.email||null}return null}setCredentials(e){super.setCredentials(e),this.cachedAccessToken=e}async getAccessToken(){return(!this.cachedAccessToken||this.isExpired(this.cachedAccessToken))&&await this.refreshAccessTokenAsync(),{token:this.cachedAccessToken.access_token,res:this.cachedAccessToken.res}}async getRequestHeaders(){let e=await this.getAccessToken(),r=new Headers({authorization:`Bearer ${e.token}`});return this.addSharedMetadataHeaders(r)}request(e,r){if(r)this.requestAsync(e).then(n=>r(null,n),n=>r(n,n.response));else return this.requestAsync(e)}async getProjectId(){let e=this.projectNumber||this.workforcePoolUserProject;if(this.projectId)return this.projectId;if(e){let r=await this.getRequestHeaders(),n={...t.RETRY_CONFIG,headers:r,url:`${this.cloudResourceManagerURL.toString()}${e}`};ml.AuthClient.setMethodName(n,"getProjectId");let s=await this.transporter.request(n);return this.projectId=s.data.projectId,this.projectId}return null}async requestAsync(e,r=!1){let n;try{let s=await this.getRequestHeaders();e.headers=WA.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,s),n=await this.transporter.request(e)}catch(s){let i=s.response;if(i){let u=i.status,c=i.config.data instanceof GA.Readable;if(!r&&(u===401||u===403)&&!c&&this.forceRefreshOnFailure)return await this.refreshAccessTokenAsync(),await this.requestAsync(e,!0)}throw s}return n}async refreshAccessTokenAsync(){this.#e=this.#e||this.#t();try{return await this.#e}finally{this.#e=null}}async#t(){let e=await this.retrieveSubjectToken(),r={grantType:KA,audience:this.audience,requestedTokenType:YA,subjectToken:e,subjectTokenType:this.subjectTokenType,scope:this.serviceAccountImpersonationUrl?[gl]:this.getScopesArray()},n=!this.clientAuth&&this.workforcePoolUserProject?{userProject:this.workforcePoolUserProject}:void 0,s=new Headers({"x-goog-api-client":this.getMetricsHeaderValue()}),i=await this.stsCredential.exchangeToken(r,s,n);return this.serviceAccountImpersonationUrl?this.cachedAccessToken=await this.getImpersonatedAccessToken(i.access_token):i.expires_in?this.cachedAccessToken={access_token:i.access_token,expiry_date:new Date().getTime()+i.expires_in*1e3,res:i.res}:this.cachedAccessToken={access_token:i.access_token,res:i.res},this.credentials={},Object.assign(this.credentials,this.cachedAccessToken),delete this.credentials.res,this.emit("tokens",{refresh_token:null,expiry_date:this.cachedAccessToken.expiry_date,access_token:this.cachedAccessToken.access_token,token_type:"Bearer",id_token:null}),this.cachedAccessToken}getProjectNumber(e){let r=e.match(/\/projects\/([^/]+)/);return r?r[1]:null}async getImpersonatedAccessToken(e){let r={...t.RETRY_CONFIG,url:this.serviceAccountImpersonationUrl,method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e}`},data:{scope:this.getScopesArray(),lifetime:this.serviceAccountImpersonationLifetime+"s"}};ml.AuthClient.setMethodName(r,"getImpersonatedAccessToken");let n=await this.transporter.request(r),s=n.data;return{access_token:s.accessToken,expiry_date:new Date(s.expireTime).getTime(),res:n}}isExpired(e){let r=new Date().getTime();return e.expiry_date?r>=e.expiry_date-this.eagerRefreshThresholdMillis:!1}getScopesArray(){return typeof this.scopes=="string"?[this.scopes]:this.scopes||[gl]}getMetricsHeaderValue(){let e=process.version.replace(/^v/,""),r=this.serviceAccountImpersonationUrl!==void 0,n=this.credentialSourceType?this.credentialSourceType:"unknown";return`gl-node/${e} auth/${VA.pkg.version} google-byoid-sdk source/${n} sa-impersonation/${r} config-lifetime/${this.configLifetimeRequested}`}getTokenUrl(){return this.tokenUrl}};Tt.BaseExternalAccountClient=yl});var Gg=V(Ji=>{"use strict";Object.defineProperty(Ji,"__esModule",{value:!0});Ji.FileSubjectTokenSupplier=void 0;var bl=X("util"),Cl=X("fs"),eS=(0,bl.promisify)(Cl.readFile??(()=>{})),tS=(0,bl.promisify)(Cl.realpath??(()=>{})),rS=(0,bl.promisify)(Cl.lstat??(()=>{})),_l=class{filePath;formatType;subjectTokenFieldName;constructor(e){this.filePath=e.filePath,this.formatType=e.formatType,this.subjectTokenFieldName=e.subjectTokenFieldName}async getSubjectToken(){let e=this.filePath;try{if(e=await tS(e),!(await rS(e)).isFile())throw new Error}catch(s){throw s instanceof Error&&(s.message=`The file at ${e} does not exist, or it is not a file. ${s.message}`),s}let r,n=await eS(e,{encoding:"utf8"});if(this.formatType==="text"?r=n:this.formatType==="json"&&this.subjectTokenFieldName&&(r=JSON.parse(n)[this.subjectTokenFieldName]),!r)throw new Error("Unable to parse the subject_token from the credential_source file");return r}};Ji.FileSubjectTokenSupplier=_l});var Jg=V(Vi=>{"use strict";Object.defineProperty(Vi,"__esModule",{value:!0});Vi.UrlSubjectTokenSupplier=void 0;var nS=pt(),wl=class{url;headers;formatType;subjectTokenFieldName;additionalGaxiosOptions;constructor(e){this.url=e.url,this.formatType=e.formatType,this.subjectTokenFieldName=e.subjectTokenFieldName,this.headers=e.headers,this.additionalGaxiosOptions=e.additionalGaxiosOptions}async getSubjectToken(e){let r={...this.additionalGaxiosOptions,url:this.url,method:"GET",headers:this.headers};nS.AuthClient.setMethodName(r,"getSubjectToken");let n;if(this.formatType==="text"?n=(await e.transporter.request(r)).data:this.formatType==="json"&&this.subjectTokenFieldName&&(n=(await e.transporter.request(r)).data[this.subjectTokenFieldName]),!n)throw new Error("Unable to parse the subject_token from the credential_source URL");return n}};Vi.UrlSubjectTokenSupplier=wl});var Vg=V(_t=>{"use strict";Object.defineProperty(_t,"__esModule",{value:!0});_t.CertificateSubjectTokenSupplier=_t.InvalidConfigurationError=_t.CertificateSourceUnavailableError=_t.CERTIFICATE_CONFIGURATION_ENV_VARIABLE=void 0;var Ki=Ut(),Yi=X("fs"),Qi=X("crypto"),sS=X("https");_t.CERTIFICATE_CONFIGURATION_ENV_VARIABLE="GOOGLE_API_CERTIFICATE_CONFIG";var rr=class extends Error{constructor(e){super(e),this.name="CertificateSourceUnavailableError"}};_t.CertificateSourceUnavailableError=rr;var Dt=class extends Error{constructor(e){super(e),this.name="InvalidConfigurationError"}};_t.InvalidConfigurationError=Dt;var El=class{certificateConfigPath;trustChainPath;cert;key;constructor(e){if(!e.useDefaultCertificateConfig&&!e.certificateConfigLocation)throw new Dt("Either `useDefaultCertificateConfig` must be true or a `certificateConfigLocation` must be provided.");if(e.useDefaultCertificateConfig&&e.certificateConfigLocation)throw new Dt("Both `useDefaultCertificateConfig` and `certificateConfigLocation` cannot be provided.");this.trustChainPath=e.trustChainPath,this.certificateConfigPath=e.certificateConfigLocation??""}async createMtlsHttpsAgent(){if(!this.key||!this.cert)throw new Dt("Cannot create mTLS Agent with missing certificate or key");return new sS.Agent({key:this.key,cert:this.cert})}async getSubjectToken(){this.certificateConfigPath=await this.#e();let{certPath:e,keyPath:r}=await this.#t();return{cert:this.cert,key:this.key}=await this.#r(e,r),await this.#n(this.cert)}async#e(){let e=this.certificateConfigPath;if(e){if(await(0,Ki.isValidFile)(e))return e;throw new rr(`Provided certificate config path is invalid: ${e}`)}let r=process.env[_t.CERTIFICATE_CONFIGURATION_ENV_VARIABLE];if(r){if(await(0,Ki.isValidFile)(r))return r;throw new rr(`Path from environment variable "${_t.CERTIFICATE_CONFIGURATION_ENV_VARIABLE}" is invalid: ${r}`)}let n=(0,Ki.getWellKnownCertificateConfigFileLocation)();if(await(0,Ki.isValidFile)(n))return n;throw new rr(`Could not find certificate configuration file. Searched override path, the "${_t.CERTIFICATE_CONFIGURATION_ENV_VARIABLE}" env var, and the gcloud path (${n}).`)}async#t(){let e=this.certificateConfigPath,r;try{r=await Yi.promises.readFile(e,"utf8")}catch{throw new rr(`Failed to read certificate config file at: ${e}`)}try{let n=JSON.parse(r),s=n?.cert_configs?.workload?.cert_path,i=n?.cert_configs?.workload?.key_path;if(!s||!i)throw new Dt(`Certificate config file (${e}) is missing required "cert_path" or "key_path" in the workload config.`);return{certPath:s,keyPath:i}}catch(n){throw n instanceof Dt?n:new Dt(`Failed to parse certificate config from ${e}: ${n.message}`)}}async#r(e,r){let n,s;try{n=await Yi.promises.readFile(e),new Qi.X509Certificate(n)}catch(i){let u=i instanceof Error?i.message:String(i);throw new rr(`Failed to read certificate file at ${e}: ${u}`)}try{s=await Yi.promises.readFile(r),(0,Qi.createPrivateKey)(s)}catch(i){let u=i instanceof Error?i.message:String(i);throw new rr(`Failed to read private key file at ${r}: ${u}`)}return{cert:n,key:s}}async#n(e){let r=new Qi.X509Certificate(e);if(!this.trustChainPath)return JSON.stringify([r.raw.toString("base64")]);try{let i=((await Yi.promises.readFile(this.trustChainPath,"utf8")).match(/-----BEGIN CERTIFICATE-----[^-]+-----END CERTIFICATE-----/g)??[]).map((l,h)=>{try{return new Qi.X509Certificate(l)}catch(d){let p=d instanceof Error?d.message:String(d);throw new Dt(`Failed to parse certificate at index ${h} in trust chain file ${this.trustChainPath}: ${p}`)}}),u=i.findIndex(l=>r.raw.equals(l.raw)),c;if(u===-1)c=[r,...i];else if(u===0)c=i;else throw new Dt(`Leaf certificate exists in the trust chain but is not the first entry (found at index ${u}).`);return JSON.stringify(c.map(l=>l.raw.toString("base64")))}catch(n){if(n instanceof Dt)throw n;let s=n instanceof Error?n.message:String(n);throw new rr(`Failed to process certificate chain from ${this.trustChainPath}: ${s}`)}}};_t.CertificateSubjectTokenSupplier=El});var vl=V(Xi=>{"use strict";Object.defineProperty(Xi,"__esModule",{value:!0});Xi.IdentityPoolClient=void 0;var oS=Wr(),Al=Ut(),iS=Gg(),aS=Jg(),Kg=Vg(),uS=Gi(),Yg=Ve(),Sl=class t extends oS.BaseExternalAccountClient{subjectTokenSupplier;constructor(e){super(e);let r=(0,Al.originalOrCamelOptions)(e),n=r.get("credential_source"),s=r.get("subject_token_supplier");if(!n&&!s)throw new Error("A credential source or subject token supplier must be specified.");if(n&&s)throw new Error("Only one of credential source or subject token supplier can be specified.");if(s)this.subjectTokenSupplier=s,this.credentialSourceType="programmatic";else{let i=(0,Al.originalOrCamelOptions)(n),u=(0,Al.originalOrCamelOptions)(i.get("format")),c=u.get("type")||"text",l=u.get("subject_token_field_name");if(c!=="json"&&c!=="text")throw new Error(`Invalid credential_source format "${c}"`);if(c==="json"&&!l)throw new Error("Missing subject_token_field_name for JSON credential_source format");let h=i.get("file"),d=i.get("url"),p=i.get("certificate"),w=i.get("headers");if(h&&d||d&&p||h&&p)throw new Error('No valid Identity Pool "credential_source" provided, must be either file, url, or certificate.');if(h)this.credentialSourceType="file",this.subjectTokenSupplier=new iS.FileSubjectTokenSupplier({filePath:h,formatType:c,subjectTokenFieldName:l});else if(d)this.credentialSourceType="url",this.subjectTokenSupplier=new aS.UrlSubjectTokenSupplier({url:d,formatType:c,subjectTokenFieldName:l,headers:w,additionalGaxiosOptions:t.RETRY_CONFIG});else if(p){this.credentialSourceType="certificate";let T=new Kg.CertificateSubjectTokenSupplier({useDefaultCertificateConfig:p.use_default_certificate_config,certificateConfigLocation:p.certificate_config_location,trustChainPath:p.trust_chain_path});this.subjectTokenSupplier=T}else throw new Error('No valid Identity Pool "credential_source" provided, must be either file, url, or certificate.')}}async retrieveSubjectToken(){let e=await this.subjectTokenSupplier.getSubjectToken(this.supplierContext);if(this.subjectTokenSupplier instanceof Kg.CertificateSubjectTokenSupplier){let r=await this.subjectTokenSupplier.createMtlsHttpsAgent();this.stsCredential=new uS.StsCredentials({tokenExchangeEndpoint:this.getTokenUrl(),clientAuthentication:this.clientAuth,transporter:new Yg.Gaxios({agent:r})}),this.transporter=new Yg.Gaxios({...this.transporter.defaults||{},agent:r})}return e}};Xi.IdentityPoolClient=Sl});var Tl=V(ea=>{"use strict";Object.defineProperty(ea,"__esModule",{value:!0});ea.AwsRequestSigner=void 0;var Zi=Ve(),Xg=Bs(),Qg="AWS4-HMAC-SHA256",cS="aws4_request",kl=class{getCredentials;region;crypto;constructor(e,r){this.getCredentials=e,this.region=r,this.crypto=(0,Xg.createCrypto)()}async getRequestOptions(e){if(!e.url)throw new RangeError('"url" is required in "amzOptions"');let r=typeof e.data=="object"?JSON.stringify(e.data):e.data,n=e.url,s=e.method||"GET",i=e.body||r,u=e.headers,c=await this.getCredentials(),l=new URL(n);if(typeof i!="string"&&i!==void 0)throw new TypeError(`'requestPayload' is expected to be a string if provided. Got: ${i}`);let h=await dS({crypto:this.crypto,host:l.host,canonicalUri:l.pathname,canonicalQuerystring:l.search.slice(1),method:s,region:this.region,securityCredentials:c,requestPayload:i,additionalAmzHeaders:u}),d=Zi.Gaxios.mergeHeaders(h.amzDate?{"x-amz-date":h.amzDate}:{},{authorization:h.authorizationHeader,host:l.host},u||{});c.token&&Zi.Gaxios.mergeHeaders(d,{"x-amz-security-token":c.token});let p={url:n,method:s,headers:d};return i!==void 0&&(p.body=i),p}};ea.AwsRequestSigner=kl;async function Js(t,e,r){return await t.signWithHmacSha256(e,r)}async function lS(t,e,r,n,s){let i=await Js(t,`AWS4${e}`,r),u=await Js(t,i,n),c=await Js(t,u,s);return await Js(t,c,"aws4_request")}async function dS(t){let e=Zi.Gaxios.mergeHeaders(t.additionalAmzHeaders),r=t.requestPayload||"",n=t.host.split(".")[0],s=new Date,i=s.toISOString().replace(/[-:]/g,"").replace(/\.[0-9]+/,""),u=s.toISOString().replace(/[-]/g,"").replace(/T.*/,"");t.securityCredentials.token&&e.set("x-amz-security-token",t.securityCredentials.token);let c=Zi.Gaxios.mergeHeaders({host:t.host},e.has("date")?{}:{"x-amz-date":i},e),l="",h=[...c.keys()].sort();h.forEach(v=>{l+=`${v}:${c.get(v)}
|
|
53
|
+
`});let d=h.join(";"),p=await t.crypto.sha256DigestHex(r),w=`${t.method.toUpperCase()}
|
|
54
54
|
${t.canonicalUri}
|
|
55
55
|
${t.canonicalQuerystring}
|
|
56
56
|
${l}
|
|
57
57
|
${d}
|
|
58
|
-
${p}`,
|
|
58
|
+
${p}`,T=`${u}/${t.region}/${n}/${cS}`,S=`${Qg}
|
|
59
59
|
${i}
|
|
60
|
-
${
|
|
61
|
-
`+await t.crypto.sha256DigestHex(A),y=await zA(t.crypto,t.securityCredentials.secretAccessKey,u,t.region,n),g=await Hs(t.crypto,y,S),m=`${Bg} Credential=${t.securityCredentials.accessKeyId}/${v}, SignedHeaders=${d}, Signature=${(0,jg.fromArrayBufferToHex)(g)}`;return{amzDate:e.has("date")?void 0:i,authorizationHeader:m,canonicalQuerystring:t.canonicalQuerystring}}});var Lg=V(Qi=>{"use strict";Object.defineProperty(Qi,"__esModule",{value:!0});Qi.DefaultAwsSecurityCredentialsSupplier=void 0;var Xi=pt(),Al=class{regionUrl;securityCredentialsUrl;imdsV2SessionTokenUrl;additionalGaxiosOptions;constructor(e){this.regionUrl=e.regionUrl,this.securityCredentialsUrl=e.securityCredentialsUrl,this.imdsV2SessionTokenUrl=e.imdsV2SessionTokenUrl,this.additionalGaxiosOptions=e.additionalGaxiosOptions}async getAwsRegion(e){if(this.#n)return this.#n;let r=new Headers;if(!this.#n&&this.imdsV2SessionTokenUrl&&r.set("x-aws-ec2-metadata-token",await this.#e(e.transporter)),!this.regionUrl)throw new RangeError('Unable to determine AWS region due to missing "options.credential_source.region_url"');let n={...this.additionalGaxiosOptions,url:this.regionUrl,method:"GET",headers:r};Xi.AuthClient.setMethodName(n,"getAwsRegion");let s=await e.transporter.request(n);return s.data.substr(0,s.data.length-1)}async getAwsSecurityCredentials(e){if(this.#s)return this.#s;let r=new Headers;this.imdsV2SessionTokenUrl&&r.set("x-aws-ec2-metadata-token",await this.#e(e.transporter));let n=await this.#t(r,e.transporter),s=await this.#r(n,r,e.transporter);return{accessKeyId:s.AccessKeyId,secretAccessKey:s.SecretAccessKey,token:s.Token}}async#e(e){let r={...this.additionalGaxiosOptions,url:this.imdsV2SessionTokenUrl,method:"PUT",headers:{"x-aws-ec2-metadata-token-ttl-seconds":"300"}};return Xi.AuthClient.setMethodName(r,"#getImdsV2SessionToken"),(await e.request(r)).data}async#t(e,r){if(!this.securityCredentialsUrl)throw new Error('Unable to determine AWS role name due to missing "options.credential_source.url"');let n={...this.additionalGaxiosOptions,url:this.securityCredentialsUrl,method:"GET",headers:e};return Xi.AuthClient.setMethodName(n,"#getAwsRoleName"),(await r.request(n)).data}async#r(e,r,n){let s={...this.additionalGaxiosOptions,url:`${this.securityCredentialsUrl}/${e}`,headers:r};return Xi.AuthClient.setMethodName(s,"#retrieveAwsSecurityCredentials"),(await n.request(s)).data}get#n(){return process.env.AWS_REGION||process.env.AWS_DEFAULT_REGION||null}get#s(){return process.env.AWS_ACCESS_KEY_ID&&process.env.AWS_SECRET_ACCESS_KEY?{accessKeyId:process.env.AWS_ACCESS_KEY_ID,secretAccessKey:process.env.AWS_SECRET_ACCESS_KEY,token:process.env.AWS_SESSION_TOKEN}:null}};Qi.DefaultAwsSecurityCredentialsSupplier=Al});var kl=V(Zi=>{"use strict";Object.defineProperty(Zi,"__esModule",{value:!0});Zi.AwsClient=void 0;var WA=El(),GA=zr(),JA=Lg(),Mg=Ut(),VA=Ve(),Sl=class t extends GA.BaseExternalAccountClient{environmentId;awsSecurityCredentialsSupplier;regionalCredVerificationUrl;awsRequestSigner;region;static#e="https://sts.{region}.amazonaws.com?Action=GetCallerIdentity&Version=2011-06-15";static AWS_EC2_METADATA_IPV4_ADDRESS="169.254.169.254";static AWS_EC2_METADATA_IPV6_ADDRESS="fd00:ec2::254";constructor(e){super(e);let r=(0,Mg.originalOrCamelOptions)(e),n=r.get("credential_source"),s=r.get("aws_security_credentials_supplier");if(!n&&!s)throw new Error("A credential source or AWS security credentials supplier must be specified.");if(n&&s)throw new Error("Only one of credential source or AWS security credentials supplier can be specified.");if(s)this.awsSecurityCredentialsSupplier=s,this.regionalCredVerificationUrl=t.#e,this.credentialSourceType="programmatic";else{let i=(0,Mg.originalOrCamelOptions)(n);this.environmentId=i.get("environment_id");let u=i.get("region_url"),c=i.get("url"),l=i.get("imdsv2_session_token_url");this.awsSecurityCredentialsSupplier=new JA.DefaultAwsSecurityCredentialsSupplier({regionUrl:u,securityCredentialsUrl:c,imdsV2SessionTokenUrl:l}),this.regionalCredVerificationUrl=i.get("regional_cred_verification_url"),this.credentialSourceType="aws",this.validateEnvironmentId()}this.awsRequestSigner=null,this.region=""}validateEnvironmentId(){let e=this.environmentId?.match(/^(aws)(\d+)$/);if(!e||!this.regionalCredVerificationUrl)throw new Error('No valid AWS "credential_source" provided');if(parseInt(e[2],10)!==1)throw new Error(`aws version "${e[2]}" is not supported in the current build.`)}async retrieveSubjectToken(){this.awsRequestSigner||(this.region=await this.awsSecurityCredentialsSupplier.getAwsRegion(this.supplierContext),this.awsRequestSigner=new WA.AwsRequestSigner(async()=>this.awsSecurityCredentialsSupplier.getAwsSecurityCredentials(this.supplierContext),this.region));let e=await this.awsRequestSigner.getRequestOptions({...t.RETRY_CONFIG,url:this.regionalCredVerificationUrl.replace("{region}",this.region),method:"POST"}),r=[];return VA.Gaxios.mergeHeaders({"x-goog-cloud-target-resource":this.audience},e.headers).forEach((s,i)=>r.push({key:i,value:s})),encodeURIComponent(JSON.stringify({url:e.url,method:e.method,headers:r}))}};Zi.AwsClient=Sl});var Ol=V(Le=>{"use strict";Object.defineProperty(Le,"__esModule",{value:!0});Le.InvalidSubjectTokenError=Le.InvalidMessageFieldError=Le.InvalidCodeFieldError=Le.InvalidTokenTypeFieldError=Le.InvalidExpirationTimeFieldError=Le.InvalidSuccessFieldError=Le.InvalidVersionFieldError=Le.ExecutableResponseError=Le.ExecutableResponse=void 0;var ea="urn:ietf:params:oauth:token-type:saml2",Tl="urn:ietf:params:oauth:token-type:id_token",Dl="urn:ietf:params:oauth:token-type:jwt",vl=class{version;success;expirationTime;tokenType;errorCode;errorMessage;subjectToken;constructor(e){if(!e.version)throw new ta("Executable response must contain a 'version' field.");if(e.success===void 0)throw new ra("Executable response must contain a 'success' field.");if(this.version=e.version,this.success=e.success,this.success){if(this.expirationTime=e.expiration_time,this.tokenType=e.token_type,this.tokenType!==ea&&this.tokenType!==Tl&&this.tokenType!==Dl)throw new na(`Executable response must contain a 'token_type' field when successful and it must be one of ${Tl}, ${Dl}, or ${ea}.`);if(this.tokenType===ea){if(!e.saml_response)throw new Ws(`Executable response must contain a 'saml_response' field when token_type=${ea}.`);this.subjectToken=e.saml_response}else{if(!e.id_token)throw new Ws(`Executable response must contain a 'id_token' field when token_type=${Tl} or ${Dl}.`);this.subjectToken=e.id_token}}else{if(!e.code)throw new sa("Executable response must contain a 'code' field when unsuccessful.");if(!e.message)throw new oa("Executable response must contain a 'message' field when unsuccessful.");this.errorCode=e.code,this.errorMessage=e.message}}isValid(){return!this.isExpired()&&this.success}isExpired(){return this.expirationTime!==void 0&&this.expirationTime<Math.round(Date.now()/1e3)}};Le.ExecutableResponse=vl;var rr=class extends Error{constructor(e){super(e),Object.setPrototypeOf(this,new.target.prototype)}};Le.ExecutableResponseError=rr;var ta=class extends rr{};Le.InvalidVersionFieldError=ta;var ra=class extends rr{};Le.InvalidSuccessFieldError=ra;var Rl=class extends rr{};Le.InvalidExpirationTimeFieldError=Rl;var na=class extends rr{};Le.InvalidTokenTypeFieldError=na;var sa=class extends rr{};Le.InvalidCodeFieldError=sa;var oa=class extends rr{};Le.InvalidMessageFieldError=oa;var Ws=class extends rr{};Le.InvalidSubjectTokenError=Ws});var Pl=V(es=>{"use strict";Object.defineProperty(es,"__esModule",{value:!0});es.PluggableAuthHandler=es.ExecutableError=void 0;var dn=Ol(),KA=Q("child_process"),xl=Q("fs"),ia=class extends Error{code;constructor(e,r){super(`The executable failed with exit code: ${r} and error message: ${e}.`),this.code=r,Object.setPrototypeOf(this,new.target.prototype)}};es.ExecutableError=ia;var Fl=class t{commandComponents;timeoutMillis;outputFile;constructor(e){if(!e.command)throw new Error("No command provided.");if(this.commandComponents=t.parseCommand(e.command),this.timeoutMillis=e.timeoutMillis,!this.timeoutMillis)throw new Error("No timeoutMillis provided.");this.outputFile=e.outputFile}retrieveResponseFromExecutable(e){return new Promise((r,n)=>{let s=KA.spawn(this.commandComponents[0],this.commandComponents.slice(1),{env:{...process.env,...Object.fromEntries(e)}}),i="";s.stdout.on("data",c=>{i+=c}),s.stderr.on("data",c=>{i+=c});let u=setTimeout(()=>(s.removeAllListeners(),s.kill(),n(new Error("The executable failed to finish within the timeout specified."))),this.timeoutMillis);s.on("close",c=>{if(clearTimeout(u),c===0)try{let l=JSON.parse(i),h=new dn.ExecutableResponse(l);return r(h)}catch(l){return l instanceof dn.ExecutableResponseError?n(l):n(new dn.ExecutableResponseError(`The executable returned an invalid response: ${i}`))}else return n(new ia(i,c.toString()))})})}async retrieveCachedResponse(){if(!this.outputFile||this.outputFile.length===0)return;let e;try{e=await xl.promises.realpath(this.outputFile)}catch{return}if(!(await xl.promises.lstat(e)).isFile())return;let r=await xl.promises.readFile(e,{encoding:"utf8"});if(r!=="")try{let n=JSON.parse(r);return new dn.ExecutableResponse(n).isValid()?new dn.ExecutableResponse(n):void 0}catch(n){throw n instanceof dn.ExecutableResponseError?n:new dn.ExecutableResponseError(`The output file contained an invalid response: ${r}`)}}static parseCommand(e){let r=e.match(/(?:[^\s"]+|"[^"]*")+/g);if(!r)throw new Error(`Provided command: "${e}" could not be parsed.`);for(let n=0;n<r.length;n++)r[n][0]==='"'&&r[n].slice(-1)==='"'&&(r[n]=r[n].slice(1,-1));return r}};es.PluggableAuthHandler=Fl});var Nl=V(ts=>{"use strict";Object.defineProperty(ts,"__esModule",{value:!0});ts.PluggableAuthClient=ts.ExecutableError=void 0;var YA=zr(),XA=Ol(),Ug=Pl(),QA=Pl();Object.defineProperty(ts,"ExecutableError",{enumerable:!0,get:function(){return QA.ExecutableError}});var ZA=30*1e3,qg=5*1e3,$g=120*1e3,eS="GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES",zg=1,Il=class extends YA.BaseExternalAccountClient{command;timeoutMillis;outputFile;handler;constructor(e){if(super(e),!e.credential_source.executable)throw new Error('No valid Pluggable Auth "credential_source" provided.');if(this.command=e.credential_source.executable.command,!this.command)throw new Error('No valid Pluggable Auth "credential_source" provided.');if(e.credential_source.executable.timeout_millis===void 0)this.timeoutMillis=ZA;else if(this.timeoutMillis=e.credential_source.executable.timeout_millis,this.timeoutMillis<qg||this.timeoutMillis>$g)throw new Error(`Timeout must be between ${qg} and ${$g} milliseconds.`);this.outputFile=e.credential_source.executable.output_file,this.handler=new Ug.PluggableAuthHandler({command:this.command,timeoutMillis:this.timeoutMillis,outputFile:this.outputFile}),this.credentialSourceType="executable"}async retrieveSubjectToken(){if(process.env[eS]!=="1")throw new Error("Pluggable Auth executables need to be explicitly allowed to run by setting the GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES environment Variable to 1.");let e;if(this.outputFile&&(e=await this.handler.retrieveCachedResponse()),!e){let r=new Map;r.set("GOOGLE_EXTERNAL_ACCOUNT_AUDIENCE",this.audience),r.set("GOOGLE_EXTERNAL_ACCOUNT_TOKEN_TYPE",this.subjectTokenType),r.set("GOOGLE_EXTERNAL_ACCOUNT_INTERACTIVE","0"),this.outputFile&&r.set("GOOGLE_EXTERNAL_ACCOUNT_OUTPUT_FILE",this.outputFile);let n=this.getServiceAccountEmail();n&&r.set("GOOGLE_EXTERNAL_ACCOUNT_IMPERSONATED_EMAIL",n),e=await this.handler.retrieveResponseFromExecutable(r)}if(e.version>zg)throw new Error(`Version of executable is not currently supported, maximum supported version is ${zg}.`);if(!e.success)throw new Ug.ExecutableError(e.errorMessage,e.errorCode);if(this.outputFile&&!e.expirationTime)throw new XA.InvalidExpirationTimeFieldError("The executable response must contain the `expiration_time` field for successful responses when an output_file has been specified in the configuration.");if(e.isExpired())throw new Error("Executable response is expired.");return e.subjectToken}};ts.PluggableAuthClient=Il});var jl=V(aa=>{"use strict";Object.defineProperty(aa,"__esModule",{value:!0});aa.ExternalAccountClient=void 0;var tS=zr(),rS=Cl(),nS=kl(),sS=Nl(),Bl=class{constructor(){throw new Error("ExternalAccountClients should be initialized via: ExternalAccountClient.fromJSON(), directly via explicit constructors, eg. new AwsClient(options), new IdentityPoolClient(options), newPluggableAuthClientOptions, or via new GoogleAuth(options).getClient()")}static fromJSON(e){return console.warn("The `fromJSON` method does not validate the credential configuration. A security risk occurs when a credential configuration configured with malicious URLs is used. When the credential configuration is accepted from an untrusted source, you should validate it before using it with this method. For more details, see https://cloud.google.com/docs/authentication/external/externally-sourced-credentials."),e&&e.type===tS.EXTERNAL_ACCOUNT_TYPE?e.credential_source?.environment_id?new nS.AwsClient(e):e.credential_source?.executable?new sS.PluggableAuthClient(e):new rS.IdentityPoolClient(e):null}};aa.ExternalAccountClient=Bl});var Jg=V(rs=>{"use strict";Object.defineProperty(rs,"__esModule",{value:!0});rs.ExternalAccountAuthorizedUserClient=rs.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE=void 0;var Wg=pt(),Hg=ul(),Gg=Ve(),oS=Q("stream"),iS=zr();rs.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE="external_account_authorized_user";var aS="https://sts.{universeDomain}/v1/oauthtoken",Ll=class t extends Hg.OAuthClientAuthHandler{#e;constructor(e){super(e),this.#e=e.tokenRefreshEndpoint}async refreshToken(e,r){let n={...t.RETRY_CONFIG,url:this.#e,method:"POST",headers:r,data:new URLSearchParams({grant_type:"refresh_token",refresh_token:e})};Wg.AuthClient.setMethodName(n,"refreshToken"),this.applyClientAuthenticationOptions(n);try{let s=await this.transporter.request(n),i=s.data;return i.res=s,i}catch(s){throw s instanceof Gg.GaxiosError&&s.response?(0,Hg.getErrorFromOAuthErrorResponse)(s.response.data,s):s}}},Ml=class extends Wg.AuthClient{cachedAccessToken;externalAccountAuthorizedUserHandler;refreshToken;constructor(e){super(e),e.universe_domain&&(this.universeDomain=e.universe_domain),this.refreshToken=e.refresh_token;let r={confidentialClientType:"basic",clientId:e.client_id,clientSecret:e.client_secret};this.externalAccountAuthorizedUserHandler=new Ll({tokenRefreshEndpoint:e.token_url??aS.replace("{universeDomain}",this.universeDomain),transporter:this.transporter,clientAuthentication:r}),this.cachedAccessToken=null,this.quotaProjectId=e.quota_project_id,typeof e?.eagerRefreshThresholdMillis!="number"?this.eagerRefreshThresholdMillis=iS.EXPIRATION_TIME_OFFSET:this.eagerRefreshThresholdMillis=e.eagerRefreshThresholdMillis,this.forceRefreshOnFailure=!!e?.forceRefreshOnFailure}async getAccessToken(){return(!this.cachedAccessToken||this.isExpired(this.cachedAccessToken))&&await this.refreshAccessTokenAsync(),{token:this.cachedAccessToken.access_token,res:this.cachedAccessToken.res}}async getRequestHeaders(){let e=await this.getAccessToken(),r=new Headers({authorization:`Bearer ${e.token}`});return this.addSharedMetadataHeaders(r)}request(e,r){if(r)this.requestAsync(e).then(n=>r(null,n),n=>r(n,n.response));else return this.requestAsync(e)}async requestAsync(e,r=!1){let n;try{let s=await this.getRequestHeaders();e.headers=Gg.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,s),n=await this.transporter.request(e)}catch(s){let i=s.response;if(i){let u=i.status,c=i.config.data instanceof oS.Readable;if(!r&&(u===401||u===403)&&!c&&this.forceRefreshOnFailure)return await this.refreshAccessTokenAsync(),await this.requestAsync(e,!0)}throw s}return n}async refreshAccessTokenAsync(){let e=await this.externalAccountAuthorizedUserHandler.refreshToken(this.refreshToken);return this.cachedAccessToken={access_token:e.access_token,expiry_date:new Date().getTime()+e.expires_in*1e3,res:e.res},e.refresh_token!==void 0&&(this.refreshToken=e.refresh_token),this.cachedAccessToken}isExpired(e){let r=new Date().getTime();return e.expiry_date?r>=e.expiry_date-this.eagerRefreshThresholdMillis:!1}};rs.ExternalAccountAuthorizedUserClient=Ml});var Xg=V(Ht=>{"use strict";Object.defineProperty(Ht,"__esModule",{value:!0});Ht.GoogleAuth=Ht.GoogleAuthExceptionMessages=void 0;var uS=Q("child_process"),Gs=Q("fs"),cS=Ve(),Js=Fs(),lS=Q("os"),Ul=Q("path"),fS=Ps(),dS=Ic(),hS=Bc(),pS=jc(),ns=rl(),Vg=sl(),ss=il(),mS=jl(),Vs=zr(),ql=pt(),Kg=Jg(),Yg=Ut();Ht.GoogleAuthExceptionMessages={API_KEY_WITH_CREDENTIALS:"API Keys and Credentials are mutually exclusive authentication methods and cannot be used together.",NO_PROJECT_ID_FOUND:`Unable to detect a Project Id in the current environment.
|
|
60
|
+
${T}
|
|
61
|
+
`+await t.crypto.sha256DigestHex(w),y=await lS(t.crypto,t.securityCredentials.secretAccessKey,u,t.region,n),g=await Js(t.crypto,y,S),m=`${Qg} Credential=${t.securityCredentials.accessKeyId}/${T}, SignedHeaders=${d}, Signature=${(0,Xg.fromArrayBufferToHex)(g)}`;return{amzDate:e.has("date")?void 0:i,authorizationHeader:m,canonicalQuerystring:t.canonicalQuerystring}}});var Zg=V(ra=>{"use strict";Object.defineProperty(ra,"__esModule",{value:!0});ra.DefaultAwsSecurityCredentialsSupplier=void 0;var ta=pt(),Dl=class{regionUrl;securityCredentialsUrl;imdsV2SessionTokenUrl;additionalGaxiosOptions;constructor(e){this.regionUrl=e.regionUrl,this.securityCredentialsUrl=e.securityCredentialsUrl,this.imdsV2SessionTokenUrl=e.imdsV2SessionTokenUrl,this.additionalGaxiosOptions=e.additionalGaxiosOptions}async getAwsRegion(e){if(this.#n)return this.#n;let r=new Headers;if(!this.#n&&this.imdsV2SessionTokenUrl&&r.set("x-aws-ec2-metadata-token",await this.#e(e.transporter)),!this.regionUrl)throw new RangeError('Unable to determine AWS region due to missing "options.credential_source.region_url"');let n={...this.additionalGaxiosOptions,url:this.regionUrl,method:"GET",headers:r};ta.AuthClient.setMethodName(n,"getAwsRegion");let s=await e.transporter.request(n);return s.data.substr(0,s.data.length-1)}async getAwsSecurityCredentials(e){if(this.#s)return this.#s;let r=new Headers;this.imdsV2SessionTokenUrl&&r.set("x-aws-ec2-metadata-token",await this.#e(e.transporter));let n=await this.#t(r,e.transporter),s=await this.#r(n,r,e.transporter);return{accessKeyId:s.AccessKeyId,secretAccessKey:s.SecretAccessKey,token:s.Token}}async#e(e){let r={...this.additionalGaxiosOptions,url:this.imdsV2SessionTokenUrl,method:"PUT",headers:{"x-aws-ec2-metadata-token-ttl-seconds":"300"}};return ta.AuthClient.setMethodName(r,"#getImdsV2SessionToken"),(await e.request(r)).data}async#t(e,r){if(!this.securityCredentialsUrl)throw new Error('Unable to determine AWS role name due to missing "options.credential_source.url"');let n={...this.additionalGaxiosOptions,url:this.securityCredentialsUrl,method:"GET",headers:e};return ta.AuthClient.setMethodName(n,"#getAwsRoleName"),(await r.request(n)).data}async#r(e,r,n){let s={...this.additionalGaxiosOptions,url:`${this.securityCredentialsUrl}/${e}`,headers:r};return ta.AuthClient.setMethodName(s,"#retrieveAwsSecurityCredentials"),(await n.request(s)).data}get#n(){return process.env.AWS_REGION||process.env.AWS_DEFAULT_REGION||null}get#s(){return process.env.AWS_ACCESS_KEY_ID&&process.env.AWS_SECRET_ACCESS_KEY?{accessKeyId:process.env.AWS_ACCESS_KEY_ID,secretAccessKey:process.env.AWS_SECRET_ACCESS_KEY,token:process.env.AWS_SESSION_TOKEN}:null}};ra.DefaultAwsSecurityCredentialsSupplier=Dl});var xl=V(na=>{"use strict";Object.defineProperty(na,"__esModule",{value:!0});na.AwsClient=void 0;var fS=Tl(),hS=Wr(),pS=Zg(),ey=Ut(),mS=Ve(),Rl=class t extends hS.BaseExternalAccountClient{environmentId;awsSecurityCredentialsSupplier;regionalCredVerificationUrl;awsRequestSigner;region;static#e="https://sts.{region}.amazonaws.com?Action=GetCallerIdentity&Version=2011-06-15";static AWS_EC2_METADATA_IPV4_ADDRESS="169.254.169.254";static AWS_EC2_METADATA_IPV6_ADDRESS="fd00:ec2::254";constructor(e){super(e);let r=(0,ey.originalOrCamelOptions)(e),n=r.get("credential_source"),s=r.get("aws_security_credentials_supplier");if(!n&&!s)throw new Error("A credential source or AWS security credentials supplier must be specified.");if(n&&s)throw new Error("Only one of credential source or AWS security credentials supplier can be specified.");if(s)this.awsSecurityCredentialsSupplier=s,this.regionalCredVerificationUrl=t.#e,this.credentialSourceType="programmatic";else{let i=(0,ey.originalOrCamelOptions)(n);this.environmentId=i.get("environment_id");let u=i.get("region_url"),c=i.get("url"),l=i.get("imdsv2_session_token_url");this.awsSecurityCredentialsSupplier=new pS.DefaultAwsSecurityCredentialsSupplier({regionUrl:u,securityCredentialsUrl:c,imdsV2SessionTokenUrl:l}),this.regionalCredVerificationUrl=i.get("regional_cred_verification_url"),this.credentialSourceType="aws",this.validateEnvironmentId()}this.awsRequestSigner=null,this.region=""}validateEnvironmentId(){let e=this.environmentId?.match(/^(aws)(\d+)$/);if(!e||!this.regionalCredVerificationUrl)throw new Error('No valid AWS "credential_source" provided');if(parseInt(e[2],10)!==1)throw new Error(`aws version "${e[2]}" is not supported in the current build.`)}async retrieveSubjectToken(){this.awsRequestSigner||(this.region=await this.awsSecurityCredentialsSupplier.getAwsRegion(this.supplierContext),this.awsRequestSigner=new fS.AwsRequestSigner(async()=>this.awsSecurityCredentialsSupplier.getAwsSecurityCredentials(this.supplierContext),this.region));let e=await this.awsRequestSigner.getRequestOptions({...t.RETRY_CONFIG,url:this.regionalCredVerificationUrl.replace("{region}",this.region),method:"POST"}),r=[];return mS.Gaxios.mergeHeaders({"x-goog-cloud-target-resource":this.audience},e.headers).forEach((s,i)=>r.push({key:i,value:s})),encodeURIComponent(JSON.stringify({url:e.url,method:e.method,headers:r}))}};na.AwsClient=Rl});var Nl=V(Le=>{"use strict";Object.defineProperty(Le,"__esModule",{value:!0});Le.InvalidSubjectTokenError=Le.InvalidMessageFieldError=Le.InvalidCodeFieldError=Le.InvalidTokenTypeFieldError=Le.InvalidExpirationTimeFieldError=Le.InvalidSuccessFieldError=Le.InvalidVersionFieldError=Le.ExecutableResponseError=Le.ExecutableResponse=void 0;var sa="urn:ietf:params:oauth:token-type:saml2",Ol="urn:ietf:params:oauth:token-type:id_token",Fl="urn:ietf:params:oauth:token-type:jwt",Pl=class{version;success;expirationTime;tokenType;errorCode;errorMessage;subjectToken;constructor(e){if(!e.version)throw new oa("Executable response must contain a 'version' field.");if(e.success===void 0)throw new ia("Executable response must contain a 'success' field.");if(this.version=e.version,this.success=e.success,this.success){if(this.expirationTime=e.expiration_time,this.tokenType=e.token_type,this.tokenType!==sa&&this.tokenType!==Ol&&this.tokenType!==Fl)throw new aa(`Executable response must contain a 'token_type' field when successful and it must be one of ${Ol}, ${Fl}, or ${sa}.`);if(this.tokenType===sa){if(!e.saml_response)throw new Vs(`Executable response must contain a 'saml_response' field when token_type=${sa}.`);this.subjectToken=e.saml_response}else{if(!e.id_token)throw new Vs(`Executable response must contain a 'id_token' field when token_type=${Ol} or ${Fl}.`);this.subjectToken=e.id_token}}else{if(!e.code)throw new ua("Executable response must contain a 'code' field when unsuccessful.");if(!e.message)throw new ca("Executable response must contain a 'message' field when unsuccessful.");this.errorCode=e.code,this.errorMessage=e.message}}isValid(){return!this.isExpired()&&this.success}isExpired(){return this.expirationTime!==void 0&&this.expirationTime<Math.round(Date.now()/1e3)}};Le.ExecutableResponse=Pl;var nr=class extends Error{constructor(e){super(e),Object.setPrototypeOf(this,new.target.prototype)}};Le.ExecutableResponseError=nr;var oa=class extends nr{};Le.InvalidVersionFieldError=oa;var ia=class extends nr{};Le.InvalidSuccessFieldError=ia;var Il=class extends nr{};Le.InvalidExpirationTimeFieldError=Il;var aa=class extends nr{};Le.InvalidTokenTypeFieldError=aa;var ua=class extends nr{};Le.InvalidCodeFieldError=ua;var ca=class extends nr{};Le.InvalidMessageFieldError=ca;var Vs=class extends nr{};Le.InvalidSubjectTokenError=Vs});var Ll=V(rs=>{"use strict";Object.defineProperty(rs,"__esModule",{value:!0});rs.PluggableAuthHandler=rs.ExecutableError=void 0;var mn=Nl(),gS=X("child_process"),Bl=X("fs"),la=class extends Error{code;constructor(e,r){super(`The executable failed with exit code: ${r} and error message: ${e}.`),this.code=r,Object.setPrototypeOf(this,new.target.prototype)}};rs.ExecutableError=la;var jl=class t{commandComponents;timeoutMillis;outputFile;constructor(e){if(!e.command)throw new Error("No command provided.");if(this.commandComponents=t.parseCommand(e.command),this.timeoutMillis=e.timeoutMillis,!this.timeoutMillis)throw new Error("No timeoutMillis provided.");this.outputFile=e.outputFile}retrieveResponseFromExecutable(e){return new Promise((r,n)=>{let s=gS.spawn(this.commandComponents[0],this.commandComponents.slice(1),{env:{...process.env,...Object.fromEntries(e)}}),i="";s.stdout.on("data",c=>{i+=c}),s.stderr.on("data",c=>{i+=c});let u=setTimeout(()=>(s.removeAllListeners(),s.kill(),n(new Error("The executable failed to finish within the timeout specified."))),this.timeoutMillis);s.on("close",c=>{if(clearTimeout(u),c===0)try{let l=JSON.parse(i),h=new mn.ExecutableResponse(l);return r(h)}catch(l){return l instanceof mn.ExecutableResponseError?n(l):n(new mn.ExecutableResponseError(`The executable returned an invalid response: ${i}`))}else return n(new la(i,c.toString()))})})}async retrieveCachedResponse(){if(!this.outputFile||this.outputFile.length===0)return;let e;try{e=await Bl.promises.realpath(this.outputFile)}catch{return}if(!(await Bl.promises.lstat(e)).isFile())return;let r=await Bl.promises.readFile(e,{encoding:"utf8"});if(r!=="")try{let n=JSON.parse(r);return new mn.ExecutableResponse(n).isValid()?new mn.ExecutableResponse(n):void 0}catch(n){throw n instanceof mn.ExecutableResponseError?n:new mn.ExecutableResponseError(`The output file contained an invalid response: ${r}`)}}static parseCommand(e){let r=e.match(/(?:[^\s"]+|"[^"]*")+/g);if(!r)throw new Error(`Provided command: "${e}" could not be parsed.`);for(let n=0;n<r.length;n++)r[n][0]==='"'&&r[n].slice(-1)==='"'&&(r[n]=r[n].slice(1,-1));return r}};rs.PluggableAuthHandler=jl});var Ul=V(ns=>{"use strict";Object.defineProperty(ns,"__esModule",{value:!0});ns.PluggableAuthClient=ns.ExecutableError=void 0;var yS=Wr(),_S=Nl(),ty=Ll(),bS=Ll();Object.defineProperty(ns,"ExecutableError",{enumerable:!0,get:function(){return bS.ExecutableError}});var CS=30*1e3,ry=5*1e3,ny=120*1e3,wS="GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES",sy=1,Ml=class extends yS.BaseExternalAccountClient{command;timeoutMillis;outputFile;handler;constructor(e){if(super(e),!e.credential_source.executable)throw new Error('No valid Pluggable Auth "credential_source" provided.');if(this.command=e.credential_source.executable.command,!this.command)throw new Error('No valid Pluggable Auth "credential_source" provided.');if(e.credential_source.executable.timeout_millis===void 0)this.timeoutMillis=CS;else if(this.timeoutMillis=e.credential_source.executable.timeout_millis,this.timeoutMillis<ry||this.timeoutMillis>ny)throw new Error(`Timeout must be between ${ry} and ${ny} milliseconds.`);this.outputFile=e.credential_source.executable.output_file,this.handler=new ty.PluggableAuthHandler({command:this.command,timeoutMillis:this.timeoutMillis,outputFile:this.outputFile}),this.credentialSourceType="executable"}async retrieveSubjectToken(){if(process.env[wS]!=="1")throw new Error("Pluggable Auth executables need to be explicitly allowed to run by setting the GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES environment Variable to 1.");let e;if(this.outputFile&&(e=await this.handler.retrieveCachedResponse()),!e){let r=new Map;r.set("GOOGLE_EXTERNAL_ACCOUNT_AUDIENCE",this.audience),r.set("GOOGLE_EXTERNAL_ACCOUNT_TOKEN_TYPE",this.subjectTokenType),r.set("GOOGLE_EXTERNAL_ACCOUNT_INTERACTIVE","0"),this.outputFile&&r.set("GOOGLE_EXTERNAL_ACCOUNT_OUTPUT_FILE",this.outputFile);let n=this.getServiceAccountEmail();n&&r.set("GOOGLE_EXTERNAL_ACCOUNT_IMPERSONATED_EMAIL",n),e=await this.handler.retrieveResponseFromExecutable(r)}if(e.version>sy)throw new Error(`Version of executable is not currently supported, maximum supported version is ${sy}.`);if(!e.success)throw new ty.ExecutableError(e.errorMessage,e.errorCode);if(this.outputFile&&!e.expirationTime)throw new _S.InvalidExpirationTimeFieldError("The executable response must contain the `expiration_time` field for successful responses when an output_file has been specified in the configuration.");if(e.isExpired())throw new Error("Executable response is expired.");return e.subjectToken}};ns.PluggableAuthClient=Ml});var $l=V(da=>{"use strict";Object.defineProperty(da,"__esModule",{value:!0});da.ExternalAccountClient=void 0;var ES=Wr(),AS=vl(),SS=xl(),vS=Ul(),ql=class{constructor(){throw new Error("ExternalAccountClients should be initialized via: ExternalAccountClient.fromJSON(), directly via explicit constructors, eg. new AwsClient(options), new IdentityPoolClient(options), newPluggableAuthClientOptions, or via new GoogleAuth(options).getClient()")}static fromJSON(e){return console.warn("The `fromJSON` method does not validate the credential configuration. A security risk occurs when a credential configuration configured with malicious URLs is used. When the credential configuration is accepted from an untrusted source, you should validate it before using it with this method. For more details, see https://cloud.google.com/docs/authentication/external/externally-sourced-credentials."),e&&e.type===ES.EXTERNAL_ACCOUNT_TYPE?e.credential_source?.environment_id?new SS.AwsClient(e):e.credential_source?.executable?new vS.PluggableAuthClient(e):new AS.IdentityPoolClient(e):null}};da.ExternalAccountClient=ql});var uy=V(ss=>{"use strict";Object.defineProperty(ss,"__esModule",{value:!0});ss.ExternalAccountAuthorizedUserClient=ss.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE=void 0;var iy=pt(),oy=hl(),ay=Ve(),kS=X("stream"),TS=Wr();ss.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE="external_account_authorized_user";var DS="https://sts.{universeDomain}/v1/oauthtoken",zl=class t extends oy.OAuthClientAuthHandler{#e;constructor(e){super(e),this.#e=e.tokenRefreshEndpoint}async refreshToken(e,r){let n={...t.RETRY_CONFIG,url:this.#e,method:"POST",headers:r,data:new URLSearchParams({grant_type:"refresh_token",refresh_token:e})};iy.AuthClient.setMethodName(n,"refreshToken"),this.applyClientAuthenticationOptions(n);try{let s=await this.transporter.request(n),i=s.data;return i.res=s,i}catch(s){throw s instanceof ay.GaxiosError&&s.response?(0,oy.getErrorFromOAuthErrorResponse)(s.response.data,s):s}}},Hl=class extends iy.AuthClient{cachedAccessToken;externalAccountAuthorizedUserHandler;refreshToken;constructor(e){super(e),e.universe_domain&&(this.universeDomain=e.universe_domain),this.refreshToken=e.refresh_token;let r={confidentialClientType:"basic",clientId:e.client_id,clientSecret:e.client_secret};this.externalAccountAuthorizedUserHandler=new zl({tokenRefreshEndpoint:e.token_url??DS.replace("{universeDomain}",this.universeDomain),transporter:this.transporter,clientAuthentication:r}),this.cachedAccessToken=null,this.quotaProjectId=e.quota_project_id,typeof e?.eagerRefreshThresholdMillis!="number"?this.eagerRefreshThresholdMillis=TS.EXPIRATION_TIME_OFFSET:this.eagerRefreshThresholdMillis=e.eagerRefreshThresholdMillis,this.forceRefreshOnFailure=!!e?.forceRefreshOnFailure}async getAccessToken(){return(!this.cachedAccessToken||this.isExpired(this.cachedAccessToken))&&await this.refreshAccessTokenAsync(),{token:this.cachedAccessToken.access_token,res:this.cachedAccessToken.res}}async getRequestHeaders(){let e=await this.getAccessToken(),r=new Headers({authorization:`Bearer ${e.token}`});return this.addSharedMetadataHeaders(r)}request(e,r){if(r)this.requestAsync(e).then(n=>r(null,n),n=>r(n,n.response));else return this.requestAsync(e)}async requestAsync(e,r=!1){let n;try{let s=await this.getRequestHeaders();e.headers=ay.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,s),n=await this.transporter.request(e)}catch(s){let i=s.response;if(i){let u=i.status,c=i.config.data instanceof kS.Readable;if(!r&&(u===401||u===403)&&!c&&this.forceRefreshOnFailure)return await this.refreshAccessTokenAsync(),await this.requestAsync(e,!0)}throw s}return n}async refreshAccessTokenAsync(){let e=await this.externalAccountAuthorizedUserHandler.refreshToken(this.refreshToken);return this.cachedAccessToken={access_token:e.access_token,expiry_date:new Date().getTime()+e.expires_in*1e3,res:e.res},e.refresh_token!==void 0&&(this.refreshToken=e.refresh_token),this.cachedAccessToken}isExpired(e){let r=new Date().getTime();return e.expiry_date?r>=e.expiry_date-this.eagerRefreshThresholdMillis:!1}};ss.ExternalAccountAuthorizedUserClient=Hl});var fy=V(Ht=>{"use strict";Object.defineProperty(Ht,"__esModule",{value:!0});Ht.GoogleAuth=Ht.GoogleAuthExceptionMessages=void 0;var RS=X("child_process"),Ks=X("fs"),xS=Ve(),Ys=Ns(),OS=X("os"),Wl=X("path"),FS=Bs(),PS=Mc(),IS=qc(),NS=$c(),os=al(),cy=cl(),is=dl(),BS=$l(),Qs=Wr(),Gl=pt(),ly=uy(),dy=Ut();Ht.GoogleAuthExceptionMessages={API_KEY_WITH_CREDENTIALS:"API Keys and Credentials are mutually exclusive authentication methods and cannot be used together.",NO_PROJECT_ID_FOUND:`Unable to detect a Project Id in the current environment.
|
|
62
62
|
To learn more about authentication and Google APIs, visit:
|
|
63
63
|
https://cloud.google.com/docs/authentication/getting-started`,NO_CREDENTIALS_FOUND:`Unable to find credentials in current environment.
|
|
64
64
|
To learn more about authentication and Google APIs, visit:
|
|
65
65
|
https://cloud.google.com/docs/authentication/getting-started`,NO_ADC_FOUND:"Could not load the default credentials. Browse to https://cloud.google.com/docs/authentication/getting-started for more information.",NO_UNIVERSE_DOMAIN_FOUND:`Unable to detect a Universe Domain in the current environment.
|
|
66
66
|
To learn more about Universe Domain retrieval, visit:
|
|
67
|
-
https://cloud.google.com/compute/docs/metadata/predefined-metadata-keys`};var $l=class{checkIsGCE=void 0;useJWTAccessWithScope;defaultServicePath;get isGCE(){return this.checkIsGCE}_findProjectIdPromise;_cachedProjectId;jsonContent=null;apiKey;cachedCredential=null;#e=null;defaultScopes;keyFilename;scopes;clientOptions={};constructor(e={}){if(this._cachedProjectId=e.projectId||null,this.cachedCredential=e.authClient||null,this.keyFilename=e.keyFilename||e.keyFile,this.keyFilename&&console.warn("The `keyFilename` option is deprecated. Please use the `credentials` option instead. For more details, see https://cloud.google.com/docs/authentication/external/externally-sourced-credentials."),this.scopes=e.scopes,this.clientOptions=e.clientOptions||{},this.jsonContent=e.credentials||null,this.jsonContent&&console.warn("The `credentials` option is deprecated. Please use the `auth` object constructor instead. For more details, see https://cloud.google.com/docs/authentication/external/externally-sourced-credentials."),this.apiKey=e.apiKey||this.clientOptions.apiKey||null,this.apiKey&&(this.jsonContent||this.clientOptions.credentials))throw new RangeError(Ht.GoogleAuthExceptionMessages.API_KEY_WITH_CREDENTIALS);e.universeDomain&&(this.clientOptions.universeDomain=e.universeDomain)}setGapicJWTValues(e){e.defaultServicePath=this.defaultServicePath,e.useJWTAccessWithScope=this.useJWTAccessWithScope,e.defaultScopes=this.defaultScopes}getProjectId(e){if(e)this.getProjectIdAsync().then(r=>e(null,r),e);else return this.getProjectIdAsync()}async getProjectIdOptional(){try{return await this.getProjectId()}catch(e){if(e instanceof Error&&e.message===Ht.GoogleAuthExceptionMessages.NO_PROJECT_ID_FOUND)return null;throw e}}async findAndCacheProjectId(){let e=null;if(e||=await this.getProductionProjectId(),e||=await this.getFileProjectId(),e||=await this.getDefaultServiceProjectId(),e||=await this.getGCEProjectId(),e||=await this.getExternalAccountClientProjectId(),e)return this._cachedProjectId=e,e;throw new Error(Ht.GoogleAuthExceptionMessages.NO_PROJECT_ID_FOUND)}async getProjectIdAsync(){return this._cachedProjectId?this._cachedProjectId:(this._findProjectIdPromise||(this._findProjectIdPromise=this.findAndCacheProjectId()),this._findProjectIdPromise)}async getUniverseDomainFromMetadataServer(){let e;try{e=await Js.universe("universe-domain"),e||=ql.DEFAULT_UNIVERSE}catch(r){if(r&&r?.response?.status===404)e=ql.DEFAULT_UNIVERSE;else throw r}return e}async getUniverseDomain(){let e=(0,Yg.originalOrCamelOptions)(this.clientOptions).get("universe_domain");try{e??=(await this.getClient()).universeDomain}catch{e??=ql.DEFAULT_UNIVERSE}return e}getAnyScopes(){return this.scopes||this.defaultScopes}getApplicationDefault(e={},r){let n;if(typeof e=="function"?r=e:n=e,r)this.getApplicationDefaultAsync(n).then(s=>r(null,s.credential,s.projectId),r);else return this.getApplicationDefaultAsync(n)}async getApplicationDefaultAsync(e={}){if(this.cachedCredential)return await this.#t(this.cachedCredential,null);let r;if(r=await this._tryGetApplicationCredentialsFromEnvironmentVariable(e),r)return r instanceof ns.JWT?r.scopes=this.scopes:r instanceof Vs.BaseExternalAccountClient&&(r.scopes=this.getAnyScopes()),await this.#t(r);if(r=await this._tryGetApplicationCredentialsFromWellKnownFile(e),r)return r instanceof ns.JWT?r.scopes=this.scopes:r instanceof Vs.BaseExternalAccountClient&&(r.scopes=this.getAnyScopes()),await this.#t(r);if(await this._checkIsGCE())return e.scopes=this.getAnyScopes(),await this.#t(new dS.Compute(e));throw new Error(Ht.GoogleAuthExceptionMessages.NO_ADC_FOUND)}async#t(e,r=process.env.GOOGLE_CLOUD_QUOTA_PROJECT||null){let n=await this.getProjectIdOptional();return r&&(e.quotaProjectId=r),this.cachedCredential=e,{credential:e,projectId:n}}async _checkIsGCE(){return this.checkIsGCE===void 0&&(this.checkIsGCE=Js.getGCPResidency()||await Js.isAvailable()),this.checkIsGCE}async _tryGetApplicationCredentialsFromEnvironmentVariable(e){let r=process.env.GOOGLE_APPLICATION_CREDENTIALS||process.env.google_application_credentials;if(!r||r.length===0)return null;try{return this._getApplicationCredentialsFromFilePath(r,e)}catch(n){throw n instanceof Error&&(n.message=`Unable to read the credential file specified by the GOOGLE_APPLICATION_CREDENTIALS environment variable: ${n.message}`),n}}async _tryGetApplicationCredentialsFromWellKnownFile(e){let r=null;if(this._isWindows())r=process.env.APPDATA;else{let s=process.env.HOME;s&&(r=Ul.join(s,".config"))}return r&&(r=Ul.join(r,"gcloud","application_default_credentials.json"),Gs.existsSync(r)||(r=null)),r?await this._getApplicationCredentialsFromFilePath(r,e):null}async _getApplicationCredentialsFromFilePath(e,r={}){if(!e||e.length===0)throw new Error("The file path is invalid.");try{if(e=Gs.realpathSync(e),!Gs.lstatSync(e).isFile())throw new Error}catch(s){throw s instanceof Error&&(s.message=`The file at ${e} does not exist, or it is not a file. ${s.message}`),s}let n=Gs.createReadStream(e);return this.fromStream(n,r)}fromImpersonatedJSON(e){if(!e)throw new Error("Must pass in a JSON object containing an impersonated refresh token");if(e.type!==ss.IMPERSONATED_ACCOUNT_TYPE)throw new Error(`The incoming JSON object does not have the "${ss.IMPERSONATED_ACCOUNT_TYPE}" type`);if(!e.source_credentials)throw new Error("The incoming JSON object does not contain a source_credentials field");if(!e.service_account_impersonation_url)throw new Error("The incoming JSON object does not contain a service_account_impersonation_url field");let r=this.fromJSON(e.source_credentials);if(e.service_account_impersonation_url?.length>256)throw new RangeError(`Target principal is too long: ${e.service_account_impersonation_url}`);let n=/(?<target>[^/]+):(generateAccessToken|generateIdToken)$/.exec(e.service_account_impersonation_url)?.groups?.target;if(!n)throw new RangeError(`Cannot extract target principal from ${e.service_account_impersonation_url}`);let s=this.getAnyScopes()??[];return new ss.Impersonated({...e,sourceClient:r,targetPrincipal:n,targetScopes:Array.isArray(s)?s:[s]})}fromJSON(e,r={}){console.warn("The `fromJSON` method is deprecated. Please use the `JWT` constructor instead. For more details, see https://cloud.google.com/docs/authentication/external/externally-sourced-credentials.");let n,s=(0,Yg.originalOrCamelOptions)(r).get("universe_domain");return e.type===Vg.USER_REFRESH_ACCOUNT_TYPE?(n=new Vg.UserRefreshClient(r),n.fromJSON(e)):e.type===ss.IMPERSONATED_ACCOUNT_TYPE?n=this.fromImpersonatedJSON(e):e.type===Vs.EXTERNAL_ACCOUNT_TYPE?(n=mS.ExternalAccountClient.fromJSON({...e,...r}),n.scopes=this.getAnyScopes()):e.type===Kg.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE?n=new Kg.ExternalAccountAuthorizedUserClient({...e,...r}):(r.scopes=this.scopes,n=new ns.JWT(r),this.setGapicJWTValues(n),n.fromJSON(e)),s&&(n.universeDomain=s),n}_cacheClientFromJSON(e,r){let n=this.fromJSON(e,r);return this.jsonContent=e,this.cachedCredential=n,n}fromStream(e,r={},n){console.warn("The `fromStream` method is deprecated. Please use the `JWT` constructor with a parsed stream instead. For more details, see https://cloud.google.com/docs/authentication/external/externally-sourced-credentials.");let s={};if(typeof r=="function"?n=r:s=r,n)this.fromStreamAsync(e,s).then(i=>n(null,i),n);else return this.fromStreamAsync(e,s)}fromStreamAsync(e,r){return new Promise((n,s)=>{if(!e)throw new Error("Must pass in a stream containing the Google auth settings.");let i=[];e.setEncoding("utf8").on("error",s).on("data",u=>i.push(u)).on("end",()=>{try{try{let u=JSON.parse(i.join("")),c=this._cacheClientFromJSON(u,r);return n(c)}catch(u){if(!this.keyFilename)throw u;let c=new ns.JWT({...this.clientOptions,keyFile:this.keyFilename});return this.cachedCredential=c,this.setGapicJWTValues(c),n(c)}}catch(u){return s(u)}})})}fromAPIKey(e,r={}){return new ns.JWT({...r,apiKey:e})}_isWindows(){let e=lS.platform();return!!(e&&e.length>=3&&e.substring(0,3).toLowerCase()==="win")}async getDefaultServiceProjectId(){return new Promise(e=>{(0,uS.exec)("gcloud config config-helper --format json",(r,n)=>{if(!r&&n)try{let s=JSON.parse(n).configuration.properties.core.project;e(s);return}catch{}e(null)})})}getProductionProjectId(){return process.env.GCLOUD_PROJECT||process.env.GOOGLE_CLOUD_PROJECT||process.env.gcloud_project||process.env.google_cloud_project}async getFileProjectId(){if(this.cachedCredential)return this.cachedCredential.projectId;if(this.keyFilename){let r=await this.getClient();if(r&&r.projectId)return r.projectId}let e=await this._tryGetApplicationCredentialsFromEnvironmentVariable();return e?e.projectId:null}async getExternalAccountClientProjectId(){return!this.jsonContent||this.jsonContent.type!==Vs.EXTERNAL_ACCOUNT_TYPE?null:await(await this.getClient()).getProjectId()}async getGCEProjectId(){try{return await Js.project("project-id")}catch{return null}}getCredentials(e){if(e)this.getCredentialsAsync().then(r=>e(null,r),e);else return this.getCredentialsAsync()}async getCredentialsAsync(){let e=await this.getClient();if(e instanceof ss.Impersonated)return{client_email:e.getTargetPrincipal()};if(e instanceof Vs.BaseExternalAccountClient){let r=e.getServiceAccountEmail();if(r)return{client_email:r,universe_domain:e.universeDomain}}if(this.jsonContent)return{client_email:this.jsonContent.client_email,private_key:this.jsonContent.private_key,universe_domain:this.jsonContent.universe_domain};if(await this._checkIsGCE()){let[r,n]=await Promise.all([Js.instance("service-accounts/default/email"),this.getUniverseDomain()]);return{client_email:r,universe_domain:n}}throw new Error(Ht.GoogleAuthExceptionMessages.NO_CREDENTIALS_FOUND)}async getClient(){if(this.cachedCredential)return this.cachedCredential;this.#e=this.#e||this.#r();try{return await this.#e}finally{this.#e=null}}async#r(){if(this.jsonContent)return this._cacheClientFromJSON(this.jsonContent,this.clientOptions);if(this.keyFilename){let e=Ul.resolve(this.keyFilename),r=Gs.createReadStream(e);return await this.fromStreamAsync(r,this.clientOptions)}else if(this.apiKey){let e=await this.fromAPIKey(this.apiKey,this.clientOptions);e.scopes=this.scopes;let{credential:r}=await this.#t(e);return r}else{let{credential:e}=await this.getApplicationDefaultAsync(this.clientOptions);return e}}async getIdTokenClient(e){let r=await this.getClient();if(!("fetchIdToken"in r))throw new Error("Cannot fetch ID token in this environment, use GCE or set the GOOGLE_APPLICATION_CREDENTIALS environment variable to a service account credentials JSON file.");return new hS.IdTokenClient({targetAudience:e,idTokenProvider:r})}async getAccessToken(){return(await(await this.getClient()).getAccessToken()).token}async getRequestHeaders(e){return(await this.getClient()).getRequestHeaders(e)}async authorizeRequest(e={}){let r=e.url,s=await(await this.getClient()).getRequestHeaders(r);return e.headers=cS.Gaxios.mergeHeaders(e.headers,s),e}async fetch(...e){return(await this.getClient()).fetch(...e)}async request(e){return(await this.getClient()).request(e)}getEnv(){return(0,pS.getEnv)()}async sign(e,r){let n=await this.getClient(),s=await this.getUniverseDomain();if(r=r||`https://iamcredentials.${s}/v1/projects/-/serviceAccounts/`,n instanceof ss.Impersonated)return(await n.sign(e)).signedBlob;let i=(0,fS.createCrypto)();if(n instanceof ns.JWT&&n.key)return await i.sign(n.key,e);let u=await this.getCredentials();if(!u.client_email)throw new Error("Cannot sign data without `client_email`.");return this.signBlob(i,u.client_email,e,r)}async signBlob(e,r,n,s){let i=new URL(s+`${r}:signBlob`);return(await this.request({method:"POST",url:i.href,data:{payload:e.encodeBase64StringUtf8(n)},retry:!0,retryConfig:{httpMethodsToRetry:["POST"]}})).data.signedBlob}};Ht.GoogleAuth=$l});var Qg=V(ua=>{"use strict";Object.defineProperty(ua,"__esModule",{value:!0});ua.IAMAuth=void 0;var zl=class{selector;token;constructor(e,r){this.selector=e,this.token=r,this.selector=e,this.token=r}getRequestHeaders(){return{"x-goog-iam-authority-selector":this.selector,"x-goog-iam-authorization-token":this.token}}};ua.IAMAuth=zl});var Zg=V(nr=>{"use strict";Object.defineProperty(nr,"__esModule",{value:!0});nr.DownscopedClient=nr.EXPIRATION_TIME_OFFSET=nr.MAX_ACCESS_BOUNDARY_RULES_COUNT=void 0;var gS=Ve(),yS=Q("stream"),Hl=pt(),_S=$i(),bS="urn:ietf:params:oauth:grant-type:token-exchange",CS="urn:ietf:params:oauth:token-type:access_token",wS="urn:ietf:params:oauth:token-type:access_token";nr.MAX_ACCESS_BOUNDARY_RULES_COUNT=10;nr.EXPIRATION_TIME_OFFSET=300*1e3;var Wl=class extends Hl.AuthClient{authClient;credentialAccessBoundary;cachedDownscopedAccessToken;stsCredential;constructor(e,r={accessBoundary:{accessBoundaryRules:[]}}){if(super(e instanceof Hl.AuthClient?{}:e),e instanceof Hl.AuthClient?(this.authClient=e,this.credentialAccessBoundary=r):(this.authClient=e.authClient,this.credentialAccessBoundary=e.credentialAccessBoundary),this.credentialAccessBoundary.accessBoundary.accessBoundaryRules.length===0)throw new Error("At least one access boundary rule needs to be defined.");if(this.credentialAccessBoundary.accessBoundary.accessBoundaryRules.length>nr.MAX_ACCESS_BOUNDARY_RULES_COUNT)throw new Error(`The provided access boundary has more than ${nr.MAX_ACCESS_BOUNDARY_RULES_COUNT} access boundary rules.`);for(let n of this.credentialAccessBoundary.accessBoundary.accessBoundaryRules)if(n.availablePermissions.length===0)throw new Error("At least one permission should be defined in access boundary rules.");this.stsCredential=new _S.StsCredentials({tokenExchangeEndpoint:`https://sts.${this.universeDomain}/v1/token`}),this.cachedDownscopedAccessToken=null}setCredentials(e){if(!e.expiry_date)throw new Error("The access token expiry_date field is missing in the provided credentials.");super.setCredentials(e),this.cachedDownscopedAccessToken=e}async getAccessToken(){return(!this.cachedDownscopedAccessToken||this.isExpired(this.cachedDownscopedAccessToken))&&await this.refreshAccessTokenAsync(),{token:this.cachedDownscopedAccessToken.access_token,expirationTime:this.cachedDownscopedAccessToken.expiry_date,res:this.cachedDownscopedAccessToken.res}}async getRequestHeaders(){let e=await this.getAccessToken(),r=new Headers({authorization:`Bearer ${e.token}`});return this.addSharedMetadataHeaders(r)}request(e,r){if(r)this.requestAsync(e).then(n=>r(null,n),n=>r(n,n.response));else return this.requestAsync(e)}async requestAsync(e,r=!1){let n;try{let s=await this.getRequestHeaders();e.headers=gS.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,s),n=await this.transporter.request(e)}catch(s){let i=s.response;if(i){let u=i.status,c=i.config.data instanceof yS.Readable;if(!r&&(u===401||u===403)&&!c&&this.forceRefreshOnFailure)return await this.refreshAccessTokenAsync(),await this.requestAsync(e,!0)}throw s}return n}async refreshAccessTokenAsync(){let e=(await this.authClient.getAccessToken()).token,r={grantType:bS,requestedTokenType:CS,subjectToken:e,subjectTokenType:wS},n=await this.stsCredential.exchangeToken(r,void 0,this.credentialAccessBoundary),s=this.authClient.credentials?.expiry_date||null,i=n.expires_in?new Date().getTime()+n.expires_in*1e3:s;return this.cachedDownscopedAccessToken={access_token:n.access_token,expiry_date:i,res:n.res},this.credentials={},Object.assign(this.credentials,this.cachedDownscopedAccessToken),delete this.credentials.res,this.emit("tokens",{refresh_token:null,expiry_date:this.cachedDownscopedAccessToken.expiry_date,access_token:this.cachedDownscopedAccessToken.access_token,token_type:"Bearer",id_token:null}),this.cachedDownscopedAccessToken}isExpired(e){let r=new Date().getTime();return e.expiry_date?r>=e.expiry_date-this.eagerRefreshThresholdMillis:!1}};nr.DownscopedClient=Wl});var ey=V(ca=>{"use strict";Object.defineProperty(ca,"__esModule",{value:!0});ca.PassThroughClient=void 0;var ES=pt(),Gl=class extends ES.AuthClient{async request(e){return this.transporter.request(e)}async getAccessToken(){return{}}async getRequestHeaders(){return new Headers}};ca.PassThroughClient=Gl});var Vl=V(te=>{"use strict";Object.defineProperty(te,"__esModule",{value:!0});te.GoogleAuth=te.auth=te.PassThroughClient=te.ExecutableError=te.PluggableAuthClient=te.DownscopedClient=te.BaseExternalAccountClient=te.ExternalAccountClient=te.IdentityPoolClient=te.AwsRequestSigner=te.AwsClient=te.UserRefreshClient=te.LoginTicket=te.ClientAuthentication=te.OAuth2Client=te.CodeChallengeMethod=te.Impersonated=te.JWT=te.JWTAccess=te.IdTokenClient=te.IAMAuth=te.GCPEnv=te.Compute=te.DEFAULT_UNIVERSE=te.AuthClient=te.gaxios=te.gcpMetadata=void 0;var ty=Xg();Object.defineProperty(te,"GoogleAuth",{enumerable:!0,get:function(){return ty.GoogleAuth}});te.gcpMetadata=Fs();te.gaxios=Ve();var ry=pt();Object.defineProperty(te,"AuthClient",{enumerable:!0,get:function(){return ry.AuthClient}});Object.defineProperty(te,"DEFAULT_UNIVERSE",{enumerable:!0,get:function(){return ry.DEFAULT_UNIVERSE}});var AS=Ic();Object.defineProperty(te,"Compute",{enumerable:!0,get:function(){return AS.Compute}});var SS=jc();Object.defineProperty(te,"GCPEnv",{enumerable:!0,get:function(){return SS.GCPEnv}});var kS=Qg();Object.defineProperty(te,"IAMAuth",{enumerable:!0,get:function(){return kS.IAMAuth}});var TS=Bc();Object.defineProperty(te,"IdTokenClient",{enumerable:!0,get:function(){return TS.IdTokenClient}});var DS=el();Object.defineProperty(te,"JWTAccess",{enumerable:!0,get:function(){return DS.JWTAccess}});var vS=rl();Object.defineProperty(te,"JWT",{enumerable:!0,get:function(){return vS.JWT}});var RS=il();Object.defineProperty(te,"Impersonated",{enumerable:!0,get:function(){return RS.Impersonated}});var Jl=fn();Object.defineProperty(te,"CodeChallengeMethod",{enumerable:!0,get:function(){return Jl.CodeChallengeMethod}});Object.defineProperty(te,"OAuth2Client",{enumerable:!0,get:function(){return Jl.OAuth2Client}});Object.defineProperty(te,"ClientAuthentication",{enumerable:!0,get:function(){return Jl.ClientAuthentication}});var OS=Oc();Object.defineProperty(te,"LoginTicket",{enumerable:!0,get:function(){return OS.LoginTicket}});var xS=sl();Object.defineProperty(te,"UserRefreshClient",{enumerable:!0,get:function(){return xS.UserRefreshClient}});var FS=kl();Object.defineProperty(te,"AwsClient",{enumerable:!0,get:function(){return FS.AwsClient}});var PS=El();Object.defineProperty(te,"AwsRequestSigner",{enumerable:!0,get:function(){return PS.AwsRequestSigner}});var IS=Cl();Object.defineProperty(te,"IdentityPoolClient",{enumerable:!0,get:function(){return IS.IdentityPoolClient}});var NS=jl();Object.defineProperty(te,"ExternalAccountClient",{enumerable:!0,get:function(){return NS.ExternalAccountClient}});var BS=zr();Object.defineProperty(te,"BaseExternalAccountClient",{enumerable:!0,get:function(){return BS.BaseExternalAccountClient}});var jS=Zg();Object.defineProperty(te,"DownscopedClient",{enumerable:!0,get:function(){return jS.DownscopedClient}});var ny=Nl();Object.defineProperty(te,"PluggableAuthClient",{enumerable:!0,get:function(){return ny.PluggableAuthClient}});Object.defineProperty(te,"ExecutableError",{enumerable:!0,get:function(){return ny.ExecutableError}});var LS=ey();Object.defineProperty(te,"PassThroughClient",{enumerable:!0,get:function(){return LS.PassThroughClient}});var MS=new ty.GoogleAuth;te.auth=MS});var Uy=V((jF,bf)=>{"use strict";var hD=/at\s(?:.*\.)?plugin\s.*\n\s*(.*)/,pD=/(\w*(\.\w*)*)\..*/;bf.exports=function(e){if(e.name.length>0)return e.name;let r=Error.stackTraceLimit;Error.stackTraceLimit=10;try{throw new Error("anonymous function")}catch(n){return Error.stackTraceLimit=r,My(n.stack)}};function My(t){let e=t.match(hD);return e?e[1].split(/[/\\]/).slice(-1)[0].match(pD)[1]:"anonymous"}bf.exports.extractPluginName=My});var $y=V((LF,qy)=>{"use strict";qy.exports=function(e){return e[0]==="@"&&(e=e.slice(1).replace("/","-")),e.replace(/-(.)/g,function(r,n){return n.toUpperCase()})}});var zy=V((MF,Ma)=>{"use strict";var mD=Uy(),gD=$y(),yD=0;function Cf(t,e={}){let r=!1;if(t.default!==void 0&&(t=t.default),typeof t!="function")throw new TypeError(`fastify-plugin expects a function, instead got a '${typeof t}'`);if(typeof e=="string"&&(e={fastify:e}),typeof e!="object"||Array.isArray(e)||e===null)throw new TypeError("The options object should be an object");if(e.fastify!==void 0&&typeof e.fastify!="string")throw new TypeError(`fastify-plugin expects a version string, instead got '${typeof e.fastify}'`);e.name||(r=!0,e.name=mD(t)+"-auto-"+yD++),t[Symbol.for("skip-override")]=e.encapsulate!==!0,t[Symbol.for("fastify.display-name")]=e.name,t[Symbol.for("plugin-meta")]=e,t.default||(t.default=t);let n=gD(e.name);return!r&&!t[n]&&(t[n]=t),t}Ma.exports=Cf;Ma.exports.default=Cf;Ma.exports.fastifyPlugin=Cf});var to,wf=je(()=>{"use strict";to=class{type="console";config;colors={reset:"\x1B[0m",bright:"\x1B[1m",dim:"\x1B[2m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",white:"\x1B[37m"};constructor(e={}){this.config={colors:!0,level:"log",...e}}formatData(e,r){let{format:n="text",timestamp:s=!0,prefix:i,metadata:u}=r||{},c="";if(s){let l=new Date().toISOString();c+=this.config.colors?`${this.colors.cyan}[${l}]${this.colors.reset} `:`[${l}] `}switch(i&&(c+=this.config.colors?`${this.colors.bright}${i}${this.colors.reset} `:`${i} `),n){case"json":c+=JSON.stringify(e,null,2);break;case"markdown":typeof e=="object"?c+=this.toMarkdown(e):c+=String(e);break;case"text":default:typeof e=="object"?c+=JSON.stringify(e,null,2):c+=String(e);break}return u&&Object.keys(u).length>0&&(c+=`
|
|
67
|
+
https://cloud.google.com/compute/docs/metadata/predefined-metadata-keys`};var Jl=class{checkIsGCE=void 0;useJWTAccessWithScope;defaultServicePath;get isGCE(){return this.checkIsGCE}_findProjectIdPromise;_cachedProjectId;jsonContent=null;apiKey;cachedCredential=null;#e=null;defaultScopes;keyFilename;scopes;clientOptions={};constructor(e={}){if(this._cachedProjectId=e.projectId||null,this.cachedCredential=e.authClient||null,this.keyFilename=e.keyFilename||e.keyFile,this.keyFilename&&console.warn("The `keyFilename` option is deprecated. Please use the `credentials` option instead. For more details, see https://cloud.google.com/docs/authentication/external/externally-sourced-credentials."),this.scopes=e.scopes,this.clientOptions=e.clientOptions||{},this.jsonContent=e.credentials||null,this.jsonContent&&console.warn("The `credentials` option is deprecated. Please use the `auth` object constructor instead. For more details, see https://cloud.google.com/docs/authentication/external/externally-sourced-credentials."),this.apiKey=e.apiKey||this.clientOptions.apiKey||null,this.apiKey&&(this.jsonContent||this.clientOptions.credentials))throw new RangeError(Ht.GoogleAuthExceptionMessages.API_KEY_WITH_CREDENTIALS);e.universeDomain&&(this.clientOptions.universeDomain=e.universeDomain)}setGapicJWTValues(e){e.defaultServicePath=this.defaultServicePath,e.useJWTAccessWithScope=this.useJWTAccessWithScope,e.defaultScopes=this.defaultScopes}getProjectId(e){if(e)this.getProjectIdAsync().then(r=>e(null,r),e);else return this.getProjectIdAsync()}async getProjectIdOptional(){try{return await this.getProjectId()}catch(e){if(e instanceof Error&&e.message===Ht.GoogleAuthExceptionMessages.NO_PROJECT_ID_FOUND)return null;throw e}}async findAndCacheProjectId(){let e=null;if(e||=await this.getProductionProjectId(),e||=await this.getFileProjectId(),e||=await this.getDefaultServiceProjectId(),e||=await this.getGCEProjectId(),e||=await this.getExternalAccountClientProjectId(),e)return this._cachedProjectId=e,e;throw new Error(Ht.GoogleAuthExceptionMessages.NO_PROJECT_ID_FOUND)}async getProjectIdAsync(){return this._cachedProjectId?this._cachedProjectId:(this._findProjectIdPromise||(this._findProjectIdPromise=this.findAndCacheProjectId()),this._findProjectIdPromise)}async getUniverseDomainFromMetadataServer(){let e;try{e=await Ys.universe("universe-domain"),e||=Gl.DEFAULT_UNIVERSE}catch(r){if(r&&r?.response?.status===404)e=Gl.DEFAULT_UNIVERSE;else throw r}return e}async getUniverseDomain(){let e=(0,dy.originalOrCamelOptions)(this.clientOptions).get("universe_domain");try{e??=(await this.getClient()).universeDomain}catch{e??=Gl.DEFAULT_UNIVERSE}return e}getAnyScopes(){return this.scopes||this.defaultScopes}getApplicationDefault(e={},r){let n;if(typeof e=="function"?r=e:n=e,r)this.getApplicationDefaultAsync(n).then(s=>r(null,s.credential,s.projectId),r);else return this.getApplicationDefaultAsync(n)}async getApplicationDefaultAsync(e={}){if(this.cachedCredential)return await this.#t(this.cachedCredential,null);let r;if(r=await this._tryGetApplicationCredentialsFromEnvironmentVariable(e),r)return r instanceof os.JWT?r.scopes=this.scopes:r instanceof Qs.BaseExternalAccountClient&&(r.scopes=this.getAnyScopes()),await this.#t(r);if(r=await this._tryGetApplicationCredentialsFromWellKnownFile(e),r)return r instanceof os.JWT?r.scopes=this.scopes:r instanceof Qs.BaseExternalAccountClient&&(r.scopes=this.getAnyScopes()),await this.#t(r);if(await this._checkIsGCE())return e.scopes=this.getAnyScopes(),await this.#t(new PS.Compute(e));throw new Error(Ht.GoogleAuthExceptionMessages.NO_ADC_FOUND)}async#t(e,r=process.env.GOOGLE_CLOUD_QUOTA_PROJECT||null){let n=await this.getProjectIdOptional();return r&&(e.quotaProjectId=r),this.cachedCredential=e,{credential:e,projectId:n}}async _checkIsGCE(){return this.checkIsGCE===void 0&&(this.checkIsGCE=Ys.getGCPResidency()||await Ys.isAvailable()),this.checkIsGCE}async _tryGetApplicationCredentialsFromEnvironmentVariable(e){let r=process.env.GOOGLE_APPLICATION_CREDENTIALS||process.env.google_application_credentials;if(!r||r.length===0)return null;try{return this._getApplicationCredentialsFromFilePath(r,e)}catch(n){throw n instanceof Error&&(n.message=`Unable to read the credential file specified by the GOOGLE_APPLICATION_CREDENTIALS environment variable: ${n.message}`),n}}async _tryGetApplicationCredentialsFromWellKnownFile(e){let r=null;if(this._isWindows())r=process.env.APPDATA;else{let s=process.env.HOME;s&&(r=Wl.join(s,".config"))}return r&&(r=Wl.join(r,"gcloud","application_default_credentials.json"),Ks.existsSync(r)||(r=null)),r?await this._getApplicationCredentialsFromFilePath(r,e):null}async _getApplicationCredentialsFromFilePath(e,r={}){if(!e||e.length===0)throw new Error("The file path is invalid.");try{if(e=Ks.realpathSync(e),!Ks.lstatSync(e).isFile())throw new Error}catch(s){throw s instanceof Error&&(s.message=`The file at ${e} does not exist, or it is not a file. ${s.message}`),s}let n=Ks.createReadStream(e);return this.fromStream(n,r)}fromImpersonatedJSON(e){if(!e)throw new Error("Must pass in a JSON object containing an impersonated refresh token");if(e.type!==is.IMPERSONATED_ACCOUNT_TYPE)throw new Error(`The incoming JSON object does not have the "${is.IMPERSONATED_ACCOUNT_TYPE}" type`);if(!e.source_credentials)throw new Error("The incoming JSON object does not contain a source_credentials field");if(!e.service_account_impersonation_url)throw new Error("The incoming JSON object does not contain a service_account_impersonation_url field");let r=this.fromJSON(e.source_credentials);if(e.service_account_impersonation_url?.length>256)throw new RangeError(`Target principal is too long: ${e.service_account_impersonation_url}`);let n=/(?<target>[^/]+):(generateAccessToken|generateIdToken)$/.exec(e.service_account_impersonation_url)?.groups?.target;if(!n)throw new RangeError(`Cannot extract target principal from ${e.service_account_impersonation_url}`);let s=this.getAnyScopes()??[];return new is.Impersonated({...e,sourceClient:r,targetPrincipal:n,targetScopes:Array.isArray(s)?s:[s]})}fromJSON(e,r={}){console.warn("The `fromJSON` method is deprecated. Please use the `JWT` constructor instead. For more details, see https://cloud.google.com/docs/authentication/external/externally-sourced-credentials.");let n,s=(0,dy.originalOrCamelOptions)(r).get("universe_domain");return e.type===cy.USER_REFRESH_ACCOUNT_TYPE?(n=new cy.UserRefreshClient(r),n.fromJSON(e)):e.type===is.IMPERSONATED_ACCOUNT_TYPE?n=this.fromImpersonatedJSON(e):e.type===Qs.EXTERNAL_ACCOUNT_TYPE?(n=BS.ExternalAccountClient.fromJSON({...e,...r}),n.scopes=this.getAnyScopes()):e.type===ly.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE?n=new ly.ExternalAccountAuthorizedUserClient({...e,...r}):(r.scopes=this.scopes,n=new os.JWT(r),this.setGapicJWTValues(n),n.fromJSON(e)),s&&(n.universeDomain=s),n}_cacheClientFromJSON(e,r){let n=this.fromJSON(e,r);return this.jsonContent=e,this.cachedCredential=n,n}fromStream(e,r={},n){console.warn("The `fromStream` method is deprecated. Please use the `JWT` constructor with a parsed stream instead. For more details, see https://cloud.google.com/docs/authentication/external/externally-sourced-credentials.");let s={};if(typeof r=="function"?n=r:s=r,n)this.fromStreamAsync(e,s).then(i=>n(null,i),n);else return this.fromStreamAsync(e,s)}fromStreamAsync(e,r){return new Promise((n,s)=>{if(!e)throw new Error("Must pass in a stream containing the Google auth settings.");let i=[];e.setEncoding("utf8").on("error",s).on("data",u=>i.push(u)).on("end",()=>{try{try{let u=JSON.parse(i.join("")),c=this._cacheClientFromJSON(u,r);return n(c)}catch(u){if(!this.keyFilename)throw u;let c=new os.JWT({...this.clientOptions,keyFile:this.keyFilename});return this.cachedCredential=c,this.setGapicJWTValues(c),n(c)}}catch(u){return s(u)}})})}fromAPIKey(e,r={}){return new os.JWT({...r,apiKey:e})}_isWindows(){let e=OS.platform();return!!(e&&e.length>=3&&e.substring(0,3).toLowerCase()==="win")}async getDefaultServiceProjectId(){return new Promise(e=>{(0,RS.exec)("gcloud config config-helper --format json",(r,n)=>{if(!r&&n)try{let s=JSON.parse(n).configuration.properties.core.project;e(s);return}catch{}e(null)})})}getProductionProjectId(){return process.env.GCLOUD_PROJECT||process.env.GOOGLE_CLOUD_PROJECT||process.env.gcloud_project||process.env.google_cloud_project}async getFileProjectId(){if(this.cachedCredential)return this.cachedCredential.projectId;if(this.keyFilename){let r=await this.getClient();if(r&&r.projectId)return r.projectId}let e=await this._tryGetApplicationCredentialsFromEnvironmentVariable();return e?e.projectId:null}async getExternalAccountClientProjectId(){return!this.jsonContent||this.jsonContent.type!==Qs.EXTERNAL_ACCOUNT_TYPE?null:await(await this.getClient()).getProjectId()}async getGCEProjectId(){try{return await Ys.project("project-id")}catch{return null}}getCredentials(e){if(e)this.getCredentialsAsync().then(r=>e(null,r),e);else return this.getCredentialsAsync()}async getCredentialsAsync(){let e=await this.getClient();if(e instanceof is.Impersonated)return{client_email:e.getTargetPrincipal()};if(e instanceof Qs.BaseExternalAccountClient){let r=e.getServiceAccountEmail();if(r)return{client_email:r,universe_domain:e.universeDomain}}if(this.jsonContent)return{client_email:this.jsonContent.client_email,private_key:this.jsonContent.private_key,universe_domain:this.jsonContent.universe_domain};if(await this._checkIsGCE()){let[r,n]=await Promise.all([Ys.instance("service-accounts/default/email"),this.getUniverseDomain()]);return{client_email:r,universe_domain:n}}throw new Error(Ht.GoogleAuthExceptionMessages.NO_CREDENTIALS_FOUND)}async getClient(){if(this.cachedCredential)return this.cachedCredential;this.#e=this.#e||this.#r();try{return await this.#e}finally{this.#e=null}}async#r(){if(this.jsonContent)return this._cacheClientFromJSON(this.jsonContent,this.clientOptions);if(this.keyFilename){let e=Wl.resolve(this.keyFilename),r=Ks.createReadStream(e);return await this.fromStreamAsync(r,this.clientOptions)}else if(this.apiKey){let e=await this.fromAPIKey(this.apiKey,this.clientOptions);e.scopes=this.scopes;let{credential:r}=await this.#t(e);return r}else{let{credential:e}=await this.getApplicationDefaultAsync(this.clientOptions);return e}}async getIdTokenClient(e){let r=await this.getClient();if(!("fetchIdToken"in r))throw new Error("Cannot fetch ID token in this environment, use GCE or set the GOOGLE_APPLICATION_CREDENTIALS environment variable to a service account credentials JSON file.");return new IS.IdTokenClient({targetAudience:e,idTokenProvider:r})}async getAccessToken(){return(await(await this.getClient()).getAccessToken()).token}async getRequestHeaders(e){return(await this.getClient()).getRequestHeaders(e)}async authorizeRequest(e={}){let r=e.url,s=await(await this.getClient()).getRequestHeaders(r);return e.headers=xS.Gaxios.mergeHeaders(e.headers,s),e}async fetch(...e){return(await this.getClient()).fetch(...e)}async request(e){return(await this.getClient()).request(e)}getEnv(){return(0,NS.getEnv)()}async sign(e,r){let n=await this.getClient(),s=await this.getUniverseDomain();if(r=r||`https://iamcredentials.${s}/v1/projects/-/serviceAccounts/`,n instanceof is.Impersonated)return(await n.sign(e)).signedBlob;let i=(0,FS.createCrypto)();if(n instanceof os.JWT&&n.key)return await i.sign(n.key,e);let u=await this.getCredentials();if(!u.client_email)throw new Error("Cannot sign data without `client_email`.");return this.signBlob(i,u.client_email,e,r)}async signBlob(e,r,n,s){let i=new URL(s+`${r}:signBlob`);return(await this.request({method:"POST",url:i.href,data:{payload:e.encodeBase64StringUtf8(n)},retry:!0,retryConfig:{httpMethodsToRetry:["POST"]}})).data.signedBlob}};Ht.GoogleAuth=Jl});var hy=V(fa=>{"use strict";Object.defineProperty(fa,"__esModule",{value:!0});fa.IAMAuth=void 0;var Vl=class{selector;token;constructor(e,r){this.selector=e,this.token=r,this.selector=e,this.token=r}getRequestHeaders(){return{"x-goog-iam-authority-selector":this.selector,"x-goog-iam-authorization-token":this.token}}};fa.IAMAuth=Vl});var py=V(sr=>{"use strict";Object.defineProperty(sr,"__esModule",{value:!0});sr.DownscopedClient=sr.EXPIRATION_TIME_OFFSET=sr.MAX_ACCESS_BOUNDARY_RULES_COUNT=void 0;var jS=Ve(),LS=X("stream"),Kl=pt(),MS=Gi(),US="urn:ietf:params:oauth:grant-type:token-exchange",qS="urn:ietf:params:oauth:token-type:access_token",$S="urn:ietf:params:oauth:token-type:access_token";sr.MAX_ACCESS_BOUNDARY_RULES_COUNT=10;sr.EXPIRATION_TIME_OFFSET=300*1e3;var Yl=class extends Kl.AuthClient{authClient;credentialAccessBoundary;cachedDownscopedAccessToken;stsCredential;constructor(e,r={accessBoundary:{accessBoundaryRules:[]}}){if(super(e instanceof Kl.AuthClient?{}:e),e instanceof Kl.AuthClient?(this.authClient=e,this.credentialAccessBoundary=r):(this.authClient=e.authClient,this.credentialAccessBoundary=e.credentialAccessBoundary),this.credentialAccessBoundary.accessBoundary.accessBoundaryRules.length===0)throw new Error("At least one access boundary rule needs to be defined.");if(this.credentialAccessBoundary.accessBoundary.accessBoundaryRules.length>sr.MAX_ACCESS_BOUNDARY_RULES_COUNT)throw new Error(`The provided access boundary has more than ${sr.MAX_ACCESS_BOUNDARY_RULES_COUNT} access boundary rules.`);for(let n of this.credentialAccessBoundary.accessBoundary.accessBoundaryRules)if(n.availablePermissions.length===0)throw new Error("At least one permission should be defined in access boundary rules.");this.stsCredential=new MS.StsCredentials({tokenExchangeEndpoint:`https://sts.${this.universeDomain}/v1/token`}),this.cachedDownscopedAccessToken=null}setCredentials(e){if(!e.expiry_date)throw new Error("The access token expiry_date field is missing in the provided credentials.");super.setCredentials(e),this.cachedDownscopedAccessToken=e}async getAccessToken(){return(!this.cachedDownscopedAccessToken||this.isExpired(this.cachedDownscopedAccessToken))&&await this.refreshAccessTokenAsync(),{token:this.cachedDownscopedAccessToken.access_token,expirationTime:this.cachedDownscopedAccessToken.expiry_date,res:this.cachedDownscopedAccessToken.res}}async getRequestHeaders(){let e=await this.getAccessToken(),r=new Headers({authorization:`Bearer ${e.token}`});return this.addSharedMetadataHeaders(r)}request(e,r){if(r)this.requestAsync(e).then(n=>r(null,n),n=>r(n,n.response));else return this.requestAsync(e)}async requestAsync(e,r=!1){let n;try{let s=await this.getRequestHeaders();e.headers=jS.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,s),n=await this.transporter.request(e)}catch(s){let i=s.response;if(i){let u=i.status,c=i.config.data instanceof LS.Readable;if(!r&&(u===401||u===403)&&!c&&this.forceRefreshOnFailure)return await this.refreshAccessTokenAsync(),await this.requestAsync(e,!0)}throw s}return n}async refreshAccessTokenAsync(){let e=(await this.authClient.getAccessToken()).token,r={grantType:US,requestedTokenType:qS,subjectToken:e,subjectTokenType:$S},n=await this.stsCredential.exchangeToken(r,void 0,this.credentialAccessBoundary),s=this.authClient.credentials?.expiry_date||null,i=n.expires_in?new Date().getTime()+n.expires_in*1e3:s;return this.cachedDownscopedAccessToken={access_token:n.access_token,expiry_date:i,res:n.res},this.credentials={},Object.assign(this.credentials,this.cachedDownscopedAccessToken),delete this.credentials.res,this.emit("tokens",{refresh_token:null,expiry_date:this.cachedDownscopedAccessToken.expiry_date,access_token:this.cachedDownscopedAccessToken.access_token,token_type:"Bearer",id_token:null}),this.cachedDownscopedAccessToken}isExpired(e){let r=new Date().getTime();return e.expiry_date?r>=e.expiry_date-this.eagerRefreshThresholdMillis:!1}};sr.DownscopedClient=Yl});var my=V(ha=>{"use strict";Object.defineProperty(ha,"__esModule",{value:!0});ha.PassThroughClient=void 0;var zS=pt(),Ql=class extends zS.AuthClient{async request(e){return this.transporter.request(e)}async getAccessToken(){return{}}async getRequestHeaders(){return new Headers}};ha.PassThroughClient=Ql});var Zl=V(te=>{"use strict";Object.defineProperty(te,"__esModule",{value:!0});te.GoogleAuth=te.auth=te.PassThroughClient=te.ExecutableError=te.PluggableAuthClient=te.DownscopedClient=te.BaseExternalAccountClient=te.ExternalAccountClient=te.IdentityPoolClient=te.AwsRequestSigner=te.AwsClient=te.UserRefreshClient=te.LoginTicket=te.ClientAuthentication=te.OAuth2Client=te.CodeChallengeMethod=te.Impersonated=te.JWT=te.JWTAccess=te.IdTokenClient=te.IAMAuth=te.GCPEnv=te.Compute=te.DEFAULT_UNIVERSE=te.AuthClient=te.gaxios=te.gcpMetadata=void 0;var gy=fy();Object.defineProperty(te,"GoogleAuth",{enumerable:!0,get:function(){return gy.GoogleAuth}});te.gcpMetadata=Ns();te.gaxios=Ve();var yy=pt();Object.defineProperty(te,"AuthClient",{enumerable:!0,get:function(){return yy.AuthClient}});Object.defineProperty(te,"DEFAULT_UNIVERSE",{enumerable:!0,get:function(){return yy.DEFAULT_UNIVERSE}});var HS=Mc();Object.defineProperty(te,"Compute",{enumerable:!0,get:function(){return HS.Compute}});var WS=$c();Object.defineProperty(te,"GCPEnv",{enumerable:!0,get:function(){return WS.GCPEnv}});var GS=hy();Object.defineProperty(te,"IAMAuth",{enumerable:!0,get:function(){return GS.IAMAuth}});var JS=qc();Object.defineProperty(te,"IdTokenClient",{enumerable:!0,get:function(){return JS.IdTokenClient}});var VS=ol();Object.defineProperty(te,"JWTAccess",{enumerable:!0,get:function(){return VS.JWTAccess}});var KS=al();Object.defineProperty(te,"JWT",{enumerable:!0,get:function(){return KS.JWT}});var YS=dl();Object.defineProperty(te,"Impersonated",{enumerable:!0,get:function(){return YS.Impersonated}});var Xl=pn();Object.defineProperty(te,"CodeChallengeMethod",{enumerable:!0,get:function(){return Xl.CodeChallengeMethod}});Object.defineProperty(te,"OAuth2Client",{enumerable:!0,get:function(){return Xl.OAuth2Client}});Object.defineProperty(te,"ClientAuthentication",{enumerable:!0,get:function(){return Xl.ClientAuthentication}});var QS=Nc();Object.defineProperty(te,"LoginTicket",{enumerable:!0,get:function(){return QS.LoginTicket}});var XS=cl();Object.defineProperty(te,"UserRefreshClient",{enumerable:!0,get:function(){return XS.UserRefreshClient}});var ZS=xl();Object.defineProperty(te,"AwsClient",{enumerable:!0,get:function(){return ZS.AwsClient}});var ev=Tl();Object.defineProperty(te,"AwsRequestSigner",{enumerable:!0,get:function(){return ev.AwsRequestSigner}});var tv=vl();Object.defineProperty(te,"IdentityPoolClient",{enumerable:!0,get:function(){return tv.IdentityPoolClient}});var rv=$l();Object.defineProperty(te,"ExternalAccountClient",{enumerable:!0,get:function(){return rv.ExternalAccountClient}});var nv=Wr();Object.defineProperty(te,"BaseExternalAccountClient",{enumerable:!0,get:function(){return nv.BaseExternalAccountClient}});var sv=py();Object.defineProperty(te,"DownscopedClient",{enumerable:!0,get:function(){return sv.DownscopedClient}});var _y=Ul();Object.defineProperty(te,"PluggableAuthClient",{enumerable:!0,get:function(){return _y.PluggableAuthClient}});Object.defineProperty(te,"ExecutableError",{enumerable:!0,get:function(){return _y.ExecutableError}});var ov=my();Object.defineProperty(te,"PassThroughClient",{enumerable:!0,get:function(){return ov.PassThroughClient}});var iv=new gy.GoogleAuth;te.auth=iv});var n0=V((EP,Fd)=>{"use strict";var HT=/at\s(?:.*\.)?plugin\s.*\n\s*(.*)/,WT=/(\w*(\.\w*)*)\..*/;Fd.exports=function(e){if(e.name.length>0)return e.name;let r=Error.stackTraceLimit;Error.stackTraceLimit=10;try{throw new Error("anonymous function")}catch(n){return Error.stackTraceLimit=r,r0(n.stack)}};function r0(t){let e=t.match(HT);return e?e[1].split(/[/\\]/).slice(-1)[0].match(WT)[1]:"anonymous"}Fd.exports.extractPluginName=r0});var o0=V((AP,s0)=>{"use strict";s0.exports=function(e){return e[0]==="@"&&(e=e.slice(1).replace("/","-")),e.replace(/-(.)/g,function(r,n){return n.toUpperCase()})}});var i0=V((SP,Ha)=>{"use strict";var GT=n0(),JT=o0(),VT=0;function Pd(t,e={}){let r=!1;if(t.default!==void 0&&(t=t.default),typeof t!="function")throw new TypeError(`fastify-plugin expects a function, instead got a '${typeof t}'`);if(typeof e=="string"&&(e={fastify:e}),typeof e!="object"||Array.isArray(e)||e===null)throw new TypeError("The options object should be an object");if(e.fastify!==void 0&&typeof e.fastify!="string")throw new TypeError(`fastify-plugin expects a version string, instead got '${typeof e.fastify}'`);e.name||(r=!0,e.name=GT(t)+"-auto-"+VT++),t[Symbol.for("skip-override")]=e.encapsulate!==!0,t[Symbol.for("fastify.display-name")]=e.name,t[Symbol.for("plugin-meta")]=e,t.default||(t.default=t);let n=JT(e.name);return!r&&!t[n]&&(t[n]=t),t}Ha.exports=Pd;Ha.exports.default=Pd;Ha.exports.fastifyPlugin=Pd});var oo,Id=je(()=>{"use strict";oo=class{type="console";config;colors={reset:"\x1B[0m",bright:"\x1B[1m",dim:"\x1B[2m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",white:"\x1B[37m"};constructor(e={}){this.config={colors:!0,level:"log",...e}}formatData(e,r){let{format:n="text",timestamp:s=!0,prefix:i,metadata:u}=r||{},c="";if(s){let l=new Date().toISOString();c+=this.config.colors?`${this.colors.cyan}[${l}]${this.colors.reset} `:`[${l}] `}switch(i&&(c+=this.config.colors?`${this.colors.bright}${i}${this.colors.reset} `:`${i} `),n){case"json":c+=JSON.stringify(e,null,2);break;case"markdown":typeof e=="object"?c+=this.toMarkdown(e):c+=String(e);break;case"text":default:typeof e=="object"?c+=JSON.stringify(e,null,2):c+=String(e);break}return u&&Object.keys(u).length>0&&(c+=`
|
|
68
68
|
`+(this.config.colors?`${this.colors.dim}`:""),c+="Metadata: "+JSON.stringify(u,null,2),this.config.colors&&(c+=this.colors.reset)),c}toMarkdown(e,r=0){let n=" ".repeat(r);return Array.isArray(e)?e.map(s=>typeof s=="object"?`${n}-
|
|
69
69
|
${this.toMarkdown(s,r+1)}`:`${n}- ${s}`).join(`
|
|
70
70
|
`):typeof e=="object"&&e!==null?Object.entries(e).map(([s,i])=>typeof i=="object"&&i!==null?`${n}${s}:
|
|
71
71
|
${this.toMarkdown(i,r+1)}`:`${n}${s}: ${i}`).join(`
|
|
72
|
-
`):`${n}${e}`}async output(e,r={}){try{let n=this.formatData(e,r);switch(this.config.level||"log"){case"info":console.info(n);break;case"warn":console.warn(n);break;case"error":console.error(n);break;case"debug":console.debug(n);break;case"log":default:console.log(n);break}return!0}catch(n){return console.error("[ConsoleOutputHandler] Output failed:",n),!1}}}});var ro,Ef=je(()=>{"use strict";ro=class{type="webhook";config;defaultTimeout=3e4;constructor(e){if(!e.url)throw new Error("Webhook URL is required");this.config={method:"POST",retry:{maxAttempts:3,backoffMs:1e3},silent:!1,...e}}buildHeaders(){let e={"Content-Type":"application/json",...this.config.headers||{}};if(this.config.auth)switch(this.config.auth.type){case"bearer":this.config.auth.token&&(e.Authorization=`Bearer ${this.config.auth.token}`);break;case"basic":if(this.config.auth.username&&this.config.auth.password){let r=Buffer.from(`${this.config.auth.username}:${this.config.auth.password}`).toString("base64");e.Authorization=`Basic ${r}`}break;case"custom":this.config.auth.custom&&(e[this.config.auth.custom.header]=this.config.auth.custom.value);break}return e}buildBody(e,r){let{format:n="json",timestamp:s=!0,prefix:i,metadata:u}=r||{},c={data:e};return s&&(c.timestamp=new Date().toISOString()),i&&(c.prefix=i),u&&Object.keys(u).length>0&&(c.metadata=u),c}async sendRequest(e,r,n,s,i){let u=new AbortController,c=setTimeout(()=>u.abort(),i);try{let l=await fetch(e,{method:r,headers:n,body:JSON.stringify(s),signal:u.signal});if(clearTimeout(c),!l.ok)throw new Error(`HTTP ${l.status}: ${l.statusText}`);return l}catch(l){throw clearTimeout(c),l}}delay(e){return new Promise(r=>setTimeout(r,e))}async sendWithRetry(e,r,n,s,i,u){let c=null;for(let l=1;l<=u.maxAttempts;l++)try{return await this.sendRequest(e,r,n,s,i)}catch(h){if(c=h,l===u.maxAttempts)break;let d=u.backoffMs*Math.pow(2,l-1);console.warn(`[WebhookOutputHandler] Request failed (attempt ${l}/${u.maxAttempts}), retrying in ${d}ms...`,h.message),await this.delay(d)}throw c}async output(e,r={}){let n=r.timeout||this.defaultTimeout;try{let s=this.buildHeaders(),i=this.buildBody(e,r),u=await this.sendWithRetry(this.config.url,this.config.method,s,i,n,this.config.retry);return!0}catch(s){let i=s instanceof Error?s.message:String(s);if(this.config.silent)return console.error(`[WebhookOutputHandler] Failed to send data: ${i}`),!1;throw new Error(`Webhook output failed: ${i}`)}}}});import{writeFileSync as _D,existsSync as bD,mkdirSync as CD}from"fs";import{join as Wy}from"path";import{tmpdir as wD}from"os";var no,Af=je(()=>{"use strict";no=class{type="temp-file";config;baseDir;constructor(e={}){this.config={subdirectory:"claude-code-router",extension:"json",includeTimestamp:!1,prefix:"session",...e};let r=wD();this.baseDir=Wy(r,this.config.subdirectory),this.ensureDir()}ensureDir(){try{bD(this.baseDir)||CD(this.baseDir,{recursive:!0})}catch{}}extractSessionId(e){try{let r=e.match(/_session_([a-f0-9-]+)/i);return r?r[1]:null}catch{return null}}getFilePath(e){let r=this.config.prefix||"session",n=this.config.extension?`.${this.config.extension}`:"",s;if(this.config.includeTimestamp){let i=Date.now();s=`${r}-${e}-${i}${n}`}else s=`${r}-${e}${n}`;return Wy(this.baseDir,s)}async output(e,r={}){try{let n=r.metadata?.sessionId;if(!n)return!1;let s={...e,timestamp:Date.now(),sessionId:n},i=this.getFilePath(n);return _D(i,JSON.stringify(s,null,2),"utf-8"),!0}catch{return!1}}getBaseDir(){return this.baseDir}}});var Sf,cs,Gy=je(()=>{"use strict";wf();Ef();Af();Sf=class{handlers=new Map;defaultOptions={};registerHandler(e,r){this.handlers.set(e,r)}registerHandlers(e){for(let r of e)if(r.enabled!==!1)try{let n=this.createHandler(r),s=r.type+"_"+Date.now();this.registerHandler(s,n)}catch(n){console.error(`[OutputManager] Failed to register ${r.type} handler:`,n)}}createHandler(e){switch(e.type){case"console":return new to(e.config);case"webhook":return new ro(e.config);case"temp-file":return new no(e.config);default:throw new Error(`Unknown output handler type: ${e.type}`)}}unregisterHandler(e){return this.handlers.delete(e)}getHandler(e){return this.handlers.get(e)}getAllHandlers(){return new Map(this.handlers)}clearHandlers(){this.handlers.clear()}setDefaultOptions(e){this.defaultOptions={...this.defaultOptions,...e}}getDefaultOptions(){return{...this.defaultOptions}}async output(e,r){let n={...this.defaultOptions,...r},s={success:[],failed:[]},i=Array.from(this.handlers.entries()).map(async([u,c])=>{try{await c.output(e,n)?s.success.push(u):s.failed.push(u)}catch(l){console.error(`[OutputManager] Handler ${u} failed:`,l),s.failed.push(u)}});return await Promise.all(i),s}async outputTo(e,r,n){let s={...this.defaultOptions,...n},i={success:[],failed:[]},u=e.map(async c=>{let l=this.handlers.get(c);if(!l){console.warn(`[OutputManager] Handler ${c} not found`),i.failed.push(c);return}try{await l.output(r,s)?i.success.push(c):i.failed.push(c)}catch(h){console.error(`[OutputManager] Handler ${c} failed:`,h),i.failed.push(c)}});return await Promise.all(u),i}async outputToType(e,r,n){let s=Array.from(this.handlers.entries()).filter(([i,u])=>u.type===e).map(([i])=>i);return this.outputTo(s,r,n)}},cs=new Sf});import AD from"fastify";import SD from"@fastify/cors";var $d=Pr(Au(),1);import{readFileSync as G_,existsSync as Ud}from"fs";import{join as qd}from"path";import{config as J_}from"dotenv";var Dn=class{config={};options;constructor(e={jsonPath:"./config.json"}){this.options={envPath:e.envPath||".env",jsonPath:e.jsonPath,useEnvFile:!1,useJsonFile:e.useJsonFile!==!1,useEnvironmentVariables:e.useEnvironmentVariables!==!1,...e},this.loadConfig()}loadConfig(){this.options.useJsonFile&&this.options.jsonPath&&this.loadJsonConfig(),this.options.initialConfig&&(this.config={...this.config,...this.options.initialConfig}),this.options.useEnvFile&&this.loadEnvConfig(),this.config.LOG_FILE&&(process.env.LOG_FILE=this.config.LOG_FILE),this.config.LOG&&(process.env.LOG=this.config.LOG)}loadJsonConfig(){if(!this.options.jsonPath)return;let e=this.isAbsolutePath(this.options.jsonPath)?this.options.jsonPath:qd(process.cwd(),this.options.jsonPath);if(Ud(e))try{let r=G_(e,"utf-8"),n=$d.default.parse(r);this.config={...this.config,...n},console.log(`Loaded JSON config from: ${e}`)}catch(r){console.warn(`Failed to load JSON config from ${e}:`,r)}else console.warn(`JSON config file not found: ${e}`)}loadEnvConfig(){let e=this.isAbsolutePath(this.options.envPath)?this.options.envPath:qd(process.cwd(),this.options.envPath);if(Ud(e))try{let r=J_({path:e});r.parsed&&(this.config={...this.config,...this.parseEnvConfig(r.parsed)})}catch(r){console.warn(`Failed to load .env config from ${e}:`,r)}}loadEnvironmentVariables(){let e=this.parseEnvConfig(process.env);this.config={...this.config,...e}}parseEnvConfig(e){let r={};return Object.assign(r,e),r}isAbsolutePath(e){return e.startsWith("/")||e.includes(":")}get(e,r){let n=this.config[e];return n!==void 0?n:r}getAll(){return{...this.config}}getHttpsProxy(){return this.get("HTTPS_PROXY")||this.get("https_proxy")||this.get("httpsProxy")||this.get("PROXY_URL")}has(e){return this.config[e]!==void 0}set(e,r){this.config[e]=r}reload(){this.config={},this.loadConfig()}getConfigSummary(){let e=[];return this.options.initialConfig&&e.push("Initial Config"),this.options.useJsonFile&&this.options.jsonPath&&e.push(`JSON: ${this.options.jsonPath}`),this.options.useEnvFile&&e.push(`ENV: ${this.options.envPath}`),this.options.useEnvironmentVariables&&e.push("Environment Variables"),`Config sources: ${e.join(", ")}`}};function nt(t,e=500,r="internal_error",n="api_error"){let s=new Error(t);return s.statusCode=e,s.code=r,s.type=n,s}async function zd(t,e,r){e.log.error(t);let n=t.statusCode||500,s={error:{message:t.message+t.stack||"Internal Server Error",type:t.type||"api_error",code:t.code||"internal_error"}};return r.code(n).send(s)}import{ProxyAgent as V_}from"undici";function Hd(t,e,r,n,s){let i=new Headers({"Content-Type":"application/json"});r.headers&&Object.entries(r.headers).forEach(([h,d])=>{d&&i.set(h,d)});let u,c=AbortSignal.timeout(r.TIMEOUT??60*1e3*60);if(r.signal){let h=new AbortController,d=()=>h.abort();r.signal.addEventListener("abort",d),c.addEventListener("abort",d),u=h.signal}else u=c;let l={method:"POST",headers:i,body:JSON.stringify(e),signal:u};return r.httpsProxy&&(l.dispatcher=new V_(new URL(r.httpsProxy).toString())),s?.debug({reqId:n.req.id,request:l,headers:Object.fromEntries(i.entries()),requestUrl:typeof t=="string"?t:t.toString(),useProxy:r.httpsProxy},"final request"),fetch(typeof t=="string"?t:t.toString(),l)}var Wd="2.0.47";var Y_={enabled:!0,failureThreshold:3,probeIntervalMinutes:5,halfOpenSuccessThreshold:2,rateLimitThreshold:1},Lo=class{states=new Map;config;probeTimer;constructor(e){this.config={...Y_,...e}}getKey(e,r){return`${e},${r}`}recordSuccess(e,r){if(!this.config.enabled)return;let n=this.getKey(e,r),s=this.states.get(n);s&&(s.successCount++,s.status==="half-open"?s.successCount>=this.config.halfOpenSuccessThreshold&&this.states.delete(n):s.status==="open"&&(s.status="half-open",s.successCount=1,s.failureCount=0))}isRateLimitError(e){if(!e)return!1;let r=e.toLowerCase();return r.includes("429")||r.includes("rate_limit")||r.includes("ratelimit")||r.includes("rate limit")||r.includes("overloaded")||r.includes("quota")}recordFailure(e,r,n){if(!this.config.enabled)return;let s=this.getKey(e,r),i=this.states.get(s);i||(i={provider:e,model:r,status:"closed",failureCount:0,successCount:0,lastFailureTime:0,lastProbeTime:0},this.states.set(s,i)),i.failureCount++,i.lastFailureTime=Date.now(),i.lastError=n;let c=this.isRateLimitError(n)?this.config.rateLimitThreshold:this.config.failureThreshold;i.status==="half-open"?(i.status="open",i.successCount=0,i.lastProbeTime=0):i.status==="closed"&&i.failureCount>=c&&(i.status="open",i.lastProbeTime=0)}getState(e,r){return this.states.get(this.getKey(e,r))}isAvailable(e,r){if(!this.config.enabled)return!0;let n=this.getState(e,r);return n?n.status!=="open":!0}getPriority(e,r){if(!this.config.enabled)return 0;let n=this.getState(e,r);if(!n)return 0;switch(n.status){case"closed":return 0;case"half-open":return 1;case"open":return 2}}getHealthyModels(){return[]}getFailPoolModels(){let e=[];for(let[r,n]of this.states)n.status==="open"&&e.push(r);return e}getHalfOpenModels(){let e=[];for(let[r,n]of this.states)n.status==="half-open"&&e.push(r);return e}needsProbe(e){return Date.now()-e.lastProbeTime>=this.config.probeIntervalMinutes*60*1e3}markProbeAttempt(e,r){let n=this.getKey(e,r),s=this.states.get(n);s&&s.status==="open"&&(s.lastProbeTime=Date.now())}clear(){this.states.clear()}getAllStates(){return Array.from(this.states.values())}stopProbeTimer(){this.probeTimer&&(clearInterval(this.probeTimer),this.probeTimer=void 0)}},Su=null;function vn(t){return Su||(Su=new Lo(t)),Su}var ku=new Map;function X_(t){try{let e=new URL(t);return e.hostname.includes("moonshot")||e.hostname.includes("kimi")}catch{return!1}}function Tu(t,e,r){if(!X_(e))return;let n=c=>{if(r instanceof Headers)return r.get(c);let l=Object.keys(r).find(h=>h.toLowerCase()===c);return l?r[l]:null},s=n("x-ratelimit-remaining"),i=n("x-ratelimit-limit"),u=n("x-ratelimit-reset");(s||i||u)&&ku.set(t,{provider:t,remaining:s?parseInt(s,10):null,limit:i?parseInt(i,10):null,reset:u?parseInt(u,10):null,capturedAt:Date.now()})}function Q_(t){return ku.get(t)}function Z_(){return Array.from(ku.values())}async function eb(t,e,r,n){let s=t.body,i=t.provider,u=r.providerService.getProvider(i);if(!u)throw nt(`Provider '${i}' not found`,404,"provider_not_found");try{let{requestBody:c,config:l,bypass:h}=await Gd(s,u,n,t.headers,{req:t}),d=await Jd(c,l,u,r,h,n,{req:t});try{u?.baseUrl&&d?.headers&&Tu(i,u.baseUrl,d.headers)}catch{}let p=await Vd(c,d,u,n,h,{req:t});return Kd(p,e,s)}catch(c){let l=await tb(t,e,r,n,c);if(l)return l;throw c}}async function tb(t,e,r,n,s){let i=t.scenarioType||"default",u=t.familyFallback,c=r.configService.get("fallback"),l=vn(),h=[];if(u?.[i]?h=u[i]:c?.[i]&&(h=c[i]),!Array.isArray(h)||h.length===0)return null;let d=t.provider||"",p=t.body.model||"";l.recordFailure(d,p,s?.message),t.log.warn(`Request failed for ${t.scenarioType}, trying ${h.length} fallback models`);let A=h.sort((v,S)=>{let[y,g]=v.split(","),[m,k]=S.split(",");return l.getPriority(y,g)-l.getPriority(m,k)});for(let v of A)try{let[S,...y]=v.split(","),g=y.join(",");if(!l.isAvailable(S,g)){t.log.warn(`Fallback model ${v} unavailable (fail pool), skipping`);continue}t.log.info(`Trying fallback model: ${v}`);let m={...t.body};m.model=g;let k={...t,provider:S,body:m},b=r.providerService.getProvider(S);if(!b){t.log.warn(`Fallback provider '${S}' not found, skipping`);continue}let{requestBody:E,config:R,bypass:F}=await Gd(m,b,n,t.headers,{req:k}),$=await Jd(E,R,b,r,F,n,{req:k});try{b?.baseUrl&&$?.headers&&Tu(S,b.baseUrl,$.headers)}catch{}let J=await Vd(E,$,b,n,F,{req:k});return t.log.info(`Fallback model ${v} succeeded`),l.recordSuccess(S,g),Kd(J,e,m)}catch(S){let[y,...g]=v.split(","),m=g.join(",");l.recordFailure(y,m,S.message),t.log.warn(`Fallback model ${v} failed: ${S.message}`);continue}return t.log.error(`All fallback models failed for ${i}`),null}async function Gd(t,e,r,n,s){let i=JSON.parse(JSON.stringify(t)),u={},c=!1;if(c=rb(e,r,t),c&&(n instanceof Headers?n.delete("content-length"):delete n["content-length"],u.headers=n),!c&&typeof r.transformRequestOut=="function"){let l=await r.transformRequestOut(i);l.body?(i=l.body,u=l.config||{}):i=l}if(!c&&e.transformer?.use?.length)for(let l of e.transformer.use){if(!l||typeof l.transformRequestIn!="function")continue;let h=await l.transformRequestIn(i,e,s);h.body?(i=h.body,u={...u,...h.config}):i=h}if(!c&&e.transformer?.[t.model]?.use?.length)for(let l of e.transformer[t.model].use)!l||typeof l.transformRequestIn!="function"||(i=await l.transformRequestIn(i,e,s));return{requestBody:i,config:u,bypass:c}}function rb(t,e,r){return t.transformer?.use?.length===1&&t.transformer.use[0].name===e.name&&(!t.transformer?.[r.model]?.use.length||t.transformer?.[r.model]?.use.length===1&&t.transformer?.[r.model]?.use[0].name===e.name)}async function Jd(t,e,r,n,s,i,u){let c=e.url||new URL(r.baseUrl);if(!e.TIMEOUT){let d=n.configService.get("API_TIMEOUT_MS");d&&(e.TIMEOUT=typeof d=="string"?parseInt(d,10):d)}if(s&&typeof i.auth=="function"){let d=await i.auth(t,r);if(d.body){t=d.body;let p=e.headers||{};d.config?.headers&&(p={...p,...d.config.headers},delete p.host,delete d.config.headers),e={...e,...d.config,headers:p}}else t=d}let l={Authorization:`Bearer ${r.apiKey}`,...e?.headers||{}};for(let d in l)(l[d]==="undefined"||["authorization","Authorization"].includes(d)&&l[d]?.includes("undefined"))&&delete l[d];let h=await Hd(c,t,{httpsProxy:n.configService.getHttpsProxy(),...e,headers:JSON.parse(JSON.stringify(l))},u,n.log);if(!h.ok){let d=await h.text();throw n.log.error(`[provider_response_error] Error from provider(${r.name},${t.model}: ${h.status}): ${d}`),nt(`Error from provider(${r.name},${t.model}: ${h.status}): ${d}`,h.status,"provider_response_error")}return h}async function Vd(t,e,r,n,s,i){let u=e;if(!s&&r.transformer?.use?.length)for(let c of Array.from(r.transformer.use).reverse())!c||typeof c.transformResponseOut!="function"||(u=await c.transformResponseOut(u,i));if(!s&&r.transformer?.[t.model]?.use?.length)for(let c of Array.from(r.transformer[t.model].use).reverse())!c||typeof c.transformResponseOut!="function"||(u=await c.transformResponseOut(u,i));return!s&&n.transformResponseIn&&(u=await n.transformResponseIn(u,i)),u}function Kd(t,e,r){return t.ok||e.code(t.status),r.stream===!0?(e.header("Content-Type","text/event-stream"),e.header("Cache-Control","no-cache"),e.header("Connection","keep-alive"),e.send(t.body)):t.json()}var Du=async t=>{t.get("/",async()=>({message:"LLMs API",version:Wd})),t.get("/health",async()=>({status:"ok",timestamp:new Date().toISOString()})),t.get("/providers/health",async()=>({states:vn().getAllStates().map(s=>({provider:s.provider,model:s.model,status:s.status,failureCount:s.failureCount,successCount:s.successCount,lastFailureTime:s.lastFailureTime,lastError:s.lastError})),timestamp:new Date().toISOString()}));let e=t.transformerService.getTransformersWithEndpoint();for(let{transformer:r}of e)r.endPoint&&t.post(r.endPoint,async(n,s)=>eb(n,s,t,r));t.post("/providers",{schema:{body:{type:"object",properties:{id:{type:"string"},name:{type:"string"},type:{type:"string",enum:["openai","anthropic"]},baseUrl:{type:"string"},apiKey:{type:"string"},models:{type:"array",items:{type:"string"}}},required:["id","name","type","baseUrl","apiKey","models"]}}},async(r,n)=>{let{name:s,baseUrl:i,apiKey:u,models:c}=r.body;if(!s?.trim())throw nt("Provider name is required",400,"invalid_request");if(!i||!nb(i))throw nt("Valid base URL is required",400,"invalid_request");if(!u?.trim())throw nt("API key is required",400,"invalid_request");if(!c||!Array.isArray(c)||c.length===0)throw nt("At least one model is required",400,"invalid_request");if(t.providerService.getProvider(r.body.name))throw nt(`Provider with name '${r.body.name}' already exists`,400,"provider_exists");return t.providerService.registerProvider(r.body)}),t.get("/providers",async()=>t.providerService.getProviders()),t.get("/providers/:id",{schema:{params:{type:"object",properties:{id:{type:"string"}},required:["id"]}}},async r=>{let n=t.providerService.getProvider(r.params.id);if(!n)throw nt("Provider not found",404,"provider_not_found");return n}),t.put("/providers/:id",{schema:{params:{type:"object",properties:{id:{type:"string"}},required:["id"]},body:{type:"object",properties:{name:{type:"string"},type:{type:"string",enum:["openai","anthropic"]},baseUrl:{type:"string"},apiKey:{type:"string"},models:{type:"array",items:{type:"string"}},enabled:{type:"boolean"}}}}},async(r,n)=>{let s=t.providerService.updateProvider(r.params.id,r.body);if(!s)throw nt("Provider not found",404,"provider_not_found");return s}),t.delete("/providers/:id",{schema:{params:{type:"object",properties:{id:{type:"string"}},required:["id"]}}},async r=>{if(!t.providerService.deleteProvider(r.params.id))throw nt("Provider not found",404,"provider_not_found");return{message:"Provider deleted successfully"}}),t.patch("/providers/:id/toggle",{schema:{params:{type:"object",properties:{id:{type:"string"}},required:["id"]},body:{type:"object",properties:{enabled:{type:"boolean"}},required:["enabled"]}}},async(r,n)=>{if(!t.providerService.toggleProvider(r.params.id,r.body.enabled))throw nt("Provider not found",404,"provider_not_found");return{message:`Provider ${r.body.enabled?"enabled":"disabled"} successfully`}})};function nb(t){try{return new URL(t),!0}catch{return!1}}var Rn=class{constructor(e,r,n){this.configService=e;this.transformerService=r;this.logger=n;this.initializeCustomProviders()}providers=new Map;modelRoutes=new Map;initializeCustomProviders(){let e=this.configService.get("providers");if(e&&Array.isArray(e)){this.initializeFromProvidersArray(e);return}}initializeFromProvidersArray(e){e.forEach(r=>{try{if(!r.name||!r.api_base_url||!r.api_key)return;let n={};r.transformer&&Object.keys(r.transformer).forEach(s=>{s==="use"?Array.isArray(r.transformer.use)&&(n.use=r.transformer.use.map(i=>{if(Array.isArray(i)&&typeof i[0]=="string"){let u=this.transformerService.getTransformer(i[0]);if(u)return new u(i[1])}if(typeof i=="string"){let u=this.transformerService.getTransformer(i);return typeof u=="function"?new u:u}}).filter(i=>typeof i<"u")):Array.isArray(r.transformer[s]?.use)&&(n[s]={use:r.transformer[s].use.map(i=>{if(Array.isArray(i)&&typeof i[0]=="string"){let u=this.transformerService.getTransformer(i[0]);if(u)return new u(i[1])}if(typeof i=="string"){let u=this.transformerService.getTransformer(i);return typeof u=="function"?new u:u}}).filter(i=>typeof i<"u")})}),this.registerProvider({name:r.name,baseUrl:r.api_base_url,apiKey:r.api_key,models:r.models||[],transformer:r.transformer?n:void 0}),this.logger.info(`${r.name} provider registered`)}catch(n){this.logger.error(`${r.name} provider registered error: ${n}`)}})}registerProvider(e){let r={...e};return this.providers.set(r.name,r),e.models.forEach(n=>{let s=`${r.name},${n}`,i={provider:r.name,model:n,fullModel:s};this.modelRoutes.set(s,i),this.modelRoutes.has(n)||this.modelRoutes.set(n,i)}),r}getProviders(){return Array.from(this.providers.values())}getProvider(e){return this.providers.get(e)}updateProvider(e,r){let n=this.providers.get(e);if(!n)return null;let s={...n,...r,updatedAt:new Date};return this.providers.set(e,s),r.models&&(n.models.forEach(i=>{let u=`${n.name},${i}`;this.modelRoutes.delete(u),this.modelRoutes.delete(i)}),r.models.forEach(i=>{let u=`${n.name},${i}`,c={provider:n.name,model:i,fullModel:u};this.modelRoutes.set(u,c),this.modelRoutes.has(i)||this.modelRoutes.set(i,c)})),s}deleteProvider(e){let r=this.providers.get(e);return r?(r.models.forEach(n=>{let s=`${r.name},${n}`;this.modelRoutes.delete(s),this.modelRoutes.delete(n)}),this.providers.delete(e),!0):!1}toggleProvider(e,r){return!!this.providers.get(e)}resolveModelRoute(e){let r=this.modelRoutes.get(e);if(!r)return null;let n=this.providers.get(r.provider);return n?{provider:n,originalModel:e,targetModel:r.model}:null}getAvailableModelNames(){let e=[];return this.providers.forEach(r=>{r.models.forEach(n=>{e.push(n),e.push(`${r.name},${n}`)})}),e}getModelRoutes(){return Array.from(this.modelRoutes.values())}parseTransformerConfig(e){return e?Array.isArray(e)?e.reduce((r,n)=>{if(Array.isArray(n)){let[s,i={}]=n;r[s]=i}else r[n]={};return r},{}):e:{}}async getAvailableModels(){let e=[];return this.providers.forEach(r=>{r.models.forEach(n=>{e.push({id:n,object:"model",owned_by:r.name,provider:r.name}),e.push({id:`${r.name},${n}`,object:"model",owned_by:r.name,provider:r.name})})}),{object:"list",data:e}}};var Je=[];for(let t=0;t<256;++t)Je.push((t+256).toString(16).slice(1));function Yd(t,e=0){return(Je[t[e+0]]+Je[t[e+1]]+Je[t[e+2]]+Je[t[e+3]]+"-"+Je[t[e+4]]+Je[t[e+5]]+"-"+Je[t[e+6]]+Je[t[e+7]]+"-"+Je[t[e+8]]+Je[t[e+9]]+"-"+Je[t[e+10]]+Je[t[e+11]]+Je[t[e+12]]+Je[t[e+13]]+Je[t[e+14]]+Je[t[e+15]]).toLowerCase()}import{randomFillSync as sb}from"crypto";var Uo=new Uint8Array(256),Mo=Uo.length;function vu(){return Mo>Uo.length-16&&(sb(Uo),Mo=0),Uo.slice(Mo,Mo+=16)}import{randomUUID as ob}from"crypto";var Ru={randomUUID:ob};function ib(t,e,r){if(Ru.randomUUID&&!e&&!t)return Ru.randomUUID();t=t||{};let n=t.random??t.rng?.()??vu();if(n.length<16)throw new Error("Random bytes length must be >= 16");if(n[6]=n[6]&15|64,n[8]=n[8]&63|128,e){if(r=r||0,r<0||r+16>e.length)throw new RangeError(`UUID byte range ${r}:${r+15} is out of buffer bounds`);for(let s=0;s<16;++s)e[r+s]=n[s];return e}return Yd(n)}var Gt=ib;var Xd=t=>t<=0?"none":t<=1024?"low":t<=8192?"medium":"high";var Qd=(t,e)=>(t.includes("base64")&&(t=t.split("base64").pop(),t.startsWith(",")&&(t=t.slice(1))),`data:${e};base64,${t}`);var qo=class{constructor(e){this.options=e;this.useBearer=this.options?.UseBearer??!1}name="Anthropic";endPoint="/v1/messages";useBearer;logger;async auth(e,r){let n={};return this.useBearer?(n.authorization=`Bearer ${r.apiKey}`,n["x-api-key"]=void 0):(n["x-api-key"]=r.apiKey,n.authorization=void 0),{body:e,config:{headers:n}}}async transformRequestOut(e){let r=[];if(e.system){if(typeof e.system=="string")r.push({role:"system",content:e.system});else if(Array.isArray(e.system)&&e.system.length){let i=e.system.filter(u=>u.type==="text"&&u.text).map(u=>({type:"text",text:u.text,cache_control:u.cache_control}));r.push({role:"system",content:i})}}JSON.parse(JSON.stringify(e.messages||[]))?.forEach(i=>{if(i.role==="user"||i.role==="assistant"){if(typeof i.content=="string"){r.push({role:i.role,content:i.content});return}if(Array.isArray(i.content)){if(i.role==="user"){let u=i.content.filter(l=>l.type==="tool_result"&&l.tool_use_id);u.length&&u.forEach(l=>{let h={role:"tool",content:typeof l.content=="string"?l.content:JSON.stringify(l.content),tool_call_id:l.tool_use_id,cache_control:l.cache_control};r.push(h)});let c=i.content.filter(l=>l.type==="text"&&l.text||l.type==="image"&&l.source);c.length&&r.push({role:"user",content:c.map(l=>l?.type==="image"?{type:"image_url",image_url:{url:l.source?.type==="base64"?Qd(l.source.data,l.source.media_type):l.source.url},media_type:l.source.media_type}:l)})}else if(i.role==="assistant"){let u={role:"assistant",content:""},c=i.content.filter(d=>d.type==="text"&&d.text);c.length&&(u.content=c.map(d=>d.text).join(`
|
|
73
|
-
`));let l=i.content.filter(d=>d.type==="tool_use"&&d.id);l.length&&(u.tool_calls=l.map(d=>({id:d.id,type:"function",function:{name:d.name,arguments:JSON.stringify(d.input||{})}})));let h=i.content.find(d=>d.type==="thinking"&&d.signature);h&&(u.thinking={content:h.thinking,signature:h.signature}),r.push(u)}return}}});let s={messages:r,model:e.model,max_tokens:e.max_tokens,temperature:e.temperature,stream:e.stream,tools:e.tools?.length?this.convertAnthropicToolsToUnified(e.tools):void 0,tool_choice:e.tool_choice};return e.thinking&&(s.reasoning={effort:
|
|
74
|
-
data: ${JSON.stringify(
|
|
72
|
+
`):`${n}${e}`}async output(e,r={}){try{let n=this.formatData(e,r);switch(this.config.level||"log"){case"info":console.info(n);break;case"warn":console.warn(n);break;case"error":console.error(n);break;case"debug":console.debug(n);break;case"log":default:console.log(n);break}return!0}catch(n){return console.error("[ConsoleOutputHandler] Output failed:",n),!1}}}});var io,Nd=je(()=>{"use strict";io=class{type="webhook";config;defaultTimeout=3e4;constructor(e){if(!e.url)throw new Error("Webhook URL is required");this.config={method:"POST",retry:{maxAttempts:3,backoffMs:1e3},silent:!1,...e}}buildHeaders(){let e={"Content-Type":"application/json",...this.config.headers||{}};if(this.config.auth)switch(this.config.auth.type){case"bearer":this.config.auth.token&&(e.Authorization=`Bearer ${this.config.auth.token}`);break;case"basic":if(this.config.auth.username&&this.config.auth.password){let r=Buffer.from(`${this.config.auth.username}:${this.config.auth.password}`).toString("base64");e.Authorization=`Basic ${r}`}break;case"custom":this.config.auth.custom&&(e[this.config.auth.custom.header]=this.config.auth.custom.value);break}return e}buildBody(e,r){let{format:n="json",timestamp:s=!0,prefix:i,metadata:u}=r||{},c={data:e};return s&&(c.timestamp=new Date().toISOString()),i&&(c.prefix=i),u&&Object.keys(u).length>0&&(c.metadata=u),c}async sendRequest(e,r,n,s,i){let u=new AbortController,c=setTimeout(()=>u.abort(),i);try{let l=await fetch(e,{method:r,headers:n,body:JSON.stringify(s),signal:u.signal});if(clearTimeout(c),!l.ok)throw new Error(`HTTP ${l.status}: ${l.statusText}`);return l}catch(l){throw clearTimeout(c),l}}delay(e){return new Promise(r=>setTimeout(r,e))}async sendWithRetry(e,r,n,s,i,u){let c=null;for(let l=1;l<=u.maxAttempts;l++)try{return await this.sendRequest(e,r,n,s,i)}catch(h){if(c=h,l===u.maxAttempts)break;let d=u.backoffMs*Math.pow(2,l-1);console.warn(`[WebhookOutputHandler] Request failed (attempt ${l}/${u.maxAttempts}), retrying in ${d}ms...`,h.message),await this.delay(d)}throw c}async output(e,r={}){let n=r.timeout||this.defaultTimeout;try{let s=this.buildHeaders(),i=this.buildBody(e,r),u=await this.sendWithRetry(this.config.url,this.config.method,s,i,n,this.config.retry);return!0}catch(s){let i=s instanceof Error?s.message:String(s);if(this.config.silent)return console.error(`[WebhookOutputHandler] Failed to send data: ${i}`),!1;throw new Error(`Webhook output failed: ${i}`)}}}});import{writeFileSync as KT,existsSync as YT,mkdirSync as QT}from"fs";import{join as u0}from"path";import{tmpdir as XT}from"os";var ao,Bd=je(()=>{"use strict";ao=class{type="temp-file";config;baseDir;constructor(e={}){this.config={subdirectory:"claude-code-router",extension:"json",includeTimestamp:!1,prefix:"session",...e};let r=XT();this.baseDir=u0(r,this.config.subdirectory),this.ensureDir()}ensureDir(){try{YT(this.baseDir)||QT(this.baseDir,{recursive:!0})}catch{}}extractSessionId(e){try{let r=e.match(/_session_([a-f0-9-]+)/i);return r?r[1]:null}catch{return null}}getFilePath(e){let r=this.config.prefix||"session",n=this.config.extension?`.${this.config.extension}`:"",s;if(this.config.includeTimestamp){let i=Date.now();s=`${r}-${e}-${i}${n}`}else s=`${r}-${e}${n}`;return u0(this.baseDir,s)}async output(e,r={}){try{let n=r.metadata?.sessionId;if(!n)return!1;let s={...e,timestamp:Date.now(),sessionId:n},i=this.getFilePath(n);return KT(i,JSON.stringify(s,null,2),"utf-8"),!0}catch{return!1}}getBaseDir(){return this.baseDir}}});var jd,ds,c0=je(()=>{"use strict";Id();Nd();Bd();jd=class{handlers=new Map;defaultOptions={};registerHandler(e,r){this.handlers.set(e,r)}registerHandlers(e){for(let r of e)if(r.enabled!==!1)try{let n=this.createHandler(r),s=r.type+"_"+Date.now();this.registerHandler(s,n)}catch(n){console.error(`[OutputManager] Failed to register ${r.type} handler:`,n)}}createHandler(e){switch(e.type){case"console":return new oo(e.config);case"webhook":return new io(e.config);case"temp-file":return new ao(e.config);default:throw new Error(`Unknown output handler type: ${e.type}`)}}unregisterHandler(e){return this.handlers.delete(e)}getHandler(e){return this.handlers.get(e)}getAllHandlers(){return new Map(this.handlers)}clearHandlers(){this.handlers.clear()}setDefaultOptions(e){this.defaultOptions={...this.defaultOptions,...e}}getDefaultOptions(){return{...this.defaultOptions}}async output(e,r){let n={...this.defaultOptions,...r},s={success:[],failed:[]},i=Array.from(this.handlers.entries()).map(async([u,c])=>{try{await c.output(e,n)?s.success.push(u):s.failed.push(u)}catch(l){console.error(`[OutputManager] Handler ${u} failed:`,l),s.failed.push(u)}});return await Promise.all(i),s}async outputTo(e,r,n){let s={...this.defaultOptions,...n},i={success:[],failed:[]},u=e.map(async c=>{let l=this.handlers.get(c);if(!l){console.warn(`[OutputManager] Handler ${c} not found`),i.failed.push(c);return}try{await l.output(r,s)?i.success.push(c):i.failed.push(c)}catch(h){console.error(`[OutputManager] Handler ${c} failed:`,h),i.failed.push(c)}});return await Promise.all(u),i}async outputToType(e,r,n){let s=Array.from(this.handlers.entries()).filter(([i,u])=>u.type===e).map(([i])=>i);return this.outputTo(s,r,n)}},ds=new jd});import eD from"fastify";import tD from"@fastify/cors";var rh=Nr(Du(),1);import{readFileSync as cb,existsSync as eh}from"fs";import{join as th}from"path";import{config as lb}from"dotenv";var xn=class{config={};options;constructor(e={jsonPath:"./config.json"}){this.options={envPath:e.envPath||".env",jsonPath:e.jsonPath,useEnvFile:!1,useJsonFile:e.useJsonFile!==!1,useEnvironmentVariables:e.useEnvironmentVariables!==!1,...e},this.loadConfig()}loadConfig(){this.options.useJsonFile&&this.options.jsonPath&&this.loadJsonConfig(),this.options.initialConfig&&(this.config={...this.config,...this.options.initialConfig}),this.options.useEnvFile&&this.loadEnvConfig(),this.config.LOG_FILE&&(process.env.LOG_FILE=this.config.LOG_FILE),this.config.LOG&&(process.env.LOG=this.config.LOG)}loadJsonConfig(){if(!this.options.jsonPath)return;let e=this.isAbsolutePath(this.options.jsonPath)?this.options.jsonPath:th(process.cwd(),this.options.jsonPath);if(eh(e))try{let r=cb(e,"utf-8"),n=rh.default.parse(r);this.config={...this.config,...n},console.log(`Loaded JSON config from: ${e}`)}catch(r){console.warn(`Failed to load JSON config from ${e}:`,r)}else console.warn(`JSON config file not found: ${e}`)}loadEnvConfig(){let e=this.isAbsolutePath(this.options.envPath)?this.options.envPath:th(process.cwd(),this.options.envPath);if(eh(e))try{let r=lb({path:e});r.parsed&&(this.config={...this.config,...this.parseEnvConfig(r.parsed)})}catch(r){console.warn(`Failed to load .env config from ${e}:`,r)}}loadEnvironmentVariables(){let e=this.parseEnvConfig(process.env);this.config={...this.config,...e}}parseEnvConfig(e){let r={};return Object.assign(r,e),r}isAbsolutePath(e){return e.startsWith("/")||e.includes(":")}get(e,r){let n=this.config[e];return n!==void 0?n:r}getAll(){return{...this.config}}getHttpsProxy(){return this.get("HTTPS_PROXY")||this.get("https_proxy")||this.get("httpsProxy")||this.get("PROXY_URL")}has(e){return this.config[e]!==void 0}set(e,r){this.config[e]=r}reload(){this.config={},this.loadConfig()}getConfigSummary(){let e=[];return this.options.initialConfig&&e.push("Initial Config"),this.options.useJsonFile&&this.options.jsonPath&&e.push(`JSON: ${this.options.jsonPath}`),this.options.useEnvFile&&e.push(`ENV: ${this.options.envPath}`),this.options.useEnvironmentVariables&&e.push("Environment Variables"),`Config sources: ${e.join(", ")}`}};function nt(t,e=500,r="internal_error",n="api_error"){let s=new Error(t);return s.statusCode=e,s.code=r,s.type=n,s}async function nh(t,e,r){e.log.error(t);let n=t.statusCode||500,s={error:{message:t.message+t.stack||"Internal Server Error",type:t.type||"api_error",code:t.code||"internal_error"}};return r.code(n).send(s)}import{ProxyAgent as db}from"undici";function sh(t,e,r,n,s){let i=new Headers({"Content-Type":"application/json"});r.headers&&Object.entries(r.headers).forEach(([h,d])=>{d&&i.set(h,d)});let u,c=AbortSignal.timeout(r.TIMEOUT??60*1e3*60);if(r.signal){let h=new AbortController,d=()=>h.abort();r.signal.addEventListener("abort",d),c.addEventListener("abort",d),u=h.signal}else u=c;let l={method:"POST",headers:i,body:JSON.stringify(e),signal:u};return r.httpsProxy&&(l.dispatcher=new db(new URL(r.httpsProxy).toString())),s?.debug({reqId:n.req.id,request:l,headers:Object.fromEntries(i.entries()),requestUrl:typeof t=="string"?t:t.toString(),useProxy:r.httpsProxy},"final request"),fetch(typeof t=="string"?t:t.toString(),l)}var oh="2.0.50";var hb={enabled:!0,failureThreshold:3,probeIntervalMinutes:5,halfOpenSuccessThreshold:2,rateLimitThreshold:1},$o=class{states=new Map;config;probeTimer;constructor(e){this.config={...hb,...e}}getKey(e,r){return`${e},${r}`}recordSuccess(e,r){if(!this.config.enabled)return;let n=this.getKey(e,r),s=this.states.get(n);s&&(s.successCount++,s.status==="half-open"?s.successCount>=this.config.halfOpenSuccessThreshold&&this.states.delete(n):s.status==="open"&&(s.status="half-open",s.successCount=1,s.failureCount=0))}isRateLimitError(e){if(!e)return!1;let r=e.toLowerCase();return r.includes("429")||r.includes("rate_limit")||r.includes("ratelimit")||r.includes("rate limit")||r.includes("overloaded")||r.includes("quota")}recordFailure(e,r,n){if(!this.config.enabled)return;let s=this.getKey(e,r),i=this.states.get(s);i||(i={provider:e,model:r,status:"closed",failureCount:0,successCount:0,lastFailureTime:0,lastProbeTime:0},this.states.set(s,i)),i.failureCount++,i.lastFailureTime=Date.now(),i.lastError=n;let c=this.isRateLimitError(n)?this.config.rateLimitThreshold:this.config.failureThreshold;i.status==="half-open"?(i.status="open",i.successCount=0,i.lastProbeTime=0):i.status==="closed"&&i.failureCount>=c&&(i.status="open",i.lastProbeTime=0)}getState(e,r){return this.states.get(this.getKey(e,r))}isAvailable(e,r){if(!this.config.enabled)return!0;let n=this.getState(e,r);return n?n.status!=="open":!0}getPriority(e,r){if(!this.config.enabled)return 0;let n=this.getState(e,r);if(!n)return 0;switch(n.status){case"closed":return 0;case"half-open":return 1;case"open":return 2}}getHealthyModels(){return[]}getFailPoolModels(){let e=[];for(let[r,n]of this.states)n.status==="open"&&e.push(r);return e}getHalfOpenModels(){let e=[];for(let[r,n]of this.states)n.status==="half-open"&&e.push(r);return e}needsProbe(e){return Date.now()-e.lastProbeTime>=this.config.probeIntervalMinutes*60*1e3}markProbeAttempt(e,r){let n=this.getKey(e,r),s=this.states.get(n);s&&s.status==="open"&&(s.lastProbeTime=Date.now())}clear(){this.states.clear()}getAllStates(){return Array.from(this.states.values())}stopProbeTimer(){this.probeTimer&&(clearInterval(this.probeTimer),this.probeTimer=void 0)}},Ru=null;function Gt(t){return Ru||(Ru=new $o(t)),Ru}var Ou=new Map,pb=["x-ratelimit-remaining","x-ratelimit-remaining-requests","x-ratelimit-remaining-tokens"],mb=["x-ratelimit-limit","x-ratelimit-limit-requests","x-ratelimit-limit-tokens"],gb=["x-ratelimit-reset","x-ratelimit-reset-requests","x-ratelimit-reset-tokens"];function Es(t,e,r){let n=c=>{if(r instanceof Headers)return r.get(c);let l=Object.keys(r).find(h=>h.toLowerCase()===c);return l?r[l]:null},s=xu(n,pb),i=xu(n,mb),u=xu(n,gb);(s||i||u)&&Ou.set(t,{provider:t,remaining:ih(s),limit:ih(i),reset:bb(u),capturedAt:Date.now()})}function yb(t){return Ou.get(t)}function _b(){return Array.from(Ou.values())}function xu(t,e){for(let r of e){let n=t(r);if(n)return n}return null}function ih(t){if(!t)return null;let e=Number(t.trim().replace(/,/g,""));return Number.isFinite(e)?e:null}function bb(t){if(!t)return null;let e=t.trim();if(!e)return null;let r=Number(e);if(Number.isFinite(r))return r>1e12?Math.floor(r/1e3):r>1e9?Math.floor(r):Math.floor(Date.now()/1e3+r);let n=Date.parse(e);if(Number.isFinite(n))return Math.floor(n/1e3);let s=Cb(e);return s===null?null:Math.floor((Date.now()+s)/1e3)}function Cb(t){let e=/(\d+(?:\.\d+)?)(ms|s|m|h|d)/gi,r=0,n=!1;for(let s of t.matchAll(e)){n=!0;let i=Number(s[1]),u=s[2].toLowerCase();if(Number.isFinite(i))switch(u){case"ms":r+=i;break;case"s":r+=i*1e3;break;case"m":r+=i*60*1e3;break;case"h":r+=i*60*60*1e3;break;case"d":r+=i*24*60*60*1e3;break}}return n?r:null}async function wb(t,e,r,n){let s=t.body,i=t.provider,u=r.providerService.getProvider(i);if(!u)throw nt(`Provider '${i}' not found`,404,"provider_not_found");try{let{requestBody:c,config:l,bypass:h}=await ah(s,u,n,t.headers,{req:t}),d=await uh(c,l,u,r,h,n,{req:t});try{u?.baseUrl&&d?.headers&&Es(i,u.baseUrl,d.headers)}catch{}let p=await ch(c,d,u,n,h,{req:t});return lh(p,e,s)}catch(c){let l=await Eb(t,e,r,n,c);if(l)return l;throw c}}async function Eb(t,e,r,n,s){let i=t.scenarioType||"default",u=t.familyFallback,c=r.configService.get("fallback"),l=Gt(),h=[];if(u?.[i]?h=u[i]:c?.[i]&&(h=c[i]),!Array.isArray(h)||h.length===0)return null;let d=t.provider||"",p=t.body.model||"";l.recordFailure(d,p,s?.message),t.log.warn(`Request failed for ${t.scenarioType}, trying ${h.length} fallback models`);let w=h.sort((T,S)=>{let[y,g]=T.split(","),[m,v]=S.split(",");return l.getPriority(y,g)-l.getPriority(m,v)});for(let T of w)try{let[S,...y]=T.split(","),g=y.join(",");if(!l.isAvailable(S,g)){t.log.warn(`Fallback model ${T} unavailable (fail pool), skipping`);continue}t.log.info(`Trying fallback model: ${T}`);let m={...t.body};m.model=g;let v={...t,provider:S,body:m},b=r.providerService.getProvider(S);if(!b){t.log.warn(`Fallback provider '${S}' not found, skipping`);continue}let{requestBody:A,config:R,bypass:F}=await ah(m,b,n,t.headers,{req:v}),$=await uh(A,R,b,r,F,n,{req:v});try{b?.baseUrl&&$?.headers&&Es(S,b.baseUrl,$.headers)}catch{}let J=await ch(A,$,b,n,F,{req:v});return t.log.info(`Fallback model ${T} succeeded`),l.recordSuccess(S,g),lh(J,e,m)}catch(S){let[y,...g]=T.split(","),m=g.join(",");l.recordFailure(y,m,S.message),t.log.warn(`Fallback model ${T} failed: ${S.message}`);continue}return t.log.error(`All fallback models failed for ${i}`),null}async function ah(t,e,r,n,s){let i=JSON.parse(JSON.stringify(t)),u={},c=!1;if(c=Ab(e,r,t),c&&(n instanceof Headers?n.delete("content-length"):delete n["content-length"],u.headers=n),!c&&typeof r.transformRequestOut=="function"){let l=await r.transformRequestOut(i);l.body?(i=l.body,u=l.config||{}):i=l}if(!c&&e.transformer?.use?.length)for(let l of e.transformer.use){if(!l||typeof l.transformRequestIn!="function")continue;let h=await l.transformRequestIn(i,e,s);h.body?(i=h.body,u={...u,...h.config}):i=h}if(!c&&e.transformer?.[t.model]?.use?.length)for(let l of e.transformer[t.model].use)!l||typeof l.transformRequestIn!="function"||(i=await l.transformRequestIn(i,e,s));return{requestBody:i,config:u,bypass:c}}function Ab(t,e,r){return t.transformer?.use?.length===1&&t.transformer.use[0].name===e.name&&(!t.transformer?.[r.model]?.use.length||t.transformer?.[r.model]?.use.length===1&&t.transformer?.[r.model]?.use[0].name===e.name)}async function uh(t,e,r,n,s,i,u){let c=e.url||new URL(r.baseUrl);if(!e.TIMEOUT){let d=n.configService.get("API_TIMEOUT_MS");d&&(e.TIMEOUT=typeof d=="string"?parseInt(d,10):d)}if(s&&typeof i.auth=="function"){let d=await i.auth(t,r);if(d.body){t=d.body;let p=e.headers||{};d.config?.headers&&(p={...p,...d.config.headers},delete p.host,delete d.config.headers),e={...e,...d.config,headers:p}}else t=d}let l={Authorization:`Bearer ${r.apiKey}`,...e?.headers||{}};for(let d in l)(l[d]==="undefined"||["authorization","Authorization"].includes(d)&&l[d]?.includes("undefined"))&&delete l[d];let h=await sh(c,t,{httpsProxy:n.configService.getHttpsProxy(),...e,headers:JSON.parse(JSON.stringify(l))},u,n.log);if(!h.ok){let d=await h.text();throw n.log.error(`[provider_response_error] Error from provider(${r.name},${t.model}: ${h.status}): ${d}`),nt(`Error from provider(${r.name},${t.model}: ${h.status}): ${d}`,h.status,"provider_response_error")}return h}async function ch(t,e,r,n,s,i){let u=e;if(!s&&r.transformer?.use?.length)for(let c of Array.from(r.transformer.use).reverse())!c||typeof c.transformResponseOut!="function"||(u=await c.transformResponseOut(u,i));if(!s&&r.transformer?.[t.model]?.use?.length)for(let c of Array.from(r.transformer[t.model].use).reverse())!c||typeof c.transformResponseOut!="function"||(u=await c.transformResponseOut(u,i));return!s&&n.transformResponseIn&&(u=await n.transformResponseIn(u,i)),u}function lh(t,e,r){return t.ok||e.code(t.status),r.stream===!0?(e.header("Content-Type","text/event-stream"),e.header("Cache-Control","no-cache"),e.header("Connection","keep-alive"),e.send(t.body)):t.json()}var Fu=async t=>{t.get("/",async()=>({message:"LLMs API",version:oh})),t.get("/health",async()=>({status:"ok",timestamp:new Date().toISOString()})),t.get("/providers/health",async()=>({states:Gt().getAllStates().map(s=>({provider:s.provider,model:s.model,status:s.status,failureCount:s.failureCount,successCount:s.successCount,lastFailureTime:s.lastFailureTime,lastError:s.lastError})),timestamp:new Date().toISOString()}));let e=t.transformerService.getTransformersWithEndpoint();for(let{transformer:r}of e)r.endPoint&&t.post(r.endPoint,async(n,s)=>wb(n,s,t,r));t.post("/providers",{schema:{body:{type:"object",properties:{id:{type:"string"},name:{type:"string"},type:{type:"string",enum:["openai","anthropic"]},baseUrl:{type:"string"},apiKey:{type:"string"},models:{type:"array",items:{type:"string"}}},required:["id","name","type","baseUrl","apiKey","models"]}}},async(r,n)=>{let{name:s,baseUrl:i,apiKey:u,models:c}=r.body;if(!s?.trim())throw nt("Provider name is required",400,"invalid_request");if(!i||!Sb(i))throw nt("Valid base URL is required",400,"invalid_request");if(!u?.trim())throw nt("API key is required",400,"invalid_request");if(!c||!Array.isArray(c)||c.length===0)throw nt("At least one model is required",400,"invalid_request");if(t.providerService.getProvider(r.body.name))throw nt(`Provider with name '${r.body.name}' already exists`,400,"provider_exists");return t.providerService.registerProvider(r.body)}),t.get("/providers",async()=>t.providerService.getProviders()),t.get("/providers/:id",{schema:{params:{type:"object",properties:{id:{type:"string"}},required:["id"]}}},async r=>{let n=t.providerService.getProvider(r.params.id);if(!n)throw nt("Provider not found",404,"provider_not_found");return n}),t.put("/providers/:id",{schema:{params:{type:"object",properties:{id:{type:"string"}},required:["id"]},body:{type:"object",properties:{name:{type:"string"},type:{type:"string",enum:["openai","anthropic"]},baseUrl:{type:"string"},apiKey:{type:"string"},models:{type:"array",items:{type:"string"}},enabled:{type:"boolean"}}}}},async(r,n)=>{let s=t.providerService.updateProvider(r.params.id,r.body);if(!s)throw nt("Provider not found",404,"provider_not_found");return s}),t.delete("/providers/:id",{schema:{params:{type:"object",properties:{id:{type:"string"}},required:["id"]}}},async r=>{if(!t.providerService.deleteProvider(r.params.id))throw nt("Provider not found",404,"provider_not_found");return{message:"Provider deleted successfully"}}),t.patch("/providers/:id/toggle",{schema:{params:{type:"object",properties:{id:{type:"string"}},required:["id"]},body:{type:"object",properties:{enabled:{type:"boolean"}},required:["enabled"]}}},async(r,n)=>{if(!t.providerService.toggleProvider(r.params.id,r.body.enabled))throw nt("Provider not found",404,"provider_not_found");return{message:`Provider ${r.body.enabled?"enabled":"disabled"} successfully`}})};function Sb(t){try{return new URL(t),!0}catch{return!1}}var On=class{constructor(e,r,n){this.configService=e;this.transformerService=r;this.logger=n;this.initializeCustomProviders()}providers=new Map;modelRoutes=new Map;initializeCustomProviders(){let e=this.configService.get("providers");if(e&&Array.isArray(e)){this.initializeFromProvidersArray(e);return}}initializeFromProvidersArray(e){e.forEach(r=>{try{if(!r.name||!r.api_base_url||!r.api_key)return;let n={};r.transformer&&Object.keys(r.transformer).forEach(s=>{s==="use"?Array.isArray(r.transformer.use)&&(n.use=r.transformer.use.map(i=>{if(Array.isArray(i)&&typeof i[0]=="string"){let u=this.transformerService.getTransformer(i[0]);if(u)return new u(i[1])}if(typeof i=="string"){let u=this.transformerService.getTransformer(i);return typeof u=="function"?new u:u}}).filter(i=>typeof i<"u")):Array.isArray(r.transformer[s]?.use)&&(n[s]={use:r.transformer[s].use.map(i=>{if(Array.isArray(i)&&typeof i[0]=="string"){let u=this.transformerService.getTransformer(i[0]);if(u)return new u(i[1])}if(typeof i=="string"){let u=this.transformerService.getTransformer(i);return typeof u=="function"?new u:u}}).filter(i=>typeof i<"u")})}),this.registerProvider({name:r.name,baseUrl:r.api_base_url,apiKey:r.api_key,models:r.models||[],transformer:r.transformer?n:void 0}),this.logger.info(`${r.name} provider registered`)}catch(n){this.logger.error(`${r.name} provider registered error: ${n}`)}})}registerProvider(e){let r={...e};return this.providers.set(r.name,r),e.models.forEach(n=>{let s=`${r.name},${n}`,i={provider:r.name,model:n,fullModel:s};this.modelRoutes.set(s,i),this.modelRoutes.has(n)||this.modelRoutes.set(n,i)}),r}getProviders(){return Array.from(this.providers.values())}getProvider(e){return this.providers.get(e)}updateProvider(e,r){let n=this.providers.get(e);if(!n)return null;let s={...n,...r,updatedAt:new Date};return this.providers.set(e,s),r.models&&(n.models.forEach(i=>{let u=`${n.name},${i}`;this.modelRoutes.delete(u),this.modelRoutes.delete(i)}),r.models.forEach(i=>{let u=`${n.name},${i}`,c={provider:n.name,model:i,fullModel:u};this.modelRoutes.set(u,c),this.modelRoutes.has(i)||this.modelRoutes.set(i,c)})),s}deleteProvider(e){let r=this.providers.get(e);return r?(r.models.forEach(n=>{let s=`${r.name},${n}`;this.modelRoutes.delete(s),this.modelRoutes.delete(n)}),this.providers.delete(e),!0):!1}toggleProvider(e,r){return!!this.providers.get(e)}resolveModelRoute(e){let r=this.modelRoutes.get(e);if(!r)return null;let n=this.providers.get(r.provider);return n?{provider:n,originalModel:e,targetModel:r.model}:null}getAvailableModelNames(){let e=[];return this.providers.forEach(r=>{r.models.forEach(n=>{e.push(n),e.push(`${r.name},${n}`)})}),e}getModelRoutes(){return Array.from(this.modelRoutes.values())}parseTransformerConfig(e){return e?Array.isArray(e)?e.reduce((r,n)=>{if(Array.isArray(n)){let[s,i={}]=n;r[s]=i}else r[n]={};return r},{}):e:{}}async getAvailableModels(){let e=[];return this.providers.forEach(r=>{r.models.forEach(n=>{e.push({id:n,object:"model",owned_by:r.name,provider:r.name}),e.push({id:`${r.name},${n}`,object:"model",owned_by:r.name,provider:r.name})})}),{object:"list",data:e}}};var Je=[];for(let t=0;t<256;++t)Je.push((t+256).toString(16).slice(1));function dh(t,e=0){return(Je[t[e+0]]+Je[t[e+1]]+Je[t[e+2]]+Je[t[e+3]]+"-"+Je[t[e+4]]+Je[t[e+5]]+"-"+Je[t[e+6]]+Je[t[e+7]]+"-"+Je[t[e+8]]+Je[t[e+9]]+"-"+Je[t[e+10]]+Je[t[e+11]]+Je[t[e+12]]+Je[t[e+13]]+Je[t[e+14]]+Je[t[e+15]]).toLowerCase()}import{randomFillSync as vb}from"crypto";var Ho=new Uint8Array(256),zo=Ho.length;function Pu(){return zo>Ho.length-16&&(vb(Ho),zo=0),Ho.slice(zo,zo+=16)}import{randomUUID as kb}from"crypto";var Iu={randomUUID:kb};function Tb(t,e,r){if(Iu.randomUUID&&!e&&!t)return Iu.randomUUID();t=t||{};let n=t.random??t.rng?.()??Pu();if(n.length<16)throw new Error("Random bytes length must be >= 16");if(n[6]=n[6]&15|64,n[8]=n[8]&63|128,e){if(r=r||0,r<0||r+16>e.length)throw new RangeError(`UUID byte range ${r}:${r+15} is out of buffer bounds`);for(let s=0;s<16;++s)e[r+s]=n[s];return e}return dh(n)}var Jt=Tb;var fh=t=>t<=0?"none":t<=1024?"low":t<=8192?"medium":"high";var hh=(t,e)=>(t.includes("base64")&&(t=t.split("base64").pop(),t.startsWith(",")&&(t=t.slice(1))),`data:${e};base64,${t}`);var Wo=class{constructor(e){this.options=e;this.useBearer=this.options?.UseBearer??!1}name="Anthropic";endPoint="/v1/messages";useBearer;logger;async auth(e,r){let n={};return this.useBearer?(n.authorization=`Bearer ${r.apiKey}`,n["x-api-key"]=void 0):(n["x-api-key"]=r.apiKey,n.authorization=void 0),{body:e,config:{headers:n}}}async transformRequestOut(e){let r=[];if(e.system){if(typeof e.system=="string")r.push({role:"system",content:e.system});else if(Array.isArray(e.system)&&e.system.length){let i=e.system.filter(u=>u.type==="text"&&u.text).map(u=>({type:"text",text:u.text,cache_control:u.cache_control}));r.push({role:"system",content:i})}}JSON.parse(JSON.stringify(e.messages||[]))?.forEach(i=>{if(i.role==="user"||i.role==="assistant"){if(typeof i.content=="string"){r.push({role:i.role,content:i.content});return}if(Array.isArray(i.content)){if(i.role==="user"){let u=i.content.filter(l=>l.type==="tool_result"&&l.tool_use_id);u.length&&u.forEach(l=>{let h={role:"tool",content:typeof l.content=="string"?l.content:JSON.stringify(l.content),tool_call_id:l.tool_use_id,cache_control:l.cache_control};r.push(h)});let c=i.content.filter(l=>l.type==="text"&&l.text||l.type==="image"&&l.source);c.length&&r.push({role:"user",content:c.map(l=>l?.type==="image"?{type:"image_url",image_url:{url:l.source?.type==="base64"?hh(l.source.data,l.source.media_type):l.source.url},media_type:l.source.media_type}:l)})}else if(i.role==="assistant"){let u={role:"assistant",content:""},c=i.content.filter(d=>d.type==="text"&&d.text);c.length&&(u.content=c.map(d=>d.text).join(`
|
|
73
|
+
`));let l=i.content.filter(d=>d.type==="tool_use"&&d.id);l.length&&(u.tool_calls=l.map(d=>({id:d.id,type:"function",function:{name:d.name,arguments:JSON.stringify(d.input||{})}})));let h=i.content.find(d=>d.type==="thinking"&&d.signature);h&&(u.thinking={content:h.thinking,signature:h.signature}),r.push(u)}return}}});let s={messages:r,model:e.model,max_tokens:e.max_tokens,temperature:e.temperature,stream:e.stream,tools:e.tools?.length?this.convertAnthropicToolsToUnified(e.tools):void 0,tool_choice:e.tool_choice};return e.thinking&&(s.reasoning={effort:fh(e.thinking.budget_tokens),enabled:e.thinking.type==="enabled"}),e.tool_choice&&(e.tool_choice.type==="tool"?s.tool_choice={type:"function",function:{name:e.tool_choice.name}}:s.tool_choice=e.tool_choice.type),s}async transformResponseIn(e,r){if(e.headers.get("Content-Type")?.includes("text/event-stream")){if(!e.body)throw new Error("Stream response body is null");let s=await this.convertOpenAIStreamToAnthropic(e.body,r);return new Response(s,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}else{let s=await e.json(),i=this.convertOpenAIResponseToAnthropic(s,r);return new Response(JSON.stringify(i),{headers:{"Content-Type":"application/json"}})}}convertAnthropicToolsToUnified(e){return e.map(r=>({type:"function",function:{name:r.name,description:r.description||"",parameters:r.input_schema}}))}async convertOpenAIStreamToAnthropic(e,r){return new ReadableStream({start:async s=>{let i=new TextEncoder,u=`msg_${Date.now()}`,c=null,l="unknown",h=!1,d=!1,p=!1,w=new Map,T=new Map,S=0,y=0,g=0,m=!1,v=!1,b=0,A=-1,R=()=>{let M=b;return b++,M},F=M=>{if(!m)try{s.enqueue(M);let Q=new TextDecoder().decode(M);this.logger.debug({reqId:r.req.id,data:Q,type:"send data"})}catch(Q){if(Q instanceof TypeError&&Q.message.includes("Controller is already closed"))m=!0;else throw this.logger.debug({reqId:r.req.id,error:Q instanceof Error?Q.message:String(Q),type:"send data error"}),Q}},$=()=>{if(!m)try{if(A>=0){let Q={type:"content_block_stop",index:A};F(i.encode(`event: content_block_stop
|
|
74
|
+
data: ${JSON.stringify(Q)}
|
|
75
75
|
|
|
76
|
-
`)),
|
|
76
|
+
`)),A=-1}c?(F(i.encode(`event: message_delta
|
|
77
77
|
data: ${JSON.stringify(c)}
|
|
78
78
|
|
|
79
79
|
`)),c=null):F(i.encode(`event: message_delta
|
|
@@ -82,166 +82,166 @@ data: ${JSON.stringify({type:"message_delta",delta:{stop_reason:"end_turn",stop_
|
|
|
82
82
|
`));let M={type:"message_stop"};F(i.encode(`event: message_stop
|
|
83
83
|
data: ${JSON.stringify(M)}
|
|
84
84
|
|
|
85
|
-
`)),s.close(),m=!0}catch(M){if(M instanceof TypeError&&M.message.includes("Controller is already closed"))m=!0;else throw M}},J=null;try{J=e.getReader();let M=new TextDecoder,
|
|
86
|
-
`);
|
|
85
|
+
`)),s.close(),m=!0}catch(M){if(M instanceof TypeError&&M.message.includes("Controller is already closed"))m=!0;else throw M}},J=null;try{J=e.getReader();let M=new TextDecoder,Q="";for(;!m;){let{done:ue,value:re}=await J.read();if(ue)break;Q+=M.decode(re,{stream:!0});let de=Q.split(`
|
|
86
|
+
`);Q=de.pop()||"";for(let pe of de){if(m||p)break;if(!pe.startsWith("data:"))continue;let Ae=pe.slice(5).trim();if(this.logger.debug({reqId:r.req.id,type:"recieved data",data:Ae}),Ae!=="[DONE]")try{let oe=JSON.parse(Ae);if(S++,this.logger.debug({reqId:r.req.id,response:oe,tppe:"Original Response"}),oe.error){let G={type:"error",message:{type:"api_error",message:JSON.stringify(oe.error)}};F(i.encode(`event: error
|
|
87
87
|
data: ${JSON.stringify(G)}
|
|
88
88
|
|
|
89
89
|
`));continue}if(l=oe.model||l,!h&&!m&&!p){h=!0;let G={type:"message_start",message:{id:u,type:"message",role:"assistant",content:[],model:l,stop_reason:null,stop_sequence:null,usage:{input_tokens:0,output_tokens:0}}};F(i.encode(`event: message_start
|
|
90
90
|
data: ${JSON.stringify(G)}
|
|
91
91
|
|
|
92
|
-
`))}let me=oe.choices?.[0];if(oe.usage&&(c?c.usage={input_tokens:(oe.usage?.prompt_tokens||0)-(oe.usage?.prompt_tokens_details?.cached_tokens||0),output_tokens:oe.usage?.completion_tokens||0,cache_read_input_tokens:oe.usage?.prompt_tokens_details?.cached_tokens||0}:c={type:"message_delta",delta:{stop_reason:"end_turn",stop_sequence:null},usage:{input_tokens:(oe.usage?.prompt_tokens||0)-(oe.usage?.prompt_tokens_details?.cached_tokens||0),output_tokens:oe.usage?.completion_tokens||0,cache_read_input_tokens:oe.usage?.prompt_tokens_details?.cached_tokens||0}}),!me)continue;if(me?.delta?.thinking&&!m&&!p){if(!
|
|
92
|
+
`))}let me=oe.choices?.[0];if(oe.usage&&(c?c.usage={input_tokens:(oe.usage?.prompt_tokens||0)-(oe.usage?.prompt_tokens_details?.cached_tokens||0),output_tokens:oe.usage?.completion_tokens||0,cache_read_input_tokens:oe.usage?.prompt_tokens_details?.cached_tokens||0}:c={type:"message_delta",delta:{stop_reason:"end_turn",stop_sequence:null},usage:{input_tokens:(oe.usage?.prompt_tokens||0)-(oe.usage?.prompt_tokens_details?.cached_tokens||0),output_tokens:oe.usage?.completion_tokens||0,cache_read_input_tokens:oe.usage?.prompt_tokens_details?.cached_tokens||0}}),!me)continue;if(me?.delta?.thinking&&!m&&!p){if(!v){let G=R(),K={type:"content_block_start",index:G,content_block:{type:"thinking",thinking:""}};F(i.encode(`event: content_block_start
|
|
93
93
|
data: ${JSON.stringify(K)}
|
|
94
94
|
|
|
95
|
-
`)),
|
|
95
|
+
`)),A=G,v=!0}if(me.delta.thinking.signature){let G={type:"content_block_delta",index:A,delta:{type:"signature_delta",signature:me.delta.thinking.signature}};F(i.encode(`event: content_block_delta
|
|
96
96
|
data: ${JSON.stringify(G)}
|
|
97
97
|
|
|
98
|
-
`));let K={type:"content_block_stop",index:
|
|
98
|
+
`));let K={type:"content_block_stop",index:A};F(i.encode(`event: content_block_stop
|
|
99
99
|
data: ${JSON.stringify(K)}
|
|
100
100
|
|
|
101
|
-
`)),
|
|
101
|
+
`)),A=-1}else if(me.delta.thinking.content){let G={type:"content_block_delta",index:A,delta:{type:"thinking_delta",thinking:me.delta.thinking.content||""}};F(i.encode(`event: content_block_delta
|
|
102
102
|
data: ${JSON.stringify(G)}
|
|
103
103
|
|
|
104
|
-
`))}}if(me?.delta?.content&&!m&&!p){if(y++,
|
|
104
|
+
`))}}if(me?.delta?.content&&!m&&!p){if(y++,A>=0&&!d){let K={type:"content_block_stop",index:A};F(i.encode(`event: content_block_stop
|
|
105
105
|
data: ${JSON.stringify(K)}
|
|
106
106
|
|
|
107
|
-
`)),
|
|
107
|
+
`)),A=-1}if(!d&&!p){d=!0;let G=R(),K={type:"content_block_start",index:G,content_block:{type:"text",text:""}};F(i.encode(`event: content_block_start
|
|
108
108
|
data: ${JSON.stringify(K)}
|
|
109
109
|
|
|
110
|
-
`)),
|
|
110
|
+
`)),A=G}if(!m&&!p){let G={type:"content_block_delta",index:A,delta:{type:"text_delta",text:me.delta.content}};F(i.encode(`event: content_block_delta
|
|
111
111
|
data: ${JSON.stringify(G)}
|
|
112
112
|
|
|
113
|
-
`))}}if(me?.delta?.annotations?.length&&!m&&!p){if(
|
|
113
|
+
`))}}if(me?.delta?.annotations?.length&&!m&&!p){if(A>=0&&d){let G={type:"content_block_stop",index:A};F(i.encode(`event: content_block_stop
|
|
114
114
|
data: ${JSON.stringify(G)}
|
|
115
115
|
|
|
116
|
-
`)),
|
|
116
|
+
`)),A=-1,d=!1}me?.delta?.annotations.forEach(G=>{let K=R(),ae={type:"content_block_start",index:K,content_block:{type:"web_search_tool_result",tool_use_id:`srvtoolu_${Jt()}`,content:[{type:"web_search_result",title:G.url_citation.title,url:G.url_citation.url}]}};F(i.encode(`event: content_block_start
|
|
117
117
|
data: ${JSON.stringify(ae)}
|
|
118
118
|
|
|
119
119
|
`));let qe={type:"content_block_stop",index:K};F(i.encode(`event: content_block_stop
|
|
120
120
|
data: ${JSON.stringify(qe)}
|
|
121
121
|
|
|
122
|
-
`)),
|
|
122
|
+
`)),A=-1})}if(me?.delta?.tool_calls&&!m&&!p){g++;let G=new Set;for(let K of me.delta.tool_calls){if(m)break;let ae=K.index??0;if(G.has(ae))continue;if(G.add(ae),!T.has(ae)){if(A>=0){let Re={type:"content_block_stop",index:A};F(i.encode(`event: content_block_stop
|
|
123
123
|
data: ${JSON.stringify(Re)}
|
|
124
124
|
|
|
125
|
-
`)),
|
|
125
|
+
`)),A=-1}let Te=R();T.set(ae,Te);let W=K.id||`call_${Date.now()}_${ae}`,le=K.function?.name||`tool_${ae}`,_e={type:"content_block_start",index:Te,content_block:{type:"tool_use",id:W,name:le,input:{}}};F(i.encode(`event: content_block_start
|
|
126
126
|
data: ${JSON.stringify(_e)}
|
|
127
127
|
|
|
128
|
-
`)),
|
|
128
|
+
`)),A=Te;let Ot={id:W,name:le,arguments:"",contentBlockIndex:Te};w.set(ae,Ot)}else if(K.id&&K.function?.name){let Te=w.get(ae);Te.id.startsWith("call_")&&Te.name.startsWith("tool_")&&(Te.id=K.id,Te.name=K.function.name)}if(K.function?.arguments&&!m&&!p){let Te=T.get(ae);if(Te===void 0)continue;let W=w.get(ae);W&&(W.arguments+=K.function.arguments);try{let le={type:"content_block_delta",index:Te,delta:{type:"input_json_delta",partial_json:K.function.arguments}};F(i.encode(`event: content_block_delta
|
|
129
129
|
data: ${JSON.stringify(le)}
|
|
130
130
|
|
|
131
|
-
`))}catch{try{let le=K.function.arguments.replace(/[\x00-\x1F\x7F-\x9F]/g,"").replace(/\\/g,"\\\\").replace(/"/g,'\\"'),_e={type:"content_block_delta",index:
|
|
131
|
+
`))}catch{try{let le=K.function.arguments.replace(/[\x00-\x1F\x7F-\x9F]/g,"").replace(/\\/g,"\\\\").replace(/"/g,'\\"'),_e={type:"content_block_delta",index:Te,delta:{type:"input_json_delta",partial_json:le}};F(i.encode(`event: content_block_delta
|
|
132
132
|
data: ${JSON.stringify(_e)}
|
|
133
133
|
|
|
134
|
-
`))}catch(le){console.error(le)}}}}}if(me?.finish_reason&&!m&&!p){if(y===0&&g===0&&console.error("Warning: No content in the stream response!"),
|
|
134
|
+
`))}catch(le){console.error(le)}}}}}if(me?.finish_reason&&!m&&!p){if(y===0&&g===0&&console.error("Warning: No content in the stream response!"),A>=0){let G={type:"content_block_stop",index:A};F(i.encode(`event: content_block_stop
|
|
135
135
|
data: ${JSON.stringify(G)}
|
|
136
136
|
|
|
137
|
-
`)),
|
|
138
|
-
`)||"",d={id:n.responseId,choices:[{finish_reason:n.candidates[0].finishReason?.toLowerCase()||null,index:0,message:{content:h,role:"assistant",tool_calls:l.length>0?l:void 0,...i&&{thinking:{content:s||"(no content)",signature:i}}}}],created:parseInt(new Date().getTime()/1e3+"",10),model:n.modelVersion,object:"chat.completion",usage:{completion_tokens:n.usageMetadata?.candidatesTokenCount||0,prompt_tokens:n.usageMetadata?.promptTokenCount||0,prompt_tokens_details:{cached_tokens:n.usageMetadata?.cachedContentTokenCount||0},total_tokens:n.usageMetadata?.totalTokenCount||0,output_tokens_details:{reasoning_tokens:n.usageMetadata?.thoughtsTokenCount||0}}};return new Response(JSON.stringify(d),{status:t.status,statusText:t.statusText,headers:t.headers})}else if(t.headers.get("Content-Type")?.includes("stream")){if(!t.body)return t;let n=new TextDecoder,s=new TextEncoder,i=!1,u=!1,c=!1,l="",h=0,d=-1,p=new ReadableStream({async start(
|
|
137
|
+
`)),A=-1}m||(c={type:"message_delta",delta:{stop_reason:{stop:"end_turn",length:"max_tokens",tool_calls:"tool_use",content_filter:"stop_sequence"}[me.finish_reason]||"end_turn",stop_sequence:null},usage:{input_tokens:(oe.usage?.prompt_tokens||0)-(oe.usage?.prompt_tokens_details?.cached_tokens||0),output_tokens:oe.usage?.completion_tokens||0,cache_read_input_tokens:oe.usage?.prompt_tokens_details?.cached_tokens||0}});break}}catch(oe){this.logger?.error(`parseError: ${oe.name} message: ${oe.message} stack: ${oe.stack} data: ${Ae}`)}}}$()}catch(M){if(!m)try{s.error(M)}catch(Q){console.error(Q)}}finally{if(J)try{J.releaseLock()}catch(M){console.error(M)}}},cancel:s=>{this.logger.debug({reqId:r.req.id},`cancle stream: ${s}`)}})}convertOpenAIResponseToAnthropic(e,r){this.logger.debug({reqId:r.req.id,response:e},"Original OpenAI response");try{let n=e.choices[0];if(!n)throw new Error("No choices found in OpenAI response");let s=[];if(n.message.annotations){let u=`srvtoolu_${Jt()}`;s.push({type:"server_tool_use",id:u,name:"web_search",input:{query:""}}),s.push({type:"web_search_tool_result",tool_use_id:u,content:n.message.annotations.map(c=>({type:"web_search_result",url:c.url_citation.url,title:c.url_citation.title}))})}n.message.content&&s.push({type:"text",text:n.message.content}),n.message.tool_calls&&n.message.tool_calls.length>0&&n.message.tool_calls.forEach(u=>{let c={};try{let l=u.function.arguments||"{}";typeof l=="object"?c=l:typeof l=="string"&&(c=JSON.parse(l))}catch{c={text:u.function.arguments||""}}s.push({type:"tool_use",id:u.id,name:u.function.name,input:c})}),n.message?.thinking?.content&&s.push({type:"thinking",thinking:n.message.thinking.content,signature:n.message.thinking.signature});let i={id:e.id,type:"message",role:"assistant",model:e.model,content:s,stop_reason:n.finish_reason==="stop"?"end_turn":n.finish_reason==="length"?"max_tokens":n.finish_reason==="tool_calls"?"tool_use":n.finish_reason==="content_filter"?"stop_sequence":"end_turn",stop_sequence:null,usage:{input_tokens:(e.usage?.prompt_tokens||0)-(e.usage?.prompt_tokens_details?.cached_tokens||0),output_tokens:e.usage?.completion_tokens||0,cache_read_input_tokens:e.usage?.prompt_tokens_details?.cached_tokens||0}};return this.logger.debug({reqId:r.req.id,result:i},"Conversion complete, final Anthropic response"),i}catch{throw nt(`Provider error: ${JSON.stringify(e)}`,500,"provider_error")}}};var Fn={TYPE_UNSPECIFIED:"TYPE_UNSPECIFIED",STRING:"STRING",NUMBER:"NUMBER",INTEGER:"INTEGER",BOOLEAN:"BOOLEAN",ARRAY:"ARRAY",OBJECT:"OBJECT",NULL:"NULL"};function Db(t,e){t.includes("null")&&(e.nullable=!0);let r=t.filter(n=>n!=="null");if(r.length===1){let n=r[0].toUpperCase();e.type=Object.values(Fn).includes(n)?n:Fn.TYPE_UNSPECIFIED}else{e.anyOf=[];for(let n of r){let s=n.toUpperCase();e.anyOf.push({type:Object.values(Fn).includes(s)?s:Fn.TYPE_UNSPECIFIED})}}}function As(t){let e={},r=["items"],n=["anyOf"],s=["properties"];if(t.type&&t.anyOf)throw new Error("type and anyOf cannot be both populated.");let i=t.anyOf;i!=null&&Array.isArray(i)&&i.length==2&&(i[0]&&i[0].type==="null"?(e.nullable=!0,t=i[1]):i[1]&&i[1].type==="null"&&(e.nullable=!0,t=i[0])),t.type&&Array.isArray(t.type)&&Db(t.type,e);for(let[u,c]of Object.entries(t))if(c!=null)if(u=="type"){if(c==="null")throw new Error("type: null can not be the only possible type for the field.");if(Array.isArray(c))continue;let l=c.toUpperCase();e.type=Object.values(Fn).includes(l)?l:Fn.TYPE_UNSPECIFIED}else if(r.includes(u))e[u]=As(c);else if(n.includes(u)){let l=[];for(let h of c){if(h.type=="null"){e.nullable=!0;continue}l.push(As(h))}e[u]=l}else if(s.includes(u)){let l={};for(let[h,d]of Object.entries(c))l[h]=As(d);e[u]=l}else{if(u==="additionalProperties")continue;e[u]=c}return e}function Rb(t){if(t.functionDeclarations)for(let e of t.functionDeclarations)e.parameters&&(Object.keys(e.parameters).includes("$schema")?e.parametersJsonSchema||(e.parametersJsonSchema=e.parameters,delete e.parameters):e.parameters=As(e.parameters)),e.response&&(Object.keys(e.response).includes("$schema")?e.responseJsonSchema||(e.responseJsonSchema=e.response,delete e.response):e.response=As(e.response));return t}function Go(t){let e=[],r=t.tools?.filter(l=>l.function.name!=="web_search")?.map(l=>({name:l.function.name,description:l.function.description,parametersJsonSchema:l.function.parameters}));r?.length&&e.push(Rb({functionDeclarations:r})),t.tools?.find(l=>l.function.name==="web_search")&&e.push({googleSearch:{}});let s=[],i=t.messages.filter(l=>l.role==="tool");t.messages.filter(l=>l.role!=="tool").forEach(l=>{let h;l.role==="assistant"?h="model":(["user","system"].includes(l.role),h="user");let d=[];if(typeof l.content=="string"){let p={text:l.content};l?.thinking?.signature&&(p.thoughtSignature=l.thinking.signature),d.push(p)}else Array.isArray(l.content)?d.push(...l.content.map(p=>{if(p.type==="text")return{text:p.text||""};if(p.type==="image_url")return p.image_url.url.startsWith("http")?{file_data:{mime_type:p.media_type,file_uri:p.image_url.url}}:{inlineData:{mime_type:p.media_type,data:p.image_url.url?.split(",")?.pop()||p.image_url.url}}})):l.content&&typeof l.content=="object"&&(l.content.text?d.push({text:l.content.text}):d.push({text:JSON.stringify(l.content)}));if(Array.isArray(l.tool_calls)&&d.push(...l.tool_calls.map((p,w)=>({functionCall:{id:p.id||`tool_${Math.random().toString(36).substring(2,15)}`,name:p.function.name,args:JSON.parse(p.function.arguments||"{}")},thoughtSignature:w===0&&l.thinking?.signature?l.thinking?.signature:void 0}))),d.length===0&&d.push({text:""}),s.push({role:h,parts:d}),h==="model"&&l.tool_calls){let p=l.tool_calls.map(w=>{let T=i.find(S=>S.tool_call_id===w.id);return{functionResponse:{name:w?.function?.name,response:{result:T?.content}}}});s.push({role:"user",parts:p})}});let u={};if(t.reasoning&&t.reasoning.effort&&t.reasoning.effort!=="none")if(u.thinkingConfig={includeThoughts:!0},t.model.includes("gemini-3"))u.thinkingConfig.thinkingLevel=t.reasoning.effort;else{let l=t.model.includes("pro")?[128,32768]:[0,24576],h,d=t.reasoning.max_tokens;typeof d<"u"&&(d>=l[0]&&d<=l[1]?h=d:d<l[0]?h=l[0]:d>l[1]&&(h=l[1]),u.thinkingConfig.thinkingBudget=h)}let c={contents:s,tools:e.length?e:void 0,generationConfig:u};if(t.tool_choice){let l={functionCallingConfig:{}};t.tool_choice==="auto"?l.functionCallingConfig.mode="auto":t.tool_choice==="none"?l.functionCallingConfig.mode="none":t.tool_choice==="required"?l.functionCallingConfig.mode="any":t.tool_choice?.function?.name&&(l.functionCallingConfig.mode="any",l.functionCallingConfig.allowedFunctionNames=[t.tool_choice?.function?.name]),c.toolConfig=l}return c}function Jo(t){let e=t.contents,r=t.tools,n=t.model,s=t.max_tokens,i=t.temperature,u=t.stream,c=t.tool_choice,l={messages:[],model:n,max_tokens:s,temperature:i,stream:u,tool_choice:c};return Array.isArray(e)&&e.forEach(h=>{typeof h=="string"?l.messages.push({role:"user",content:h}):typeof h.text=="string"?l.messages.push({role:"user",content:h.text||null}):h.role==="user"?l.messages.push({role:"user",content:h?.parts?.map(d=>({type:"text",text:d.text||""}))||[]}):h.role==="model"&&l.messages.push({role:"assistant",content:h?.parts?.map(d=>({type:"text",text:d.text||""}))||[]})}),Array.isArray(r)&&(l.tools=[],r.forEach(h=>{Array.isArray(h.functionDeclarations)&&h.functionDeclarations.forEach(d=>{l.tools.push({type:"function",function:{name:d.name,description:d.description,parameters:d.parameters}})})})),l}async function Vo(t,e,r){if(t.headers.get("Content-Type")?.includes("application/json")){let n=await t.json();r?.debug({response:n},`${e} response:`);let s="",i="",u=n.candidates[0]?.content?.parts||[],c=[];for(let p of u)p.text&&p.thought===!0?s+=p.text:c.push(p);i=u.find(p=>p.thoughtSignature)?.thoughtSignature;let l=c?.filter(p=>p.functionCall)?.map(p=>({id:p.functionCall?.id||`tool_${Math.random().toString(36).substring(2,15)}`,type:"function",function:{name:p.functionCall?.name,arguments:JSON.stringify(p.functionCall?.args||{})}}))||[],h=c?.filter(p=>p.text)?.map(p=>p.text)?.join(`
|
|
138
|
+
`)||"",d={id:n.responseId,choices:[{finish_reason:n.candidates[0].finishReason?.toLowerCase()||null,index:0,message:{content:h,role:"assistant",tool_calls:l.length>0?l:void 0,...i&&{thinking:{content:s||"(no content)",signature:i}}}}],created:parseInt(new Date().getTime()/1e3+"",10),model:n.modelVersion,object:"chat.completion",usage:{completion_tokens:n.usageMetadata?.candidatesTokenCount||0,prompt_tokens:n.usageMetadata?.promptTokenCount||0,prompt_tokens_details:{cached_tokens:n.usageMetadata?.cachedContentTokenCount||0},total_tokens:n.usageMetadata?.totalTokenCount||0,output_tokens_details:{reasoning_tokens:n.usageMetadata?.thoughtsTokenCount||0}}};return new Response(JSON.stringify(d),{status:t.status,statusText:t.statusText,headers:t.headers})}else if(t.headers.get("Content-Type")?.includes("stream")){if(!t.body)return t;let n=new TextDecoder,s=new TextEncoder,i=!1,u=!1,c=!1,l="",h=0,d=-1,p=new ReadableStream({async start(w){let T=async(g,m)=>{if(g.startsWith("data: ")){let v=g.slice(6).trim();if(v){r?.debug({chunkStr:v},`${e} chunk:`);try{let b=JSON.parse(v);if(!b.candidates||!b.candidates[0]){r?.debug({chunkStr:v},"Invalid chunk structure");return}let A=b.candidates[0],R=A.content?.parts||[];R.filter(M=>M.text&&M.thought===!0).forEach(M=>{c||(c=!0);let Q={choices:[{delta:{role:"assistant",content:null,thinking:{content:M.text}},finish_reason:null,index:h,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:b.responseId||"",model:b.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};m.enqueue(s.encode(`data: ${JSON.stringify(Q)}
|
|
139
139
|
|
|
140
|
-
`))});let F=R.find(M=>M.thoughtSignature)?.thoughtSignature;if(F&&!i){if(!c){let
|
|
140
|
+
`))});let F=R.find(M=>M.thoughtSignature)?.thoughtSignature;if(F&&!i){if(!c){let Q={choices:[{delta:{role:"assistant",content:null,thinking:{content:"(no content)"}},finish_reason:null,index:h,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:b.responseId||"",model:b.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};m.enqueue(s.encode(`data: ${JSON.stringify(Q)}
|
|
141
141
|
|
|
142
142
|
`))}let M={choices:[{delta:{role:"assistant",content:null,thinking:{signature:F}},finish_reason:null,index:h,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:b.responseId||"",model:b.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};if(m.enqueue(s.encode(`data: ${JSON.stringify(M)}
|
|
143
143
|
|
|
144
|
-
`)),i=!0,h++,l){let
|
|
144
|
+
`)),i=!0,h++,l){let Q={choices:[{delta:{role:"assistant",content:l},finish_reason:null,index:h,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:b.responseId||"",model:b.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};m.enqueue(s.encode(`data: ${JSON.stringify(Q)}
|
|
145
145
|
|
|
146
146
|
`)),l="",u||(u=!0)}}let $=R.filter(M=>M.functionCall).map(M=>({id:M.functionCall?.id||`ccr_tool_${Math.random().toString(36).substring(2,15)}`,type:"function",function:{name:M.functionCall?.name,arguments:JSON.stringify(M.functionCall?.args||{})}})),J=R.filter(M=>M.text&&M.thought!==!0).map(M=>M.text).join(`
|
|
147
147
|
`);if(!J&&i&&!u){let M={choices:[{delta:{role:"assistant",content:"(no content)"},index:h,finish_reason:null,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:b.responseId||"",model:b.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};m.enqueue(s.encode(`data: ${JSON.stringify(M)}
|
|
148
148
|
|
|
149
149
|
`)),u||(u=!0)}if(c&&J&&!i)if(b.modelVersion.includes("3")){l+=J;return}else{let M={choices:[{delta:{role:"assistant",content:null,thinking:{signature:`ccr_${+new Date}`}},finish_reason:null,index:h,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:b.responseId||"",model:b.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};m.enqueue(s.encode(`data: ${JSON.stringify(M)}
|
|
150
150
|
|
|
151
|
-
`)),i=!0}if(J){l||h++;let M={choices:[{delta:{role:"assistant",content:J},finish_reason:
|
|
151
|
+
`)),i=!0}if(J){l||h++;let M={choices:[{delta:{role:"assistant",content:J},finish_reason:A.finishReason?.toLowerCase()||null,index:h,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:b.responseId||"",model:b.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:{completion_tokens:b.usageMetadata?.candidatesTokenCount||0,prompt_tokens:b.usageMetadata?.promptTokenCount||0,prompt_tokens_details:{cached_tokens:b.usageMetadata?.cachedContentTokenCount||0},total_tokens:b.usageMetadata?.totalTokenCount||0,output_tokens_details:{reasoning_tokens:b.usageMetadata?.thoughtsTokenCount||0}}};A?.groundingMetadata?.groundingChunks?.length&&(M.choices[0].delta.annotations=A.groundingMetadata.groundingChunks.map((Q,ue)=>{let re=A?.groundingMetadata?.groundingSupports?.filter(de=>de.groundingChunkIndices?.includes(ue));return{type:"url_citation",url_citation:{url:Q?.web?.uri||"",title:Q?.web?.title||"",content:re?.[0]?.segment?.text||"",start_index:re?.[0]?.segment?.startIndex||0,end_index:re?.[0]?.segment?.endIndex||0}}})),m.enqueue(s.encode(`data: ${JSON.stringify(M)}
|
|
152
152
|
|
|
153
|
-
`)),!u&&J&&(u=!0)}$.length>0&&($.forEach(M=>{h++,d++;let
|
|
153
|
+
`)),!u&&J&&(u=!0)}$.length>0&&($.forEach(M=>{h++,d++;let Q={choices:[{delta:{role:"assistant",tool_calls:[{...M,index:d}]},finish_reason:A.finishReason?.toLowerCase()||null,index:h,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:b.responseId||"",model:b.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:{completion_tokens:b.usageMetadata?.candidatesTokenCount||0,prompt_tokens:b.usageMetadata?.promptTokenCount||0,prompt_tokens_details:{cached_tokens:b.usageMetadata?.cachedContentTokenCount||0},total_tokens:b.usageMetadata?.totalTokenCount||0,output_tokens_details:{reasoning_tokens:b.usageMetadata?.thoughtsTokenCount||0}}};A?.groundingMetadata?.groundingChunks?.length&&(Q.choices[0].delta.annotations=A.groundingMetadata.groundingChunks.map((ue,re)=>{let de=A?.groundingMetadata?.groundingSupports?.filter(pe=>pe.groundingChunkIndices?.includes(re));return{type:"url_citation",url_citation:{url:ue?.web?.uri||"",title:ue?.web?.title||"",content:de?.[0]?.segment?.text||"",start_index:de?.[0]?.segment?.startIndex||0,end_index:de?.[0]?.segment?.endIndex||0}}})),m.enqueue(s.encode(`data: ${JSON.stringify(Q)}
|
|
154
154
|
|
|
155
|
-
`))}),!u&&J&&(u=!0))}catch(b){r?.error(`Error parsing ${e} stream chunk`,
|
|
156
|
-
`);y=
|
|
155
|
+
`))}),!u&&J&&(u=!0))}catch(b){r?.error(`Error parsing ${e} stream chunk`,v,b.message)}}}},S=t.body.getReader(),y="";try{for(;;){let{done:g,value:m}=await S.read();if(g){y&&await T(y,w);break}y+=n.decode(m,{stream:!0});let v=y.split(`
|
|
156
|
+
`);y=v.pop()||"";for(let b of v)await T(b,w)}}catch(g){w.error(g)}finally{w.close()}}});return new Response(p,{status:t.status,statusText:t.statusText,headers:t.headers})}}var Ko=class{name="gemini";endPoint="/v1beta/models/:modelAndAction";async transformRequestIn(e,r){return{body:Go(e),config:{url:new URL(`./${e.model}:${e.stream?"streamGenerateContent?alt=sse":"generateContent"}`,r.baseUrl),headers:{"x-goog-api-key":r.apiKey,Authorization:void 0}}}}transformRequestOut=Jo;async transformResponseOut(e){return Vo(e,this.name,this.logger)}};async function av(){try{let{GoogleAuth:t}=await Promise.resolve().then(()=>Nr(Zl(),1));return(await(await new t({scopes:["https://www.googleapis.com/auth/cloud-platform"]}).getClient()).getAccessToken()).token||""}catch(t){throw console.error("Error getting access token:",t),new Error(`Failed to get access token for Vertex AI. Please ensure you have set up authentication using one of these methods:
|
|
157
157
|
1. Set GOOGLE_APPLICATION_CREDENTIALS to point to service account key file
|
|
158
158
|
2. Run "gcloud auth application-default login"
|
|
159
|
-
3. Use Google Cloud environment with default service account`)}}var
|
|
160
|
-
`);for(let g of y)g.trim()&&
|
|
161
|
-
`))},p=(
|
|
159
|
+
3. Use Google Cloud environment with default service account`)}}var pa=class{name="vertex-gemini";async transformRequestIn(e,r){let n=process.env.GOOGLE_CLOUD_PROJECT,s=process.env.GOOGLE_CLOUD_LOCATION||"us-central1";if(!n&&process.env.GOOGLE_APPLICATION_CREDENTIALS)try{let c=(await import("fs")).readFileSync(process.env.GOOGLE_APPLICATION_CREDENTIALS,"utf8"),l=JSON.parse(c);l&&l.project_id&&(n=l.project_id)}catch(u){console.error("Error extracting project_id from GOOGLE_APPLICATION_CREDENTIALS:",u)}if(!n)throw new Error("Project ID is required for Vertex AI. Set GOOGLE_CLOUD_PROJECT environment variable or ensure project_id is in GOOGLE_APPLICATION_CREDENTIALS file.");let i=await av();return{body:Go(e),config:{url:new URL(`./v1beta1/projects/${n}/locations/${s}/publishers/google/models/${e.model}:${e.stream?"streamGenerateContent":"generateContent"}`,r.baseUrl.endsWith("/")?r.baseUrl:r.baseUrl+"/"||`https://${s}-aiplatform.googleapis.com`),headers:{Authorization:`Bearer ${i}`,"x-goog-api-key":void 0}}}}async transformRequestOut(e){return Jo(e)}async transformResponseOut(e){return Vo(e,this.name)}};var ma=class{name="deepseek";async transformRequestIn(e){return e.max_tokens&&e.max_tokens>8192&&(e.max_tokens=8192),e.messages.forEach(r=>{if(r.role==="assistant"){let n=r.thinking?.content,s=r.thinking?.signature;n&&typeof n=="string"&&n.trim()&&(r.reasoning_content=n,s&&(r.reasoning_content_signature=s)),r.thinking&&delete r.thinking}}),e}async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let r=await e.json();return new Response(JSON.stringify(r),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let r=new TextDecoder,n=new TextEncoder,s="",i=!1,u="",c=new ReadableStream({async start(l){let h=e.body.getReader(),d=(w,T,S)=>{let y=w.split(`
|
|
160
|
+
`);for(let g of y)g.trim()&&T.enqueue(S.encode(g+`
|
|
161
|
+
`))},p=(w,T)=>{let{controller:S,encoder:y}=T;if(w.startsWith("data: ")&&w.trim()!=="data: [DONE]")try{let g=JSON.parse(w.slice(6));if(g.choices?.[0]?.delta?.reasoning_content){T.appendReasoningContent(g.choices[0].delta.reasoning_content);let m={...g,choices:[{...g.choices[0],delta:{...g.choices[0].delta,thinking:{content:g.choices[0].delta.reasoning_content}}}]};delete m.choices[0].delta.reasoning_content;let v=`data: ${JSON.stringify(m)}
|
|
162
162
|
|
|
163
|
-
`;S.enqueue(y.encode(
|
|
163
|
+
`;S.enqueue(y.encode(v));return}if(g.choices?.[0]?.delta?.content&&T.reasoningContent()&&!T.isReasoningComplete()){T.setReasoningComplete(!0);let m=Date.now().toString(),v={...g,choices:[{...g.choices[0],delta:{...g.choices[0].delta,content:null,thinking:{content:T.reasoningContent(),signature:m}}}]};delete v.choices[0].delta.reasoning_content;let b=`data: ${JSON.stringify(v)}
|
|
164
164
|
|
|
165
|
-
`;S.enqueue(y.encode(b))}if(g.choices[0]?.delta?.reasoning_content&&delete g.choices[0].delta.reasoning_content,g.choices?.[0]?.delta&&Object.keys(g.choices[0].delta).length>0){
|
|
165
|
+
`;S.enqueue(y.encode(b))}if(g.choices[0]?.delta?.reasoning_content&&delete g.choices[0].delta.reasoning_content,g.choices?.[0]?.delta&&Object.keys(g.choices[0].delta).length>0){T.isReasoningComplete()&&g.choices[0].index++;let m=`data: ${JSON.stringify(g)}
|
|
166
166
|
|
|
167
|
-
`;S.enqueue(y.encode(m))}}catch{S.enqueue(y.encode(
|
|
168
|
-
`))}else S.enqueue(y.encode(
|
|
169
|
-
`))};try{for(;;){let{done:
|
|
167
|
+
`;S.enqueue(y.encode(m))}}catch{S.enqueue(y.encode(w+`
|
|
168
|
+
`))}else S.enqueue(y.encode(w+`
|
|
169
|
+
`))};try{for(;;){let{done:w,value:T}=await h.read();if(w){u.trim()&&d(u,l,n);break}let S=r.decode(T,{stream:!0});u+=S;let y=u.split(`
|
|
170
170
|
`);u=y.pop()||"";for(let g of y)if(g.trim())try{p(g,{controller:l,encoder:n,reasoningContent:()=>s,appendReasoningContent:m=>s+=m,isReasoningComplete:()=>i,setReasoningComplete:m=>i=m})}catch(m){console.error("Error processing line:",g,m),l.enqueue(n.encode(g+`
|
|
171
|
-
`))}}}catch(
|
|
171
|
+
`))}}}catch(w){console.error("Stream error:",w),l.error(w)}finally{try{h.releaseLock()}catch(w){console.error("Error releasing reader lock:",w)}l.close()}}});return new Response(c,{status:e.status,statusText:e.statusText,headers:{"Content-Type":e.headers.get("Content-Type")||"text/plain","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}};var ga=class{name="tooluse";transformRequestIn(e){return e.messages.push({role:"system",content:"<system-reminder>Tool mode is active. The user expects you to proactively execute the most suitable tool to help complete the task. \nBefore invoking a tool, you must carefully evaluate whether it matches the current task. If no available tool is appropriate for the task, you MUST call the `ExitTool` to exit tool mode \u2014 this is the only valid way to terminate tool mode.\nAlways prioritize completing the user's task effectively and efficiently by using tools whenever appropriate.</system-reminder>"}),e.tools?.length&&(e.tool_choice="required",e.tools.push({type:"function",function:{name:"ExitTool",description:`Use this tool when you are in tool mode and have completed the task. This is the only valid way to exit tool mode.
|
|
172
172
|
IMPORTANT: Before using this tool, ensure that none of the available tools are applicable to the current task. You must evaluate all available options \u2014 only if no suitable tool can help you complete the task should you use ExitTool to terminate tool mode.
|
|
173
173
|
Examples:
|
|
174
174
|
1. Task: "Use a tool to summarize this document" \u2014 Do not use ExitTool if a summarization tool is available.
|
|
175
|
-
2. Task: "What\u2019s the weather today?" \u2014 If no tool is available to answer, use ExitTool after reasoning that none can fulfill the task.`,parameters:{type:"object",properties:{response:{type:"string",description:"Your response will be forwarded to the user exactly as returned \u2014 the tool will not modify or post-process it in any way."}},required:["response"]}}})),e}async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let r=await e.json();if(r?.choices?.[0]?.message.tool_calls?.length&&r?.choices?.[0]?.message.tool_calls[0]?.function?.name==="ExitTool"){let n=r?.choices[0]?.message.tool_calls[0],s=JSON.parse(n.function.arguments||"{}");r.choices[0].message.content=s.response||"",delete r.choices[0].message.tool_calls}return new Response(JSON.stringify(r),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let r=new TextDecoder,n=new TextEncoder,s=-1,i="",u="",c=new ReadableStream({async start(l){let h=e.body.getReader(),d=(
|
|
176
|
-
`);for(let g of y)g.trim()&&
|
|
177
|
-
`))},p=(
|
|
175
|
+
2. Task: "What\u2019s the weather today?" \u2014 If no tool is available to answer, use ExitTool after reasoning that none can fulfill the task.`,parameters:{type:"object",properties:{response:{type:"string",description:"Your response will be forwarded to the user exactly as returned \u2014 the tool will not modify or post-process it in any way."}},required:["response"]}}})),e}async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let r=await e.json();if(r?.choices?.[0]?.message.tool_calls?.length&&r?.choices?.[0]?.message.tool_calls[0]?.function?.name==="ExitTool"){let n=r?.choices[0]?.message.tool_calls[0],s=JSON.parse(n.function.arguments||"{}");r.choices[0].message.content=s.response||"",delete r.choices[0].message.tool_calls}return new Response(JSON.stringify(r),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let r=new TextDecoder,n=new TextEncoder,s=-1,i="",u="",c=new ReadableStream({async start(l){let h=e.body.getReader(),d=(w,T,S)=>{let y=w.split(`
|
|
176
|
+
`);for(let g of y)g.trim()&&T.enqueue(S.encode(g+`
|
|
177
|
+
`))},p=(w,T)=>{let{controller:S,encoder:y,exitToolIndex:g,setExitToolIndex:m,appendExitToolResponse:v}=T;if(w.startsWith("data: ")&&w.trim()!=="data: [DONE]")try{let b=JSON.parse(w.slice(6));if(b.choices[0]?.delta?.tool_calls?.length){let A=b.choices[0].delta.tool_calls[0];if(A.function?.name==="ExitTool"){m(A.index);return}else if(g()>-1&&A.index===g()&&A.function.arguments){v(A.function.arguments);try{let R=JSON.parse(T.exitToolResponse());b.choices=[{delta:{role:"assistant",content:R.response||""}}];let F=`data: ${JSON.stringify(b)}
|
|
178
178
|
|
|
179
|
-
`;S.enqueue(y.encode(F))}catch{}return}}if(b.choices?.[0]?.delta&&Object.keys(b.choices[0].delta).length>0){let
|
|
179
|
+
`;S.enqueue(y.encode(F))}catch{}return}}if(b.choices?.[0]?.delta&&Object.keys(b.choices[0].delta).length>0){let A=`data: ${JSON.stringify(b)}
|
|
180
180
|
|
|
181
|
-
`;S.enqueue(y.encode(
|
|
182
|
-
`))}else S.enqueue(y.encode(
|
|
183
|
-
`))};try{for(;;){let{done:
|
|
181
|
+
`;S.enqueue(y.encode(A))}}catch{S.enqueue(y.encode(w+`
|
|
182
|
+
`))}else S.enqueue(y.encode(w+`
|
|
183
|
+
`))};try{for(;;){let{done:w,value:T}=await h.read();if(w){u.trim()&&d(u,l,n);break}let S=r.decode(T,{stream:!0});u+=S;let y=u.split(`
|
|
184
184
|
`);u=y.pop()||"";for(let g of y)if(g.trim())try{p(g,{controller:l,encoder:n,exitToolIndex:()=>s,setExitToolIndex:m=>s=m,exitToolResponse:()=>i,appendExitToolResponse:m=>i+=m})}catch(m){console.error("Error processing line:",g,m),l.enqueue(n.encode(g+`
|
|
185
|
-
`))}}}catch(
|
|
186
|
-
`);for(let
|
|
187
|
-
`))},
|
|
185
|
+
`))}}}catch(w){console.error("Stream error:",w),l.error(w)}finally{try{h.releaseLock()}catch(w){console.error("Error releasing reader lock:",w)}l.close()}}});return new Response(c,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}};var ya=class{constructor(e){this.options=e}static TransformerName="openrouter";async transformRequestIn(e){return e.model.includes("claude")?e.messages.forEach(r=>{Array.isArray(r.content)&&r.content.forEach(n=>{n.type==="image_url"&&(n.image_url.url.startsWith("http")||(n.image_url.url=`data:${n.media_type};base64,${n.image_url.url}`),delete n.media_type)})}):e.messages.forEach(r=>{Array.isArray(r.content)?r.content.forEach(n=>{n.cache_control&&delete n.cache_control,n.type==="image_url"&&(n.image_url.url.startsWith("http")||(n.image_url.url=`${n.image_url.url}`),delete n.media_type)}):r.cache_control&&delete r.cache_control}),Object.assign(e,this.options||{}),e}async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let r=await e.json();return new Response(JSON.stringify(r),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let r=new TextDecoder,n=new TextEncoder,s=!1,i="",u=!1,c=!1,l="",h=new ReadableStream({async start(d){let p=e.body.getReader(),w=(S,y,g)=>{let m=S.split(`
|
|
186
|
+
`);for(let v of m)v.trim()&&y.enqueue(g.encode(v+`
|
|
187
|
+
`))},T=(S,y)=>{let{controller:g,encoder:m}=y;if(S.startsWith("data: ")&&S.trim()!=="data: [DONE]"){let v=S.slice(6);try{let b=JSON.parse(v);if(b.usage&&(this.logger?.debug({usage:b.usage,hasToolCall:c},"usage"),b.choices[0].finish_reason=c?"tool_calls":"stop"),b.choices?.[0]?.finish_reason==="error"){g.enqueue(m.encode(`data: ${JSON.stringify({error:b.choices?.[0].error})}
|
|
188
188
|
|
|
189
189
|
`));return}if(b.choices?.[0]?.delta?.content&&!y.hasTextContent()&&y.setHasTextContent(!0),b.choices?.[0]?.delta?.reasoning){y.appendReasoningContent(b.choices[0].delta.reasoning);let J={...b,choices:[{...b.choices?.[0],delta:{...b.choices[0].delta,thinking:{content:b.choices[0].delta.reasoning}}}]};J.choices?.[0]?.delta&&delete J.choices[0].delta.reasoning;let M=`data: ${JSON.stringify(J)}
|
|
190
190
|
|
|
191
|
-
`;g.enqueue(m.encode(M));return}if(b.choices?.[0]?.delta?.content&&y.reasoningContent()&&!y.isReasoningComplete()){y.setReasoningComplete(!0);let J=Date.now().toString(),M={...b,choices:[{...b.choices?.[0],delta:{...b.choices[0].delta,content:null,thinking:{content:y.reasoningContent(),signature:J}}}]};M.choices?.[0]?.delta&&delete M.choices[0].delta.reasoning;let
|
|
191
|
+
`;g.enqueue(m.encode(M));return}if(b.choices?.[0]?.delta?.content&&y.reasoningContent()&&!y.isReasoningComplete()){y.setReasoningComplete(!0);let J=Date.now().toString(),M={...b,choices:[{...b.choices?.[0],delta:{...b.choices[0].delta,content:null,thinking:{content:y.reasoningContent(),signature:J}}}]};M.choices?.[0]?.delta&&delete M.choices[0].delta.reasoning;let Q=`data: ${JSON.stringify(M)}
|
|
192
192
|
|
|
193
|
-
`;g.enqueue(m.encode(
|
|
193
|
+
`;g.enqueue(m.encode(Q))}b.choices?.[0]?.delta?.reasoning&&delete b.choices[0].delta.reasoning,b.choices?.[0]?.delta?.tool_calls?.length&&!Number.isNaN(parseInt(b.choices?.[0]?.delta?.tool_calls[0].id,10))&&b.choices?.[0]?.delta?.tool_calls.forEach(J=>{J.id=`call_${Jt()}`}),b.choices?.[0]?.delta?.tool_calls?.length&&!c&&(c=!0),b.choices?.[0]?.delta?.tool_calls?.length&&y.hasTextContent()&&(typeof b.choices[0].index=="number"?b.choices[0].index+=1:b.choices[0].index=1);let A=b.choices?.[0]?.delta,R=A&&Object.keys(A).length>0,F=b.choices?.[0]?.finish_reason,$=b.usage;if(R||F||$){let J=`data: ${JSON.stringify(b)}
|
|
194
194
|
|
|
195
195
|
`;g.enqueue(m.encode(J))}}catch{g.enqueue(m.encode(S+`
|
|
196
196
|
`))}}else g.enqueue(m.encode(S+`
|
|
197
|
-
`))};try{for(;;){let{done:S,value:y}=await p.read();if(S){l.trim()&&
|
|
198
|
-
`);l=
|
|
197
|
+
`))};try{for(;;){let{done:S,value:y}=await p.read();if(S){l.trim()&&w(l,d,n);break}if(!y||y.length===0)continue;let g;try{g=r.decode(y,{stream:!0})}catch(v){console.warn("Failed to decode chunk",v);continue}if(g.length===0)continue;if(l+=g,l.length>1e6){console.warn("Buffer size exceeds limit, processing partial data");let v=l.split(`
|
|
198
|
+
`);l=v.pop()||"";for(let b of v)if(b.trim())try{T(b,{controller:d,encoder:n,hasTextContent:()=>s,setHasTextContent:A=>s=A,reasoningContent:()=>i,appendReasoningContent:A=>i+=A,isReasoningComplete:()=>u,setReasoningComplete:A=>u=A})}catch(A){console.error("Error processing line:",b,A),d.enqueue(n.encode(b+`
|
|
199
199
|
`))}continue}let m=l.split(`
|
|
200
|
-
`);l=m.pop()||"";for(let
|
|
201
|
-
`))}}}catch(S){console.error("Stream error:",S),d.error(S)}finally{try{p.releaseLock()}catch(S){console.error("Error releasing reader lock:",S)}d.close()}}});return new Response(h,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}};var
|
|
200
|
+
`);l=m.pop()||"";for(let v of m)if(v.trim())try{T(v,{controller:d,encoder:n,hasTextContent:()=>s,setHasTextContent:b=>s=b,reasoningContent:()=>i,appendReasoningContent:b=>i+=b,isReasoningComplete:()=>u,setReasoningComplete:b=>u=b})}catch(b){console.error("Error processing line:",v,b),d.enqueue(n.encode(v+`
|
|
201
|
+
`))}}}catch(S){console.error("Stream error:",S),d.error(S)}finally{try{p.releaseLock()}catch(S){console.error("Error releasing reader lock:",S)}d.close()}}});return new Response(h,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}};var _a=class{constructor(e){this.options=e;this.max_tokens=this.options?.max_tokens}static TransformerName="maxtoken";max_tokens;async transformRequestIn(e){return e.max_tokens&&e.max_tokens>this.max_tokens&&(e.max_tokens=this.max_tokens),e}};var ba=class{name="groq";async transformRequestIn(e){return e.messages.forEach(r=>{Array.isArray(r.content)?r.content.forEach(n=>{n.cache_control&&delete n.cache_control}):r.cache_control&&delete r.cache_control}),Array.isArray(e.tools)&&e.tools.forEach(r=>{delete r.function.parameters.$schema}),e}async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let r=await e.json();return new Response(JSON.stringify(r),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let r=new TextDecoder,n=new TextEncoder,s=!1,i="",u=!1,c="",l=new ReadableStream({async start(h){let d=e.body.getReader(),p=(T,S,y)=>{let g=T.split(`
|
|
202
202
|
`);for(let m of g)m.trim()&&S.enqueue(y.encode(m+`
|
|
203
|
-
`))},
|
|
203
|
+
`))},w=(T,S)=>{let{controller:y,encoder:g}=S;if(T.startsWith("data: ")&&T.trim()!=="data: [DONE]"){let m=T.slice(6);try{let v=JSON.parse(m);if(v.error)throw new Error(JSON.stringify(v));v.choices?.[0]?.delta?.content&&!S.hasTextContent()&&S.setHasTextContent(!0),v.choices?.[0]?.delta?.tool_calls?.length&&v.choices?.[0]?.delta?.tool_calls.forEach(A=>{A.id=`call_${Jt()}`}),v.choices?.[0]?.delta?.tool_calls?.length&&S.hasTextContent()&&(typeof v.choices[0].index=="number"?v.choices[0].index+=1:v.choices[0].index=1);let b=`data: ${JSON.stringify(v)}
|
|
204
204
|
|
|
205
|
-
`;y.enqueue(g.encode(b))}catch{y.enqueue(g.encode(
|
|
206
|
-
`))}}else y.enqueue(g.encode(
|
|
207
|
-
`))};try{for(;;){let{done:
|
|
208
|
-
`);c=m.pop()||"";for(let
|
|
205
|
+
`;y.enqueue(g.encode(b))}catch{y.enqueue(g.encode(T+`
|
|
206
|
+
`))}}else y.enqueue(g.encode(T+`
|
|
207
|
+
`))};try{for(;;){let{done:T,value:S}=await d.read();if(T){c.trim()&&p(c,h,n);break}if(!S||S.length===0)continue;let y;try{y=r.decode(S,{stream:!0})}catch(m){console.warn("Failed to decode chunk",m);continue}if(y.length===0)continue;if(c+=y,c.length>1e6){console.warn("Buffer size exceeds limit, processing partial data");let m=c.split(`
|
|
208
|
+
`);c=m.pop()||"";for(let v of m)if(v.trim())try{w(v,{controller:h,encoder:n,hasTextContent:()=>s,setHasTextContent:b=>s=b,reasoningContent:()=>i,appendReasoningContent:b=>i+=b,isReasoningComplete:()=>u,setReasoningComplete:b=>u=b})}catch(b){console.error("Error processing line:",v,b),h.enqueue(n.encode(v+`
|
|
209
209
|
`))}continue}let g=c.split(`
|
|
210
|
-
`);c=g.pop()||"";for(let m of g)if(m.trim())try{
|
|
211
|
-
`))}}}catch(
|
|
212
|
-
+`.includes(t)}function
|
|
213
|
-
+`.includes(t)}function
|
|
214
|
-
`||t==="\r"||t===" "||t==="\b"||t==="\f"}function
|
|
215
|
-
`,r:"\r",t:" "};function
|
|
216
|
-
`;)e++;return!0}return!1}function h(G){if(d(G)){if(
|
|
210
|
+
`);c=g.pop()||"";for(let m of g)if(m.trim())try{w(m,{controller:h,encoder:n,hasTextContent:()=>s,setHasTextContent:v=>s=v,reasoningContent:()=>i,appendReasoningContent:v=>i+=v,isReasoningComplete:()=>u,setReasoningComplete:v=>u=v})}catch(v){console.error("Error processing line:",m,v),h.enqueue(n.encode(m+`
|
|
211
|
+
`))}}}catch(T){console.error("Stream error:",T),h.error(T)}finally{try{d.releaseLock()}catch(T){console.error("Error releasing reader lock:",T)}h.close()}}});return new Response(l,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}};var Ca=class{name="cleancache";async transformRequestIn(e){return Array.isArray(e.messages)&&e.messages.forEach(r=>{Array.isArray(r.content)?r.content.forEach(n=>{n.cache_control&&delete n.cache_control}):r.cache_control&&delete r.cache_control}),e}};var ky=Nr(Du());var Ar=class extends Error{constructor(e,r){super(`${e} at position ${r}`),this.position=r}};function by(t){return/^[0-9A-Fa-f]$/.test(t)}function Jr(t){return t>="0"&&t<="9"}function Cy(t){return t>=" "}function Xs(t){return`,:[]/{}()
|
|
212
|
+
+`.includes(t)}function ed(t){return t>="a"&&t<="z"||t>="A"&&t<="Z"||t==="_"||t==="$"}function td(t){return t>="a"&&t<="z"||t>="A"&&t<="Z"||t==="_"||t==="$"||t>="0"&&t<="9"}var rd=/^(http|https|ftp|mailto|file|data|irc):\/\/$/,nd=/^[A-Za-z0-9-._~:/?#@!$&'()*+;=]$/;function sd(t){return`,[]/{}
|
|
213
|
+
+`.includes(t)}function od(t){return Zs(t)||uv.test(t)}var uv=/^[[{\w-]$/;function wy(t){return t===`
|
|
214
|
+
`||t==="\r"||t===" "||t==="\b"||t==="\f"}function Gr(t,e){let r=t.charCodeAt(e);return r===32||r===10||r===9||r===13}function Ey(t,e){let r=t.charCodeAt(e);return r===32||r===9||r===13}function Ay(t,e){let r=t.charCodeAt(e);return r===160||r>=8192&&r<=8202||r===8239||r===8287||r===12288}function Zs(t){return id(t)||wa(t)}function id(t){return t==='"'||t==="\u201C"||t==="\u201D"}function ad(t){return t==='"'}function wa(t){return t==="'"||t==="\u2018"||t==="\u2019"||t==="`"||t==="\xB4"}function ud(t){return t==="'"}function as(t,e){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,n=t.lastIndexOf(e);return n!==-1?t.substring(0,n)+(r?"":t.substring(n+1)):t}function Rt(t,e){let r=t.length;if(!Gr(t,r-1))return t+e;for(;Gr(t,r-1);)r--;return t.substring(0,r)+e+t.substring(r)}function Sy(t,e,r){return t.substring(0,e)+t.substring(e+r)}function vy(t){return/[,\n][ \t\r]*$/.test(t)}var cv={"\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r"," ":"\\t"},lv={'"':'"',"\\":"\\","/":"/",b:"\b",f:"\f",n:`
|
|
215
|
+
`,r:"\r",t:" "};function cd(t){let e=0,r="";h(["```","[```","{```"]),i()||pe(),h(["```","```]","```}"]);let s=p(",");for(s&&u(),od(t[e])&&vy(r)?(s||(r=Rt(r,",")),m()):s&&(r=as(r,","));t[e]==="}"||t[e]==="]";)e++,u();if(e>=t.length)return r;de();function i(){u();let G=y()||g()||v()||A()||R()||$(!1)||J();return u(),G}function u(){let G=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,K=e,ae=c(G);do ae=l(),ae&&(ae=c(G));while(ae);return e>K}function c(G){let K=G?Gr:Ey,ae="";for(;;)if(K(t,e))ae+=t[e],e++;else if(Ay(t,e))ae+=" ",e++;else break;return ae.length>0?(r+=ae,!0):!1}function l(){if(t[e]==="/"&&t[e+1]==="*"){for(;e<t.length&&!dv(t,e);)e++;return e+=2,!0}if(t[e]==="/"&&t[e+1]==="/"){for(;e<t.length&&t[e]!==`
|
|
216
|
+
`;)e++;return!0}return!1}function h(G){if(d(G)){if(ed(t[e]))for(;e<t.length&&td(t[e]);)e++;return u(),!0}return!1}function d(G){c(!0);for(let K of G){let ae=e+K.length;if(t.slice(e,ae)===K)return e=ae,!0}return!1}function p(G){return t[e]===G?(r+=t[e],e++,!0):!1}function w(G){return t[e]===G?(e++,!0):!1}function T(){return w("\\")}function S(){return u(),t[e]==="."&&t[e+1]==="."&&t[e+2]==="."?(e+=3,u(),w(","),!0):!1}function y(){if(t[e]==="{"){r+="{",e++,u(),w(",")&&u();let G=!0;for(;e<t.length&&t[e]!=="}";){let K;if(G?(K=!0,G=!1):(K=p(","),K||(r=Rt(r,",")),u()),S(),!(v()||$(!0))){t[e]==="}"||t[e]==="{"||t[e]==="]"||t[e]==="["||t[e]===void 0?r=as(r,","):Ae();break}u();let qe=p(":"),Te=e>=t.length;qe||(od(t[e])||Te?r=Rt(r,":"):oe()),i()||(qe||Te?r+="null":oe())}return t[e]==="}"?(r+="}",e++):r=Rt(r,"}"),!0}return!1}function g(){if(t[e]==="["){r+="[",e++,u(),w(",")&&u();let G=!0;for(;e<t.length&&t[e]!=="]";)if(G?G=!1:p(",")||(r=Rt(r,",")),S(),!i()){r=as(r,",");break}return t[e]==="]"?(r+="]",e++):r=Rt(r,"]"),!0}return!1}function m(){let G=!0,K=!0;for(;K;)G?G=!1:p(",")||(r=Rt(r,",")),K=i();K||(r=as(r,",")),r=`[
|
|
217
217
|
${r}
|
|
218
|
-
]`}function
|
|
219
|
-
`);for(let
|
|
220
|
-
`))},S=(g,m,
|
|
218
|
+
]`}function v(){let G=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1,K=arguments.length>1&&arguments[1]!==void 0?arguments[1]:-1,ae=t[e]==="\\";if(ae&&(e++,ae=!0),Zs(t[e])){let qe=ad(t[e])?ad:ud(t[e])?ud:wa(t[e])?wa:id,Te=e,W=r.length,le='"';for(e++;;){if(e>=t.length){let _e=M(e-1);return!G&&Xs(t.charAt(_e))?(e=Te,r=r.substring(0,W),v(!0)):(le=Rt(le,'"'),r+=le,!0)}if(e===K)return le=Rt(le,'"'),r+=le,!0;if(qe(t[e])){let _e=e,Ot=le.length;if(le+='"',e++,r+=le,u(!1),G||e>=t.length||Xs(t[e])||Zs(t[e])||Jr(t[e]))return b(),!0;let Re=M(_e-1),Be=t.charAt(Re);if(Be===",")return e=Te,r=r.substring(0,W),v(!1,Re);if(Xs(Be))return e=Te,r=r.substring(0,W),v(!0);r=r.substring(0,W),e=_e+1,le=`${le.substring(0,Ot)}\\${le.substring(Ot)}`}else if(G&&sd(t[e])){if(t[e-1]===":"&&rd.test(t.substring(Te+1,e+2)))for(;e<t.length&&nd.test(t[e]);)le+=t[e],e++;return le=Rt(le,'"'),r+=le,b(),!0}else if(t[e]==="\\"){let _e=t.charAt(e+1);if(lv[_e]!==void 0)le+=t.slice(e,e+2),e+=2;else if(_e==="u"){let Re=2;for(;Re<6&&by(t[e+Re]);)Re++;Re===6?(le+=t.slice(e,e+6),e+=6):e+Re>=t.length?e=t.length:me()}else le+=_e,e+=2}else{let _e=t.charAt(e);_e==='"'&&t[e-1]!=="\\"?(le+=`\\${_e}`,e++):wy(_e)?(le+=cv[_e],e++):(Cy(_e)||re(_e),le+=_e,e++)}ae&&T()}}return!1}function b(){let G=!1;for(u();t[e]==="+";){G=!0,e++,u(),r=as(r,'"',!0);let K=r.length;v()?r=Sy(r,K,1):r=Rt(r,'"')}return G}function A(){let G=e;if(t[e]==="-"){if(e++,Q())return ue(G),!0;if(!Jr(t[e]))return e=G,!1}for(;Jr(t[e]);)e++;if(t[e]==="."){if(e++,Q())return ue(G),!0;if(!Jr(t[e]))return e=G,!1;for(;Jr(t[e]);)e++}if(t[e]==="e"||t[e]==="E"){if(e++,(t[e]==="-"||t[e]==="+")&&e++,Q())return ue(G),!0;if(!Jr(t[e]))return e=G,!1;for(;Jr(t[e]);)e++}if(!Q())return e=G,!1;if(e>G){let K=t.slice(G,e),ae=/^0\d/.test(K);return r+=ae?`"${K}"`:K,!0}return!1}function R(){return F("true","true")||F("false","false")||F("null","null")||F("True","true")||F("False","false")||F("None","null")}function F(G,K){return t.slice(e,e+G.length)===G?(r+=K,e+=G.length,!0):!1}function $(G){let K=e;if(ed(t[e])){for(;e<t.length&&td(t[e]);)e++;let ae=e;for(;Gr(t,ae);)ae++;if(t[ae]==="(")return e=ae+1,i(),t[e]===")"&&(e++,t[e]===";"&&e++),!0}for(;e<t.length&&!sd(t[e])&&!Zs(t[e])&&(!G||t[e]!==":");)e++;if(t[e-1]===":"&&rd.test(t.substring(K,e+2)))for(;e<t.length&&nd.test(t[e]);)e++;if(e>K){for(;Gr(t,e-1)&&e>0;)e--;let ae=t.slice(K,e);return r+=ae==="undefined"?"null":JSON.stringify(ae),t[e]==='"'&&e++,!0}}function J(){if(t[e]==="/"){let G=e;for(e++;e<t.length&&(t[e]!=="/"||t[e-1]==="\\");)e++;return e++,r+=`"${t.substring(G,e)}"`,!0}}function M(G){let K=G;for(;K>0&&Gr(t,K);)K--;return K}function Q(){return e>=t.length||Xs(t[e])||Gr(t,e)}function ue(G){r+=`${t.slice(G,e)}0`}function re(G){throw new Ar(`Invalid character ${JSON.stringify(G)}`,e)}function de(){throw new Ar(`Unexpected character ${JSON.stringify(t[e])}`,e)}function pe(){throw new Ar("Unexpected end of json string",t.length)}function Ae(){throw new Ar("Object key expected",e)}function oe(){throw new Ar("Colon expected",e)}function me(){let G=t.slice(e,e+6);throw new Ar(`Invalid unicode character "${G}"`,e)}}function dv(t,e){return t[e]==="*"&&t[e+1]==="/"}function ld(t,e){if(!t||t.trim()===""||t==="{}")return"{}";try{return JSON.parse(t),e?.debug("\u5DE5\u5177\u8C03\u7528\u53C2\u6570\u6807\u51C6JSON\u89E3\u6790\u6210\u529F / Tool arguments standard JSON parsing successful"),t}catch(r){try{let n=ky.default.parse(t);return e?.debug("Tool arguments JSON5 parsing successful"),JSON.stringify(n)}catch(n){try{let s=cd(t);return e?.debug("Tool arguments safely repaired"),s}catch(s){return e?.error(`JSON parsing failed: ${r.message}. JSON5 parsing failed: ${n.message}. JSON repair failed: ${s.message}. Input data: ${JSON.stringify(t)}`),e?.debug("Returning safe empty object as fallback"),"{}"}}}}var Ea=class{name="enhancetool";async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let r=await e.json();if(r?.choices?.[0]?.message?.tool_calls?.length)for(let n of r.choices[0].message.tool_calls)n.function?.arguments&&(n.function.arguments=ld(n.function.arguments,this.logger));return new Response(JSON.stringify(r),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let r=new TextDecoder,n=new TextEncoder,s={},i=!1,u="",c=!1,l=!1,h="",d=new ReadableStream({async start(p){let w=e.body.getReader(),T=(g,m,v)=>{let b=g.split(`
|
|
219
|
+
`);for(let A of b)A.trim()&&m.enqueue(v.encode(A+`
|
|
220
|
+
`))},S=(g,m,v)=>{let b="";try{b=ld(s.arguments||"",this.logger)}catch($){console.error(`${$.message} ${$.stack} \u5DE5\u5177\u8C03\u7528\u53C2\u6570\u89E3\u6790\u5931\u8D25: ${JSON.stringify(s)}`),b=s.arguments||""}let A={role:"assistant",tool_calls:[{function:{name:s.name,arguments:b},id:s.id,index:s.index,type:"function"}]},R={...g,choices:[{...g.choices[0],delta:A}]};R.choices[0].delta.content!==void 0&&delete R.choices[0].delta.content;let F=`data: ${JSON.stringify(R)}
|
|
221
221
|
|
|
222
|
-
`;m.enqueue(
|
|
222
|
+
`;m.enqueue(v.encode(F))},y=(g,m)=>{let{controller:v,encoder:b}=m;if(g.startsWith("data: ")&&g.trim()!=="data: [DONE]"){let A=g.slice(6);try{let R=JSON.parse(A);if(R.choices?.[0]?.delta?.tool_calls?.length){let $=R.choices[0].delta.tool_calls[0];if(typeof s.index>"u"){s={index:$.index,name:$.function?.name||"",id:$.id||"",arguments:$.function?.arguments||""},$.function?.arguments&&($.function.arguments="");let J=`data: ${JSON.stringify(R)}
|
|
223
223
|
|
|
224
|
-
`;
|
|
224
|
+
`;v.enqueue(b.encode(J));return}else if(s.index===$.index){$.function?.arguments&&(s.arguments+=$.function.arguments);return}else{S(R,v,b),s={index:$.index,name:$.function?.name||"",id:$.id||"",arguments:$.function?.arguments||""};return}}if(R.choices?.[0]?.finish_reason==="tool_calls"&&s.index!==void 0){S(R,v,b),s={};return}R.choices?.[0]?.delta?.tool_calls?.length&&m.hasTextContent()&&(typeof R.choices[0].index=="number"?R.choices[0].index+=1:R.choices[0].index=1);let F=`data: ${JSON.stringify(R)}
|
|
225
225
|
|
|
226
|
-
`;
|
|
227
|
-
`))}}else
|
|
228
|
-
`))};try{for(;;){let{done:g,value:m}=await
|
|
229
|
-
`);h=
|
|
226
|
+
`;v.enqueue(b.encode(F))}catch{v.enqueue(b.encode(g+`
|
|
227
|
+
`))}}else v.enqueue(b.encode(g+`
|
|
228
|
+
`))};try{for(;;){let{done:g,value:m}=await w.read();if(g){h.trim()&&T(h,p,n);break}if(!m||m.length===0)continue;let v;try{v=r.decode(m,{stream:!0})}catch(A){console.warn("Failed to decode chunk",A);continue}if(v.length===0)continue;if(h+=v,h.length>1e6){console.warn("Buffer size exceeds limit, processing partial data");let A=h.split(`
|
|
229
|
+
`);h=A.pop()||"";for(let R of A)if(R.trim())try{y(R,{controller:p,encoder:n,hasTextContent:()=>i,setHasTextContent:F=>i=F,reasoningContent:()=>u,appendReasoningContent:F=>u+=F,isReasoningComplete:()=>c,setReasoningComplete:F=>c=F})}catch(F){console.error("Error processing line:",R,F),p.enqueue(n.encode(R+`
|
|
230
230
|
`))}continue}let b=h.split(`
|
|
231
|
-
`);h=b.pop()||"";for(let
|
|
232
|
-
`))}}}catch(g){console.error("Stream error:",g),p.error(g)}finally{try{
|
|
233
|
-
`);for(let g of y)g.trim()&&
|
|
234
|
-
`))},p=(
|
|
231
|
+
`);h=b.pop()||"";for(let A of b)if(A.trim())try{y(A,{controller:p,encoder:n,hasTextContent:()=>i,setHasTextContent:R=>i=R,reasoningContent:()=>u,appendReasoningContent:R=>u+=R,isReasoningComplete:()=>c,setReasoningComplete:R=>c=R})}catch(R){console.error("Error processing line:",A,R),p.enqueue(n.encode(A+`
|
|
232
|
+
`))}}}catch(g){console.error("Stream error:",g),p.error(g)}finally{try{w.releaseLock()}catch(g){console.error("Error releasing reader lock:",g)}p.close()}}});return new Response(d,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}};var Aa=class{constructor(e){this.options=e;this.enable=this.options?.enable??!0}static TransformerName="reasoning";enable;async transformRequestIn(e){return this.enable?(e.reasoning&&(e.thinking={type:"enabled",budget_tokens:e.reasoning.max_tokens},e.enable_thinking=!0),e):(e.thinking={type:"disabled",budget_tokens:-1},e.enable_thinking=!1,e)}async transformResponseOut(e){if(!this.enable)return e;if(e.headers.get("Content-Type")?.includes("application/json")){let r=await e.json();return r.choices[0]?.message.reasoning_content&&(r.thinking={content:r.choices[0]?.message.reasoning_content}),new Response(JSON.stringify(r),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let r=new TextDecoder,n=new TextEncoder,s="",i=!1,u="",c=new ReadableStream({async start(l){let h=e.body.getReader(),d=(w,T,S)=>{let y=w.split(`
|
|
233
|
+
`);for(let g of y)g.trim()&&T.enqueue(S.encode(g+`
|
|
234
|
+
`))},p=(w,T)=>{let{controller:S,encoder:y}=T;if(this.logger?.debug({line:w},"Processing reason line"),w.startsWith("data: ")&&w.trim()!=="data: [DONE]")try{let g=JSON.parse(w.slice(6));if(console.log(JSON.stringify(g)),g.choices?.[0]?.delta?.reasoning_content){T.appendReasoningContent(g.choices[0].delta.reasoning_content);let m={...g,choices:[{...g.choices[0],delta:{...g.choices[0].delta,thinking:{content:g.choices[0].delta.reasoning_content}}}]};delete m.choices[0].delta.reasoning_content;let v=`data: ${JSON.stringify(m)}
|
|
235
235
|
|
|
236
|
-
`;S.enqueue(y.encode(
|
|
236
|
+
`;S.enqueue(y.encode(v));return}if((g.choices?.[0]?.delta?.content||g.choices?.[0]?.delta?.tool_calls)&&T.reasoningContent()&&!T.isReasoningComplete()){T.setReasoningComplete(!0);let m=Date.now().toString(),v={...g,choices:[{...g.choices[0],delta:{...g.choices[0].delta,content:null,thinking:{content:T.reasoningContent(),signature:m}}}]};delete v.choices[0].delta.reasoning_content;let b=`data: ${JSON.stringify(v)}
|
|
237
237
|
|
|
238
|
-
`;S.enqueue(y.encode(b))}if(g.choices?.[0]?.delta?.reasoning_content&&delete g.choices[0].delta.reasoning_content,g.choices?.[0]?.delta&&Object.keys(g.choices[0].delta).length>0){
|
|
238
|
+
`;S.enqueue(y.encode(b))}if(g.choices?.[0]?.delta?.reasoning_content&&delete g.choices[0].delta.reasoning_content,g.choices?.[0]?.delta&&Object.keys(g.choices[0].delta).length>0){T.isReasoningComplete()&&g.choices[0].index++;let m=`data: ${JSON.stringify(g)}
|
|
239
239
|
|
|
240
|
-
`;S.enqueue(y.encode(m))}}catch{S.enqueue(y.encode(
|
|
241
|
-
`))}else S.enqueue(y.encode(
|
|
242
|
-
`))};try{for(;;){let{done:
|
|
240
|
+
`;S.enqueue(y.encode(m))}}catch{S.enqueue(y.encode(w+`
|
|
241
|
+
`))}else S.enqueue(y.encode(w+`
|
|
242
|
+
`))};try{for(;;){let{done:w,value:T}=await h.read();if(w){u.trim()&&d(u,l,n);break}let S=r.decode(T,{stream:!0});u+=S;let y=u.split(`
|
|
243
243
|
`);u=y.pop()||"";for(let g of y)if(g.trim())try{p(g,{controller:l,encoder:n,reasoningContent:()=>s,appendReasoningContent:m=>s+=m,isReasoningComplete:()=>i,setReasoningComplete:m=>i=m})}catch(m){console.error("Error processing line:",g,m),l.enqueue(n.encode(g+`
|
|
244
|
-
`))}}}catch(
|
|
244
|
+
`))}}}catch(w){console.error("Stream error:",w),l.error(w)}finally{try{h.releaseLock()}catch(w){console.error("Error releasing reader lock:",w)}l.close()}}});return new Response(c,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}};var Sa=class{constructor(e){this.options=e;this.max_tokens=this.options?.max_tokens,this.temperature=this.options?.temperature,this.top_p=this.options?.top_p,this.top_k=this.options?.top_k,this.repetition_penalty=this.options?.repetition_penalty}static TransformerName="sampling";max_tokens;temperature;top_p;top_k;repetition_penalty;async transformRequestIn(e){return e.max_tokens&&e.max_tokens>this.max_tokens&&(e.max_tokens=this.max_tokens),typeof this.temperature<"u"&&(e.temperature=this.temperature),typeof this.top_p<"u"&&(e.top_p=this.top_p),typeof this.top_k<"u"&&(e.top_k=this.top_k),typeof this.repetition_penalty<"u"&&(e.repetition_penalty=this.repetition_penalty),e}};var va=class{static TransformerName="maxcompletiontokens";async transformRequestIn(e){return e.max_tokens&&(e.max_completion_tokens=e.max_tokens,delete e.max_tokens),e}};function Ty(t){let e=[];for(let n=0;n<t.messages.length;n++){let s=t.messages[n],i=n===t.messages.length-1,u=s.role==="assistant",c=[];typeof s.content=="string"?c.push({type:"text",text:s.content}):Array.isArray(s.content)&&s.content.forEach(l=>{l.type==="text"?c.push({type:"text",text:l.text||""}):l.type==="image_url"&&c.push({type:"image",source:{type:"base64",media_type:l.media_type||"image/jpeg",data:l.image_url.url}})}),!(!i&&c.length===0&&!s.tool_calls&&!s.content)&&(i&&u&&c.length===0&&s.tool_calls&&c.push({type:"text",text:""}),e.push({role:s.role==="assistant"?"assistant":"user",content:c}))}let r={anthropic_version:"vertex-2023-10-16",messages:e,max_tokens:t.max_tokens||1e3,stream:t.stream||!1,...t.temperature&&{temperature:t.temperature}};return t.tools&&t.tools.length>0&&(r.tools=t.tools.map(n=>({name:n.function.name,description:n.function.description,input_schema:n.function.parameters}))),t.tool_choice&&(t.tool_choice==="auto"||t.tool_choice==="none"?r.tool_choice=t.tool_choice:typeof t.tool_choice=="string"&&(r.tool_choice={type:"tool",name:t.tool_choice})),r}function Dy(t){let e=t,n={messages:e.messages.map(s=>{let i=s.content.map(u=>u.type==="text"?{type:"text",text:u.text||""}:u.type==="image"&&u.source?{type:"image_url",image_url:{url:u.source.data},media_type:u.source.media_type}:{type:"text",text:""});return{role:s.role,content:i}}),model:t.model||"claude-sonnet-4@20250514",max_tokens:e.max_tokens,temperature:e.temperature,stream:e.stream};return e.tools&&e.tools.length>0&&(n.tools=e.tools.map(s=>({type:"function",function:{name:s.name,description:s.description,parameters:{type:"object",properties:s.input_schema.properties,required:s.input_schema.required,additionalProperties:s.input_schema.additionalProperties,$schema:s.input_schema.$schema}}}))),e.tool_choice&&(typeof e.tool_choice=="string"?n.tool_choice=e.tool_choice:e.tool_choice.type==="tool"&&(n.tool_choice=e.tool_choice.name)),n}async function Ry(t,e,r){if(t.headers.get("Content-Type")?.includes("application/json")){let n=await t.json(),s;n.tool_use&&n.tool_use.length>0&&(s=n.tool_use.map(u=>({id:u.id,type:"function",function:{name:u.name,arguments:JSON.stringify(u.input)}})));let i={id:n.id,choices:[{finish_reason:n.stop_reason||null,index:0,message:{content:n.content[0]?.text||"",role:"assistant",...s&&{tool_calls:s}}}],created:parseInt(new Date().getTime()/1e3+"",10),model:n.model,object:"chat.completion",usage:{completion_tokens:n.usage.output_tokens,prompt_tokens:n.usage.input_tokens,total_tokens:n.usage.input_tokens+n.usage.output_tokens}};return new Response(JSON.stringify(i),{status:t.status,statusText:t.statusText,headers:t.headers})}else if(t.headers.get("Content-Type")?.includes("stream")){if(!t.body)return t;let n=new TextDecoder,s=new TextEncoder,i=(c,l)=>{if(c.startsWith("data: ")){let h=c.slice(6).trim();if(h){r?.debug({chunkStr:h},`${e} chunk:`);try{let d=JSON.parse(h);if(d.type==="content_block_delta"&&d.delta?.type==="text_delta"){let p={choices:[{delta:{role:"assistant",content:d.delta.text||""},finish_reason:null,index:0,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:d.id||"",model:d.model||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:{completion_tokens:d.usage?.output_tokens||0,prompt_tokens:d.usage?.input_tokens||0,total_tokens:(d.usage?.input_tokens||0)+(d.usage?.output_tokens||0)}};l.enqueue(s.encode(`data: ${JSON.stringify(p)}
|
|
245
245
|
|
|
246
246
|
`))}else if(d.type==="content_block_delta"&&d.delta?.type==="input_json_delta"){let p={choices:[{delta:{tool_calls:[{index:d.index||0,function:{arguments:d.delta.partial_json||""}}]},finish_reason:null,index:0,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:d.id||"",model:d.model||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:{completion_tokens:d.usage?.output_tokens||0,prompt_tokens:d.usage?.input_tokens||0,total_tokens:(d.usage?.input_tokens||0)+(d.usage?.output_tokens||0)}};l.enqueue(s.encode(`data: ${JSON.stringify(p)}
|
|
247
247
|
|
|
@@ -253,79 +253,79 @@ ${r}
|
|
|
253
253
|
|
|
254
254
|
`));else{let p={choices:[{delta:{role:"assistant",content:d.content?.[0]?.text||""},finish_reason:d.stop_reason?.toLowerCase()||null,index:0,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:d.id||"",model:d.model||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:{completion_tokens:d.usage?.output_tokens||0,prompt_tokens:d.usage?.input_tokens||0,total_tokens:(d.usage?.input_tokens||0)+(d.usage?.output_tokens||0)}};l.enqueue(s.encode(`data: ${JSON.stringify(p)}
|
|
255
255
|
|
|
256
|
-
`))}}catch(d){r?.error(`Error parsing ${e} stream chunk`,h,d.message)}}}},u=new ReadableStream({async start(c){let l=t.body.getReader(),h="";try{for(;;){let{done:d,value:p}=await l.read();if(d){h&&i(h,c);break}h+=n.decode(p,{stream:!0});let
|
|
257
|
-
`);h=
|
|
256
|
+
`))}}catch(d){r?.error(`Error parsing ${e} stream chunk`,h,d.message)}}}},u=new ReadableStream({async start(c){let l=t.body.getReader(),h="";try{for(;;){let{done:d,value:p}=await l.read();if(d){h&&i(h,c);break}h+=n.decode(p,{stream:!0});let w=h.split(`
|
|
257
|
+
`);h=w.pop()||"";for(let T of w)i(T,c)}}catch(d){c.error(d)}finally{c.close()}}});return new Response(u,{status:t.status,statusText:t.statusText,headers:t.headers})}return t}async function fv(){try{let{GoogleAuth:t}=await Promise.resolve().then(()=>Nr(Zl(),1));return(await(await new t({scopes:["https://www.googleapis.com/auth/cloud-platform"]}).getClient()).getAccessToken()).token||""}catch(t){throw console.error("Error getting access token:",t),new Error(`Failed to get access token for Vertex AI. Please ensure you have set up authentication using one of these methods:
|
|
258
258
|
1. Set GOOGLE_APPLICATION_CREDENTIALS to point to service account key file
|
|
259
259
|
2. Run "gcloud auth application-default login"
|
|
260
|
-
3. Use Google Cloud environment with default service account`)}}var
|
|
261
|
-
`);for(let
|
|
262
|
-
`))},
|
|
260
|
+
3. Use Google Cloud environment with default service account`)}}var ka=class{name="vertex-claude";async transformRequestIn(e,r){let n=process.env.GOOGLE_CLOUD_PROJECT,s=process.env.GOOGLE_CLOUD_LOCATION||"us-east5";if(!n&&process.env.GOOGLE_APPLICATION_CREDENTIALS)try{let c=(await import("fs")).readFileSync(process.env.GOOGLE_APPLICATION_CREDENTIALS,"utf8"),l=JSON.parse(c);l&&l.project_id&&(n=l.project_id)}catch(u){console.error("Error extracting project_id from GOOGLE_APPLICATION_CREDENTIALS:",u)}if(!n)throw new Error("Project ID is required for Vertex AI. Set GOOGLE_CLOUD_PROJECT environment variable or ensure project_id is in GOOGLE_APPLICATION_CREDENTIALS file.");let i=await fv();return{body:Ty(e),config:{url:new URL(`/v1/projects/${n}/locations/${s}/publishers/anthropic/models/${e.model}:${e.stream?"streamRawPredict":"rawPredict"}`,`https://${s}-aiplatform.googleapis.com`).toString(),headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json"}}}}async transformRequestOut(e){return Dy(e)}async transformResponseOut(e){return Ry(e,this.name,this.logger)}};var Ta=class{name="cerebras";async transformRequestIn(e,r){let n=JSON.parse(JSON.stringify(e));return n.reasoning?delete n.reasoning:n.disable_reasoning=!1,{body:n,config:{headers:{Authorization:`Bearer ${r.apiKey}`,"Content-Type":"application/json"}}}}async transformResponseOut(e){return e}};var Da=class{name="streamoptions";async transformRequestIn(e){return e.stream&&(e.stream_options={include_usage:!0}),e}};var Ra=class{name="OpenAI";endPoint="/v1/chat/completions"};var xa=class{static TransformerName="customparams";options;constructor(e={}){this.options=e}async transformRequestIn(e){let r={...e},n=Object.entries(this.options);for(let[s,i]of n)if(s in r)if(typeof r[s]=="object"&&typeof i=="object"&&!Array.isArray(r[s])&&!Array.isArray(i)&&r[s]!==null&&i!==null)r[s]=this.deepMergeObjects(r[s],i);else continue;else r[s]=this.cloneValue(i);return r}async transformResponseOut(e){return e}deepMergeObjects(e,r){let n={...e};for(let[s,i]of Object.entries(r))s in n&&typeof n[s]=="object"&&typeof i=="object"&&!Array.isArray(n[s])&&!Array.isArray(i)&&n[s]!==null&&i!==null?n[s]=this.deepMergeObjects(n[s],i):n[s]=this.cloneValue(i);return n}cloneValue(e){if(e===null||typeof e!="object")return e;if(Array.isArray(e))return e.map(n=>this.cloneValue(n));let r={};for(let[n,s]of Object.entries(e))r[n]=this.cloneValue(s);return r}};var Oa=class{constructor(e){this.options=e}static TransformerName="vercel";endPoint="/v1/chat/completions";async transformRequestIn(e){return e.model.includes("claude")?e.messages.forEach(r=>{Array.isArray(r.content)&&r.content.forEach(n=>{n.type==="image_url"&&(n.image_url.url.startsWith("http")||(n.image_url.url=`data:${n.media_type};base64,${n.image_url.url}`),delete n.media_type)})}):e.messages.forEach(r=>{Array.isArray(r.content)?r.content.forEach(n=>{n.cache_control&&delete n.cache_control,n.type==="image_url"&&(n.image_url.url.startsWith("http")||(n.image_url.url=`data:${n.media_type};base64,${n.image_url.url}`),delete n.media_type)}):r.cache_control&&delete r.cache_control}),Object.assign(e,this.options||{}),e}async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let r=await e.json();return new Response(JSON.stringify(r),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let r=new TextDecoder,n=new TextEncoder,s=!1,i="",u=!1,c=!1,l="",h=new ReadableStream({async start(d){let p=e.body.getReader(),w=(S,y,g)=>{let m=S.split(`
|
|
261
|
+
`);for(let v of m)v.trim()&&y.enqueue(g.encode(v+`
|
|
262
|
+
`))},T=(S,y)=>{let{controller:g,encoder:m}=y;if(S.startsWith("data: ")&&S.trim()!=="data: [DONE]"){let v=S.slice(6);try{let b=JSON.parse(v);if(b.usage&&(this.logger?.debug({usage:b.usage,hasToolCall:c},"usage"),b.choices[0].finish_reason=c?"tool_calls":"stop"),b.choices?.[0]?.finish_reason==="error"&&g.enqueue(m.encode(`data: ${JSON.stringify({error:b.choices?.[0].error})}
|
|
263
263
|
|
|
264
264
|
`)),b.choices?.[0]?.delta?.content&&!y.hasTextContent()&&y.setHasTextContent(!0),b.choices?.[0]?.delta?.reasoning){y.appendReasoningContent(b.choices[0].delta.reasoning);let R={...b,choices:[{...b.choices?.[0],delta:{...b.choices[0].delta,thinking:{content:b.choices[0].delta.reasoning}}}]};R.choices?.[0]?.delta&&delete R.choices[0].delta.reasoning;let F=`data: ${JSON.stringify(R)}
|
|
265
265
|
|
|
266
266
|
`;g.enqueue(m.encode(F));return}if(b.choices?.[0]?.delta?.content&&y.reasoningContent()&&!y.isReasoningComplete()){y.setReasoningComplete(!0);let R=Date.now().toString(),F={...b,choices:[{...b.choices?.[0],delta:{...b.choices[0].delta,content:null,thinking:{content:y.reasoningContent(),signature:R}}}]};F.choices?.[0]?.delta&&delete F.choices[0].delta.reasoning;let $=`data: ${JSON.stringify(F)}
|
|
267
267
|
|
|
268
|
-
`;g.enqueue(m.encode($))}b.choices?.[0]?.delta?.reasoning&&delete b.choices[0].delta.reasoning,b.choices?.[0]?.delta?.tool_calls?.length&&!Number.isNaN(parseInt(b.choices?.[0]?.delta?.tool_calls[0].id,10))&&b.choices?.[0]?.delta?.tool_calls.forEach(R=>{R.id=`call_${
|
|
268
|
+
`;g.enqueue(m.encode($))}b.choices?.[0]?.delta?.reasoning&&delete b.choices[0].delta.reasoning,b.choices?.[0]?.delta?.tool_calls?.length&&!Number.isNaN(parseInt(b.choices?.[0]?.delta?.tool_calls[0].id,10))&&b.choices?.[0]?.delta?.tool_calls.forEach(R=>{R.id=`call_${Jt()}`}),b.choices?.[0]?.delta?.tool_calls?.length&&!c&&(c=!0),b.choices?.[0]?.delta?.tool_calls?.length&&y.hasTextContent()&&(typeof b.choices[0].index=="number"?b.choices[0].index+=1:b.choices[0].index=1);let A=`data: ${JSON.stringify(b)}
|
|
269
269
|
|
|
270
|
-
`;g.enqueue(m.encode(
|
|
270
|
+
`;g.enqueue(m.encode(A))}catch{g.enqueue(m.encode(S+`
|
|
271
271
|
`))}}else g.enqueue(m.encode(S+`
|
|
272
|
-
`))};try{for(;;){let{done:S,value:y}=await p.read();if(S){l.trim()&&
|
|
273
|
-
`);l=
|
|
272
|
+
`))};try{for(;;){let{done:S,value:y}=await p.read();if(S){l.trim()&&w(l,d,n);break}if(!y||y.length===0)continue;let g;try{g=r.decode(y,{stream:!0})}catch(v){console.warn("Failed to decode chunk",v);continue}if(g.length===0)continue;if(l+=g,l.length>1e6){console.warn("Buffer size exceeds limit, processing partial data");let v=l.split(`
|
|
273
|
+
`);l=v.pop()||"";for(let b of v)if(b.trim())try{T(b,{controller:d,encoder:n,hasTextContent:()=>s,setHasTextContent:A=>s=A,reasoningContent:()=>i,appendReasoningContent:A=>i+=A,isReasoningComplete:()=>u,setReasoningComplete:A=>u=A})}catch(A){console.error("Error processing line:",b,A),d.enqueue(n.encode(b+`
|
|
274
274
|
`))}continue}let m=l.split(`
|
|
275
|
-
`);l=m.pop()||"";for(let
|
|
276
|
-
`))}}}catch(S){console.error("Stream error:",S),d.error(S)}finally{try{p.releaseLock()}catch(S){console.error("Error releasing reader lock:",S)}d.close()}}});return new Response(h,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}};var
|
|
275
|
+
`);l=m.pop()||"";for(let v of m)if(v.trim())try{T(v,{controller:d,encoder:n,hasTextContent:()=>s,setHasTextContent:b=>s=b,reasoningContent:()=>i,appendReasoningContent:b=>i+=b,isReasoningComplete:()=>u,setReasoningComplete:b=>u=b})}catch(b){console.error("Error processing line:",v,b),d.enqueue(n.encode(v+`
|
|
276
|
+
`))}}}catch(S){console.error("Stream error:",S),d.error(S)}finally{try{p.releaseLock()}catch(S){console.error("Error releasing reader lock:",S)}d.close()}}});return new Response(h,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}};var Fa=class{name="openai-responses";endPoint="/v1/responses";async transformRequestIn(e){delete e.temperature,delete e.max_tokens,e.reasoning&&(e.reasoning={effort:e.reasoning.effort,summary:"detailed"});let r=[],n=e.messages.filter(s=>s.role==="system");if(n.length>0){let s=n[0];Array.isArray(s.content)?s.content.forEach(i=>{let u="";typeof i=="string"?u=i:i&&typeof i=="object"&&"text"in i&&(u=i.text),r.push({role:"system",content:u})}):e.instructions=s.content}if(e.messages.forEach(s=>{if(s.role!=="system"){if(Array.isArray(s.content)){let i=s.content.map(u=>this.normalizeRequestContent(u,s.role)).filter(u=>u!==null);i.length>0?s.content=i:delete s.content}if(s.role==="tool"){let i={...s};i.type="function_call_output",i.call_id=s.tool_call_id,i.output=s.content,delete i.cache_control,delete i.role,delete i.tool_call_id,delete i.content,r.push(i);return}if(s.role==="assistant"&&Array.isArray(s.tool_calls)){s.tool_calls.forEach(i=>{r.push({type:"function_call",arguments:i.function.arguments,name:i.function.name,call_id:i.id})});return}r.push(s)}}),e.input=r,delete e.messages,Array.isArray(e.tools)){let s=e.tools.find(i=>i.function.name==="web_search");e.tools=e.tools.filter(i=>i.function.name!=="web_search").map(i=>(i.function.name==="WebSearch"&&delete i.function.parameters.properties.allowed_domains,i.function.name==="Edit"?{type:i.type,name:i.function.name,description:i.function.description,parameters:{...i.function.parameters,required:["file_path","old_string","new_string","replace_all"]},strict:!0}:{type:i.type,name:i.function.name,description:i.function.description,parameters:i.function.parameters})),s&&e.tools.push({type:"web_search"})}return e.parallel_tool_calls=!1,e}async transformResponseOut(e){let r=e.headers.get("Content-Type")||"";if(r.includes("application/json")){let n=await e.json();if(n.object==="response"&&n.output){let s=this.convertResponseToChat(n);return new Response(JSON.stringify(s),{status:e.status,statusText:e.statusText,headers:e.headers})}return new Response(JSON.stringify(n),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(r.includes("text/event-stream")){if(!e.body)return e;let n=new TextDecoder,s=new TextEncoder,i="",u=!1,c=this,l=new ReadableStream({async start(h){let d=e.body.getReader(),p=-1,w="",T=S=>(S!==w&&(p++,w=S),p);try{for(;;){let{done:S,value:y}=await d.read();if(S){u||h.enqueue(s.encode(`data: [DONE]
|
|
277
277
|
|
|
278
|
-
`));break}let g=n.decode(y,{stream:!0});i+=g;let m=i.split(/\r?\n/);i=m.pop()||"";for(let
|
|
278
|
+
`));break}let g=n.decode(y,{stream:!0});i+=g;let m=i.split(/\r?\n/);i=m.pop()||"";for(let v of m)if(v.trim())try{if(v.startsWith("event: "))continue;if(v.startsWith("data: ")){let b=v.slice(5).trim();if(b==="[DONE]"){u=!0,h.enqueue(s.encode(`data: [DONE]
|
|
279
279
|
|
|
280
|
-
`));continue}try{let
|
|
280
|
+
`));continue}try{let A=JSON.parse(b);if(A.type==="response.output_text.delta"){let R={id:A.item_id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:A.response?.model,choices:[{index:T(A.type),delta:{content:A.delta||""},finish_reason:null}]};h.enqueue(s.encode(`data: ${JSON.stringify(R)}
|
|
281
281
|
|
|
282
|
-
`))}else if(
|
|
282
|
+
`))}else if(A.type==="response.output_item.added"&&A.item?.type==="function_call"){let R={id:A.item.call_id||A.item.id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:A.response?.model||"gpt-5-codex-",choices:[{index:T(A.type),delta:{role:"assistant",tool_calls:[{index:0,id:A.item.call_id||A.item.id,function:{name:A.item.name||"",arguments:""},type:"function"}]},finish_reason:null}]};h.enqueue(s.encode(`data: ${JSON.stringify(R)}
|
|
283
283
|
|
|
284
|
-
`))}else if(
|
|
284
|
+
`))}else if(A.type==="response.output_item.added"&&A.item?.type==="message"){let R=[];(A.item.content||[]).forEach($=>{$.type==="output_text"&&R.push({type:"text",text:$.text||""})});let F={role:"assistant"};if(R.length===1&&R[0].type==="text"?F.content=R[0].text:R.length>0&&(F.content=R),F.content){let $={id:A.item.id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:A.response?.model,choices:[{index:T(A.type),delta:F,finish_reason:null}]};h.enqueue(s.encode(`data: ${JSON.stringify($)}
|
|
285
285
|
|
|
286
|
-
`))}}else if(
|
|
286
|
+
`))}}else if(A.type==="response.output_text.annotation.added"){let R={id:A.item_id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:A.response?.model||"gpt-5-codex",choices:[{index:T(A.type),delta:{annotations:[{type:"url_citation",url_citation:{url:A.annotation?.url||"",title:A.annotation?.title||"",content:"",start_index:A.annotation?.start_index||0,end_index:A.annotation?.end_index||0}}]},finish_reason:null}]};h.enqueue(s.encode(`data: ${JSON.stringify(R)}
|
|
287
287
|
|
|
288
|
-
`))}else if(
|
|
288
|
+
`))}else if(A.type==="response.function_call_arguments.delta"){let R={id:A.item_id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:A.response?.model||"gpt-5-codex-",choices:[{index:T(A.type),delta:{tool_calls:[{index:0,function:{arguments:A.delta||""}}]},finish_reason:null}]};h.enqueue(s.encode(`data: ${JSON.stringify(R)}
|
|
289
289
|
|
|
290
|
-
`))}else if(
|
|
290
|
+
`))}else if(A.type==="response.completed"){let R=A.response?.output?.some($=>$.type==="function_call")?"tool_calls":"stop",F={id:A.response?.id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:A.response?.model||"gpt-5-codex-",choices:[{index:0,delta:{},finish_reason:R}]};h.enqueue(s.encode(`data: ${JSON.stringify(F)}
|
|
291
291
|
|
|
292
|
-
`)),u=!0}else if(
|
|
292
|
+
`)),u=!0}else if(A.type==="response.reasoning_summary_text.delta"){let R={id:A.item_id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:A.response?.model,choices:[{index:T(A.type),delta:{thinking:{content:A.delta||""}},finish_reason:null}]};h.enqueue(s.encode(`data: ${JSON.stringify(R)}
|
|
293
293
|
|
|
294
|
-
`))}else if(
|
|
294
|
+
`))}else if(A.type==="response.reasoning_summary_part.done"&&A.part){let R={id:A.item_id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:A.response?.model,choices:[{index:p,delta:{thinking:{signature:A.item_id}},finish_reason:null}]};h.enqueue(s.encode(`data: ${JSON.stringify(R)}
|
|
295
295
|
|
|
296
|
-
`))}}catch{h.enqueue(s.encode(
|
|
297
|
-
`))}}else h.enqueue(s.encode(
|
|
298
|
-
`))}catch(b){console.error("Error processing line:",
|
|
296
|
+
`))}}catch{h.enqueue(s.encode(v+`
|
|
297
|
+
`))}}else h.enqueue(s.encode(v+`
|
|
298
|
+
`))}catch(b){console.error("Error processing line:",v,b),h.enqueue(s.encode(v+`
|
|
299
299
|
`))}}i.trim()&&h.enqueue(s.encode(i+`
|
|
300
300
|
`)),u||h.enqueue(s.encode(`data: [DONE]
|
|
301
301
|
|
|
302
|
-
`))}catch(S){console.error("Stream error:",S),h.error(S)}finally{try{d.releaseLock()}catch(S){console.error("Error releasing reader lock:",S)}h.close()}}});return new Response(l,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive","Access-Control-Allow-Origin":"*"}})}return e}normalizeRequestContent(e,r){let n={...e};if(delete n.cache_control,e.type==="text")return{type:r==="assistant"?"output_text":"input_text",text:e.text};if(e.type==="image_url"){console.log(e);let s={type:r==="assistant"?"output_image":"input_image"};return typeof e.image_url?.url=="string"&&(s.image_url=e.image_url.url),s}return null}convertResponseToChat(e){let r=e.output?.find(h=>h.type==="message"),n=e.output?.find(h=>h.type==="function_call"),s;r?.content?.length&&r?.content[0].annotations&&(s=r.content[0].annotations.map(h=>({type:"url_citation",url_citation:{url:h.url||"",title:h.title||"",content:"",start_index:h.start_index||0,end_index:h.end_index||0}}))),this.logger.debug({data:s,type:"url_citation"});let i=null,u=null,c=null;if(r&&r.reasoning&&(c={content:r.reasoning}),r&&r.content){let h=[],d=[];if(r.content.forEach(p=>{if(p.type==="output_text")h.push(p.text||"");else if(p.type==="output_image"){let
|
|
302
|
+
`))}catch(S){console.error("Stream error:",S),h.error(S)}finally{try{d.releaseLock()}catch(S){console.error("Error releasing reader lock:",S)}h.close()}}});return new Response(l,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive","Access-Control-Allow-Origin":"*"}})}return e}normalizeRequestContent(e,r){let n={...e};if(delete n.cache_control,e.type==="text")return{type:r==="assistant"?"output_text":"input_text",text:e.text};if(e.type==="image_url"){console.log(e);let s={type:r==="assistant"?"output_image":"input_image"};return typeof e.image_url?.url=="string"&&(s.image_url=e.image_url.url),s}return null}convertResponseToChat(e){let r=e.output?.find(h=>h.type==="message"),n=e.output?.find(h=>h.type==="function_call"),s;r?.content?.length&&r?.content[0].annotations&&(s=r.content[0].annotations.map(h=>({type:"url_citation",url_citation:{url:h.url||"",title:h.title||"",content:"",start_index:h.start_index||0,end_index:h.end_index||0}}))),this.logger.debug({data:s,type:"url_citation"});let i=null,u=null,c=null;if(r&&r.reasoning&&(c={content:r.reasoning}),r&&r.content){let h=[],d=[];if(r.content.forEach(p=>{if(p.type==="output_text")h.push(p.text||"");else if(p.type==="output_image"){let w=this.buildImageContent({url:p.image_url,mime_type:p.mime_type});w&&d.push(w)}else if(p.type==="output_image_base64"){let w=this.buildImageContent({b64_json:p.image_base64,mime_type:p.mime_type});w&&d.push(w)}}),d.length>0){let p=[];h.length>0&&p.push({type:"text",text:h.join("")}),p.push(...d),i=p}else i=h.join("")}return n&&(u=[{id:n.call_id||n.id,function:{name:n.name,arguments:n.arguments},type:"function"}]),{id:e.id||"chatcmpl-"+Date.now(),object:"chat.completion",created:e.created_at,model:e.model,choices:[{index:0,message:{role:"assistant",content:i||null,tool_calls:u,thinking:c,annotations:s},logprobs:null,finish_reason:u?"tool_calls":"stop"}],usage:e.usage?{prompt_tokens:e.usage.input_tokens||0,completion_tokens:e.usage.output_tokens||0,total_tokens:e.usage.total_tokens||0}:null}}buildImageContent(e){return e&&(e.url||e.b64_json)?{type:"image_url",image_url:{url:e.url||"",b64_json:e.b64_json},media_type:e.mime_type}:null}};var dd=`Always think before answering. Even if the problem seems simple, always write down your reasoning process explicitly.
|
|
303
303
|
|
|
304
304
|
Output format:
|
|
305
305
|
<reasoning_content>
|
|
306
306
|
Your detailed thinking process goes here
|
|
307
307
|
</reasoning_content>
|
|
308
|
-
Your final answer must follow after the closing tag above.`,
|
|
309
|
-
${s.content}`),delete s.thinking)});let n=e.messages[e.messages.length-1];return n.role==="user"&&(Array.isArray(n.content)?n.content.push({type:"text",text:
|
|
308
|
+
Your final answer must follow after the closing tag above.`,hv=10,Pa=class{name="forcereasoning";async transformRequestIn(e){let r=0;e.messages.filter(s=>s.role==="assistant").reverse().forEach(s=>{s.thinking&&(s.thinking.content&&(!s.content||r<hv)&&(r++,s.content=`<reasoning_content>${s.thinking.content}</reasoning_content>
|
|
309
|
+
${s.content}`),delete s.thinking)});let n=e.messages[e.messages.length-1];return n.role==="user"&&(Array.isArray(n.content)?n.content.push({type:"text",text:dd}):n.content=[{type:"text",text:dd},{type:"text",text:n.content||""}]),n.role==="tool"&&e.messages.push({role:"user",content:[{type:"text",text:dd}]}),e}async transformResponseOut(e){let r="<reasoning_content>",n="</reasoning_content>";if(e.headers.get("Content-Type")?.includes("application/json")){let s=await e.json();if(s.choices[0]?.message.content){let i=/<reasoning_content>(.*?)<\/reasoning_content>/s,u=s.choices[0]?.message.content.match(i);u&&u[1]&&(s.thinking={content:u[1]})}return new Response(JSON.stringify(s),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let s=0,i=new TextDecoder,u=new TextEncoder,c=new ReadableStream({async start(l){let h=e.body.getReader(),d="",p="SEARCHING",w="",T="",S=(y,g)=>{if(typeof g!="string"){y.choices?.[0]?.delta&&Object.keys(y.choices[0].delta).length>0&&!y.choices[0].delta.content&&(y.choices[0].index=s,l.enqueue(u.encode(`data: ${JSON.stringify(y)}
|
|
310
310
|
|
|
311
|
-
`)));return}let m=
|
|
311
|
+
`)));return}let m=w+g;for(w="";m.length>0;)if(p==="SEARCHING"){let v=m.indexOf(r);if(v!==-1)m=m.substring(v+r.length),p="REASONING";else{for(let b=r.length-1;b>0;b--)if(m.endsWith(r.substring(0,b))){w=m.substring(m.length-b);break}m=""}}else if(p==="REASONING"){let v=m.indexOf(n);if(v!==-1){let b=m.substring(0,v);if(b.length>0){let F={...y.choices[0].delta,thinking:{content:b}};delete F.content;let $={...y,choices:[{...y.choices[0],delta:F,index:s}]};l.enqueue(u.encode(`data: ${JSON.stringify($)}
|
|
312
312
|
|
|
313
|
-
`))}let
|
|
313
|
+
`))}let A={...y.choices[0].delta,thinking:{signature:new Date().getTime().toString()}};delete A.content;let R={...y,choices:[{...y.choices[0],delta:A,index:s}]};l.enqueue(u.encode(`data: ${JSON.stringify(R)}
|
|
314
314
|
|
|
315
|
-
`)),s++,m=m.substring(
|
|
315
|
+
`)),s++,m=m.substring(v+n.length),p="FINAL"}else{let b=m;for(let A=n.length-1;A>0;A--)if(m.endsWith(n.substring(0,A))){w=m.substring(m.length-A),b=m.substring(0,m.length-A);break}if(b.length>0){let A={...y.choices[0].delta,thinking:{content:b}};delete A.content;let R={...y,choices:[{...y.choices[0],delta:A,index:s}]};l.enqueue(u.encode(`data: ${JSON.stringify(R)}
|
|
316
316
|
|
|
317
|
-
`))}m=""}}else if(p==="FINAL"){if(m.length>0)if(/^\s*$/.test(m))
|
|
317
|
+
`))}m=""}}else if(p==="FINAL"){if(m.length>0)if(/^\s*$/.test(m))T+=m;else{let b=T+m,A={...y.choices[0].delta,content:b};A.thinking&&delete A.thinking;let R={...y,choices:[{...y.choices[0],delta:A}]};l.enqueue(u.encode(`data: ${JSON.stringify(R)}
|
|
318
318
|
|
|
319
|
-
`)),
|
|
320
|
-
`);d=
|
|
319
|
+
`)),T=""}s++,m=""}};try{for(;;){let{done:y,value:g}=await h.read();if(y)break;let m=i.decode(g,{stream:!0});d+=m;let v=d.split(`
|
|
320
|
+
`);d=v.pop()||"";for(let b of v)if(b.trim()){if(b.trim()==="data: [DONE]"){l.enqueue(u.encode(b+`
|
|
321
321
|
|
|
322
|
-
`));break}if(b.startsWith("data:"))try{let
|
|
322
|
+
`));break}if(b.startsWith("data:"))try{let A=JSON.parse(b.slice(5));S(A,A.choices?.[0]?.delta?.content)}catch{l.enqueue(u.encode(b+`
|
|
323
323
|
`))}else l.enqueue(u.encode(b+`
|
|
324
324
|
`))}}}catch(y){console.error("Stream error:",y),l.error(y)}finally{try{h.releaseLock()}catch(y){console.error("Error releasing reader lock:",y)}if(p==="REASONING"){let g={choices:[{delta:{thinking:{signature:new Date().getTime().toString()}}}]};l.enqueue(u.encode(`data: ${JSON.stringify(g)}
|
|
325
325
|
|
|
326
|
-
`))}l.close()}}});return new Response(c,{status:e.status,statusText:e.statusText,headers:{"Content-Type":e.headers.get("Content-Type")||"text/plain","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}};var
|
|
327
|
-
`));break}let
|
|
328
|
-
`);u=
|
|
326
|
+
`))}l.close()}}});return new Response(c,{status:e.status,statusText:e.statusText,headers:{"Content-Type":e.headers.get("Content-Type")||"text/plain","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}};var Ia=class{name="kimi";async transformRequestIn(e){return(e.thinking||e.reasoning?.enabled||e.messages.some(n=>n.thinking?.content))&&e.messages.forEach(n=>{if(n.role==="assistant"){let s=n.thinking?.content,i=n.thinking?.signature;s&&typeof s=="string"&&s.trim()&&(n.reasoning_content=s,i&&(n.reasoning_content_signature=i)),n.tool_calls&&n.tool_calls.length>0&&(n.reasoning_content||(n.reasoning_content="")),n.thinking&&delete n.thinking}}),e}async transformResponseOut(e){let r=e.headers.get("Content-Type");if(r?.includes("stream")){if(!e.body)return e;let n=new TextDecoder,s=new TextEncoder,i="",u="",c=new ReadableStream({async start(l){let h=e.body.getReader();try{for(;;){let{done:d,value:p}=await h.read();if(d){u.trim()&&l.enqueue(s.encode(u+`
|
|
327
|
+
`));break}let w=n.decode(p,{stream:!0});u+=w;let T=u.split(`
|
|
328
|
+
`);u=T.pop()||"";for(let S of T)if(S.trim())if(S.startsWith("data: ")&&S.trim()!=="data: [DONE]")try{let y=JSON.parse(S.slice(6));if(y.choices?.[0]?.delta?.reasoning_content){i+=y.choices[0].delta.reasoning_content;let g={...y,choices:[{...y.choices[0],delta:{thinking:{content:y.choices[0].delta.reasoning_content}}}]};delete g.choices[0].delta.reasoning_content,l.enqueue(s.encode(`data: ${JSON.stringify(g)}
|
|
329
329
|
|
|
330
330
|
`));continue}if(y.choices?.[0]?.delta?.content&&i&&!y.choices[0]?.delta?.reasoning_content){let g=Date.now().toString(),m={...y,choices:[{...y.choices[0],delta:{content:null,thinking:{content:i,signature:g}}}]};l.enqueue(s.encode(`data: ${JSON.stringify(m)}
|
|
331
331
|
|
|
@@ -333,18 +333,18 @@ ${s.content}`),delete s.thinking)});let n=e.messages[e.messages.length-1];return
|
|
|
333
333
|
|
|
334
334
|
`))}catch{l.enqueue(s.encode(S+`
|
|
335
335
|
`))}else l.enqueue(s.encode(S+`
|
|
336
|
-
`))}}catch(d){l.error(d)}finally{try{h.releaseLock()}catch{}l.close()}}});return new Response(c,{status:e.status,statusText:e.statusText,headers:{"Content-Type":r||"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}if(r?.includes("application/json")){let n=await e.json();return n.choices?.[0]?.message?.reasoning_content&&(n.choices[0].message.thinking={content:n.choices[0].message.reasoning_content},delete n.choices[0].message.reasoning_content),new Response(JSON.stringify(n),{status:e.status,statusText:e.statusText,headers:e.headers})}return e}};var
|
|
336
|
+
`))}}catch(d){l.error(d)}finally{try{h.releaseLock()}catch{}l.close()}}});return new Response(c,{status:e.status,statusText:e.statusText,headers:{"Content-Type":r||"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}if(r?.includes("application/json")){let n=await e.json();return n.choices?.[0]?.message?.reasoning_content&&(n.choices[0].message.thinking={content:n.choices[0].message.reasoning_content},delete n.choices[0].message.reasoning_content),new Response(JSON.stringify(n),{status:e.status,statusText:e.statusText,headers:e.headers})}return e}};var xy={AnthropicTransformer:Wo,GeminiTransformer:Ko,VertexGeminiTransformer:pa,VertexClaudeTransformer:ka,DeepseekTransformer:ma,TooluseTransformer:ga,OpenrouterTransformer:ya,OpenAITransformer:Ra,MaxTokenTransformer:_a,GroqTransformer:ba,CleancacheTransformer:Ca,EnhanceToolTransformer:Ea,ReasoningTransformer:Aa,SamplingTransformer:Sa,MaxCompletionTokens:va,CerebrasTransformer:Ta,StreamOptionsTransformer:Da,CustomParamsTransformer:xa,VercelTransformer:Oa,OpenAIResponsesTransformer:Fa,ForceReasoningTransformer:Pa,KimiTransformer:Ia};var us=class{constructor(e,r){this.configService=e;this.logger=r}transformers=new Map;registerTransformer(e,r){this.transformers.set(e,r),this.logger.info(`register transformer: ${e}${r.endPoint?` (endpoint: ${r.endPoint})`:" (no endpoint)"}`)}getTransformer(e){return this.transformers.get(e)}getAllTransformers(){return new Map(this.transformers)}getTransformersWithEndpoint(){let e=[];return this.transformers.forEach((r,n)=>{typeof r=="object"&&r.endPoint&&e.push({name:n,transformer:r})}),e}getTransformersWithoutEndpoint(){let e=[];return this.transformers.forEach((r,n)=>{typeof r=="object"&&!r.endPoint&&e.push({name:n,transformer:r})}),e}removeTransformer(e){return this.transformers.delete(e)}hasTransformer(e){return this.transformers.has(e)}async registerTransformerFromConfig(e){try{if(e.path){let r=X(X.resolve(e.path));if(r){let n=new r(e.options);if(n&&typeof n=="object"&&(n.logger=this.logger),!n.name)throw new Error(`Transformer instance from ${e.path} does not have a name property.`);return this.registerTransformer(n.name,n),!0}}return!1}catch(r){return this.logger.error(`load transformer (${e.path})
|
|
337
337
|
error: ${r.message}
|
|
338
338
|
stack: ${r.stack}`),!1}}async initialize(){try{await this.registerDefaultTransformersInternal(),await this.loadFromConfig()}catch(e){this.logger.error(`TransformerService init error: ${e.message}
|
|
339
|
-
Stack: ${e.stack}`)}}async registerDefaultTransformersInternal(){try{Object.values(
|
|
340
|
-
`:case"\r":return!1;default:return new RegExp("^\\p{Cc}|\\p{Cf}|\\p{Co}|\\p{Cs}$","u").test(t)}}clean_text(t){let e=[];for(let r of t){let n=r.charCodeAt(0);n===0||n===65533||this.is_control(r)||(/^\s$/.test(r)?e.push(" "):e.push(r))}return e.join("")}normalize(t){return this.config.clean_text&&(t=this.clean_text(t)),this.config.handle_chinese_chars&&(t=this.tokenize_chinese_chars(t)),this.config.lowercase?(t=t.toLowerCase(),this.config.strip_accents!==!1&&(t=this.strip_accents(t))):this.config.strip_accents&&(t=this.strip_accents(t)),t}},dk=fk,hk=class extends Er{constructor(t){super(t),this.charsmap=t.precompiled_charsmap??null}normalize(t){return t=t.replace(/[\u0001-\u0008\u000B\u000E-\u001F\u007F\u008F\u009F]/gm,""),t=t.replace(/[\u0009\u000A\u000C\u000D\u00A0\u1680\u2000-\u200F\u2028\u2029\u202F\u205F\u2581\u3000\uFEFF\uFFFD]/gm," "),t.includes("\uFF5E")?t=t.split("\uFF5E").map(e=>e.normalize("NFKC")).join("\uFF5E"):t=t.normalize("NFKC"),t}},pk=hk,mk=class extends Er{constructor(t){super(t),this.normalizers=(t.normalizers??[]).map(e=>Sy(e))}normalize(t){return this.normalizers.reduce((e,r)=>r?r.normalize(e):e,t)}},gk=mk,yk=class extends Er{normalize(t){let e=xa(this.config.pattern??{});return e===null?t:t.replaceAll(e,this.config.content??"")}},_k=yk,bk=class extends Er{constructor(){super(...arguments),this.form="NFC"}normalize(t){return t=t.normalize(this.form),t}},Fa=bk,Ck=class extends Fa{constructor(){super(...arguments),this.form="NFC"}},wk=Ck,Ek=class extends Fa{constructor(){super(...arguments),this.form="NFD"}},Ak=Ek,Sk=class extends Fa{constructor(){super(...arguments),this.form="NFKC"}},kk=Sk,Tk=class extends Fa{constructor(){super(...arguments),this.form="NFKD"}},Dk=Tk,vk=class extends Er{normalize(t){return this.config.strip_left&&this.config.strip_right?t=t.trim():(this.config.strip_left&&(t=t.trimStart()),this.config.strip_right&&(t=t.trimEnd())),t}},Rk=vk,Ok=class extends Er{normalize(t){return Ay(t)}},xk=Ok,Fk=class extends Er{normalize(t){return t.toLowerCase()}},Pk=Fk,Ik=class extends Er{normalize(t){return t=this.config.prepend+t,t}},Nk=Ik;function Bk(t){if(t===null)return null;switch(t.type){case"BertNormalizer":return new dk(t);case"Precompiled":return new pk(t);case"Sequence":return new gk(t);case"Replace":return new _k(t);case"NFC":return new wk(t);case"NFD":return new Ak(t);case"NFKC":return new kk(t);case"NFKD":return new Dk(t);case"Strip":return new Rk(t);case"StripAccents":return new xk(t);case"Lowercase":return new Pk(t);case"Prepend":return new Nk(t);default:throw new Error(`Unknown Normalizer type: ${t.type}`)}}var Sy=Bk,jk=class extends Zs{pre_tokenize(t,e){return(Array.isArray(t)?t.map(r=>this.pre_tokenize_text(r,e)):this.pre_tokenize_text(t,e)).flat()}_call(t,e){return this.pre_tokenize(t,e)}},sr=jk,Lk=class extends sr{constructor(t){super(),this.config=t,this.add_prefix_space=this.config.add_prefix_space??!1,this.trim_offsets=this.config.trim_offsets??!1,this.use_regex=this.config.use_regex??!0,this.pattern=new RegExp("'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)|\\s+","gu"),this.byte_encoder=Ey,this.text_encoder=new TextEncoder}pre_tokenize_text(t,e){return this.add_prefix_space&&!t.startsWith(" ")&&(t=" "+t),(this.use_regex?t.match(this.pattern)||[]:[t]).map(r=>Array.from(this.text_encoder.encode(r),n=>this.byte_encoder[n]).join(""))}},Mk=Lk,Uk=class extends sr{pre_tokenize_text(t,e){return t.match(/\w+|[^\w\s]+/g)||[]}},qk=Uk,$k=class extends sr{constructor(t){super(),this.replacement=t.replacement??"\u2581",this.str_rep=t.str_rep||this.replacement,this.prepend_scheme=t.prepend_scheme??"always"}pre_tokenize_text(t,e){let{section_index:r=void 0}=e??{},n=t.replaceAll(" ",this.str_rep);return!n.startsWith(this.replacement)&&(this.prepend_scheme==="always"||this.prepend_scheme==="first"&&r===0)&&(n=this.str_rep+n),[n]}},zk=$k,Hk=class extends sr{constructor(t){super(),this.config=t,this.pattern=xa(this.config.pattern??{},this.config.invert??!0)}pre_tokenize_text(t){return this.pattern===null?[]:this.config.invert?t.match(this.pattern)||[]:this.config.behavior?.toLowerCase()==="removed"?t.split(this.pattern).filter(e=>e):ak(t,this.pattern)}},Wk=Hk,Gk=class extends sr{constructor(t){super(),this.config=t,this.pattern=new RegExp(`[^${Qs}]+|[${Qs}]+`,"gu")}pre_tokenize_text(t){return t.match(this.pattern)||[]}},Jk=Gk,Vk=class extends sr{constructor(t){super(),this.config=t;let e=`[^\\d]+|\\d${this.config.individual_digits?"":"+"}`;this.pattern=new RegExp(e,"gu")}pre_tokenize_text(t){return t.match(this.pattern)||[]}},Kk=Vk,Yk=class extends sr{constructor(){super(),this.pattern=new RegExp(`[^\\s${Qs}]+|[${Qs}]`,"gu")}pre_tokenize_text(t,e){return t.trim().match(this.pattern)||[]}},Xk=Yk,Qk=class extends sr{constructor(t){super(),this.config=t,this.pattern=xa(this.config.pattern??{}),this.content=this.config.content??""}pre_tokenize_text(t){return this.pattern===null?[t]:[t.replaceAll(this.pattern,this.config.content??"")]}},Zk=Qk,eT=class extends sr{constructor(t){super(),this.tokenizers=(t.pretokenizers??[]).map(e=>ky(e))}pre_tokenize_text(t,e){return this.tokenizers.reduce((r,n)=>n?n.pre_tokenize(r,e):r,[t])}},tT=eT,rT=class extends sr{pre_tokenize_text(t){return uk(t)}},nT=rT;function sT(t){if(t===null)return null;switch(t.type){case"BertPreTokenizer":return new Xk;case"Sequence":return new tT(t);case"Whitespace":return new qk;case"WhitespaceSplit":return new nT;case"Metaspace":return new zk(t);case"ByteLevel":return new Mk(t);case"Split":return new Wk(t);case"Punctuation":return new Jk(t);case"Digits":return new Kk(t);case"Replace":return new Zk(t);default:throw new Error(`Unknown PreTokenizer type: ${t.type}`)}}var ky=sT,oT=class extends Zs{constructor(t){super(),this.config=t,this.vocab=[],this.tokens_to_ids=new Map,this.unk_token_id=void 0,this.unk_token=void 0,this.end_of_word_suffix=void 0,this.fuse_unk=this.config.fuse_unk??!1}_call(t){let e=this.encode(t);return this.fuse_unk&&(e=rk(e,this.tokens_to_ids,this.unk_token_id)),e}convert_tokens_to_ids(t){return t.map(e=>this.tokens_to_ids.get(e)??this.unk_token_id)}convert_ids_to_tokens(t){return t.map(e=>this.vocab[Number(e)]??this.unk_token)}},Pa=oT,iT=class extends Pa{constructor(t){super(t),this.max_input_chars_per_word=100,this.tokens_to_ids=lf(t.vocab),this.unk_token_id=this.tokens_to_ids.get(t.unk_token),this.unk_token=t.unk_token,this.max_input_chars_per_word=t.max_input_chars_per_word??100,this.vocab=new Array(this.tokens_to_ids.size);for(let[e,r]of this.tokens_to_ids)this.vocab[r]=e}encode(t){let e=[];for(let r of t){let n=[...r];if(n.length>this.max_input_chars_per_word){e.push(this.unk_token);continue}let s=!1,i=0,u=[];for(;i<n.length;){let c=n.length,l=null;for(;i<c;){let h=n.slice(i,c).join("");if(i>0&&(h=this.config.continuing_subword_prefix+h),this.tokens_to_ids.has(h)){l=h;break}--c}if(l===null){s=!0;break}u.push(l),i=c}s?e.push(this.unk_token):e.push(...u)}return e}},_y=iT,by=class Ty{constructor(e,r){this.is_leaf=e,this.children=r}static default(){return new Ty(!1,new Map)}},aT=class{constructor(){this.root=by.default()}extend(t){for(let e of t)this.push(e)}push(t){let e=this.root;for(let r of t){let n=e.children.get(r);n===void 0&&(n=by.default(),e.children.set(r,n)),e=n}e.is_leaf=!0}*common_prefix_search(t){let e=this.root;if(e===void 0)return;let r="";for(let n of t){if(r+=n,e=e.children.get(n),e===void 0)return;e.is_leaf&&(yield r)}}},uT=aT,uf=class Dy{constructor(e,r,n,s,i){this.token_id=e,this.node_id=r,this.pos=n,this.length=s,this.score=i,this.prev=null,this.backtrace_score=0}clone(){let e=new Dy(this.token_id,this.node_id,this.pos,this.length,this.score);return e.prev=this.prev,e.backtrace_score=this.backtrace_score,e}},cT=class{constructor(t,e,r){this.chars=Array.from(t),this.len=this.chars.length,this.bos_token_id=e,this.eos_token_id=r,this.nodes=[],this.begin_nodes=Array.from({length:this.len+1},()=>[]),this.end_nodes=Array.from({length:this.len+1},()=>[]);let n=new uf(this.bos_token_id??0,0,0,0,0),s=new uf(this.eos_token_id??0,1,this.len,0,0);this.nodes.push(n.clone()),this.nodes.push(s.clone()),this.begin_nodes[this.len].push(s),this.end_nodes[0].push(n)}insert(t,e,r,n){let s=this.nodes.length,i=new uf(n,s,t,e,r);this.begin_nodes[t].push(i),this.end_nodes[t+e].push(i),this.nodes.push(i)}viterbi(){let t=this.len,e=0;for(;e<=t;){if(this.begin_nodes[e].length==0)return[];for(let i of this.begin_nodes[e]){i.prev=null;let u=0,c=null;for(let l of this.end_nodes[e]){let h=l.backtrace_score+i.score;(c===null||h>u)&&(c=l.clone(),u=h)}if(c!==null)i.prev=c,i.backtrace_score=u;else return[]}++e}let r=[],n=this.begin_nodes[t][0].prev;if(n===null)return[];let s=n.clone();for(;s.prev!==null;)r.push(s.clone()),s=s.clone().prev.clone();return r.reverse(),r}piece(t){return this.chars.slice(t.pos,t.pos+t.length).join("")}tokens(){return this.viterbi().map(t=>this.piece(t))}token_ids(){return this.viterbi().map(t=>t.token_id)}},lT=cT;function fT(t){if(t.length===0)throw new Error("Array must not be empty");let e=t[0],r=0;for(let n=1;n<t.length;++n)t[n]<e&&(e=t[n],r=n);return[e,r]}var dT=class extends Pa{constructor(t,e){super(t);let r=t.vocab.length;this.vocab=new Array(r),this.scores=new Array(r);for(let n=0;n<r;++n)[this.vocab[n],this.scores[n]]=t.vocab[n];this.unk_token_id=t.unk_id,this.unk_token=this.vocab[t.unk_id],this.tokens_to_ids=new Map(this.vocab.map((n,s)=>[n,s])),this.bos_token=" ",this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=e,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.unk_token=this.vocab[this.unk_token_id],this.min_score=fT(this.scores)[0],this.unk_score=this.min_score-10,this.scores[this.unk_token_id]=this.unk_score,this.trie=new uT,this.trie.extend(this.vocab),this.fuse_unk=!0}populate_nodes(t){let e=t.chars,r=1,n=0;for(;n<e.length;){let s=!1,i=[],u=e.slice(n).join(""),c=this.trie.common_prefix_search(u);for(let l of c){i.push(l);let h=this.tokens_to_ids.get(l),d=this.scores[h],p=ok(l);t.insert(n,p,d,h),!s&&p===r&&(s=!0)}s||t.insert(n,r,this.unk_score,this.unk_token_id),n+=r}}tokenize(t){let e=new lT(t,this.bos_token_id,this.eos_token_id);return this.populate_nodes(e),e.tokens()}encode(t){let e=[];for(let r of t){let n=this.tokenize(r);e.push(...n)}return e}},Cy=dT,hT=class{constructor(t=(r,n)=>r>n,e=1/0){this._heap=[],this._comparator=t,this._max_size=e}get size(){return this._heap.length}is_empty(){return this.size===0}peek(){return this._heap[0]}push(...t){return this.extend(t)}extend(t){for(let e of t)if(this.size<this._max_size)this._heap.push(e),this._sift_up();else{let r=this._smallest();this._comparator(e,this._heap[r])&&(this._heap[r]=e,this._sift_up_from(r))}return this.size}pop(){let t=this.peek(),e=this.size-1;return e>0&&this._swap(0,e),this._heap.pop(),this._sift_down(),t}replace(t){let e=this.peek();return this._heap[0]=t,this._sift_down(),e}_parent(t){return(t+1>>>1)-1}_left(t){return(t<<1)+1}_right(t){return t+1<<1}_greater(t,e){return this._comparator(this._heap[t],this._heap[e])}_swap(t,e){let r=this._heap[t];this._heap[t]=this._heap[e],this._heap[e]=r}_sift_up(){this._sift_up_from(this.size-1)}_sift_up_from(t){for(;t>0&&this._greater(t,this._parent(t));)this._swap(t,this._parent(t)),t=this._parent(t)}_sift_down(){let t=0;for(;this._left(t)<this.size&&this._greater(this._left(t),t)||this._right(t)<this.size&&this._greater(this._right(t),t);){let e=this._right(t)<this.size&&this._greater(this._right(t),this._left(t))?this._right(t):this._left(t);this._swap(t,e),t=e}}_smallest(){return 2**Math.floor(Math.log2(this.size))-1}},pT=hT,mT=class{constructor(t){this.capacity=t,this.cache=new Map}get(t){if(!this.cache.has(t))return;let e=this.cache.get(t);return this.cache.delete(t),this.cache.set(t,e),e}put(t,e){this.cache.has(t)&&this.cache.delete(t),this.cache.set(t,e),this.cache.size>this.capacity&&this.cache.delete(this.cache.keys().next().value)}clear(){this.cache.clear()}},gT=mT,yT=class extends Pa{constructor(t){super(t),this.tokens_to_ids=lf(t.vocab),this.unk_token_id=this.tokens_to_ids.get(t.unk_token),this.unk_token=t.unk_token,this.vocab=new Array(this.tokens_to_ids.size);for(let[r,n]of this.tokens_to_ids)this.vocab[n]=r;let e=Array.isArray(t.merges[0]);this.merges=e?t.merges:t.merges.map(r=>r.split(" ",2)),this.bpe_ranks=new Map(this.merges.map((r,n)=>[JSON.stringify(r),n])),this.end_of_word_suffix=t.end_of_word_suffix,this.continuing_subword_suffix=t.continuing_subword_suffix??null,this.byte_fallback=this.config.byte_fallback??!1,this.byte_fallback&&(this.text_encoder=new TextEncoder),this.ignore_merges=this.config.ignore_merges??!1,this.max_length_to_cache=256,this.cache_capacity=1e4,this.cache=new gT(this.cache_capacity)}clear_cache(){this.cache.clear()}bpe(t){if(t.length===0)return[];let e=this.cache.get(t);if(e!==void 0)return e;let r=Array.from(t);this.end_of_word_suffix&&(r[r.length-1]+=this.end_of_word_suffix);let n=[];if(r.length>1){let s=new pT((c,l)=>c.score<l.score),i={token:r[0],bias:0,prev:null,next:null},u=i;for(let c=1;c<r.length;++c){let l={bias:c/r.length,token:r[c],prev:u,next:null};u.next=l,this.add_node(s,u),u=l}for(;!s.is_empty();){let c=s.pop();if(c.deleted||!c.next||c.next.deleted)continue;if(c.deleted=!0,c.next.deleted=!0,c.prev){let h={...c.prev};c.prev.deleted=!0,c.prev=h,h.prev?h.prev.next=h:i=h}let l={token:c.token+c.next.token,bias:c.bias,prev:c.prev,next:c.next.next};l.prev?(l.prev.next=l,this.add_node(s,l.prev)):i=l,l.next&&(l.next.prev=l,this.add_node(s,l))}for(let c=i;c!==null;c=c.next)n.push(c.token)}else n=r;if(this.continuing_subword_suffix)for(let s=0;s<n.length-1;++s)n[s]+=this.continuing_subword_suffix;return t.length<this.max_length_to_cache&&this.cache.put(t,n),n}add_node(t,e){let r=this.bpe_ranks.get(JSON.stringify([e.token,e.next.token]));r!==void 0&&(e.score=r+e.bias,t.push(e))}encode(t){let e=[];for(let r of t){if(this.ignore_merges&&this.tokens_to_ids.has(r)){e.push(r);continue}let n=this.bpe(r);for(let s of n)if(this.tokens_to_ids.has(s))e.push(s);else if(this.byte_fallback){let i=Array.from(this.text_encoder.encode(s)).map(u=>`<0x${u.toString(16).toUpperCase().padStart(2,"0")}>`);i.every(u=>this.tokens_to_ids.has(u))?e.push(...i):e.push(this.unk_token)}else e.push(this.unk_token)}return e}},wy=yT,_T=class extends Pa{constructor(t,e){super(t);let r=t.vocab;this.tokens_to_ids=lf(e.target_lang?r[e.target_lang]:r),this.bos_token=e.bos_token,this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=e.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.pad_token=e.pad_token,this.pad_token_id=this.tokens_to_ids.get(this.pad_token),this.unk_token=e.unk_token,this.unk_token_id=this.tokens_to_ids.get(this.unk_token),this.vocab=new Array(this.tokens_to_ids.size);for(let[n,s]of this.tokens_to_ids)this.vocab[s]=n}encode(t){return t}},bT=_T;function CT(t,e){switch(t.type){case"WordPiece":return new _y(t);case"Unigram":return new Cy(t,e.eos_token);case"BPE":return new wy(t);default:if(t.vocab)return Array.isArray(t.vocab)?new Cy(t,e.eos_token):Object.hasOwn(t,"continuing_subword_prefix")&&Object.hasOwn(t,"unk_token")?Object.hasOwn(t,"merges")?new wy(t):new _y(t):new bT(t,{target_lang:e.target_lang,bos_token:e.bos_token,eos_token:e.eos_token,pad_token:e.pad_token,unk_token:e.unk_token});throw new Error(`Unknown TokenizerModel type: ${t?.type}`)}}var wT=CT,ET=class extends Zs{constructor(t){super(),this.config=t}_call(t,...e){return this.post_process(t,...e)}},eo=ET,AT=class extends eo{post_process(t,e=null,r=!0){let n=e===null?this.config.single:this.config.pair,s=[],i=[];for(let u of n)"SpecialToken"in u?r&&(s.push(u.SpecialToken.id),i.push(u.SpecialToken.type_id)):"Sequence"in u&&(u.Sequence.id==="A"?(s=Ot(s,t),i=Ot(i,new Array(t.length).fill(u.Sequence.type_id))):u.Sequence.id==="B"&&(s=Ot(s,e),i=Ot(i,new Array(e.length).fill(u.Sequence.type_id))));return{tokens:s,token_type_ids:i}}},ST=AT,kT=class extends eo{post_process(t,e=null){return{tokens:e?Ot(t,e):t}}},TT=kT,DT=class extends eo{constructor(t){super(t),this.sep=t.sep,this.cls=t.cls}post_process(t,e=null,r=!0){r&&(t=Ot([this.cls[0]],t,[this.sep[0]]));let n=new Array(t.length).fill(0);if(e){let s=[],i=r?[this.sep[0]]:[];t=Ot(t,s,e,i),n=Ot(n,new Array(e.length+s.length+i.length).fill(1))}return{tokens:t,token_type_ids:n}}},vT=DT,RT=class extends eo{constructor(t){super(t),this.sep=t.sep,this.cls=t.cls}post_process(t,e,r=!0){r&&(t=Ot([this.cls[0]],t,[this.sep[0]]));let n=new Array(t.length).fill(0);if(e){let s=r?[this.sep[0]]:[],i=r?[this.sep[0]]:[];t=Ot(t,s,e,i),n=Ot(n,new Array(e.length+s.length+i.length).fill(1))}return{tokens:t,token_type_ids:n}}},OT=RT,xT=class extends eo{constructor(t){super(t),this.processors=(t.processors??[]).map(e=>vy(e))}post_process(t,e=null,r=!0){let n={tokens:t};for(let s of this.processors)n=s.post_process(n.tokens,e,r);return n}},FT=xT;function PT(t){if(t===null)return null;switch(t.type){case"TemplateProcessing":return new ST(t);case"ByteLevel":return new TT(t);case"BertProcessing":return new vT(t);case"RobertaProcessing":return new OT(t);case"Sequence":return new FT(t);default:throw new Error(`Unknown PostProcessor type: ${t.type}`)}}var vy=PT,IT=class extends Zs{constructor(t){super(),this.config=t,this.added_tokens=[],this.end_of_word_suffix=null,this.trim_offsets="trim_offsets"in t?t.trim_offsets:!1}_call(t){return this.decode(t)}decode(t){return this.decode_chain(t).join("")}},or=IT,NT=class extends or{constructor(t){super(t),this.byte_decoder=ZS,this.text_decoder=new TextDecoder("utf-8",{fatal:!1,ignoreBOM:!0}),this.end_of_word_suffix=null}convert_tokens_to_string(t){let e=t.join(""),r=new Uint8Array([...e].map(n=>this.byte_decoder[n]));return this.text_decoder.decode(r)}decode_chain(t){let e=[],r=[];for(let n of t)this.added_tokens.find(s=>s.content===n)!==void 0?(r.length>0&&(e.push(this.convert_tokens_to_string(r)),r=[]),e.push(n)):r.push(n);return r.length>0&&e.push(this.convert_tokens_to_string(r)),e}},BT=NT,jT=class extends or{constructor(t){super(t),this.cleanup=t.cleanup}decode_chain(t){return t.map((e,r)=>{if(r!==0){let n=this.config.prefix;n&&e.startsWith(n)?e=e.replace(n,""):e=" "+e}return this.cleanup&&(e=cf(e)),e})}},LT=jT,MT=class extends or{constructor(t){super(t),this.replacement=t.replacement??"\u2581"}decode_chain(t){let e=[];for(let r=0;r<t.length;++r){let n=t[r].replaceAll(this.replacement," ");r==0&&n.startsWith(" ")&&(n=n.substring(1)),e.push(n)}return e}},UT=MT,qT=class extends or{constructor(t){super(t),this.suffix=t.suffix??""}decode_chain(t){return t.map((e,r)=>e.replaceAll(this.suffix,r===t.length-1?"":" "))}},$T=qT,zT=class extends or{constructor(t){super(t),this.pad_token=t.pad_token??"",this.word_delimiter_token=t.word_delimiter_token??"",this.cleanup=t.cleanup}convert_tokens_to_string(t){if(t.length===0)return"";let e=[t[0]];for(let n=1;n<t.length;++n)t[n]!==e.at(-1)&&e.push(t[n]);let r=e.filter(n=>n!==this.pad_token).join("");return this.cleanup&&(r=cf(r).replaceAll(this.word_delimiter_token," ").trim()),r}decode_chain(t){return[this.convert_tokens_to_string(t)]}},HT=zT,WT=class extends or{constructor(t){super(t),this.decoders=(t.decoders??[]).map(e=>Ry(e))}decode_chain(t){return this.decoders.reduce((e,r)=>r.decode_chain(e),t)}},GT=WT,JT=class extends or{decode_chain(t){let e=xa(this.config.pattern),r=this.config.content??"";return e===null?t:t.map(n=>n.replaceAll(e,r))}},VT=JT,KT=class extends or{decode_chain(t){return[t.join("")]}},YT=KT,XT=class extends or{constructor(t){super(t),this.content=t.content??"",this.start=t.start??0,this.stop=t.stop??0}decode_chain(t){return t.map(e=>{let r=0;for(let s=0;s<this.start&&e[s]===this.content;++s)r=s+1;let n=e.length;for(let s=0;s<this.stop;++s){let i=e.length-s-1;if(e[i]===this.content){n=i;continue}else break}return e.slice(r,n)})}},QT=XT,ZT=class extends or{constructor(t){super(t),this.text_decoder=new TextDecoder}decode_chain(t){let e=[],r=[];for(let n of t){let s=null;if(n.length===6&&n.startsWith("<0x")&&n.endsWith(">")){let i=parseInt(n.slice(3,5),16);isNaN(i)||(s=i)}if(s!==null)r.push(s);else{if(r.length>0){let i=this.text_decoder.decode(Uint8Array.from(r));e.push(i),r=[]}e.push(n)}}if(r.length>0){let n=this.text_decoder.decode(Uint8Array.from(r));e.push(n),r=[]}return e}},eD=ZT;function tD(t){if(t===null)return null;switch(t.type){case"ByteLevel":return new BT(t);case"WordPiece":return new LT(t);case"Metaspace":return new UT(t);case"BPEDecoder":return new $T(t);case"CTC":return new HT(t);case"Sequence":return new GT(t);case"Replace":return new VT(t);case"Fuse":return new YT(t);case"Strip":return new QT(t);case"ByteFallback":return new eD(t);default:throw new Error(`Unknown Decoder type: ${t.type}`)}}var Ry=tD,rD=class{constructor(t,e){let r=yy(t,"Tokenizer",["model","decoder","post_processor","pre_tokenizer","normalizer"]);if(r)throw new Error(r);let n=yy(e,"Config");if(n)throw new Error(n);this.tokenizer=t,this.config=e,this.normalizer=Sy(this.tokenizer.normalizer),this.pre_tokenizer=ky(this.tokenizer.pre_tokenizer),this.model=wT(this.tokenizer.model,this.config),this.post_processor=vy(this.tokenizer.post_processor),this.decoder=Ry(this.tokenizer.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[],this.tokenizer.added_tokens.forEach(s=>{let i=new XS(s);this.added_tokens.push(i),this.model.tokens_to_ids.set(i.content,i.id),this.model.vocab[i.id]=i.content,i.special&&(this.special_tokens.push(i.content),this.all_special_ids.push(i.id))}),(this.config.additional_special_tokens??[]).forEach(s=>{this.special_tokens.includes(s)||this.special_tokens.push(s)}),this.decoder&&(this.decoder.added_tokens=this.added_tokens,this.decoder.end_of_word_suffix=this.model.end_of_word_suffix),this.added_tokens_splitter=new KS(this.added_tokens.map(s=>s.content)),this.added_tokens_map=new Map(this.added_tokens.map(s=>[s.content,s])),this.remove_space=this.config.remove_space,this.clean_up_tokenization_spaces=this.config.clean_up_tokenization_spaces??!0,this.do_lowercase_and_remove_accent=this.config.do_lowercase_and_remove_accent??!1}encode(t,{text_pair:e=null,add_special_tokens:r=!0,return_token_type_ids:n=null}={}){let{tokens:s,token_type_ids:i}=this.tokenize_helper(t,{text_pair:e,add_special_tokens:r}),u=this.model.convert_tokens_to_ids(s),c={ids:u,tokens:s,attention_mask:new Array(u.length).fill(1)};return n&&i&&(c.token_type_ids=i),c}decode(t,e={}){if(!Array.isArray(t)||t.length===0||!sk(t[0]))throw Error("token_ids must be a non-empty array of integers.");let r=this.model.convert_ids_to_tokens(t);e.skip_special_tokens&&(r=r.filter(s=>!this.special_tokens.includes(s)));let n=this.decoder?this.decoder(r):r.join(" ");return this.decoder&&this.decoder.end_of_word_suffix&&(n=n.replaceAll(this.decoder.end_of_word_suffix," "),e.skip_special_tokens&&(n=n.trim())),(e.clean_up_tokenization_spaces??this.clean_up_tokenization_spaces)&&(n=cf(n)),n}tokenize(t,{text_pair:e=null,add_special_tokens:r=!1}={}){return this.tokenize_helper(t,{text_pair:e,add_special_tokens:r}).tokens}encode_text(t){if(t===null)return null;let e=this.added_tokens_splitter.split(t);return e.forEach((r,n)=>{let s=this.added_tokens_map.get(r);s&&(s.lstrip&&n>0&&(e[n-1]=e[n-1].trimEnd()),s.rstrip&&n<e.length-1&&(e[n+1]=e[n+1].trimStart()))}),e.flatMap((r,n)=>{if(r.length===0)return[];if(this.added_tokens_map.has(r))return[r];if(this.remove_space===!0&&(r=r.trim().split(/\s+/).join(" ")),this.do_lowercase_and_remove_accent&&(r=ik(r)),this.normalizer!==null&&(r=this.normalizer(r)),r.length===0)return[];let s=this.pre_tokenizer!==null?this.pre_tokenizer(r,{section_index:n}):[r];return this.model(s)})}tokenize_helper(t,{text_pair:e=null,add_special_tokens:r=!0}){let n=this.encode_text(t),s=this.encode_text(e||null);return this.post_processor?this.post_processor(n,s,r):{tokens:Ot(n??[],s??[])}}token_to_id(t){return this.model.tokens_to_ids.get(t)}id_to_token(t){return this.model.vocab[t]}get_added_tokens_decoder(){let t=new Map;for(let e of this.added_tokens)t.set(e.id,e);return t}},Oy=rD;var Ba=class{type="huggingface";name;modelId;logger;options;tokenizer=null;cacheDir;safeModelName;constructor(e,r,n={}){this.modelId=e,this.logger=r,this.options=n,this.cacheDir=n.cacheDir||Ia(nD(),".claude-code-router",".huggingface"),this.safeModelName=e.replace(/\//g,"_").replace(/[^a-zA-Z0-9_-]/g,"_"),this.name=`huggingface-${e.split("/").pop()}`}getCachePaths(){let e=Ia(this.cacheDir,this.safeModelName);return{modelDir:e,tokenizerJson:Ia(e,"tokenizer.json"),tokenizerConfig:Ia(e,"tokenizer_config.json")}}ensureDir(e){ff(e)||sD(e,{recursive:!0})}async loadFromCache(){try{let e=this.getCachePaths();if(!ff(e.tokenizerJson)||!ff(e.tokenizerConfig))return null;let[r,n]=await Promise.all([Na.readFile(e.tokenizerJson,"utf-8"),Na.readFile(e.tokenizerConfig,"utf-8")]);return{tokenizerJson:JSON.parse(r),tokenizerConfig:JSON.parse(n)}}catch(e){return this.logger?.warn(`Failed to load from cache: ${e.message}`),null}}async downloadAndCache(){let e=this.getCachePaths(),r={json:`https://huggingface.co/${this.modelId}/resolve/main/tokenizer.json`,config:`https://huggingface.co/${this.modelId}/resolve/main/tokenizer_config.json`};this.logger?.info(`Downloading tokenizer files for ${this.modelId}`);let n=new AbortController,s=setTimeout(()=>n.abort(),this.options.timeout||3e4);try{let[i,u]=await Promise.all([fetch(r.json,{signal:n.signal}),fetch(r.config,{signal:n.signal})]);if(!i.ok)throw new Error(`Failed to fetch tokenizer.json: ${i.statusText}`);let[c,l]=await Promise.all([i.json(),u.ok?u.json():Promise.resolve({})]);return this.ensureDir(e.modelDir),await Promise.all([Na.writeFile(e.tokenizerJson,JSON.stringify(c,null,2)),Na.writeFile(e.tokenizerConfig,JSON.stringify(l,null,2))]),{tokenizerJson:c,tokenizerConfig:l}}finally{clearTimeout(s)}}async initialize(){try{this.logger?.info(`Initializing HuggingFace tokenizer: ${this.modelId}`);let e=this.getCachePaths();this.ensureDir(this.cacheDir);let r=await this.loadFromCache()||await this.downloadAndCache();this.tokenizer=new Oy(r.tokenizerJson,r.tokenizerConfig),this.logger?.info(`Tokenizer initialized: ${this.name}`)}catch(e){throw this.logger?.error(`Failed to initialize tokenizer: ${e.message}`),new Error(`Failed to initialize HuggingFace tokenizer for ${this.modelId}: ${e.message}`)}}async countTokens(e){if(!this.tokenizer)throw new Error("Tokenizer not initialized");try{let r=this.extractTextFromRequest(e);return this.tokenizer.encode(r).ids.length}catch(r){throw this.logger?.error(`Error counting tokens: ${r.message}`),r}}isInitialized(){return this.tokenizer!==null}encodeText(e){if(!this.tokenizer)throw new Error("Tokenizer not initialized");return this.tokenizer.encode(e).ids}dispose(){this.tokenizer=null}extractTextFromRequest(e){let r=[],{messages:n,system:s,tools:i}=e;if(Array.isArray(n)){for(let u of n)if(typeof u.content=="string")r.push(u.content);else if(Array.isArray(u.content))for(let c of u.content)c.type==="text"&&c.text?r.push(c.text):c.type==="tool_use"&&c.input?r.push(JSON.stringify(c.input)):c.type==="tool_result"&&r.push(typeof c.content=="string"?c.content:JSON.stringify(c.content))}if(typeof s=="string")r.push(s);else if(Array.isArray(s)){for(let u of s)if(u.type==="text"){if(typeof u.text=="string")r.push(u.text);else if(Array.isArray(u.text))for(let c of u.text)c&&r.push(c)}}if(i)for(let u of i)u.name&&r.push(u.name),u.description&&r.push(u.description),u.input_schema&&r.push(JSON.stringify(u.input_schema));return r.join(" ")}};var ja=class{type="api";name;config;logger;options;constructor(e,r,n={}){if(!e.url||!e.apiKey)throw new Error("API tokenizer requires url and apiKey");this.config={url:e.url,apiKey:e.apiKey,requestFormat:e.requestFormat||"standard",responseField:e.responseField||"token_count",headers:e.headers||{}},this.logger=r,this.options=n;try{let s=new URL(e.url);this.name=`api-${s.hostname}`}catch{this.name=`api-${e.url}`}}async initialize(){try{new URL(this.config.url)}catch{throw new Error(`Invalid API URL: ${this.config.url}`)}}async countTokens(e){try{let r=this.formatRequestBody(e),n={"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,...this.config.headers},s=new AbortController,i=setTimeout(()=>s.abort(),this.options.timeout||3e4),u=await fetch(this.config.url,{method:"POST",headers:n,body:JSON.stringify(r),signal:s.signal});if(clearTimeout(i),!u.ok)throw new Error(`API tokenizer request failed: ${u.status} ${u.statusText}`);let c=await u.json();return this.extractTokenCount(c)}catch(r){throw r.name==="AbortError"?new Error("API tokenizer request timed out"):r}}isInitialized(){return!0}dispose(){}formatRequestBody(e){switch(this.config.requestFormat){case"standard":return e;case"openai":return{model:"gpt-3.5-turbo",messages:this.extractMessagesAsOpenAIFormat(e)};case"anthropic":return{messages:e.messages||[],system:e.system,tools:e.tools};case"custom":return{text:this.extractConcatenatedText(e)};default:return e}}extractMessagesAsOpenAIFormat(e){return e.messages?e.messages.map(r=>({role:r.role,content:this.extractTextFromMessage(r)})):[]}extractTextFromMessage(e){return typeof e.content=="string"?e.content:Array.isArray(e.content)?e.content.map(r=>r.type==="text"&&r.text?r.text:r.type==="tool_use"&&r.input?JSON.stringify(r.input):r.type==="tool_result"?typeof r.content=="string"?r.content:JSON.stringify(r.content):"").join(" "):""}extractConcatenatedText(e){let r=[];return e.messages&&e.messages.forEach(n=>{r.push(this.extractTextFromMessage(n))}),typeof e.system=="string"?r.push(e.system):Array.isArray(e.system)&&e.system.forEach(n=>{n.type==="text"&&(typeof n.text=="string"?r.push(n.text):Array.isArray(n.text)&&n.text.forEach(s=>{s&&r.push(s)}))}),e.tools&&e.tools.forEach(n=>{n.name&&r.push(n.name),n.description&&r.push(n.description),n.input_schema&&r.push(JSON.stringify(n.input_schema))}),r.join(" ")}extractTokenCount(e){try{let r=this.config.responseField,n=r.split("."),s=e;for(let i of n){if(s==null)throw new Error(`Field path '${r}' not found in response`);s=s[i]}if(typeof s!="number")throw new Error(`Expected number at field path '${r}', got ${typeof s}`);return s}catch(r){throw this.logger?.error(`Failed to extract token count from API response: ${r.message}. Response: ${JSON.stringify(e)}`),new Error(`Invalid response from API tokenizer: ${r.message}`)}}};var as=class{tokenizers=new Map;configService;logger;options;fallbackTokenizer;constructor(e,r,n={}){this.configService=e,this.logger=r,this.options={timeout:n.timeout??3e4,...n}}async initialize(){try{this.fallbackTokenizer=new Xs("cl100k_base"),await this.fallbackTokenizer.initialize(),this.tokenizers.set("fallback",this.fallbackTokenizer),this.logger?.info("TokenizerService initialized successfully")}catch(e){throw this.logger?.error(`TokenizerService initialization error: ${e.message}`),e}}async getTokenizer(e){let r=this.getCacheKey(e);if(this.tokenizers.has(r))return this.tokenizers.get(r);let n;try{switch(e.type){case"tiktoken":n=new Xs(e.encoding||"cl100k_base");break;case"huggingface":this.logger?.info(`Initializing HuggingFace tokenizer for model: ${e.model}`),n=new Ba(e.model,this.logger,{timeout:this.options.timeout});break;case"api":n=new ja(e,this.logger,{timeout:this.options.timeout});break;default:throw new Error(`Unknown tokenizer type: ${e.type}`)}return this.logger?.info(`Calling initialize() on ${e.type} tokenizer...`),await n.initialize(),this.tokenizers.set(r,n),this.logger?.info(`Tokenizer initialized successfully: ${e.type} (${r})`),n}catch(s){return this.logger?.error(`Failed to initialize ${e.type} tokenizer: ${s.message}`),this.logger?.error(`Error stack: ${s.stack}`),this.fallbackTokenizer||await this.initialize(),this.fallbackTokenizer}}async countTokens(e,r){let n=r?await this.getTokenizer(r):this.fallbackTokenizer;return{tokenCount:await n.countTokens(e),tokenizerUsed:n.name,cached:!1}}getTokenizerConfigForModel(e,r){let s=(this.configService.get("providers")||[]).find(i=>i.name===e);if(s?.tokenizer)return s.tokenizer.models?.[r]?s.tokenizer.models[r]:s.tokenizer.default}dispose(){this.tokenizers.forEach(e=>{try{e.dispose()}catch(r){this.logger?.error(`Error disposing tokenizer: ${r}`)}}),this.tokenizers.clear()}getCacheKey(e){switch(e.type){case"tiktoken":return`tiktoken:${e.encoding||"cl100k_base"}`;case"huggingface":return`hf:${e.model}`;case"api":return`api:${e.url}`;default:return`unknown:${JSON.stringify(e)}`}}};import{get_encoding as oD}from"tiktoken";var df=class{capacity;cache;constructor(e){this.capacity=e,this.cache=new Map}get(e){if(!this.cache.has(e))return;let r=this.cache.get(e);return this.cache.delete(e),this.cache.set(e,r),r}put(e,r){if(this.cache.has(e))this.cache.delete(e);else if(this.cache.size>=this.capacity){let n=this.cache.keys().next().value;n!==void 0&&this.cache.delete(n)}this.cache.set(e,r)}values(){return Array.from(this.cache.values())}},hf=new df(100);import{readFile as mf}from"fs/promises";import{opendir as iD,stat as aD}from"fs/promises";import{join as gf}from"path";import{CLAUDE_PROJECTS_DIR as xy,HOME_DIR as Fy}from"@wengine-ai/claude-code-router-shared";var Ar=oD("cl100k_base"),Iy=(t,e,r)=>{let n=0;return Array.isArray(t)&&t.forEach(s=>{typeof s.content=="string"?n+=Ar.encode(s.content).length:Array.isArray(s.content)&&s.content.forEach(i=>{i.type==="text"?n+=Ar.encode(i.text).length:i.type==="tool_use"?n+=Ar.encode(JSON.stringify(i.input)).length:i.type==="tool_result"&&(n+=Ar.encode(typeof i.content=="string"?i.content:JSON.stringify(i.content)).length)})}),typeof e=="string"?n+=Ar.encode(e).length:Array.isArray(e)&&e.forEach(s=>{s.type==="text"&&(typeof s.text=="string"?n+=Ar.encode(s.text).length:Array.isArray(s.text)&&s.text.forEach(i=>{n+=Ar.encode(i||"").length}))}),r&&r.forEach(s=>{s.description&&(n+=Ar.encode(s.name+s.description).length),s.input_schema&&(n+=Ar.encode(JSON.stringify(s.input_schema)).length)}),n},Ny=async(t,e)=>{if(t.sessionId){let r=await jy(t.sessionId);if(r){let n=gf(Fy,r,"config.json"),s=gf(Fy,r,`${t.sessionId}.json`);try{let i=JSON.parse(await mf(s,"utf8"));if(i&&i.Router)return i.Router}catch{}try{let i=JSON.parse(await mf(n,"utf8"));if(i&&i.Router)return i.Router}catch{}}}};function La(t){let e=t||"";return e.includes(",")&&(e=e.split(",").pop()||e),e.includes("/")&&(e=e.split("/").pop()||e),e.includes(":")&&(e=e.split(":")[0]),e.trim().toLowerCase()}function By(t){let e=La(t),r=e.includes("[1m]")||e.endsWith("[1m"),n=e.replace(/\[1m\]|\[1m$/g,""),s=n.match(/^ccr-(opus|sonnet|haiku)$/i);if(s)return{family:s[1].toLowerCase(),extended:r};let i=n.match(/claude-(?:\d+-\d+-|\d+-)?(sonnet|opus|haiku)(?:-|$)/i)||n.match(/claude-(sonnet|opus|haiku)(?:-|$)/i);return i?{family:i[1].toLowerCase(),extended:r}:{family:null,extended:r}}function uD(t,e){if(!e||!t)return null;let r=La(t);if(e[t])return e[t];if(e[r])return e[r];let{family:n}=By(t);if(n&&e[n])return e[n];for(let[s,i]of Object.entries(e)){let u=La(s);if(u&&r.includes(u))return i}return null}function Gr(t,e,r){if(!t?.includes(","))return t;let[n,...s]=t.split(","),i=n.trim(),u=s.join(",").trim();if(!r&&!vn().isAvailable(i,u))return null;let c=e.find(h=>h.name.toLowerCase()===i.toLowerCase()),l=c?.models?.find(h=>String(h).toLowerCase()===u.toLowerCase());return c&&l?`${c.name},${l}`:t}function cD(t){return t.body.messages?.some(e=>e.role==="user"&&Array.isArray(e.content)&&e.content.some(r=>r.type==="image"||r.type==="image_url"||Array.isArray(r?.content)&&r.content.some(n=>n.type==="image"||n.type==="image_url")))}function lD(t){let e=La(t);return[/claude/i,/gemini/i,/gpt-4o/i,/gpt-4\.1/i,/gpt-4-vision/i,/qwen.*vl/i,/glm-4v/i,/grok.*vision/i,/pixtral/i,/llava/i].some(n=>n.test(e))}function fD(t,e,r,n,s,i){let u=r.longContextThreshold||6e4;if((i||e>2e5)&&r.extendedContext){let p=Gr(r.extendedContext,n);if(p)return t.log.info(`Family: using extended context model (1M+), tokens: ${e}, explicit: ${i}`),{model:p,scenarioType:"extendedContext"};t.log.warn("Family: extendedContext model unavailable (fail pool), skipping")}let h=s&&s.input_tokens>u&&e>2e4,d=e>u;if((h||d)&&r.longContext){let p=Gr(r.longContext,n);if(p)return t.log.info(`Family: using long context model, tokens: ${e}`),{model:p,scenarioType:"longContext"};t.log.warn("Family: longContext model unavailable (fail pool), skipping")}if(Array.isArray(t.body.tools)&&t.body.tools.some(p=>p.type?.startsWith("web_search"))&&r.webSearch){let p=Gr(r.webSearch,n);if(p)return{model:p,scenarioType:"webSearch"};t.log.warn("Family: webSearch model unavailable (fail pool), skipping")}if(t.body.thinking&&r.think){let p=Gr(r.think,n);if(p)return{model:p,scenarioType:"think"};t.log.warn("Family: think model unavailable (fail pool), skipping")}if(r.default){let p=Gr(r.default,n);if(p)return{model:p,scenarioType:"default"};t.log.warn("Family: default model unavailable (fail pool), skipping")}return null}var dD=async(t,e,r,n)=>{let s=await Ny(t,r),i=r.get("providers")||[],u=s||r.get("Router");if(t.body.model.includes(",")){let g=Gr(t.body.model,i);if(g)return{model:g,scenarioType:"default"};t.log.warn(`Explicit model ${t.body.model} unavailable (fail pool), trying alternatives`)}let{family:c,extended:l}=By(t.body.model),h=u?.families?.[c||""];if(h){t.log.info(`Using model family routing for: ${c}${l?" (1M)":""}`),t.modelFamily=c,t.familyFallback=h.fallback;let g=fD(t,e,h,i,n,l);if(g)return g}let d=uD(t.body.model,u?.models);if(d){let g=Gr(d,i);if(g)return t.log.info(`Using mapped model for ${t.body.model}: ${d}`),{model:g,scenarioType:"modelMapping"};t.log.warn(`Mapped model ${d} unavailable (fail pool), skipping`)}let p=u?.extendedContextThreshold||2e5;if(e>p&&u?.extendedContext)return t.log.info(`Using extended context (1M) model due to token count: ${e}, threshold: ${p}`),{model:u.extendedContext,scenarioType:"extendedContext"};let A=u?.longContextThreshold||6e4,v=n&&n.input_tokens>A&&e>2e4,S=e>A;if((v||S)&&u?.longContext)return t.log.info(`Using long context model due to token count: ${e}, threshold: ${A}`),{model:u.longContext,scenarioType:"longContext"};if(t.body?.system?.length>1&&t.body?.system[1]?.text?.startsWith("<CCR-SUBAGENT-MODEL>")){let g=t.body?.system[1].text.match(/<CCR-SUBAGENT-MODEL>(.*?)<\/CCR-SUBAGENT-MODEL>/s);if(g)return t.body.system[1].text=t.body.system[1].text.replace(`<CCR-SUBAGENT-MODEL>${g[1]}</CCR-SUBAGENT-MODEL>`,""),{model:g[1],scenarioType:"default"}}let y=r.get("Router");return t.body.model?.includes("claude")&&t.body.model?.includes("haiku")&&y?.background?(t.log.info(`Using background model for ${t.body.model}`),{model:y.background,scenarioType:"background"}):Array.isArray(t.body.tools)&&t.body.tools.some(g=>g.type?.startsWith("web_search"))&&u?.webSearch?{model:u.webSearch,scenarioType:"webSearch"}:t.body.thinking&&u?.think?(t.log.info(`Using think model for ${t.body.thinking}`),{model:u.think,scenarioType:"think"}):{model:u?.default,scenarioType:"default"}},yf=async(t,e,r)=>{let{configService:n,event:s}=r;if(t.originalModel=t.body.model,t.body.metadata?.user_id){let v=t.body.metadata.user_id.split("_session_");v.length>1&&(t.sessionId=v[1])}let u=await Ny(t,n)||n.get("Router"),c=n.get("providers")||[],l=hf.get(t.sessionId),{messages:h,system:d=[],tools:p}=t.body,A=n.get("REWRITE_SYSTEM_PROMPT");if(A&&d.length>1&&d[1]?.text?.includes("<env>")){let v=await mf(A,"utf-8");d[1].text=`${v}<env>${d[1].text.split("<env>").pop()}`}try{let[v,S]=t.body.model.split(","),y=r.tokenizerService?.getTokenizerConfigForModel(v,S),g;r.tokenizerService?g=(await r.tokenizerService.countTokens({messages:h,system:d,tools:p},y)).tokenCount:g=Iy(h,d,p),t.tokenCount=g;let m,k=n.get("CUSTOM_ROUTER_PATH");if(k)try{m=await Q(k)(t,n.getAll(),{event:s})}catch(b){t.log.error(`failed to load custom router: ${b.message}`)}if(m)t.scenarioType="default";else{let b=await dD(t,g,n,l);m=b.model,t.scenarioType=b.scenarioType}if(u?.image&&m!==u.image&&cD(t)&&!lD(m)){let b=Gr(u.image,c);b?(t.log.info(`Using image model fallback for ${m}`),m=b,t.scenarioType="image"):t.log.warn(`Image model ${u.image} unavailable (fail pool), keeping ${m}`)}t.body.model=m}catch(v){t.log.error(`Error in router middleware: ${v.message}`),t.body.model=u?.default,t.scenarioType="default"}},Sr=new Map,Py=1e3;function pf(){if(Sr.size<=Py)return;let t=[...Sr.keys()].slice(0,Sr.size-Py);for(let e of t)Sr.delete(e)}var jy=async t=>{if(Sr.has(t)){let e=Sr.get(t);return!e||e===""?null:e}try{let e=await iD(xy),r=[];for await(let i of e)i.isDirectory()&&r.push(i.name);let n=r.map(async i=>{let u=gf(xy,i,`${t}.jsonl`);try{return(await aD(u)).isFile()?i:null}catch{return null}}),s=await Promise.all(n);for(let i of s)if(i)return Sr.set(t,i),pf(),i;return Sr.set(t,""),pf(),null}catch(e){return console.error("Error searching for project by session:",e),Sr.set(t,""),pf(),null}};var _f=class{plugins=new Map;pluginInstances=new Map;registerPlugin(e,r={}){this.pluginInstances.set(e.name,e),this.plugins.set(e.name,{name:e.name,enabled:r.enabled!==!1,options:r})}async enablePlugin(e,r){let n=this.plugins.get(e),s=this.pluginInstances.get(e);if(!n||!s)throw new Error(`Plugin ${e} not found`);n.enabled&&await r.register(s.register,n.options)}async enablePlugins(e){for(let[r,n]of this.plugins)if(n.enabled)try{await this.enablePlugin(r,e)}catch(s){let i=s instanceof Error?s.message:String(s);e.log?.error(`Failed to enable plugin ${r}: ${i}`)}}getPlugins(){return Array.from(this.plugins.values())}getPlugin(e){return this.pluginInstances.get(e)}hasPlugin(e){return this.pluginInstances.has(e)}isPluginEnabled(e){return this.plugins.get(e)?.enabled||!1}setPluginEnabled(e,r){let n=this.plugins.get(e);n&&(n.enabled=r)}removePlugin(e){this.plugins.delete(e),this.pluginInstances.delete(e)}clear(){this.plugins.clear(),this.pluginInstances.clear()}},Ly=new _f;var Ky=Pr(zy(),1);var us=class extends TransformStream{buffer="";currentEvent={};constructor(){super({transform:(e,r)=>{this.buffer+=e;let n=this.buffer.split(`
|
|
341
|
-
`);this.buffer=n.pop()||"";for(let s of n){let i=this.processLine(s);i&&r.enqueue(i)}},flush:e=>{if(this.buffer.trim()){let r=[];this.processLine(this.buffer.trim(),r),r.forEach(n=>e.enqueue(n))}Object.keys(this.currentEvent).length>0&&e.enqueue(this.currentEvent)}})}processLine(e,r){if(!e.trim()){if(Object.keys(this.currentEvent).length>0){let n={...this.currentEvent};return this.currentEvent={},r?(r.push(n),null):n}return null}if(e.startsWith("event:"))this.currentEvent.event=e.slice(6).trim();else if(e.startsWith("data:")){let n=e.slice(5).trim();if(n==="[DONE]")this.currentEvent.data={type:"done"};else try{this.currentEvent.data=JSON.parse(n)}catch{this.currentEvent.data={raw:n,error:"JSON parse failed"}}}else e.startsWith("id:")?this.currentEvent.id=e.slice(3).trim():e.startsWith("retry:")&&(this.currentEvent.retry=parseInt(e.slice(6).trim()));return null}};var
|
|
339
|
+
Stack: ${e.stack}`)}}async registerDefaultTransformersInternal(){try{Object.values(xy).forEach(e=>{if("TransformerName"in e&&typeof e.TransformerName=="string")this.registerTransformer(e.TransformerName,e);else{let r=new e;r&&typeof r=="object"&&(r.logger=this.logger),this.registerTransformer(r.name,r)}})}catch(e){this.logger.error({error:e},"transformer regist error:")}}async loadFromConfig(){let e=this.configService.get("transformers",[]);for(let r of e)await this.registerTransformerFromConfig(r)}};import{get_encoding as pv}from"tiktoken";var eo=class{type="tiktoken";name;encoding;constructor(e="cl100k_base"){this.name=`tiktoken-${e}`;try{this.encoding=pv(e)}catch{throw new Error(`Failed to initialize tiktoken encoding: ${e}`)}}async initialize(){if(!this.encoding)throw new Error("Tiktoken encoding not initialized")}async countTokens(e){let r=this.encoding;if(!r)throw new Error("Encoding not initialized");let n=0,{messages:s,system:i,tools:u}=e;return Array.isArray(s)&&s.forEach(c=>{typeof c.content=="string"?n+=r.encode(c.content).length:Array.isArray(c.content)&&c.content.forEach(l=>{if(l.type==="text")n+=r.encode(l.text).length;else if(l.type==="tool_use")n+=r.encode(JSON.stringify(l.input)).length;else if(l.type==="tool_result"){let h=typeof l.content=="string"?l.content:JSON.stringify(l.content);n+=r.encode(h).length}})}),typeof i=="string"?n+=r.encode(i).length:Array.isArray(i)&&i.forEach(c=>{c.type==="text"&&(typeof c.text=="string"?n+=r.encode(c.text).length:Array.isArray(c.text)&&c.text.forEach(l=>{n+=r.encode(l||"").length}))}),u&&u.forEach(c=>{c.description&&(n+=r.encode(c.name+c.description).length),c.input_schema&&(n+=r.encode(JSON.stringify(c.input_schema)).length)}),n}isInitialized(){return this.encoding!==void 0}encodeText(e){let r=this.encoding;if(!r)throw new Error("Encoding not initialized");return Array.from(r.encode(e))}dispose(){this.encoding&&(this.encoding.free(),this.encoding=void 0)}};import{join as La}from"path";import{homedir as ST}from"os";import{existsSync as md,mkdirSync as vT}from"fs";import{promises as Ma}from"fs";var mv=class{constructor(t){this.trie=this._build_trie(t)}_build_trie(t){let e=Object.create(null);for(let r of t){let n=e;for(let s=0;s<r.length;++s){let i=r[s];n=n[i]??=Object.create(null)}n.end=r}return e}split(t){let e=[],r=t.length,n=0,s=0;for(;s<r;){let i=this.trie,u=null,c=s;for(;c<r&&(i=i[t[c]]);)i.end&&(u=i.end),++c;u?(s>n&&e.push(t.slice(n,s)),e.push(u),s+=u.length,n=s):++s}return n<r&&e.push(t.slice(n)),e}},gv=mv,yv=class{constructor(t){this.content=t.content,this.id=t.id,this.single_word=t.single_word??!1,this.lstrip=t.lstrip??!1,this.rstrip=t.rstrip??!1,this.special=t.special??!1,this.normalized=t.normalized??null}},_v=yv,jy=(()=>{let t=[...Array.from({length:94},(s,i)=>i+33),...Array.from({length:12},(s,i)=>i+161),...Array.from({length:82},(s,i)=>i+174)],e=t.slice(),r=0;for(let s=0;s<256;++s)t.includes(s)||(t.push(s),e.push(256+r),r+=1);let n=e.map(s=>String.fromCharCode(s));return Object.fromEntries(t.map((s,i)=>[s,n[i]]))})(),bv=t=>Object.fromEntries(Object.entries(t).map(([e,r])=>[r,e])),Cv=bv(jy),Oy=".,!?\u2026\u3002\uFF0C\u3001\u0964\u06D4\u060C",wv=new Map([["(?i:'s|'t|'re|'ve|'m|'ll|'d)","(?:'([sS]|[tT]|[rR][eE]|[vV][eE]|[mM]|[lL][lL]|[dD]))"],["(?i:[sdmt]|ll|ve|re)","(?:[sS]|[dD]|[mM]|[tT]|[lL][lL]|[vV][eE]|[rR][eE])"],["[^\\r\\n\\p{L}\\p{N}]?+","[^\\r\\n\\p{L}\\p{N}]?"],["[^\\s\\p{L}\\p{N}]++","[^\\s\\p{L}\\p{N}]+"],[` ?[^(\\s|[${Oy}])]+`,` ?[^\\s${Oy}]+`]]),to="\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E",$O=new RegExp(`^[${to}]+$`,"gu"),hd=t=>t.replace(/ \./g,".").replace(/ \?/g,"?").replace(/ \!/g,"!").replace(/ ,/g,",").replace(/ \' /g,"'").replace(/ n't/g,"n't").replace(/ 'm/g,"'m").replace(/ 's/g,"'s").replace(/ 've/g,"'ve").replace(/ 're/g,"'re"),Na=(t,e=!0)=>{if(t.Regex!==void 0){let r=t.Regex.replace(/\\([#&~])/g,"$1");for(let[n,s]of wv)r=r.replaceAll(n,s);return new RegExp(r,"gu")}else if(t.String!==void 0){let r=Ev(t.String);return new RegExp(e?r:`(${r})`,"gu")}else return console.warn("Unknown pattern type:",t),null},Ev=t=>t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),Av=(t,e,r)=>{let n=[],s=0;for(;s<t.length;){if(n.push(t[s]),(e.get(t[s])??r)!==r){++s;continue}for(;++s<t.length&&(e.get(t[s])??r)===r;)e.get(n.at(-1))!==r&&(n[n.length-1]+=t[s])}return n},Sv=t=>t>=19968&&t<=40959||t>=13312&&t<=19903||t>=131072&&t<=173791||t>=173824&&t<=177983||t>=177984&&t<=178207||t>=178208&&t<=183983||t>=63744&&t<=64255||t>=194560&&t<=195103,vv=t=>Number.isInteger(t)||typeof t=="bigint",kv=t=>{let e=0;for(let r of t)++e;return e},Tv=t=>Ly(t.toLowerCase()),xt=(...t)=>Array.prototype.concat.apply([],t),pd=t=>new Map(Object.entries(t)),Dv=(t,e)=>{let r=[],n=0;for(let s of t.matchAll(e)){let i=s[0];n<s.index&&r.push(t.slice(n,s.index)),i.length>0&&r.push(i),n=s.index+i.length}return n<t.length&&r.push(t.slice(n)),r},Ly=t=>t.replace(new RegExp("\\p{M}","gu"),""),Fy=(t,e,r=[])=>{if(!t||Array.isArray(t)||typeof t!="object")return`${e} must be a valid object`;for(let n of r)if(!(n in t))return`${e} must contain a "${n}" property`;return null},Rv=t=>t.match(/\S+/g)||[],xv=class{constructor(){let t=function(...e){return t._call(...e)};return Object.setPrototypeOf(t,new.target.prototype)}},ro=xv,Ov=class extends ro{constructor(t){super(),this.config=t}_call(t){return this.normalize(t)}},Sr=Ov,Fv=class extends Sr{tokenize_chinese_chars(t){let e=[];for(let r=0;r<t.length;++r){let n=t[r],s=n.charCodeAt(0);Sv(s)?(e.push(" "),e.push(n),e.push(" ")):e.push(n)}return e.join("")}strip_accents(t){return t.normalize("NFD").replace(new RegExp("\\p{Mn}","gu"),"")}is_control(t){switch(t){case" ":case`
|
|
340
|
+
`:case"\r":return!1;default:return new RegExp("^\\p{Cc}|\\p{Cf}|\\p{Co}|\\p{Cs}$","u").test(t)}}clean_text(t){let e=[];for(let r of t){let n=r.charCodeAt(0);n===0||n===65533||this.is_control(r)||(/^\s$/.test(r)?e.push(" "):e.push(r))}return e.join("")}normalize(t){return this.config.clean_text&&(t=this.clean_text(t)),this.config.handle_chinese_chars&&(t=this.tokenize_chinese_chars(t)),this.config.lowercase?(t=t.toLowerCase(),this.config.strip_accents!==!1&&(t=this.strip_accents(t))):this.config.strip_accents&&(t=this.strip_accents(t)),t}},Pv=Fv,Iv=class extends Sr{constructor(t){super(t),this.charsmap=t.precompiled_charsmap??null}normalize(t){return t=t.replace(/[\u0001-\u0008\u000B\u000E-\u001F\u007F\u008F\u009F]/gm,""),t=t.replace(/[\u0009\u000A\u000C\u000D\u00A0\u1680\u2000-\u200F\u2028\u2029\u202F\u205F\u2581\u3000\uFEFF\uFFFD]/gm," "),t.includes("\uFF5E")?t=t.split("\uFF5E").map(e=>e.normalize("NFKC")).join("\uFF5E"):t=t.normalize("NFKC"),t}},Nv=Iv,Bv=class extends Sr{constructor(t){super(t),this.normalizers=(t.normalizers??[]).map(e=>My(e))}normalize(t){return this.normalizers.reduce((e,r)=>r?r.normalize(e):e,t)}},jv=Bv,Lv=class extends Sr{normalize(t){let e=Na(this.config.pattern??{});return e===null?t:t.replaceAll(e,this.config.content??"")}},Mv=Lv,Uv=class extends Sr{constructor(){super(...arguments),this.form="NFC"}normalize(t){return t=t.normalize(this.form),t}},Ba=Uv,qv=class extends Ba{constructor(){super(...arguments),this.form="NFC"}},$v=qv,zv=class extends Ba{constructor(){super(...arguments),this.form="NFD"}},Hv=zv,Wv=class extends Ba{constructor(){super(...arguments),this.form="NFKC"}},Gv=Wv,Jv=class extends Ba{constructor(){super(...arguments),this.form="NFKD"}},Vv=Jv,Kv=class extends Sr{normalize(t){return this.config.strip_left&&this.config.strip_right?t=t.trim():(this.config.strip_left&&(t=t.trimStart()),this.config.strip_right&&(t=t.trimEnd())),t}},Yv=Kv,Qv=class extends Sr{normalize(t){return Ly(t)}},Xv=Qv,Zv=class extends Sr{normalize(t){return t.toLowerCase()}},ek=Zv,tk=class extends Sr{normalize(t){return t=this.config.prepend+t,t}},rk=tk;function nk(t){if(t===null)return null;switch(t.type){case"BertNormalizer":return new Pv(t);case"Precompiled":return new Nv(t);case"Sequence":return new jv(t);case"Replace":return new Mv(t);case"NFC":return new $v(t);case"NFD":return new Hv(t);case"NFKC":return new Gv(t);case"NFKD":return new Vv(t);case"Strip":return new Yv(t);case"StripAccents":return new Xv(t);case"Lowercase":return new ek(t);case"Prepend":return new rk(t);default:throw new Error(`Unknown Normalizer type: ${t.type}`)}}var My=nk,sk=class extends ro{pre_tokenize(t,e){return(Array.isArray(t)?t.map(r=>this.pre_tokenize_text(r,e)):this.pre_tokenize_text(t,e)).flat()}_call(t,e){return this.pre_tokenize(t,e)}},or=sk,ok=class extends or{constructor(t){super(),this.config=t,this.add_prefix_space=this.config.add_prefix_space??!1,this.trim_offsets=this.config.trim_offsets??!1,this.use_regex=this.config.use_regex??!0,this.pattern=new RegExp("'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)|\\s+","gu"),this.byte_encoder=jy,this.text_encoder=new TextEncoder}pre_tokenize_text(t,e){return this.add_prefix_space&&!t.startsWith(" ")&&(t=" "+t),(this.use_regex?t.match(this.pattern)||[]:[t]).map(r=>Array.from(this.text_encoder.encode(r),n=>this.byte_encoder[n]).join(""))}},ik=ok,ak=class extends or{pre_tokenize_text(t,e){return t.match(/\w+|[^\w\s]+/g)||[]}},uk=ak,ck=class extends or{constructor(t){super(),this.replacement=t.replacement??"\u2581",this.str_rep=t.str_rep||this.replacement,this.prepend_scheme=t.prepend_scheme??"always"}pre_tokenize_text(t,e){let{section_index:r=void 0}=e??{},n=t.replaceAll(" ",this.str_rep);return!n.startsWith(this.replacement)&&(this.prepend_scheme==="always"||this.prepend_scheme==="first"&&r===0)&&(n=this.str_rep+n),[n]}},lk=ck,dk=class extends or{constructor(t){super(),this.config=t,this.pattern=Na(this.config.pattern??{},this.config.invert??!0)}pre_tokenize_text(t){return this.pattern===null?[]:this.config.invert?t.match(this.pattern)||[]:this.config.behavior?.toLowerCase()==="removed"?t.split(this.pattern).filter(e=>e):Dv(t,this.pattern)}},fk=dk,hk=class extends or{constructor(t){super(),this.config=t,this.pattern=new RegExp(`[^${to}]+|[${to}]+`,"gu")}pre_tokenize_text(t){return t.match(this.pattern)||[]}},pk=hk,mk=class extends or{constructor(t){super(),this.config=t;let e=`[^\\d]+|\\d${this.config.individual_digits?"":"+"}`;this.pattern=new RegExp(e,"gu")}pre_tokenize_text(t){return t.match(this.pattern)||[]}},gk=mk,yk=class extends or{constructor(){super(),this.pattern=new RegExp(`[^\\s${to}]+|[${to}]`,"gu")}pre_tokenize_text(t,e){return t.trim().match(this.pattern)||[]}},_k=yk,bk=class extends or{constructor(t){super(),this.config=t,this.pattern=Na(this.config.pattern??{}),this.content=this.config.content??""}pre_tokenize_text(t){return this.pattern===null?[t]:[t.replaceAll(this.pattern,this.config.content??"")]}},Ck=bk,wk=class extends or{constructor(t){super(),this.tokenizers=(t.pretokenizers??[]).map(e=>Uy(e))}pre_tokenize_text(t,e){return this.tokenizers.reduce((r,n)=>n?n.pre_tokenize(r,e):r,[t])}},Ek=wk,Ak=class extends or{pre_tokenize_text(t){return Rv(t)}},Sk=Ak;function vk(t){if(t===null)return null;switch(t.type){case"BertPreTokenizer":return new _k;case"Sequence":return new Ek(t);case"Whitespace":return new uk;case"WhitespaceSplit":return new Sk;case"Metaspace":return new lk(t);case"ByteLevel":return new ik(t);case"Split":return new fk(t);case"Punctuation":return new pk(t);case"Digits":return new gk(t);case"Replace":return new Ck(t);default:throw new Error(`Unknown PreTokenizer type: ${t.type}`)}}var Uy=vk,kk=class extends ro{constructor(t){super(),this.config=t,this.vocab=[],this.tokens_to_ids=new Map,this.unk_token_id=void 0,this.unk_token=void 0,this.end_of_word_suffix=void 0,this.fuse_unk=this.config.fuse_unk??!1}_call(t){let e=this.encode(t);return this.fuse_unk&&(e=Av(e,this.tokens_to_ids,this.unk_token_id)),e}convert_tokens_to_ids(t){return t.map(e=>this.tokens_to_ids.get(e)??this.unk_token_id)}convert_ids_to_tokens(t){return t.map(e=>this.vocab[Number(e)]??this.unk_token)}},ja=kk,Tk=class extends ja{constructor(t){super(t),this.max_input_chars_per_word=100,this.tokens_to_ids=pd(t.vocab),this.unk_token_id=this.tokens_to_ids.get(t.unk_token),this.unk_token=t.unk_token,this.max_input_chars_per_word=t.max_input_chars_per_word??100,this.vocab=new Array(this.tokens_to_ids.size);for(let[e,r]of this.tokens_to_ids)this.vocab[r]=e}encode(t){let e=[];for(let r of t){let n=[...r];if(n.length>this.max_input_chars_per_word){e.push(this.unk_token);continue}let s=!1,i=0,u=[];for(;i<n.length;){let c=n.length,l=null;for(;i<c;){let h=n.slice(i,c).join("");if(i>0&&(h=this.config.continuing_subword_prefix+h),this.tokens_to_ids.has(h)){l=h;break}--c}if(l===null){s=!0;break}u.push(l),i=c}s?e.push(this.unk_token):e.push(...u)}return e}},Py=Tk,Iy=class qy{constructor(e,r){this.is_leaf=e,this.children=r}static default(){return new qy(!1,new Map)}},Dk=class{constructor(){this.root=Iy.default()}extend(t){for(let e of t)this.push(e)}push(t){let e=this.root;for(let r of t){let n=e.children.get(r);n===void 0&&(n=Iy.default(),e.children.set(r,n)),e=n}e.is_leaf=!0}*common_prefix_search(t){let e=this.root;if(e===void 0)return;let r="";for(let n of t){if(r+=n,e=e.children.get(n),e===void 0)return;e.is_leaf&&(yield r)}}},Rk=Dk,fd=class $y{constructor(e,r,n,s,i){this.token_id=e,this.node_id=r,this.pos=n,this.length=s,this.score=i,this.prev=null,this.backtrace_score=0}clone(){let e=new $y(this.token_id,this.node_id,this.pos,this.length,this.score);return e.prev=this.prev,e.backtrace_score=this.backtrace_score,e}},xk=class{constructor(t,e,r){this.chars=Array.from(t),this.len=this.chars.length,this.bos_token_id=e,this.eos_token_id=r,this.nodes=[],this.begin_nodes=Array.from({length:this.len+1},()=>[]),this.end_nodes=Array.from({length:this.len+1},()=>[]);let n=new fd(this.bos_token_id??0,0,0,0,0),s=new fd(this.eos_token_id??0,1,this.len,0,0);this.nodes.push(n.clone()),this.nodes.push(s.clone()),this.begin_nodes[this.len].push(s),this.end_nodes[0].push(n)}insert(t,e,r,n){let s=this.nodes.length,i=new fd(n,s,t,e,r);this.begin_nodes[t].push(i),this.end_nodes[t+e].push(i),this.nodes.push(i)}viterbi(){let t=this.len,e=0;for(;e<=t;){if(this.begin_nodes[e].length==0)return[];for(let i of this.begin_nodes[e]){i.prev=null;let u=0,c=null;for(let l of this.end_nodes[e]){let h=l.backtrace_score+i.score;(c===null||h>u)&&(c=l.clone(),u=h)}if(c!==null)i.prev=c,i.backtrace_score=u;else return[]}++e}let r=[],n=this.begin_nodes[t][0].prev;if(n===null)return[];let s=n.clone();for(;s.prev!==null;)r.push(s.clone()),s=s.clone().prev.clone();return r.reverse(),r}piece(t){return this.chars.slice(t.pos,t.pos+t.length).join("")}tokens(){return this.viterbi().map(t=>this.piece(t))}token_ids(){return this.viterbi().map(t=>t.token_id)}},Ok=xk;function Fk(t){if(t.length===0)throw new Error("Array must not be empty");let e=t[0],r=0;for(let n=1;n<t.length;++n)t[n]<e&&(e=t[n],r=n);return[e,r]}var Pk=class extends ja{constructor(t,e){super(t);let r=t.vocab.length;this.vocab=new Array(r),this.scores=new Array(r);for(let n=0;n<r;++n)[this.vocab[n],this.scores[n]]=t.vocab[n];this.unk_token_id=t.unk_id,this.unk_token=this.vocab[t.unk_id],this.tokens_to_ids=new Map(this.vocab.map((n,s)=>[n,s])),this.bos_token=" ",this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=e,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.unk_token=this.vocab[this.unk_token_id],this.min_score=Fk(this.scores)[0],this.unk_score=this.min_score-10,this.scores[this.unk_token_id]=this.unk_score,this.trie=new Rk,this.trie.extend(this.vocab),this.fuse_unk=!0}populate_nodes(t){let e=t.chars,r=1,n=0;for(;n<e.length;){let s=!1,i=[],u=e.slice(n).join(""),c=this.trie.common_prefix_search(u);for(let l of c){i.push(l);let h=this.tokens_to_ids.get(l),d=this.scores[h],p=kv(l);t.insert(n,p,d,h),!s&&p===r&&(s=!0)}s||t.insert(n,r,this.unk_score,this.unk_token_id),n+=r}}tokenize(t){let e=new Ok(t,this.bos_token_id,this.eos_token_id);return this.populate_nodes(e),e.tokens()}encode(t){let e=[];for(let r of t){let n=this.tokenize(r);e.push(...n)}return e}},Ny=Pk,Ik=class{constructor(t=(r,n)=>r>n,e=1/0){this._heap=[],this._comparator=t,this._max_size=e}get size(){return this._heap.length}is_empty(){return this.size===0}peek(){return this._heap[0]}push(...t){return this.extend(t)}extend(t){for(let e of t)if(this.size<this._max_size)this._heap.push(e),this._sift_up();else{let r=this._smallest();this._comparator(e,this._heap[r])&&(this._heap[r]=e,this._sift_up_from(r))}return this.size}pop(){let t=this.peek(),e=this.size-1;return e>0&&this._swap(0,e),this._heap.pop(),this._sift_down(),t}replace(t){let e=this.peek();return this._heap[0]=t,this._sift_down(),e}_parent(t){return(t+1>>>1)-1}_left(t){return(t<<1)+1}_right(t){return t+1<<1}_greater(t,e){return this._comparator(this._heap[t],this._heap[e])}_swap(t,e){let r=this._heap[t];this._heap[t]=this._heap[e],this._heap[e]=r}_sift_up(){this._sift_up_from(this.size-1)}_sift_up_from(t){for(;t>0&&this._greater(t,this._parent(t));)this._swap(t,this._parent(t)),t=this._parent(t)}_sift_down(){let t=0;for(;this._left(t)<this.size&&this._greater(this._left(t),t)||this._right(t)<this.size&&this._greater(this._right(t),t);){let e=this._right(t)<this.size&&this._greater(this._right(t),this._left(t))?this._right(t):this._left(t);this._swap(t,e),t=e}}_smallest(){return 2**Math.floor(Math.log2(this.size))-1}},Nk=Ik,Bk=class{constructor(t){this.capacity=t,this.cache=new Map}get(t){if(!this.cache.has(t))return;let e=this.cache.get(t);return this.cache.delete(t),this.cache.set(t,e),e}put(t,e){this.cache.has(t)&&this.cache.delete(t),this.cache.set(t,e),this.cache.size>this.capacity&&this.cache.delete(this.cache.keys().next().value)}clear(){this.cache.clear()}},jk=Bk,Lk=class extends ja{constructor(t){super(t),this.tokens_to_ids=pd(t.vocab),this.unk_token_id=this.tokens_to_ids.get(t.unk_token),this.unk_token=t.unk_token,this.vocab=new Array(this.tokens_to_ids.size);for(let[r,n]of this.tokens_to_ids)this.vocab[n]=r;let e=Array.isArray(t.merges[0]);this.merges=e?t.merges:t.merges.map(r=>r.split(" ",2)),this.bpe_ranks=new Map(this.merges.map((r,n)=>[JSON.stringify(r),n])),this.end_of_word_suffix=t.end_of_word_suffix,this.continuing_subword_suffix=t.continuing_subword_suffix??null,this.byte_fallback=this.config.byte_fallback??!1,this.byte_fallback&&(this.text_encoder=new TextEncoder),this.ignore_merges=this.config.ignore_merges??!1,this.max_length_to_cache=256,this.cache_capacity=1e4,this.cache=new jk(this.cache_capacity)}clear_cache(){this.cache.clear()}bpe(t){if(t.length===0)return[];let e=this.cache.get(t);if(e!==void 0)return e;let r=Array.from(t);this.end_of_word_suffix&&(r[r.length-1]+=this.end_of_word_suffix);let n=[];if(r.length>1){let s=new Nk((c,l)=>c.score<l.score),i={token:r[0],bias:0,prev:null,next:null},u=i;for(let c=1;c<r.length;++c){let l={bias:c/r.length,token:r[c],prev:u,next:null};u.next=l,this.add_node(s,u),u=l}for(;!s.is_empty();){let c=s.pop();if(c.deleted||!c.next||c.next.deleted)continue;if(c.deleted=!0,c.next.deleted=!0,c.prev){let h={...c.prev};c.prev.deleted=!0,c.prev=h,h.prev?h.prev.next=h:i=h}let l={token:c.token+c.next.token,bias:c.bias,prev:c.prev,next:c.next.next};l.prev?(l.prev.next=l,this.add_node(s,l.prev)):i=l,l.next&&(l.next.prev=l,this.add_node(s,l))}for(let c=i;c!==null;c=c.next)n.push(c.token)}else n=r;if(this.continuing_subword_suffix)for(let s=0;s<n.length-1;++s)n[s]+=this.continuing_subword_suffix;return t.length<this.max_length_to_cache&&this.cache.put(t,n),n}add_node(t,e){let r=this.bpe_ranks.get(JSON.stringify([e.token,e.next.token]));r!==void 0&&(e.score=r+e.bias,t.push(e))}encode(t){let e=[];for(let r of t){if(this.ignore_merges&&this.tokens_to_ids.has(r)){e.push(r);continue}let n=this.bpe(r);for(let s of n)if(this.tokens_to_ids.has(s))e.push(s);else if(this.byte_fallback){let i=Array.from(this.text_encoder.encode(s)).map(u=>`<0x${u.toString(16).toUpperCase().padStart(2,"0")}>`);i.every(u=>this.tokens_to_ids.has(u))?e.push(...i):e.push(this.unk_token)}else e.push(this.unk_token)}return e}},By=Lk,Mk=class extends ja{constructor(t,e){super(t);let r=t.vocab;this.tokens_to_ids=pd(e.target_lang?r[e.target_lang]:r),this.bos_token=e.bos_token,this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=e.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.pad_token=e.pad_token,this.pad_token_id=this.tokens_to_ids.get(this.pad_token),this.unk_token=e.unk_token,this.unk_token_id=this.tokens_to_ids.get(this.unk_token),this.vocab=new Array(this.tokens_to_ids.size);for(let[n,s]of this.tokens_to_ids)this.vocab[s]=n}encode(t){return t}},Uk=Mk;function qk(t,e){switch(t.type){case"WordPiece":return new Py(t);case"Unigram":return new Ny(t,e.eos_token);case"BPE":return new By(t);default:if(t.vocab)return Array.isArray(t.vocab)?new Ny(t,e.eos_token):Object.hasOwn(t,"continuing_subword_prefix")&&Object.hasOwn(t,"unk_token")?Object.hasOwn(t,"merges")?new By(t):new Py(t):new Uk(t,{target_lang:e.target_lang,bos_token:e.bos_token,eos_token:e.eos_token,pad_token:e.pad_token,unk_token:e.unk_token});throw new Error(`Unknown TokenizerModel type: ${t?.type}`)}}var $k=qk,zk=class extends ro{constructor(t){super(),this.config=t}_call(t,...e){return this.post_process(t,...e)}},no=zk,Hk=class extends no{post_process(t,e=null,r=!0){let n=e===null?this.config.single:this.config.pair,s=[],i=[];for(let u of n)"SpecialToken"in u?r&&(s.push(u.SpecialToken.id),i.push(u.SpecialToken.type_id)):"Sequence"in u&&(u.Sequence.id==="A"?(s=xt(s,t),i=xt(i,new Array(t.length).fill(u.Sequence.type_id))):u.Sequence.id==="B"&&(s=xt(s,e),i=xt(i,new Array(e.length).fill(u.Sequence.type_id))));return{tokens:s,token_type_ids:i}}},Wk=Hk,Gk=class extends no{post_process(t,e=null){return{tokens:e?xt(t,e):t}}},Jk=Gk,Vk=class extends no{constructor(t){super(t),this.sep=t.sep,this.cls=t.cls}post_process(t,e=null,r=!0){r&&(t=xt([this.cls[0]],t,[this.sep[0]]));let n=new Array(t.length).fill(0);if(e){let s=[],i=r?[this.sep[0]]:[];t=xt(t,s,e,i),n=xt(n,new Array(e.length+s.length+i.length).fill(1))}return{tokens:t,token_type_ids:n}}},Kk=Vk,Yk=class extends no{constructor(t){super(t),this.sep=t.sep,this.cls=t.cls}post_process(t,e,r=!0){r&&(t=xt([this.cls[0]],t,[this.sep[0]]));let n=new Array(t.length).fill(0);if(e){let s=r?[this.sep[0]]:[],i=r?[this.sep[0]]:[];t=xt(t,s,e,i),n=xt(n,new Array(e.length+s.length+i.length).fill(1))}return{tokens:t,token_type_ids:n}}},Qk=Yk,Xk=class extends no{constructor(t){super(t),this.processors=(t.processors??[]).map(e=>zy(e))}post_process(t,e=null,r=!0){let n={tokens:t};for(let s of this.processors)n=s.post_process(n.tokens,e,r);return n}},Zk=Xk;function eT(t){if(t===null)return null;switch(t.type){case"TemplateProcessing":return new Wk(t);case"ByteLevel":return new Jk(t);case"BertProcessing":return new Kk(t);case"RobertaProcessing":return new Qk(t);case"Sequence":return new Zk(t);default:throw new Error(`Unknown PostProcessor type: ${t.type}`)}}var zy=eT,tT=class extends ro{constructor(t){super(),this.config=t,this.added_tokens=[],this.end_of_word_suffix=null,this.trim_offsets="trim_offsets"in t?t.trim_offsets:!1}_call(t){return this.decode(t)}decode(t){return this.decode_chain(t).join("")}},ir=tT,rT=class extends ir{constructor(t){super(t),this.byte_decoder=Cv,this.text_decoder=new TextDecoder("utf-8",{fatal:!1,ignoreBOM:!0}),this.end_of_word_suffix=null}convert_tokens_to_string(t){let e=t.join(""),r=new Uint8Array([...e].map(n=>this.byte_decoder[n]));return this.text_decoder.decode(r)}decode_chain(t){let e=[],r=[];for(let n of t)this.added_tokens.find(s=>s.content===n)!==void 0?(r.length>0&&(e.push(this.convert_tokens_to_string(r)),r=[]),e.push(n)):r.push(n);return r.length>0&&e.push(this.convert_tokens_to_string(r)),e}},nT=rT,sT=class extends ir{constructor(t){super(t),this.cleanup=t.cleanup}decode_chain(t){return t.map((e,r)=>{if(r!==0){let n=this.config.prefix;n&&e.startsWith(n)?e=e.replace(n,""):e=" "+e}return this.cleanup&&(e=hd(e)),e})}},oT=sT,iT=class extends ir{constructor(t){super(t),this.replacement=t.replacement??"\u2581"}decode_chain(t){let e=[];for(let r=0;r<t.length;++r){let n=t[r].replaceAll(this.replacement," ");r==0&&n.startsWith(" ")&&(n=n.substring(1)),e.push(n)}return e}},aT=iT,uT=class extends ir{constructor(t){super(t),this.suffix=t.suffix??""}decode_chain(t){return t.map((e,r)=>e.replaceAll(this.suffix,r===t.length-1?"":" "))}},cT=uT,lT=class extends ir{constructor(t){super(t),this.pad_token=t.pad_token??"",this.word_delimiter_token=t.word_delimiter_token??"",this.cleanup=t.cleanup}convert_tokens_to_string(t){if(t.length===0)return"";let e=[t[0]];for(let n=1;n<t.length;++n)t[n]!==e.at(-1)&&e.push(t[n]);let r=e.filter(n=>n!==this.pad_token).join("");return this.cleanup&&(r=hd(r).replaceAll(this.word_delimiter_token," ").trim()),r}decode_chain(t){return[this.convert_tokens_to_string(t)]}},dT=lT,fT=class extends ir{constructor(t){super(t),this.decoders=(t.decoders??[]).map(e=>Hy(e))}decode_chain(t){return this.decoders.reduce((e,r)=>r.decode_chain(e),t)}},hT=fT,pT=class extends ir{decode_chain(t){let e=Na(this.config.pattern),r=this.config.content??"";return e===null?t:t.map(n=>n.replaceAll(e,r))}},mT=pT,gT=class extends ir{decode_chain(t){return[t.join("")]}},yT=gT,_T=class extends ir{constructor(t){super(t),this.content=t.content??"",this.start=t.start??0,this.stop=t.stop??0}decode_chain(t){return t.map(e=>{let r=0;for(let s=0;s<this.start&&e[s]===this.content;++s)r=s+1;let n=e.length;for(let s=0;s<this.stop;++s){let i=e.length-s-1;if(e[i]===this.content){n=i;continue}else break}return e.slice(r,n)})}},bT=_T,CT=class extends ir{constructor(t){super(t),this.text_decoder=new TextDecoder}decode_chain(t){let e=[],r=[];for(let n of t){let s=null;if(n.length===6&&n.startsWith("<0x")&&n.endsWith(">")){let i=parseInt(n.slice(3,5),16);isNaN(i)||(s=i)}if(s!==null)r.push(s);else{if(r.length>0){let i=this.text_decoder.decode(Uint8Array.from(r));e.push(i),r=[]}e.push(n)}}if(r.length>0){let n=this.text_decoder.decode(Uint8Array.from(r));e.push(n),r=[]}return e}},wT=CT;function ET(t){if(t===null)return null;switch(t.type){case"ByteLevel":return new nT(t);case"WordPiece":return new oT(t);case"Metaspace":return new aT(t);case"BPEDecoder":return new cT(t);case"CTC":return new dT(t);case"Sequence":return new hT(t);case"Replace":return new mT(t);case"Fuse":return new yT(t);case"Strip":return new bT(t);case"ByteFallback":return new wT(t);default:throw new Error(`Unknown Decoder type: ${t.type}`)}}var Hy=ET,AT=class{constructor(t,e){let r=Fy(t,"Tokenizer",["model","decoder","post_processor","pre_tokenizer","normalizer"]);if(r)throw new Error(r);let n=Fy(e,"Config");if(n)throw new Error(n);this.tokenizer=t,this.config=e,this.normalizer=My(this.tokenizer.normalizer),this.pre_tokenizer=Uy(this.tokenizer.pre_tokenizer),this.model=$k(this.tokenizer.model,this.config),this.post_processor=zy(this.tokenizer.post_processor),this.decoder=Hy(this.tokenizer.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[],this.tokenizer.added_tokens.forEach(s=>{let i=new _v(s);this.added_tokens.push(i),this.model.tokens_to_ids.set(i.content,i.id),this.model.vocab[i.id]=i.content,i.special&&(this.special_tokens.push(i.content),this.all_special_ids.push(i.id))}),(this.config.additional_special_tokens??[]).forEach(s=>{this.special_tokens.includes(s)||this.special_tokens.push(s)}),this.decoder&&(this.decoder.added_tokens=this.added_tokens,this.decoder.end_of_word_suffix=this.model.end_of_word_suffix),this.added_tokens_splitter=new gv(this.added_tokens.map(s=>s.content)),this.added_tokens_map=new Map(this.added_tokens.map(s=>[s.content,s])),this.remove_space=this.config.remove_space,this.clean_up_tokenization_spaces=this.config.clean_up_tokenization_spaces??!0,this.do_lowercase_and_remove_accent=this.config.do_lowercase_and_remove_accent??!1}encode(t,{text_pair:e=null,add_special_tokens:r=!0,return_token_type_ids:n=null}={}){let{tokens:s,token_type_ids:i}=this.tokenize_helper(t,{text_pair:e,add_special_tokens:r}),u=this.model.convert_tokens_to_ids(s),c={ids:u,tokens:s,attention_mask:new Array(u.length).fill(1)};return n&&i&&(c.token_type_ids=i),c}decode(t,e={}){if(!Array.isArray(t)||t.length===0||!vv(t[0]))throw Error("token_ids must be a non-empty array of integers.");let r=this.model.convert_ids_to_tokens(t);e.skip_special_tokens&&(r=r.filter(s=>!this.special_tokens.includes(s)));let n=this.decoder?this.decoder(r):r.join(" ");return this.decoder&&this.decoder.end_of_word_suffix&&(n=n.replaceAll(this.decoder.end_of_word_suffix," "),e.skip_special_tokens&&(n=n.trim())),(e.clean_up_tokenization_spaces??this.clean_up_tokenization_spaces)&&(n=hd(n)),n}tokenize(t,{text_pair:e=null,add_special_tokens:r=!1}={}){return this.tokenize_helper(t,{text_pair:e,add_special_tokens:r}).tokens}encode_text(t){if(t===null)return null;let e=this.added_tokens_splitter.split(t);return e.forEach((r,n)=>{let s=this.added_tokens_map.get(r);s&&(s.lstrip&&n>0&&(e[n-1]=e[n-1].trimEnd()),s.rstrip&&n<e.length-1&&(e[n+1]=e[n+1].trimStart()))}),e.flatMap((r,n)=>{if(r.length===0)return[];if(this.added_tokens_map.has(r))return[r];if(this.remove_space===!0&&(r=r.trim().split(/\s+/).join(" ")),this.do_lowercase_and_remove_accent&&(r=Tv(r)),this.normalizer!==null&&(r=this.normalizer(r)),r.length===0)return[];let s=this.pre_tokenizer!==null?this.pre_tokenizer(r,{section_index:n}):[r];return this.model(s)})}tokenize_helper(t,{text_pair:e=null,add_special_tokens:r=!0}){let n=this.encode_text(t),s=this.encode_text(e||null);return this.post_processor?this.post_processor(n,s,r):{tokens:xt(n??[],s??[])}}token_to_id(t){return this.model.tokens_to_ids.get(t)}id_to_token(t){return this.model.vocab[t]}get_added_tokens_decoder(){let t=new Map;for(let e of this.added_tokens)t.set(e.id,e);return t}},Wy=AT;var Ua=class{type="huggingface";name;modelId;logger;options;tokenizer=null;cacheDir;safeModelName;constructor(e,r,n={}){this.modelId=e,this.logger=r,this.options=n,this.cacheDir=n.cacheDir||La(ST(),".claude-code-router",".huggingface"),this.safeModelName=e.replace(/\//g,"_").replace(/[^a-zA-Z0-9_-]/g,"_"),this.name=`huggingface-${e.split("/").pop()}`}getCachePaths(){let e=La(this.cacheDir,this.safeModelName);return{modelDir:e,tokenizerJson:La(e,"tokenizer.json"),tokenizerConfig:La(e,"tokenizer_config.json")}}ensureDir(e){md(e)||vT(e,{recursive:!0})}async loadFromCache(){try{let e=this.getCachePaths();if(!md(e.tokenizerJson)||!md(e.tokenizerConfig))return null;let[r,n]=await Promise.all([Ma.readFile(e.tokenizerJson,"utf-8"),Ma.readFile(e.tokenizerConfig,"utf-8")]);return{tokenizerJson:JSON.parse(r),tokenizerConfig:JSON.parse(n)}}catch(e){return this.logger?.warn(`Failed to load from cache: ${e.message}`),null}}async downloadAndCache(){let e=this.getCachePaths(),r={json:`https://huggingface.co/${this.modelId}/resolve/main/tokenizer.json`,config:`https://huggingface.co/${this.modelId}/resolve/main/tokenizer_config.json`};this.logger?.info(`Downloading tokenizer files for ${this.modelId}`);let n=new AbortController,s=setTimeout(()=>n.abort(),this.options.timeout||3e4);try{let[i,u]=await Promise.all([fetch(r.json,{signal:n.signal}),fetch(r.config,{signal:n.signal})]);if(!i.ok)throw new Error(`Failed to fetch tokenizer.json: ${i.statusText}`);let[c,l]=await Promise.all([i.json(),u.ok?u.json():Promise.resolve({})]);return this.ensureDir(e.modelDir),await Promise.all([Ma.writeFile(e.tokenizerJson,JSON.stringify(c,null,2)),Ma.writeFile(e.tokenizerConfig,JSON.stringify(l,null,2))]),{tokenizerJson:c,tokenizerConfig:l}}finally{clearTimeout(s)}}async initialize(){try{this.logger?.info(`Initializing HuggingFace tokenizer: ${this.modelId}`);let e=this.getCachePaths();this.ensureDir(this.cacheDir);let r=await this.loadFromCache()||await this.downloadAndCache();this.tokenizer=new Wy(r.tokenizerJson,r.tokenizerConfig),this.logger?.info(`Tokenizer initialized: ${this.name}`)}catch(e){throw this.logger?.error(`Failed to initialize tokenizer: ${e.message}`),new Error(`Failed to initialize HuggingFace tokenizer for ${this.modelId}: ${e.message}`)}}async countTokens(e){if(!this.tokenizer)throw new Error("Tokenizer not initialized");try{let r=this.extractTextFromRequest(e);return this.tokenizer.encode(r).ids.length}catch(r){throw this.logger?.error(`Error counting tokens: ${r.message}`),r}}isInitialized(){return this.tokenizer!==null}encodeText(e){if(!this.tokenizer)throw new Error("Tokenizer not initialized");return this.tokenizer.encode(e).ids}dispose(){this.tokenizer=null}extractTextFromRequest(e){let r=[],{messages:n,system:s,tools:i}=e;if(Array.isArray(n)){for(let u of n)if(typeof u.content=="string")r.push(u.content);else if(Array.isArray(u.content))for(let c of u.content)c.type==="text"&&c.text?r.push(c.text):c.type==="tool_use"&&c.input?r.push(JSON.stringify(c.input)):c.type==="tool_result"&&r.push(typeof c.content=="string"?c.content:JSON.stringify(c.content))}if(typeof s=="string")r.push(s);else if(Array.isArray(s)){for(let u of s)if(u.type==="text"){if(typeof u.text=="string")r.push(u.text);else if(Array.isArray(u.text))for(let c of u.text)c&&r.push(c)}}if(i)for(let u of i)u.name&&r.push(u.name),u.description&&r.push(u.description),u.input_schema&&r.push(JSON.stringify(u.input_schema));return r.join(" ")}};var qa=class{type="api";name;config;logger;options;constructor(e,r,n={}){if(!e.url||!e.apiKey)throw new Error("API tokenizer requires url and apiKey");this.config={url:e.url,apiKey:e.apiKey,requestFormat:e.requestFormat||"standard",responseField:e.responseField||"token_count",headers:e.headers||{}},this.logger=r,this.options=n;try{let s=new URL(e.url);this.name=`api-${s.hostname}`}catch{this.name=`api-${e.url}`}}async initialize(){try{new URL(this.config.url)}catch{throw new Error(`Invalid API URL: ${this.config.url}`)}}async countTokens(e){try{let r=this.formatRequestBody(e),n={"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,...this.config.headers},s=new AbortController,i=setTimeout(()=>s.abort(),this.options.timeout||3e4),u=await fetch(this.config.url,{method:"POST",headers:n,body:JSON.stringify(r),signal:s.signal});if(clearTimeout(i),!u.ok)throw new Error(`API tokenizer request failed: ${u.status} ${u.statusText}`);let c=await u.json();return this.extractTokenCount(c)}catch(r){throw r.name==="AbortError"?new Error("API tokenizer request timed out"):r}}isInitialized(){return!0}dispose(){}formatRequestBody(e){switch(this.config.requestFormat){case"standard":return e;case"openai":return{model:"gpt-3.5-turbo",messages:this.extractMessagesAsOpenAIFormat(e)};case"anthropic":return{messages:e.messages||[],system:e.system,tools:e.tools};case"custom":return{text:this.extractConcatenatedText(e)};default:return e}}extractMessagesAsOpenAIFormat(e){return e.messages?e.messages.map(r=>({role:r.role,content:this.extractTextFromMessage(r)})):[]}extractTextFromMessage(e){return typeof e.content=="string"?e.content:Array.isArray(e.content)?e.content.map(r=>r.type==="text"&&r.text?r.text:r.type==="tool_use"&&r.input?JSON.stringify(r.input):r.type==="tool_result"?typeof r.content=="string"?r.content:JSON.stringify(r.content):"").join(" "):""}extractConcatenatedText(e){let r=[];return e.messages&&e.messages.forEach(n=>{r.push(this.extractTextFromMessage(n))}),typeof e.system=="string"?r.push(e.system):Array.isArray(e.system)&&e.system.forEach(n=>{n.type==="text"&&(typeof n.text=="string"?r.push(n.text):Array.isArray(n.text)&&n.text.forEach(s=>{s&&r.push(s)}))}),e.tools&&e.tools.forEach(n=>{n.name&&r.push(n.name),n.description&&r.push(n.description),n.input_schema&&r.push(JSON.stringify(n.input_schema))}),r.join(" ")}extractTokenCount(e){try{let r=this.config.responseField,n=r.split("."),s=e;for(let i of n){if(s==null)throw new Error(`Field path '${r}' not found in response`);s=s[i]}if(typeof s!="number")throw new Error(`Expected number at field path '${r}', got ${typeof s}`);return s}catch(r){throw this.logger?.error(`Failed to extract token count from API response: ${r.message}. Response: ${JSON.stringify(e)}`),new Error(`Invalid response from API tokenizer: ${r.message}`)}}};var cs=class{tokenizers=new Map;configService;logger;options;fallbackTokenizer;constructor(e,r,n={}){this.configService=e,this.logger=r,this.options={timeout:n.timeout??3e4,...n}}async initialize(){try{this.fallbackTokenizer=new eo("cl100k_base"),await this.fallbackTokenizer.initialize(),this.tokenizers.set("fallback",this.fallbackTokenizer),this.logger?.info("TokenizerService initialized successfully")}catch(e){throw this.logger?.error(`TokenizerService initialization error: ${e.message}`),e}}async getTokenizer(e){let r=this.getCacheKey(e);if(this.tokenizers.has(r))return this.tokenizers.get(r);let n;try{switch(e.type){case"tiktoken":n=new eo(e.encoding||"cl100k_base");break;case"huggingface":this.logger?.info(`Initializing HuggingFace tokenizer for model: ${e.model}`),n=new Ua(e.model,this.logger,{timeout:this.options.timeout});break;case"api":n=new qa(e,this.logger,{timeout:this.options.timeout});break;default:throw new Error(`Unknown tokenizer type: ${e.type}`)}return this.logger?.info(`Calling initialize() on ${e.type} tokenizer...`),await n.initialize(),this.tokenizers.set(r,n),this.logger?.info(`Tokenizer initialized successfully: ${e.type} (${r})`),n}catch(s){return this.logger?.error(`Failed to initialize ${e.type} tokenizer: ${s.message}`),this.logger?.error(`Error stack: ${s.stack}`),this.fallbackTokenizer||await this.initialize(),this.fallbackTokenizer}}async countTokens(e,r){let n=r?await this.getTokenizer(r):this.fallbackTokenizer;return{tokenCount:await n.countTokens(e),tokenizerUsed:n.name,cached:!1}}getTokenizerConfigForModel(e,r){let s=(this.configService.get("providers")||[]).find(i=>i.name===e);if(s?.tokenizer)return s.tokenizer.models?.[r]?s.tokenizer.models[r]:s.tokenizer.default}dispose(){this.tokenizers.forEach(e=>{try{e.dispose()}catch(r){this.logger?.error(`Error disposing tokenizer: ${r}`)}}),this.tokenizers.clear()}getCacheKey(e){switch(e.type){case"tiktoken":return`tiktoken:${e.encoding||"cl100k_base"}`;case"huggingface":return`hf:${e.model}`;case"api":return`api:${e.url}`;default:return`unknown:${JSON.stringify(e)}`}}};import{get_encoding as kT}from"tiktoken";var gd=class{capacity;cache;constructor(e){this.capacity=e,this.cache=new Map}get(e){if(!this.cache.has(e))return;let r=this.cache.get(e);return this.cache.delete(e),this.cache.set(e,r),r}put(e,r){if(this.cache.has(e))this.cache.delete(e);else if(this.cache.size>=this.capacity){let n=this.cache.keys().next().value;n!==void 0&&this.cache.delete(n)}this.cache.set(e,r)}values(){return Array.from(this.cache.values())}},yd=new gd(100);import{readFile as bd}from"fs/promises";import{opendir as TT,stat as DT}from"fs/promises";import{join as Cd}from"path";import{CLAUDE_PROJECTS_DIR as Gy,HOME_DIR as Jy}from"@wengine-ai/claude-code-router-shared";var vr=kT("cl100k_base"),Ky=(t,e,r)=>{let n=0;return Array.isArray(t)&&t.forEach(s=>{typeof s.content=="string"?n+=vr.encode(s.content).length:Array.isArray(s.content)&&s.content.forEach(i=>{i.type==="text"?n+=vr.encode(i.text).length:i.type==="tool_use"?n+=vr.encode(JSON.stringify(i.input)).length:i.type==="tool_result"&&(n+=vr.encode(typeof i.content=="string"?i.content:JSON.stringify(i.content)).length)})}),typeof e=="string"?n+=vr.encode(e).length:Array.isArray(e)&&e.forEach(s=>{s.type==="text"&&(typeof s.text=="string"?n+=vr.encode(s.text).length:Array.isArray(s.text)&&s.text.forEach(i=>{n+=vr.encode(i||"").length}))}),r&&r.forEach(s=>{s.description&&(n+=vr.encode(s.name+s.description).length),s.input_schema&&(n+=vr.encode(JSON.stringify(s.input_schema)).length)}),n},Yy=async(t,e)=>{if(t.sessionId){let r=await Xy(t.sessionId);if(r){let n=Cd(Jy,r,"config.json"),s=Cd(Jy,r,`${t.sessionId}.json`);try{let i=JSON.parse(await bd(s,"utf8"));if(i&&i.Router)return i.Router}catch{}try{let i=JSON.parse(await bd(n,"utf8"));if(i&&i.Router)return i.Router}catch{}}}};function $a(t){let e=t||"";return e.includes(",")&&(e=e.split(",").pop()||e),e.includes("/")&&(e=e.split("/").pop()||e),e.includes(":")&&(e=e.split(":")[0]),e.trim().toLowerCase()}function Qy(t){let e=$a(t),r=e.includes("[1m]")||e.endsWith("[1m"),n=e.replace(/\[1m\]|\[1m$/g,""),s=n.match(/^ccr-(opus|sonnet|haiku)$/i);if(s)return{family:s[1].toLowerCase(),extended:r};let i=n.match(/claude-(?:\d+-\d+-|\d+-)?(sonnet|opus|haiku)(?:-|$)/i)||n.match(/claude-(sonnet|opus|haiku)(?:-|$)/i);return i?{family:i[1].toLowerCase(),extended:r}:{family:null,extended:r}}function RT(t,e){if(!e||!t)return null;let r=$a(t);if(e[t])return e[t];if(e[r])return e[r];let{family:n}=Qy(t);if(n&&e[n])return e[n];for(let[s,i]of Object.entries(e)){let u=$a(s);if(u&&r.includes(u))return i}return null}function ar(t,e,r){if(!t?.includes(","))return t;let[n,...s]=t.split(","),i=n.trim(),u=s.join(",").trim();if(!r&&!Gt().isAvailable(i,u))return null;let c=e.find(h=>h.name.toLowerCase()===i.toLowerCase()),l=c?.models?.find(h=>String(h).toLowerCase()===u.toLowerCase());return c&&l?`${c.name},${l}`:t}function xT(t){return t.body.messages?.some(e=>e.role==="user"&&Array.isArray(e.content)&&e.content.some(r=>r.type==="image"||r.type==="image_url"||Array.isArray(r?.content)&&r.content.some(n=>n.type==="image"||n.type==="image_url")))}function OT(t){let e=$a(t);return[/claude/i,/gemini/i,/gpt-4o/i,/gpt-4\.1/i,/gpt-4-vision/i,/qwen.*vl/i,/glm-4v/i,/grok.*vision/i,/pixtral/i,/llava/i].some(n=>n.test(e))}function FT(t,e,r,n,s,i){let u=r.longContextThreshold||6e4;if((i||e>2e5)&&r.extendedContext){let p=ar(r.extendedContext,n);if(p)return t.log.info(`Family: using extended context model (1M+), tokens: ${e}, explicit: ${i}`),{model:p,scenarioType:"extendedContext"};t.log.warn("Family: extendedContext model unavailable (fail pool), skipping")}let h=s&&s.input_tokens>u&&e>2e4,d=e>u;if((h||d)&&r.longContext){let p=ar(r.longContext,n);if(p)return t.log.info(`Family: using long context model, tokens: ${e}`),{model:p,scenarioType:"longContext"};let w=r.fallback?.longContext||[];if(w.length>0){t.log.warn("Family: longContext primary unhealthy, searching longContext fallback list");for(let S of w){let y=ar(S,n);if(y)return t.log.info(`Family: using longContext fallback ${S} as primary`),{model:y,scenarioType:"longContext"}}t.log.warn("Family: all longContext fallback models unhealthy")}let T=ar(r.longContext,n,!0);if(T)return t.log.warn("Family: no healthy longContext model, forcing primary to keep scenarioType=longContext"),{model:T,scenarioType:"longContext"}}if(Array.isArray(t.body.tools)&&t.body.tools.some(p=>p.type?.startsWith("web_search"))&&r.webSearch){let p=ar(r.webSearch,n);if(p)return{model:p,scenarioType:"webSearch"};t.log.warn("Family: webSearch model unavailable (fail pool), skipping")}if(t.body.thinking&&r.think){let p=ar(r.think,n);if(p)return{model:p,scenarioType:"think"};t.log.warn("Family: think model unavailable (fail pool), skipping")}if(r.default){let p=ar(r.default,n);if(p)return{model:p,scenarioType:"default"};t.log.warn("Family: default model unavailable (fail pool), skipping")}return null}var PT=async(t,e,r,n)=>{let s=await Yy(t,r),i=r.get("providers")||[],u=s||r.get("Router");if(t.body.model.includes(",")){let g=ar(t.body.model,i);if(g)return{model:g,scenarioType:"default"};t.log.warn(`Explicit model ${t.body.model} unavailable (fail pool), trying alternatives`)}let{family:c,extended:l}=Qy(t.body.model),h=u?.families?.[c||""];if(h){t.log.info(`Using model family routing for: ${c}${l?" (1M)":""}`),t.modelFamily=c,t.familyFallback=h.fallback;let g=FT(t,e,h,i,n,l);if(g)return g}let d=RT(t.body.model,u?.models);if(d){let g=ar(d,i);if(g)return t.log.info(`Using mapped model for ${t.body.model}: ${d}`),{model:g,scenarioType:"modelMapping"};t.log.warn(`Mapped model ${d} unavailable (fail pool), skipping`)}let p=u?.extendedContextThreshold||2e5;if(e>p&&u?.extendedContext)return t.log.info(`Using extended context (1M) model due to token count: ${e}, threshold: ${p}`),{model:u.extendedContext,scenarioType:"extendedContext"};let w=u?.longContextThreshold||6e4,T=n&&n.input_tokens>w&&e>2e4,S=e>w;if((T||S)&&u?.longContext)return t.log.info(`Using long context model due to token count: ${e}, threshold: ${w}`),{model:u.longContext,scenarioType:"longContext"};if(t.body?.system?.length>1&&t.body?.system[1]?.text?.startsWith("<CCR-SUBAGENT-MODEL>")){let g=t.body?.system[1].text.match(/<CCR-SUBAGENT-MODEL>(.*?)<\/CCR-SUBAGENT-MODEL>/s);if(g)return t.body.system[1].text=t.body.system[1].text.replace(`<CCR-SUBAGENT-MODEL>${g[1]}</CCR-SUBAGENT-MODEL>`,""),{model:g[1],scenarioType:"default"}}let y=r.get("Router");return t.body.model?.includes("claude")&&t.body.model?.includes("haiku")&&y?.background?(t.log.info(`Using background model for ${t.body.model}`),{model:y.background,scenarioType:"background"}):Array.isArray(t.body.tools)&&t.body.tools.some(g=>g.type?.startsWith("web_search"))&&u?.webSearch?{model:u.webSearch,scenarioType:"webSearch"}:t.body.thinking&&u?.think?(t.log.info(`Using think model for ${t.body.thinking}`),{model:u.think,scenarioType:"think"}):{model:u?.default,scenarioType:"default"}},wd=async(t,e,r)=>{let{configService:n,event:s}=r;if(t.originalModel=t.body.model,t.body.metadata?.user_id){let T=t.body.metadata.user_id.split("_session_");T.length>1&&(t.sessionId=T[1])}let u=await Yy(t,n)||n.get("Router"),c=n.get("providers")||[],l=yd.get(t.sessionId),{messages:h,system:d=[],tools:p}=t.body,w=n.get("REWRITE_SYSTEM_PROMPT");if(w&&d.length>1&&d[1]?.text?.includes("<env>")){let T=await bd(w,"utf-8");d[1].text=`${T}<env>${d[1].text.split("<env>").pop()}`}try{let[T,S]=t.body.model.split(","),y=r.tokenizerService?.getTokenizerConfigForModel(T,S),g;r.tokenizerService?g=(await r.tokenizerService.countTokens({messages:h,system:d,tools:p},y)).tokenCount:g=Ky(h,d,p),t.tokenCount=g;let m,v=n.get("CUSTOM_ROUTER_PATH");if(v)try{m=await X(v)(t,n.getAll(),{event:s})}catch(b){t.log.error(`failed to load custom router: ${b.message}`)}if(m)t.scenarioType="default";else{let b=await PT(t,g,n,l);m=b.model,t.scenarioType=b.scenarioType}if(u?.image&&m!==u.image&&xT(t)&&!OT(m)){let b=ar(u.image,c);b?(t.log.info(`Using image model fallback for ${m}`),m=b,t.scenarioType="image"):t.log.warn(`Image model ${u.image} unavailable (fail pool), keeping ${m}`)}t.body.model=m}catch(T){t.log.error(`Error in router middleware: ${T.message}`),t.body.model=u?.default,t.scenarioType="default"}},kr=new Map,Vy=1e3;function _d(){if(kr.size<=Vy)return;let t=[...kr.keys()].slice(0,kr.size-Vy);for(let e of t)kr.delete(e)}var Xy=async t=>{if(kr.has(t)){let e=kr.get(t);return!e||e===""?null:e}try{let e=await TT(Gy),r=[];for await(let i of e)i.isDirectory()&&r.push(i.name);let n=r.map(async i=>{let u=Cd(Gy,i,`${t}.jsonl`);try{return(await DT(u)).isFile()?i:null}catch{return null}}),s=await Promise.all(n);for(let i of s)if(i)return kr.set(t,i),_d(),i;return kr.set(t,""),_d(),null}catch(e){return console.error("Error searching for project by session:",e),kr.set(t,""),_d(),null}};var so=class{async fetchJson(e,r,n,s){if(!r.apiKey)return null;let i={method:"GET",headers:{Accept:"application/json",Authorization:`Bearer ${r.apiKey}`},signal:AbortSignal.timeout(n)};if(s)try{let{ProxyAgent:u}=await import("undici");i.dispatcher=new u(new URL(s).toString())}catch{}try{let u=await fetch(e,i);return u.ok?await u.json():null}catch{return null}}hasQuotaData(e){return e.totalBalance!==void 0||e.usedBalance!==void 0||e.remainingBalance!==void 0||e.usedDailyBalance!==void 0||e.resetTime!==void 0}},Ed=class extends so{async queryQuota(e,r,n){let s=await this.fetchJson("https://api.deepseek.com/user/balance",e,r,n),u=(Array.isArray(s?.balance_infos)?s.balance_infos:[]).find(l=>Vr(l?.total_balance)!==void 0);if(!u)return null;let c=Vr(u.total_balance);return c===void 0?null:{totalBalance:c,currency:typeof u.currency=="string"?u.currency:void 0}}},Ad=class extends so{async queryQuota(e,r,n){let i=(await this.fetchJson("https://openrouter.ai/api/v1/key",e,r,n))?.data;if(!i||typeof i!="object")return null;let u={},c=Vr(i.limit),l=Vr(i.limit_remaining),h=Vr(i.usage),d=Vr(i.usage_daily);return c!==void 0&&(u.totalBalance=c),l!==void 0&&(u.remainingBalance=l),h!==void 0&&(u.usedBalance=h),d!==void 0&&(u.usedDailyBalance=d),this.hasQuotaData(u)?u:null}},Sd=class extends so{async queryQuota(e,r,n){let s=jT(e.baseUrl),u=(await this.fetchJson(s,e,r,n))?.data;if(!u||typeof u!="object")return null;let c={},l=Vr(u.totalBalance),h=Vr(u.balance);return l!==void 0&&(c.totalBalance=l),h!==void 0&&(c.remainingBalance=h),l!==void 0&&h!==void 0&&(c.usedBalance=Math.max(0,l-h)),this.hasQuotaData(c)?c:null}},IT=new Ed,NT=new Ad,BT=new Sd;function vd(t){let e=Zy(t);return e?e==="deepseek.com"||e.endsWith(".deepseek.com")?IT:e==="openrouter.ai"||e.endsWith(".openrouter.ai")?NT:e==="siliconflow.com"||e.endsWith(".siliconflow.com")||e==="siliconflow.cn"||e.endsWith(".siliconflow.cn")?BT:null:null}function jT(t){let e=Zy(t);return e?.endsWith(".siliconflow.cn")||e==="siliconflow.cn"?"https://api.siliconflow.cn/v1/user/info":"https://api.siliconflow.com/v1/user/info"}function Zy(t){try{return new URL(t).hostname.toLowerCase()}catch{return null}}function Vr(t){if(typeof t=="number")return Number.isFinite(t)?t:void 0;if(typeof t!="string")return;let e=t.trim().replace(/,/g,"");if(!e)return;let r=Number(e);return Number.isFinite(r)?r:void 0}var kd=new Map;function Td(t,e){t&&kd.set(t,{...e,provider:t,capturedAt:Date.now()})}function LT(t){let e=kd.get(t);return e?{...e}:void 0}function MT(){return Array.from(kd.values()).map(t=>({...t}))}var UT={enabled:!0,quotaProbeIntervalMinutes:10,probeTimeoutMs:15e3,initialDelayMs:5e3,excludeProviders:[]};function qT(t){try{let e=new URL(t),r=e.pathname;return r.endsWith("/v1/messages")?r=r.slice(0,-12):r.endsWith("/messages")?r=r.slice(0,-9):r.endsWith("/v1/chat/completions")?r=r.slice(0,-20):r.endsWith("/chat/completions")&&(r=r.slice(0,-17)),r.endsWith("/v1")||(r=r.endsWith("/")?`${r}v1`:`${r}/v1`),e.pathname=`${r}/models`,e.toString()}catch{return null}}function $T(t){try{let e=new URL(t).hostname.toLowerCase();return e.includes("moonshot")||e.includes("kimi")}catch{return!1}}async function Dd(t,e,r){let n=qT(t.baseUrl);if(!n)return{success:!1,error:"Cannot derive models endpoint from baseUrl"};try{let s={method:"GET",headers:{Authorization:`Bearer ${t.apiKey}`},signal:AbortSignal.timeout(e)};if(r)try{let{ProxyAgent:c}=await import("undici");s.dispatcher=new c(new URL(r).toString())}catch{}let i=await fetch(n,s);if(i.headers&&Es(t.name,t.baseUrl,i.headers),i.ok)return{success:!0,headers:i.headers};if(i.status===401||i.status===403)return{success:!0,headers:i.headers};let u=await i.text().catch(()=>"");return{success:!1,error:`HTTP ${i.status}: ${u.slice(0,100)}`,headers:i.headers}}catch(s){return{success:!1,error:s?.message||s?.toString()||"Unknown probe error"}}}var za=class{config;quotaProbeTimer;healthProbeTimer;getProviders;getHttpsProxy;logger;running=!1;constructor(e,r,n,s){this.config={...UT,...r},this.getProviders=e,this.getHttpsProxy=n,this.logger=s}start(){!this.config.enabled||this.running||(this.running=!0,setTimeout(()=>{this.running&&(this.runQuotaProbe(),this.runHealthProbe())},this.config.initialDelayMs),this.quotaProbeTimer=setInterval(()=>this.runQuotaProbe(),this.config.quotaProbeIntervalMinutes*60*1e3),this.healthProbeTimer=setInterval(()=>this.runHealthProbe(),300*1e3),this.logger?.info("Active probe service started"))}stop(){this.running=!1,this.quotaProbeTimer&&(clearInterval(this.quotaProbeTimer),this.quotaProbeTimer=void 0),this.healthProbeTimer&&(clearInterval(this.healthProbeTimer),this.healthProbeTimer=void 0),this.logger?.info("Active probe service stopped")}async runQuotaProbe(){let e=this.getProviders().filter(i=>i?.name&&!this.config.excludeProviders.includes(i.name)),r=this.getHttpsProxy?.();if(e.length===0)return;let n=[];for(let i of e){let u=vd(i.baseUrl);u&&n.push({provider:i.name,type:"quota-adapter",promise:u.queryQuota(i,this.config.probeTimeoutMs,r).then(c=>{c&&(Td(i.name,c),this.logger?.debug?.(`Stored quota probe result for ${i.name}`))})}),$T(i.baseUrl)&&n.push({provider:i.name,type:"rate-limit-headers",promise:Dd(i,this.config.probeTimeoutMs,r).then(()=>{})})}if(n.length===0)return;this.logger?.debug?.(`Running quota probe with ${n.length} tasks for ${e.length} providers`);let s=await Promise.allSettled(n.map(i=>i.promise));for(let i=0;i<n.length;i++){let u=s[i];if(u.status==="rejected"){let c=n[i];this.logger?.warn?.(`Quota probe failed for ${c.provider} (${c.type}): ${u.reason}`)}}}async runHealthProbe(){let e=Gt(),r=this.getProviders(),n=this.getHttpsProxy?.(),s=e.getFailPoolModels(),i=[];for(let c of s){let[l,h]=c.split(","),d=e.getState(l,h);if(d&&d.status==="open"&&e.needsProbe(d)){let p=r.find(w=>w.name===l);p&&!this.config.excludeProviders.includes(l)&&i.push({provider:p,model:h,state:d})}}if(i.length===0)return;this.logger?.debug?.(`Running health probe for ${i.length} open models`);for(let{provider:c,model:l}of i)e.markProbeAttempt(c.name,l);let u=await Promise.allSettled(i.map(({provider:c})=>Dd(c,this.config.probeTimeoutMs,n)));for(let c=0;c<i.length;c++){let{provider:l,model:h}=i[c],d=u[c];if(d.status==="fulfilled"){let p=d.value;if(p.success){for(let w of l.models)e.recordSuccess(l.name,w);this.logger?.info?.(`Health probe succeeded for ${l.name}`)}else{for(let w of l.models)e.recordFailure(l.name,w,p.error);this.logger?.warn?.(`Health probe failed for ${l.name}: ${p.error}`)}}else{for(let p of l.models)e.recordFailure(l.name,p,d.reason?.message||"Probe error");this.logger?.warn?.(`Health probe error for ${l.name}: ${d.reason}`)}}}async probeProviderManually(e){let n=this.getProviders().find(u=>u.name===e);if(!n)return this.logger?.warn?.(`Provider ${e} not found for manual probe`),!1;let s=this.getHttpsProxy?.(),i=await Dd(n,this.config.probeTimeoutMs,s);if(i.success)for(let u of n.models)Gt().recordSuccess(n.name,u);else for(let u of n.models)Gt().recordFailure(n.name,u,i.error);return i.success}},Kr=null;function e0(t,e,r,n){return Kr||(Kr=new za(t,e,r,n)),Kr}function Rd(t,e,r,n){let s=e0(t,e,r,n);return s.start(),s}function xd(){Kr&&Kr.stop()}function zT(){Kr&&(Kr.stop(),Kr=null)}var Od=class{plugins=new Map;pluginInstances=new Map;registerPlugin(e,r={}){this.pluginInstances.set(e.name,e),this.plugins.set(e.name,{name:e.name,enabled:r.enabled!==!1,options:r})}async enablePlugin(e,r){let n=this.plugins.get(e),s=this.pluginInstances.get(e);if(!n||!s)throw new Error(`Plugin ${e} not found`);n.enabled&&await r.register(s.register,n.options)}async enablePlugins(e){for(let[r,n]of this.plugins)if(n.enabled)try{await this.enablePlugin(r,e)}catch(s){let i=s instanceof Error?s.message:String(s);e.log?.error(`Failed to enable plugin ${r}: ${i}`)}}getPlugins(){return Array.from(this.plugins.values())}getPlugin(e){return this.pluginInstances.get(e)}hasPlugin(e){return this.pluginInstances.has(e)}isPluginEnabled(e){return this.plugins.get(e)?.enabled||!1}setPluginEnabled(e,r){let n=this.plugins.get(e);n&&(n.enabled=r)}removePlugin(e){this.plugins.delete(e),this.pluginInstances.delete(e)}clear(){this.plugins.clear(),this.pluginInstances.clear()}},t0=new Od;var f0=Nr(i0(),1);var ls=class extends TransformStream{buffer="";currentEvent={};constructor(){super({transform:(e,r)=>{this.buffer+=e;let n=this.buffer.split(`
|
|
341
|
+
`);this.buffer=n.pop()||"";for(let s of n){let i=this.processLine(s);i&&r.enqueue(i)}},flush:e=>{if(this.buffer.trim()){let r=[];this.processLine(this.buffer.trim(),r),r.forEach(n=>e.enqueue(n))}Object.keys(this.currentEvent).length>0&&e.enqueue(this.currentEvent)}})}processLine(e,r){if(!e.trim()){if(Object.keys(this.currentEvent).length>0){let n={...this.currentEvent};return this.currentEvent={},r?(r.push(n),null):n}return null}if(e.startsWith("event:"))this.currentEvent.event=e.slice(6).trim();else if(e.startsWith("data:")){let n=e.slice(5).trim();if(n==="[DONE]")this.currentEvent.data={type:"done"};else try{this.currentEvent.data=JSON.parse(n)}catch{this.currentEvent.data={raw:n,error:"JSON parse failed"}}}else e.startsWith("id:")?this.currentEvent.id=e.slice(3).trim():e.startsWith("retry:")&&(this.currentEvent.retry=parseInt(e.slice(6).trim()));return null}};var Wa=class extends TransformStream{constructor(){super({transform:(e,r)=>{let n="";e.event&&(n+=`event: ${e.event}
|
|
342
342
|
`),e.id&&(n+=`id: ${e.id}
|
|
343
343
|
`),e.retry&&(n+=`retry: ${e.retry}
|
|
344
344
|
`),e.data&&(e.data.type==="done"?n+=`data: [DONE]
|
|
345
345
|
`:n+=`data: ${JSON.stringify(e.data)}
|
|
346
346
|
`),n+=`
|
|
347
|
-
`,r.enqueue(n)}})}};var
|
|
347
|
+
`,r.enqueue(n)}})}};var a0=(t,e)=>{let r=t.getReader();return new ReadableStream({async start(n){try{for(;;){let{done:s,value:i}=await r.read();if(s){n.close();break}let u=await e(i,n);u!==void 0&&n.enqueue(u)}}catch(s){n.error(s)}finally{r.releaseLock()}}})};Id();Nd();Bd();c0();var uo=new Map,Ld=new Map,ZT=1,h0={name:"token-speed",version:"1.0.0",description:"Statistics for streaming response token generation speed",register:(0,f0.default)(async(t,e)=>{let r={reporter:["console","temp-file"],...e},n=Array.isArray(r.reporter)?r.reporter:[r.reporter];if(r.outputHandlers&&r.outputHandlers.length>0)ds.registerHandlers(r.outputHandlers);else{let i=[];for(let u of n)u==="console"?i.push({type:"console",enabled:!0,config:{colors:!0,level:"log"}}):u==="temp-file"?i.push({type:"temp-file",enabled:!0,config:{subdirectory:"claude-code-router",extension:"json",includeTimestamp:!0,prefix:"session"}}):u==="webhook"&&console.warn("[TokenSpeedPlugin] Webhook reporter requires explicit configuration in outputHandlers");i.length>0&&ds.registerHandlers(i)}r.outputOptions&&ds.setDefaultOptions(r.outputOptions);let s=async i=>{let u=t.tokenizerService;if(!u)return t.log?.warn("TokenizerService not available"),null;if(!i.provider||!i.model)return null;let c=i.provider,l=i.model,h=`${c}:${l}`;if(Ld.has(h))return Ld.get(h);let d=u.getTokenizerConfigForModel(c,l);if(!d)return t.log?.debug(`No tokenizer config for ${c}:${l}, using fallback`),null;try{let p=await u.getTokenizer(d);return Ld.set(h,p),t.log?.info(`Created tokenizer for ${c}:${l} - ${p.name}`),p}catch(p){return t.log?.warn(`Failed to create tokenizer for ${c}:${l}: ${p.message}`),null}};t.addHook("onRequest",async i=>{new URL(`http://127.0.0.1${i.url}`).pathname.endsWith("/v1/messages")&&(i.requestStartTime=performance.now())}),t.addHook("onSend",async(i,u,c)=>{let l=i.requestStartTime;if(!l)return;let h=i.id||Date.now().toString(),d;try{let y=i.body?.metadata?.user_id;if(y&&typeof y=="string")try{let g=JSON.parse(y);g.session_id&&(d=g.session_id)}catch{let g=y.match(/_session_([a-f0-9-]+)/i);d=g?g[1]:void 0}}catch{}if(!d)return;let p=await s(i);if(c instanceof ReadableStream){uo.set(h,{requestId:h,sessionId:d,startTime:l,lastTokenTime:l,tokenCount:0,tokensPerSecond:0,tokenTimestamps:[],stream:!0});let[y,g]=c.tee();return(async()=>{let v=null,b=async A=>{let R=uo.get(h);if(!R)return;let F=performance.now();if(A){let $=R.firstTokenTime?R.firstTokenTime-R.startTime:0,J=R.lastTokenTime-R.startTime;R.tokensPerSecond=l0(R.tokenCount,J,$)}else{let $=F-1e3;R.tokenTimestamps=R.tokenTimestamps.filter(J=>J>$),R.tokensPerSecond=R.tokenTimestamps.length}await d0(R,n,r.outputOptions,A).catch($=>{t.log?.warn(`Failed to output streaming stats: ${$.message}`)})};try{let R=g.pipeThrough(new TextDecoderStream).pipeThrough(new ls).getReader();for(v=setInterval(async()=>{uo.get(h)&&await b(!1)},1e3);;){let{done:F,value:$}=await R.read();if(F)break;let J=$,M=uo.get(h);if(!M)continue;let Q=performance.now();if(!M.firstTokenTime&&(J.event==="content_block_start"||J.event==="content_block_delta"||J.event==="text_block"||J.event==="content_block")&&(M.firstTokenTime=Q,M.timeToFirstToken=Math.round(Q-M.startTime)),J.event==="content_block_delta"&&J.data?.delta){let ue=J.data.delta.type,re="";if(ue==="text_delta"?re=J.data.delta.text||"":ue==="input_json_delta"?re=J.data.delta.partial_json||"":ue==="thinking_delta"&&(re=J.data.delta.thinking||""),re){let de=p&&p.encodeText?p.encodeText(re).length:co(re);M.tokenCount+=de,M.lastTokenTime=Q;for(let pe=0;pe<de;pe++)M.tokenTimestamps.push(Q)}}J.event==="message_stop"&&(v&&(clearInterval(v),v=null),await b(!0),uo.delete(h))}}catch(A){v&&clearInterval(v),A.name!=="AbortError"&&A.code!=="ERR_STREAM_PREMATURE_CLOSE"&&t.log?.warn(`Error processing token stats: ${A.message}`)}})().catch(v=>{console.log(v),t.log?.warn(`Background stats processing failed: ${v.message}`)}),y}let w=performance.now(),T=0,S=!1;if(c&&typeof c=="string")try{let y=JSON.parse(c);if(typeof y.usage?.output_tokens=="number")T=y.usage.output_tokens,S=!0;else{let g=y.content??y.message?.content;if(g!==void 0)if(S=!0,p)Array.isArray(g)?T=g.reduce((m,v)=>{if(v.type==="text"){let b=v.text||"";return m+(p.encodeText?p.encodeText(b).length:co(b))}return m},0):typeof g=="string"&&(T=p.encodeText?p.encodeText(g).length:co(g));else{let m=Array.isArray(g)?g.map(v=>v.text).join(""):typeof g=="string"?g:"";T=co(m)}}}catch{}if(S){let y=Math.round(w-l),g=w-l,m={requestId:h,sessionId:d,startTime:l,lastTokenTime:w,tokenCount:T,tokensPerSecond:l0(T,g),timeToFirstToken:y,stream:!1,tokenTimestamps:[]};await d0(m,n,r.outputOptions,!0)}return c})})};function l0(t,e,r=0){if(t<=0)return 0;let n=Math.max((e-r)/1e3,ZT);return Math.round(t/n)}function co(t){let e=(t.match(/[\u4e00-\u9fa5]/g)||[]).length,r=t.length-e;return Math.ceil(e/1.5+r/4)}async function d0(t,e,r,n=!1){let s=n?"[Token Speed Final]":"[Token Speed]",i={requestId:t.requestId.substring(0,8),sessionId:t.sessionId,stream:t.stream,tokenCount:t.tokenCount,tokensPerSecond:t.tokensPerSecond,timeToFirstToken:t.timeToFirstToken?`${t.timeToFirstToken}ms`:"N/A",duration:`${((t.lastTokenTime-t.startTime)/1e3).toFixed(2)}s`,timestamp:Date.now()},u={prefix:s,metadata:{sessionId:t.sessionId},...r};for(let c of e)try{await ds.outputToType(c,i,u)}catch(l){console.error(`[TokenSpeedPlugin] Failed to output to ${c}:`,l)}}function rD(t={}){let e=eD({bodyLimit:52428800,...t});return e.setErrorHandler(nh),e.register(tD),e}var Md=class{app;configService;providerService;transformerService;tokenizerService;activeProbeService;constructor(e={}){let{initialConfig:r,...n}=e;this.app=rD({...n,logger:n.logger??!0}),this.configService=new xn(e),this.transformerService=new us(this.configService,this.app.log),this.tokenizerService=new cs(this.configService,this.app.log),this.transformerService.initialize().finally(()=>{this.providerService=new On(this.configService,this.transformerService,this.app.log)}),this.tokenizerService.initialize().catch(s=>{this.app.log.error(`Failed to initialize TokenizerService: ${s}`)})}async register(e,r){await this.app.register(e,r)}addHook(e,r){this.app.addHook(e,r)}async registerNamespace(e,r){if(!e)throw new Error("name is required");if(e==="/"){await this.app.register(async c=>{c.decorate("configService",this.configService),c.decorate("transformerService",this.transformerService),c.decorate("providerService",this.providerService),c.decorate("tokenizerService",this.tokenizerService),c.addHook("preHandler",async(l,h)=>{new URL(`http://127.0.0.1${l.url}`).pathname.endsWith("/v1/messages")&&await wd(l,h,{configService:this.configService,tokenizerService:this.tokenizerService})}),await Fu(c)});return}if(!r)throw new Error("options is required");let n=new xn({initialConfig:{providers:r.Providers,Router:r.Router}}),s=new us(n,this.app.log);await s.initialize();let i=new On(n,s,this.app.log),u=new cs(n,this.app.log);await u.initialize(),await this.app.register(async c=>{c.decorate("configService",n),c.decorate("transformerService",s),c.decorate("providerService",i),c.decorate("tokenizerService",u),c.addHook("preHandler",async(l,h)=>{new URL(`http://127.0.0.1${l.url}`).pathname.endsWith("/v1/messages")&&await wd(l,h,{configService:n,tokenizerService:u})}),await Fu(c)},{prefix:e})}async start(){try{this.app._server=this,this.app.addHook("preHandler",(n,s,i)=>{if(new URL(`http://127.0.0.1${n.url}`).pathname.endsWith("/v1/messages")&&n.body){let c=n.body;n.log.info({data:c,type:"request body"}),c.stream||(c.stream=!1)}i()}),await this.registerNamespace("/"),this.app.addHook("preHandler",async(n,s)=>{if(new URL(`http://127.0.0.1${n.url}`).pathname.endsWith("/v1/messages")&&n.body)try{let u=n.body;if(!u||!u.model)return s.code(400).send({error:"Missing model in request body"});let[c,...l]=u.model.split(",");u.model=l.join(","),n.provider=c,n.model=l;return}catch(u){return n.log.error({error:u},"Error in modelProviderMiddleware:"),s.code(500).send({error:"Internal server error"})}});let e=await this.app.listen({port:parseInt(this.configService.get("PORT")||"3000",10),host:this.configService.get("HOST")||"127.0.0.1"});this.app.log.info(`\u{1F680} LLMs API server listening on ${e}`);try{let n={enabled:this.configService.get("ACTIVE_PROBE_ENABLED")??!0,quotaProbeIntervalMinutes:this.configService.get("QUOTA_PROBE_INTERVAL_MINUTES")??10,probeTimeoutMs:this.configService.get("PROBE_TIMEOUT_MS")??15e3,initialDelayMs:this.configService.get("PROBE_INITIAL_DELAY_MS")??5e3,excludeProviders:this.configService.get("EXCLUDE_PROBE_PROVIDERS")??[]};this.activeProbeService=Rd(()=>this.providerService.getProviders(),n,()=>this.configService.getHttpsProxy(),this.app.log)}catch(n){this.app.log.warn?.(`Failed to start active probe service: ${n.message}`)}let r=async n=>{this.app.log.info(`Received ${n}, shutting down gracefully...`);try{xd()}catch{}await this.app.close(),process.exit(0)};process.on("SIGINT",()=>r("SIGINT")),process.on("SIGTERM",()=>r("SIGTERM"))}catch(e){this.app.log.error(`Error starting server: ${e}`),process.exit(1)}}},VI=Md;export{za as ActiveProbeService,xn as ConfigService,$o as ProviderHealthStore,On as ProviderService,ls as SSEParserTransform,Wa as SSESerializerTransform,cs as TokenizerService,us as TransformerService,Ky as calculateTokenCount,VI as default,e0 as getActiveProbeService,MT as getAllQuotaResults,_b as getAllRateLimitInfo,Gt as getHealthStore,vd as getQuotaAdapter,LT as getQuotaResult,yb as getRateLimitInfo,t0 as pluginManager,zT as resetActiveProbeService,a0 as rewriteStream,wd as router,Xy as searchProjectBySession,yd as sessionUsageCache,Rd as startActiveProbe,xd as stopActiveProbe,Td as storeQuotaResult,h0 as tokenSpeedPlugin};
|
|
348
348
|
/*! Bundled license information:
|
|
349
349
|
|
|
350
350
|
web-streams-polyfill/dist/ponyfill.es2018.js:
|