@ubec/llms 1.0.51 → 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,76 +1,76 @@
1
- var b_=Object.create;var cu=Object.defineProperty;var C_=Object.getOwnPropertyDescriptor;var w_=Object.getOwnPropertyNames;var E_=Object.getPrototypeOf,A_=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 J=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Cd=(t,e)=>{for(var r in e)cu(t,r,{get:e[r],enumerable:!0})},S_=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of w_(e))!A_.call(t,s)&&s!==r&&cu(t,s,{get:()=>e[s],enumerable:!(n=C_(e,s))||n.enumerable});return t};var xr=(t,e,r)=>(r=t!=null?b_(E_(t)):{},S_(e||!t||!t.__esModule?cu(r,"default",{value:t,enumerable:!0}):r,t));var wd=J((aT,xo)=>{xo.exports.Space_Separator=/[\u1680\u2000-\u200A\u202F\u205F\u3000]/;xo.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]/;xo.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 fu=J((uT,Ed)=>{var lu=wd();Ed.exports={isSpaceSeparator(t){return typeof t=="string"&&lu.Space_Separator.test(t)},isIdStartChar(t){return typeof t=="string"&&(t>="a"&&t<="z"||t>="A"&&t<="Z"||t==="$"||t==="_"||lu.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"||lu.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 Td=J((cT,Dd)=>{var $e=fu(),hu,Ze,pr,Io,Pr,Nt,ze,gu,gs;Dd.exports=function(e,r){hu=String(e),Ze="start",pr=[],Io=0,Pr=1,Nt=0,ze=void 0,gu=void 0,gs=void 0;do ze=k_(),v_[Ze]();while(ze.type!=="eof");return typeof r=="function"?pu({"":gs},"",r):gs};function pu(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=pu(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=pu(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 me,he,ms,hr,Ce;function k_(){for(me="default",he="",ms=!1,hr=1;;){Ce=mr();let t=Sd[me]();if(t)return t}}function mr(){if(hu[Io])return String.fromCodePoint(hu.codePointAt(Io))}function H(){let t=mr();return t===`
2
- `?(Pr++,Nt=0):t?Nt+=t.length:Nt++,t&&(Io+=t.length),t}var Sd={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(),me="comment";return;case void 0:return H(),Pe("eof")}if($e.isSpaceSeparator(Ce)){H();return}return Sd[Ze]()},comment(){switch(Ce){case"*":H(),me="multiLineComment";return;case"/":H(),me="singleLineComment";return}throw Ie(H())},multiLineComment(){switch(Ce){case"*":H(),me="multiLineCommentAsterisk";return;case void 0:throw Ie(H())}H()},multiLineCommentAsterisk(){switch(Ce){case"*":H();return;case"/":H(),me="default";return;case void 0:throw Ie(H())}H(),me="multiLineComment"},singleLineComment(){switch(Ce){case`
4
- `:case"\r":case"\u2028":case"\u2029":H(),me="default";return;case void 0:return H(),Pe("eof")}H()},value(){switch(Ce){case"{":case"[":return Pe("punctuator",H());case"n":return H(),Zr("ull"),Pe("null",null);case"t":return H(),Zr("rue"),Pe("boolean",!0);case"f":return H(),Zr("alse"),Pe("boolean",!1);case"-":case"+":H()==="-"&&(hr=-1),me="sign";return;case".":he=H(),me="decimalPointLeading";return;case"0":he=H(),me="zero";return;case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":he=H(),me="decimalInteger";return;case"I":return H(),Zr("nfinity"),Pe("numeric",1/0);case"N":return H(),Zr("aN"),Pe("numeric",NaN);case'"':case"'":ms=H()==='"',he="",me="string";return}throw Ie(H())},identifierNameStartEscape(){if(Ce!=="u")throw Ie(H());H();let t=mu();switch(t){case"$":case"_":break;default:if(!$e.isIdStartChar(t))throw Ad();break}he+=t,me="identifierName"},identifierName(){switch(Ce){case"$":case"_":case"\u200C":case"\u200D":he+=H();return;case"\\":H(),me="identifierNameEscape";return}if($e.isIdContinueChar(Ce)){he+=H();return}return Pe("identifier",he)},identifierNameEscape(){if(Ce!=="u")throw Ie(H());H();let t=mu();switch(t){case"$":case"_":case"\u200C":case"\u200D":break;default:if(!$e.isIdContinueChar(t))throw Ad();break}he+=t,me="identifierName"},sign(){switch(Ce){case".":he=H(),me="decimalPointLeading";return;case"0":he=H(),me="zero";return;case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":he=H(),me="decimalInteger";return;case"I":return H(),Zr("nfinity"),Pe("numeric",hr*(1/0));case"N":return H(),Zr("aN"),Pe("numeric",NaN)}throw Ie(H())},zero(){switch(Ce){case".":he+=H(),me="decimalPoint";return;case"e":case"E":he+=H(),me="decimalExponent";return;case"x":case"X":he+=H(),me="hexadecimal";return}return Pe("numeric",hr*0)},decimalInteger(){switch(Ce){case".":he+=H(),me="decimalPoint";return;case"e":case"E":he+=H(),me="decimalExponent";return}if($e.isDigit(Ce)){he+=H();return}return Pe("numeric",hr*Number(he))},decimalPointLeading(){if($e.isDigit(Ce)){he+=H(),me="decimalFraction";return}throw Ie(H())},decimalPoint(){switch(Ce){case"e":case"E":he+=H(),me="decimalExponent";return}if($e.isDigit(Ce)){he+=H(),me="decimalFraction";return}return Pe("numeric",hr*Number(he))},decimalFraction(){switch(Ce){case"e":case"E":he+=H(),me="decimalExponent";return}if($e.isDigit(Ce)){he+=H();return}return Pe("numeric",hr*Number(he))},decimalExponent(){switch(Ce){case"+":case"-":he+=H(),me="decimalExponentSign";return}if($e.isDigit(Ce)){he+=H(),me="decimalExponentInteger";return}throw Ie(H())},decimalExponentSign(){if($e.isDigit(Ce)){he+=H(),me="decimalExponentInteger";return}throw Ie(H())},decimalExponentInteger(){if($e.isDigit(Ce)){he+=H();return}return Pe("numeric",hr*Number(he))},hexadecimal(){if($e.isHexDigit(Ce)){he+=H(),me="hexadecimalInteger";return}throw Ie(H())},hexadecimalInteger(){if($e.isHexDigit(Ce)){he+=H();return}return Pe("numeric",hr*Number(he))},string(){switch(Ce){case"\\":H(),he+=D_();return;case'"':if(ms)return H(),Pe("string",he);he+=H();return;case"'":if(!ms)return H(),Pe("string",he);he+=H();return;case`
5
- `:case"\r":throw Ie(H());case"\u2028":case"\u2029":R_(Ce);break;case void 0:throw Ie(H())}he+=H()},start(){switch(Ce){case"{":case"[":return Pe("punctuator",H())}me="value"},beforePropertyName(){switch(Ce){case"$":case"_":he=H(),me="identifierName";return;case"\\":H(),me="identifierNameStartEscape";return;case"}":return Pe("punctuator",H());case'"':case"'":ms=H()==='"',me="string";return}if($e.isIdStartChar(Ce)){he+=H(),me="identifierName";return}throw Ie(H())},afterPropertyName(){if(Ce===":")return Pe("punctuator",H());throw Ie(H())},beforePropertyValue(){me="value"},afterPropertyValue(){switch(Ce){case",":case"}":return Pe("punctuator",H())}throw Ie(H())},beforeArrayValue(){if(Ce==="]")return Pe("punctuator",H());me="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:Pr,column:Nt}}function Zr(t){for(let e of t){if(mr()!==e)throw Ie(H());H()}}function D_(){switch(mr()){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(mr()))throw Ie(H());return"\0";case"x":return H(),T_();case"u":return H(),mu();case`
1
+ var C_=Object.create;var lu=Object.defineProperty;var w_=Object.getOwnPropertyDescriptor;var E_=Object.getOwnPropertyNames;var A_=Object.getPrototypeOf,S_=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 J=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),wd=(t,e)=>{for(var r in e)lu(t,r,{get:e[r],enumerable:!0})},k_=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of E_(e))!S_.call(t,s)&&s!==r&&lu(t,s,{get:()=>e[s],enumerable:!(n=w_(e,s))||n.enumerable});return t};var xr=(t,e,r)=>(r=t!=null?C_(A_(t)):{},k_(e||!t||!t.__esModule?lu(r,"default",{value:t,enumerable:!0}):r,t));var Ed=J((uT,xo)=>{xo.exports.Space_Separator=/[\u1680\u2000-\u200A\u202F\u205F\u3000]/;xo.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]/;xo.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 du=J((cT,Ad)=>{var fu=Ed();Ad.exports={isSpaceSeparator(t){return typeof t=="string"&&fu.Space_Separator.test(t)},isIdStartChar(t){return typeof t=="string"&&(t>="a"&&t<="z"||t>="A"&&t<="Z"||t==="$"||t==="_"||fu.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"||fu.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 vd=J((lT,Td)=>{var $e=du(),pu,Ze,pr,Io,Pr,Nt,ze,yu,gs;Td.exports=function(e,r){pu=String(e),Ze="start",pr=[],Io=0,Pr=1,Nt=0,ze=void 0,yu=void 0,gs=void 0;do ze=D_(),R_[Ze]();while(ze.type!=="eof");return typeof r=="function"?mu({"":gs},"",r):gs};function mu(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=mu(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=mu(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 me,he,ms,hr,Ce;function D_(){for(me="default",he="",ms=!1,hr=1;;){Ce=mr();let t=kd[me]();if(t)return t}}function mr(){if(pu[Io])return String.fromCodePoint(pu.codePointAt(Io))}function H(){let t=mr();return t===`
2
+ `?(Pr++,Nt=0):t?Nt+=t.length:Nt++,t&&(Io+=t.length),t}var kd={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(),me="comment";return;case void 0:return H(),Pe("eof")}if($e.isSpaceSeparator(Ce)){H();return}return kd[Ze]()},comment(){switch(Ce){case"*":H(),me="multiLineComment";return;case"/":H(),me="singleLineComment";return}throw Ie(H())},multiLineComment(){switch(Ce){case"*":H(),me="multiLineCommentAsterisk";return;case void 0:throw Ie(H())}H()},multiLineCommentAsterisk(){switch(Ce){case"*":H();return;case"/":H(),me="default";return;case void 0:throw Ie(H())}H(),me="multiLineComment"},singleLineComment(){switch(Ce){case`
4
+ `:case"\r":case"\u2028":case"\u2029":H(),me="default";return;case void 0:return H(),Pe("eof")}H()},value(){switch(Ce){case"{":case"[":return Pe("punctuator",H());case"n":return H(),Zr("ull"),Pe("null",null);case"t":return H(),Zr("rue"),Pe("boolean",!0);case"f":return H(),Zr("alse"),Pe("boolean",!1);case"-":case"+":H()==="-"&&(hr=-1),me="sign";return;case".":he=H(),me="decimalPointLeading";return;case"0":he=H(),me="zero";return;case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":he=H(),me="decimalInteger";return;case"I":return H(),Zr("nfinity"),Pe("numeric",1/0);case"N":return H(),Zr("aN"),Pe("numeric",NaN);case'"':case"'":ms=H()==='"',he="",me="string";return}throw Ie(H())},identifierNameStartEscape(){if(Ce!=="u")throw Ie(H());H();let t=gu();switch(t){case"$":case"_":break;default:if(!$e.isIdStartChar(t))throw Sd();break}he+=t,me="identifierName"},identifierName(){switch(Ce){case"$":case"_":case"\u200C":case"\u200D":he+=H();return;case"\\":H(),me="identifierNameEscape";return}if($e.isIdContinueChar(Ce)){he+=H();return}return Pe("identifier",he)},identifierNameEscape(){if(Ce!=="u")throw Ie(H());H();let t=gu();switch(t){case"$":case"_":case"\u200C":case"\u200D":break;default:if(!$e.isIdContinueChar(t))throw Sd();break}he+=t,me="identifierName"},sign(){switch(Ce){case".":he=H(),me="decimalPointLeading";return;case"0":he=H(),me="zero";return;case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":he=H(),me="decimalInteger";return;case"I":return H(),Zr("nfinity"),Pe("numeric",hr*(1/0));case"N":return H(),Zr("aN"),Pe("numeric",NaN)}throw Ie(H())},zero(){switch(Ce){case".":he+=H(),me="decimalPoint";return;case"e":case"E":he+=H(),me="decimalExponent";return;case"x":case"X":he+=H(),me="hexadecimal";return}return Pe("numeric",hr*0)},decimalInteger(){switch(Ce){case".":he+=H(),me="decimalPoint";return;case"e":case"E":he+=H(),me="decimalExponent";return}if($e.isDigit(Ce)){he+=H();return}return Pe("numeric",hr*Number(he))},decimalPointLeading(){if($e.isDigit(Ce)){he+=H(),me="decimalFraction";return}throw Ie(H())},decimalPoint(){switch(Ce){case"e":case"E":he+=H(),me="decimalExponent";return}if($e.isDigit(Ce)){he+=H(),me="decimalFraction";return}return Pe("numeric",hr*Number(he))},decimalFraction(){switch(Ce){case"e":case"E":he+=H(),me="decimalExponent";return}if($e.isDigit(Ce)){he+=H();return}return Pe("numeric",hr*Number(he))},decimalExponent(){switch(Ce){case"+":case"-":he+=H(),me="decimalExponentSign";return}if($e.isDigit(Ce)){he+=H(),me="decimalExponentInteger";return}throw Ie(H())},decimalExponentSign(){if($e.isDigit(Ce)){he+=H(),me="decimalExponentInteger";return}throw Ie(H())},decimalExponentInteger(){if($e.isDigit(Ce)){he+=H();return}return Pe("numeric",hr*Number(he))},hexadecimal(){if($e.isHexDigit(Ce)){he+=H(),me="hexadecimalInteger";return}throw Ie(H())},hexadecimalInteger(){if($e.isHexDigit(Ce)){he+=H();return}return Pe("numeric",hr*Number(he))},string(){switch(Ce){case"\\":H(),he+=T_();return;case'"':if(ms)return H(),Pe("string",he);he+=H();return;case"'":if(!ms)return H(),Pe("string",he);he+=H();return;case`
5
+ `:case"\r":throw Ie(H());case"\u2028":case"\u2029":O_(Ce);break;case void 0:throw Ie(H())}he+=H()},start(){switch(Ce){case"{":case"[":return Pe("punctuator",H())}me="value"},beforePropertyName(){switch(Ce){case"$":case"_":he=H(),me="identifierName";return;case"\\":H(),me="identifierNameStartEscape";return;case"}":return Pe("punctuator",H());case'"':case"'":ms=H()==='"',me="string";return}if($e.isIdStartChar(Ce)){he+=H(),me="identifierName";return}throw Ie(H())},afterPropertyName(){if(Ce===":")return Pe("punctuator",H());throw Ie(H())},beforePropertyValue(){me="value"},afterPropertyValue(){switch(Ce){case",":case"}":return Pe("punctuator",H())}throw Ie(H())},beforeArrayValue(){if(Ce==="]")return Pe("punctuator",H());me="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:Pr,column:Nt}}function Zr(t){for(let e of t){if(mr()!==e)throw Ie(H());H()}}function T_(){switch(mr()){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(mr()))throw Ie(H());return"\0";case"x":return H(),v_();case"u":return H(),gu();case`
7
7
  `:case"\u2028":case"\u2029":return H(),"";case"\r":return H(),mr()===`
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 T_(){let t="",e=mr();if(!$e.isHexDigit(e)||(t+=H(),e=mr(),!$e.isHexDigit(e)))throw Ie(H());return t+=H(),String.fromCodePoint(parseInt(t,16))}function mu(){let t="",e=4;for(;e-- >0;){let r=mr();if(!$e.isHexDigit(r))throw Ie(H());t+=H()}return String.fromCodePoint(parseInt(t,16))}var v_={start(){if(ze.type==="eof")throw en();du()},beforePropertyName(){switch(ze.type){case"identifier":case"string":gu=ze.value,Ze="afterPropertyName";return;case"punctuator":Po();return;case"eof":throw en()}},afterPropertyName(){if(ze.type==="eof")throw en();Ze="beforePropertyValue"},beforePropertyValue(){if(ze.type==="eof")throw en();du()},beforeArrayValue(){if(ze.type==="eof")throw en();if(ze.type==="punctuator"&&ze.value==="]"){Po();return}du()},afterPropertyValue(){if(ze.type==="eof")throw en();switch(ze.value){case",":Ze="beforePropertyName";return;case"}":Po()}},afterArrayValue(){if(ze.type==="eof")throw en();switch(ze.value){case",":Ze="beforeArrayValue";return;case"]":Po()}},end(){}};function du(){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(gs===void 0)gs=t;else{let e=pr[pr.length-1];Array.isArray(e)?e.push(t):Object.defineProperty(e,gu,{value:t,writable:!0,enumerable:!0,configurable:!0})}if(t!==null&&typeof t=="object")pr.push(t),Array.isArray(t)?Ze="beforeArrayValue":Ze="beforePropertyName";else{let e=pr[pr.length-1];e==null?Ze="end":Array.isArray(e)?Ze="afterArrayValue":Ze="afterPropertyValue"}}function Po(){pr.pop();let t=pr[pr.length-1];t==null?Ze="end":Array.isArray(t)?Ze="afterArrayValue":Ze="afterPropertyValue"}function Ie(t){return No(t===void 0?`JSON5: invalid end of input at ${Pr}:${Nt}`:`JSON5: invalid character '${kd(t)}' at ${Pr}:${Nt}`)}function en(){return No(`JSON5: invalid end of input at ${Pr}:${Nt}`)}function Ad(){return Nt-=5,No(`JSON5: invalid identifier character at ${Pr}:${Nt}`)}function R_(t){console.warn(`JSON5: '${kd(t)}' in strings is not valid ECMAScript; consider escaping`)}function kd(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 No(t){let e=new SyntaxError(t);return e.lineNumber=Pr,e.columnNumber=Nt,e}});var Rd=J((lT,vd)=>{var yu=fu();vd.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 _ of r){let y;typeof _=="string"?y=_:(typeof _=="number"||_ instanceof String||_ instanceof Number)&&(y=String(_)),y!==void 0&&u.indexOf(y)<0&&u.push(y)}}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){let m=y[_];switch(m!=null&&(typeof m.toJSON5=="function"?m=m.toJSON5(_):typeof m.toJSON=="function"&&(m=m.toJSON(_))),c&&(m=c.call(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):A(m)}function p(_){let y={"'":.1,'"':.2},m={"'":"\\'",'"':'\\"',"\\":"\\\\","\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r"," ":"\\t","\v":"\\v","\0":"\\0","\u2028":"\\u2028","\u2029":"\\u2029"},D="";for(let E=0;E<_.length;E++){let v=_[E];switch(v){case"'":case'"':y[v]++,D+=v;continue;case"\0":if(yu.isDigit(_[E+1])){D+="\\x00";continue}}if(m[v]){D+=m[v];continue}if(v<" "){let x=v.charCodeAt(0).toString(16);D+="\\x"+("00"+x).substring(x.length);continue}D+=v}let C=h||Object.keys(y).reduce((E,v)=>y[E]<y[v]?E:v);return D=D.replace(new RegExp(C,"g"),m[C]),C+D+C}function A(_){if(s.indexOf(_)>=0)throw TypeError("Converting circular structure to JSON5");s.push(_);let y=i;i=i+l;let m=u||Object.keys(_),D=[];for(let E of m){let v=d(E,_);if(v!==void 0){let x=R(E)+":";l!==""&&(x+=" "),x+=v,D.push(x)}}let C;if(D.length===0)C="{}";else{let E;if(l==="")E=D.join(","),C="{"+E+"}";else{let v=`,
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 v_(){let t="",e=mr();if(!$e.isHexDigit(e)||(t+=H(),e=mr(),!$e.isHexDigit(e)))throw Ie(H());return t+=H(),String.fromCodePoint(parseInt(t,16))}function gu(){let t="",e=4;for(;e-- >0;){let r=mr();if(!$e.isHexDigit(r))throw Ie(H());t+=H()}return String.fromCodePoint(parseInt(t,16))}var R_={start(){if(ze.type==="eof")throw en();hu()},beforePropertyName(){switch(ze.type){case"identifier":case"string":yu=ze.value,Ze="afterPropertyName";return;case"punctuator":Po();return;case"eof":throw en()}},afterPropertyName(){if(ze.type==="eof")throw en();Ze="beforePropertyValue"},beforePropertyValue(){if(ze.type==="eof")throw en();hu()},beforeArrayValue(){if(ze.type==="eof")throw en();if(ze.type==="punctuator"&&ze.value==="]"){Po();return}hu()},afterPropertyValue(){if(ze.type==="eof")throw en();switch(ze.value){case",":Ze="beforePropertyName";return;case"}":Po()}},afterArrayValue(){if(ze.type==="eof")throw en();switch(ze.value){case",":Ze="beforeArrayValue";return;case"]":Po()}},end(){}};function hu(){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(gs===void 0)gs=t;else{let e=pr[pr.length-1];Array.isArray(e)?e.push(t):Object.defineProperty(e,yu,{value:t,writable:!0,enumerable:!0,configurable:!0})}if(t!==null&&typeof t=="object")pr.push(t),Array.isArray(t)?Ze="beforeArrayValue":Ze="beforePropertyName";else{let e=pr[pr.length-1];e==null?Ze="end":Array.isArray(e)?Ze="afterArrayValue":Ze="afterPropertyValue"}}function Po(){pr.pop();let t=pr[pr.length-1];t==null?Ze="end":Array.isArray(t)?Ze="afterArrayValue":Ze="afterPropertyValue"}function Ie(t){return No(t===void 0?`JSON5: invalid end of input at ${Pr}:${Nt}`:`JSON5: invalid character '${Dd(t)}' at ${Pr}:${Nt}`)}function en(){return No(`JSON5: invalid end of input at ${Pr}:${Nt}`)}function Sd(){return Nt-=5,No(`JSON5: invalid identifier character at ${Pr}:${Nt}`)}function O_(t){console.warn(`JSON5: '${Dd(t)}' in strings is not valid ECMAScript; consider escaping`)}function Dd(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 No(t){let e=new SyntaxError(t);return e.lineNumber=Pr,e.columnNumber=Nt,e}});var Od=J((fT,Rd)=>{var _u=du();Rd.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 _ of r){let y;typeof _=="string"?y=_:(typeof _=="number"||_ instanceof String||_ instanceof Number)&&(y=String(_)),y!==void 0&&u.indexOf(y)<0&&u.push(y)}}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){let m=y[_];switch(m!=null&&(typeof m.toJSON5=="function"?m=m.toJSON5(_):typeof m.toJSON=="function"&&(m=m.toJSON(_))),c&&(m=c.call(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):A(m)}function p(_){let y={"'":.1,'"':.2},m={"'":"\\'",'"':'\\"',"\\":"\\\\","\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r"," ":"\\t","\v":"\\v","\0":"\\0","\u2028":"\\u2028","\u2029":"\\u2029"},D="";for(let E=0;E<_.length;E++){let v=_[E];switch(v){case"'":case'"':y[v]++,D+=v;continue;case"\0":if(_u.isDigit(_[E+1])){D+="\\x00";continue}}if(m[v]){D+=m[v];continue}if(v<" "){let x=v.charCodeAt(0).toString(16);D+="\\x"+("00"+x).substring(x.length);continue}D+=v}let C=h||Object.keys(y).reduce((E,v)=>y[E]<y[v]?E:v);return D=D.replace(new RegExp(C,"g"),m[C]),C+D+C}function A(_){if(s.indexOf(_)>=0)throw TypeError("Converting circular structure to JSON5");s.push(_);let y=i;i=i+l;let m=u||Object.keys(_),D=[];for(let E of m){let v=d(E,_);if(v!==void 0){let x=R(E)+":";l!==""&&(x+=" "),x+=v,D.push(x)}}let C;if(D.length===0)C="{}";else{let E;if(l==="")E=D.join(","),C="{"+E+"}";else{let v=`,
9
9
  `+i;E=D.join(v),C=`{
10
10
  `+i+E+`,
11
- `+y+"}"}}return s.pop(),i=y,C}function R(_){if(_.length===0)return p(_,!0);let y=String.fromCodePoint(_.codePointAt(0));if(!yu.isIdStartChar(y))return p(_,!0);for(let m=y.length;m<_.length;m++)if(!yu.isIdContinueChar(String.fromCodePoint(_.codePointAt(m))))return p(_,!0);return _}function S(_){if(s.indexOf(_)>=0)throw TypeError("Converting circular structure to JSON5");s.push(_);let y=i;i=i+l;let m=[];for(let C=0;C<_.length;C++){let E=d(String(C),_);m.push(E!==void 0?E:"null")}let D;if(m.length===0)D="[]";else if(l==="")D="["+m.join(",")+"]";else{let C=`,
11
+ `+y+"}"}}return s.pop(),i=y,C}function R(_){if(_.length===0)return p(_,!0);let y=String.fromCodePoint(_.codePointAt(0));if(!_u.isIdStartChar(y))return p(_,!0);for(let m=y.length;m<_.length;m++)if(!_u.isIdContinueChar(String.fromCodePoint(_.codePointAt(m))))return p(_,!0);return _}function S(_){if(s.indexOf(_)>=0)throw TypeError("Converting circular structure to JSON5");s.push(_);let y=i;i=i+l;let m=[];for(let C=0;C<_.length;C++){let E=d(String(C),_);m.push(E!==void 0?E:"null")}let D;if(m.length===0)D="[]";else if(l==="")D="["+m.join(",")+"]";else{let C=`,
12
12
  `+i,E=m.join(C);D=`[
13
13
  `+i+E+`,
14
- `+y+"]"}return s.pop(),i=y,D}}});var _u=J((fT,Od)=>{var O_=Td(),F_=Rd(),x_={parse:O_,stringify:F_};Od.exports=x_});var Eu=J((GT,Xd)=>{"use strict";var zo=Object.prototype.hasOwnProperty,Yd=Object.prototype.toString,Hd=Object.defineProperty,Wd=Object.getOwnPropertyDescriptor,Gd=function(e){return typeof Array.isArray=="function"?Array.isArray(e):Yd.call(e)==="[object Array]"},Jd=function(e){if(!e||Yd.call(e)!=="[object Object]")return!1;var r=zo.call(e,"constructor"),n=e.constructor&&e.constructor.prototype&&zo.call(e.constructor.prototype,"isPrototypeOf");if(e.constructor&&!r&&!n)return!1;var s;for(s in e);return typeof s>"u"||zo.call(e,s)},Vd=function(e,r){Hd&&r.name==="__proto__"?Hd(e,r.name,{enumerable:!0,configurable:!0,value:r.newValue,writable:!0}):e[r.name]=r.newValue},Kd=function(e,r){if(r==="__proto__")if(zo.call(e,r)){if(Wd)return Wd(e,r).value}else return;return e[r]};Xd.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=Kd(c,r),s=Kd(e,r),c!==s&&(d&&s&&(Jd(s)||(i=Gd(s)))?(i?(i=!1,u=n&&Gd(n)?n:[]):u=n&&Jd(n)?n:{},Vd(c,{name:r,newValue:t(d,u,s)})):typeof s<"u"&&Vd(c,{name:r,newValue:s}));return c}});var Qd=J((JT,G_)=>{G_.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 eh=J((VT,Zd)=>{"use strict";var J_=Qd();Zd.exports={pkg:J_}});var ku=J(wt=>{"use strict";var rh=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=nh;var th=rh(Eu()),V_=rh(eh()),Au=V_.default.pkg;wt.GAXIOS_ERROR_SYMBOL=Symbol.for(`${Au.name}-gaxios-error`);var Su=class t extends Error{config;response;code;status;error;[wt.GAXIOS_ERROR_SYMBOL]=Au.version;static[Symbol.hasInstance](e){return e&&typeof e=="object"&&wt.GAXIOS_ERROR_SYMBOL in e&&e[wt.GAXIOS_ERROR_SYMBOL]===Au.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,th.default)(!0,{},r),this.response&&(this.response.config=(0,th.default)(!0,{},this.response.config)),this.response){try{this.response.data=K_(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=Su;function K_(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 nh(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&&(nh({config:t.response.config}),r(t.response.headers),t.response.bodyUsed&&(n(t.response,"data"),s(t.response.data))),t}});var oh=J(Du=>{"use strict";Object.defineProperty(Du,"__esModule",{value:!0});Du.getRetryConfig=Y_;async function Y_(t){let e=sh(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||X_)(t))return{shouldRetry:!1,config:t.config};let s=Q_(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 X_(t){let e=sh(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 sh(t){if(t&&t.config&&t.config.retryConfig)return t.config.retryConfig}function Q_(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 vu=J(Ho=>{"use strict";Object.defineProperty(Ho,"__esModule",{value:!0});Ho.GaxiosInterceptorManager=void 0;var Tu=class extends Set{};Ho.GaxiosInterceptorManager=Tu});var ah=J((QT,ih)=>{var vn=1e3,Rn=vn*60,On=Rn*60,tn=On*24,Z_=tn*7,eb=tn*365.25;ih.exports=function(t,e){e=e||{};var r=typeof t;if(r==="string"&&t.length>0)return tb(t);if(r==="number"&&isFinite(t))return e.long?nb(t):rb(t);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(t))};function tb(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*eb;case"weeks":case"week":case"w":return r*Z_;case"days":case"day":case"d":return r*tn;case"hours":case"hour":case"hrs":case"hr":case"h":return r*On;case"minutes":case"minute":case"mins":case"min":case"m":return r*Rn;case"seconds":case"second":case"secs":case"sec":case"s":return r*vn;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return r;default:return}}}}function rb(t){var e=Math.abs(t);return e>=tn?Math.round(t/tn)+"d":e>=On?Math.round(t/On)+"h":e>=Rn?Math.round(t/Rn)+"m":e>=vn?Math.round(t/vn)+"s":t+"ms"}function nb(t){var e=Math.abs(t);return e>=tn?Wo(t,e,tn,"day"):e>=On?Wo(t,e,On,"hour"):e>=Rn?Wo(t,e,Rn,"minute"):e>=vn?Wo(t,e,vn,"second"):t+" ms"}function Wo(t,e,r,n){var s=e>=r*1.5;return Math.round(t/r)+" "+n+(s?"s":"")}});var Ru=J((ZT,uh)=>{function sb(t){r.debug=r,r.default=r,r.coerce=l,r.disable=u,r.enable=s,r.enabled=c,r.humanize=ah(),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,R,S;function _(...y){if(!_.enabled)return;let m=_,D=Number(new Date),C=D-(p||D);m.diff=C,m.prev=p,m.curr=D,p=D,y[0]=r.coerce(y[0]),typeof y[0]!="string"&&y.unshift("%O");let E=0;y[0]=y[0].replace(/%([a-zA-Z%])/g,(x,$)=>{if(x==="%%")return"%";E++;let V=r.formatters[$];if(typeof V=="function"){let U=y[E];x=V.call(m,U),y.splice(E,1),E--}return x}),r.formatArgs.call(m,y),(m.log||r.log).apply(m,y)}return _.namespace=d,_.useColors=r.useColors(),_.color=r.selectColor(d),_.extend=n,_.destroy=r.destroy,Object.defineProperty(_,"enabled",{enumerable:!0,configurable:!1,get:()=>A!==null?A:(R!==r.namespaces&&(R=r.namespaces,S=r.enabled(d)),S),set:y=>{A=y}}),typeof r.init=="function"&&r.init(_),_}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,R=0,S=-1,_=0;for(;A<d.length;)if(R<p.length&&(p[R]===d[A]||p[R]==="*"))p[R]==="*"?(S=R,_=A,R++):(A++,R++);else if(S!==-1)R=S+1,_++,A=_;else return!1;for(;R<p.length&&p[R]==="*";)R++;return R===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}uh.exports=sb});var ch=J((st,Go)=>{st.formatArgs=ib;st.save=ab;st.load=ub;st.useColors=ob;st.storage=cb();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 ob(){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 ib(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+Go.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 ab(t){try{t?st.storage.setItem("debug",t):st.storage.removeItem("debug")}catch{}}function ub(){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 cb(){try{return localStorage}catch{}}Go.exports=Ru()(st);var{formatters:lb}=Go.exports;lb.j=function(t){try{return JSON.stringify(t)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var fh=J((ev,lh)=>{"use strict";lh.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 ph=J((tv,hh)=>{"use strict";var fb=X("os"),dh=X("tty"),Et=fh(),{env:He}=process,Ir;Et("no-color")||Et("no-colors")||Et("color=false")||Et("color=never")?Ir=0:(Et("color")||Et("colors")||Et("color=true")||Et("color=always"))&&(Ir=1);"FORCE_COLOR"in He&&(He.FORCE_COLOR==="true"?Ir=1:He.FORCE_COLOR==="false"?Ir=0:Ir=He.FORCE_COLOR.length===0?1:Math.min(parseInt(He.FORCE_COLOR,10),3));function Ou(t){return t===0?!1:{level:t,hasBasic:!0,has256:t>=2,has16m:t>=3}}function Fu(t,e){if(Ir===0)return 0;if(Et("color=16m")||Et("color=full")||Et("color=truecolor"))return 3;if(Et("color=256"))return 2;if(t&&!e&&Ir===void 0)return 0;let r=Ir||0;if(He.TERM==="dumb")return r;if(process.platform==="win32"){let n=fb.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 db(t){let e=Fu(t,t&&t.isTTY);return Ou(e)}hh.exports={supportsColor:db,stdout:Ou(Fu(!0,dh.isatty(1))),stderr:Ou(Fu(!0,dh.isatty(2)))}});var gh=J((We,Vo)=>{var hb=X("tty"),Jo=X("util");We.init=Cb;We.log=yb;We.formatArgs=mb;We.save=_b;We.load=bb;We.useColors=pb;We.destroy=Jo.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=ph();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 pb(){return"colors"in We.inspectOpts?!!We.inspectOpts.colors:hb.isatty(process.stderr.fd)}function mb(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(`
14
+ `+y+"]"}return s.pop(),i=y,D}}});var bu=J((dT,Fd)=>{var F_=vd(),x_=Od(),P_={parse:F_,stringify:x_};Fd.exports=P_});var Au=J((JT,Qd)=>{"use strict";var zo=Object.prototype.hasOwnProperty,Xd=Object.prototype.toString,Wd=Object.defineProperty,Gd=Object.getOwnPropertyDescriptor,Jd=function(e){return typeof Array.isArray=="function"?Array.isArray(e):Xd.call(e)==="[object Array]"},Vd=function(e){if(!e||Xd.call(e)!=="[object Object]")return!1;var r=zo.call(e,"constructor"),n=e.constructor&&e.constructor.prototype&&zo.call(e.constructor.prototype,"isPrototypeOf");if(e.constructor&&!r&&!n)return!1;var s;for(s in e);return typeof s>"u"||zo.call(e,s)},Kd=function(e,r){Wd&&r.name==="__proto__"?Wd(e,r.name,{enumerable:!0,configurable:!0,value:r.newValue,writable:!0}):e[r.name]=r.newValue},Yd=function(e,r){if(r==="__proto__")if(zo.call(e,r)){if(Gd)return Gd(e,r).value}else return;return e[r]};Qd.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=Yd(c,r),s=Yd(e,r),c!==s&&(d&&s&&(Vd(s)||(i=Jd(s)))?(i?(i=!1,u=n&&Jd(n)?n:[]):u=n&&Vd(n)?n:{},Kd(c,{name:r,newValue:t(d,u,s)})):typeof s<"u"&&Kd(c,{name:r,newValue:s}));return c}});var Zd=J((VT,J_)=>{J_.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 th=J((KT,eh)=>{"use strict";var V_=Zd();eh.exports={pkg:V_}});var Du=J(wt=>{"use strict";var nh=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=sh;var rh=nh(Au()),K_=nh(th()),Su=K_.default.pkg;wt.GAXIOS_ERROR_SYMBOL=Symbol.for(`${Su.name}-gaxios-error`);var ku=class t extends Error{config;response;code;status;error;[wt.GAXIOS_ERROR_SYMBOL]=Su.version;static[Symbol.hasInstance](e){return e&&typeof e=="object"&&wt.GAXIOS_ERROR_SYMBOL in e&&e[wt.GAXIOS_ERROR_SYMBOL]===Su.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,rh.default)(!0,{},r),this.response&&(this.response.config=(0,rh.default)(!0,{},this.response.config)),this.response){try{this.response.data=Y_(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=ku;function Y_(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 sh(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&&(sh({config:t.response.config}),r(t.response.headers),t.response.bodyUsed&&(n(t.response,"data"),s(t.response.data))),t}});var ih=J(Tu=>{"use strict";Object.defineProperty(Tu,"__esModule",{value:!0});Tu.getRetryConfig=X_;async function X_(t){let e=oh(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||Q_)(t))return{shouldRetry:!1,config:t.config};let s=Z_(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 Q_(t){let e=oh(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 oh(t){if(t&&t.config&&t.config.retryConfig)return t.config.retryConfig}function Z_(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 Ru=J(Ho=>{"use strict";Object.defineProperty(Ho,"__esModule",{value:!0});Ho.GaxiosInterceptorManager=void 0;var vu=class extends Set{};Ho.GaxiosInterceptorManager=vu});var uh=J((ZT,ah)=>{var vn=1e3,Rn=vn*60,On=Rn*60,tn=On*24,eb=tn*7,tb=tn*365.25;ah.exports=function(t,e){e=e||{};var r=typeof t;if(r==="string"&&t.length>0)return rb(t);if(r==="number"&&isFinite(t))return e.long?sb(t):nb(t);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(t))};function rb(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*tb;case"weeks":case"week":case"w":return r*eb;case"days":case"day":case"d":return r*tn;case"hours":case"hour":case"hrs":case"hr":case"h":return r*On;case"minutes":case"minute":case"mins":case"min":case"m":return r*Rn;case"seconds":case"second":case"secs":case"sec":case"s":return r*vn;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return r;default:return}}}}function nb(t){var e=Math.abs(t);return e>=tn?Math.round(t/tn)+"d":e>=On?Math.round(t/On)+"h":e>=Rn?Math.round(t/Rn)+"m":e>=vn?Math.round(t/vn)+"s":t+"ms"}function sb(t){var e=Math.abs(t);return e>=tn?Wo(t,e,tn,"day"):e>=On?Wo(t,e,On,"hour"):e>=Rn?Wo(t,e,Rn,"minute"):e>=vn?Wo(t,e,vn,"second"):t+" ms"}function Wo(t,e,r,n){var s=e>=r*1.5;return Math.round(t/r)+" "+n+(s?"s":"")}});var Ou=J((ev,ch)=>{function ob(t){r.debug=r,r.default=r,r.coerce=l,r.disable=u,r.enable=s,r.enabled=c,r.humanize=uh(),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,R,S;function _(...y){if(!_.enabled)return;let m=_,D=Number(new Date),C=D-(p||D);m.diff=C,m.prev=p,m.curr=D,p=D,y[0]=r.coerce(y[0]),typeof y[0]!="string"&&y.unshift("%O");let E=0;y[0]=y[0].replace(/%([a-zA-Z%])/g,(x,$)=>{if(x==="%%")return"%";E++;let V=r.formatters[$];if(typeof V=="function"){let U=y[E];x=V.call(m,U),y.splice(E,1),E--}return x}),r.formatArgs.call(m,y),(m.log||r.log).apply(m,y)}return _.namespace=d,_.useColors=r.useColors(),_.color=r.selectColor(d),_.extend=n,_.destroy=r.destroy,Object.defineProperty(_,"enabled",{enumerable:!0,configurable:!1,get:()=>A!==null?A:(R!==r.namespaces&&(R=r.namespaces,S=r.enabled(d)),S),set:y=>{A=y}}),typeof r.init=="function"&&r.init(_),_}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,R=0,S=-1,_=0;for(;A<d.length;)if(R<p.length&&(p[R]===d[A]||p[R]==="*"))p[R]==="*"?(S=R,_=A,R++):(A++,R++);else if(S!==-1)R=S+1,_++,A=_;else return!1;for(;R<p.length&&p[R]==="*";)R++;return R===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}ch.exports=ob});var lh=J((st,Go)=>{st.formatArgs=ab;st.save=ub;st.load=cb;st.useColors=ib;st.storage=lb();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 ib(){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 ":" ")+"+"+Go.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 ub(t){try{t?st.storage.setItem("debug",t):st.storage.removeItem("debug")}catch{}}function cb(){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 lb(){try{return localStorage}catch{}}Go.exports=Ou()(st);var{formatters:fb}=Go.exports;fb.j=function(t){try{return JSON.stringify(t)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var dh=J((tv,fh)=>{"use strict";fh.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 mh=J((rv,ph)=>{"use strict";var db=X("os"),hh=X("tty"),Et=dh(),{env:He}=process,Ir;Et("no-color")||Et("no-colors")||Et("color=false")||Et("color=never")?Ir=0:(Et("color")||Et("colors")||Et("color=true")||Et("color=always"))&&(Ir=1);"FORCE_COLOR"in He&&(He.FORCE_COLOR==="true"?Ir=1:He.FORCE_COLOR==="false"?Ir=0:Ir=He.FORCE_COLOR.length===0?1:Math.min(parseInt(He.FORCE_COLOR,10),3));function Fu(t){return t===0?!1:{level:t,hasBasic:!0,has256:t>=2,has16m:t>=3}}function xu(t,e){if(Ir===0)return 0;if(Et("color=16m")||Et("color=full")||Et("color=truecolor"))return 3;if(Et("color=256"))return 2;if(t&&!e&&Ir===void 0)return 0;let r=Ir||0;if(He.TERM==="dumb")return r;if(process.platform==="win32"){let n=db.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 hb(t){let e=xu(t,t&&t.isTTY);return Fu(e)}ph.exports={supportsColor:hb,stdout:Fu(xu(!0,hh.isatty(1))),stderr:Fu(xu(!0,hh.isatty(2)))}});var yh=J((We,Vo)=>{var pb=X("tty"),Jo=X("util");We.init=wb;We.log=_b;We.formatArgs=gb;We.save=bb;We.load=Cb;We.useColors=mb;We.destroy=Jo.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=mh();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 mb(){return"colors"in We.inspectOpts?!!We.inspectOpts.colors:pb.isatty(process.stderr.fd)}function gb(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+"+Vo.exports.humanize(this.diff)+"\x1B[0m")}else t[0]=gb()+e+" "+t[0]}function gb(){return We.inspectOpts.hideDate?"":new Date().toISOString()+" "}function yb(...t){return process.stderr.write(Jo.formatWithOptions(We.inspectOpts,...t)+`
18
- `)}function _b(t){t?process.env.DEBUG=t:delete process.env.DEBUG}function bb(){return process.env.DEBUG}function Cb(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]]}Vo.exports=Ru()(We);var{formatters:mh}=Vo.exports;mh.o=function(t){return this.inspectOpts.colors=this.useColors,Jo.inspect(t,this.inspectOpts).split(`
19
- `).map(e=>e.trim()).join(" ")};mh.O=function(t){return this.inspectOpts.colors=this.useColors,Jo.inspect(t,this.inspectOpts)}});var Pu=J((rv,xu)=>{typeof process>"u"||process.type==="renderer"||process.browser===!0||process.__nwjs?xu.exports=ch():xu.exports=gh()});var bh=J(ot=>{"use strict";var wb=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]})),Eb=ot&&ot.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),yh=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)&&wb(e,t,r);return Eb(e,t),e};Object.defineProperty(ot,"__esModule",{value:!0});ot.req=ot.json=ot.toBuffer=void 0;var Ab=yh(X("http")),Sb=yh(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 kb(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=kb;function Db(t,e={}){let n=((typeof t=="string"?t:t.href).startsWith("https:")?Sb:Ab).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=Db});var Ah=J(lt=>{"use strict";var wh=lt&&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]})),Tb=lt&&lt.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),Eh=lt&&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 Tb(e,t),e},vb=lt&&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 Rb=Eh(X("net")),Ch=Eh(X("http")),Ob=X("https");vb(bh(),lt);var Jt=Symbol("AgentBaseInternalState"),Iu=class extends Ch.Agent{constructor(e){super(e),this[Jt]={}}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 Rb.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)?Ob.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 Ch.Agent)try{return c.addRequest(e,s)}catch(l){return n(l)}this[Jt].currentSocket=c,super.createSocket(e,r,n)},c=>{this.decrementSockets(i,u),n(c)})}createConnection(){let e=this[Jt].currentSocket;if(this[Jt].currentSocket=void 0,!e)throw new Error("No socket was returned in the `connect()` function");return e}get defaultPort(){return this[Jt].defaultPort??(this.protocol==="https:"?443:80)}set defaultPort(e){this[Jt]&&(this[Jt].defaultPort=e)}get protocol(){return this[Jt].protocol??(this.isSecureEndpoint()?"https:":"http:")}set protocol(e){this[Jt]&&(this[Jt].protocol=e)}};lt.Agent=Iu});var Sh=J(Fn=>{"use strict";var Fb=Fn&&Fn.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Fn,"__esModule",{value:!0});Fn.parseProxyResponse=void 0;var xb=Fb(Pu()),Ko=(0,xb.default)("https-proxy-agent:parse-proxy-response");function Pb(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(),Ko("onend"),r(new Error("Proxy connection ended before receiving CONNECT response"))}function l(d){u(),Ko("onerror %o",d),r(d)}function h(d){s.push(d),n+=d.length;let p=Buffer.concat(s,n),A=p.indexOf(`\r
17
+ `+i),t.push(s+"m+"+Vo.exports.humanize(this.diff)+"\x1B[0m")}else t[0]=yb()+e+" "+t[0]}function yb(){return We.inspectOpts.hideDate?"":new Date().toISOString()+" "}function _b(...t){return process.stderr.write(Jo.formatWithOptions(We.inspectOpts,...t)+`
18
+ `)}function bb(t){t?process.env.DEBUG=t:delete process.env.DEBUG}function Cb(){return process.env.DEBUG}function wb(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]]}Vo.exports=Ou()(We);var{formatters:gh}=Vo.exports;gh.o=function(t){return this.inspectOpts.colors=this.useColors,Jo.inspect(t,this.inspectOpts).split(`
19
+ `).map(e=>e.trim()).join(" ")};gh.O=function(t){return this.inspectOpts.colors=this.useColors,Jo.inspect(t,this.inspectOpts)}});var Iu=J((nv,Pu)=>{typeof process>"u"||process.type==="renderer"||process.browser===!0||process.__nwjs?Pu.exports=lh():Pu.exports=yh()});var Ch=J(ot=>{"use strict";var Eb=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]})),Ab=ot&&ot.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),_h=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)&&Eb(e,t,r);return Ab(e,t),e};Object.defineProperty(ot,"__esModule",{value:!0});ot.req=ot.json=ot.toBuffer=void 0;var Sb=_h(X("http")),kb=_h(X("https"));async function bh(t){let e=0,r=[];for await(let n of t)e+=n.length,r.push(n);return Buffer.concat(r,e)}ot.toBuffer=bh;async function Db(t){let r=(await bh(t)).toString("utf8");try{return JSON.parse(r)}catch(n){let s=n;throw s.message+=` (input: ${r})`,s}}ot.json=Db;function Tb(t,e={}){let n=((typeof t=="string"?t:t.href).startsWith("https:")?kb:Sb).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=Tb});var Sh=J(lt=>{"use strict";var Eh=lt&&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]})),vb=lt&&lt.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),Ah=lt&&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)&&Eh(e,t,r);return vb(e,t),e},Rb=lt&&lt.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&Eh(e,t,r)};Object.defineProperty(lt,"__esModule",{value:!0});lt.Agent=void 0;var Ob=Ah(X("net")),wh=Ah(X("http")),Fb=X("https");Rb(Ch(),lt);var Jt=Symbol("AgentBaseInternalState"),Nu=class extends wh.Agent{constructor(e){super(e),this[Jt]={}}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 Ob.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)?Fb.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 wh.Agent)try{return c.addRequest(e,s)}catch(l){return n(l)}this[Jt].currentSocket=c,super.createSocket(e,r,n)},c=>{this.decrementSockets(i,u),n(c)})}createConnection(){let e=this[Jt].currentSocket;if(this[Jt].currentSocket=void 0,!e)throw new Error("No socket was returned in the `connect()` function");return e}get defaultPort(){return this[Jt].defaultPort??(this.protocol==="https:"?443:80)}set defaultPort(e){this[Jt]&&(this[Jt].defaultPort=e)}get protocol(){return this[Jt].protocol??(this.isSecureEndpoint()?"https:":"http:")}set protocol(e){this[Jt]&&(this[Jt].protocol=e)}};lt.Agent=Nu});var kh=J(Fn=>{"use strict";var xb=Fn&&Fn.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Fn,"__esModule",{value:!0});Fn.parseProxyResponse=void 0;var Pb=xb(Iu()),Ko=(0,Pb.default)("https-proxy-agent:parse-proxy-response");function Ib(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(),Ko("onend"),r(new Error("Proxy connection ended before receiving CONNECT response"))}function l(d){u(),Ko("onerror %o",d),r(d)}function h(d){s.push(d),n+=d.length;let p=Buffer.concat(s,n),A=p.indexOf(`\r
21
21
  \r
22
22
  `);if(A===-1){Ko("have not received end of HTTP headers yet..."),i();return}let R=p.slice(0,A).toString("ascii").split(`\r
23
- `),S=R.shift();if(!S)return t.destroy(),r(new Error("No header received from proxy CONNECT response"));let _=S.split(" "),y=+_[1],m=_.slice(2).join(" "),D={};for(let C of R){if(!C)continue;let E=C.indexOf(":");if(E===-1)return t.destroy(),r(new Error(`Invalid header from proxy CONNECT response: "${C}"`));let v=C.slice(0,E).toLowerCase(),x=C.slice(E+1).trimStart(),$=D[v];typeof $=="string"?D[v]=[$,x]:Array.isArray($)?$.push(x):D[v]=x}Ko("got proxy server response: %o %o",S,D),u(),e({connect:{statusCode:y,statusText:m,headers:D},buffered:p})}t.on("error",l),t.on("end",c),i()})}Fn.parseProxyResponse=Pb});var Oh=J(At=>{"use strict";var Ib=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]})),Nb=At&&At.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),vh=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)&&Ib(e,t,r);return Nb(e,t),e},Rh=At&&At.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(At,"__esModule",{value:!0});At.HttpsProxyAgent=void 0;var Yo=vh(X("net")),kh=vh(X("tls")),Bb=Rh(X("assert")),jb=Rh(Pu()),qb=Ah(),Lb=X("url"),Ub=Sh(),_s=(0,jb.default)("https-proxy-agent"),Dh=t=>t.servername===void 0&&t.host&&!Yo.isIP(t.host)?{...t,servername:t.host}:t,Xo=class extends qb.Agent{constructor(e,r){super(r),this.options={path:void 0},this.proxy=typeof e=="string"?new Lb.URL(e):e,this.proxyHeaders=r?.headers??{},_s("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?Th(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:"?(_s("Creating `tls.Socket`: %o",this.connectOpts),s=kh.connect(Dh(this.connectOpts))):(_s("Creating `net.Socket`: %o",this.connectOpts),s=Yo.connect(this.connectOpts));let i=typeof this.proxyHeaders=="function"?this.proxyHeaders():{...this.proxyHeaders},u=Yo.isIPv6(r.host)?`[${r.host}]`:r.host,c=`CONNECT ${u}:${r.port} HTTP/1.1\r
23
+ `),S=R.shift();if(!S)return t.destroy(),r(new Error("No header received from proxy CONNECT response"));let _=S.split(" "),y=+_[1],m=_.slice(2).join(" "),D={};for(let C of R){if(!C)continue;let E=C.indexOf(":");if(E===-1)return t.destroy(),r(new Error(`Invalid header from proxy CONNECT response: "${C}"`));let v=C.slice(0,E).toLowerCase(),x=C.slice(E+1).trimStart(),$=D[v];typeof $=="string"?D[v]=[$,x]:Array.isArray($)?$.push(x):D[v]=x}Ko("got proxy server response: %o %o",S,D),u(),e({connect:{statusCode:y,statusText:m,headers:D},buffered:p})}t.on("error",l),t.on("end",c),i()})}Fn.parseProxyResponse=Ib});var Fh=J(At=>{"use strict";var Nb=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]})),Bb=At&&At.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),Rh=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)&&Nb(e,t,r);return Bb(e,t),e},Oh=At&&At.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(At,"__esModule",{value:!0});At.HttpsProxyAgent=void 0;var Yo=Rh(X("net")),Dh=Rh(X("tls")),jb=Oh(X("assert")),qb=Oh(Iu()),Lb=Sh(),Ub=X("url"),Mb=kh(),_s=(0,qb.default)("https-proxy-agent"),Th=t=>t.servername===void 0&&t.host&&!Yo.isIP(t.host)?{...t,servername:t.host}:t,Xo=class extends Lb.Agent{constructor(e,r){super(r),this.options={path:void 0},this.proxy=typeof e=="string"?new Ub.URL(e):e,this.proxyHeaders=r?.headers??{},_s("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?vh(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:"?(_s("Creating `tls.Socket`: %o",this.connectOpts),s=Dh.connect(Th(this.connectOpts))):(_s("Creating `net.Socket`: %o",this.connectOpts),s=Yo.connect(this.connectOpts));let i=typeof this.proxyHeaders=="function"?this.proxyHeaders():{...this.proxyHeaders},u=Yo.isIPv6(r.host)?`[${r.host}]`:r.host,c=`CONNECT ${u}:${r.port} HTTP/1.1\r
24
24
  `;if(n.username||n.password){let A=`${decodeURIComponent(n.username)}:${decodeURIComponent(n.password)}`;i["Proxy-Authorization"]=`Basic ${Buffer.from(A).toString("base64")}`}i.Host=`${u}:${r.port}`,i["Proxy-Connection"]||(i["Proxy-Connection"]=this.keepAlive?"Keep-Alive":"close");for(let A of Object.keys(i))c+=`${A}: ${i[A]}\r
25
- `;let l=(0,Ub.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",Mb),r.secureEndpoint?(_s("Upgrading socket connection to TLS"),kh.connect({...Th(Dh(r),"host","path","port"),socket:s})):s;s.destroy();let p=new Yo.Socket({writable:!1});return p.readable=!0,e.once("socket",A=>{_s("Replaying proxy buffer for failed request"),(0,Bb.default)(A.listenerCount("data")>0),A.push(d),A.push(null)}),p}};Xo.protocols=["http","https"];At.HttpsProxyAgent=Xo;function Mb(t){t.resume()}function Th(t,...e){let r={},n;for(n in t)e.includes(n)||(r[n]=t[n]);return r}});function $b(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 Fh,xh=je(()=>{Fh=$b});var Ih=J((Qo,Ph)=>{(function(t,e){typeof Qo=="object"&&typeof Ph<"u"?e(Qo):typeof define=="function"&&define.amd?define(["exports"],e):(t=typeof globalThis<"u"?globalThis:t||self,e(t.WebStreamsPolyfill={}))})(Qo,(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 R(o,a){A(o,a)}function S(o,a){A(o,void 0,a)}function _(o,a,f){return p(o,a,f)}function y(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 D(o,a,f){if(typeof o!="function")throw new TypeError("Argument is not a function");return Function.prototype.apply.call(o,a,f)}function C(o,a,f){try{return h(D(o,a,f))}catch(b){return d(b)}}let E=16384;class v{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,b=f;f._elements.length===E-1&&(b={_elements:[],_next:void 0}),f._elements.push(a),b!==f&&(this._back=b,f._next=b),++this._size}shift(){let a=this._front,f=a,b=this._cursor,T=b+1,q=a._elements,M=q[b];return T===E&&(f=a._next,T=0),--this._size,this._cursor=T,a!==f&&(this._front=f),q[b]=void 0,M}forEach(a){let f=this._cursor,b=this._front,T=b._elements;for(;(f!==T.length||b._next!==void 0)&&!(f===T.length&&(b=b._next,T=b._elements,f=0,T.length===0));)a(T[f]),++f}peek(){let a=this._front,f=this._cursor;return a._elements[f]}}let x=Symbol("[[AbortSteps]]"),$=Symbol("[[ErrorSteps]]"),V=Symbol("[[CancelSteps]]"),U=Symbol("[[PullSteps]]"),Q=Symbol("[[ReleaseSteps]]");function ne(o,a){o._ownerReadableStream=a,a._reader=o,a._state==="readable"?Ae(o):a._state==="closed"?pe(o):oe(o,a._storedError)}function ae(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[Q](),a._reader=void 0,o._ownerReadableStream=void 0}function ye(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 pe(o){Ae(o),ue(o)}function G(o,a){o._closedPromise_reject!==void 0&&(y(o._closedPromise),o._closedPromise_reject(a),o._closedPromise_resolve=void 0,o._closedPromise_reject=void 0)}function K(o,a){oe(o,a)}function ue(o){o._closedPromise_resolve!==void 0&&(o._closedPromise_resolve(void 0),o._closedPromise_resolve=void 0,o._closedPromise_reject=void 0)}let Me=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 Ft(o){return typeof o=="object"&&o!==null||typeof o=="function"}function Re(o,a){if(!Ft(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 g(o,a,f){if(o===void 0)throw new TypeError(`${a} is required in '${f}'.`)}function w(o){return Number(o)}function k(o){return o===0?0:o}function B(o){return k(Te(o))}function F(o,a){let b=Number.MAX_SAFE_INTEGER,T=Number(o);if(T=k(T),!Me(T))throw new TypeError(`${a} is not a finite number`);if(T=B(T),T<0||T>b)throw new TypeError(`${a} is outside the accepted range of 0 to ${b}, inclusive`);return!Me(T)||T===0?0:T}function I(o,a){if(!vr(o))throw new TypeError(`${a} is not a ReadableStream.`)}function L(o){return new z(o)}function O(o,a){o._reader._readRequests.push(a)}function P(o,a,f){let T=o._reader._readRequests.shift();f?T._closeSteps():T._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"),Rr(a))throw new TypeError("This stream has already been locked for exclusive reading by another reader");ne(this,a),this._readRequests=new v}get closed(){return Z(this)?this._closedPromise:d(Ne("closed"))}cancel(a=void 0){return Z(this)?this._ownerReadableStream===void 0?d(ye("cancel")):ae(this,a):d(Ne("cancel"))}read(){if(!Z(this))return d(Ne("read"));if(this._ownerReadableStream===void 0)return d(ye("read from"));let a,f,b=l((q,M)=>{a=q,f=M});return ee(this,{_chunkSteps:q=>a({value:q,done:!1}),_closeSteps:()=>a({value:void 0,done:!0}),_errorSteps:q=>f(q)}),b}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[U](a)}function Ee(o){fe(o);let a=new TypeError("Reader was released");xe(o,a)}function xe(o,a){let f=o._readRequests;o._readRequests=new v,f.forEach(b=>{b._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?_(this._ongoingPromise,a,a):a(),this._ongoingPromise}return(a){let f=()=>this._returnSteps(a);return this._ongoingPromise?_(this._ongoingPromise,f,f):f()}_nextSteps(){if(this._isFinished)return Promise.resolve({value:void 0,done:!0});let a=this._reader,f,b,T=l((M,Y)=>{f=M,b=Y});return ee(a,{_chunkSteps:M=>{this._ongoingPromise=void 0,m(()=>f({value:M,done:!1}))},_closeSteps:()=>{this._ongoingPromise=void 0,this._isFinished=!0,fe(a),f({value:void 0,done:!0})},_errorSteps:M=>{this._ongoingPromise=void 0,this._isFinished=!0,fe(a),b(M)}}),T}_returnSteps(a){if(this._isFinished)return Promise.resolve({value:a,done:!0});this._isFinished=!0;let f=this._reader;if(!this._preventCancel){let b=ae(f,a);return fe(f),_(b,()=>({value:a,done:!0}))}return fe(f),h({value:a,done:!0})}}let Le={next(){return dn(this)?this._asyncIteratorImpl.next():d(hn("next"))},return(o){return dn(this)?this._asyncIteratorImpl.return(o):d(hn("return"))}};Object.setPrototypeOf(Le,we);function fn(o,a){let f=L(o),b=new Se(f,a),T=Object.create(Le);return T._asyncIteratorImpl=b,T}function dn(o){if(!r(o)||!Object.prototype.hasOwnProperty.call(o,"_asyncIteratorImpl"))return!1;try{return o._asyncIteratorImpl instanceof Se}catch{return!1}}function hn(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 _f(o,a,f,b,T){new Uint8Array(o).set(new Uint8Array(f,b,T),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)),Sr=o=>(typeof o.detached=="boolean"?Sr=a=>a.detached:Sr=a=>a.byteLength===0,Sr(o));function bf(o,a,f){if(o.slice)return o.slice(a,f);let b=f-a,T=new ArrayBuffer(b);return _f(T,0,o,a,b),T}function so(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 qy(o){let a={[Symbol.iterator]:()=>o.iterator},f=(async function*(){return yield*a})(),b=f.next;return{iterator:f,nextMethod:b,done:!1}}let Ba=(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 Cf(o,a="sync",f){if(f===void 0)if(a==="async"){if(f=so(o,Ba),f===void 0){let q=so(o,Symbol.iterator),M=Cf(o,"sync",q);return qy(M)}}else f=so(o,Symbol.iterator);if(f===void 0)throw new TypeError("The object is not iterable");let b=D(f,o,[]);if(!r(b))throw new TypeError("The iterator method must return an object");let T=b.next;return{iterator:b,nextMethod:T,done:!1}}function Ly(o){let a=D(o.nextMethod,o.iterator,[]);if(!r(a))throw new TypeError("The iterator.next() method must return an object");return a}function Uy(o){return!!o.done}function My(o){return o.value}function $y(o){return!(typeof o!="number"||ut(o)||o<0)}function wf(o){let a=bf(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 qa(o,a,f){if(!$y(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 zy(o){return o._queue.peek().value}function kr(o){o._queue=new v,o._queueTotalSize=0}function Ef(o){return o===DataView}function Hy(o){return Ef(o.constructor)}function Wy(o){return Ef(o)?1:o.BYTES_PER_ELEMENT}class Wr{constructor(){throw new TypeError("Illegal constructor")}get view(){if(!La(this))throw Ha("view");return this._view}respond(a){if(!La(this))throw Ha("respond");if(Be(a,1,"respond"),a=F(a,"First parameter"),this._associatedReadableByteStreamController===void 0)throw new TypeError("This BYOB request has been invalidated");if(Sr(this._view.buffer))throw new TypeError("The BYOB request's buffer has been detached and so cannot be used as a response");uo(this._associatedReadableByteStreamController,a)}respondWithNewView(a){if(!La(this))throw Ha("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(Sr(a.buffer))throw new TypeError("The given view's buffer has been detached and so cannot be used as a response");co(this._associatedReadableByteStreamController,a)}}Object.defineProperties(Wr.prototype,{respond:{enumerable:!0},respondWithNewView:{enumerable:!0},view:{enumerable:!0}}),s(Wr.prototype.respond,"respond"),s(Wr.prototype.respondWithNewView,"respondWithNewView"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Wr.prototype,Symbol.toStringTag,{value:"ReadableStreamBYOBRequest",configurable:!0});class ur{constructor(){throw new TypeError("Illegal constructor")}get byobRequest(){if(!Gr(this))throw us("byobRequest");return za(this)}get desiredSize(){if(!Gr(this))throw us("desiredSize");return xf(this)}close(){if(!Gr(this))throw us("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`);as(this)}enqueue(a){if(!Gr(this))throw us("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`);ao(this,a)}error(a=void 0){if(!Gr(this))throw us("error");bt(this,a)}[V](a){Af(this),kr(this);let f=this._cancelAlgorithm(a);return io(this),f}[U](a){let f=this._controlledReadableByteStream;if(this._queueTotalSize>0){Ff(this,a);return}let b=this._autoAllocateChunkSize;if(b!==void 0){let T;try{T=new ArrayBuffer(b)}catch(M){a._errorSteps(M);return}let q={buffer:T,bufferByteLength:b,byteOffset:0,byteLength:b,bytesFilled:0,minimumFill:1,elementSize:1,viewConstructor:Uint8Array,readerType:"default"};this._pendingPullIntos.push(q)}O(f,a),Jr(this)}[Q](){if(this._pendingPullIntos.length>0){let a=this._pendingPullIntos.peek();a.readerType="none",this._pendingPullIntos=new v,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 Gr(o){return!r(o)||!Object.prototype.hasOwnProperty.call(o,"_controlledReadableByteStream")?!1:o instanceof ur}function La(o){return!r(o)||!Object.prototype.hasOwnProperty.call(o,"_associatedReadableByteStreamController")?!1:o instanceof Wr}function Jr(o){if(!Yy(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,Jr(o)),null),b=>(bt(o,b),null))}function Af(o){Ma(o),o._pendingPullIntos=new v}function Ua(o,a){let f=!1;o._state==="closed"&&(f=!0);let b=Sf(a);a.readerType==="default"?P(o,b,f):r0(o,b,f)}function Sf(o){let a=o.bytesFilled,f=o.elementSize;return new o.viewConstructor(o.buffer,o.byteOffset,a/f)}function oo(o,a,f,b){o._queue.push({buffer:a,byteOffset:f,byteLength:b}),o._queueTotalSize+=b}function kf(o,a,f,b){let T;try{T=bf(a,f,f+b)}catch(q){throw bt(o,q),q}oo(o,T,0,b)}function Df(o,a){a.bytesFilled>0&&kf(o,a.buffer,a.byteOffset,a.bytesFilled),pn(o)}function Tf(o,a){let f=Math.min(o._queueTotalSize,a.byteLength-a.bytesFilled),b=a.bytesFilled+f,T=f,q=!1,M=b%a.elementSize,Y=b-M;Y>=a.minimumFill&&(T=Y-a.bytesFilled,q=!0);let ce=o._queue;for(;T>0;){let re=ce.peek(),de=Math.min(T,re.byteLength),ge=a.byteOffset+a.bytesFilled;_f(a.buffer,ge,re.buffer,re.byteOffset,de),re.byteLength===de?ce.shift():(re.byteOffset+=de,re.byteLength-=de),o._queueTotalSize-=de,vf(o,de,a),T-=de}return q}function vf(o,a,f){f.bytesFilled+=a}function Rf(o){o._queueTotalSize===0&&o._closeRequested?(io(o),ps(o._controlledReadableByteStream)):Jr(o)}function Ma(o){o._byobRequest!==null&&(o._byobRequest._associatedReadableByteStreamController=void 0,o._byobRequest._view=null,o._byobRequest=null)}function $a(o){for(;o._pendingPullIntos.length>0;){if(o._queueTotalSize===0)return;let a=o._pendingPullIntos.peek();Tf(o,a)&&(pn(o),Ua(o._controlledReadableByteStream,a))}}function Gy(o){let a=o._controlledReadableByteStream._reader;for(;a._readRequests.length>0;){if(o._queueTotalSize===0)return;let f=a._readRequests.shift();Ff(o,f)}}function Jy(o,a,f,b){let T=o._controlledReadableByteStream,q=a.constructor,M=Wy(q),{byteOffset:Y,byteLength:ce}=a,re=f*M,de;try{de=ar(a.buffer)}catch(ve){b._errorSteps(ve);return}let ge={buffer:de,bufferByteLength:de.byteLength,byteOffset:Y,byteLength:ce,bytesFilled:0,minimumFill:re,elementSize:M,viewConstructor:q,readerType:"byob"};if(o._pendingPullIntos.length>0){o._pendingPullIntos.push(ge),Nf(T,b);return}if(T._state==="closed"){let ve=new q(ge.buffer,ge.byteOffset,0);b._closeSteps(ve);return}if(o._queueTotalSize>0){if(Tf(o,ge)){let ve=Sf(ge);Rf(o),b._chunkSteps(ve);return}if(o._closeRequested){let ve=new TypeError("Insufficient bytes to fill elements in the given buffer");bt(o,ve),b._errorSteps(ve);return}}o._pendingPullIntos.push(ge),Nf(T,b),Jr(o)}function Vy(o,a){a.readerType==="none"&&pn(o);let f=o._controlledReadableByteStream;if(Wa(f))for(;Bf(f)>0;){let b=pn(o);Ua(f,b)}}function Ky(o,a,f){if(vf(o,a,f),f.readerType==="none"){Df(o,f),$a(o);return}if(f.bytesFilled<f.minimumFill)return;pn(o);let b=f.bytesFilled%f.elementSize;if(b>0){let T=f.byteOffset+f.bytesFilled;kf(o,f.buffer,T-b,b)}f.bytesFilled-=b,Ua(o._controlledReadableByteStream,f),$a(o)}function Of(o,a){let f=o._pendingPullIntos.peek();Ma(o),o._controlledReadableByteStream._state==="closed"?Vy(o,f):Ky(o,a,f),Jr(o)}function pn(o){return o._pendingPullIntos.shift()}function Yy(o){let a=o._controlledReadableByteStream;return a._state!=="readable"||o._closeRequested||!o._started?!1:!!(N(a)&&j(a)>0||Wa(a)&&Bf(a)>0||xf(o)>0)}function io(o){o._pullAlgorithm=void 0,o._cancelAlgorithm=void 0}function as(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 b=new TypeError("Insufficient bytes to fill elements in the given buffer");throw bt(o,b),b}}io(o),ps(a)}}function ao(o,a){let f=o._controlledReadableByteStream;if(o._closeRequested||f._state!=="readable")return;let{buffer:b,byteOffset:T,byteLength:q}=a;if(Sr(b))throw new TypeError("chunk's buffer is detached and so cannot be enqueued");let M=ar(b);if(o._pendingPullIntos.length>0){let Y=o._pendingPullIntos.peek();if(Sr(Y.buffer))throw new TypeError("The BYOB request's buffer has been detached and so cannot be filled with an enqueued chunk");Ma(o),Y.buffer=ar(Y.buffer),Y.readerType==="none"&&Df(o,Y)}if(N(f))if(Gy(o),j(f)===0)oo(o,M,T,q);else{o._pendingPullIntos.length>0&&pn(o);let Y=new Uint8Array(M,T,q);P(f,Y,!1)}else Wa(f)?(oo(o,M,T,q),$a(o)):oo(o,M,T,q);Jr(o)}function bt(o,a){let f=o._controlledReadableByteStream;f._state==="readable"&&(Af(o),kr(o),io(o),id(f,a))}function Ff(o,a){let f=o._queue.shift();o._queueTotalSize-=f.byteLength,Rf(o);let b=new Uint8Array(f.buffer,f.byteOffset,f.byteLength);a._chunkSteps(b)}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),b=Object.create(Wr.prototype);Qy(b,o,f),o._byobRequest=b}return o._byobRequest}function xf(o){let a=o._controlledReadableByteStream._state;return a==="errored"?null:a==="closed"?0:o._strategyHWM-o._queueTotalSize}function uo(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),Of(o,a)}function co(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 T=a.byteLength;f.buffer=ar(a.buffer),Of(o,T)}function Pf(o,a,f,b,T,q,M){a._controlledReadableByteStream=o,a._pullAgain=!1,a._pulling=!1,a._byobRequest=null,a._queue=a._queueTotalSize=void 0,kr(a),a._closeRequested=!1,a._started=!1,a._strategyHWM=q,a._pullAlgorithm=b,a._cancelAlgorithm=T,a._autoAllocateChunkSize=M,a._pendingPullIntos=new v,o._readableStreamController=a;let Y=f();A(h(Y),()=>(a._started=!0,Jr(a),null),ce=>(bt(a,ce),null))}function Xy(o,a,f){let b=Object.create(ur.prototype),T,q,M;a.start!==void 0?T=()=>a.start(b):T=()=>{},a.pull!==void 0?q=()=>a.pull(b):q=()=>h(void 0),a.cancel!==void 0?M=ce=>a.cancel(ce):M=()=>h(void 0);let Y=a.autoAllocateChunkSize;if(Y===0)throw new TypeError("autoAllocateChunkSize must be greater than 0");Pf(o,b,T,q,M,f,Y)}function Qy(o,a,f){o._associatedReadableByteStreamController=a,o._view=f}function Ha(o){return new TypeError(`ReadableStreamBYOBRequest.prototype.${o} can only be used on a ReadableStreamBYOBRequest`)}function us(o){return new TypeError(`ReadableByteStreamController.prototype.${o} can only be used on a ReadableByteStreamController`)}function Zy(o,a){le(o,a);let f=o?.mode;return{mode:f===void 0?void 0:e0(f,`${a} has member 'mode' that`)}}function e0(o,a){if(o=`${o}`,o!=="byob")throw new TypeError(`${a} '${o}' is not a valid enumeration value for ReadableStreamReaderMode`);return o}function t0(o,a){var f;le(o,a);let b=(f=o?.min)!==null&&f!==void 0?f:1;return{min:F(b,`${a} has member 'min' that`)}}function If(o){return new Dr(o)}function Nf(o,a){o._reader._readIntoRequests.push(a)}function r0(o,a,f){let T=o._reader._readIntoRequests.shift();f?T._closeSteps(a):T._chunkSteps(a)}function Bf(o){return o._reader._readIntoRequests.length}function Wa(o){let a=o._reader;return!(a===void 0||!Vr(a))}class Dr{constructor(a){if(Be(a,1,"ReadableStreamBYOBReader"),I(a,"First parameter"),Rr(a))throw new TypeError("This stream has already been locked for exclusive reading by another reader");if(!Gr(a._readableStreamController))throw new TypeError("Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte source");ne(this,a),this._readIntoRequests=new v}get closed(){return Vr(this)?this._closedPromise:d(lo("closed"))}cancel(a=void 0){return Vr(this)?this._ownerReadableStream===void 0?d(ye("cancel")):ae(this,a):d(lo("cancel"))}read(a,f={}){if(!Vr(this))return d(lo("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(Sr(a.buffer))return d(new TypeError("view's buffer has been detached"));let b;try{b=t0(f,"options")}catch(re){return d(re)}let T=b.min;if(T===0)return d(new TypeError("options.min must be greater than 0"));if(Hy(a)){if(T>a.byteLength)return d(new RangeError("options.min must be less than or equal to view's byteLength"))}else if(T>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(ye("read from"));let q,M,Y=l((re,de)=>{q=re,M=de});return jf(this,a,T,{_chunkSteps:re=>q({value:re,done:!1}),_closeSteps:re=>q({value:re,done:!0}),_errorSteps:re=>M(re)}),Y}releaseLock(){if(!Vr(this))throw lo("releaseLock");this._ownerReadableStream!==void 0&&n0(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 Vr(o){return!r(o)||!Object.prototype.hasOwnProperty.call(o,"_readIntoRequests")?!1:o instanceof Dr}function jf(o,a,f,b){let T=o._ownerReadableStream;T._disturbed=!0,T._state==="errored"?b._errorSteps(T._storedError):Jy(T._readableStreamController,a,f,b)}function n0(o){fe(o);let a=new TypeError("Reader was released");qf(o,a)}function qf(o,a){let f=o._readIntoRequests;o._readIntoRequests=new v,f.forEach(b=>{b._errorSteps(a)})}function lo(o){return new TypeError(`ReadableStreamBYOBReader.prototype.${o} can only be used on a ReadableStreamBYOBReader`)}function cs(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 fo(o){let{size:a}=o;return a||(()=>1)}function ho(o,a){le(o,a);let f=o?.highWaterMark,b=o?.size;return{highWaterMark:f===void 0?void 0:w(f),size:b===void 0?void 0:s0(b,`${a} has member 'size' that`)}}function s0(o,a){return _e(o,a),f=>w(o(f))}function o0(o,a){le(o,a);let f=o?.abort,b=o?.close,T=o?.start,q=o?.type,M=o?.write;return{abort:f===void 0?void 0:i0(f,o,`${a} has member 'abort' that`),close:b===void 0?void 0:a0(b,o,`${a} has member 'close' that`),start:T===void 0?void 0:u0(T,o,`${a} has member 'start' that`),write:M===void 0?void 0:c0(M,o,`${a} has member 'write' that`),type:q}}function i0(o,a,f){return _e(o,f),b=>C(o,a,[b])}function a0(o,a,f){return _e(o,f),()=>C(o,a,[])}function u0(o,a,f){return _e(o,f),b=>D(o,a,[b])}function c0(o,a,f){return _e(o,f),(b,T)=>C(o,a,[b,T])}function Lf(o,a){if(!mn(o))throw new TypeError(`${a} is not a WritableStream.`)}function l0(o){if(typeof o!="object"||o===null)return!1;try{return typeof o.aborted=="boolean"}catch{return!1}}let f0=typeof AbortController=="function";function d0(){if(f0)return new AbortController}class Tr{constructor(a={},f={}){a===void 0?a=null:Re(a,"First parameter");let b=ho(f,"Second parameter"),T=o0(a,"First parameter");if(Mf(this),T.type!==void 0)throw new RangeError("Invalid type is specified");let M=fo(b),Y=cs(b,1);D0(this,T,Y,M)}get locked(){if(!mn(this))throw _o("locked");return gn(this)}abort(a=void 0){return mn(this)?gn(this)?d(new TypeError("Cannot abort a stream that already has a writer")):po(this,a):d(_o("abort"))}close(){return mn(this)?gn(this)?d(new TypeError("Cannot close a stream that already has a writer")):Wt(this)?d(new TypeError("Cannot close an already-closing stream")):$f(this):d(_o("close"))}getWriter(){if(!mn(this))throw _o("getWriter");return Uf(this)}}Object.defineProperties(Tr.prototype,{abort:{enumerable:!0},close:{enumerable:!0},getWriter:{enumerable:!0},locked:{enumerable:!0}}),s(Tr.prototype.abort,"abort"),s(Tr.prototype.close,"close"),s(Tr.prototype.getWriter,"getWriter"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Tr.prototype,Symbol.toStringTag,{value:"WritableStream",configurable:!0});function Uf(o){return new cr(o)}function h0(o,a,f,b,T=1,q=()=>1){let M=Object.create(Tr.prototype);Mf(M);let Y=Object.create(yn.prototype);return Vf(M,Y,o,a,f,b,T,q),M}function Mf(o){o._state="writable",o._storedError=void 0,o._writer=void 0,o._writableStreamController=void 0,o._writeRequests=new v,o._inFlightWriteRequest=void 0,o._closeRequest=void 0,o._inFlightCloseRequest=void 0,o._pendingAbortRequest=void 0,o._backpressure=!1}function mn(o){return!r(o)||!Object.prototype.hasOwnProperty.call(o,"_writableStreamController")?!1:o instanceof Tr}function gn(o){return o._writer!==void 0}function po(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 b=o._state;if(b==="closed"||b==="errored")return h(void 0);if(o._pendingAbortRequest!==void 0)return o._pendingAbortRequest._promise;let T=!1;b==="erroring"&&(T=!0,a=void 0);let q=l((M,Y)=>{o._pendingAbortRequest={_promise:void 0,_resolve:M,_reject:Y,_reason:a,_wasAlreadyErroring:T}});return o._pendingAbortRequest._promise=q,T||Ja(o,a),q}function $f(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((T,q)=>{let M={_resolve:T,_reject:q};o._closeRequest=M}),b=o._writer;return b!==void 0&&o._backpressure&&a==="writable"&&tu(b),T0(o._writableStreamController),f}function p0(o){return l((f,b)=>{let T={_resolve:f,_reject:b};o._writeRequests.push(T)})}function Ga(o,a){if(o._state==="writable"){Ja(o,a);return}Va(o)}function Ja(o,a){let f=o._writableStreamController;o._state="erroring",o._storedError=a;let b=o._writer;b!==void 0&&Hf(b,a),!b0(o)&&f._started&&Va(o)}function Va(o){o._state="errored",o._writableStreamController[$]();let a=o._storedError;if(o._writeRequests.forEach(T=>{T._reject(a)}),o._writeRequests=new v,o._pendingAbortRequest===void 0){mo(o);return}let f=o._pendingAbortRequest;if(o._pendingAbortRequest=void 0,f._wasAlreadyErroring){f._reject(a),mo(o);return}let b=o._writableStreamController[x](f._reason);A(b,()=>(f._resolve(),mo(o),null),T=>(f._reject(T),mo(o),null))}function m0(o){o._inFlightWriteRequest._resolve(void 0),o._inFlightWriteRequest=void 0}function g0(o,a){o._inFlightWriteRequest._reject(a),o._inFlightWriteRequest=void 0,Ga(o,a)}function y0(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&&Qf(f)}function _0(o,a){o._inFlightCloseRequest._reject(a),o._inFlightCloseRequest=void 0,o._pendingAbortRequest!==void 0&&(o._pendingAbortRequest._reject(a),o._pendingAbortRequest=void 0),Ga(o,a)}function Wt(o){return!(o._closeRequest===void 0&&o._inFlightCloseRequest===void 0)}function b0(o){return!(o._inFlightWriteRequest===void 0&&o._inFlightCloseRequest===void 0)}function C0(o){o._inFlightCloseRequest=o._closeRequest,o._closeRequest=void 0}function w0(o){o._inFlightWriteRequest=o._writeRequests.shift()}function mo(o){o._closeRequest!==void 0&&(o._closeRequest._reject(o._storedError),o._closeRequest=void 0);let a=o._writer;a!==void 0&&Za(a,o._storedError)}function Ka(o,a){let f=o._writer;f!==void 0&&a!==o._backpressure&&(a?I0(f):tu(f)),o._backpressure=a}class cr{constructor(a){if(Be(a,1,"WritableStreamDefaultWriter"),Lf(a,"First parameter"),gn(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?Co(this):Zf(this),bo(this);else if(f==="erroring")eu(this,a._storedError),bo(this);else if(f==="closed")Zf(this),x0(this);else{let b=a._storedError;eu(this,b),Xf(this,b)}}get closed(){return Kr(this)?this._closedPromise:d(Yr("closed"))}get desiredSize(){if(!Kr(this))throw Yr("desiredSize");if(this._ownerWritableStream===void 0)throw fs("desiredSize");return k0(this)}get ready(){return Kr(this)?this._readyPromise:d(Yr("ready"))}abort(a=void 0){return Kr(this)?this._ownerWritableStream===void 0?d(fs("abort")):E0(this,a):d(Yr("abort"))}close(){if(!Kr(this))return d(Yr("close"));let a=this._ownerWritableStream;return a===void 0?d(fs("close")):Wt(a)?d(new TypeError("Cannot close an already-closing stream")):zf(this)}releaseLock(){if(!Kr(this))throw Yr("releaseLock");this._ownerWritableStream!==void 0&&Wf(this)}write(a=void 0){return Kr(this)?this._ownerWritableStream===void 0?d(fs("write to")):Gf(this,a):d(Yr("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 Kr(o){return!r(o)||!Object.prototype.hasOwnProperty.call(o,"_ownerWritableStream")?!1:o instanceof cr}function E0(o,a){let f=o._ownerWritableStream;return po(f,a)}function zf(o){let a=o._ownerWritableStream;return $f(a)}function A0(o){let a=o._ownerWritableStream,f=a._state;return Wt(a)||f==="closed"?h(void 0):f==="errored"?d(a._storedError):zf(o)}function S0(o,a){o._closedPromiseState==="pending"?Za(o,a):P0(o,a)}function Hf(o,a){o._readyPromiseState==="pending"?ed(o,a):N0(o,a)}function k0(o){let a=o._ownerWritableStream,f=a._state;return f==="errored"||f==="erroring"?null:f==="closed"?0:Kf(a._writableStreamController)}function Wf(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),S0(o,f),a._writer=void 0,o._ownerWritableStream=void 0}function Gf(o,a){let f=o._ownerWritableStream,b=f._writableStreamController,T=v0(b,a);if(f!==o._ownerWritableStream)return d(fs("write to"));let q=f._state;if(q==="errored")return d(f._storedError);if(Wt(f)||q==="closed")return d(new TypeError("The stream is closing or closed and cannot be written to"));if(q==="erroring")return d(f._storedError);let M=p0(f);return R0(b,a,T),M}let Jf={};class yn{constructor(){throw new TypeError("Illegal constructor")}get abortReason(){if(!Ya(this))throw Qa("abortReason");return this._abortReason}get signal(){if(!Ya(this))throw Qa("signal");if(this._abortController===void 0)throw new TypeError("WritableStreamDefaultController.prototype.signal is not supported");return this._abortController.signal}error(a=void 0){if(!Ya(this))throw Qa("error");this._controlledWritableStream._state==="writable"&&Yf(this,a)}[x](a){let f=this._abortAlgorithm(a);return go(this),f}[$](){kr(this)}}Object.defineProperties(yn.prototype,{abortReason:{enumerable:!0},signal:{enumerable:!0},error:{enumerable:!0}}),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(yn.prototype,Symbol.toStringTag,{value:"WritableStreamDefaultController",configurable:!0});function Ya(o){return!r(o)||!Object.prototype.hasOwnProperty.call(o,"_controlledWritableStream")?!1:o instanceof yn}function Vf(o,a,f,b,T,q,M,Y){a._controlledWritableStream=o,o._writableStreamController=a,a._queue=void 0,a._queueTotalSize=void 0,kr(a),a._abortReason=void 0,a._abortController=d0(),a._started=!1,a._strategySizeAlgorithm=Y,a._strategyHWM=M,a._writeAlgorithm=b,a._closeAlgorithm=T,a._abortAlgorithm=q;let ce=Xa(a);Ka(o,ce);let re=f(),de=h(re);A(de,()=>(a._started=!0,yo(a),null),ge=>(a._started=!0,Ga(o,ge),null))}function D0(o,a,f,b){let T=Object.create(yn.prototype),q,M,Y,ce;a.start!==void 0?q=()=>a.start(T):q=()=>{},a.write!==void 0?M=re=>a.write(re,T):M=()=>h(void 0),a.close!==void 0?Y=()=>a.close():Y=()=>h(void 0),a.abort!==void 0?ce=re=>a.abort(re):ce=()=>h(void 0),Vf(o,T,q,M,Y,ce,f,b)}function go(o){o._writeAlgorithm=void 0,o._closeAlgorithm=void 0,o._abortAlgorithm=void 0,o._strategySizeAlgorithm=void 0}function T0(o){qa(o,Jf,0),yo(o)}function v0(o,a){try{return o._strategySizeAlgorithm(a)}catch(f){return ls(o,f),1}}function Kf(o){return o._strategyHWM-o._queueTotalSize}function R0(o,a,f){try{qa(o,a,f)}catch(T){ls(o,T);return}let b=o._controlledWritableStream;if(!Wt(b)&&b._state==="writable"){let T=Xa(o);Ka(b,T)}yo(o)}function yo(o){let a=o._controlledWritableStream;if(!o._started||a._inFlightWriteRequest!==void 0)return;if(a._state==="erroring"){Va(a);return}if(o._queue.length===0)return;let b=zy(o);b===Jf?O0(o):F0(o,b)}function ls(o,a){o._controlledWritableStream._state==="writable"&&Yf(o,a)}function O0(o){let a=o._controlledWritableStream;C0(a),ja(o);let f=o._closeAlgorithm();go(o),A(f,()=>(y0(a),null),b=>(_0(a,b),null))}function F0(o,a){let f=o._controlledWritableStream;w0(f);let b=o._writeAlgorithm(a);A(b,()=>{m0(f);let T=f._state;if(ja(o),!Wt(f)&&T==="writable"){let q=Xa(o);Ka(f,q)}return yo(o),null},T=>(f._state==="writable"&&go(o),g0(f,T),null))}function Xa(o){return Kf(o)<=0}function Yf(o,a){let f=o._controlledWritableStream;go(o),Ja(f,a)}function _o(o){return new TypeError(`WritableStream.prototype.${o} can only be used on a WritableStream`)}function Qa(o){return new TypeError(`WritableStreamDefaultController.prototype.${o} can only be used on a WritableStreamDefaultController`)}function Yr(o){return new TypeError(`WritableStreamDefaultWriter.prototype.${o} can only be used on a WritableStreamDefaultWriter`)}function fs(o){return new TypeError("Cannot "+o+" a stream using a released writer")}function bo(o){o._closedPromise=l((a,f)=>{o._closedPromise_resolve=a,o._closedPromise_reject=f,o._closedPromiseState="pending"})}function Xf(o,a){bo(o),Za(o,a)}function x0(o){bo(o),Qf(o)}function Za(o,a){o._closedPromise_reject!==void 0&&(y(o._closedPromise),o._closedPromise_reject(a),o._closedPromise_resolve=void 0,o._closedPromise_reject=void 0,o._closedPromiseState="rejected")}function P0(o,a){Xf(o,a)}function Qf(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 Co(o){o._readyPromise=l((a,f)=>{o._readyPromise_resolve=a,o._readyPromise_reject=f}),o._readyPromiseState="pending"}function eu(o,a){Co(o),ed(o,a)}function Zf(o){Co(o),tu(o)}function ed(o,a){o._readyPromise_reject!==void 0&&(y(o._readyPromise),o._readyPromise_reject(a),o._readyPromise_resolve=void 0,o._readyPromise_reject=void 0,o._readyPromiseState="rejected")}function I0(o){Co(o)}function N0(o,a){eu(o,a)}function tu(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 B0(){if(typeof globalThis<"u")return globalThis;if(typeof self<"u")return self;if(typeof global<"u")return global}let ru=B0();function j0(o){if(!(typeof o=="function"||typeof o=="object")||o.name!=="DOMException")return!1;try{return new o,!0}catch{return!1}}function q0(){let o=ru?.DOMException;return j0(o)?o:void 0}function L0(){let o=function(f,b){this.message=f||"",this.name=b||"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 U0=q0()||L0();function td(o,a,f,b,T,q){let M=L(o),Y=Uf(a);o._disturbed=!0;let ce=!1,re=h(void 0);return l((de,ge)=>{let ve;if(q!==void 0){if(ve=()=>{let se=q.reason!==void 0?q.reason:new U0("Aborted","AbortError"),be=[];b||be.push(()=>a._state==="writable"?po(a,se):h(void 0)),T||be.push(()=>o._state==="readable"?Pt(o,se):h(void 0)),rt(()=>Promise.all(be.map(Oe=>Oe())),!0,se)},q.aborted){ve();return}q.addEventListener("abort",ve)}function It(){return l((se,be)=>{function Oe(ct){ct?se():p(wn(),Oe,be)}Oe(!1)})}function wn(){return ce?h(!0):p(Y._readyPromise,()=>l((se,be)=>{ee(M,{_chunkSteps:Oe=>{re=p(Gf(Y,Oe),void 0,e),se(!1)},_closeSteps:()=>se(!0),_errorSteps:be})}))}if(fr(o,M._closedPromise,se=>(b?Ct(!0,se):rt(()=>po(a,se),!0,se),null)),fr(a,Y._closedPromise,se=>(T?Ct(!0,se):rt(()=>Pt(o,se),!0,se),null)),Qe(o,M._closedPromise,()=>(f?Ct():rt(()=>A0(Y)),null)),Wt(a)||a._state==="closed"){let se=new TypeError("the destination writable stream closed before all data could be piped to it");T?Ct(!0,se):rt(()=>Pt(o,se),!0,se)}y(It());function Fr(){let se=re;return p(re,()=>se!==re?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():R(be,Oe)}function rt(se,be,Oe){if(ce)return;ce=!0,a._state==="writable"&&!Wt(a)?R(Fr(),ct):ct();function ct(){return A(se(),()=>dr(be,Oe),En=>dr(!0,En)),null}}function Ct(se,be){ce||(ce=!0,a._state==="writable"&&!Wt(a)?R(Fr(),()=>dr(se,be)):dr(se,be))}function dr(se,be){return Wf(Y),fe(M),q!==void 0&&q.removeEventListener("abort",ve),se?ge(be):de(void 0),null}})}class lr{constructor(){throw new TypeError("Illegal constructor")}get desiredSize(){if(!wo(this))throw Ao("desiredSize");return nu(this)}close(){if(!wo(this))throw Ao("close");if(!bn(this))throw new TypeError("The stream is not in a state that permits close");Xr(this)}enqueue(a=void 0){if(!wo(this))throw Ao("enqueue");if(!bn(this))throw new TypeError("The stream is not in a state that permits enqueue");return _n(this,a)}error(a=void 0){if(!wo(this))throw Ao("error");xt(this,a)}[V](a){kr(this);let f=this._cancelAlgorithm(a);return Eo(this),f}[U](a){let f=this._controlledReadableStream;if(this._queue.length>0){let b=ja(this);this._closeRequested&&this._queue.length===0?(Eo(this),ps(f)):ds(this),a._chunkSteps(b)}else O(f,a),ds(this)}[Q](){}}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 wo(o){return!r(o)||!Object.prototype.hasOwnProperty.call(o,"_controlledReadableStream")?!1:o instanceof lr}function ds(o){if(!rd(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,ds(o)),null),b=>(xt(o,b),null))}function rd(o){let a=o._controlledReadableStream;return!bn(o)||!o._started?!1:!!(Rr(a)&&j(a)>0||nu(o)>0)}function Eo(o){o._pullAlgorithm=void 0,o._cancelAlgorithm=void 0,o._strategySizeAlgorithm=void 0}function Xr(o){if(!bn(o))return;let a=o._controlledReadableStream;o._closeRequested=!0,o._queue.length===0&&(Eo(o),ps(a))}function _n(o,a){if(!bn(o))return;let f=o._controlledReadableStream;if(Rr(f)&&j(f)>0)P(f,a,!1);else{let b;try{b=o._strategySizeAlgorithm(a)}catch(T){throw xt(o,T),T}try{qa(o,a,b)}catch(T){throw xt(o,T),T}}ds(o)}function xt(o,a){let f=o._controlledReadableStream;f._state==="readable"&&(kr(o),Eo(o),id(f,a))}function nu(o){let a=o._controlledReadableStream._state;return a==="errored"?null:a==="closed"?0:o._strategyHWM-o._queueTotalSize}function M0(o){return!rd(o)}function bn(o){let a=o._controlledReadableStream._state;return!o._closeRequested&&a==="readable"}function nd(o,a,f,b,T,q,M){a._controlledReadableStream=o,a._queue=void 0,a._queueTotalSize=void 0,kr(a),a._started=!1,a._closeRequested=!1,a._pullAgain=!1,a._pulling=!1,a._strategySizeAlgorithm=M,a._strategyHWM=q,a._pullAlgorithm=b,a._cancelAlgorithm=T,o._readableStreamController=a;let Y=f();A(h(Y),()=>(a._started=!0,ds(a),null),ce=>(xt(a,ce),null))}function $0(o,a,f,b){let T=Object.create(lr.prototype),q,M,Y;a.start!==void 0?q=()=>a.start(T):q=()=>{},a.pull!==void 0?M=()=>a.pull(T):M=()=>h(void 0),a.cancel!==void 0?Y=ce=>a.cancel(ce):Y=()=>h(void 0),nd(o,T,q,M,Y,f,b)}function Ao(o){return new TypeError(`ReadableStreamDefaultController.prototype.${o} can only be used on a ReadableStreamDefaultController`)}function z0(o,a){return Gr(o._readableStreamController)?W0(o):H0(o)}function H0(o,a){let f=L(o),b=!1,T=!1,q=!1,M=!1,Y,ce,re,de,ge,ve=l(Qe=>{ge=Qe});function It(){return b?(T=!0,h(void 0)):(b=!0,ee(f,{_chunkSteps:rt=>{m(()=>{T=!1;let Ct=rt,dr=rt;q||_n(re._readableStreamController,Ct),M||_n(de._readableStreamController,dr),b=!1,T&&It()})},_closeSteps:()=>{b=!1,q||Xr(re._readableStreamController),M||Xr(de._readableStreamController),(!q||!M)&&ge(void 0)},_errorSteps:()=>{b=!1}}),h(void 0))}function wn(Qe){if(q=!0,Y=Qe,M){let rt=ke([Y,ce]),Ct=Pt(o,rt);ge(Ct)}return ve}function Fr(Qe){if(M=!0,ce=Qe,q){let rt=ke([Y,ce]),Ct=Pt(o,rt);ge(Ct)}return ve}function fr(){}return re=hs(fr,It,wn),de=hs(fr,It,Fr),S(f._closedPromise,Qe=>(xt(re._readableStreamController,Qe),xt(de._readableStreamController,Qe),(!q||!M)&&ge(void 0),null)),[re,de]}function W0(o){let a=L(o),f=!1,b=!1,T=!1,q=!1,M=!1,Y,ce,re,de,ge,ve=l(se=>{ge=se});function It(se){S(se._closedPromise,be=>(se!==a||(bt(re._readableStreamController,be),bt(de._readableStreamController,be),(!q||!M)&&ge(void 0)),null))}function wn(){Vr(a)&&(fe(a),a=L(o),It(a)),ee(a,{_chunkSteps:be=>{m(()=>{b=!1,T=!1;let Oe=be,ct=be;if(!q&&!M)try{ct=wf(be)}catch(En){bt(re._readableStreamController,En),bt(de._readableStreamController,En),ge(Pt(o,En));return}q||ao(re._readableStreamController,Oe),M||ao(de._readableStreamController,ct),f=!1,b?fr():T&&Qe()})},_closeSteps:()=>{f=!1,q||as(re._readableStreamController),M||as(de._readableStreamController),re._readableStreamController._pendingPullIntos.length>0&&uo(re._readableStreamController,0),de._readableStreamController._pendingPullIntos.length>0&&uo(de._readableStreamController,0),(!q||!M)&&ge(void 0)},_errorSteps:()=>{f=!1}})}function Fr(se,be){Z(a)&&(fe(a),a=If(o),It(a));let Oe=be?de:re,ct=be?re:de;jf(a,se,1,{_chunkSteps:An=>{m(()=>{b=!1,T=!1;let Sn=be?M:q;if(be?q:M)Sn||co(Oe._readableStreamController,An);else{let bd;try{bd=wf(An)}catch(uu){bt(Oe._readableStreamController,uu),bt(ct._readableStreamController,uu),ge(Pt(o,uu));return}Sn||co(Oe._readableStreamController,An),ao(ct._readableStreamController,bd)}f=!1,b?fr():T&&Qe()})},_closeSteps:An=>{f=!1;let Sn=be?M:q,Fo=be?q:M;Sn||as(Oe._readableStreamController),Fo||as(ct._readableStreamController),An!==void 0&&(Sn||co(Oe._readableStreamController,An),!Fo&&ct._readableStreamController._pendingPullIntos.length>0&&uo(ct._readableStreamController,0)),(!Sn||!Fo)&&ge(void 0)},_errorSteps:()=>{f=!1}})}function fr(){if(f)return b=!0,h(void 0);f=!0;let se=za(re._readableStreamController);return se===null?wn():Fr(se._view,!1),h(void 0)}function Qe(){if(f)return T=!0,h(void 0);f=!0;let se=za(de._readableStreamController);return se===null?wn():Fr(se._view,!0),h(void 0)}function rt(se){if(q=!0,Y=se,M){let be=ke([Y,ce]),Oe=Pt(o,be);ge(Oe)}return ve}function Ct(se){if(M=!0,ce=se,q){let be=ke([Y,ce]),Oe=Pt(o,be);ge(Oe)}return ve}function dr(){}return re=od(dr,fr,rt),de=od(dr,Qe,Ct),It(a),[re,de]}function G0(o){return r(o)&&typeof o.getReader<"u"}function J0(o){return G0(o)?K0(o.getReader()):V0(o)}function V0(o){let a,f=Cf(o,"async"),b=e;function T(){let M;try{M=Ly(f)}catch(ce){return d(ce)}let Y=h(M);return _(Y,ce=>{if(!r(ce))throw new TypeError("The promise returned by the iterator.next() method must fulfill with an object");if(Uy(ce))Xr(a._readableStreamController);else{let de=My(ce);_n(a._readableStreamController,de)}})}function q(M){let Y=f.iterator,ce;try{ce=so(Y,"return")}catch(ge){return d(ge)}if(ce===void 0)return h(void 0);let re;try{re=D(ce,Y,[M])}catch(ge){return d(ge)}let de=h(re);return _(de,ge=>{if(!r(ge))throw new TypeError("The promise returned by the iterator.return() method must fulfill with an object")})}return a=hs(b,T,q,0),a}function K0(o){let a,f=e;function b(){let q;try{q=o.read()}catch(M){return d(M)}return _(q,M=>{if(!r(M))throw new TypeError("The promise returned by the reader.read() method must fulfill with an object");if(M.done)Xr(a._readableStreamController);else{let Y=M.value;_n(a._readableStreamController,Y)}})}function T(q){try{return h(o.cancel(q))}catch(M){return d(M)}}return a=hs(f,b,T,0),a}function Y0(o,a){le(o,a);let f=o,b=f?.autoAllocateChunkSize,T=f?.cancel,q=f?.pull,M=f?.start,Y=f?.type;return{autoAllocateChunkSize:b===void 0?void 0:F(b,`${a} has member 'autoAllocateChunkSize' that`),cancel:T===void 0?void 0:X0(T,f,`${a} has member 'cancel' that`),pull:q===void 0?void 0:Q0(q,f,`${a} has member 'pull' that`),start:M===void 0?void 0:Z0(M,f,`${a} has member 'start' that`),type:Y===void 0?void 0:e_(Y,`${a} has member 'type' that`)}}function X0(o,a,f){return _e(o,f),b=>C(o,a,[b])}function Q0(o,a,f){return _e(o,f),b=>C(o,a,[b])}function Z0(o,a,f){return _e(o,f),b=>D(o,a,[b])}function e_(o,a){if(o=`${o}`,o!=="bytes")throw new TypeError(`${a} '${o}' is not a valid enumeration value for ReadableStreamType`);return o}function t_(o,a){return le(o,a),{preventCancel:!!o?.preventCancel}}function sd(o,a){le(o,a);let f=o?.preventAbort,b=o?.preventCancel,T=o?.preventClose,q=o?.signal;return q!==void 0&&r_(q,`${a} has member 'signal' that`),{preventAbort:!!f,preventCancel:!!b,preventClose:!!T,signal:q}}function r_(o,a){if(!l0(o))throw new TypeError(`${a} is not an AbortSignal.`)}function n_(o,a){le(o,a);let f=o?.readable;g(f,"readable","ReadableWritablePair"),I(f,`${a} has member 'readable' that`);let b=o?.writable;return g(b,"writable","ReadableWritablePair"),Lf(b,`${a} has member 'writable' that`),{readable:f,writable:b}}class Ye{constructor(a={},f={}){a===void 0?a=null:Re(a,"First parameter");let b=ho(f,"Second parameter"),T=Y0(a,"First parameter");if(su(this),T.type==="bytes"){if(b.size!==void 0)throw new RangeError("The strategy for a byte stream cannot have a size function");let q=cs(b,0);Xy(this,T,q)}else{let q=fo(b),M=cs(b,1);$0(this,T,M,q)}}get locked(){if(!vr(this))throw Qr("locked");return Rr(this)}cancel(a=void 0){return vr(this)?Rr(this)?d(new TypeError("Cannot cancel a stream that already has a reader")):Pt(this,a):d(Qr("cancel"))}getReader(a=void 0){if(!vr(this))throw Qr("getReader");return Zy(a,"First parameter").mode===void 0?L(this):If(this)}pipeThrough(a,f={}){if(!vr(this))throw Qr("pipeThrough");Be(a,1,"pipeThrough");let b=n_(a,"First parameter"),T=sd(f,"Second parameter");if(Rr(this))throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream");if(gn(b.writable))throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream");let q=td(this,b.writable,T.preventClose,T.preventAbort,T.preventCancel,T.signal);return y(q),b.readable}pipeTo(a,f={}){if(!vr(this))return d(Qr("pipeTo"));if(a===void 0)return d("Parameter 1 is required in 'pipeTo'.");if(!mn(a))return d(new TypeError("ReadableStream.prototype.pipeTo's first argument must be a WritableStream"));let b;try{b=sd(f,"Second parameter")}catch(T){return d(T)}return Rr(this)?d(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream")):gn(a)?d(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream")):td(this,a,b.preventClose,b.preventAbort,b.preventCancel,b.signal)}tee(){if(!vr(this))throw Qr("tee");let a=z0(this);return ke(a)}values(a=void 0){if(!vr(this))throw Qr("values");let f=t_(a,"First parameter");return fn(this,f.preventCancel)}[Ba](a){return this.values(a)}static from(a){return J0(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,Ba,{value:Ye.prototype.values,writable:!0,configurable:!0});function hs(o,a,f,b=1,T=()=>1){let q=Object.create(Ye.prototype);su(q);let M=Object.create(lr.prototype);return nd(q,M,o,a,f,b,T),q}function od(o,a,f){let b=Object.create(Ye.prototype);su(b);let T=Object.create(ur.prototype);return Pf(b,T,o,a,f,0,void 0),b}function su(o){o._state="readable",o._reader=void 0,o._storedError=void 0,o._disturbed=!1}function vr(o){return!r(o)||!Object.prototype.hasOwnProperty.call(o,"_readableStreamController")?!1:o instanceof Ye}function Rr(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);ps(o);let f=o._reader;if(f!==void 0&&Vr(f)){let T=f._readIntoRequests;f._readIntoRequests=new v,T.forEach(q=>{q._closeSteps(void 0)})}let b=o._readableStreamController[V](a);return _(b,e)}function ps(o){o._state="closed";let a=o._reader;if(a!==void 0&&(ue(a),Z(a))){let f=a._readRequests;a._readRequests=new v,f.forEach(b=>{b._closeSteps()})}}function id(o,a){o._state="errored",o._storedError=a;let f=o._reader;f!==void 0&&(G(f,a),Z(f)?xe(f,a):qf(f,a))}function Qr(o){return new TypeError(`ReadableStream.prototype.${o} can only be used on a ReadableStream`)}function ad(o,a){le(o,a);let f=o?.highWaterMark;return g(f,"highWaterMark","QueuingStrategyInit"),{highWaterMark:w(f)}}let ud=o=>o.byteLength;s(ud,"size");class So{constructor(a){Be(a,1,"ByteLengthQueuingStrategy"),a=ad(a,"First parameter"),this._byteLengthQueuingStrategyHighWaterMark=a.highWaterMark}get highWaterMark(){if(!ld(this))throw cd("highWaterMark");return this._byteLengthQueuingStrategyHighWaterMark}get size(){if(!ld(this))throw cd("size");return ud}}Object.defineProperties(So.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(So.prototype,Symbol.toStringTag,{value:"ByteLengthQueuingStrategy",configurable:!0});function cd(o){return new TypeError(`ByteLengthQueuingStrategy.prototype.${o} can only be used on a ByteLengthQueuingStrategy`)}function ld(o){return!r(o)||!Object.prototype.hasOwnProperty.call(o,"_byteLengthQueuingStrategyHighWaterMark")?!1:o instanceof So}let fd=()=>1;s(fd,"size");class ko{constructor(a){Be(a,1,"CountQueuingStrategy"),a=ad(a,"First parameter"),this._countQueuingStrategyHighWaterMark=a.highWaterMark}get highWaterMark(){if(!hd(this))throw dd("highWaterMark");return this._countQueuingStrategyHighWaterMark}get size(){if(!hd(this))throw dd("size");return fd}}Object.defineProperties(ko.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(ko.prototype,Symbol.toStringTag,{value:"CountQueuingStrategy",configurable:!0});function dd(o){return new TypeError(`CountQueuingStrategy.prototype.${o} can only be used on a CountQueuingStrategy`)}function hd(o){return!r(o)||!Object.prototype.hasOwnProperty.call(o,"_countQueuingStrategyHighWaterMark")?!1:o instanceof ko}function s_(o,a){le(o,a);let f=o?.cancel,b=o?.flush,T=o?.readableType,q=o?.start,M=o?.transform,Y=o?.writableType;return{cancel:f===void 0?void 0:u_(f,o,`${a} has member 'cancel' that`),flush:b===void 0?void 0:o_(b,o,`${a} has member 'flush' that`),readableType:T,start:q===void 0?void 0:i_(q,o,`${a} has member 'start' that`),transform:M===void 0?void 0:a_(M,o,`${a} has member 'transform' that`),writableType:Y}}function o_(o,a,f){return _e(o,f),b=>C(o,a,[b])}function i_(o,a,f){return _e(o,f),b=>D(o,a,[b])}function a_(o,a,f){return _e(o,f),(b,T)=>C(o,a,[b,T])}function u_(o,a,f){return _e(o,f),b=>C(o,a,[b])}class Do{constructor(a={},f={},b={}){a===void 0&&(a=null);let T=ho(f,"Second parameter"),q=ho(b,"Third parameter"),M=s_(a,"First parameter");if(M.readableType!==void 0)throw new RangeError("Invalid readableType specified");if(M.writableType!==void 0)throw new RangeError("Invalid writableType specified");let Y=cs(q,0),ce=fo(q),re=cs(T,1),de=fo(T),ge,ve=l(It=>{ge=It});c_(this,ve,re,de,Y,ce),f_(this,M),M.start!==void 0?ge(M.start(this._transformStreamController)):ge(void 0)}get readable(){if(!pd(this))throw _d("readable");return this._readable}get writable(){if(!pd(this))throw _d("writable");return this._writable}}Object.defineProperties(Do.prototype,{readable:{enumerable:!0},writable:{enumerable:!0}}),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Do.prototype,Symbol.toStringTag,{value:"TransformStream",configurable:!0});function c_(o,a,f,b,T,q){function M(){return a}function Y(ve){return p_(o,ve)}function ce(ve){return m_(o,ve)}function re(){return g_(o)}o._writable=h0(M,Y,re,ce,f,b);function de(){return y_(o)}function ge(ve){return __(o,ve)}o._readable=hs(M,de,ge,T,q),o._backpressure=void 0,o._backpressureChangePromise=void 0,o._backpressureChangePromise_resolve=void 0,To(o,!0),o._transformStreamController=void 0}function pd(o){return!r(o)||!Object.prototype.hasOwnProperty.call(o,"_transformStreamController")?!1:o instanceof Do}function md(o,a){xt(o._readable._readableStreamController,a),ou(o,a)}function ou(o,a){Ro(o._transformStreamController),ls(o._writable._writableStreamController,a),iu(o)}function iu(o){o._backpressure&&To(o,!1)}function To(o,a){o._backpressureChangePromise!==void 0&&o._backpressureChangePromise_resolve(),o._backpressureChangePromise=l(f=>{o._backpressureChangePromise_resolve=f}),o._backpressure=a}class Or{constructor(){throw new TypeError("Illegal constructor")}get desiredSize(){if(!vo(this))throw Oo("desiredSize");let a=this._controlledTransformStream._readable._readableStreamController;return nu(a)}enqueue(a=void 0){if(!vo(this))throw Oo("enqueue");gd(this,a)}error(a=void 0){if(!vo(this))throw Oo("error");d_(this,a)}terminate(){if(!vo(this))throw Oo("terminate");h_(this)}}Object.defineProperties(Or.prototype,{enqueue:{enumerable:!0},error:{enumerable:!0},terminate:{enumerable:!0},desiredSize:{enumerable:!0}}),s(Or.prototype.enqueue,"enqueue"),s(Or.prototype.error,"error"),s(Or.prototype.terminate,"terminate"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Or.prototype,Symbol.toStringTag,{value:"TransformStreamDefaultController",configurable:!0});function vo(o){return!r(o)||!Object.prototype.hasOwnProperty.call(o,"_controlledTransformStream")?!1:o instanceof Or}function l_(o,a,f,b,T){a._controlledTransformStream=o,o._transformStreamController=a,a._transformAlgorithm=f,a._flushAlgorithm=b,a._cancelAlgorithm=T,a._finishPromise=void 0,a._finishPromise_resolve=void 0,a._finishPromise_reject=void 0}function f_(o,a){let f=Object.create(Or.prototype),b,T,q;a.transform!==void 0?b=M=>a.transform(M,f):b=M=>{try{return gd(f,M),h(void 0)}catch(Y){return d(Y)}},a.flush!==void 0?T=()=>a.flush(f):T=()=>h(void 0),a.cancel!==void 0?q=M=>a.cancel(M):q=()=>h(void 0),l_(o,f,b,T,q)}function Ro(o){o._transformAlgorithm=void 0,o._flushAlgorithm=void 0,o._cancelAlgorithm=void 0}function gd(o,a){let f=o._controlledTransformStream,b=f._readable._readableStreamController;if(!bn(b))throw new TypeError("Readable side is not in a state that permits enqueue");try{_n(b,a)}catch(q){throw ou(f,q),f._readable._storedError}M0(b)!==f._backpressure&&To(f,!0)}function d_(o,a){md(o._controlledTransformStream,a)}function yd(o,a){let f=o._transformAlgorithm(a);return _(f,void 0,b=>{throw md(o._controlledTransformStream,b),b})}function h_(o){let a=o._controlledTransformStream,f=a._readable._readableStreamController;Xr(f);let b=new TypeError("TransformStream terminated");ou(a,b)}function p_(o,a){let f=o._transformStreamController;if(o._backpressure){let b=o._backpressureChangePromise;return _(b,()=>{let T=o._writable;if(T._state==="erroring")throw T._storedError;return yd(f,a)})}return yd(f,a)}function m_(o,a){let f=o._transformStreamController;if(f._finishPromise!==void 0)return f._finishPromise;let b=o._readable;f._finishPromise=l((q,M)=>{f._finishPromise_resolve=q,f._finishPromise_reject=M});let T=f._cancelAlgorithm(a);return Ro(f),A(T,()=>(b._state==="errored"?Cn(f,b._storedError):(xt(b._readableStreamController,a),au(f)),null),q=>(xt(b._readableStreamController,q),Cn(f,q),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((T,q)=>{a._finishPromise_resolve=T,a._finishPromise_reject=q});let b=a._flushAlgorithm();return Ro(a),A(b,()=>(f._state==="errored"?Cn(a,f._storedError):(Xr(f._readableStreamController),au(a)),null),T=>(xt(f._readableStreamController,T),Cn(a,T),null)),a._finishPromise}function y_(o){return To(o,!1),o._backpressureChangePromise}function __(o,a){let f=o._transformStreamController;if(f._finishPromise!==void 0)return f._finishPromise;let b=o._writable;f._finishPromise=l((q,M)=>{f._finishPromise_resolve=q,f._finishPromise_reject=M});let T=f._cancelAlgorithm(a);return Ro(f),A(T,()=>(b._state==="errored"?Cn(f,b._storedError):(ls(b._writableStreamController,a),iu(o),au(f)),null),q=>(ls(b._writableStreamController,q),iu(o),Cn(f,q),null)),f._finishPromise}function Oo(o){return new TypeError(`TransformStreamDefaultController.prototype.${o} can only be used on a TransformStreamDefaultController`)}function au(o){o._finishPromise_resolve!==void 0&&(o._finishPromise_resolve(),o._finishPromise_resolve=void 0,o._finishPromise_reject=void 0)}function Cn(o,a){o._finishPromise_reject!==void 0&&(y(o._finishPromise),o._finishPromise_reject(a),o._finishPromise_resolve=void 0,o._finishPromise_reject=void 0)}function _d(o){return new TypeError(`TransformStream.prototype.${o} can only be used on a TransformStream`)}t.ByteLengthQueuingStrategy=So,t.CountQueuingStrategy=ko,t.ReadableByteStreamController=ur,t.ReadableStream=Ye,t.ReadableStreamBYOBReader=Dr,t.ReadableStreamBYOBRequest=Wr,t.ReadableStreamDefaultController=lr,t.ReadableStreamDefaultReader=z,t.TransformStream=Do,t.TransformStreamDefaultController=Or,t.WritableStream=Tr,t.WritableStreamDefaultController=yn,t.WritableStreamDefaultWriter=cr}))});var Nh=J(()=>{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,Ih())}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*Nu(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,Bh),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+Bh)).arrayBuffer();n+=u.byteLength,yield new Uint8Array(u)}}}var lv,Bh,jh,zb,Bt,bs=je(()=>{lv=xr(Nh(),1);Bh=65536;jh=class Bu{#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 Bu?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 Nu(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 Nu(this.#e,!1))e.set(n,r),r+=n.length;return e.buffer}stream(){let e=Nu(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 R=ArrayBuffer.isView(A)?A.byteLength:A.size;if(i&&R<=i)i-=R,u-=R;else{let S;ArrayBuffer.isView(A)?(S=A.subarray(i,Math.min(R,u)),d+=S.byteLength):(S=A.slice(i,Math.min(R,u)),d+=S.size),u-=R,h.push(S),i=0}}let p=new Bu([],{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(jh.prototype,{size:{enumerable:!0},type:{enumerable:!0},slice:{enumerable:!0}});zb=jh,Bt=zb});var Hb,Wb,Nr,ju=je(()=>{bs();Hb=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])}},Wb=Hb,Nr=Wb});function Uh(t,e=Bt){var r=`${qh()}${qh()}`.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
25
+ `;let l=(0,Mb.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",$b),r.secureEndpoint?(_s("Upgrading socket connection to TLS"),Dh.connect({...vh(Th(r),"host","path","port"),socket:s})):s;s.destroy();let p=new Yo.Socket({writable:!1});return p.readable=!0,e.once("socket",A=>{_s("Replaying proxy buffer for failed request"),(0,jb.default)(A.listenerCount("data")>0),A.push(d),A.push(null)}),p}};Xo.protocols=["http","https"];At.HttpsProxyAgent=Xo;function $b(t){t.resume()}function vh(t,...e){let r={},n;for(n in t)e.includes(n)||(r[n]=t[n]);return r}});function zb(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 xh,Ph=je(()=>{xh=zb});var Nh=J((Qo,Ih)=>{(function(t,e){typeof Qo=="object"&&typeof Ih<"u"?e(Qo):typeof define=="function"&&define.amd?define(["exports"],e):(t=typeof globalThis<"u"?globalThis:t||self,e(t.WebStreamsPolyfill={}))})(Qo,(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 R(o,a){A(o,a)}function S(o,a){A(o,void 0,a)}function _(o,a,f){return p(o,a,f)}function y(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 D(o,a,f){if(typeof o!="function")throw new TypeError("Argument is not a function");return Function.prototype.apply.call(o,a,f)}function C(o,a,f){try{return h(D(o,a,f))}catch(b){return d(b)}}let E=16384;class v{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,b=f;f._elements.length===E-1&&(b={_elements:[],_next:void 0}),f._elements.push(a),b!==f&&(this._back=b,f._next=b),++this._size}shift(){let a=this._front,f=a,b=this._cursor,T=b+1,q=a._elements,M=q[b];return T===E&&(f=a._next,T=0),--this._size,this._cursor=T,a!==f&&(this._front=f),q[b]=void 0,M}forEach(a){let f=this._cursor,b=this._front,T=b._elements;for(;(f!==T.length||b._next!==void 0)&&!(f===T.length&&(b=b._next,T=b._elements,f=0,T.length===0));)a(T[f]),++f}peek(){let a=this._front,f=this._cursor;return a._elements[f]}}let x=Symbol("[[AbortSteps]]"),$=Symbol("[[ErrorSteps]]"),V=Symbol("[[CancelSteps]]"),U=Symbol("[[PullSteps]]"),Q=Symbol("[[ReleaseSteps]]");function ne(o,a){o._ownerReadableStream=a,a._reader=o,a._state==="readable"?Ae(o):a._state==="closed"?pe(o):oe(o,a._storedError)}function ae(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[Q](),a._reader=void 0,o._ownerReadableStream=void 0}function ye(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 pe(o){Ae(o),ue(o)}function G(o,a){o._closedPromise_reject!==void 0&&(y(o._closedPromise),o._closedPromise_reject(a),o._closedPromise_resolve=void 0,o._closedPromise_reject=void 0)}function K(o,a){oe(o,a)}function ue(o){o._closedPromise_resolve!==void 0&&(o._closedPromise_resolve(void 0),o._closedPromise_resolve=void 0,o._closedPromise_reject=void 0)}let Me=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 Ft(o){return typeof o=="object"&&o!==null||typeof o=="function"}function Re(o,a){if(!Ft(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 g(o,a,f){if(o===void 0)throw new TypeError(`${a} is required in '${f}'.`)}function w(o){return Number(o)}function k(o){return o===0?0:o}function B(o){return k(Te(o))}function F(o,a){let b=Number.MAX_SAFE_INTEGER,T=Number(o);if(T=k(T),!Me(T))throw new TypeError(`${a} is not a finite number`);if(T=B(T),T<0||T>b)throw new TypeError(`${a} is outside the accepted range of 0 to ${b}, inclusive`);return!Me(T)||T===0?0:T}function I(o,a){if(!vr(o))throw new TypeError(`${a} is not a ReadableStream.`)}function L(o){return new z(o)}function O(o,a){o._reader._readRequests.push(a)}function P(o,a,f){let T=o._reader._readRequests.shift();f?T._closeSteps():T._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"),Rr(a))throw new TypeError("This stream has already been locked for exclusive reading by another reader");ne(this,a),this._readRequests=new v}get closed(){return Z(this)?this._closedPromise:d(Ne("closed"))}cancel(a=void 0){return Z(this)?this._ownerReadableStream===void 0?d(ye("cancel")):ae(this,a):d(Ne("cancel"))}read(){if(!Z(this))return d(Ne("read"));if(this._ownerReadableStream===void 0)return d(ye("read from"));let a,f,b=l((q,M)=>{a=q,f=M});return ee(this,{_chunkSteps:q=>a({value:q,done:!1}),_closeSteps:()=>a({value:void 0,done:!0}),_errorSteps:q=>f(q)}),b}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[U](a)}function Ee(o){fe(o);let a=new TypeError("Reader was released");xe(o,a)}function xe(o,a){let f=o._readRequests;o._readRequests=new v,f.forEach(b=>{b._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?_(this._ongoingPromise,a,a):a(),this._ongoingPromise}return(a){let f=()=>this._returnSteps(a);return this._ongoingPromise?_(this._ongoingPromise,f,f):f()}_nextSteps(){if(this._isFinished)return Promise.resolve({value:void 0,done:!0});let a=this._reader,f,b,T=l((M,Y)=>{f=M,b=Y});return ee(a,{_chunkSteps:M=>{this._ongoingPromise=void 0,m(()=>f({value:M,done:!1}))},_closeSteps:()=>{this._ongoingPromise=void 0,this._isFinished=!0,fe(a),f({value:void 0,done:!0})},_errorSteps:M=>{this._ongoingPromise=void 0,this._isFinished=!0,fe(a),b(M)}}),T}_returnSteps(a){if(this._isFinished)return Promise.resolve({value:a,done:!0});this._isFinished=!0;let f=this._reader;if(!this._preventCancel){let b=ae(f,a);return fe(f),_(b,()=>({value:a,done:!0}))}return fe(f),h({value:a,done:!0})}}let Le={next(){return dn(this)?this._asyncIteratorImpl.next():d(hn("next"))},return(o){return dn(this)?this._asyncIteratorImpl.return(o):d(hn("return"))}};Object.setPrototypeOf(Le,we);function fn(o,a){let f=L(o),b=new Se(f,a),T=Object.create(Le);return T._asyncIteratorImpl=b,T}function dn(o){if(!r(o)||!Object.prototype.hasOwnProperty.call(o,"_asyncIteratorImpl"))return!1;try{return o._asyncIteratorImpl instanceof Se}catch{return!1}}function hn(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 bf(o,a,f,b,T){new Uint8Array(o).set(new Uint8Array(f,b,T),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)),Sr=o=>(typeof o.detached=="boolean"?Sr=a=>a.detached:Sr=a=>a.byteLength===0,Sr(o));function Cf(o,a,f){if(o.slice)return o.slice(a,f);let b=f-a,T=new ArrayBuffer(b);return bf(T,0,o,a,b),T}function so(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 Ly(o){let a={[Symbol.iterator]:()=>o.iterator},f=(async function*(){return yield*a})(),b=f.next;return{iterator:f,nextMethod:b,done:!1}}let ja=(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 wf(o,a="sync",f){if(f===void 0)if(a==="async"){if(f=so(o,ja),f===void 0){let q=so(o,Symbol.iterator),M=wf(o,"sync",q);return Ly(M)}}else f=so(o,Symbol.iterator);if(f===void 0)throw new TypeError("The object is not iterable");let b=D(f,o,[]);if(!r(b))throw new TypeError("The iterator method must return an object");let T=b.next;return{iterator:b,nextMethod:T,done:!1}}function Uy(o){let a=D(o.nextMethod,o.iterator,[]);if(!r(a))throw new TypeError("The iterator.next() method must return an object");return a}function My(o){return!!o.done}function $y(o){return o.value}function zy(o){return!(typeof o!="number"||ut(o)||o<0)}function Ef(o){let a=Cf(o.buffer,o.byteOffset,o.byteOffset+o.byteLength);return new Uint8Array(a)}function qa(o){let a=o._queue.shift();return o._queueTotalSize-=a.size,o._queueTotalSize<0&&(o._queueTotalSize=0),a.value}function La(o,a,f){if(!zy(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 Hy(o){return o._queue.peek().value}function kr(o){o._queue=new v,o._queueTotalSize=0}function Af(o){return o===DataView}function Wy(o){return Af(o.constructor)}function Gy(o){return Af(o)?1:o.BYTES_PER_ELEMENT}class Wr{constructor(){throw new TypeError("Illegal constructor")}get view(){if(!Ua(this))throw Wa("view");return this._view}respond(a){if(!Ua(this))throw Wa("respond");if(Be(a,1,"respond"),a=F(a,"First parameter"),this._associatedReadableByteStreamController===void 0)throw new TypeError("This BYOB request has been invalidated");if(Sr(this._view.buffer))throw new TypeError("The BYOB request's buffer has been detached and so cannot be used as a response");uo(this._associatedReadableByteStreamController,a)}respondWithNewView(a){if(!Ua(this))throw Wa("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(Sr(a.buffer))throw new TypeError("The given view's buffer has been detached and so cannot be used as a response");co(this._associatedReadableByteStreamController,a)}}Object.defineProperties(Wr.prototype,{respond:{enumerable:!0},respondWithNewView:{enumerable:!0},view:{enumerable:!0}}),s(Wr.prototype.respond,"respond"),s(Wr.prototype.respondWithNewView,"respondWithNewView"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Wr.prototype,Symbol.toStringTag,{value:"ReadableStreamBYOBRequest",configurable:!0});class ur{constructor(){throw new TypeError("Illegal constructor")}get byobRequest(){if(!Gr(this))throw us("byobRequest");return Ha(this)}get desiredSize(){if(!Gr(this))throw us("desiredSize");return Pf(this)}close(){if(!Gr(this))throw us("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`);as(this)}enqueue(a){if(!Gr(this))throw us("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`);ao(this,a)}error(a=void 0){if(!Gr(this))throw us("error");bt(this,a)}[V](a){Sf(this),kr(this);let f=this._cancelAlgorithm(a);return io(this),f}[U](a){let f=this._controlledReadableByteStream;if(this._queueTotalSize>0){xf(this,a);return}let b=this._autoAllocateChunkSize;if(b!==void 0){let T;try{T=new ArrayBuffer(b)}catch(M){a._errorSteps(M);return}let q={buffer:T,bufferByteLength:b,byteOffset:0,byteLength:b,bytesFilled:0,minimumFill:1,elementSize:1,viewConstructor:Uint8Array,readerType:"default"};this._pendingPullIntos.push(q)}O(f,a),Jr(this)}[Q](){if(this._pendingPullIntos.length>0){let a=this._pendingPullIntos.peek();a.readerType="none",this._pendingPullIntos=new v,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 Gr(o){return!r(o)||!Object.prototype.hasOwnProperty.call(o,"_controlledReadableByteStream")?!1:o instanceof ur}function Ua(o){return!r(o)||!Object.prototype.hasOwnProperty.call(o,"_associatedReadableByteStreamController")?!1:o instanceof Wr}function Jr(o){if(!Xy(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,Jr(o)),null),b=>(bt(o,b),null))}function Sf(o){$a(o),o._pendingPullIntos=new v}function Ma(o,a){let f=!1;o._state==="closed"&&(f=!0);let b=kf(a);a.readerType==="default"?P(o,b,f):n0(o,b,f)}function kf(o){let a=o.bytesFilled,f=o.elementSize;return new o.viewConstructor(o.buffer,o.byteOffset,a/f)}function oo(o,a,f,b){o._queue.push({buffer:a,byteOffset:f,byteLength:b}),o._queueTotalSize+=b}function Df(o,a,f,b){let T;try{T=Cf(a,f,f+b)}catch(q){throw bt(o,q),q}oo(o,T,0,b)}function Tf(o,a){a.bytesFilled>0&&Df(o,a.buffer,a.byteOffset,a.bytesFilled),pn(o)}function vf(o,a){let f=Math.min(o._queueTotalSize,a.byteLength-a.bytesFilled),b=a.bytesFilled+f,T=f,q=!1,M=b%a.elementSize,Y=b-M;Y>=a.minimumFill&&(T=Y-a.bytesFilled,q=!0);let ce=o._queue;for(;T>0;){let re=ce.peek(),de=Math.min(T,re.byteLength),ge=a.byteOffset+a.bytesFilled;bf(a.buffer,ge,re.buffer,re.byteOffset,de),re.byteLength===de?ce.shift():(re.byteOffset+=de,re.byteLength-=de),o._queueTotalSize-=de,Rf(o,de,a),T-=de}return q}function Rf(o,a,f){f.bytesFilled+=a}function Of(o){o._queueTotalSize===0&&o._closeRequested?(io(o),ps(o._controlledReadableByteStream)):Jr(o)}function $a(o){o._byobRequest!==null&&(o._byobRequest._associatedReadableByteStreamController=void 0,o._byobRequest._view=null,o._byobRequest=null)}function za(o){for(;o._pendingPullIntos.length>0;){if(o._queueTotalSize===0)return;let a=o._pendingPullIntos.peek();vf(o,a)&&(pn(o),Ma(o._controlledReadableByteStream,a))}}function Jy(o){let a=o._controlledReadableByteStream._reader;for(;a._readRequests.length>0;){if(o._queueTotalSize===0)return;let f=a._readRequests.shift();xf(o,f)}}function Vy(o,a,f,b){let T=o._controlledReadableByteStream,q=a.constructor,M=Gy(q),{byteOffset:Y,byteLength:ce}=a,re=f*M,de;try{de=ar(a.buffer)}catch(ve){b._errorSteps(ve);return}let ge={buffer:de,bufferByteLength:de.byteLength,byteOffset:Y,byteLength:ce,bytesFilled:0,minimumFill:re,elementSize:M,viewConstructor:q,readerType:"byob"};if(o._pendingPullIntos.length>0){o._pendingPullIntos.push(ge),Bf(T,b);return}if(T._state==="closed"){let ve=new q(ge.buffer,ge.byteOffset,0);b._closeSteps(ve);return}if(o._queueTotalSize>0){if(vf(o,ge)){let ve=kf(ge);Of(o),b._chunkSteps(ve);return}if(o._closeRequested){let ve=new TypeError("Insufficient bytes to fill elements in the given buffer");bt(o,ve),b._errorSteps(ve);return}}o._pendingPullIntos.push(ge),Bf(T,b),Jr(o)}function Ky(o,a){a.readerType==="none"&&pn(o);let f=o._controlledReadableByteStream;if(Ga(f))for(;jf(f)>0;){let b=pn(o);Ma(f,b)}}function Yy(o,a,f){if(Rf(o,a,f),f.readerType==="none"){Tf(o,f),za(o);return}if(f.bytesFilled<f.minimumFill)return;pn(o);let b=f.bytesFilled%f.elementSize;if(b>0){let T=f.byteOffset+f.bytesFilled;Df(o,f.buffer,T-b,b)}f.bytesFilled-=b,Ma(o._controlledReadableByteStream,f),za(o)}function Ff(o,a){let f=o._pendingPullIntos.peek();$a(o),o._controlledReadableByteStream._state==="closed"?Ky(o,f):Yy(o,a,f),Jr(o)}function pn(o){return o._pendingPullIntos.shift()}function Xy(o){let a=o._controlledReadableByteStream;return a._state!=="readable"||o._closeRequested||!o._started?!1:!!(N(a)&&j(a)>0||Ga(a)&&jf(a)>0||Pf(o)>0)}function io(o){o._pullAlgorithm=void 0,o._cancelAlgorithm=void 0}function as(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 b=new TypeError("Insufficient bytes to fill elements in the given buffer");throw bt(o,b),b}}io(o),ps(a)}}function ao(o,a){let f=o._controlledReadableByteStream;if(o._closeRequested||f._state!=="readable")return;let{buffer:b,byteOffset:T,byteLength:q}=a;if(Sr(b))throw new TypeError("chunk's buffer is detached and so cannot be enqueued");let M=ar(b);if(o._pendingPullIntos.length>0){let Y=o._pendingPullIntos.peek();if(Sr(Y.buffer))throw new TypeError("The BYOB request's buffer has been detached and so cannot be filled with an enqueued chunk");$a(o),Y.buffer=ar(Y.buffer),Y.readerType==="none"&&Tf(o,Y)}if(N(f))if(Jy(o),j(f)===0)oo(o,M,T,q);else{o._pendingPullIntos.length>0&&pn(o);let Y=new Uint8Array(M,T,q);P(f,Y,!1)}else Ga(f)?(oo(o,M,T,q),za(o)):oo(o,M,T,q);Jr(o)}function bt(o,a){let f=o._controlledReadableByteStream;f._state==="readable"&&(Sf(o),kr(o),io(o),ad(f,a))}function xf(o,a){let f=o._queue.shift();o._queueTotalSize-=f.byteLength,Of(o);let b=new Uint8Array(f.buffer,f.byteOffset,f.byteLength);a._chunkSteps(b)}function Ha(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),b=Object.create(Wr.prototype);Zy(b,o,f),o._byobRequest=b}return o._byobRequest}function Pf(o){let a=o._controlledReadableByteStream._state;return a==="errored"?null:a==="closed"?0:o._strategyHWM-o._queueTotalSize}function uo(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),Ff(o,a)}function co(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 T=a.byteLength;f.buffer=ar(a.buffer),Ff(o,T)}function If(o,a,f,b,T,q,M){a._controlledReadableByteStream=o,a._pullAgain=!1,a._pulling=!1,a._byobRequest=null,a._queue=a._queueTotalSize=void 0,kr(a),a._closeRequested=!1,a._started=!1,a._strategyHWM=q,a._pullAlgorithm=b,a._cancelAlgorithm=T,a._autoAllocateChunkSize=M,a._pendingPullIntos=new v,o._readableStreamController=a;let Y=f();A(h(Y),()=>(a._started=!0,Jr(a),null),ce=>(bt(a,ce),null))}function Qy(o,a,f){let b=Object.create(ur.prototype),T,q,M;a.start!==void 0?T=()=>a.start(b):T=()=>{},a.pull!==void 0?q=()=>a.pull(b):q=()=>h(void 0),a.cancel!==void 0?M=ce=>a.cancel(ce):M=()=>h(void 0);let Y=a.autoAllocateChunkSize;if(Y===0)throw new TypeError("autoAllocateChunkSize must be greater than 0");If(o,b,T,q,M,f,Y)}function Zy(o,a,f){o._associatedReadableByteStreamController=a,o._view=f}function Wa(o){return new TypeError(`ReadableStreamBYOBRequest.prototype.${o} can only be used on a ReadableStreamBYOBRequest`)}function us(o){return new TypeError(`ReadableByteStreamController.prototype.${o} can only be used on a ReadableByteStreamController`)}function e0(o,a){le(o,a);let f=o?.mode;return{mode:f===void 0?void 0:t0(f,`${a} has member 'mode' that`)}}function t0(o,a){if(o=`${o}`,o!=="byob")throw new TypeError(`${a} '${o}' is not a valid enumeration value for ReadableStreamReaderMode`);return o}function r0(o,a){var f;le(o,a);let b=(f=o?.min)!==null&&f!==void 0?f:1;return{min:F(b,`${a} has member 'min' that`)}}function Nf(o){return new Dr(o)}function Bf(o,a){o._reader._readIntoRequests.push(a)}function n0(o,a,f){let T=o._reader._readIntoRequests.shift();f?T._closeSteps(a):T._chunkSteps(a)}function jf(o){return o._reader._readIntoRequests.length}function Ga(o){let a=o._reader;return!(a===void 0||!Vr(a))}class Dr{constructor(a){if(Be(a,1,"ReadableStreamBYOBReader"),I(a,"First parameter"),Rr(a))throw new TypeError("This stream has already been locked for exclusive reading by another reader");if(!Gr(a._readableStreamController))throw new TypeError("Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte source");ne(this,a),this._readIntoRequests=new v}get closed(){return Vr(this)?this._closedPromise:d(lo("closed"))}cancel(a=void 0){return Vr(this)?this._ownerReadableStream===void 0?d(ye("cancel")):ae(this,a):d(lo("cancel"))}read(a,f={}){if(!Vr(this))return d(lo("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(Sr(a.buffer))return d(new TypeError("view's buffer has been detached"));let b;try{b=r0(f,"options")}catch(re){return d(re)}let T=b.min;if(T===0)return d(new TypeError("options.min must be greater than 0"));if(Wy(a)){if(T>a.byteLength)return d(new RangeError("options.min must be less than or equal to view's byteLength"))}else if(T>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(ye("read from"));let q,M,Y=l((re,de)=>{q=re,M=de});return qf(this,a,T,{_chunkSteps:re=>q({value:re,done:!1}),_closeSteps:re=>q({value:re,done:!0}),_errorSteps:re=>M(re)}),Y}releaseLock(){if(!Vr(this))throw lo("releaseLock");this._ownerReadableStream!==void 0&&s0(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 Vr(o){return!r(o)||!Object.prototype.hasOwnProperty.call(o,"_readIntoRequests")?!1:o instanceof Dr}function qf(o,a,f,b){let T=o._ownerReadableStream;T._disturbed=!0,T._state==="errored"?b._errorSteps(T._storedError):Vy(T._readableStreamController,a,f,b)}function s0(o){fe(o);let a=new TypeError("Reader was released");Lf(o,a)}function Lf(o,a){let f=o._readIntoRequests;o._readIntoRequests=new v,f.forEach(b=>{b._errorSteps(a)})}function lo(o){return new TypeError(`ReadableStreamBYOBReader.prototype.${o} can only be used on a ReadableStreamBYOBReader`)}function cs(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 fo(o){let{size:a}=o;return a||(()=>1)}function ho(o,a){le(o,a);let f=o?.highWaterMark,b=o?.size;return{highWaterMark:f===void 0?void 0:w(f),size:b===void 0?void 0:o0(b,`${a} has member 'size' that`)}}function o0(o,a){return _e(o,a),f=>w(o(f))}function i0(o,a){le(o,a);let f=o?.abort,b=o?.close,T=o?.start,q=o?.type,M=o?.write;return{abort:f===void 0?void 0:a0(f,o,`${a} has member 'abort' that`),close:b===void 0?void 0:u0(b,o,`${a} has member 'close' that`),start:T===void 0?void 0:c0(T,o,`${a} has member 'start' that`),write:M===void 0?void 0:l0(M,o,`${a} has member 'write' that`),type:q}}function a0(o,a,f){return _e(o,f),b=>C(o,a,[b])}function u0(o,a,f){return _e(o,f),()=>C(o,a,[])}function c0(o,a,f){return _e(o,f),b=>D(o,a,[b])}function l0(o,a,f){return _e(o,f),(b,T)=>C(o,a,[b,T])}function Uf(o,a){if(!mn(o))throw new TypeError(`${a} is not a WritableStream.`)}function f0(o){if(typeof o!="object"||o===null)return!1;try{return typeof o.aborted=="boolean"}catch{return!1}}let d0=typeof AbortController=="function";function h0(){if(d0)return new AbortController}class Tr{constructor(a={},f={}){a===void 0?a=null:Re(a,"First parameter");let b=ho(f,"Second parameter"),T=i0(a,"First parameter");if($f(this),T.type!==void 0)throw new RangeError("Invalid type is specified");let M=fo(b),Y=cs(b,1);T0(this,T,Y,M)}get locked(){if(!mn(this))throw _o("locked");return gn(this)}abort(a=void 0){return mn(this)?gn(this)?d(new TypeError("Cannot abort a stream that already has a writer")):po(this,a):d(_o("abort"))}close(){return mn(this)?gn(this)?d(new TypeError("Cannot close a stream that already has a writer")):Wt(this)?d(new TypeError("Cannot close an already-closing stream")):zf(this):d(_o("close"))}getWriter(){if(!mn(this))throw _o("getWriter");return Mf(this)}}Object.defineProperties(Tr.prototype,{abort:{enumerable:!0},close:{enumerable:!0},getWriter:{enumerable:!0},locked:{enumerable:!0}}),s(Tr.prototype.abort,"abort"),s(Tr.prototype.close,"close"),s(Tr.prototype.getWriter,"getWriter"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Tr.prototype,Symbol.toStringTag,{value:"WritableStream",configurable:!0});function Mf(o){return new cr(o)}function p0(o,a,f,b,T=1,q=()=>1){let M=Object.create(Tr.prototype);$f(M);let Y=Object.create(yn.prototype);return Kf(M,Y,o,a,f,b,T,q),M}function $f(o){o._state="writable",o._storedError=void 0,o._writer=void 0,o._writableStreamController=void 0,o._writeRequests=new v,o._inFlightWriteRequest=void 0,o._closeRequest=void 0,o._inFlightCloseRequest=void 0,o._pendingAbortRequest=void 0,o._backpressure=!1}function mn(o){return!r(o)||!Object.prototype.hasOwnProperty.call(o,"_writableStreamController")?!1:o instanceof Tr}function gn(o){return o._writer!==void 0}function po(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 b=o._state;if(b==="closed"||b==="errored")return h(void 0);if(o._pendingAbortRequest!==void 0)return o._pendingAbortRequest._promise;let T=!1;b==="erroring"&&(T=!0,a=void 0);let q=l((M,Y)=>{o._pendingAbortRequest={_promise:void 0,_resolve:M,_reject:Y,_reason:a,_wasAlreadyErroring:T}});return o._pendingAbortRequest._promise=q,T||Va(o,a),q}function zf(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((T,q)=>{let M={_resolve:T,_reject:q};o._closeRequest=M}),b=o._writer;return b!==void 0&&o._backpressure&&a==="writable"&&ru(b),v0(o._writableStreamController),f}function m0(o){return l((f,b)=>{let T={_resolve:f,_reject:b};o._writeRequests.push(T)})}function Ja(o,a){if(o._state==="writable"){Va(o,a);return}Ka(o)}function Va(o,a){let f=o._writableStreamController;o._state="erroring",o._storedError=a;let b=o._writer;b!==void 0&&Wf(b,a),!C0(o)&&f._started&&Ka(o)}function Ka(o){o._state="errored",o._writableStreamController[$]();let a=o._storedError;if(o._writeRequests.forEach(T=>{T._reject(a)}),o._writeRequests=new v,o._pendingAbortRequest===void 0){mo(o);return}let f=o._pendingAbortRequest;if(o._pendingAbortRequest=void 0,f._wasAlreadyErroring){f._reject(a),mo(o);return}let b=o._writableStreamController[x](f._reason);A(b,()=>(f._resolve(),mo(o),null),T=>(f._reject(T),mo(o),null))}function g0(o){o._inFlightWriteRequest._resolve(void 0),o._inFlightWriteRequest=void 0}function y0(o,a){o._inFlightWriteRequest._reject(a),o._inFlightWriteRequest=void 0,Ja(o,a)}function _0(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&&Zf(f)}function b0(o,a){o._inFlightCloseRequest._reject(a),o._inFlightCloseRequest=void 0,o._pendingAbortRequest!==void 0&&(o._pendingAbortRequest._reject(a),o._pendingAbortRequest=void 0),Ja(o,a)}function Wt(o){return!(o._closeRequest===void 0&&o._inFlightCloseRequest===void 0)}function C0(o){return!(o._inFlightWriteRequest===void 0&&o._inFlightCloseRequest===void 0)}function w0(o){o._inFlightCloseRequest=o._closeRequest,o._closeRequest=void 0}function E0(o){o._inFlightWriteRequest=o._writeRequests.shift()}function mo(o){o._closeRequest!==void 0&&(o._closeRequest._reject(o._storedError),o._closeRequest=void 0);let a=o._writer;a!==void 0&&eu(a,o._storedError)}function Ya(o,a){let f=o._writer;f!==void 0&&a!==o._backpressure&&(a?N0(f):ru(f)),o._backpressure=a}class cr{constructor(a){if(Be(a,1,"WritableStreamDefaultWriter"),Uf(a,"First parameter"),gn(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?Co(this):ed(this),bo(this);else if(f==="erroring")tu(this,a._storedError),bo(this);else if(f==="closed")ed(this),P0(this);else{let b=a._storedError;tu(this,b),Qf(this,b)}}get closed(){return Kr(this)?this._closedPromise:d(Yr("closed"))}get desiredSize(){if(!Kr(this))throw Yr("desiredSize");if(this._ownerWritableStream===void 0)throw fs("desiredSize");return D0(this)}get ready(){return Kr(this)?this._readyPromise:d(Yr("ready"))}abort(a=void 0){return Kr(this)?this._ownerWritableStream===void 0?d(fs("abort")):A0(this,a):d(Yr("abort"))}close(){if(!Kr(this))return d(Yr("close"));let a=this._ownerWritableStream;return a===void 0?d(fs("close")):Wt(a)?d(new TypeError("Cannot close an already-closing stream")):Hf(this)}releaseLock(){if(!Kr(this))throw Yr("releaseLock");this._ownerWritableStream!==void 0&&Gf(this)}write(a=void 0){return Kr(this)?this._ownerWritableStream===void 0?d(fs("write to")):Jf(this,a):d(Yr("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 Kr(o){return!r(o)||!Object.prototype.hasOwnProperty.call(o,"_ownerWritableStream")?!1:o instanceof cr}function A0(o,a){let f=o._ownerWritableStream;return po(f,a)}function Hf(o){let a=o._ownerWritableStream;return zf(a)}function S0(o){let a=o._ownerWritableStream,f=a._state;return Wt(a)||f==="closed"?h(void 0):f==="errored"?d(a._storedError):Hf(o)}function k0(o,a){o._closedPromiseState==="pending"?eu(o,a):I0(o,a)}function Wf(o,a){o._readyPromiseState==="pending"?td(o,a):B0(o,a)}function D0(o){let a=o._ownerWritableStream,f=a._state;return f==="errored"||f==="erroring"?null:f==="closed"?0:Yf(a._writableStreamController)}function Gf(o){let a=o._ownerWritableStream,f=new TypeError("Writer was released and can no longer be used to monitor the stream's closedness");Wf(o,f),k0(o,f),a._writer=void 0,o._ownerWritableStream=void 0}function Jf(o,a){let f=o._ownerWritableStream,b=f._writableStreamController,T=R0(b,a);if(f!==o._ownerWritableStream)return d(fs("write to"));let q=f._state;if(q==="errored")return d(f._storedError);if(Wt(f)||q==="closed")return d(new TypeError("The stream is closing or closed and cannot be written to"));if(q==="erroring")return d(f._storedError);let M=m0(f);return O0(b,a,T),M}let Vf={};class yn{constructor(){throw new TypeError("Illegal constructor")}get abortReason(){if(!Xa(this))throw Za("abortReason");return this._abortReason}get signal(){if(!Xa(this))throw Za("signal");if(this._abortController===void 0)throw new TypeError("WritableStreamDefaultController.prototype.signal is not supported");return this._abortController.signal}error(a=void 0){if(!Xa(this))throw Za("error");this._controlledWritableStream._state==="writable"&&Xf(this,a)}[x](a){let f=this._abortAlgorithm(a);return go(this),f}[$](){kr(this)}}Object.defineProperties(yn.prototype,{abortReason:{enumerable:!0},signal:{enumerable:!0},error:{enumerable:!0}}),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(yn.prototype,Symbol.toStringTag,{value:"WritableStreamDefaultController",configurable:!0});function Xa(o){return!r(o)||!Object.prototype.hasOwnProperty.call(o,"_controlledWritableStream")?!1:o instanceof yn}function Kf(o,a,f,b,T,q,M,Y){a._controlledWritableStream=o,o._writableStreamController=a,a._queue=void 0,a._queueTotalSize=void 0,kr(a),a._abortReason=void 0,a._abortController=h0(),a._started=!1,a._strategySizeAlgorithm=Y,a._strategyHWM=M,a._writeAlgorithm=b,a._closeAlgorithm=T,a._abortAlgorithm=q;let ce=Qa(a);Ya(o,ce);let re=f(),de=h(re);A(de,()=>(a._started=!0,yo(a),null),ge=>(a._started=!0,Ja(o,ge),null))}function T0(o,a,f,b){let T=Object.create(yn.prototype),q,M,Y,ce;a.start!==void 0?q=()=>a.start(T):q=()=>{},a.write!==void 0?M=re=>a.write(re,T):M=()=>h(void 0),a.close!==void 0?Y=()=>a.close():Y=()=>h(void 0),a.abort!==void 0?ce=re=>a.abort(re):ce=()=>h(void 0),Kf(o,T,q,M,Y,ce,f,b)}function go(o){o._writeAlgorithm=void 0,o._closeAlgorithm=void 0,o._abortAlgorithm=void 0,o._strategySizeAlgorithm=void 0}function v0(o){La(o,Vf,0),yo(o)}function R0(o,a){try{return o._strategySizeAlgorithm(a)}catch(f){return ls(o,f),1}}function Yf(o){return o._strategyHWM-o._queueTotalSize}function O0(o,a,f){try{La(o,a,f)}catch(T){ls(o,T);return}let b=o._controlledWritableStream;if(!Wt(b)&&b._state==="writable"){let T=Qa(o);Ya(b,T)}yo(o)}function yo(o){let a=o._controlledWritableStream;if(!o._started||a._inFlightWriteRequest!==void 0)return;if(a._state==="erroring"){Ka(a);return}if(o._queue.length===0)return;let b=Hy(o);b===Vf?F0(o):x0(o,b)}function ls(o,a){o._controlledWritableStream._state==="writable"&&Xf(o,a)}function F0(o){let a=o._controlledWritableStream;w0(a),qa(o);let f=o._closeAlgorithm();go(o),A(f,()=>(_0(a),null),b=>(b0(a,b),null))}function x0(o,a){let f=o._controlledWritableStream;E0(f);let b=o._writeAlgorithm(a);A(b,()=>{g0(f);let T=f._state;if(qa(o),!Wt(f)&&T==="writable"){let q=Qa(o);Ya(f,q)}return yo(o),null},T=>(f._state==="writable"&&go(o),y0(f,T),null))}function Qa(o){return Yf(o)<=0}function Xf(o,a){let f=o._controlledWritableStream;go(o),Va(f,a)}function _o(o){return new TypeError(`WritableStream.prototype.${o} can only be used on a WritableStream`)}function Za(o){return new TypeError(`WritableStreamDefaultController.prototype.${o} can only be used on a WritableStreamDefaultController`)}function Yr(o){return new TypeError(`WritableStreamDefaultWriter.prototype.${o} can only be used on a WritableStreamDefaultWriter`)}function fs(o){return new TypeError("Cannot "+o+" a stream using a released writer")}function bo(o){o._closedPromise=l((a,f)=>{o._closedPromise_resolve=a,o._closedPromise_reject=f,o._closedPromiseState="pending"})}function Qf(o,a){bo(o),eu(o,a)}function P0(o){bo(o),Zf(o)}function eu(o,a){o._closedPromise_reject!==void 0&&(y(o._closedPromise),o._closedPromise_reject(a),o._closedPromise_resolve=void 0,o._closedPromise_reject=void 0,o._closedPromiseState="rejected")}function I0(o,a){Qf(o,a)}function Zf(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 Co(o){o._readyPromise=l((a,f)=>{o._readyPromise_resolve=a,o._readyPromise_reject=f}),o._readyPromiseState="pending"}function tu(o,a){Co(o),td(o,a)}function ed(o){Co(o),ru(o)}function td(o,a){o._readyPromise_reject!==void 0&&(y(o._readyPromise),o._readyPromise_reject(a),o._readyPromise_resolve=void 0,o._readyPromise_reject=void 0,o._readyPromiseState="rejected")}function N0(o){Co(o)}function B0(o,a){tu(o,a)}function ru(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 j0(){if(typeof globalThis<"u")return globalThis;if(typeof self<"u")return self;if(typeof global<"u")return global}let nu=j0();function q0(o){if(!(typeof o=="function"||typeof o=="object")||o.name!=="DOMException")return!1;try{return new o,!0}catch{return!1}}function L0(){let o=nu?.DOMException;return q0(o)?o:void 0}function U0(){let o=function(f,b){this.message=f||"",this.name=b||"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 M0=L0()||U0();function rd(o,a,f,b,T,q){let M=L(o),Y=Mf(a);o._disturbed=!0;let ce=!1,re=h(void 0);return l((de,ge)=>{let ve;if(q!==void 0){if(ve=()=>{let se=q.reason!==void 0?q.reason:new M0("Aborted","AbortError"),be=[];b||be.push(()=>a._state==="writable"?po(a,se):h(void 0)),T||be.push(()=>o._state==="readable"?Pt(o,se):h(void 0)),rt(()=>Promise.all(be.map(Oe=>Oe())),!0,se)},q.aborted){ve();return}q.addEventListener("abort",ve)}function It(){return l((se,be)=>{function Oe(ct){ct?se():p(wn(),Oe,be)}Oe(!1)})}function wn(){return ce?h(!0):p(Y._readyPromise,()=>l((se,be)=>{ee(M,{_chunkSteps:Oe=>{re=p(Jf(Y,Oe),void 0,e),se(!1)},_closeSteps:()=>se(!0),_errorSteps:be})}))}if(fr(o,M._closedPromise,se=>(b?Ct(!0,se):rt(()=>po(a,se),!0,se),null)),fr(a,Y._closedPromise,se=>(T?Ct(!0,se):rt(()=>Pt(o,se),!0,se),null)),Qe(o,M._closedPromise,()=>(f?Ct():rt(()=>S0(Y)),null)),Wt(a)||a._state==="closed"){let se=new TypeError("the destination writable stream closed before all data could be piped to it");T?Ct(!0,se):rt(()=>Pt(o,se),!0,se)}y(It());function Fr(){let se=re;return p(re,()=>se!==re?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():R(be,Oe)}function rt(se,be,Oe){if(ce)return;ce=!0,a._state==="writable"&&!Wt(a)?R(Fr(),ct):ct();function ct(){return A(se(),()=>dr(be,Oe),En=>dr(!0,En)),null}}function Ct(se,be){ce||(ce=!0,a._state==="writable"&&!Wt(a)?R(Fr(),()=>dr(se,be)):dr(se,be))}function dr(se,be){return Gf(Y),fe(M),q!==void 0&&q.removeEventListener("abort",ve),se?ge(be):de(void 0),null}})}class lr{constructor(){throw new TypeError("Illegal constructor")}get desiredSize(){if(!wo(this))throw Ao("desiredSize");return su(this)}close(){if(!wo(this))throw Ao("close");if(!bn(this))throw new TypeError("The stream is not in a state that permits close");Xr(this)}enqueue(a=void 0){if(!wo(this))throw Ao("enqueue");if(!bn(this))throw new TypeError("The stream is not in a state that permits enqueue");return _n(this,a)}error(a=void 0){if(!wo(this))throw Ao("error");xt(this,a)}[V](a){kr(this);let f=this._cancelAlgorithm(a);return Eo(this),f}[U](a){let f=this._controlledReadableStream;if(this._queue.length>0){let b=qa(this);this._closeRequested&&this._queue.length===0?(Eo(this),ps(f)):ds(this),a._chunkSteps(b)}else O(f,a),ds(this)}[Q](){}}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 wo(o){return!r(o)||!Object.prototype.hasOwnProperty.call(o,"_controlledReadableStream")?!1:o instanceof lr}function ds(o){if(!nd(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,ds(o)),null),b=>(xt(o,b),null))}function nd(o){let a=o._controlledReadableStream;return!bn(o)||!o._started?!1:!!(Rr(a)&&j(a)>0||su(o)>0)}function Eo(o){o._pullAlgorithm=void 0,o._cancelAlgorithm=void 0,o._strategySizeAlgorithm=void 0}function Xr(o){if(!bn(o))return;let a=o._controlledReadableStream;o._closeRequested=!0,o._queue.length===0&&(Eo(o),ps(a))}function _n(o,a){if(!bn(o))return;let f=o._controlledReadableStream;if(Rr(f)&&j(f)>0)P(f,a,!1);else{let b;try{b=o._strategySizeAlgorithm(a)}catch(T){throw xt(o,T),T}try{La(o,a,b)}catch(T){throw xt(o,T),T}}ds(o)}function xt(o,a){let f=o._controlledReadableStream;f._state==="readable"&&(kr(o),Eo(o),ad(f,a))}function su(o){let a=o._controlledReadableStream._state;return a==="errored"?null:a==="closed"?0:o._strategyHWM-o._queueTotalSize}function $0(o){return!nd(o)}function bn(o){let a=o._controlledReadableStream._state;return!o._closeRequested&&a==="readable"}function sd(o,a,f,b,T,q,M){a._controlledReadableStream=o,a._queue=void 0,a._queueTotalSize=void 0,kr(a),a._started=!1,a._closeRequested=!1,a._pullAgain=!1,a._pulling=!1,a._strategySizeAlgorithm=M,a._strategyHWM=q,a._pullAlgorithm=b,a._cancelAlgorithm=T,o._readableStreamController=a;let Y=f();A(h(Y),()=>(a._started=!0,ds(a),null),ce=>(xt(a,ce),null))}function z0(o,a,f,b){let T=Object.create(lr.prototype),q,M,Y;a.start!==void 0?q=()=>a.start(T):q=()=>{},a.pull!==void 0?M=()=>a.pull(T):M=()=>h(void 0),a.cancel!==void 0?Y=ce=>a.cancel(ce):Y=()=>h(void 0),sd(o,T,q,M,Y,f,b)}function Ao(o){return new TypeError(`ReadableStreamDefaultController.prototype.${o} can only be used on a ReadableStreamDefaultController`)}function H0(o,a){return Gr(o._readableStreamController)?G0(o):W0(o)}function W0(o,a){let f=L(o),b=!1,T=!1,q=!1,M=!1,Y,ce,re,de,ge,ve=l(Qe=>{ge=Qe});function It(){return b?(T=!0,h(void 0)):(b=!0,ee(f,{_chunkSteps:rt=>{m(()=>{T=!1;let Ct=rt,dr=rt;q||_n(re._readableStreamController,Ct),M||_n(de._readableStreamController,dr),b=!1,T&&It()})},_closeSteps:()=>{b=!1,q||Xr(re._readableStreamController),M||Xr(de._readableStreamController),(!q||!M)&&ge(void 0)},_errorSteps:()=>{b=!1}}),h(void 0))}function wn(Qe){if(q=!0,Y=Qe,M){let rt=ke([Y,ce]),Ct=Pt(o,rt);ge(Ct)}return ve}function Fr(Qe){if(M=!0,ce=Qe,q){let rt=ke([Y,ce]),Ct=Pt(o,rt);ge(Ct)}return ve}function fr(){}return re=hs(fr,It,wn),de=hs(fr,It,Fr),S(f._closedPromise,Qe=>(xt(re._readableStreamController,Qe),xt(de._readableStreamController,Qe),(!q||!M)&&ge(void 0),null)),[re,de]}function G0(o){let a=L(o),f=!1,b=!1,T=!1,q=!1,M=!1,Y,ce,re,de,ge,ve=l(se=>{ge=se});function It(se){S(se._closedPromise,be=>(se!==a||(bt(re._readableStreamController,be),bt(de._readableStreamController,be),(!q||!M)&&ge(void 0)),null))}function wn(){Vr(a)&&(fe(a),a=L(o),It(a)),ee(a,{_chunkSteps:be=>{m(()=>{b=!1,T=!1;let Oe=be,ct=be;if(!q&&!M)try{ct=Ef(be)}catch(En){bt(re._readableStreamController,En),bt(de._readableStreamController,En),ge(Pt(o,En));return}q||ao(re._readableStreamController,Oe),M||ao(de._readableStreamController,ct),f=!1,b?fr():T&&Qe()})},_closeSteps:()=>{f=!1,q||as(re._readableStreamController),M||as(de._readableStreamController),re._readableStreamController._pendingPullIntos.length>0&&uo(re._readableStreamController,0),de._readableStreamController._pendingPullIntos.length>0&&uo(de._readableStreamController,0),(!q||!M)&&ge(void 0)},_errorSteps:()=>{f=!1}})}function Fr(se,be){Z(a)&&(fe(a),a=Nf(o),It(a));let Oe=be?de:re,ct=be?re:de;qf(a,se,1,{_chunkSteps:An=>{m(()=>{b=!1,T=!1;let Sn=be?M:q;if(be?q:M)Sn||co(Oe._readableStreamController,An);else{let Cd;try{Cd=Ef(An)}catch(cu){bt(Oe._readableStreamController,cu),bt(ct._readableStreamController,cu),ge(Pt(o,cu));return}Sn||co(Oe._readableStreamController,An),ao(ct._readableStreamController,Cd)}f=!1,b?fr():T&&Qe()})},_closeSteps:An=>{f=!1;let Sn=be?M:q,Fo=be?q:M;Sn||as(Oe._readableStreamController),Fo||as(ct._readableStreamController),An!==void 0&&(Sn||co(Oe._readableStreamController,An),!Fo&&ct._readableStreamController._pendingPullIntos.length>0&&uo(ct._readableStreamController,0)),(!Sn||!Fo)&&ge(void 0)},_errorSteps:()=>{f=!1}})}function fr(){if(f)return b=!0,h(void 0);f=!0;let se=Ha(re._readableStreamController);return se===null?wn():Fr(se._view,!1),h(void 0)}function Qe(){if(f)return T=!0,h(void 0);f=!0;let se=Ha(de._readableStreamController);return se===null?wn():Fr(se._view,!0),h(void 0)}function rt(se){if(q=!0,Y=se,M){let be=ke([Y,ce]),Oe=Pt(o,be);ge(Oe)}return ve}function Ct(se){if(M=!0,ce=se,q){let be=ke([Y,ce]),Oe=Pt(o,be);ge(Oe)}return ve}function dr(){}return re=id(dr,fr,rt),de=id(dr,Qe,Ct),It(a),[re,de]}function J0(o){return r(o)&&typeof o.getReader<"u"}function V0(o){return J0(o)?Y0(o.getReader()):K0(o)}function K0(o){let a,f=wf(o,"async"),b=e;function T(){let M;try{M=Uy(f)}catch(ce){return d(ce)}let Y=h(M);return _(Y,ce=>{if(!r(ce))throw new TypeError("The promise returned by the iterator.next() method must fulfill with an object");if(My(ce))Xr(a._readableStreamController);else{let de=$y(ce);_n(a._readableStreamController,de)}})}function q(M){let Y=f.iterator,ce;try{ce=so(Y,"return")}catch(ge){return d(ge)}if(ce===void 0)return h(void 0);let re;try{re=D(ce,Y,[M])}catch(ge){return d(ge)}let de=h(re);return _(de,ge=>{if(!r(ge))throw new TypeError("The promise returned by the iterator.return() method must fulfill with an object")})}return a=hs(b,T,q,0),a}function Y0(o){let a,f=e;function b(){let q;try{q=o.read()}catch(M){return d(M)}return _(q,M=>{if(!r(M))throw new TypeError("The promise returned by the reader.read() method must fulfill with an object");if(M.done)Xr(a._readableStreamController);else{let Y=M.value;_n(a._readableStreamController,Y)}})}function T(q){try{return h(o.cancel(q))}catch(M){return d(M)}}return a=hs(f,b,T,0),a}function X0(o,a){le(o,a);let f=o,b=f?.autoAllocateChunkSize,T=f?.cancel,q=f?.pull,M=f?.start,Y=f?.type;return{autoAllocateChunkSize:b===void 0?void 0:F(b,`${a} has member 'autoAllocateChunkSize' that`),cancel:T===void 0?void 0:Q0(T,f,`${a} has member 'cancel' that`),pull:q===void 0?void 0:Z0(q,f,`${a} has member 'pull' that`),start:M===void 0?void 0:e_(M,f,`${a} has member 'start' that`),type:Y===void 0?void 0:t_(Y,`${a} has member 'type' that`)}}function Q0(o,a,f){return _e(o,f),b=>C(o,a,[b])}function Z0(o,a,f){return _e(o,f),b=>C(o,a,[b])}function e_(o,a,f){return _e(o,f),b=>D(o,a,[b])}function t_(o,a){if(o=`${o}`,o!=="bytes")throw new TypeError(`${a} '${o}' is not a valid enumeration value for ReadableStreamType`);return o}function r_(o,a){return le(o,a),{preventCancel:!!o?.preventCancel}}function od(o,a){le(o,a);let f=o?.preventAbort,b=o?.preventCancel,T=o?.preventClose,q=o?.signal;return q!==void 0&&n_(q,`${a} has member 'signal' that`),{preventAbort:!!f,preventCancel:!!b,preventClose:!!T,signal:q}}function n_(o,a){if(!f0(o))throw new TypeError(`${a} is not an AbortSignal.`)}function s_(o,a){le(o,a);let f=o?.readable;g(f,"readable","ReadableWritablePair"),I(f,`${a} has member 'readable' that`);let b=o?.writable;return g(b,"writable","ReadableWritablePair"),Uf(b,`${a} has member 'writable' that`),{readable:f,writable:b}}class Ye{constructor(a={},f={}){a===void 0?a=null:Re(a,"First parameter");let b=ho(f,"Second parameter"),T=X0(a,"First parameter");if(ou(this),T.type==="bytes"){if(b.size!==void 0)throw new RangeError("The strategy for a byte stream cannot have a size function");let q=cs(b,0);Qy(this,T,q)}else{let q=fo(b),M=cs(b,1);z0(this,T,M,q)}}get locked(){if(!vr(this))throw Qr("locked");return Rr(this)}cancel(a=void 0){return vr(this)?Rr(this)?d(new TypeError("Cannot cancel a stream that already has a reader")):Pt(this,a):d(Qr("cancel"))}getReader(a=void 0){if(!vr(this))throw Qr("getReader");return e0(a,"First parameter").mode===void 0?L(this):Nf(this)}pipeThrough(a,f={}){if(!vr(this))throw Qr("pipeThrough");Be(a,1,"pipeThrough");let b=s_(a,"First parameter"),T=od(f,"Second parameter");if(Rr(this))throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream");if(gn(b.writable))throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream");let q=rd(this,b.writable,T.preventClose,T.preventAbort,T.preventCancel,T.signal);return y(q),b.readable}pipeTo(a,f={}){if(!vr(this))return d(Qr("pipeTo"));if(a===void 0)return d("Parameter 1 is required in 'pipeTo'.");if(!mn(a))return d(new TypeError("ReadableStream.prototype.pipeTo's first argument must be a WritableStream"));let b;try{b=od(f,"Second parameter")}catch(T){return d(T)}return Rr(this)?d(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream")):gn(a)?d(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream")):rd(this,a,b.preventClose,b.preventAbort,b.preventCancel,b.signal)}tee(){if(!vr(this))throw Qr("tee");let a=H0(this);return ke(a)}values(a=void 0){if(!vr(this))throw Qr("values");let f=r_(a,"First parameter");return fn(this,f.preventCancel)}[ja](a){return this.values(a)}static from(a){return V0(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,ja,{value:Ye.prototype.values,writable:!0,configurable:!0});function hs(o,a,f,b=1,T=()=>1){let q=Object.create(Ye.prototype);ou(q);let M=Object.create(lr.prototype);return sd(q,M,o,a,f,b,T),q}function id(o,a,f){let b=Object.create(Ye.prototype);ou(b);let T=Object.create(ur.prototype);return If(b,T,o,a,f,0,void 0),b}function ou(o){o._state="readable",o._reader=void 0,o._storedError=void 0,o._disturbed=!1}function vr(o){return!r(o)||!Object.prototype.hasOwnProperty.call(o,"_readableStreamController")?!1:o instanceof Ye}function Rr(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);ps(o);let f=o._reader;if(f!==void 0&&Vr(f)){let T=f._readIntoRequests;f._readIntoRequests=new v,T.forEach(q=>{q._closeSteps(void 0)})}let b=o._readableStreamController[V](a);return _(b,e)}function ps(o){o._state="closed";let a=o._reader;if(a!==void 0&&(ue(a),Z(a))){let f=a._readRequests;a._readRequests=new v,f.forEach(b=>{b._closeSteps()})}}function ad(o,a){o._state="errored",o._storedError=a;let f=o._reader;f!==void 0&&(G(f,a),Z(f)?xe(f,a):Lf(f,a))}function Qr(o){return new TypeError(`ReadableStream.prototype.${o} can only be used on a ReadableStream`)}function ud(o,a){le(o,a);let f=o?.highWaterMark;return g(f,"highWaterMark","QueuingStrategyInit"),{highWaterMark:w(f)}}let cd=o=>o.byteLength;s(cd,"size");class So{constructor(a){Be(a,1,"ByteLengthQueuingStrategy"),a=ud(a,"First parameter"),this._byteLengthQueuingStrategyHighWaterMark=a.highWaterMark}get highWaterMark(){if(!fd(this))throw ld("highWaterMark");return this._byteLengthQueuingStrategyHighWaterMark}get size(){if(!fd(this))throw ld("size");return cd}}Object.defineProperties(So.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(So.prototype,Symbol.toStringTag,{value:"ByteLengthQueuingStrategy",configurable:!0});function ld(o){return new TypeError(`ByteLengthQueuingStrategy.prototype.${o} can only be used on a ByteLengthQueuingStrategy`)}function fd(o){return!r(o)||!Object.prototype.hasOwnProperty.call(o,"_byteLengthQueuingStrategyHighWaterMark")?!1:o instanceof So}let dd=()=>1;s(dd,"size");class ko{constructor(a){Be(a,1,"CountQueuingStrategy"),a=ud(a,"First parameter"),this._countQueuingStrategyHighWaterMark=a.highWaterMark}get highWaterMark(){if(!pd(this))throw hd("highWaterMark");return this._countQueuingStrategyHighWaterMark}get size(){if(!pd(this))throw hd("size");return dd}}Object.defineProperties(ko.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(ko.prototype,Symbol.toStringTag,{value:"CountQueuingStrategy",configurable:!0});function hd(o){return new TypeError(`CountQueuingStrategy.prototype.${o} can only be used on a CountQueuingStrategy`)}function pd(o){return!r(o)||!Object.prototype.hasOwnProperty.call(o,"_countQueuingStrategyHighWaterMark")?!1:o instanceof ko}function o_(o,a){le(o,a);let f=o?.cancel,b=o?.flush,T=o?.readableType,q=o?.start,M=o?.transform,Y=o?.writableType;return{cancel:f===void 0?void 0:c_(f,o,`${a} has member 'cancel' that`),flush:b===void 0?void 0:i_(b,o,`${a} has member 'flush' that`),readableType:T,start:q===void 0?void 0:a_(q,o,`${a} has member 'start' that`),transform:M===void 0?void 0:u_(M,o,`${a} has member 'transform' that`),writableType:Y}}function i_(o,a,f){return _e(o,f),b=>C(o,a,[b])}function a_(o,a,f){return _e(o,f),b=>D(o,a,[b])}function u_(o,a,f){return _e(o,f),(b,T)=>C(o,a,[b,T])}function c_(o,a,f){return _e(o,f),b=>C(o,a,[b])}class Do{constructor(a={},f={},b={}){a===void 0&&(a=null);let T=ho(f,"Second parameter"),q=ho(b,"Third parameter"),M=o_(a,"First parameter");if(M.readableType!==void 0)throw new RangeError("Invalid readableType specified");if(M.writableType!==void 0)throw new RangeError("Invalid writableType specified");let Y=cs(q,0),ce=fo(q),re=cs(T,1),de=fo(T),ge,ve=l(It=>{ge=It});l_(this,ve,re,de,Y,ce),d_(this,M),M.start!==void 0?ge(M.start(this._transformStreamController)):ge(void 0)}get readable(){if(!md(this))throw bd("readable");return this._readable}get writable(){if(!md(this))throw bd("writable");return this._writable}}Object.defineProperties(Do.prototype,{readable:{enumerable:!0},writable:{enumerable:!0}}),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Do.prototype,Symbol.toStringTag,{value:"TransformStream",configurable:!0});function l_(o,a,f,b,T,q){function M(){return a}function Y(ve){return m_(o,ve)}function ce(ve){return g_(o,ve)}function re(){return y_(o)}o._writable=p0(M,Y,re,ce,f,b);function de(){return __(o)}function ge(ve){return b_(o,ve)}o._readable=hs(M,de,ge,T,q),o._backpressure=void 0,o._backpressureChangePromise=void 0,o._backpressureChangePromise_resolve=void 0,To(o,!0),o._transformStreamController=void 0}function md(o){return!r(o)||!Object.prototype.hasOwnProperty.call(o,"_transformStreamController")?!1:o instanceof Do}function gd(o,a){xt(o._readable._readableStreamController,a),iu(o,a)}function iu(o,a){Ro(o._transformStreamController),ls(o._writable._writableStreamController,a),au(o)}function au(o){o._backpressure&&To(o,!1)}function To(o,a){o._backpressureChangePromise!==void 0&&o._backpressureChangePromise_resolve(),o._backpressureChangePromise=l(f=>{o._backpressureChangePromise_resolve=f}),o._backpressure=a}class Or{constructor(){throw new TypeError("Illegal constructor")}get desiredSize(){if(!vo(this))throw Oo("desiredSize");let a=this._controlledTransformStream._readable._readableStreamController;return su(a)}enqueue(a=void 0){if(!vo(this))throw Oo("enqueue");yd(this,a)}error(a=void 0){if(!vo(this))throw Oo("error");h_(this,a)}terminate(){if(!vo(this))throw Oo("terminate");p_(this)}}Object.defineProperties(Or.prototype,{enqueue:{enumerable:!0},error:{enumerable:!0},terminate:{enumerable:!0},desiredSize:{enumerable:!0}}),s(Or.prototype.enqueue,"enqueue"),s(Or.prototype.error,"error"),s(Or.prototype.terminate,"terminate"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Or.prototype,Symbol.toStringTag,{value:"TransformStreamDefaultController",configurable:!0});function vo(o){return!r(o)||!Object.prototype.hasOwnProperty.call(o,"_controlledTransformStream")?!1:o instanceof Or}function f_(o,a,f,b,T){a._controlledTransformStream=o,o._transformStreamController=a,a._transformAlgorithm=f,a._flushAlgorithm=b,a._cancelAlgorithm=T,a._finishPromise=void 0,a._finishPromise_resolve=void 0,a._finishPromise_reject=void 0}function d_(o,a){let f=Object.create(Or.prototype),b,T,q;a.transform!==void 0?b=M=>a.transform(M,f):b=M=>{try{return yd(f,M),h(void 0)}catch(Y){return d(Y)}},a.flush!==void 0?T=()=>a.flush(f):T=()=>h(void 0),a.cancel!==void 0?q=M=>a.cancel(M):q=()=>h(void 0),f_(o,f,b,T,q)}function Ro(o){o._transformAlgorithm=void 0,o._flushAlgorithm=void 0,o._cancelAlgorithm=void 0}function yd(o,a){let f=o._controlledTransformStream,b=f._readable._readableStreamController;if(!bn(b))throw new TypeError("Readable side is not in a state that permits enqueue");try{_n(b,a)}catch(q){throw iu(f,q),f._readable._storedError}$0(b)!==f._backpressure&&To(f,!0)}function h_(o,a){gd(o._controlledTransformStream,a)}function _d(o,a){let f=o._transformAlgorithm(a);return _(f,void 0,b=>{throw gd(o._controlledTransformStream,b),b})}function p_(o){let a=o._controlledTransformStream,f=a._readable._readableStreamController;Xr(f);let b=new TypeError("TransformStream terminated");iu(a,b)}function m_(o,a){let f=o._transformStreamController;if(o._backpressure){let b=o._backpressureChangePromise;return _(b,()=>{let T=o._writable;if(T._state==="erroring")throw T._storedError;return _d(f,a)})}return _d(f,a)}function g_(o,a){let f=o._transformStreamController;if(f._finishPromise!==void 0)return f._finishPromise;let b=o._readable;f._finishPromise=l((q,M)=>{f._finishPromise_resolve=q,f._finishPromise_reject=M});let T=f._cancelAlgorithm(a);return Ro(f),A(T,()=>(b._state==="errored"?Cn(f,b._storedError):(xt(b._readableStreamController,a),uu(f)),null),q=>(xt(b._readableStreamController,q),Cn(f,q),null)),f._finishPromise}function y_(o){let a=o._transformStreamController;if(a._finishPromise!==void 0)return a._finishPromise;let f=o._readable;a._finishPromise=l((T,q)=>{a._finishPromise_resolve=T,a._finishPromise_reject=q});let b=a._flushAlgorithm();return Ro(a),A(b,()=>(f._state==="errored"?Cn(a,f._storedError):(Xr(f._readableStreamController),uu(a)),null),T=>(xt(f._readableStreamController,T),Cn(a,T),null)),a._finishPromise}function __(o){return To(o,!1),o._backpressureChangePromise}function b_(o,a){let f=o._transformStreamController;if(f._finishPromise!==void 0)return f._finishPromise;let b=o._writable;f._finishPromise=l((q,M)=>{f._finishPromise_resolve=q,f._finishPromise_reject=M});let T=f._cancelAlgorithm(a);return Ro(f),A(T,()=>(b._state==="errored"?Cn(f,b._storedError):(ls(b._writableStreamController,a),au(o),uu(f)),null),q=>(ls(b._writableStreamController,q),au(o),Cn(f,q),null)),f._finishPromise}function Oo(o){return new TypeError(`TransformStreamDefaultController.prototype.${o} can only be used on a TransformStreamDefaultController`)}function uu(o){o._finishPromise_resolve!==void 0&&(o._finishPromise_resolve(),o._finishPromise_resolve=void 0,o._finishPromise_reject=void 0)}function Cn(o,a){o._finishPromise_reject!==void 0&&(y(o._finishPromise),o._finishPromise_reject(a),o._finishPromise_resolve=void 0,o._finishPromise_reject=void 0)}function bd(o){return new TypeError(`TransformStream.prototype.${o} can only be used on a TransformStream`)}t.ByteLengthQueuingStrategy=So,t.CountQueuingStrategy=ko,t.ReadableByteStreamController=ur,t.ReadableStream=Ye,t.ReadableStreamBYOBReader=Dr,t.ReadableStreamBYOBRequest=Wr,t.ReadableStreamDefaultController=lr,t.ReadableStreamDefaultReader=z,t.TransformStream=Do,t.TransformStreamDefaultController=Or,t.WritableStream=Tr,t.WritableStreamDefaultController=yn,t.WritableStreamDefaultWriter=cr}))});var Bh=J(()=>{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,Nh())}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*Bu(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,jh),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+jh)).arrayBuffer();n+=u.byteLength,yield new Uint8Array(u)}}}var fv,jh,qh,Hb,Bt,bs=je(()=>{fv=xr(Bh(),1);jh=65536;qh=class ju{#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 ju?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 Bu(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 Bu(this.#e,!1))e.set(n,r),r+=n.length;return e.buffer}stream(){let e=Bu(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 R=ArrayBuffer.isView(A)?A.byteLength:A.size;if(i&&R<=i)i-=R,u-=R;else{let S;ArrayBuffer.isView(A)?(S=A.subarray(i,Math.min(R,u)),d+=S.byteLength):(S=A.slice(i,Math.min(R,u)),d+=S.size),u-=R,h.push(S),i=0}}let p=new ju([],{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(qh.prototype,{size:{enumerable:!0},type:{enumerable:!0},slice:{enumerable:!0}});Hb=qh,Bt=Hb});var Wb,Gb,Nr,qu=je(()=>{bs();Wb=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])}},Gb=Wb,Nr=Gb});function Mh(t,e=Bt){var r=`${Lh()}${Lh()}`.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+Lu(u)+`"\r
28
28
  \r
29
29
  ${i.replace(/\r(?!\n)|(?<!\r)\n/g,`\r
30
30
  `)}\r
31
- `):n.push(s+qu(u)+`"; filename="${qu(i.name,1)}"\r
31
+ `):n.push(s+Lu(u)+`"; filename="${Lu(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 Cs,Gb,Jb,qh,Vb,Lh,qu,rn,Br,Zo=je(()=>{bs();ju();({toStringTag:Cs,iterator:Gb,hasInstance:Jb}=Symbol),qh=Math.random,Vb="append,set,get,getAll,delete,keys,values,entries,forEach,constructor".split(","),Lh=(t,e,r)=>(t+="",/^(Blob|File)$/.test(e&&e[Cs])?[(r=r!==void 0?r+"":e[Cs]=="File"?e.name:"blob",t),e.name!==r||e[Cs]=="blob"?new Nr([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"),rn=(t,e,r)=>{if(e.length<r)throw new TypeError(`Failed to execute '${t}' on 'FormData': ${r} arguments required, but only ${e.length} present.`)},Br=class{#e=[];constructor(...e){if(e.length)throw new TypeError("Failed to construct 'FormData': parameter 1 is not of type 'HTMLFormElement'.")}get[Cs](){return"FormData"}[Gb](){return this.entries()}static[Jb](e){return e&&typeof e=="object"&&e[Cs]==="FormData"&&!Vb.some(r=>typeof e[r]!="function")}append(...e){rn("append",arguments,2),this.#e.push(Lh(...e))}delete(e){rn("delete",arguments,1),e+="",this.#e=this.#e.filter(([r])=>r!==e)}get(e){rn("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 rn("getAll",arguments,1),r=[],e+="",this.#e.forEach(n=>n[0]===e&&r.push(n[1])),r}has(e){return rn("has",arguments,1),e+="",this.#e.some(r=>r[0]===e)}forEach(e,r){rn("forEach",arguments,1);for(var[n,s]of this)e.call(r,s,n,this)}set(...e){rn("set",arguments,2);var r=[],n=!0;e=Lh(...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 gr,ei=je(()=>{gr=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,Lu=je(()=>{ei();et=class extends gr{constructor(e,r,n){super(e,r),n&&(this.code=this.errno=n.code,this.erroredSysCall=n.syscall)}}});var ti,Uu,ws,Mh,$h,zh,ri=je(()=>{ti=Symbol.toStringTag,Uu=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[ti]==="URLSearchParams",ws=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[ti]),Mh=t=>typeof t=="object"&&(t[ti]==="AbortSignal"||t[ti]==="EventTarget"),$h=(t,e)=>{let r=new URL(e).hostname,n=new URL(t).hostname;return r===n||r.endsWith(`.${n}`)},zh=(t,e)=>{let r=new URL(e).protocol,n=new URL(t).protocol;return r===n}});var Wh=J((Av,Hh)=>{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)}Hh.exports=globalThis.DOMException});import{statSync as Gh,createReadStream as Kb,promises as Yb}from"node:fs";import{basename as Xb}from"node:path";var Jh,Mu,Vh,Kh,Yh,Xh,Qh,Zh,ni,$u=je(()=>{Jh=xr(Wh(),1);ju();bs();({stat:Mu}=Yb),Vh=(t,e)=>Qh(Gh(t),t,e),Kh=(t,e)=>Mu(t).then(r=>Qh(r,t,e)),Yh=(t,e)=>Mu(t).then(r=>Zh(r,t,e)),Xh=(t,e)=>Zh(Gh(t),t,e),Qh=(t,e,r="")=>new Bt([new ni({path:e,size:t.size,lastModified:t.mtimeMs,start:0})],{type:r}),Zh=(t,e,r="")=>new Nr([new ni({path:e,size:t.size,lastModified:t.mtimeMs,start:0})],Xb(e),{type:r,lastModified:t.mtimeMs}),ni=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 Mu(this.#e);if(e>this.lastModified)throw new Jh.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*Kb(this.#e,{start:this.#t,end:this.#t+this.size-1})}get[Symbol.toStringTag](){return"Blob"}}});var tp={};Cd(tp,{toFormData:()=>sC});function nC(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 sC(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 zu(r[1]||r[2]),s,i,u,c,l,h,d=[],p=new Br,A=m=>{u+=y.decode(m,{stream:!0})},R=m=>{d.push(m)},S=()=>{let m=new Nr(d,h,{type:l});p.append(c,m)},_=()=>{p.append(c,u)},y=new TextDecoder("utf-8");y.decode(),n.onPartBegin=function(){n.onPartData=A,n.onPartEnd=_,s="",i="",u="",c="",l="",h=null,d.length=0},n.onHeaderField=function(m){s+=y.decode(m,{stream:!0})},n.onHeaderValue=function(m){i+=y.decode(m,{stream:!0})},n.onHeaderEnd=function(){if(i+=y.decode(),s=s.toLowerCase(),s==="content-disposition"){let m=i.match(/\bname=("([^"]*)"|([^()<>@,;:\\"/[\]?={}\s\t]+))/i);m&&(c=m[2]||m[3]||""),h=nC(i),h&&(n.onPartData=R,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 Vt,Fe,ep,jr,si,oi,Qb,Es,Zb,eC,tC,rC,nn,zu,rp=je(()=>{$u();Zo();Vt=0,Fe={START_BOUNDARY:Vt++,HEADER_FIELD_START:Vt++,HEADER_FIELD:Vt++,HEADER_VALUE_START:Vt++,HEADER_VALUE:Vt++,HEADER_VALUE_ALMOST_DONE:Vt++,HEADERS_ALMOST_DONE:Vt++,PART_DATA_START:Vt++,PART_DATA:Vt++,END:Vt++},ep=1,jr={PART_BOUNDARY:ep,LAST_BOUNDARY:ep*=2},si=10,oi=13,Qb=32,Es=45,Zb=58,eC=97,tC=122,rC=t=>t|32,nn=()=>{},zu=class{constructor(e){this.index=0,this.flags=0,this.onHeaderEnd=nn,this.onHeaderField=nn,this.onHeadersEnd=nn,this.onHeaderValue=nn,this.onPartBegin=nn,this.onPartData=nn,this.onPartEnd=nn,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=Fe.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,R=e.length,S,_,y=E=>{this[E+"Mark"]=r},m=E=>{delete this[E+"Mark"]},D=(E,v,x,$)=>{(v===void 0||v!==x)&&this[E]($&&$.subarray(v,x))},C=(E,v)=>{let x=E+"Mark";x in this&&(v?(D(E,this[x],r,e),delete this[x]):(D(E,this[x],e.length,e),this[x]=0))};for(r=0;r<n;r++)switch(S=e[r],h){case Fe.START_BOUNDARY:if(l===u.length-2){if(S===Es)d|=jr.LAST_BOUNDARY;else if(S!==oi)return;l++;break}else if(l-1===u.length-2){if(d&jr.LAST_BOUNDARY&&S===Es)h=Fe.END,d=0;else if(!(d&jr.LAST_BOUNDARY)&&S===si)l=0,D("onPartBegin"),h=Fe.HEADER_FIELD_START;else return;break}S!==u[l+2]&&(l=-2),S===u[l+2]&&l++;break;case Fe.HEADER_FIELD_START:h=Fe.HEADER_FIELD,y("onHeaderField"),l=0;case Fe.HEADER_FIELD:if(S===oi){m("onHeaderField"),h=Fe.HEADERS_ALMOST_DONE;break}if(l++,S===Es)break;if(S===Zb){if(l===1)return;C("onHeaderField",!0),h=Fe.HEADER_VALUE_START;break}if(_=rC(S),_<eC||_>tC)return;break;case Fe.HEADER_VALUE_START:if(S===Qb)break;y("onHeaderValue"),h=Fe.HEADER_VALUE;case Fe.HEADER_VALUE:S===oi&&(C("onHeaderValue",!0),D("onHeaderEnd"),h=Fe.HEADER_VALUE_ALMOST_DONE);break;case Fe.HEADER_VALUE_ALMOST_DONE:if(S!==si)return;h=Fe.HEADER_FIELD_START;break;case Fe.HEADERS_ALMOST_DONE:if(S!==si)return;D("onHeadersEnd"),h=Fe.PART_DATA_START;break;case Fe.PART_DATA_START:h=Fe.PART_DATA,y("onPartData");case Fe.PART_DATA:if(s=l,l===0){for(r+=A;r<R&&!(e[r]in c);)r+=p;r-=A,S=e[r]}if(l<u.length)u[l]===S?(l===0&&C("onPartData",!0),l++):l=0;else if(l===u.length)l++,S===oi?d|=jr.PART_BOUNDARY:S===Es?d|=jr.LAST_BOUNDARY:l=0;else if(l-1===u.length)if(d&jr.PART_BOUNDARY){if(l=0,S===si){d&=~jr.PART_BOUNDARY,D("onPartEnd"),D("onPartBegin"),h=Fe.HEADER_FIELD_START;break}}else d&jr.LAST_BOUNDARY&&S===Es?(D("onPartEnd"),h=Fe.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);D("onPartData",0,s,E),s=0,y("onPartData"),r--}break;case Fe.END:break;default:throw new Error(`Unexpected state entered: ${h}`)}C("onHeaderField"),C("onHeaderValue"),C("onPartData"),this.index=l,this.state=h,this.flags=d}end(){if(this.state===Fe.HEADER_FIELD_START&&this.index===0||this.state===Fe.PART_DATA&&this.index===this.boundary.length)this.onPartEnd();else if(this.state!==Fe.END)throw new Error("MultipartParser.end(): stream ended unexpectedly")}}});import qr,{PassThrough as np}from"node:stream";import{types as sp,deprecate as Wu,promisify as oC}from"node:util";import{Buffer as St}from"node:buffer";async function Hu(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 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 iC,it,Kt,xn,aC,ii,op,ip,ai=je(()=>{bs();Zo();Lu();ei();ri();iC=oC(qr.pipeline),it=Symbol("Body internals"),Kt=class{constructor(e,{size:r=0}={}){let n=null;e===null?e=null:Uu(e)?e=St.from(e.toString()):ws(e)||St.isBuffer(e)||(sp.isAnyArrayBuffer(e)?e=St.from(e):ArrayBuffer.isView(e)?e=St.from(e.buffer,e.byteOffset,e.byteLength):e instanceof qr||(e instanceof Br?(e=Uh(e),n=e.type.split("=")[1]):e=St.from(String(e))));let s=e;St.isBuffer(e)?s=qr.Readable.from(e):ws(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 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 Hu(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 Br,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(()=>(rp(),tp));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 Hu(this);return new TextDecoder().decode(e)}buffer(){return Hu(this)}};Kt.prototype.buffer=Wu(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:Wu(()=>{},"data doesn't exist, use json(), text(), arrayBuffer(), or body instead","https://github.com/node-fetch/node-fetch/issues/1000 (response)")}});xn=(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 np({highWaterMark:e}),n=new np({highWaterMark:e}),s.pipe(r),s.pipe(n),t[it].stream=r,s=n),s},aC=Wu(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"),ii=(t,e)=>t===null?null:typeof t=="string"?"text/plain;charset=UTF-8":Uu(t)?"application/x-www-form-urlencoded;charset=UTF-8":ws(t)?t.type||null:St.isBuffer(t)||sp.isAnyArrayBuffer(t)||ArrayBuffer.isView(t)?null:t instanceof Br?`multipart/form-data; boundary=${e[it].boundary}`:t&&typeof t.getBoundary=="function"?`multipart/form-data;boundary=${aC(t)}`:t instanceof qr?null:"text/plain;charset=UTF-8",op=t=>{let{body:e}=t[it];return e===null?0:ws(e)?e.size:St.isBuffer(e)?e.length:e&&typeof e.getLengthSync=="function"&&e.hasKnownLength&&e.hasKnownLength()?e.getLengthSync():null},ip=async(t,{body:e})=>{e===null?t.end():await iC(e,t)}});import{types as ap}from"node:util";import ci from"node:http";function up(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 ui(e),Gu(e,String(r)),!0}catch{return!1}}))}var ui,Gu,at,li=je(()=>{ui=typeof ci.validateHeaderName=="function"?ci.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}},Gu=typeof ci.validateHeaderValue=="function"?ci.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"&&!ap.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"||ap.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])=>(ui(n),Gu(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)=>(ui(u),Gu(u,String(c)),URLSearchParams.prototype[s].call(n,String(u).toLowerCase(),String(c)));case"delete":case"has":case"getAll":return u=>(ui(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 uC,As,Ju=je(()=>{uC=new Set([301,302,303,307,308]),As=t=>uC.has(t)});var jt,ft,cp=je(()=>{li();ai();Ju();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=ii(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(xn(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(!As(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 lp,fp=je(()=>{lp=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 cC}from"node:net";function dp(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(!hp.has(t))throw new TypeError(`Invalid referrerPolicy: ${t}`);return t}function lC(t){if(/^(http|ws)s:$/.test(t.protocol))return!0;let e=t.host.replace(/(^\[)|(]$)/g,""),r=cC(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 Pn(t){return/^about:(blank|srcdoc)$/.test(t)||t.protocol==="data:"||/^(blob|filesystem):$/.test(t.protocol)?!0:lC(t)}function gp(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=dp(s),u=dp(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 Pn(i)&&!Pn(c)?"no-referrer":u.toString();case"strict-origin-when-cross-origin":return i.origin===c.origin?i:Pn(i)&&!Pn(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 Pn(i)&&!Pn(c)?"no-referrer":i;default:throw new TypeError(`Invalid referrerPolicy: ${n}`)}}function yp(t){let e=(t.get("referrer-policy")||"").split(/[,\s]+/),r="";for(let n of e)n&&hp.has(n)&&(r=n);return r}var hp,pp,Vu=je(()=>{hp=new Set(["","no-referrer","no-referrer-when-downgrade","same-origin","origin","strict-origin","origin-when-cross-origin","strict-origin-when-cross-origin","unsafe-url"]),pp="strict-origin-when-cross-origin"});import{format as fC}from"node:url";import{deprecate as dC}from"node:util";var Ge,Ss,hC,Lr,_p,bp=je(()=>{li();ai();ri();fp();Vu();Ge=Symbol("Request internals"),Ss=t=>typeof t=="object"&&typeof t[Ge]=="object",hC=dC(()=>{},".data is not a valid RequestInit property, use .body instead","https://github.com/node-fetch/node-fetch/issues/1000 (request)"),Lr=class t extends Kt{constructor(e,r={}){let n;if(Ss(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()),!Ss(r)&&"data"in r&&hC(),(r.body!=null||Ss(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:Ss(e)&&e.body!==null?xn(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=ii(i,this);h&&u.set("Content-Type",h)}let c=Ss(e)?e.signal:null;if("signal"in r&&(c=r.signal),c!=null&&!Mh(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 fC(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(Lr.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=op(t);typeof c=="number"&&!Number.isNaN(c)&&(n=String(c))}n&&r.set("Content-Length",n),t.referrerPolicy===""&&(t.referrerPolicy=pp),t.referrer&&t.referrer!=="no-referrer"?t[Ge].referrer=gp(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=lp(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 ks,Cp=je(()=>{ei();ks=class extends gr{constructor(e,r="aborted"){super(e,r)}}});var Ap={};Cd(Ap,{AbortError:()=>ks,Blob:()=>Bt,FetchError:()=>et,File:()=>Nr,FormData:()=>Br,Headers:()=>at,Request:()=>Lr,Response:()=>ft,blobFrom:()=>Kh,blobFromSync:()=>Vh,default:()=>Ku,fileFrom:()=>Yh,fileFromSync:()=>Xh,isRedirect:()=>As});import pC from"node:http";import mC from"node:https";import In from"node:zlib";import wp,{PassThrough as Ep,pipeline as Nn}from"node:stream";import{Buffer as fi}from"node:buffer";async function Ku(t,e){return new Promise((r,n)=>{let s=new Lr(t,e),{parsedURL:i,options:u}=_p(s);if(!gC.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=Fh(s.url),_=new ft(S,{headers:{"Content-Type":S.typeFull}});r(_);return}let c=(i.protocol==="https:"?mC:pC).request,{signal:l}=s,h=null,d=()=>{let S=new ks("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(),R()},A=c(i.toString(),u);l&&l.addEventListener("abort",p);let R=()=>{A.abort(),l&&l.removeEventListener("abort",p)};A.on("error",S=>{n(new et(`request to ${s.url} failed, reason: ${S.message}`,"system",S)),R()}),yC(A,S=>{h&&h.body&&h.body.destroy(S)}),process.version<"v14"&&A.on("socket",S=>{let _;S.prependListener("end",()=>{_=S._eventsCount}),S.prependListener("close",y=>{if(h&&_<S._eventsCount&&!y){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 _=up(S.rawHeaders);if(As(S.statusCode)){let E=_.get("Location"),v=null;try{v=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")),R();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")),R();return;case"manual":break;case"follow":{if(v===null)break;if(s.counter>=s.follow){n(new et(`maximum redirect reached at: ${s.url}`,"max-redirect")),R();return}let x={headers:new at(s.headers),follow:s.follow,counter:s.counter+1,agent:s.agent,compress:s.compress,method:s.method,body:xn(s),signal:s.signal,size:s.size,referrer:s.referrer,referrerPolicy:s.referrerPolicy};if(!$h(s.url,v)||!zh(s.url,v))for(let V of["authorization","www-authenticate","cookie","cookie2"])x.headers.delete(V);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")),R();return}(S.statusCode===303||(S.statusCode===301||S.statusCode===302)&&s.method==="POST")&&(x.method="GET",x.body=void 0,x.headers.delete("content-length"));let $=yp(_);$&&(x.referrerPolicy=$),r(Ku(new Lr(v,x))),R();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 y=Nn(S,new Ep,E=>{E&&n(E)});process.version<"v12.10"&&S.on("aborted",p);let m={url:s.url,status:S.statusCode,statusText:S.statusMessage,headers:_,size:s.size,counter:s.counter,highWaterMark:s.highWaterMark},D=_.get("Content-Encoding");if(!s.compress||s.method==="HEAD"||D===null||S.statusCode===204||S.statusCode===304){h=new ft(y,m),r(h);return}let C={flush:In.Z_SYNC_FLUSH,finishFlush:In.Z_SYNC_FLUSH};if(D==="gzip"||D==="x-gzip"){y=Nn(y,In.createGunzip(C),E=>{E&&n(E)}),h=new ft(y,m),r(h);return}if(D==="deflate"||D==="x-deflate"){let E=Nn(S,new Ep,v=>{v&&n(v)});E.once("data",v=>{(v[0]&15)===8?y=Nn(y,In.createInflate(),x=>{x&&n(x)}):y=Nn(y,In.createInflateRaw(),x=>{x&&n(x)}),h=new ft(y,m),r(h)}),E.once("end",()=>{h||(h=new ft(y,m),r(h))});return}if(D==="br"){y=Nn(y,In.createBrotliDecompress(),E=>{E&&n(E)}),h=new ft(y,m),r(h);return}h=new ft(y,m),r(h)}),ip(A,s).catch(n)})}function yC(t,e){let r=fi.from(`0\r
35
+ `)),n.push(`--${r}--`),new e(n,{type:"multipart/form-data; boundary="+r})}var Cs,Jb,Vb,Lh,Kb,Uh,Lu,rn,Br,Zo=je(()=>{bs();qu();({toStringTag:Cs,iterator:Jb,hasInstance:Vb}=Symbol),Lh=Math.random,Kb="append,set,get,getAll,delete,keys,values,entries,forEach,constructor".split(","),Uh=(t,e,r)=>(t+="",/^(Blob|File)$/.test(e&&e[Cs])?[(r=r!==void 0?r+"":e[Cs]=="File"?e.name:"blob",t),e.name!==r||e[Cs]=="blob"?new Nr([e],r,e):e]:[t,e+""]),Lu=(t,e)=>(e?t:t.replace(/\r?\n|\r/g,`\r
36
+ `)).replace(/\n/g,"%0A").replace(/\r/g,"%0D").replace(/"/g,"%22"),rn=(t,e,r)=>{if(e.length<r)throw new TypeError(`Failed to execute '${t}' on 'FormData': ${r} arguments required, but only ${e.length} present.`)},Br=class{#e=[];constructor(...e){if(e.length)throw new TypeError("Failed to construct 'FormData': parameter 1 is not of type 'HTMLFormElement'.")}get[Cs](){return"FormData"}[Jb](){return this.entries()}static[Vb](e){return e&&typeof e=="object"&&e[Cs]==="FormData"&&!Kb.some(r=>typeof e[r]!="function")}append(...e){rn("append",arguments,2),this.#e.push(Uh(...e))}delete(e){rn("delete",arguments,1),e+="",this.#e=this.#e.filter(([r])=>r!==e)}get(e){rn("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 rn("getAll",arguments,1),r=[],e+="",this.#e.forEach(n=>n[0]===e&&r.push(n[1])),r}has(e){return rn("has",arguments,1),e+="",this.#e.some(r=>r[0]===e)}forEach(e,r){rn("forEach",arguments,1);for(var[n,s]of this)e.call(r,s,n,this)}set(...e){rn("set",arguments,2);var r=[],n=!0;e=Uh(...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 gr,ei=je(()=>{gr=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,Uu=je(()=>{ei();et=class extends gr{constructor(e,r,n){super(e,r),n&&(this.code=this.errno=n.code,this.erroredSysCall=n.syscall)}}});var ti,Mu,ws,$h,zh,Hh,ri=je(()=>{ti=Symbol.toStringTag,Mu=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[ti]==="URLSearchParams",ws=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[ti]),$h=t=>typeof t=="object"&&(t[ti]==="AbortSignal"||t[ti]==="EventTarget"),zh=(t,e)=>{let r=new URL(e).hostname,n=new URL(t).hostname;return r===n||r.endsWith(`.${n}`)},Hh=(t,e)=>{let r=new URL(e).protocol,n=new URL(t).protocol;return r===n}});var Gh=J((Sv,Wh)=>{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)}Wh.exports=globalThis.DOMException});import{statSync as Jh,createReadStream as Yb,promises as Xb}from"node:fs";import{basename as Qb}from"node:path";var Vh,$u,Kh,Yh,Xh,Qh,Zh,ep,ni,zu=je(()=>{Vh=xr(Gh(),1);qu();bs();({stat:$u}=Xb),Kh=(t,e)=>Zh(Jh(t),t,e),Yh=(t,e)=>$u(t).then(r=>Zh(r,t,e)),Xh=(t,e)=>$u(t).then(r=>ep(r,t,e)),Qh=(t,e)=>ep(Jh(t),t,e),Zh=(t,e,r="")=>new Bt([new ni({path:e,size:t.size,lastModified:t.mtimeMs,start:0})],{type:r}),ep=(t,e,r="")=>new Nr([new ni({path:e,size:t.size,lastModified:t.mtimeMs,start:0})],Qb(e),{type:r,lastModified:t.mtimeMs}),ni=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 $u(this.#e);if(e>this.lastModified)throw new Vh.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*Yb(this.#e,{start:this.#t,end:this.#t+this.size-1})}get[Symbol.toStringTag](){return"Blob"}}});var rp={};wd(rp,{toFormData:()=>oC});function sC(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 oC(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 Hu(r[1]||r[2]),s,i,u,c,l,h,d=[],p=new Br,A=m=>{u+=y.decode(m,{stream:!0})},R=m=>{d.push(m)},S=()=>{let m=new Nr(d,h,{type:l});p.append(c,m)},_=()=>{p.append(c,u)},y=new TextDecoder("utf-8");y.decode(),n.onPartBegin=function(){n.onPartData=A,n.onPartEnd=_,s="",i="",u="",c="",l="",h=null,d.length=0},n.onHeaderField=function(m){s+=y.decode(m,{stream:!0})},n.onHeaderValue=function(m){i+=y.decode(m,{stream:!0})},n.onHeaderEnd=function(){if(i+=y.decode(),s=s.toLowerCase(),s==="content-disposition"){let m=i.match(/\bname=("([^"]*)"|([^()<>@,;:\\"/[\]?={}\s\t]+))/i);m&&(c=m[2]||m[3]||""),h=sC(i),h&&(n.onPartData=R,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 Vt,Fe,tp,jr,si,oi,Zb,Es,eC,tC,rC,nC,nn,Hu,np=je(()=>{zu();Zo();Vt=0,Fe={START_BOUNDARY:Vt++,HEADER_FIELD_START:Vt++,HEADER_FIELD:Vt++,HEADER_VALUE_START:Vt++,HEADER_VALUE:Vt++,HEADER_VALUE_ALMOST_DONE:Vt++,HEADERS_ALMOST_DONE:Vt++,PART_DATA_START:Vt++,PART_DATA:Vt++,END:Vt++},tp=1,jr={PART_BOUNDARY:tp,LAST_BOUNDARY:tp*=2},si=10,oi=13,Zb=32,Es=45,eC=58,tC=97,rC=122,nC=t=>t|32,nn=()=>{},Hu=class{constructor(e){this.index=0,this.flags=0,this.onHeaderEnd=nn,this.onHeaderField=nn,this.onHeadersEnd=nn,this.onHeaderValue=nn,this.onPartBegin=nn,this.onPartData=nn,this.onPartEnd=nn,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=Fe.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,R=e.length,S,_,y=E=>{this[E+"Mark"]=r},m=E=>{delete this[E+"Mark"]},D=(E,v,x,$)=>{(v===void 0||v!==x)&&this[E]($&&$.subarray(v,x))},C=(E,v)=>{let x=E+"Mark";x in this&&(v?(D(E,this[x],r,e),delete this[x]):(D(E,this[x],e.length,e),this[x]=0))};for(r=0;r<n;r++)switch(S=e[r],h){case Fe.START_BOUNDARY:if(l===u.length-2){if(S===Es)d|=jr.LAST_BOUNDARY;else if(S!==oi)return;l++;break}else if(l-1===u.length-2){if(d&jr.LAST_BOUNDARY&&S===Es)h=Fe.END,d=0;else if(!(d&jr.LAST_BOUNDARY)&&S===si)l=0,D("onPartBegin"),h=Fe.HEADER_FIELD_START;else return;break}S!==u[l+2]&&(l=-2),S===u[l+2]&&l++;break;case Fe.HEADER_FIELD_START:h=Fe.HEADER_FIELD,y("onHeaderField"),l=0;case Fe.HEADER_FIELD:if(S===oi){m("onHeaderField"),h=Fe.HEADERS_ALMOST_DONE;break}if(l++,S===Es)break;if(S===eC){if(l===1)return;C("onHeaderField",!0),h=Fe.HEADER_VALUE_START;break}if(_=nC(S),_<tC||_>rC)return;break;case Fe.HEADER_VALUE_START:if(S===Zb)break;y("onHeaderValue"),h=Fe.HEADER_VALUE;case Fe.HEADER_VALUE:S===oi&&(C("onHeaderValue",!0),D("onHeaderEnd"),h=Fe.HEADER_VALUE_ALMOST_DONE);break;case Fe.HEADER_VALUE_ALMOST_DONE:if(S!==si)return;h=Fe.HEADER_FIELD_START;break;case Fe.HEADERS_ALMOST_DONE:if(S!==si)return;D("onHeadersEnd"),h=Fe.PART_DATA_START;break;case Fe.PART_DATA_START:h=Fe.PART_DATA,y("onPartData");case Fe.PART_DATA:if(s=l,l===0){for(r+=A;r<R&&!(e[r]in c);)r+=p;r-=A,S=e[r]}if(l<u.length)u[l]===S?(l===0&&C("onPartData",!0),l++):l=0;else if(l===u.length)l++,S===oi?d|=jr.PART_BOUNDARY:S===Es?d|=jr.LAST_BOUNDARY:l=0;else if(l-1===u.length)if(d&jr.PART_BOUNDARY){if(l=0,S===si){d&=~jr.PART_BOUNDARY,D("onPartEnd"),D("onPartBegin"),h=Fe.HEADER_FIELD_START;break}}else d&jr.LAST_BOUNDARY&&S===Es?(D("onPartEnd"),h=Fe.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);D("onPartData",0,s,E),s=0,y("onPartData"),r--}break;case Fe.END:break;default:throw new Error(`Unexpected state entered: ${h}`)}C("onHeaderField"),C("onHeaderValue"),C("onPartData"),this.index=l,this.state=h,this.flags=d}end(){if(this.state===Fe.HEADER_FIELD_START&&this.index===0||this.state===Fe.PART_DATA&&this.index===this.boundary.length)this.onPartEnd();else if(this.state!==Fe.END)throw new Error("MultipartParser.end(): stream ended unexpectedly")}}});import qr,{PassThrough as sp}from"node:stream";import{types as op,deprecate as Gu,promisify as iC}from"node:util";import{Buffer as St}from"node:buffer";async function Wu(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 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,xn,uC,ii,ip,ap,ai=je(()=>{bs();Zo();Uu();ei();ri();aC=iC(qr.pipeline),it=Symbol("Body internals"),Kt=class{constructor(e,{size:r=0}={}){let n=null;e===null?e=null:Mu(e)?e=St.from(e.toString()):ws(e)||St.isBuffer(e)||(op.isAnyArrayBuffer(e)?e=St.from(e):ArrayBuffer.isView(e)?e=St.from(e.buffer,e.byteOffset,e.byteLength):e instanceof qr||(e instanceof Br?(e=Mh(e),n=e.type.split("=")[1]):e=St.from(String(e))));let s=e;St.isBuffer(e)?s=qr.Readable.from(e):ws(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 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 Wu(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 Br,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(()=>(np(),rp));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 Wu(this);return new TextDecoder().decode(e)}buffer(){return Wu(this)}};Kt.prototype.buffer=Gu(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:Gu(()=>{},"data doesn't exist, use json(), text(), arrayBuffer(), or body instead","https://github.com/node-fetch/node-fetch/issues/1000 (response)")}});xn=(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 sp({highWaterMark:e}),n=new sp({highWaterMark:e}),s.pipe(r),s.pipe(n),t[it].stream=r,s=n),s},uC=Gu(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"),ii=(t,e)=>t===null?null:typeof t=="string"?"text/plain;charset=UTF-8":Mu(t)?"application/x-www-form-urlencoded;charset=UTF-8":ws(t)?t.type||null:St.isBuffer(t)||op.isAnyArrayBuffer(t)||ArrayBuffer.isView(t)?null:t instanceof Br?`multipart/form-data; boundary=${e[it].boundary}`:t&&typeof t.getBoundary=="function"?`multipart/form-data;boundary=${uC(t)}`:t instanceof qr?null:"text/plain;charset=UTF-8",ip=t=>{let{body:e}=t[it];return e===null?0:ws(e)?e.size:St.isBuffer(e)?e.length:e&&typeof e.getLengthSync=="function"&&e.hasKnownLength&&e.hasKnownLength()?e.getLengthSync():null},ap=async(t,{body:e})=>{e===null?t.end():await aC(e,t)}});import{types as up}from"node:util";import ci from"node:http";function cp(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 ui(e),Ju(e,String(r)),!0}catch{return!1}}))}var ui,Ju,at,li=je(()=>{ui=typeof ci.validateHeaderName=="function"?ci.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}},Ju=typeof ci.validateHeaderValue=="function"?ci.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"&&!up.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"||up.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])=>(ui(n),Ju(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)=>(ui(u),Ju(u,String(c)),URLSearchParams.prototype[s].call(n,String(u).toLowerCase(),String(c)));case"delete":case"has":case"getAll":return u=>(ui(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 cC,As,Vu=je(()=>{cC=new Set([301,302,303,307,308]),As=t=>cC.has(t)});var jt,ft,lp=je(()=>{li();ai();Vu();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=ii(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(xn(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(!As(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 fp,dp=je(()=>{fp=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 lC}from"node:net";function hp(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 gp(t){if(!pp.has(t))throw new TypeError(`Invalid referrerPolicy: ${t}`);return t}function fC(t){if(/^(http|ws)s:$/.test(t.protocol))return!0;let e=t.host.replace(/(^\[)|(]$)/g,""),r=lC(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 Pn(t){return/^about:(blank|srcdoc)$/.test(t)||t.protocol==="data:"||/^(blob|filesystem):$/.test(t.protocol)?!0:fC(t)}function yp(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=hp(s),u=hp(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 Pn(i)&&!Pn(c)?"no-referrer":u.toString();case"strict-origin-when-cross-origin":return i.origin===c.origin?i:Pn(i)&&!Pn(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 Pn(i)&&!Pn(c)?"no-referrer":i;default:throw new TypeError(`Invalid referrerPolicy: ${n}`)}}function _p(t){let e=(t.get("referrer-policy")||"").split(/[,\s]+/),r="";for(let n of e)n&&pp.has(n)&&(r=n);return r}var pp,mp,Ku=je(()=>{pp=new Set(["","no-referrer","no-referrer-when-downgrade","same-origin","origin","strict-origin","origin-when-cross-origin","strict-origin-when-cross-origin","unsafe-url"]),mp="strict-origin-when-cross-origin"});import{format as dC}from"node:url";import{deprecate as hC}from"node:util";var Ge,Ss,pC,Lr,bp,Cp=je(()=>{li();ai();ri();dp();Ku();Ge=Symbol("Request internals"),Ss=t=>typeof t=="object"&&typeof t[Ge]=="object",pC=hC(()=>{},".data is not a valid RequestInit property, use .body instead","https://github.com/node-fetch/node-fetch/issues/1000 (request)"),Lr=class t extends Kt{constructor(e,r={}){let n;if(Ss(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()),!Ss(r)&&"data"in r&&pC(),(r.body!=null||Ss(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:Ss(e)&&e.body!==null?xn(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=ii(i,this);h&&u.set("Content-Type",h)}let c=Ss(e)?e.signal:null;if("signal"in r&&(c=r.signal),c!=null&&!$h(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 dC(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=gp(e)}clone(){return new t(this)}get[Symbol.toStringTag](){return"Request"}};Object.defineProperties(Lr.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}});bp=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=ip(t);typeof c=="number"&&!Number.isNaN(c)&&(n=String(c))}n&&r.set("Content-Length",n),t.referrerPolicy===""&&(t.referrerPolicy=mp),t.referrer&&t.referrer!=="no-referrer"?t[Ge].referrer=yp(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=fp(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 ks,wp=je(()=>{ei();ks=class extends gr{constructor(e,r="aborted"){super(e,r)}}});var Sp={};wd(Sp,{AbortError:()=>ks,Blob:()=>Bt,FetchError:()=>et,File:()=>Nr,FormData:()=>Br,Headers:()=>at,Request:()=>Lr,Response:()=>ft,blobFrom:()=>Yh,blobFromSync:()=>Kh,default:()=>Yu,fileFrom:()=>Xh,fileFromSync:()=>Qh,isRedirect:()=>As});import mC from"node:http";import gC from"node:https";import In from"node:zlib";import Ep,{PassThrough as Ap,pipeline as Nn}from"node:stream";import{Buffer as fi}from"node:buffer";async function Yu(t,e){return new Promise((r,n)=>{let s=new Lr(t,e),{parsedURL:i,options:u}=bp(s);if(!yC.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=xh(s.url),_=new ft(S,{headers:{"Content-Type":S.typeFull}});r(_);return}let c=(i.protocol==="https:"?gC:mC).request,{signal:l}=s,h=null,d=()=>{let S=new ks("The operation was aborted.");n(S),s.body&&s.body instanceof Ep.Readable&&s.body.destroy(S),!(!h||!h.body)&&h.body.emit("error",S)};if(l&&l.aborted){d();return}let p=()=>{d(),R()},A=c(i.toString(),u);l&&l.addEventListener("abort",p);let R=()=>{A.abort(),l&&l.removeEventListener("abort",p)};A.on("error",S=>{n(new et(`request to ${s.url} failed, reason: ${S.message}`,"system",S)),R()}),_C(A,S=>{h&&h.body&&h.body.destroy(S)}),process.version<"v14"&&A.on("socket",S=>{let _;S.prependListener("end",()=>{_=S._eventsCount}),S.prependListener("close",y=>{if(h&&_<S._eventsCount&&!y){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 _=cp(S.rawHeaders);if(As(S.statusCode)){let E=_.get("Location"),v=null;try{v=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")),R();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")),R();return;case"manual":break;case"follow":{if(v===null)break;if(s.counter>=s.follow){n(new et(`maximum redirect reached at: ${s.url}`,"max-redirect")),R();return}let x={headers:new at(s.headers),follow:s.follow,counter:s.counter+1,agent:s.agent,compress:s.compress,method:s.method,body:xn(s),signal:s.signal,size:s.size,referrer:s.referrer,referrerPolicy:s.referrerPolicy};if(!zh(s.url,v)||!Hh(s.url,v))for(let V of["authorization","www-authenticate","cookie","cookie2"])x.headers.delete(V);if(S.statusCode!==303&&s.body&&e.body instanceof Ep.Readable){n(new et("Cannot follow redirect with body being a readable stream","unsupported-redirect")),R();return}(S.statusCode===303||(S.statusCode===301||S.statusCode===302)&&s.method==="POST")&&(x.method="GET",x.body=void 0,x.headers.delete("content-length"));let $=_p(_);$&&(x.referrerPolicy=$),r(Yu(new Lr(v,x))),R();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 y=Nn(S,new Ap,E=>{E&&n(E)});process.version<"v12.10"&&S.on("aborted",p);let m={url:s.url,status:S.statusCode,statusText:S.statusMessage,headers:_,size:s.size,counter:s.counter,highWaterMark:s.highWaterMark},D=_.get("Content-Encoding");if(!s.compress||s.method==="HEAD"||D===null||S.statusCode===204||S.statusCode===304){h=new ft(y,m),r(h);return}let C={flush:In.Z_SYNC_FLUSH,finishFlush:In.Z_SYNC_FLUSH};if(D==="gzip"||D==="x-gzip"){y=Nn(y,In.createGunzip(C),E=>{E&&n(E)}),h=new ft(y,m),r(h);return}if(D==="deflate"||D==="x-deflate"){let E=Nn(S,new Ap,v=>{v&&n(v)});E.once("data",v=>{(v[0]&15)===8?y=Nn(y,In.createInflate(),x=>{x&&n(x)}):y=Nn(y,In.createInflateRaw(),x=>{x&&n(x)}),h=new ft(y,m),r(h)}),E.once("end",()=>{h||(h=new ft(y,m),r(h))});return}if(D==="br"){y=Nn(y,In.createBrotliDecompress(),E=>{E&&n(E)}),h=new ft(y,m),r(h);return}h=new ft(y,m),r(h)}),ap(A,s).catch(n)})}function _C(t,e){let r=fi.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=fi.compare(h.slice(-5),r)===0,!s&&i&&(s=fi.compare(i.slice(-3),r.slice(0,3))===0&&fi.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 gC,Sp=je(()=>{xh();ai();cp();li();bp();Lu();Cp();Ju();Zo();ri();Vu();$u();gC=new Set(["data:","http:","https:"])});var Tp=J(jn=>{"use strict";var _C=jn&&jn.__importDefault||function(t){return t&&t.__esModule?t:{default:t}},Bn;Object.defineProperty(jn,"__esModule",{value:!0});jn.Gaxios=void 0;var bC=_C(Eu()),CC=X("https"),sn=ku(),wC=oh(),kp=X("stream"),Dp=vu(),EC=async()=>globalThis.crypto?.randomUUID()||(await import("crypto")).randomUUID(),di=class{agentCache=new Map;defaults;interceptors;constructor(e){this.defaults=e||{},this.interceptors={request:new Dp.GaxiosInterceptorManager,response:new Dp.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&&Bn.mergeHeaders(i,r.headers),n&&Bn.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 Bn.#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=sn.GaxiosError.extractAPIErrorFromResponse(r,`Request failed with status code ${r.status}`);throw new sn.GaxiosError(n?.message,e,r,n)}return r}catch(r){let n;r instanceof sn.GaxiosError?n=r:r instanceof Error?n=new sn.GaxiosError(r.message,e,void 0,r):n=new sn.GaxiosError("Unexpected Gaxios Error",e,void 0,r);let{shouldRetry:s,config:i}=await(0,wC.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 sn.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);Bn.mergeHeaders(r,e.headers);let n=(0,bC.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 EC();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 Bn.#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 CC.Agent({cert:n.cert,key:n.key}),this.agentCache.set(n.key,n.agent)));return typeof n.errorRedactor!="function"&&n.errorRedactor!==!1&&(n.errorRedactor=sn.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
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=fi.compare(h.slice(-5),r)===0,!s&&i&&(s=fi.compare(i.slice(-3),r.slice(0,3))===0&&fi.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 yC,kp=je(()=>{Ph();ai();lp();li();Cp();Uu();wp();Vu();Zo();ri();Ku();zu();yC=new Set(["data:","http:","https:"])});var vp=J(jn=>{"use strict";var bC=jn&&jn.__importDefault||function(t){return t&&t.__esModule?t:{default:t}},Bn;Object.defineProperty(jn,"__esModule",{value:!0});jn.Gaxios=void 0;var CC=bC(Au()),wC=X("https"),sn=Du(),EC=ih(),Dp=X("stream"),Tp=Ru(),AC=async()=>globalThis.crypto?.randomUUID()||(await import("crypto")).randomUUID(),di=class{agentCache=new Map;defaults;interceptors;constructor(e){this.defaults=e||{},this.interceptors={request:new Tp.GaxiosInterceptorManager,response:new Tp.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&&Bn.mergeHeaders(i,r.headers),n&&Bn.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 Bn.#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=sn.GaxiosError.extractAPIErrorFromResponse(r,`Request failed with status code ${r.status}`);throw new sn.GaxiosError(n?.message,e,r,n)}return r}catch(r){let n;r instanceof sn.GaxiosError?n=r:r instanceof Error?n=new sn.GaxiosError(r.message,e,void 0,r):n=new sn.GaxiosError("Unexpected Gaxios Error",e,void 0,r);let{shouldRetry:s,config:i}=await(0,EC.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 sn.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);Bn.mergeHeaders(r,e.headers);let n=(0,CC.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 Dp.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 AC();r.set("content-type",`multipart/related; boundary=${u}`),n.body=Dp.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 Bn.#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 wC.Agent({cert:n.cert,key:n.key}),this.agentCache.set(n.key,n.agent)));return typeof n.errorRedactor!="function"&&n.errorRedactor!==!1&&(n.errorRedactor=sn.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(()=>xr(Oh()))).HttpsProxyAgent,this.#o}static async#u(){let e=typeof window<"u"&&!!window;return this.#i||=e?window.fetch:(await Promise.resolve().then(()=>(Sp(),Ap))).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}};jn.Gaxios=di;Bn=di});var Ve=J(tt=>{"use strict";var AC=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]})),SC=tt&&tt.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&AC(e,t,r)};Object.defineProperty(tt,"__esModule",{value:!0});tt.instance=tt.Gaxios=tt.GaxiosError=void 0;tt.request=DC;var vp=Tp();Object.defineProperty(tt,"Gaxios",{enumerable:!0,get:function(){return vp.Gaxios}});var kC=ku();Object.defineProperty(tt,"GaxiosError",{enumerable:!0,get:function(){return kC.GaxiosError}});SC(vu(),tt);tt.instance=new vp.Gaxios;async function DC(t){return tt.instance.request(t)}});var Yu=J((Rp,hi)=>{(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 R(v){var x,$,V,U=W.prototype={constructor:W,toString:null,valueOf:null},Q=new W(1),ne=20,ae=4,fe=-7,ye=21,Ae=-1e7,oe=1e7,pe=!1,G=1,K=0,ue={prefix:"",groupSize:3,secondaryGroupSize:0,groupSeparator:",",decimalSeparator:".",fractionGroupSize:0,fractionGroupSeparator:"\xA0",suffix:""},Me="0123456789abcdefghijklmnopqrstuvwxyz",Te=!0;function W(g,w){var k,B,F,I,L,O,P,j,N=this;if(!(N instanceof W))return new W(g,w);if(w==null){if(g&&g._isBigNumber===!0){N.s=g.s,!g.c||g.e>oe?N.c=N.e=null:g.e<Ae?N.c=[N.e=0]:(N.e=g.e,N.c=g.c.slice());return}if((O=typeof g=="number")&&g*0==0){if(N.s=1/g<0?(g=-g,-1):1,g===~~g){for(I=0,L=g;L>=10;L/=10,I++);I>oe?N.c=N.e=null:(N.e=I,N.c=[g]);return}j=String(g)}else{if(!r.test(j=String(g)))return V(N,j,O);N.s=j.charCodeAt(0)==45?(j=j.slice(1),-1):1}(I=j.indexOf("."))>-1&&(j=j.replace(".","")),(L=j.search(/e/i))>0?(I<0&&(I=L),I+=+j.slice(L+1),j=j.substring(0,L)):I<0&&(I=j.length)}else{if(m(w,2,Me.length,"Base"),w==10&&Te)return N=new W(g),Re(N,ne+N.e+1,ae);if(j=String(g),O=typeof g=="number"){if(g*0!=0)return V(N,j,O,w);if(N.s=1/g<0?(j=j.slice(1),-1):1,W.DEBUG&&j.replace(/^0\.0*|\./,"").length>15)throw Error(u+g)}else N.s=j.charCodeAt(0)===45?(j=j.slice(1),-1):1;for(k=Me.slice(0,w),I=L=0,P=j.length;L<P;L++)if(k.indexOf(B=j.charAt(L))<0){if(B=="."){if(L>I){I=P;continue}}else if(!F&&(j==j.toUpperCase()&&(j=j.toLowerCase())||j==j.toLowerCase()&&(j=j.toUpperCase()))){F=!0,L=-1,I=0;continue}return V(N,String(g),O,w)}O=!1,j=$(j,w,10,N.s),(I=j.indexOf("."))>-1?j=j.replace(".",""):I=j.length}for(L=0;j.charCodeAt(L)===48;L++);for(P=j.length;j.charCodeAt(--P)===48;);if(j=j.slice(L,++P)){if(P-=L,O&&W.DEBUG&&P>15&&(g>h||g!==s(g)))throw Error(u+N.s*g);if((I=I-L-1)>oe)N.c=N.e=null;else if(I<Ae)N.c=[N.e=0];else{if(N.e=I,N.c=[],L=(I+1)%l,I<0&&(L+=l),L<P){for(L&&N.c.push(+j.slice(0,L)),P-=l;L<P;)N.c.push(+j.slice(L,L+=l));L=l-(j=j.slice(L)).length}else L-=P;for(;L--;j+="0");N.c.push(+j)}}else N.c=[N.e=0]}W.clone=R,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(g){var w,k;if(g!=null)if(typeof g=="object"){if(g.hasOwnProperty(w="DECIMAL_PLACES")&&(k=g[w],m(k,0,A,w),ne=k),g.hasOwnProperty(w="ROUNDING_MODE")&&(k=g[w],m(k,0,8,w),ae=k),g.hasOwnProperty(w="EXPONENTIAL_AT")&&(k=g[w],k&&k.pop?(m(k[0],-A,0,w),m(k[1],0,A,w),fe=k[0],ye=k[1]):(m(k,-A,A,w),fe=-(ye=k<0?-k:k))),g.hasOwnProperty(w="RANGE"))if(k=g[w],k&&k.pop)m(k[0],-A,-1,w),m(k[1],1,A,w),Ae=k[0],oe=k[1];else if(m(k,-A,A,w),k)Ae=-(oe=k<0?-k:k);else throw Error(i+w+" cannot be zero: "+k);if(g.hasOwnProperty(w="CRYPTO"))if(k=g[w],k===!!k)if(k)if(typeof crypto<"u"&&crypto&&(crypto.getRandomValues||crypto.randomBytes))pe=k;else throw pe=!k,Error(i+"crypto unavailable");else pe=k;else throw Error(i+w+" not true or false: "+k);if(g.hasOwnProperty(w="MODULO_MODE")&&(k=g[w],m(k,0,9,w),G=k),g.hasOwnProperty(w="POW_PRECISION")&&(k=g[w],m(k,0,A,w),K=k),g.hasOwnProperty(w="FORMAT"))if(k=g[w],typeof k=="object")ue=k;else throw Error(i+w+" not an object: "+k);if(g.hasOwnProperty(w="ALPHABET"))if(k=g[w],typeof k=="string"&&!/^.?$|[+\-.\s]|(.).*\1/.test(k))Te=k.slice(0,10)=="0123456789",Me=k;else throw Error(i+w+" invalid: "+k)}else throw Error(i+"Object expected: "+g);return{DECIMAL_PLACES:ne,ROUNDING_MODE:ae,EXPONENTIAL_AT:[fe,ye],RANGE:[Ae,oe],CRYPTO:pe,MODULO_MODE:G,POW_PRECISION:K,FORMAT:ue,ALPHABET:Me}},W.isBigNumber=function(g){if(!g||g._isBigNumber!==!0)return!1;if(!W.DEBUG)return!0;var w,k,B=g.c,F=g.e,I=g.s;e:if({}.toString.call(B)=="[object Array]"){if((I===1||I===-1)&&F>=-A&&F<=A&&F===s(F)){if(B[0]===0){if(F===0&&B.length===1)return!0;break e}if(w=(F+1)%l,w<1&&(w+=l),String(B[0]).length==w){for(w=0;w<B.length;w++)if(k=B[w],k<0||k>=c||k!==s(k))break e;if(k!==0)return!0}}}else if(B===null&&F===null&&(I===null||I===1||I===-1))return!0;throw Error(i+"Invalid BigNumber: "+g)},W.maximum=W.max=function(){return _e(arguments,-1)},W.minimum=W.min=function(){return _e(arguments,1)},W.random=(function(){var g=9007199254740992,w=Math.random()*g&2097151?function(){return s(Math.random()*g)}:function(){return(Math.random()*1073741824|0)*8388608+(Math.random()*8388608|0)};return function(k){var B,F,I,L,O,P=0,j=[],N=new W(Q);if(k==null?k=ne:m(k,0,A),L=n(k/l),pe)if(crypto.getRandomValues){for(B=crypto.getRandomValues(new Uint32Array(L*=2));P<L;)O=B[P]*131072+(B[P+1]>>>11),O>=9e15?(F=crypto.getRandomValues(new Uint32Array(2)),B[P]=F[0],B[P+1]=F[1]):(j.push(O%1e14),P+=2);P=L/2}else if(crypto.randomBytes){for(B=crypto.randomBytes(L*=7);P<L;)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=L/7}else throw pe=!1,Error(i+"crypto unavailable");if(!pe)for(;P<L;)O=w(),O<9e15&&(j[P++]=O%1e14);for(L=j[--P],k%=l,L&&k&&(O=d[l-k],j[P]=s(L/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 g=1,w=arguments,k=new W(w[0]);g<w.length;)k=k.plus(w[g++]);return k},$=(function(){var g="0123456789";function w(k,B,F,I){for(var L,O=[0],P,j=0,N=k.length;j<N;){for(P=O.length;P--;O[P]*=B);for(O[0]+=I.indexOf(k.charAt(j++)),L=0;L<O.length;L++)O[L]>F-1&&(O[L+1]==null&&(O[L+1]=0),O[L+1]+=O[L]/F|0,O[L]%=F)}return O.reverse()}return function(k,B,F,I,L){var O,P,j,N,z,Z,ee,Ee,xe=k.indexOf("."),Ne=ne,we=ae;for(xe>=0&&(N=K,K=0,k=k.replace(".",""),Ee=new W(B),Z=Ee.pow(k.length-xe),K=N,Ee.c=w(E(_(Z.c),Z.e,"0"),10,F,g),Ee.e=Ee.c.length),ee=w(k,B,F,L?(O=Me,g):(O=g,Me)),j=N=ee.length;ee[--N]==0;ee.pop());if(!ee[0])return O.charAt(0);if(xe<0?--j:(Z.c=ee,Z.e=j,Z.s=I,Z=x(Z,Ee,Ne,we,F),ee=Z.c,z=Z.r,j=Z.e),P=j+Ne+1,xe=ee[P],N=F/2,z=z||P<0||ee[P+1]!=null,z=we<4?(xe!=null||z)&&(we==0||we==(Z.s<0?3:2)):xe>N||xe==N&&(we==4||z||we==6&&ee[P-1]&1||we==(Z.s<0?8:7)),P<1||!ee[0])k=z?E(O.charAt(1),-Ne,O.charAt(0)):O.charAt(0);else{if(ee.length=P,z)for(--F;++ee[--P]>F;)ee[P]=0,P||(++j,ee=[1].concat(ee));for(N=ee.length;!ee[--N];);for(xe=0,k="";xe<=N;k+=O.charAt(ee[xe++]));k=E(k,j,O.charAt(0))}return k}})(),x=(function(){function g(B,F,I){var L,O,P,j,N=0,z=B.length,Z=F%p,ee=F/p|0;for(B=B.slice();z--;)P=B[z]%p,j=B[z]/p|0,L=ee*P+j*Z,O=Z*P+L%p*p+N,N=(O/I|0)+(L/p|0)+ee*j,B[z]=O%I;return N&&(B=[N].concat(B)),B}function w(B,F,I,L){var O,P;if(I!=L)P=I>L?1:-1;else for(O=P=0;O<I;O++)if(B[O]!=F[O]){P=B[O]>F[O]?1:-1;break}return P}function k(B,F,I,L){for(var O=0;I--;)B[I]-=O,O=B[I]<F[I]?1:0,B[I]=O*L+B[I]-F[I];for(;!B[0]&&B.length>1;B.splice(0,1));}return function(B,F,I,L,O){var P,j,N,z,Z,ee,Ee,xe,Ne,we,Se,Le,fn,dn,hn,ut,ir,Ke=B.s==F.s?1:-1,Ue=B.c,ke=F.c;if(!Ue||!Ue[0]||!ke||!ke[0])return new W(!B.s||!F.s||(Ue?ke&&Ue[0]==ke[0]:!ke)?NaN:Ue&&Ue[0]==0||!ke?Ke*0:Ke/0);for(xe=new W(Ke),Ne=xe.c=[],j=B.e-F.e,Ke=I+j+1,O||(O=c,j=S(B.e/l)-S(F.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(dn=Ue.length,ut=ke.length,N=0,Ke+=2,Z=s(O/(ke[0]+1)),Z>1&&(ke=g(ke,Z,O),Ue=g(Ue,Z,O),ut=ke.length,dn=Ue.length),fn=ut,we=Ue.slice(0,ut),Se=we.length;Se<ut;we[Se++]=0);ir=ke.slice(),ir=[0].concat(ir),hn=ke[0],ke[1]>=O/2&&hn++;do{if(Z=0,P=w(ke,we,ut,Se),P<0){if(Le=we[0],ut!=Se&&(Le=Le*O+(we[1]||0)),Z=s(Le/hn),Z>1)for(Z>=O&&(Z=O-1),ee=g(ke,Z,O),Ee=ee.length,Se=we.length;w(ee,we,Ee,Se)==1;)Z--,k(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)),k(we,ee,Se,O),Se=we.length,P==-1)for(;w(ke,we,ut,Se)<1;)Z++,k(we,ut<Se?ir:ke,Se,O),Se=we.length}else P===0&&(Z++,we=[0]);Ne[N++]=Z,we[0]?we[Se++]=Ue[fn]||0:(we=[Ue[fn]],Se=1)}while((fn++<dn||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(xe,I+(xe.e=N+j*l-1)+1,L,z)}else xe.e=j,xe.r=+z;return xe}})();function le(g,w,k,B){var F,I,L,O,P;if(k==null?k=ae:m(k,0,8),!g.c)return g.toString();if(F=g.c[0],L=g.e,w==null)P=_(g.c),P=B==1||B==2&&(L<=fe||L>=ye)?C(P,L):E(P,L,"0");else if(g=Re(new W(g),w,k),I=g.e,P=_(g.c),O=P.length,B==1||B==2&&(w<=I||I<=fe)){for(;O<w;P+="0",O++);P=C(P,I)}else if(w-=L+(B===2&&I>L),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 g.s<0&&F?"-"+P:P}function _e(g,w){for(var k,B,F=1,I=new W(g[0]);F<g.length;F++)B=new W(g[F]),(!B.s||(k=y(I,B))===w||k===0&&I.s===w)&&(I=B);return I}function Ft(g,w,k){for(var B=1,F=w.length;!w[--F];w.pop());for(F=w[0];F>=10;F/=10,B++);return(k=B+k*l-1)>oe?g.c=g.e=null:k<Ae?g.c=[g.e=0]:(g.e=k,g.c=w),g}V=(function(){var g=/^(-?)0([xbo])(?=\w[\w.]*$)/i,w=/^([^.]+)\.$/,k=/^\.([^.]+)$/,B=/^-?(Infinity|NaN)$/,F=/^\s*\+(?=[\w.])|^\s+|\s+$/g;return function(I,L,O,P){var j,N=O?L:L.replace(F,"");if(B.test(N))I.s=isNaN(N)?null:N<0?-1:1;else{if(!O&&(N=N.replace(g,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(k,"0.$1")),L!=N))return new W(N,j);if(W.DEBUG)throw Error(i+"Not a"+(P?" base "+P:"")+" number: "+L);I.s=null}I.c=I.e=null}})();function Re(g,w,k,B){var F,I,L,O,P,j,N,z=g.c,Z=d;if(z){e:{for(F=1,O=z[0];O>=10;O/=10,F++);if(I=w-F,I<0)I+=l,L=w,P=z[j=0],N=s(P/Z[F-L-1]%10);else if(j=n((I+1)/l),j>=z.length)if(B){for(;z.length<=j;z.push(0));P=N=0,F=1,I%=l,L=I-l+1}else break e;else{for(P=O=z[j],F=1;O>=10;O/=10,F++);I%=l,L=I-l+F,N=L<0?0:s(P/Z[F-L-1]%10)}if(B=B||w<0||z[j+1]!=null||(L<0?P:P%Z[F-L-1]),B=k<4?(N||B)&&(k==0||k==(g.s<0?3:2)):N>5||N==5&&(k==4||B||k==6&&(I>0?L>0?P/Z[F-L]:0:z[j-1])%10&1||k==(g.s<0?8:7)),w<1||!z[0])return z.length=0,B?(w-=g.e+1,z[0]=Z[(l-w%l)%l],g.e=-w||0):z[0]=g.e=0,g;if(I==0?(z.length=j,O=1,j--):(z.length=j+1,O=Z[l-I],z[j]=L>0?s(P/Z[F-L]%Z[L])*O:0),B)for(;;)if(j==0){for(I=1,L=z[0];L>=10;L/=10,I++);for(L=z[0]+=O,O=1;L>=10;L/=10,O++);I!=O&&(g.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());}g.e>oe?g.c=g.e=null:g.e<Ae&&(g.c=[g.e=0])}return g}function Be(g){var w,k=g.e;return k===null?g.toString():(w=_(g.c),w=k<=fe||k>=ye?C(w,k):E(w,k,"0"),g.s<0?"-"+w:w)}return U.absoluteValue=U.abs=function(){var g=new W(this);return g.s<0&&(g.s=1),g},U.comparedTo=function(g,w){return y(this,new W(g,w))},U.decimalPlaces=U.dp=function(g,w){var k,B,F,I=this;if(g!=null)return m(g,0,A),w==null?w=ae:m(w,0,8),Re(new W(I),g+I.e+1,w);if(!(k=I.c))return null;if(B=((F=k.length-1)-S(this.e/l))*l,F=k[F])for(;F%10==0;F/=10,B--);return B<0&&(B=0),B},U.dividedBy=U.div=function(g,w){return x(this,new W(g,w),ne,ae)},U.dividedToIntegerBy=U.idiv=function(g,w){return x(this,new W(g,w),0,1)},U.exponentiatedBy=U.pow=function(g,w){var k,B,F,I,L,O,P,j,N,z=this;if(g=new W(g),g.c&&!g.isInteger())throw Error(i+"Exponent not an integer: "+Be(g));if(w!=null&&(w=new W(w)),O=g.e>14,!z.c||!z.c[0]||z.c[0]==1&&!z.e&&z.c.length==1||!g.c||!g.c[0])return N=new W(Math.pow(+Be(z),O?g.s*(2-D(g)):+Be(g))),w?N.mod(w):N;if(P=g.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(g.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&&D(g)?-0:0,z.e>-1&&(I=1/I),new W(P?1/I:I);K&&(I=n(K/l+2))}for(O?(k=new W(.5),P&&(g.s=1),j=D(g)):(F=Math.abs(+Be(g)),j=F%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(w))}if(F){if(F=s(F/2),F===0)break;j=F%2}else if(g=g.times(k),Re(g,g.e+1,1),g.e>14)j=D(g);else{if(F=+Be(g),F===0)break;j=F%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=Q.div(N)),w?N.mod(w):I?Re(N,K,ae,L):N)},U.integerValue=function(g){var w=new W(this);return g==null?g=ae:m(g,0,8),Re(w,w.e+1,g)},U.isEqualTo=U.eq=function(g,w){return y(this,new W(g,w))===0},U.isFinite=function(){return!!this.c},U.isGreaterThan=U.gt=function(g,w){return y(this,new W(g,w))>0},U.isGreaterThanOrEqualTo=U.gte=function(g,w){return(w=y(this,new W(g,w)))===1||w===0},U.isInteger=function(){return!!this.c&&S(this.e/l)>this.c.length-2},U.isLessThan=U.lt=function(g,w){return y(this,new W(g,w))<0},U.isLessThanOrEqualTo=U.lte=function(g,w){return(w=y(this,new W(g,w)))===-1||w===0},U.isNaN=function(){return!this.s},U.isNegative=function(){return this.s<0},U.isPositive=function(){return this.s>0},U.isZero=function(){return!!this.c&&this.c[0]==0},U.minus=function(g,w){var k,B,F,I,L=this,O=L.s;if(g=new W(g,w),w=g.s,!O||!w)return new W(NaN);if(O!=w)return g.s=-w,L.plus(g);var P=L.e/l,j=g.e/l,N=L.c,z=g.c;if(!P||!j){if(!N||!z)return N?(g.s=-w,g):new W(z?L:NaN);if(!N[0]||!z[0])return z[0]?(g.s=-w,g):new W(N[0]?L:ae==3?-0:0)}if(P=S(P),j=S(j),N=N.slice(),O=P-j){for((I=O<0)?(O=-O,F=N):(j=P,F=z),F.reverse(),w=O;w--;F.push(0));F.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&&(F=N,N=z,z=F,g.s=-g.s),w=(B=z.length)-(k=N.length),w>0)for(;w--;N[k++]=0);for(w=c-1;B>O;){if(N[--B]<z[B]){for(k=B;k&&!N[--k];N[k]=w);--N[k],N[B]+=c}N[B]-=z[B]}for(;N[0]==0;N.splice(0,1),--j);return N[0]?Ft(g,N,j):(g.s=ae==3?-1:1,g.c=[g.e=0],g)},U.modulo=U.mod=function(g,w){var k,B,F=this;return g=new W(g,w),!F.c||!g.s||g.c&&!g.c[0]?new W(NaN):!g.c||F.c&&!F.c[0]?new W(F):(G==9?(B=g.s,g.s=1,k=x(F,g,0,3),g.s=B,k.s*=B):k=x(F,g,0,G),g=F.minus(k.times(g)),!g.c[0]&&G==1&&(g.s=F.s),g)},U.multipliedBy=U.times=function(g,w){var k,B,F,I,L,O,P,j,N,z,Z,ee,Ee,xe,Ne,we=this,Se=we.c,Le=(g=new W(g,w)).c;if(!Se||!Le||!Se[0]||!Le[0])return!we.s||!g.s||Se&&!Se[0]&&!Le||Le&&!Le[0]&&!Se?g.c=g.e=g.s=null:(g.s*=we.s,!Se||!Le?g.c=g.e=null:(g.c=[0],g.e=0)),g;for(B=S(we.e/l)+S(g.e/l),g.s*=we.s,P=Se.length,z=Le.length,P<z&&(Ee=Se,Se=Le,Le=Ee,F=P,P=z,z=F),F=P+z,Ee=[];F--;Ee.push(0));for(xe=c,Ne=p,F=z;--F>=0;){for(k=0,Z=Le[F]%Ne,ee=Le[F]/Ne|0,L=P,I=F+L;I>F;)j=Se[--L]%Ne,N=Se[L]/Ne|0,O=ee*j+N*Z,j=Z*j+O%Ne*Ne+Ee[I]+k,k=(j/xe|0)+(O/Ne|0)+ee*N,Ee[I--]=j%xe;Ee[I]=k}return k?++B:Ee.splice(0,1),Ft(g,Ee,B)},U.negated=function(){var g=new W(this);return g.s=-g.s||null,g},U.plus=function(g,w){var k,B=this,F=B.s;if(g=new W(g,w),w=g.s,!F||!w)return new W(NaN);if(F!=w)return g.s=-w,B.minus(g);var I=B.e/l,L=g.e/l,O=B.c,P=g.c;if(!I||!L){if(!O||!P)return new W(F/0);if(!O[0]||!P[0])return P[0]?g:new W(O[0]?B:F*0)}if(I=S(I),L=S(L),O=O.slice(),F=I-L){for(F>0?(L=I,k=P):(F=-F,k=O),k.reverse();F--;k.push(0));k.reverse()}for(F=O.length,w=P.length,F-w<0&&(k=P,P=O,O=k,w=F),F=0;w;)F=(O[--w]=O[w]+P[w]+F)/c|0,O[w]=c===O[w]?0:O[w]%c;return F&&(O=[F].concat(O),++L),Ft(g,O,L)},U.precision=U.sd=function(g,w){var k,B,F,I=this;if(g!=null&&g!==!!g)return m(g,1,A),w==null?w=ae:m(w,0,8),Re(new W(I),g,w);if(!(k=I.c))return null;if(F=k.length-1,B=F*l+1,F=k[F]){for(;F%10==0;F/=10,B--);for(F=k[0];F>=10;F/=10,B++);}return g&&I.e+1>B&&(B=I.e+1),B},U.shiftedBy=function(g){return m(g,-h,h),this.times("1e"+g)},U.squareRoot=U.sqrt=function(){var g,w,k,B,F,I=this,L=I.c,O=I.s,P=I.e,j=ne+4,N=new W("0.5");if(O!==1||!L||!L[0])return new W(!O||O<0&&(!L||L[0])?NaN:L?I:1/0);if(O=Math.sqrt(+Be(I)),O==0||O==1/0?(w=_(L),(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),k=new W(w)):k=new W(O+""),k.c[0]){for(P=k.e,O=P+j,O<3&&(O=0);;)if(F=k,k=N.times(F.plus(x(I,F,j,1))),_(F.c).slice(0,O)===(w=_(k.c)).slice(0,O))if(k.e<P&&--O,w=w.slice(O-3,O+1),w=="9999"||!B&&w=="4999"){if(!B&&(Re(F,F.e+ne+2,0),F.times(F).eq(I))){k=F;break}j+=4,O+=4,B=1}else{(!+w||!+w.slice(1)&&w.charAt(0)=="5")&&(Re(k,k.e+ne+2,1),g=!k.times(k).eq(I));break}}return Re(k,k.e+ne+1,ae,g)},U.toExponential=function(g,w){return g!=null&&(m(g,0,A),g++),le(this,g,w,1)},U.toFixed=function(g,w){return g!=null&&(m(g,0,A),g=g+this.e+1),le(this,g,w)},U.toFormat=function(g,w,k){var B,F=this;if(k==null)g!=null&&w&&typeof w=="object"?(k=w,w=null):g&&typeof g=="object"?(k=g,g=w=null):k=ue;else if(typeof k!="object")throw Error(i+"Argument not an object: "+k);if(B=F.toFixed(g,w),F.c){var I,L=B.split("."),O=+k.groupSize,P=+k.secondaryGroupSize,j=k.groupSeparator||"",N=L[0],z=L[1],Z=F.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+(k.decimalSeparator||"")+((P=+k.fractionGroupSize)?z.replace(new RegExp("\\d{"+P+"}\\B","g"),"$&"+(k.fractionGroupSeparator||"")):z):N}return(k.prefix||"")+B+(k.suffix||"")},U.toFraction=function(g){var w,k,B,F,I,L,O,P,j,N,z,Z,ee=this,Ee=ee.c;if(g!=null&&(O=new W(g),!O.isInteger()&&(O.c||O.s!==1)||O.lt(Q)))throw Error(i+"Argument "+(O.isInteger()?"out of range: ":"not an integer: ")+Be(O));if(!Ee)return new W(ee);for(w=new W(Q),j=k=new W(Q),B=P=new W(Q),Z=_(Ee),I=w.e=Z.length-ee.e-1,w.c[0]=d[(L=I%l)<0?l+L:L],g=!g||O.comparedTo(w)>0?I>0?w:j:O,L=oe,oe=1/0,O=new W(Z),P.c[0]=0;N=x(O,w,0,1),F=k.plus(N.times(B)),F.comparedTo(g)!=1;)k=B,B=F,j=P.plus(N.times(F=j)),P=F,w=O.minus(N.times(F=w)),O=F;return F=x(g.minus(k),B,0,1),P=P.plus(F.times(j)),k=k.plus(F.times(B)),P.s=j.s=ee.s,I=I*2,z=x(j,B,I,ae).minus(ee).abs().comparedTo(x(P,k,I,ae).minus(ee).abs())<1?[j,B]:[P,k],oe=L,z},U.toNumber=function(){return+Be(this)},U.toPrecision=function(g,w){return g!=null&&m(g,1,A),le(this,g,w,2)},U.toString=function(g){var w,k=this,B=k.s,F=k.e;return F===null?B?(w="Infinity",B<0&&(w="-"+w)):w="NaN":(g==null?w=F<=fe||F>=ye?C(_(k.c),F):E(_(k.c),F,"0"):g===10&&Te?(k=Re(new W(k),ne+F+1,ae),w=E(_(k.c),k.e,"0")):(m(g,2,Me.length,"Base"),w=$(E(_(k.c),F,"0"),10,g,B,!0)),B<0&&k.c[0]&&(w="-"+w)),w},U.valueOf=U.toJSON=function(){return Be(this)},U._isBigNumber=!0,v!=null&&W.set(v),W}function S(v){var x=v|0;return v>0||v===x?x:x-1}function _(v){for(var x,$,V=1,U=v.length,Q=v[0]+"";V<U;){for(x=v[V++]+"",$=l-x.length;$--;x="0"+x);Q+=x}for(U=Q.length;Q.charCodeAt(--U)===48;);return Q.slice(0,U+1||1)}function y(v,x){var $,V,U=v.c,Q=x.c,ne=v.s,ae=x.s,fe=v.e,ye=x.e;if(!ne||!ae)return null;if($=U&&!U[0],V=Q&&!Q[0],$||V)return $?V?0:-ae:ne;if(ne!=ae)return ne;if($=ne<0,V=fe==ye,!U||!Q)return V?0:!U^$?1:-1;if(!V)return fe>ye^$?1:-1;for(ae=(fe=U.length)<(ye=Q.length)?fe:ye,ne=0;ne<ae;ne++)if(U[ne]!=Q[ne])return U[ne]>Q[ne]^$?1:-1;return fe==ye?0:fe>ye^$?1:-1}function m(v,x,$,V){if(v<x||v>$||v!==s(v))throw Error(i+(V||"Argument")+(typeof v=="number"?v<x||v>$?" out of range: ":" not an integer: ":" not a primitive number: ")+String(v))}function D(v){var x=v.c.length-1;return S(v.e/l)==x&&v.c[x]%2!=0}function C(v,x){return(v.length>1?v.charAt(0)+"."+v.slice(1):v)+(x<0?"e":"e+")+x}function E(v,x,$){var V,U;if(x<0){for(U=$+".";++x;U+=$);v=U+v}else if(V=v.length,++x>V){for(U=$,x-=V;--x;U+=$);v+=U}else x<V&&(v=v.slice(0,x)+"."+v.slice(x));return v}e=R(),e.default=e.BigNumber=e,typeof define=="function"&&define.amd?define(function(){return e}):typeof hi<"u"&&hi.exports?hi.exports=e:(t||(t=typeof self<"u"&&self?self:window),t.BigNumber=e)})(Rp)});var Pp=J((DR,xp)=>{var Op=Yu(),Fp=xp.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,R,S,_=n,y,m=d[h],D=m!=null&&(m instanceof Op||Op.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 D?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,y=[],Object.prototype.toString.apply(m)==="[object Array]"){for(S=m.length,p=0;p<S;p+=1)y[p]=l(p,m)||"null";return R=y.length===0?"[]":n?`[
43
+ `}yield n}static#o;static#i;static async#a(){return this.#o||=(await Promise.resolve().then(()=>xr(Fh()))).HttpsProxyAgent,this.#o}static async#u(){let e=typeof window<"u"&&!!window;return this.#i||=e?window.fetch:(await Promise.resolve().then(()=>(kp(),Sp))).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}};jn.Gaxios=di;Bn=di});var Ve=J(tt=>{"use strict";var SC=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]})),kC=tt&&tt.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&SC(e,t,r)};Object.defineProperty(tt,"__esModule",{value:!0});tt.instance=tt.Gaxios=tt.GaxiosError=void 0;tt.request=TC;var Rp=vp();Object.defineProperty(tt,"Gaxios",{enumerable:!0,get:function(){return Rp.Gaxios}});var DC=Du();Object.defineProperty(tt,"GaxiosError",{enumerable:!0,get:function(){return DC.GaxiosError}});kC(Ru(),tt);tt.instance=new Rp.Gaxios;async function TC(t){return tt.instance.request(t)}});var Xu=J((Op,hi)=>{(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 R(v){var x,$,V,U=W.prototype={constructor:W,toString:null,valueOf:null},Q=new W(1),ne=20,ae=4,fe=-7,ye=21,Ae=-1e7,oe=1e7,pe=!1,G=1,K=0,ue={prefix:"",groupSize:3,secondaryGroupSize:0,groupSeparator:",",decimalSeparator:".",fractionGroupSize:0,fractionGroupSeparator:"\xA0",suffix:""},Me="0123456789abcdefghijklmnopqrstuvwxyz",Te=!0;function W(g,w){var k,B,F,I,L,O,P,j,N=this;if(!(N instanceof W))return new W(g,w);if(w==null){if(g&&g._isBigNumber===!0){N.s=g.s,!g.c||g.e>oe?N.c=N.e=null:g.e<Ae?N.c=[N.e=0]:(N.e=g.e,N.c=g.c.slice());return}if((O=typeof g=="number")&&g*0==0){if(N.s=1/g<0?(g=-g,-1):1,g===~~g){for(I=0,L=g;L>=10;L/=10,I++);I>oe?N.c=N.e=null:(N.e=I,N.c=[g]);return}j=String(g)}else{if(!r.test(j=String(g)))return V(N,j,O);N.s=j.charCodeAt(0)==45?(j=j.slice(1),-1):1}(I=j.indexOf("."))>-1&&(j=j.replace(".","")),(L=j.search(/e/i))>0?(I<0&&(I=L),I+=+j.slice(L+1),j=j.substring(0,L)):I<0&&(I=j.length)}else{if(m(w,2,Me.length,"Base"),w==10&&Te)return N=new W(g),Re(N,ne+N.e+1,ae);if(j=String(g),O=typeof g=="number"){if(g*0!=0)return V(N,j,O,w);if(N.s=1/g<0?(j=j.slice(1),-1):1,W.DEBUG&&j.replace(/^0\.0*|\./,"").length>15)throw Error(u+g)}else N.s=j.charCodeAt(0)===45?(j=j.slice(1),-1):1;for(k=Me.slice(0,w),I=L=0,P=j.length;L<P;L++)if(k.indexOf(B=j.charAt(L))<0){if(B=="."){if(L>I){I=P;continue}}else if(!F&&(j==j.toUpperCase()&&(j=j.toLowerCase())||j==j.toLowerCase()&&(j=j.toUpperCase()))){F=!0,L=-1,I=0;continue}return V(N,String(g),O,w)}O=!1,j=$(j,w,10,N.s),(I=j.indexOf("."))>-1?j=j.replace(".",""):I=j.length}for(L=0;j.charCodeAt(L)===48;L++);for(P=j.length;j.charCodeAt(--P)===48;);if(j=j.slice(L,++P)){if(P-=L,O&&W.DEBUG&&P>15&&(g>h||g!==s(g)))throw Error(u+N.s*g);if((I=I-L-1)>oe)N.c=N.e=null;else if(I<Ae)N.c=[N.e=0];else{if(N.e=I,N.c=[],L=(I+1)%l,I<0&&(L+=l),L<P){for(L&&N.c.push(+j.slice(0,L)),P-=l;L<P;)N.c.push(+j.slice(L,L+=l));L=l-(j=j.slice(L)).length}else L-=P;for(;L--;j+="0");N.c.push(+j)}}else N.c=[N.e=0]}W.clone=R,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(g){var w,k;if(g!=null)if(typeof g=="object"){if(g.hasOwnProperty(w="DECIMAL_PLACES")&&(k=g[w],m(k,0,A,w),ne=k),g.hasOwnProperty(w="ROUNDING_MODE")&&(k=g[w],m(k,0,8,w),ae=k),g.hasOwnProperty(w="EXPONENTIAL_AT")&&(k=g[w],k&&k.pop?(m(k[0],-A,0,w),m(k[1],0,A,w),fe=k[0],ye=k[1]):(m(k,-A,A,w),fe=-(ye=k<0?-k:k))),g.hasOwnProperty(w="RANGE"))if(k=g[w],k&&k.pop)m(k[0],-A,-1,w),m(k[1],1,A,w),Ae=k[0],oe=k[1];else if(m(k,-A,A,w),k)Ae=-(oe=k<0?-k:k);else throw Error(i+w+" cannot be zero: "+k);if(g.hasOwnProperty(w="CRYPTO"))if(k=g[w],k===!!k)if(k)if(typeof crypto<"u"&&crypto&&(crypto.getRandomValues||crypto.randomBytes))pe=k;else throw pe=!k,Error(i+"crypto unavailable");else pe=k;else throw Error(i+w+" not true or false: "+k);if(g.hasOwnProperty(w="MODULO_MODE")&&(k=g[w],m(k,0,9,w),G=k),g.hasOwnProperty(w="POW_PRECISION")&&(k=g[w],m(k,0,A,w),K=k),g.hasOwnProperty(w="FORMAT"))if(k=g[w],typeof k=="object")ue=k;else throw Error(i+w+" not an object: "+k);if(g.hasOwnProperty(w="ALPHABET"))if(k=g[w],typeof k=="string"&&!/^.?$|[+\-.\s]|(.).*\1/.test(k))Te=k.slice(0,10)=="0123456789",Me=k;else throw Error(i+w+" invalid: "+k)}else throw Error(i+"Object expected: "+g);return{DECIMAL_PLACES:ne,ROUNDING_MODE:ae,EXPONENTIAL_AT:[fe,ye],RANGE:[Ae,oe],CRYPTO:pe,MODULO_MODE:G,POW_PRECISION:K,FORMAT:ue,ALPHABET:Me}},W.isBigNumber=function(g){if(!g||g._isBigNumber!==!0)return!1;if(!W.DEBUG)return!0;var w,k,B=g.c,F=g.e,I=g.s;e:if({}.toString.call(B)=="[object Array]"){if((I===1||I===-1)&&F>=-A&&F<=A&&F===s(F)){if(B[0]===0){if(F===0&&B.length===1)return!0;break e}if(w=(F+1)%l,w<1&&(w+=l),String(B[0]).length==w){for(w=0;w<B.length;w++)if(k=B[w],k<0||k>=c||k!==s(k))break e;if(k!==0)return!0}}}else if(B===null&&F===null&&(I===null||I===1||I===-1))return!0;throw Error(i+"Invalid BigNumber: "+g)},W.maximum=W.max=function(){return _e(arguments,-1)},W.minimum=W.min=function(){return _e(arguments,1)},W.random=(function(){var g=9007199254740992,w=Math.random()*g&2097151?function(){return s(Math.random()*g)}:function(){return(Math.random()*1073741824|0)*8388608+(Math.random()*8388608|0)};return function(k){var B,F,I,L,O,P=0,j=[],N=new W(Q);if(k==null?k=ne:m(k,0,A),L=n(k/l),pe)if(crypto.getRandomValues){for(B=crypto.getRandomValues(new Uint32Array(L*=2));P<L;)O=B[P]*131072+(B[P+1]>>>11),O>=9e15?(F=crypto.getRandomValues(new Uint32Array(2)),B[P]=F[0],B[P+1]=F[1]):(j.push(O%1e14),P+=2);P=L/2}else if(crypto.randomBytes){for(B=crypto.randomBytes(L*=7);P<L;)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=L/7}else throw pe=!1,Error(i+"crypto unavailable");if(!pe)for(;P<L;)O=w(),O<9e15&&(j[P++]=O%1e14);for(L=j[--P],k%=l,L&&k&&(O=d[l-k],j[P]=s(L/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 g=1,w=arguments,k=new W(w[0]);g<w.length;)k=k.plus(w[g++]);return k},$=(function(){var g="0123456789";function w(k,B,F,I){for(var L,O=[0],P,j=0,N=k.length;j<N;){for(P=O.length;P--;O[P]*=B);for(O[0]+=I.indexOf(k.charAt(j++)),L=0;L<O.length;L++)O[L]>F-1&&(O[L+1]==null&&(O[L+1]=0),O[L+1]+=O[L]/F|0,O[L]%=F)}return O.reverse()}return function(k,B,F,I,L){var O,P,j,N,z,Z,ee,Ee,xe=k.indexOf("."),Ne=ne,we=ae;for(xe>=0&&(N=K,K=0,k=k.replace(".",""),Ee=new W(B),Z=Ee.pow(k.length-xe),K=N,Ee.c=w(E(_(Z.c),Z.e,"0"),10,F,g),Ee.e=Ee.c.length),ee=w(k,B,F,L?(O=Me,g):(O=g,Me)),j=N=ee.length;ee[--N]==0;ee.pop());if(!ee[0])return O.charAt(0);if(xe<0?--j:(Z.c=ee,Z.e=j,Z.s=I,Z=x(Z,Ee,Ne,we,F),ee=Z.c,z=Z.r,j=Z.e),P=j+Ne+1,xe=ee[P],N=F/2,z=z||P<0||ee[P+1]!=null,z=we<4?(xe!=null||z)&&(we==0||we==(Z.s<0?3:2)):xe>N||xe==N&&(we==4||z||we==6&&ee[P-1]&1||we==(Z.s<0?8:7)),P<1||!ee[0])k=z?E(O.charAt(1),-Ne,O.charAt(0)):O.charAt(0);else{if(ee.length=P,z)for(--F;++ee[--P]>F;)ee[P]=0,P||(++j,ee=[1].concat(ee));for(N=ee.length;!ee[--N];);for(xe=0,k="";xe<=N;k+=O.charAt(ee[xe++]));k=E(k,j,O.charAt(0))}return k}})(),x=(function(){function g(B,F,I){var L,O,P,j,N=0,z=B.length,Z=F%p,ee=F/p|0;for(B=B.slice();z--;)P=B[z]%p,j=B[z]/p|0,L=ee*P+j*Z,O=Z*P+L%p*p+N,N=(O/I|0)+(L/p|0)+ee*j,B[z]=O%I;return N&&(B=[N].concat(B)),B}function w(B,F,I,L){var O,P;if(I!=L)P=I>L?1:-1;else for(O=P=0;O<I;O++)if(B[O]!=F[O]){P=B[O]>F[O]?1:-1;break}return P}function k(B,F,I,L){for(var O=0;I--;)B[I]-=O,O=B[I]<F[I]?1:0,B[I]=O*L+B[I]-F[I];for(;!B[0]&&B.length>1;B.splice(0,1));}return function(B,F,I,L,O){var P,j,N,z,Z,ee,Ee,xe,Ne,we,Se,Le,fn,dn,hn,ut,ir,Ke=B.s==F.s?1:-1,Ue=B.c,ke=F.c;if(!Ue||!Ue[0]||!ke||!ke[0])return new W(!B.s||!F.s||(Ue?ke&&Ue[0]==ke[0]:!ke)?NaN:Ue&&Ue[0]==0||!ke?Ke*0:Ke/0);for(xe=new W(Ke),Ne=xe.c=[],j=B.e-F.e,Ke=I+j+1,O||(O=c,j=S(B.e/l)-S(F.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(dn=Ue.length,ut=ke.length,N=0,Ke+=2,Z=s(O/(ke[0]+1)),Z>1&&(ke=g(ke,Z,O),Ue=g(Ue,Z,O),ut=ke.length,dn=Ue.length),fn=ut,we=Ue.slice(0,ut),Se=we.length;Se<ut;we[Se++]=0);ir=ke.slice(),ir=[0].concat(ir),hn=ke[0],ke[1]>=O/2&&hn++;do{if(Z=0,P=w(ke,we,ut,Se),P<0){if(Le=we[0],ut!=Se&&(Le=Le*O+(we[1]||0)),Z=s(Le/hn),Z>1)for(Z>=O&&(Z=O-1),ee=g(ke,Z,O),Ee=ee.length,Se=we.length;w(ee,we,Ee,Se)==1;)Z--,k(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)),k(we,ee,Se,O),Se=we.length,P==-1)for(;w(ke,we,ut,Se)<1;)Z++,k(we,ut<Se?ir:ke,Se,O),Se=we.length}else P===0&&(Z++,we=[0]);Ne[N++]=Z,we[0]?we[Se++]=Ue[fn]||0:(we=[Ue[fn]],Se=1)}while((fn++<dn||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(xe,I+(xe.e=N+j*l-1)+1,L,z)}else xe.e=j,xe.r=+z;return xe}})();function le(g,w,k,B){var F,I,L,O,P;if(k==null?k=ae:m(k,0,8),!g.c)return g.toString();if(F=g.c[0],L=g.e,w==null)P=_(g.c),P=B==1||B==2&&(L<=fe||L>=ye)?C(P,L):E(P,L,"0");else if(g=Re(new W(g),w,k),I=g.e,P=_(g.c),O=P.length,B==1||B==2&&(w<=I||I<=fe)){for(;O<w;P+="0",O++);P=C(P,I)}else if(w-=L+(B===2&&I>L),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 g.s<0&&F?"-"+P:P}function _e(g,w){for(var k,B,F=1,I=new W(g[0]);F<g.length;F++)B=new W(g[F]),(!B.s||(k=y(I,B))===w||k===0&&I.s===w)&&(I=B);return I}function Ft(g,w,k){for(var B=1,F=w.length;!w[--F];w.pop());for(F=w[0];F>=10;F/=10,B++);return(k=B+k*l-1)>oe?g.c=g.e=null:k<Ae?g.c=[g.e=0]:(g.e=k,g.c=w),g}V=(function(){var g=/^(-?)0([xbo])(?=\w[\w.]*$)/i,w=/^([^.]+)\.$/,k=/^\.([^.]+)$/,B=/^-?(Infinity|NaN)$/,F=/^\s*\+(?=[\w.])|^\s+|\s+$/g;return function(I,L,O,P){var j,N=O?L:L.replace(F,"");if(B.test(N))I.s=isNaN(N)?null:N<0?-1:1;else{if(!O&&(N=N.replace(g,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(k,"0.$1")),L!=N))return new W(N,j);if(W.DEBUG)throw Error(i+"Not a"+(P?" base "+P:"")+" number: "+L);I.s=null}I.c=I.e=null}})();function Re(g,w,k,B){var F,I,L,O,P,j,N,z=g.c,Z=d;if(z){e:{for(F=1,O=z[0];O>=10;O/=10,F++);if(I=w-F,I<0)I+=l,L=w,P=z[j=0],N=s(P/Z[F-L-1]%10);else if(j=n((I+1)/l),j>=z.length)if(B){for(;z.length<=j;z.push(0));P=N=0,F=1,I%=l,L=I-l+1}else break e;else{for(P=O=z[j],F=1;O>=10;O/=10,F++);I%=l,L=I-l+F,N=L<0?0:s(P/Z[F-L-1]%10)}if(B=B||w<0||z[j+1]!=null||(L<0?P:P%Z[F-L-1]),B=k<4?(N||B)&&(k==0||k==(g.s<0?3:2)):N>5||N==5&&(k==4||B||k==6&&(I>0?L>0?P/Z[F-L]:0:z[j-1])%10&1||k==(g.s<0?8:7)),w<1||!z[0])return z.length=0,B?(w-=g.e+1,z[0]=Z[(l-w%l)%l],g.e=-w||0):z[0]=g.e=0,g;if(I==0?(z.length=j,O=1,j--):(z.length=j+1,O=Z[l-I],z[j]=L>0?s(P/Z[F-L]%Z[L])*O:0),B)for(;;)if(j==0){for(I=1,L=z[0];L>=10;L/=10,I++);for(L=z[0]+=O,O=1;L>=10;L/=10,O++);I!=O&&(g.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());}g.e>oe?g.c=g.e=null:g.e<Ae&&(g.c=[g.e=0])}return g}function Be(g){var w,k=g.e;return k===null?g.toString():(w=_(g.c),w=k<=fe||k>=ye?C(w,k):E(w,k,"0"),g.s<0?"-"+w:w)}return U.absoluteValue=U.abs=function(){var g=new W(this);return g.s<0&&(g.s=1),g},U.comparedTo=function(g,w){return y(this,new W(g,w))},U.decimalPlaces=U.dp=function(g,w){var k,B,F,I=this;if(g!=null)return m(g,0,A),w==null?w=ae:m(w,0,8),Re(new W(I),g+I.e+1,w);if(!(k=I.c))return null;if(B=((F=k.length-1)-S(this.e/l))*l,F=k[F])for(;F%10==0;F/=10,B--);return B<0&&(B=0),B},U.dividedBy=U.div=function(g,w){return x(this,new W(g,w),ne,ae)},U.dividedToIntegerBy=U.idiv=function(g,w){return x(this,new W(g,w),0,1)},U.exponentiatedBy=U.pow=function(g,w){var k,B,F,I,L,O,P,j,N,z=this;if(g=new W(g),g.c&&!g.isInteger())throw Error(i+"Exponent not an integer: "+Be(g));if(w!=null&&(w=new W(w)),O=g.e>14,!z.c||!z.c[0]||z.c[0]==1&&!z.e&&z.c.length==1||!g.c||!g.c[0])return N=new W(Math.pow(+Be(z),O?g.s*(2-D(g)):+Be(g))),w?N.mod(w):N;if(P=g.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(g.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&&D(g)?-0:0,z.e>-1&&(I=1/I),new W(P?1/I:I);K&&(I=n(K/l+2))}for(O?(k=new W(.5),P&&(g.s=1),j=D(g)):(F=Math.abs(+Be(g)),j=F%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(w))}if(F){if(F=s(F/2),F===0)break;j=F%2}else if(g=g.times(k),Re(g,g.e+1,1),g.e>14)j=D(g);else{if(F=+Be(g),F===0)break;j=F%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=Q.div(N)),w?N.mod(w):I?Re(N,K,ae,L):N)},U.integerValue=function(g){var w=new W(this);return g==null?g=ae:m(g,0,8),Re(w,w.e+1,g)},U.isEqualTo=U.eq=function(g,w){return y(this,new W(g,w))===0},U.isFinite=function(){return!!this.c},U.isGreaterThan=U.gt=function(g,w){return y(this,new W(g,w))>0},U.isGreaterThanOrEqualTo=U.gte=function(g,w){return(w=y(this,new W(g,w)))===1||w===0},U.isInteger=function(){return!!this.c&&S(this.e/l)>this.c.length-2},U.isLessThan=U.lt=function(g,w){return y(this,new W(g,w))<0},U.isLessThanOrEqualTo=U.lte=function(g,w){return(w=y(this,new W(g,w)))===-1||w===0},U.isNaN=function(){return!this.s},U.isNegative=function(){return this.s<0},U.isPositive=function(){return this.s>0},U.isZero=function(){return!!this.c&&this.c[0]==0},U.minus=function(g,w){var k,B,F,I,L=this,O=L.s;if(g=new W(g,w),w=g.s,!O||!w)return new W(NaN);if(O!=w)return g.s=-w,L.plus(g);var P=L.e/l,j=g.e/l,N=L.c,z=g.c;if(!P||!j){if(!N||!z)return N?(g.s=-w,g):new W(z?L:NaN);if(!N[0]||!z[0])return z[0]?(g.s=-w,g):new W(N[0]?L:ae==3?-0:0)}if(P=S(P),j=S(j),N=N.slice(),O=P-j){for((I=O<0)?(O=-O,F=N):(j=P,F=z),F.reverse(),w=O;w--;F.push(0));F.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&&(F=N,N=z,z=F,g.s=-g.s),w=(B=z.length)-(k=N.length),w>0)for(;w--;N[k++]=0);for(w=c-1;B>O;){if(N[--B]<z[B]){for(k=B;k&&!N[--k];N[k]=w);--N[k],N[B]+=c}N[B]-=z[B]}for(;N[0]==0;N.splice(0,1),--j);return N[0]?Ft(g,N,j):(g.s=ae==3?-1:1,g.c=[g.e=0],g)},U.modulo=U.mod=function(g,w){var k,B,F=this;return g=new W(g,w),!F.c||!g.s||g.c&&!g.c[0]?new W(NaN):!g.c||F.c&&!F.c[0]?new W(F):(G==9?(B=g.s,g.s=1,k=x(F,g,0,3),g.s=B,k.s*=B):k=x(F,g,0,G),g=F.minus(k.times(g)),!g.c[0]&&G==1&&(g.s=F.s),g)},U.multipliedBy=U.times=function(g,w){var k,B,F,I,L,O,P,j,N,z,Z,ee,Ee,xe,Ne,we=this,Se=we.c,Le=(g=new W(g,w)).c;if(!Se||!Le||!Se[0]||!Le[0])return!we.s||!g.s||Se&&!Se[0]&&!Le||Le&&!Le[0]&&!Se?g.c=g.e=g.s=null:(g.s*=we.s,!Se||!Le?g.c=g.e=null:(g.c=[0],g.e=0)),g;for(B=S(we.e/l)+S(g.e/l),g.s*=we.s,P=Se.length,z=Le.length,P<z&&(Ee=Se,Se=Le,Le=Ee,F=P,P=z,z=F),F=P+z,Ee=[];F--;Ee.push(0));for(xe=c,Ne=p,F=z;--F>=0;){for(k=0,Z=Le[F]%Ne,ee=Le[F]/Ne|0,L=P,I=F+L;I>F;)j=Se[--L]%Ne,N=Se[L]/Ne|0,O=ee*j+N*Z,j=Z*j+O%Ne*Ne+Ee[I]+k,k=(j/xe|0)+(O/Ne|0)+ee*N,Ee[I--]=j%xe;Ee[I]=k}return k?++B:Ee.splice(0,1),Ft(g,Ee,B)},U.negated=function(){var g=new W(this);return g.s=-g.s||null,g},U.plus=function(g,w){var k,B=this,F=B.s;if(g=new W(g,w),w=g.s,!F||!w)return new W(NaN);if(F!=w)return g.s=-w,B.minus(g);var I=B.e/l,L=g.e/l,O=B.c,P=g.c;if(!I||!L){if(!O||!P)return new W(F/0);if(!O[0]||!P[0])return P[0]?g:new W(O[0]?B:F*0)}if(I=S(I),L=S(L),O=O.slice(),F=I-L){for(F>0?(L=I,k=P):(F=-F,k=O),k.reverse();F--;k.push(0));k.reverse()}for(F=O.length,w=P.length,F-w<0&&(k=P,P=O,O=k,w=F),F=0;w;)F=(O[--w]=O[w]+P[w]+F)/c|0,O[w]=c===O[w]?0:O[w]%c;return F&&(O=[F].concat(O),++L),Ft(g,O,L)},U.precision=U.sd=function(g,w){var k,B,F,I=this;if(g!=null&&g!==!!g)return m(g,1,A),w==null?w=ae:m(w,0,8),Re(new W(I),g,w);if(!(k=I.c))return null;if(F=k.length-1,B=F*l+1,F=k[F]){for(;F%10==0;F/=10,B--);for(F=k[0];F>=10;F/=10,B++);}return g&&I.e+1>B&&(B=I.e+1),B},U.shiftedBy=function(g){return m(g,-h,h),this.times("1e"+g)},U.squareRoot=U.sqrt=function(){var g,w,k,B,F,I=this,L=I.c,O=I.s,P=I.e,j=ne+4,N=new W("0.5");if(O!==1||!L||!L[0])return new W(!O||O<0&&(!L||L[0])?NaN:L?I:1/0);if(O=Math.sqrt(+Be(I)),O==0||O==1/0?(w=_(L),(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),k=new W(w)):k=new W(O+""),k.c[0]){for(P=k.e,O=P+j,O<3&&(O=0);;)if(F=k,k=N.times(F.plus(x(I,F,j,1))),_(F.c).slice(0,O)===(w=_(k.c)).slice(0,O))if(k.e<P&&--O,w=w.slice(O-3,O+1),w=="9999"||!B&&w=="4999"){if(!B&&(Re(F,F.e+ne+2,0),F.times(F).eq(I))){k=F;break}j+=4,O+=4,B=1}else{(!+w||!+w.slice(1)&&w.charAt(0)=="5")&&(Re(k,k.e+ne+2,1),g=!k.times(k).eq(I));break}}return Re(k,k.e+ne+1,ae,g)},U.toExponential=function(g,w){return g!=null&&(m(g,0,A),g++),le(this,g,w,1)},U.toFixed=function(g,w){return g!=null&&(m(g,0,A),g=g+this.e+1),le(this,g,w)},U.toFormat=function(g,w,k){var B,F=this;if(k==null)g!=null&&w&&typeof w=="object"?(k=w,w=null):g&&typeof g=="object"?(k=g,g=w=null):k=ue;else if(typeof k!="object")throw Error(i+"Argument not an object: "+k);if(B=F.toFixed(g,w),F.c){var I,L=B.split("."),O=+k.groupSize,P=+k.secondaryGroupSize,j=k.groupSeparator||"",N=L[0],z=L[1],Z=F.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+(k.decimalSeparator||"")+((P=+k.fractionGroupSize)?z.replace(new RegExp("\\d{"+P+"}\\B","g"),"$&"+(k.fractionGroupSeparator||"")):z):N}return(k.prefix||"")+B+(k.suffix||"")},U.toFraction=function(g){var w,k,B,F,I,L,O,P,j,N,z,Z,ee=this,Ee=ee.c;if(g!=null&&(O=new W(g),!O.isInteger()&&(O.c||O.s!==1)||O.lt(Q)))throw Error(i+"Argument "+(O.isInteger()?"out of range: ":"not an integer: ")+Be(O));if(!Ee)return new W(ee);for(w=new W(Q),j=k=new W(Q),B=P=new W(Q),Z=_(Ee),I=w.e=Z.length-ee.e-1,w.c[0]=d[(L=I%l)<0?l+L:L],g=!g||O.comparedTo(w)>0?I>0?w:j:O,L=oe,oe=1/0,O=new W(Z),P.c[0]=0;N=x(O,w,0,1),F=k.plus(N.times(B)),F.comparedTo(g)!=1;)k=B,B=F,j=P.plus(N.times(F=j)),P=F,w=O.minus(N.times(F=w)),O=F;return F=x(g.minus(k),B,0,1),P=P.plus(F.times(j)),k=k.plus(F.times(B)),P.s=j.s=ee.s,I=I*2,z=x(j,B,I,ae).minus(ee).abs().comparedTo(x(P,k,I,ae).minus(ee).abs())<1?[j,B]:[P,k],oe=L,z},U.toNumber=function(){return+Be(this)},U.toPrecision=function(g,w){return g!=null&&m(g,1,A),le(this,g,w,2)},U.toString=function(g){var w,k=this,B=k.s,F=k.e;return F===null?B?(w="Infinity",B<0&&(w="-"+w)):w="NaN":(g==null?w=F<=fe||F>=ye?C(_(k.c),F):E(_(k.c),F,"0"):g===10&&Te?(k=Re(new W(k),ne+F+1,ae),w=E(_(k.c),k.e,"0")):(m(g,2,Me.length,"Base"),w=$(E(_(k.c),F,"0"),10,g,B,!0)),B<0&&k.c[0]&&(w="-"+w)),w},U.valueOf=U.toJSON=function(){return Be(this)},U._isBigNumber=!0,v!=null&&W.set(v),W}function S(v){var x=v|0;return v>0||v===x?x:x-1}function _(v){for(var x,$,V=1,U=v.length,Q=v[0]+"";V<U;){for(x=v[V++]+"",$=l-x.length;$--;x="0"+x);Q+=x}for(U=Q.length;Q.charCodeAt(--U)===48;);return Q.slice(0,U+1||1)}function y(v,x){var $,V,U=v.c,Q=x.c,ne=v.s,ae=x.s,fe=v.e,ye=x.e;if(!ne||!ae)return null;if($=U&&!U[0],V=Q&&!Q[0],$||V)return $?V?0:-ae:ne;if(ne!=ae)return ne;if($=ne<0,V=fe==ye,!U||!Q)return V?0:!U^$?1:-1;if(!V)return fe>ye^$?1:-1;for(ae=(fe=U.length)<(ye=Q.length)?fe:ye,ne=0;ne<ae;ne++)if(U[ne]!=Q[ne])return U[ne]>Q[ne]^$?1:-1;return fe==ye?0:fe>ye^$?1:-1}function m(v,x,$,V){if(v<x||v>$||v!==s(v))throw Error(i+(V||"Argument")+(typeof v=="number"?v<x||v>$?" out of range: ":" not an integer: ":" not a primitive number: ")+String(v))}function D(v){var x=v.c.length-1;return S(v.e/l)==x&&v.c[x]%2!=0}function C(v,x){return(v.length>1?v.charAt(0)+"."+v.slice(1):v)+(x<0?"e":"e+")+x}function E(v,x,$){var V,U;if(x<0){for(U=$+".";++x;U+=$);v=U+v}else if(V=v.length,++x>V){for(U=$,x-=V;--x;U+=$);v+=U}else x<V&&(v=v.slice(0,x)+"."+v.slice(x));return v}e=R(),e.default=e.BigNumber=e,typeof define=="function"&&define.amd?define(function(){return e}):typeof hi<"u"&&hi.exports?hi.exports=e:(t||(t=typeof self<"u"&&self?self:window),t.BigNumber=e)})(Op)});var Ip=J((TR,Pp)=>{var Fp=Xu(),xp=Pp.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,R,S,_=n,y,m=d[h],D=m!=null&&(m instanceof Fp||Fp.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 D?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,y=[],Object.prototype.toString.apply(m)==="[object Array]"){for(S=m.length,p=0;p<S;p+=1)y[p]=l(p,m)||"null";return R=y.length===0?"[]":n?`[
44
44
  `+n+y.join(`,
45
45
  `+n)+`
46
46
  `+_+"]":"["+y.join(",")+"]",n=_,R}if(u&&typeof u=="object")for(S=u.length,p=0;p<S;p+=1)typeof u[p]=="string"&&(A=u[p],R=l(A,m),R&&y.push(c(A)+(n?": ":":")+R));else Object.keys(m).forEach(function(C){var E=l(C,m);E&&y.push(c(C)+(n?": ":":")+E)});return R=y.length===0?"{}":n?`{
47
47
  `+n+y.join(`,
48
48
  `+n)+`
49
- `+_+"}":"{"+y.join(",")+"}",n=_,R}}typeof Fp.stringify!="function"&&(Fp.stringify=function(h,d,p){var A;if(n="",s="",typeof p=="number")for(A=0;A<p;A+=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 Np=J((TR,Ip)=>{var pi=null,TC=/(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])/,vC=/(?: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)/,RC=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(_){throw{name:"SyntaxError",message:_,at:r,text:i}},c=function(_){return _&&_!==n&&u("Expected '"+_+"' instead of '"+n+"'"),n=i.charAt(r),r+=1,n},l=function(){var _,y="";for(n==="-"&&(y="-",c("-"));n>="0"&&n<="9";)y+=n,c();if(n===".")for(y+=".";c()&&n>="0"&&n<="9";)y+=n;if(n==="e"||n==="E")for(y+=n,c(),(n==="-"||n==="+")&&(y+=n,c());n>="0"&&n<="9";)y+=n,c();if(_=+y,!isFinite(_))u("Bad number");else return pi==null&&(pi=Yu()),y.length>15?e.storeAsString?y:e.useNativeBigInt?BigInt(y):new pi(y):e.alwaysParseAsBig?e.useNativeBigInt?BigInt(_):new pi(_):_},h=function(){var _,y,m="",D;if(n==='"')for(var C=r;c();){if(n==='"')return r-1>C&&(m+=i.substring(C,r-1)),c(),m;if(n==="\\"){if(r-1>C&&(m+=i.substring(C,r-1)),c(),n==="u"){for(D=0,y=0;y<4&&(_=parseInt(c(),16),!!isFinite(_));y+=1)D=D*16+_;m+=String.fromCharCode(D)}else if(typeof s[n]=="string")m+=s[n];else break;C=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,R=function(){var _=[];if(n==="["){if(c("["),d(),n==="]")return c("]"),_;for(;n;){if(_.push(A()),d(),n==="]")return c("]"),_;c(","),d()}}u("Bad array")},S=function(){var _,y=Object.create(null);if(n==="{"){if(c("{"),d(),n==="}")return c("}"),y;for(;n;){if(_=h(),d(),c(":"),e.strict===!0&&Object.hasOwnProperty.call(y,_)&&u('Duplicate key "'+_+'"'),TC.test(_)===!0?e.protoAction==="error"?u("Object contains forbidden prototype property"):e.protoAction==="ignore"?A():y[_]=A():vC.test(_)===!0?e.constructorAction==="error"?u("Object contains forbidden constructor property"):e.constructorAction==="ignore"?A():y[_]=A():y[_]=A(),d(),n==="}")return c("}"),y;c(","),d()}}u("Bad object")};return A=function(){switch(d(),n){case"{":return S();case"[":return R();case'"':return h();case"-":return l();default:return n>="0"&&n<="9"?l():p()}},function(_,y){var m;return i=_+"",r=0,n=" ",m=A(),d(),n&&u("Syntax error"),typeof y=="function"?(function D(C,E){var v,x,$=C[E];return $&&typeof $=="object"&&Object.keys($).forEach(function(V){x=D($,V),x!==void 0?$[V]=x:delete $[V]}),y.call(C,E,$)})({"":m},""):m}};Ip.exports=RC});var qp=J((vR,mi)=>{var Bp=Pp().stringify,jp=Np();mi.exports=function(t){return{parse:jp(t),stringify:Bp}};mi.exports.parse=jp();mi.exports.stringify=Bp});var Xu=J(qt=>{"use strict";Object.defineProperty(qt,"__esModule",{value:!0});qt.GCE_LINUX_BIOS_PATHS=void 0;qt.isGoogleCloudServerless=Mp;qt.isGoogleComputeEngineLinux=$p;qt.isGoogleComputeEngineMACAddress=zp;qt.isGoogleComputeEngine=Hp;qt.detectGCPResidency=FC;var Lp=X("fs"),Up=X("os");qt.GCE_LINUX_BIOS_PATHS={BIOS_DATE:"/sys/class/dmi/id/bios_date",BIOS_VENDOR:"/sys/class/dmi/id/bios_vendor"};var OC=/^42:01/;function Mp(){return!!(process.env.CLOUD_RUN_JOB||process.env.FUNCTION_NAME||process.env.K_SERVICE)}function $p(){if((0,Up.platform)()!=="linux")return!1;try{(0,Lp.statSync)(qt.GCE_LINUX_BIOS_PATHS.BIOS_DATE);let t=(0,Lp.readFileSync)(qt.GCE_LINUX_BIOS_PATHS.BIOS_VENDOR,"utf8");return/Google/.test(t)}catch{return!1}}function zp(){let t=(0,Up.networkInterfaces)();for(let e of Object.values(t))if(e){for(let{mac:r}of e)if(OC.test(r))return!0}return!1}function Hp(){return $p()||zp()}function FC(){return Mp()||Hp()}});var Wp=J(gi=>{"use strict";Object.defineProperty(gi,"__esModule",{value:!0});gi.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="")}};gi.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 Kp=J(De=>{"use strict";var xC=De&&De.__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]})),PC=De&&De.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),Gp=De&&De.__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"&&xC(r,e,n[s]);return PC(r,e),r}})();Object.defineProperty(De,"__esModule",{value:!0});De.env=De.DebugLogBackendBase=De.placeholder=De.AdhocDebugLogger=De.LogSeverity=void 0;De.getNodeBackend=Zu;De.getDebugBackend=NC;De.getStructuredBackend=BC;De.setBackend=jC;De.log=Vp;var IC=X("events"),Ds=Gp(X("process")),Jp=Gp(X("util")),dt=Wp(),Lt;(function(t){t.DEFAULT="DEFAULT",t.DEBUG="DEBUG",t.INFO="INFO",t.WARNING="WARNING",t.ERROR="ERROR"})(Lt||(De.LogSeverity=Lt={}));var Ts=class extends IC.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(Lt.DEBUG,...n),this.func.info=(...n)=>this.invokeSeverity(Lt.INFO,...n),this.func.warn=(...n)=>this.invokeSeverity(Lt.WARNING,...n),this.func.error=(...n)=>this.invokeSeverity(Lt.ERROR,...n),this.func.sublog=n=>Vp(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)}};De.AdhocDebugLogger=Ts;De.placeholder=new Ts("",()=>{}).func;var qn=class{constructor(){var e;this.cached=new Map,this.filters=[],this.filtersSet=!1;let r=(e=Ds.env[De.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)}}};De.DebugLogBackendBase=qn;var Qu=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}${Ds.pid}${dt.Colours.reset}`,c;switch(r.severity){case Lt.ERROR:c=`${dt.Colours.red}${r.severity}${dt.Colours.reset}`;break;case Lt.INFO:c=`${dt.Colours.magenta}${r.severity}${dt.Colours.reset}`;break;case Lt.WARNING:c=`${dt.Colours.yellow}${r.severity}${dt.Colours.reset}`;break;default:c=(s=r.severity)!==null&&s!==void 0?s:Lt.DEFAULT;break}let l=Jp.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 Zu(){return new Qu}var ec=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=Ds.env.NODE_DEBUG)!==null&&e!==void 0?e:"";Ds.env.NODE_DEBUG=`${r}${r?",":""}${this.filters.join(",")}`}};function NC(t){return new ec(t)}var tc=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:Lt.INFO,l=Object.assign({severity:c,message:Jp.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 BC(t){return new tc(t)}De.env={nodeEnables:"GOOGLE_SDK_NODE_LOGGING"};var rc=new Map,ht;function jC(t){ht=t,rc.clear()}function Vp(t,e){if(!ht&&!Ds.env[De.env.nodeEnables]||!t)return De.placeholder;e&&(t=`${e.instance.namespace}:${t}`);let r=rc.get(t);if(r)return r.func;if(ht===null)return De.placeholder;ht===void 0&&(ht=Zu());let n=(()=>{let s;return new Ts(t,(u,...c)=>{if(s!==ht){if(ht===null)return;ht===void 0&&(ht=Zu()),s=ht}ht?.log(t,u,...c)})})();return rc.set(t,n),n.func}});var nc=J(on=>{"use strict";var qC=on&&on.__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]})),LC=on&&on.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&qC(e,t,r)};Object.defineProperty(on,"__esModule",{value:!0});LC(Kp(),on)});var Rs=J(ie=>{"use strict";var Xp=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]})),UC=ie&&ie.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),MC=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"&&Xp(r,e,n[s]);return UC(r,e),r}})(),$C=ie&&ie.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&Xp(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=VC;ie.project=KC;ie.universe=YC;ie.bulk=XC;ie.isAvailable=ZC;ie.resetIsAvailableCache=ew;ie.getGCPResidency=ic;ie.setGCPResidency=Qp;ie.requestTimeout=Zp;var sc=Ve(),zC=qp(),HC=Xu(),WC=MC(nc());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 Yp=WC.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 oc(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 GC(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 vs(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,R)=>s.set(R,A)),i=p.metadataKey,u=p.params||u,r=p.noResponseRetries||r,n=p.fastFail||n}else i=t;typeof e=="string"?i+=`/${e}`:(GC(e),e.property&&(i+=`/${e.property}`),new Headers(e.headers).forEach((p,A)=>s.set(A,p)),u=e.params||u);let c=n?JC:sc.request,l={url:`${oc()}/${i}`,headers:s,retryConfig:{noResponseRetries:r},params:u,responseType:"text",timeout:Zp()};Yp.info("instance request %j",l);let h=await c(l);Yp.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 zC.parse(h.data)}catch{}return h.data}async function JC(t){let e={...t,url:t.url?.toString().replace(oc(),oc(ie.SECONDARY_HOST_ADDRESS))},r=(0,sc.request)(t),n=(0,sc.request)(e);return Promise.any([r,n])}function VC(t){return vs("instance",t)}function KC(t){return vs("project",t)}function YC(t){return vs("universe",t)}async function XC(t){let e={};return await Promise.all(t.map(r=>(async()=>{let n=await vs(r),s=r.metadataKey;e[s]=n})())),e}function QC(){return process.env.DETECT_GCP_RETRIES?Number(process.env.DETECT_GCP_RETRIES):0}var yi;async function ZC(){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 ic();case"ping-only":}}try{return yi===void 0&&(yi=vs("instance",void 0,QC(),!(process.env.GCE_METADATA_IP||process.env.GCE_METADATA_HOST))),await yi,!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 ew(){yi=void 0}ie.gcpResidencyCache=null;function ic(){return ie.gcpResidencyCache===null&&Qp(),ie.gcpResidencyCache}function Qp(t=null){ie.gcpResidencyCache=t!==null?t:(0,HC.detectGCPResidency)()}function Zp(){return ic()?0:3e3}$C(Xu(),ie)});var rm=J(_i=>{"use strict";_i.byteLength=rw;_i.toByteArray=sw;_i.fromByteArray=aw;var Yt=[],kt=[],tw=typeof Uint8Array<"u"?Uint8Array:Array,ac="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(an=0,em=ac.length;an<em;++an)Yt[an]=ac[an],kt[ac.charCodeAt(an)]=an;var an,em;kt[45]=62;kt[95]=63;function tm(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 rw(t){var e=tm(t),r=e[0],n=e[1];return(r+n)*3/4-n}function nw(t,e,r){return(e+r)*3/4-r}function sw(t){var e,r=tm(t),n=r[0],s=r[1],i=new tw(nw(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 ow(t){return Yt[t>>18&63]+Yt[t>>12&63]+Yt[t>>6&63]+Yt[t&63]}function iw(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(ow(n));return s.join("")}function aw(t){for(var e,r=t.length,n=r%3,s=[],i=16383,u=0,c=r-n;u<c;u+=i)s.push(iw(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 cc=J(uc=>{"use strict";Object.defineProperty(uc,"__esModule",{value:!0});uc.fromArrayBufferToHex=uw;function uw(t){return Array.from(new Uint8Array(t)).map(r=>r.toString(16).padStart(2,"0")).join("")}});var nm=J(bi=>{"use strict";Object.defineProperty(bi,"__esModule",{value:!0});bi.BrowserCrypto=void 0;var Ln=rm(),cw=cc(),lc=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 Ln.fromByteArray(new Uint8Array(n))}randomBytesBase64(e){let r=new Uint8Array(e);return window.crypto.getRandomValues(r),Ln.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=Ln.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 Ln.fromByteArray(new Uint8Array(u))}decodeBase64StringUtf8(e){let r=Ln.toByteArray(t.padBase64(e));return new TextDecoder().decode(r)}encodeBase64StringUtf8(e){let r=new TextEncoder().encode(e);return Ln.fromByteArray(r)}async sha256DigestHex(e){let r=new TextEncoder().encode(e),n=await window.crypto.subtle.digest("SHA-256",r);return(0,cw.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))}};bi.BrowserCrypto=lc});var sm=J(Ci=>{"use strict";Object.defineProperty(Ci,"__esModule",{value:!0});Ci.NodeCrypto=void 0;var Un=X("crypto"),fc=class{async sha256DigestBase64(e){return Un.createHash("sha256").update(e).digest("base64")}randomBytesBase64(e){return Un.randomBytes(e).toString("base64")}async verify(e,r,n){let s=Un.createVerify("RSA-SHA256");return s.update(r),s.end(),s.verify(e,n,"base64")}async sign(e,r){let n=Un.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 Un.createHash("sha256").update(e).digest("hex")}async signWithHmacSha256(e,r){let n=typeof e=="string"?e:fw(e);return lw(Un.createHmac("sha256",n).update(r).digest())}};Ci.NodeCrypto=fc;function lw(t){return t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength)}function fw(t){return Buffer.from(t)}});var Os=J(yr=>{"use strict";var dw=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]})),hw=yr&&yr.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&dw(e,t,r)};Object.defineProperty(yr,"__esModule",{value:!0});yr.createCrypto=gw;yr.hasBrowserCrypto=om;var pw=nm(),mw=sm();hw(cc(),yr);function gw(){return om()?new pw.BrowserCrypto:new mw.NodeCrypto}function om(){return typeof window<"u"&&typeof window.crypto<"u"&&typeof window.crypto.subtle<"u"}});var Mn=J((dc,am)=>{var wi=X("buffer"),Xt=wi.Buffer;function im(t,e){for(var r in t)e[r]=t[r]}Xt.from&&Xt.alloc&&Xt.allocUnsafe&&Xt.allocUnsafeSlow?am.exports=wi:(im(wi,dc),dc.Buffer=un);function un(t,e,r){return Xt(t,e,r)}un.prototype=Object.create(Xt.prototype);im(Xt,un);un.from=function(t,e,r){if(typeof t=="number")throw new TypeError("Argument must not be a number");return Xt(t,e,r)};un.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};un.allocUnsafe=function(t){if(typeof t!="number")throw new TypeError("Argument must be a number");return Xt(t)};un.allocUnsafeSlow=function(t){if(typeof t!="number")throw new TypeError("Argument must be a number");return wi.SlowBuffer(t)}});var cm=J((LR,um)=>{"use strict";function hc(t){var e=(t/8|0)+(t%8===0?0:1);return e}var yw={ES256:hc(256),ES384:hc(384),ES512:hc(521)};function _w(t){var e=yw[t];if(e)return e;throw new Error('Unknown algorithm "'+t+'"')}um.exports=_w});var pc=J((UR,mm)=>{"use strict";var Ei=Mn().Buffer,fm=cm(),Ai=128,dm=0,bw=32,Cw=16,ww=2,hm=Cw|bw|dm<<6,Si=ww|dm<<6;function Ew(t){return t.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function pm(t){if(Ei.isBuffer(t))return t;if(typeof t=="string")return Ei.from(t,"base64");throw new TypeError("ECDSA signature must be a Base64 string or a Buffer")}function Aw(t,e){t=pm(t);var r=fm(e),n=r+1,s=t.length,i=0;if(t[i++]!==hm)throw new Error('Could not find expected "seq"');var u=t[i++];if(u===(Ai|1)&&(u=t[i++]),s-i<u)throw new Error('"seq" specified length of "'+u+'", only "'+(s-i)+'" remaining');if(t[i++]!==Si)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++]!==Si)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,R=Ei.allocUnsafe(p+c+A+h);for(i=0;i<p;++i)R[i]=0;t.copy(R,i,l+Math.max(-p,0),l+c),i=r;for(var S=i;i<S+A;++i)R[i]=0;return t.copy(R,i,d+Math.max(-A,0),d+h),R=R.toString("base64"),R=Ew(R),R}function lm(t,e,r){for(var n=0;e+n<r&&t[e+n]===0;)++n;var s=t[e+n]>=Ai;return s&&--n,n}function Sw(t,e){t=pm(t);var r=fm(e),n=t.length;if(n!==r*2)throw new TypeError('"'+e+'" signatures must be "'+r*2+'" bytes, saw "'+n+'"');var s=lm(t,0,r),i=lm(t,r,t.length),u=r-s,c=r-i,l=2+u+1+1+c,h=l<Ai,d=Ei.allocUnsafe((h?2:3)+l),p=0;return d[p++]=hm,h?d[p++]=l:(d[p++]=Ai|1,d[p++]=l&255),d[p++]=Si,d[p++]=u,s<0?(d[p++]=0,p+=t.copy(d,p,0,r)):p+=t.copy(d,p,s,r),d[p++]=Si,d[p++]=c,i<0?(d[p++]=0,t.copy(d,p,r)):t.copy(d,p,r+i),d}mm.exports={derToJose:Aw,joseToDer:Sw}});var Ut=J(_r=>{"use strict";Object.defineProperty(_r,"__esModule",{value:!0});_r.LRUCache=void 0;_r.snakeToCamel=ym;_r.originalOrCamelOptions=vw;_r.removeUndefinedValuesInObject=Rw;_r.isValidFile=Ow;_r.getWellKnownCertificateConfigFileLocation=Fw;var kw=X("fs"),Dw=X("os"),mc=X("path"),Tw="certificate_config.json",gm="gcloud";function ym(t){return t.replace(/([_][^_])/g,e=>e.slice(1).toUpperCase())}function vw(t){function e(r){let n=t||{};return n[r]??n[ym(r)]}return{get:e}}var gc=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=gc;function Rw(t){return Object.entries(t).forEach(([e,r])=>{(r===void 0||r==="undefined")&&delete t[e]}),t}async function Ow(t){try{return(await kw.promises.lstat(t)).isFile()}catch{return!1}}function Fw(){let t=process.env.CLOUDSDK_CONFIG||(xw()?mc.join(process.env.APPDATA||"",gm):mc.join(process.env.HOME||"",".config",gm));return mc.join(t,Tw)}function xw(){return Dw.platform().startsWith("win")}});var _m=J(($R,Pw)=>{Pw.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 yc=J(Ur=>{"use strict";Object.defineProperty(Ur,"__esModule",{value:!0});Ur.USER_AGENT=Ur.PRODUCT_NAME=Ur.pkg=void 0;var bm=_m();Ur.pkg=bm;var Cm="google-api-nodejs-client";Ur.PRODUCT_NAME=Cm;var Iw=`${Cm}/${bm.version}`;Ur.USER_AGENT=Iw});var pt=J(Mt=>{"use strict";Object.defineProperty(Mt,"__esModule",{value:!0});Mt.AuthClient=Mt.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS=Mt.DEFAULT_UNIVERSE=void 0;var Nw=X("events"),_c=Ve(),Bw=Ut(),jw=nc(),bc=yc();Mt.DEFAULT_UNIVERSE="googleapis.com";Mt.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS=300*1e3;var Cc=class t extends Nw.EventEmitter{apiKey;projectId;quotaProjectId;transporter;credentials={};eagerRefreshThresholdMillis=Mt.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS;forceRefreshOnFailure=!1;universeDomain=Mt.DEFAULT_UNIVERSE;static RequestMethodNameSymbol=Symbol("request method name");static RequestLogIdSymbol=Symbol("request log id");constructor(e={}){super();let r=(0,Bw.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")??Mt.DEFAULT_UNIVERSE,this.transporter=e.transporter??new _c.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&&_c.Gaxios.mergeHeaders(i,r.headers),n&&_c.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,jw.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(`${bc.PRODUCT_NAME}/`)||e.headers.set("User-Agent",`${r} ${bc.USER_AGENT}`):e.headers.set("User-Agent",bc.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"]}}}};Mt.AuthClient=Cc});var Ec=J(ki=>{"use strict";Object.defineProperty(ki,"__esModule",{value:!0});ki.LoginTicket=void 0;var wc=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()}}};ki.LoginTicket=wc});var cn=J(Qt=>{"use strict";Object.defineProperty(Qt,"__esModule",{value:!0});Qt.OAuth2Client=Qt.ClientAuthentication=Qt.CertificateFormat=Qt.CodeChallengeMethod=void 0;var wm=Ve(),qw=X("querystring"),Lw=X("stream"),Uw=pc(),Em=Ut(),Ac=Os(),$n=pt(),Mw=Ec(),Am;(function(t){t.Plain="plain",t.S256="S256"})(Am||(Qt.CodeChallengeMethod=Am={}));var br;(function(t){t.PEM="PEM",t.JWK="JWK"})(br||(Qt.CertificateFormat=br={}));var Fs;(function(t){t.ClientSecretPost="ClientSecretPost",t.ClientSecretBasic="ClientSecretBasic",t.None="None"})(Fs||(Qt.ClientAuthentication=Fs={}));var Sc=class t extends $n.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||Fs.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()+"?"+qw.stringify(e)}generateCodeVerifier(){throw new Error("generateCodeVerifier is removed, please use generateCodeVerifierAsync instead.")}async generateCodeVerifierAsync(){let e=(0,Ac.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===Fs.ClientSecretBasic){let l=Buffer.from(`${this._clientId}:${this._clientSecret}`);n.set("authorization",`Basic ${l.toString("base64")}`)}this.clientAuthentication===Fs.ClientSecretPost&&(s.client_secret=this._clientSecret);let i={...t.RETRY_CONFIG,method:"POST",url:r,data:new URLSearchParams((0,Em.removeUndefinedValuesInObject)(s)),headers:n};$n.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,Em.removeUndefinedValuesInObject)(n))};$n.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($n.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 Lw.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,Ac.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};$n.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};$n.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,Ac.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(C){throw C instanceof Error&&(C.message=`Can't parse token envelope: ${c[0]}': ${C.message}`),C}if(!d)throw new Error("Can't parse token envelope: "+c[0]);try{p=JSON.parse(u.decodeBase64StringUtf8(c[1]))}catch(C){throw C instanceof Error&&(C.message=`Can't parse token payload '${c[0]}`),C}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=Uw.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 _=Number(p.exp);if(isNaN(_))throw new Error("exp field using invalid format");let y=new Date().getTime()/1e3;if(_>=y+i)throw new Error("Expiration time too far in future: "+JSON.stringify(p));let m=S-t.CLOCK_SKEW_SECS_,D=_+t.CLOCK_SKEW_SECS_;if(y<m)throw new Error("Token used too early, "+y+" < "+m+": "+JSON.stringify(p));if(y>D)throw new Error("Token used too late, "+y+" > "+D+": "+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 C=p.aud,E=!1;if(n.constructor===Array?E=n.indexOf(C)>-1:E=C===n,!E)throw new Error("Wrong recipient, payload audience != requiredAudience")}return new Mw.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=Sc});var Dc=J(Di=>{"use strict";Object.defineProperty(Di,"__esModule",{value:!0});Di.Compute=void 0;var $w=Ve(),Sm=Rs(),zw=cn(),kc=class extends zw.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 Sm.instance(s)}catch(s){throw s instanceof $w.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 Sm.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))}};Di.Compute=kc});var vc=J(Ti=>{"use strict";Object.defineProperty(Ti,"__esModule",{value:!0});Ti.IdTokenClient=void 0;var Hw=cn(),Tc=class extends Hw.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}};Ti.IdTokenClient=Tc});var Rc=J(zn=>{"use strict";Object.defineProperty(zn,"__esModule",{value:!0});zn.GCPEnv=void 0;zn.clear=Ww;zn.getEnv=Gw;var km=Rs(),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||(zn.GCPEnv=Zt={}));var xs;function Ww(){xs=void 0}async function Gw(){return xs||(xs=Jw(),xs)}async function Jw(){let t=Zt.NONE;return Vw()?t=Zt.APP_ENGINE:Kw()?t=Zt.CLOUD_FUNCTIONS:await Zw()?await Qw()?t=Zt.KUBERNETES_ENGINE:Yw()?t=Zt.CLOUD_RUN:Xw()?t=Zt.CLOUD_RUN_JOBS:t=Zt.COMPUTE_ENGINE:t=Zt.NONE,t}function Vw(){return!!(process.env.GAE_SERVICE||process.env.GAE_MODULE_NAME)}function Kw(){return!!(process.env.FUNCTION_NAME||process.env.FUNCTION_TARGET)}function Yw(){return!!process.env.K_CONFIGURATION}function Xw(){return!!process.env.CLOUD_RUN_JOB}async function Qw(){try{return await km.instance("attributes/cluster-name"),!0}catch{return!1}}async function Zw(){return km.isAvailable()}});var Oc=J((YR,Dm)=>{var vi=Mn().Buffer,eE=X("stream"),tE=X("util");function Ri(t){if(this.buffer=null,this.writable=!0,this.readable=!0,!t)return this.buffer=vi.alloc(0),this;if(typeof t.pipe=="function")return this.buffer=vi.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+")")}tE.inherits(Ri,eE);Ri.prototype.write=function(e){this.buffer=vi.concat([this.buffer,vi.from(e)]),this.emit("data",e)};Ri.prototype.end=function(e){e&&this.write(e),this.emit("end",e),this.emit("close"),this.writable=!1,this.readable=!1};Dm.exports=Ri});var vm=J((XR,Tm)=>{"use strict";var Ps=X("buffer").Buffer,Fc=X("buffer").SlowBuffer;Tm.exports=Oi;function Oi(t,e){if(!Ps.isBuffer(t)||!Ps.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}Oi.install=function(){Ps.prototype.equal=Fc.prototype.equal=function(e){return Oi(this,e)}};var rE=Ps.prototype.equal,nE=Fc.prototype.equal;Oi.restore=function(){Ps.prototype.equal=rE,Fc.prototype.equal=nE}});var Nc=J((QR,jm)=>{var Wn=Mn().Buffer,Dt=X("crypto"),Om=pc(),Rm=X("util"),sE=`"%s" is not a valid algorithm.
49
+ `+_+"}":"{"+y.join(",")+"}",n=_,R}}typeof xp.stringify!="function"&&(xp.stringify=function(h,d,p){var A;if(n="",s="",typeof p=="number")for(A=0;A<p;A+=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 Bp=J((vR,Np)=>{var pi=null,vC=/(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])/,RC=/(?: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)/,OC=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(_){throw{name:"SyntaxError",message:_,at:r,text:i}},c=function(_){return _&&_!==n&&u("Expected '"+_+"' instead of '"+n+"'"),n=i.charAt(r),r+=1,n},l=function(){var _,y="";for(n==="-"&&(y="-",c("-"));n>="0"&&n<="9";)y+=n,c();if(n===".")for(y+=".";c()&&n>="0"&&n<="9";)y+=n;if(n==="e"||n==="E")for(y+=n,c(),(n==="-"||n==="+")&&(y+=n,c());n>="0"&&n<="9";)y+=n,c();if(_=+y,!isFinite(_))u("Bad number");else return pi==null&&(pi=Xu()),y.length>15?e.storeAsString?y:e.useNativeBigInt?BigInt(y):new pi(y):e.alwaysParseAsBig?e.useNativeBigInt?BigInt(_):new pi(_):_},h=function(){var _,y,m="",D;if(n==='"')for(var C=r;c();){if(n==='"')return r-1>C&&(m+=i.substring(C,r-1)),c(),m;if(n==="\\"){if(r-1>C&&(m+=i.substring(C,r-1)),c(),n==="u"){for(D=0,y=0;y<4&&(_=parseInt(c(),16),!!isFinite(_));y+=1)D=D*16+_;m+=String.fromCharCode(D)}else if(typeof s[n]=="string")m+=s[n];else break;C=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,R=function(){var _=[];if(n==="["){if(c("["),d(),n==="]")return c("]"),_;for(;n;){if(_.push(A()),d(),n==="]")return c("]"),_;c(","),d()}}u("Bad array")},S=function(){var _,y=Object.create(null);if(n==="{"){if(c("{"),d(),n==="}")return c("}"),y;for(;n;){if(_=h(),d(),c(":"),e.strict===!0&&Object.hasOwnProperty.call(y,_)&&u('Duplicate key "'+_+'"'),vC.test(_)===!0?e.protoAction==="error"?u("Object contains forbidden prototype property"):e.protoAction==="ignore"?A():y[_]=A():RC.test(_)===!0?e.constructorAction==="error"?u("Object contains forbidden constructor property"):e.constructorAction==="ignore"?A():y[_]=A():y[_]=A(),d(),n==="}")return c("}"),y;c(","),d()}}u("Bad object")};return A=function(){switch(d(),n){case"{":return S();case"[":return R();case'"':return h();case"-":return l();default:return n>="0"&&n<="9"?l():p()}},function(_,y){var m;return i=_+"",r=0,n=" ",m=A(),d(),n&&u("Syntax error"),typeof y=="function"?(function D(C,E){var v,x,$=C[E];return $&&typeof $=="object"&&Object.keys($).forEach(function(V){x=D($,V),x!==void 0?$[V]=x:delete $[V]}),y.call(C,E,$)})({"":m},""):m}};Np.exports=OC});var Lp=J((RR,mi)=>{var jp=Ip().stringify,qp=Bp();mi.exports=function(t){return{parse:qp(t),stringify:jp}};mi.exports.parse=qp();mi.exports.stringify=jp});var Qu=J(qt=>{"use strict";Object.defineProperty(qt,"__esModule",{value:!0});qt.GCE_LINUX_BIOS_PATHS=void 0;qt.isGoogleCloudServerless=$p;qt.isGoogleComputeEngineLinux=zp;qt.isGoogleComputeEngineMACAddress=Hp;qt.isGoogleComputeEngine=Wp;qt.detectGCPResidency=xC;var Up=X("fs"),Mp=X("os");qt.GCE_LINUX_BIOS_PATHS={BIOS_DATE:"/sys/class/dmi/id/bios_date",BIOS_VENDOR:"/sys/class/dmi/id/bios_vendor"};var FC=/^42:01/;function $p(){return!!(process.env.CLOUD_RUN_JOB||process.env.FUNCTION_NAME||process.env.K_SERVICE)}function zp(){if((0,Mp.platform)()!=="linux")return!1;try{(0,Up.statSync)(qt.GCE_LINUX_BIOS_PATHS.BIOS_DATE);let t=(0,Up.readFileSync)(qt.GCE_LINUX_BIOS_PATHS.BIOS_VENDOR,"utf8");return/Google/.test(t)}catch{return!1}}function Hp(){let t=(0,Mp.networkInterfaces)();for(let e of Object.values(t))if(e){for(let{mac:r}of e)if(FC.test(r))return!0}return!1}function Wp(){return zp()||Hp()}function xC(){return $p()||Wp()}});var Gp=J(gi=>{"use strict";Object.defineProperty(gi,"__esModule",{value:!0});gi.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="")}};gi.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 Yp=J(De=>{"use strict";var PC=De&&De.__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=De&&De.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),Jp=De&&De.__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"&&PC(r,e,n[s]);return IC(r,e),r}})();Object.defineProperty(De,"__esModule",{value:!0});De.env=De.DebugLogBackendBase=De.placeholder=De.AdhocDebugLogger=De.LogSeverity=void 0;De.getNodeBackend=ec;De.getDebugBackend=BC;De.getStructuredBackend=jC;De.setBackend=qC;De.log=Kp;var NC=X("events"),Ds=Jp(X("process")),Vp=Jp(X("util")),dt=Gp(),Lt;(function(t){t.DEFAULT="DEFAULT",t.DEBUG="DEBUG",t.INFO="INFO",t.WARNING="WARNING",t.ERROR="ERROR"})(Lt||(De.LogSeverity=Lt={}));var Ts=class extends NC.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(Lt.DEBUG,...n),this.func.info=(...n)=>this.invokeSeverity(Lt.INFO,...n),this.func.warn=(...n)=>this.invokeSeverity(Lt.WARNING,...n),this.func.error=(...n)=>this.invokeSeverity(Lt.ERROR,...n),this.func.sublog=n=>Kp(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)}};De.AdhocDebugLogger=Ts;De.placeholder=new Ts("",()=>{}).func;var qn=class{constructor(){var e;this.cached=new Map,this.filters=[],this.filtersSet=!1;let r=(e=Ds.env[De.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)}}};De.DebugLogBackendBase=qn;var Zu=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}${Ds.pid}${dt.Colours.reset}`,c;switch(r.severity){case Lt.ERROR:c=`${dt.Colours.red}${r.severity}${dt.Colours.reset}`;break;case Lt.INFO:c=`${dt.Colours.magenta}${r.severity}${dt.Colours.reset}`;break;case Lt.WARNING:c=`${dt.Colours.yellow}${r.severity}${dt.Colours.reset}`;break;default:c=(s=r.severity)!==null&&s!==void 0?s:Lt.DEFAULT;break}let l=Vp.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 ec(){return new Zu}var tc=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=Ds.env.NODE_DEBUG)!==null&&e!==void 0?e:"";Ds.env.NODE_DEBUG=`${r}${r?",":""}${this.filters.join(",")}`}};function BC(t){return new tc(t)}var rc=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:Lt.INFO,l=Object.assign({severity:c,message:Vp.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 jC(t){return new rc(t)}De.env={nodeEnables:"GOOGLE_SDK_NODE_LOGGING"};var nc=new Map,ht;function qC(t){ht=t,nc.clear()}function Kp(t,e){if(!ht&&!Ds.env[De.env.nodeEnables]||!t)return De.placeholder;e&&(t=`${e.instance.namespace}:${t}`);let r=nc.get(t);if(r)return r.func;if(ht===null)return De.placeholder;ht===void 0&&(ht=ec());let n=(()=>{let s;return new Ts(t,(u,...c)=>{if(s!==ht){if(ht===null)return;ht===void 0&&(ht=ec()),s=ht}ht?.log(t,u,...c)})})();return nc.set(t,n),n.func}});var sc=J(on=>{"use strict";var LC=on&&on.__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]})),UC=on&&on.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&LC(e,t,r)};Object.defineProperty(on,"__esModule",{value:!0});UC(Yp(),on)});var Rs=J(ie=>{"use strict";var Qp=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]})),MC=ie&&ie.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),$C=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"&&Qp(r,e,n[s]);return MC(r,e),r}})(),zC=ie&&ie.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&Qp(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=KC;ie.project=YC;ie.universe=XC;ie.bulk=QC;ie.isAvailable=ew;ie.resetIsAvailableCache=tw;ie.getGCPResidency=ac;ie.setGCPResidency=Zp;ie.requestTimeout=em;var oc=Ve(),HC=Lp(),WC=Qu(),GC=$C(sc());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 Xp=GC.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 ic(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 JC(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 vs(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,R)=>s.set(R,A)),i=p.metadataKey,u=p.params||u,r=p.noResponseRetries||r,n=p.fastFail||n}else i=t;typeof e=="string"?i+=`/${e}`:(JC(e),e.property&&(i+=`/${e.property}`),new Headers(e.headers).forEach((p,A)=>s.set(A,p)),u=e.params||u);let c=n?VC:oc.request,l={url:`${ic()}/${i}`,headers:s,retryConfig:{noResponseRetries:r},params:u,responseType:"text",timeout:em()};Xp.info("instance request %j",l);let h=await c(l);Xp.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 HC.parse(h.data)}catch{}return h.data}async function VC(t){let e={...t,url:t.url?.toString().replace(ic(),ic(ie.SECONDARY_HOST_ADDRESS))},r=(0,oc.request)(t),n=(0,oc.request)(e);return Promise.any([r,n])}function KC(t){return vs("instance",t)}function YC(t){return vs("project",t)}function XC(t){return vs("universe",t)}async function QC(t){let e={};return await Promise.all(t.map(r=>(async()=>{let n=await vs(r),s=r.metadataKey;e[s]=n})())),e}function ZC(){return process.env.DETECT_GCP_RETRIES?Number(process.env.DETECT_GCP_RETRIES):0}var yi;async function ew(){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 ac();case"ping-only":}}try{return yi===void 0&&(yi=vs("instance",void 0,ZC(),!(process.env.GCE_METADATA_IP||process.env.GCE_METADATA_HOST))),await yi,!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 tw(){yi=void 0}ie.gcpResidencyCache=null;function ac(){return ie.gcpResidencyCache===null&&Zp(),ie.gcpResidencyCache}function Zp(t=null){ie.gcpResidencyCache=t!==null?t:(0,WC.detectGCPResidency)()}function em(){return ac()?0:3e3}zC(Qu(),ie)});var nm=J(_i=>{"use strict";_i.byteLength=nw;_i.toByteArray=ow;_i.fromByteArray=uw;var Yt=[],kt=[],rw=typeof Uint8Array<"u"?Uint8Array:Array,uc="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(an=0,tm=uc.length;an<tm;++an)Yt[an]=uc[an],kt[uc.charCodeAt(an)]=an;var an,tm;kt[45]=62;kt[95]=63;function rm(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 nw(t){var e=rm(t),r=e[0],n=e[1];return(r+n)*3/4-n}function sw(t,e,r){return(e+r)*3/4-r}function ow(t){var e,r=rm(t),n=r[0],s=r[1],i=new rw(sw(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 iw(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(iw(n));return s.join("")}function uw(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 lc=J(cc=>{"use strict";Object.defineProperty(cc,"__esModule",{value:!0});cc.fromArrayBufferToHex=cw;function cw(t){return Array.from(new Uint8Array(t)).map(r=>r.toString(16).padStart(2,"0")).join("")}});var sm=J(bi=>{"use strict";Object.defineProperty(bi,"__esModule",{value:!0});bi.BrowserCrypto=void 0;var Ln=nm(),lw=lc(),fc=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 Ln.fromByteArray(new Uint8Array(n))}randomBytesBase64(e){let r=new Uint8Array(e);return window.crypto.getRandomValues(r),Ln.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=Ln.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 Ln.fromByteArray(new Uint8Array(u))}decodeBase64StringUtf8(e){let r=Ln.toByteArray(t.padBase64(e));return new TextDecoder().decode(r)}encodeBase64StringUtf8(e){let r=new TextEncoder().encode(e);return Ln.fromByteArray(r)}async sha256DigestHex(e){let r=new TextEncoder().encode(e),n=await window.crypto.subtle.digest("SHA-256",r);return(0,lw.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))}};bi.BrowserCrypto=fc});var om=J(Ci=>{"use strict";Object.defineProperty(Ci,"__esModule",{value:!0});Ci.NodeCrypto=void 0;var Un=X("crypto"),dc=class{async sha256DigestBase64(e){return Un.createHash("sha256").update(e).digest("base64")}randomBytesBase64(e){return Un.randomBytes(e).toString("base64")}async verify(e,r,n){let s=Un.createVerify("RSA-SHA256");return s.update(r),s.end(),s.verify(e,n,"base64")}async sign(e,r){let n=Un.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 Un.createHash("sha256").update(e).digest("hex")}async signWithHmacSha256(e,r){let n=typeof e=="string"?e:dw(e);return fw(Un.createHmac("sha256",n).update(r).digest())}};Ci.NodeCrypto=dc;function fw(t){return t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength)}function dw(t){return Buffer.from(t)}});var Os=J(yr=>{"use strict";var hw=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]})),pw=yr&&yr.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&hw(e,t,r)};Object.defineProperty(yr,"__esModule",{value:!0});yr.createCrypto=yw;yr.hasBrowserCrypto=im;var mw=sm(),gw=om();pw(lc(),yr);function yw(){return im()?new mw.BrowserCrypto:new gw.NodeCrypto}function im(){return typeof window<"u"&&typeof window.crypto<"u"&&typeof window.crypto.subtle<"u"}});var Mn=J((hc,um)=>{var wi=X("buffer"),Xt=wi.Buffer;function am(t,e){for(var r in t)e[r]=t[r]}Xt.from&&Xt.alloc&&Xt.allocUnsafe&&Xt.allocUnsafeSlow?um.exports=wi:(am(wi,hc),hc.Buffer=un);function un(t,e,r){return Xt(t,e,r)}un.prototype=Object.create(Xt.prototype);am(Xt,un);un.from=function(t,e,r){if(typeof t=="number")throw new TypeError("Argument must not be a number");return Xt(t,e,r)};un.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};un.allocUnsafe=function(t){if(typeof t!="number")throw new TypeError("Argument must be a number");return Xt(t)};un.allocUnsafeSlow=function(t){if(typeof t!="number")throw new TypeError("Argument must be a number");return wi.SlowBuffer(t)}});var lm=J((UR,cm)=>{"use strict";function pc(t){var e=(t/8|0)+(t%8===0?0:1);return e}var _w={ES256:pc(256),ES384:pc(384),ES512:pc(521)};function bw(t){var e=_w[t];if(e)return e;throw new Error('Unknown algorithm "'+t+'"')}cm.exports=bw});var mc=J((MR,gm)=>{"use strict";var Ei=Mn().Buffer,dm=lm(),Ai=128,hm=0,Cw=32,ww=16,Ew=2,pm=ww|Cw|hm<<6,Si=Ew|hm<<6;function Aw(t){return t.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function mm(t){if(Ei.isBuffer(t))return t;if(typeof t=="string")return Ei.from(t,"base64");throw new TypeError("ECDSA signature must be a Base64 string or a Buffer")}function Sw(t,e){t=mm(t);var r=dm(e),n=r+1,s=t.length,i=0;if(t[i++]!==pm)throw new Error('Could not find expected "seq"');var u=t[i++];if(u===(Ai|1)&&(u=t[i++]),s-i<u)throw new Error('"seq" specified length of "'+u+'", only "'+(s-i)+'" remaining');if(t[i++]!==Si)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++]!==Si)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,R=Ei.allocUnsafe(p+c+A+h);for(i=0;i<p;++i)R[i]=0;t.copy(R,i,l+Math.max(-p,0),l+c),i=r;for(var S=i;i<S+A;++i)R[i]=0;return t.copy(R,i,d+Math.max(-A,0),d+h),R=R.toString("base64"),R=Aw(R),R}function fm(t,e,r){for(var n=0;e+n<r&&t[e+n]===0;)++n;var s=t[e+n]>=Ai;return s&&--n,n}function kw(t,e){t=mm(t);var r=dm(e),n=t.length;if(n!==r*2)throw new TypeError('"'+e+'" signatures must be "'+r*2+'" bytes, saw "'+n+'"');var s=fm(t,0,r),i=fm(t,r,t.length),u=r-s,c=r-i,l=2+u+1+1+c,h=l<Ai,d=Ei.allocUnsafe((h?2:3)+l),p=0;return d[p++]=pm,h?d[p++]=l:(d[p++]=Ai|1,d[p++]=l&255),d[p++]=Si,d[p++]=u,s<0?(d[p++]=0,p+=t.copy(d,p,0,r)):p+=t.copy(d,p,s,r),d[p++]=Si,d[p++]=c,i<0?(d[p++]=0,t.copy(d,p,r)):t.copy(d,p,r+i),d}gm.exports={derToJose:Sw,joseToDer:kw}});var Ut=J(_r=>{"use strict";Object.defineProperty(_r,"__esModule",{value:!0});_r.LRUCache=void 0;_r.snakeToCamel=_m;_r.originalOrCamelOptions=Rw;_r.removeUndefinedValuesInObject=Ow;_r.isValidFile=Fw;_r.getWellKnownCertificateConfigFileLocation=xw;var Dw=X("fs"),Tw=X("os"),gc=X("path"),vw="certificate_config.json",ym="gcloud";function _m(t){return t.replace(/([_][^_])/g,e=>e.slice(1).toUpperCase())}function Rw(t){function e(r){let n=t||{};return n[r]??n[_m(r)]}return{get:e}}var yc=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=yc;function Ow(t){return Object.entries(t).forEach(([e,r])=>{(r===void 0||r==="undefined")&&delete t[e]}),t}async function Fw(t){try{return(await Dw.promises.lstat(t)).isFile()}catch{return!1}}function xw(){let t=process.env.CLOUDSDK_CONFIG||(Pw()?gc.join(process.env.APPDATA||"",ym):gc.join(process.env.HOME||"",".config",ym));return gc.join(t,vw)}function Pw(){return Tw.platform().startsWith("win")}});var bm=J((zR,Iw)=>{Iw.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 _c=J(Ur=>{"use strict";Object.defineProperty(Ur,"__esModule",{value:!0});Ur.USER_AGENT=Ur.PRODUCT_NAME=Ur.pkg=void 0;var Cm=bm();Ur.pkg=Cm;var wm="google-api-nodejs-client";Ur.PRODUCT_NAME=wm;var Nw=`${wm}/${Cm.version}`;Ur.USER_AGENT=Nw});var pt=J(Mt=>{"use strict";Object.defineProperty(Mt,"__esModule",{value:!0});Mt.AuthClient=Mt.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS=Mt.DEFAULT_UNIVERSE=void 0;var Bw=X("events"),bc=Ve(),jw=Ut(),qw=sc(),Cc=_c();Mt.DEFAULT_UNIVERSE="googleapis.com";Mt.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS=300*1e3;var wc=class t extends Bw.EventEmitter{apiKey;projectId;quotaProjectId;transporter;credentials={};eagerRefreshThresholdMillis=Mt.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS;forceRefreshOnFailure=!1;universeDomain=Mt.DEFAULT_UNIVERSE;static RequestMethodNameSymbol=Symbol("request method name");static RequestLogIdSymbol=Symbol("request log id");constructor(e={}){super();let r=(0,jw.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")??Mt.DEFAULT_UNIVERSE,this.transporter=e.transporter??new bc.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&&bc.Gaxios.mergeHeaders(i,r.headers),n&&bc.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,qw.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(`${Cc.PRODUCT_NAME}/`)||e.headers.set("User-Agent",`${r} ${Cc.USER_AGENT}`):e.headers.set("User-Agent",Cc.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"]}}}};Mt.AuthClient=wc});var Ac=J(ki=>{"use strict";Object.defineProperty(ki,"__esModule",{value:!0});ki.LoginTicket=void 0;var Ec=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()}}};ki.LoginTicket=Ec});var cn=J(Qt=>{"use strict";Object.defineProperty(Qt,"__esModule",{value:!0});Qt.OAuth2Client=Qt.ClientAuthentication=Qt.CertificateFormat=Qt.CodeChallengeMethod=void 0;var Em=Ve(),Lw=X("querystring"),Uw=X("stream"),Mw=mc(),Am=Ut(),Sc=Os(),$n=pt(),$w=Ac(),Sm;(function(t){t.Plain="plain",t.S256="S256"})(Sm||(Qt.CodeChallengeMethod=Sm={}));var br;(function(t){t.PEM="PEM",t.JWK="JWK"})(br||(Qt.CertificateFormat=br={}));var Fs;(function(t){t.ClientSecretPost="ClientSecretPost",t.ClientSecretBasic="ClientSecretBasic",t.None="None"})(Fs||(Qt.ClientAuthentication=Fs={}));var kc=class t extends $n.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||Fs.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()+"?"+Lw.stringify(e)}generateCodeVerifier(){throw new Error("generateCodeVerifier is removed, please use generateCodeVerifierAsync instead.")}async generateCodeVerifierAsync(){let e=(0,Sc.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===Fs.ClientSecretBasic){let l=Buffer.from(`${this._clientId}:${this._clientSecret}`);n.set("authorization",`Basic ${l.toString("base64")}`)}this.clientAuthentication===Fs.ClientSecretPost&&(s.client_secret=this._clientSecret);let i={...t.RETRY_CONFIG,method:"POST",url:r,data:new URLSearchParams((0,Am.removeUndefinedValuesInObject)(s)),headers:n};$n.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,Am.removeUndefinedValuesInObject)(n))};$n.AuthClient.setMethodName(u,"refreshTokenNoCache"),s=await this.transporter.request(u)}catch(u){throw u instanceof Em.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($n.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=Em.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 Uw.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,Sc.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};$n.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};$n.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,Sc.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(C){throw C instanceof Error&&(C.message=`Can't parse token envelope: ${c[0]}': ${C.message}`),C}if(!d)throw new Error("Can't parse token envelope: "+c[0]);try{p=JSON.parse(u.decodeBase64StringUtf8(c[1]))}catch(C){throw C instanceof Error&&(C.message=`Can't parse token payload '${c[0]}`),C}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=Mw.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 _=Number(p.exp);if(isNaN(_))throw new Error("exp field using invalid format");let y=new Date().getTime()/1e3;if(_>=y+i)throw new Error("Expiration time too far in future: "+JSON.stringify(p));let m=S-t.CLOCK_SKEW_SECS_,D=_+t.CLOCK_SKEW_SECS_;if(y<m)throw new Error("Token used too early, "+y+" < "+m+": "+JSON.stringify(p));if(y>D)throw new Error("Token used too late, "+y+" > "+D+": "+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 C=p.aud,E=!1;if(n.constructor===Array?E=n.indexOf(C)>-1:E=C===n,!E)throw new Error("Wrong recipient, payload audience != requiredAudience")}return new $w.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=kc});var Tc=J(Di=>{"use strict";Object.defineProperty(Di,"__esModule",{value:!0});Di.Compute=void 0;var zw=Ve(),km=Rs(),Hw=cn(),Dc=class extends Hw.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 km.instance(s)}catch(s){throw s instanceof zw.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 km.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))}};Di.Compute=Dc});var Rc=J(Ti=>{"use strict";Object.defineProperty(Ti,"__esModule",{value:!0});Ti.IdTokenClient=void 0;var Ww=cn(),vc=class extends Ww.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}};Ti.IdTokenClient=vc});var Oc=J(zn=>{"use strict";Object.defineProperty(zn,"__esModule",{value:!0});zn.GCPEnv=void 0;zn.clear=Gw;zn.getEnv=Jw;var Dm=Rs(),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||(zn.GCPEnv=Zt={}));var xs;function Gw(){xs=void 0}async function Jw(){return xs||(xs=Vw(),xs)}async function Vw(){let t=Zt.NONE;return Kw()?t=Zt.APP_ENGINE:Yw()?t=Zt.CLOUD_FUNCTIONS:await eE()?await Zw()?t=Zt.KUBERNETES_ENGINE:Xw()?t=Zt.CLOUD_RUN:Qw()?t=Zt.CLOUD_RUN_JOBS:t=Zt.COMPUTE_ENGINE:t=Zt.NONE,t}function Kw(){return!!(process.env.GAE_SERVICE||process.env.GAE_MODULE_NAME)}function Yw(){return!!(process.env.FUNCTION_NAME||process.env.FUNCTION_TARGET)}function Xw(){return!!process.env.K_CONFIGURATION}function Qw(){return!!process.env.CLOUD_RUN_JOB}async function Zw(){try{return await Dm.instance("attributes/cluster-name"),!0}catch{return!1}}async function eE(){return Dm.isAvailable()}});var Fc=J((XR,Tm)=>{var vi=Mn().Buffer,tE=X("stream"),rE=X("util");function Ri(t){if(this.buffer=null,this.writable=!0,this.readable=!0,!t)return this.buffer=vi.alloc(0),this;if(typeof t.pipe=="function")return this.buffer=vi.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+")")}rE.inherits(Ri,tE);Ri.prototype.write=function(e){this.buffer=vi.concat([this.buffer,vi.from(e)]),this.emit("data",e)};Ri.prototype.end=function(e){e&&this.write(e),this.emit("end",e),this.emit("close"),this.writable=!1,this.readable=!1};Tm.exports=Ri});var Rm=J((QR,vm)=>{"use strict";var Ps=X("buffer").Buffer,xc=X("buffer").SlowBuffer;vm.exports=Oi;function Oi(t,e){if(!Ps.isBuffer(t)||!Ps.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}Oi.install=function(){Ps.prototype.equal=xc.prototype.equal=function(e){return Oi(this,e)}};var nE=Ps.prototype.equal,sE=xc.prototype.equal;Oi.restore=function(){Ps.prototype.equal=nE,xc.prototype.equal=sE}});var Bc=J((ZR,qm)=>{var Wn=Mn().Buffer,Dt=X("crypto"),Fm=mc(),Om=X("util"),oE=`"%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".`,Is="secret must be a string or buffer",Hn="key must be a string or a buffer",oE="key must be a string, a buffer or an object",Pc=typeof Dt.createPublicKey=="function";Pc&&(Hn+=" or a KeyObject",Is+="or a KeyObject");function Fm(t){if(!Wn.isBuffer(t)&&typeof t!="string"&&(!Pc||typeof t!="object"||typeof t.type!="string"||typeof t.asymmetricKeyType!="string"||typeof t.export!="function"))throw $t(Hn)}function xm(t){if(!Wn.isBuffer(t)&&typeof t!="string"&&typeof t!="object")throw $t(oE)}function iE(t){if(!Wn.isBuffer(t)){if(typeof t=="string")return t;if(!Pc||typeof t!="object"||t.type!=="secret"||typeof t.export!="function")throw $t(Is)}}function Ic(t){return t.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function Pm(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=Rm.format.bind(Rm,t).apply(null,e);return new TypeError(r)}function aE(t){return Wn.isBuffer(t)||typeof t=="string"}function Ns(t){return aE(t)||(t=JSON.stringify(t)),t}function Im(t){return function(r,n){iE(n),r=Ns(r);var s=Dt.createHmac("sha"+t,n),i=(s.update(r),s.digest("base64"));return Ic(i)}}var xc,uE="timingSafeEqual"in Dt?function(e,r){return e.byteLength!==r.byteLength?!1:Dt.timingSafeEqual(e,r)}:function(e,r){return xc||(xc=vm()),xc(e,r)};function cE(t){return function(r,n,s){var i=Im(t)(r,s);return uE(Wn.from(n),Wn.from(i))}}function Nm(t){return function(r,n){xm(n),r=Ns(r);var s=Dt.createSign("RSA-SHA"+t),i=(s.update(r),s.sign(n,"base64"));return Ic(i)}}function Bm(t){return function(r,n,s){Fm(s),r=Ns(r),n=Pm(n);var i=Dt.createVerify("RSA-SHA"+t);return i.update(r),i.verify(s,n,"base64")}}function lE(t){return function(r,n){xm(n),r=Ns(r);var s=Dt.createSign("RSA-SHA"+t),i=(s.update(r),s.sign({key:n,padding:Dt.constants.RSA_PKCS1_PSS_PADDING,saltLength:Dt.constants.RSA_PSS_SALTLEN_DIGEST},"base64"));return Ic(i)}}function fE(t){return function(r,n,s){Fm(s),r=Ns(r),n=Pm(n);var i=Dt.createVerify("RSA-SHA"+t);return i.update(r),i.verify({key:s,padding:Dt.constants.RSA_PKCS1_PSS_PADDING,saltLength:Dt.constants.RSA_PSS_SALTLEN_DIGEST},n,"base64")}}function dE(t){var e=Nm(t);return function(){var n=e.apply(null,arguments);return n=Om.derToJose(n,"ES"+t),n}}function hE(t){var e=Bm(t);return function(n,s,i){s=Om.joseToDer(s,"ES"+t).toString("base64");var u=e(n,s,i);return u}}function pE(){return function(){return""}}function mE(){return function(e,r){return r===""}}jm.exports=function(e){var r={hs:Im,rs:Nm,ps:lE,es:dE,none:pE},n={hs:cE,rs:Bm,ps:fE,es:hE,none:mE},s=e.match(/^(RS|PS|ES|HS)(256|384|512)$|^(none)$/);if(!s)throw $t(sE,e);var i=(s[1]||s[3]).toLowerCase(),u=s[2];return{sign:r[i](u),verify:n[i](u)}}});var Bc=J((ZR,qm)=>{var gE=X("buffer").Buffer;qm.exports=function(e){return typeof e=="string"?e:typeof e=="number"||gE.isBuffer(e)?e.toString():JSON.stringify(e)}});var Hm=J((e1,zm)=>{var yE=Mn().Buffer,Lm=Oc(),_E=Nc(),bE=X("stream"),Um=Bc(),jc=X("util");function Mm(t,e){return yE.from(t,e).toString("base64").replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function CE(t,e,r){r=r||"utf8";var n=Mm(Um(t),"binary"),s=Mm(Um(e),r);return jc.format("%s.%s",n,s)}function $m(t){var e=t.header,r=t.payload,n=t.secret||t.privateKey,s=t.encoding,i=_E(e.alg),u=CE(e,r,s),c=i.sign(u,n);return jc.format("%s.%s",u,c)}function Fi(t){var e=t.secret||t.privateKey||t.key,r=new Lm(e);this.readable=!0,this.header=t.header,this.encoding=t.encoding,this.secret=this.privateKey=this.key=r,this.payload=new Lm(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))}jc.inherits(Fi,bE);Fi.prototype.sign=function(){try{var e=$m({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")}};Fi.sign=$m;zm.exports=Fi});var eg=J((t1,Zm)=>{var Gm=Mn().Buffer,Wm=Oc(),wE=Nc(),EE=X("stream"),Jm=Bc(),AE=X("util"),SE=/^[a-zA-Z0-9\-_]+?\.[a-zA-Z0-9\-_]+?\.([a-zA-Z0-9\-_]+)?$/;function kE(t){return Object.prototype.toString.call(t)==="[object Object]"}function DE(t){if(kE(t))return t;try{return JSON.parse(t)}catch{return}}function Vm(t){var e=t.split(".",1)[0];return DE(Gm.from(e,"base64").toString("binary"))}function TE(t){return t.split(".",2).join(".")}function Km(t){return t.split(".")[2]}function vE(t,e){e=e||"utf8";var r=t.split(".")[1];return Gm.from(r,"base64").toString(e)}function Ym(t){return SE.test(t)&&!!Vm(t)}function Xm(t,e,r){if(!e){var n=new Error("Missing algorithm parameter for jws.verify");throw n.code="MISSING_ALGORITHM",n}t=Jm(t);var s=Km(t),i=TE(t),u=wE(e);return u.verify(i,s,r)}function Qm(t,e){if(e=e||{},t=Jm(t),!Ym(t))return null;var r=Vm(t);if(!r)return null;var n=vE(t);return(r.typ==="JWT"||e.json)&&(n=JSON.parse(n,e.encoding)),{header:r,payload:n,signature:Km(t)}}function Gn(t){t=t||{};var e=t.secret||t.publicKey||t.key,r=new Wm(e);this.readable=!0,this.algorithm=t.algorithm,this.encoding=t.encoding,this.secret=this.publicKey=this.key=r,this.signature=new Wm(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))}AE.inherits(Gn,EE);Gn.prototype.verify=function(){try{var e=Xm(this.signature.buffer,this.algorithm,this.key.buffer),r=Qm(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")}};Gn.decode=Qm;Gn.isValid=Ym;Gn.verify=Xm;Zm.exports=Gn});var qc=J(Mr=>{var tg=Hm(),xi=eg(),RE=["HS256","HS384","HS512","RS256","RS384","RS512","PS256","PS384","PS512","ES256","ES384","ES512"];Mr.ALGORITHMS=RE;Mr.sign=tg.sign;Mr.verify=xi.verify;Mr.decode=xi.decode;Mr.isValid=xi.isValid;Mr.createSign=function(e){return new tg(e)};Mr.createVerify=function(e){return new xi(e)}});var gg=J(Ii=>{"use strict";Object.defineProperty(Ii,"__esModule",{value:!0});Ii.GoogleToken=void 0;var rg=Pi(X("fs")),OE=Ve(),FE=Pi(qc()),xE=Pi(X("path")),PE=X("util");function Pi(t,e){if(typeof WeakMap=="function")var r=new WeakMap,n=new WeakMap;return(Pi=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 IE(t,e){fg(t,e),e.add(t)}function NE(t,e,r){fg(t,e),e.set(t,r)}function fg(t,e){if(e.has(t))throw new TypeError("Cannot initialize the same private elements twice on an object")}function ng(t,e,r){return t.set(zt(t,e),r),r}function sg(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 og(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,pg(n.key),n)}}function dg(t,e,r){return e&&og(t.prototype,e),r&&og(t,r),Object.defineProperty(t,"prototype",{writable:!1}),t}function hg(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function BE(t,e,r){return e=Ls(e),jE(t,Hc()?Reflect.construct(e,r||[],Ls(t).constructor):e.apply(t,r))}function jE(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 qE(t)}function qE(t){if(t===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}function LE(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 Lc(t){var e=typeof Map=="function"?new Map:void 0;return Lc=function(n){if(n===null||!ME(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 UE(n,arguments,Ls(this).constructor)}return s.prototype=Object.create(n.prototype,{constructor:{value:s,enumerable:!1,writable:!0,configurable:!0}}),qs(s,n)},Lc(t)}function UE(t,e,r){if(Hc())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 Hc(){try{var t=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(Hc=function(){return!!t})()}function ME(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 Ls(t){return Ls=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},Ls(t)}function mt(t,e,r){return(e=pg(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function pg(t){var e=$E(t,"string");return Cr(e)=="symbol"?e:e+""}function $E(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(R,S,_,y){var m=S&&S.prototype instanceof c?S:c,D=Object.create(m.prototype);return gt(D,"_invoke",(function(C,E,v){var x,$,V,U=0,Q=v||[],ne=!1,ae={p:0,n:0,v:t,a:fe,f:fe.bind(t,4),d:function(Ae,oe){return x=Ae,$=0,V=t,ae.n=oe,u}};function fe(ye,Ae){for($=ye,V=Ae,e=0;!ne&&U&&!oe&&e<Q.length;e++){var oe,pe=Q[e],G=ae.p,K=pe[2];ye>3?(oe=K===Ae)&&(V=pe[($=pe[4])?5:($=3,3)],pe[4]=pe[5]=t):pe[0]<=G&&((oe=ye<2&&G<pe[1])?($=0,ae.v=Ae,ae.n=pe[1]):G<K&&(oe=ye<3||pe[0]>Ae||Ae>K)&&(pe[4]=ye,pe[5]=Ae,ae.n=K,$=0))}if(oe||ye>1)return u;throw ne=!0,Ae}return function(ye,Ae,oe){if(U>1)throw TypeError("Generator is already running");for(ne&&Ae===1&&fe(Ae,oe),$=Ae,V=oe;(e=$<2?t:V)||!ne;){x||($?$<3?($>1&&(ae.n=-1),fe($,V)):ae.n=V:ae.v=V);try{if(U=2,x){if($||(ye="next"),e=x[ye]){if(!(e=e.call(x,V)))throw TypeError("iterator result is not an object");if(!e.done)return e;V=e.value,$<2&&($=0)}else $===1&&(e=x.return)&&e.call(x),$<2&&(V=TypeError("The iterator does not provide a '"+ye+"' method"),$=1);x=t}else if((e=(ne=ae.n<0)?V:C.call(E,ae))!==u)break}catch(pe){x=t,$=1,V=pe}finally{U=1}}return{value:e,done:ne}}})(R,_,y),!0),D}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(R){return Object.setPrototypeOf?Object.setPrototypeOf(R,h):(R.__proto__=h,gt(R,s,"GeneratorFunction")),R.prototype=Object.create(p),R}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,R){gt(u,A,function(S){return this._invoke(A,R,S)})};d("next",0),d("throw",1),d("return",2)}},gt(t,e,r,n)}function ig(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 Jn(t){return function(){var e=this,r=arguments;return new Promise(function(n,s){var i=t.apply(e,r);function u(l){ig(i,n,s,u,c,"next",l)}function c(l){ig(i,n,s,u,c,"throw",l)}u(void 0)})}}var ag=rg.readFile?(0,PE.promisify)(rg.readFile):Jn(yt().m(function t(){return yt().w(function(e){for(;;)switch(e.n){case 0:throw new js("use key rather than keyFile.","MISSING_CREDENTIALS");case 1:return e.a(2)}},t)})),ug="https://oauth2.googleapis.com/token",zE="https://oauth2.googleapis.com/revoke?token=",js=(function(t){function e(r,n){var s;return hg(this,e),s=BE(this,e,[r]),mt(s,"code",void 0),s.code=n,s}return LE(e,t),dg(e)})(Lc(Error)),Bs=new WeakMap,er=new WeakSet,n1=Ii.GoogleToken=(function(){function t(e){hg(this,t),IE(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,OE.request)(n)}}),NE(this,Bs,void 0),zt(er,this,mg).call(this,e)}return dg(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,cg).call(this,n).then(function(i){return s(null,i)},r);return}return zt(er,this,cg).call(this,n)}},{key:"getCredentials",value:(function(){var e=Jn(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=xE.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,ag(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 js("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,ag(s,"utf8");case 5:return d=A.v,A.a(2,{privateKey:d});case 6:throw new js("*.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 js("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,lg).call(this).then(function(){return r()},r);return}return zt(er,this,lg).call(this)}}])})();function cg(t){return Uc.apply(this,arguments)}function Uc(){return Uc=Jn(yt().m(function t(e){return yt().w(function(r){for(;;)switch(r.n){case 0:if(!(sg(Bs,this)&&!e.forceRefresh)){r.n=1;break}return r.a(2,sg(Bs,this));case 1:return r.p=1,r.n=2,ng(Bs,this,zt(er,this,HE).call(this,e));case 2:return r.a(2,r.v);case 3:return r.p=3,ng(Bs,this,void 0),r.f(3);case 4:return r.a(2)}},t,this,[[1,,3,4]])})),Uc.apply(this,arguments)}function HE(t){return Mc.apply(this,arguments)}function Mc(){return Mc=Jn(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,WE).call(this);case 4:return n.a(2,zt(er,this,GE).call(this))}},t,this)})),Mc.apply(this,arguments)}function WE(){if(!this.iss)throw new js("email is required.","MISSING_CREDENTIALS")}function lg(){return $c.apply(this,arguments)}function $c(){return $c=Jn(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=zE+this.accessToken,r.n=2,this.transporter.request({url:e,retry:!0});case 2:zt(er,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)})),$c.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,Cr(t.scope)==="object"?this.scope=t.scope.join(" "):this.scope=t.scope,this.eagerRefreshThresholdMillis=t.eagerRefreshThresholdMillis,t.transporter&&(this.transporter=t.transporter)}function GE(){return zc.apply(this,arguments)}function zc(){return zc=Jn(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:ug,exp:e+3600,iat:e,sub:this.sub},r),s=FE.sign({header:{alg:"RS256"},payload:n,secret:this.key}),p.p=1,p.n=2,this.transporter.request({method:"POST",url:ug,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]])})),zc.apply(this,arguments)}});var Gc=J(Ni=>{"use strict";Object.defineProperty(Ni,"__esModule",{value:!0});Ni.JWTAccess=void 0;var JE=qc(),VE=Ut(),yg={alg:"RS256",typ:"JWT"},Wc=class t{email;key;keyId;projectId;eagerRefreshThresholdMillis;cache=new VE.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?{...yg,kid:this.keyId}:yg,p=Object.assign(h,r),A=JE.sign({header:d,payload:p,secret:this.key}),R=new Headers({authorization:`Bearer ${A}`});return this.cache.set(s,{expiration:l*1e3,headers:R}),R}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)}})})}};Ni.JWTAccess=Wc});var Vc=J(ji=>{"use strict";Object.defineProperty(ji,"__esModule",{value:!0});ji.JWT=void 0;var _g=gg(),KE=Gc(),YE=cn(),Bi=pt(),Jc=class t extends YE.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!==Bi.DEFAULT_UNIVERSE;if(this.subject&&this.universeDomain!==Bi.DEFAULT_UNIVERSE)throw new RangeError(`Service Account user is configured for the credential. Domain-wide delegation is not supported in universes other than ${Bi.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 KE.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!==Bi.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.")}};ji.JWT=Jc});var Yc=J(Vn=>{"use strict";Object.defineProperty(Vn,"__esModule",{value:!0});Vn.UserRefreshClient=Vn.USER_REFRESH_ACCOUNT_TYPE=void 0;var XE=cn(),QE=pt();Vn.USER_REFRESH_ACCOUNT_TYPE="authorized_user";var Kc=class t extends XE.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 QE.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}};Vn.UserRefreshClient=Kc});var Qc=J(Kn=>{"use strict";Object.defineProperty(Kn,"__esModule",{value:!0});Kn.Impersonated=Kn.IMPERSONATED_ACCOUNT_TYPE=void 0;var bg=cn(),ZE=Ve(),eA=Ut();Kn.IMPERSONATED_ACCOUNT_TYPE="impersonated_service_account";var Xc=class t extends bg.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 bg.OAuth2Client,this.targetPrincipal=e.targetPrincipal??"",this.delegates=e.delegates??[],this.targetScopes=e.targetScopes??[],this.lifetime=e.lifetime??3600,!!!(0,eA.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 ZE.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}};Kn.Impersonated=Xc});var el=J(Us=>{"use strict";Object.defineProperty(Us,"__esModule",{value:!0});Us.OAuthClientAuthHandler=void 0;Us.getErrorFromOAuthErrorResponse=nA;var Yn=Ve(),tA=Os(),rA=["PUT","POST","PATCH"],Zc=class{#e=(0,tA.createCrypto)();#t;transporter;constructor(e){e&&"clientId"in e?(this.#t=e,this.transporter=new Yn.Gaxios):(this.#t=e?.clientAuthentication,this.transporter=e?.transporter||new Yn.Gaxios)}applyClientAuthenticationOptions(e,r){e.headers=Yn.Gaxios.mergeHeaders(e.headers),this.injectAuthenticatedHeaders(e,r),r||this.injectAuthenticatedRequestBody(e)}injectAuthenticatedHeaders(e,r){if(r)e.headers=Yn.Gaxios.mergeHeaders(e.headers,{authorization:`Bearer ${r}`});else if(this.#t?.confidentialClientType==="basic"){e.headers=Yn.Gaxios.mergeHeaders(e.headers);let n=this.#t.clientId,s=this.#t.clientSecret||"",i=this.#e.encodeBase64StringUtf8(`${n}:${s}`);Yn.Gaxios.mergeHeaders(e.headers,{authorization:`Basic ${i}`})}}injectAuthenticatedRequestBody(e){if(this.#t?.confidentialClientType==="request-body"){let r=(e.method||"GET").toUpperCase();if(!rA.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"]}}}};Us.OAuthClientAuthHandler=Zc;function nA(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 Li=J(qi=>{"use strict";Object.defineProperty(qi,"__esModule",{value:!0});qi.StsCredentials=void 0;var sA=Ve(),oA=pt(),Cg=el(),iA=Ut(),tl=class t extends Cg.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,iA.removeUndefinedValuesInObject)(s))};oA.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 sA.GaxiosError&&u.response?(0,Cg.getErrorFromOAuthErrorResponse)(u.response.data,u):u}}};qi.StsCredentials=tl});var $r=J(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 aA=Ve(),uA=X("stream"),rl=pt(),cA=Li(),wg=Ut(),lA=yc(),fA="urn:ietf:params:oauth:grant-type:token-exchange",dA="urn:ietf:params:oauth:token-type:access_token",nl="https://www.googleapis.com/auth/cloud-platform",hA=3600;Tt.EXPIRATION_TIME_OFFSET=300*1e3;Tt.EXTERNAL_ACCOUNT_TYPE="external_account";Tt.CLOUD_RESOURCE_MANAGER="https://cloudresourcemanager.googleapis.com/v1/projects/";var pA="//iam\\.googleapis\\.com/locations/[^/]+/workforcePools/[^/]+/providers/.+",mA="https://sts.{universeDomain}/v1/token",sl=class t extends rl.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")??mA.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 cA.StsCredentials({tokenExchangeEndpoint:this.tokenUrl,clientAuthentication:this.clientAuth}),this.scopes=r.get("scopes")||[nl],this.cachedAccessToken=null,this.audience=r.get("audience"),this.subjectTokenType=u,this.workforcePoolUserProject=c;let p=new RegExp(pA);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=hA),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}`};rl.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=aA.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 uA.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:fA,audience:this.audience,requestedTokenType:dA,subjectToken:e,subjectTokenType:this.subjectTokenType,scope:this.serviceAccountImpersonationUrl?[nl]: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"}};rl.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||[nl]}getMetricsHeaderValue(){let e=process.version.replace(/^v/,""),r=this.serviceAccountImpersonationUrl!==void 0,n=this.credentialSourceType?this.credentialSourceType:"unknown";return`gl-node/${e} auth/${lA.pkg.version} google-byoid-sdk source/${n} sa-impersonation/${r} config-lifetime/${this.configLifetimeRequested}`}getTokenUrl(){return this.tokenUrl}};Tt.BaseExternalAccountClient=sl});var Eg=J(Ui=>{"use strict";Object.defineProperty(Ui,"__esModule",{value:!0});Ui.FileSubjectTokenSupplier=void 0;var il=X("util"),al=X("fs"),gA=(0,il.promisify)(al.readFile??(()=>{})),yA=(0,il.promisify)(al.realpath??(()=>{})),_A=(0,il.promisify)(al.lstat??(()=>{})),ol=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 yA(e),!(await _A(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 gA(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}};Ui.FileSubjectTokenSupplier=ol});var Ag=J(Mi=>{"use strict";Object.defineProperty(Mi,"__esModule",{value:!0});Mi.UrlSubjectTokenSupplier=void 0;var bA=pt(),ul=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}};Mi.UrlSubjectTokenSupplier=ul});var Sg=J(_t=>{"use strict";Object.defineProperty(_t,"__esModule",{value:!0});_t.CertificateSubjectTokenSupplier=_t.InvalidConfigurationError=_t.CertificateSourceUnavailableError=_t.CERTIFICATE_CONFIGURATION_ENV_VARIABLE=void 0;var $i=Ut(),zi=X("fs"),Hi=X("crypto"),CA=X("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 cl=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 CA.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,$i.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,$i.isValidFile)(r))return r;throw new tr(`Path from environment variable "${_t.CERTIFICATE_CONFIGURATION_ENV_VARIABLE}" is invalid: ${r}`)}let n=(0,$i.getWellKnownCertificateConfigFileLocation)();if(await(0,$i.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 zi.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 zi.promises.readFile(e),new Hi.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 zi.promises.readFile(r),(0,Hi.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 Hi.X509Certificate(e);if(!this.trustChainPath)return JSON.stringify([r.raw.toString("base64")]);try{let i=((await zi.promises.readFile(this.trustChainPath,"utf8")).match(/-----BEGIN CERTIFICATE-----[^-]+-----END CERTIFICATE-----/g)??[]).map((l,h)=>{try{return new Hi.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=cl});var dl=J(Wi=>{"use strict";Object.defineProperty(Wi,"__esModule",{value:!0});Wi.IdentityPoolClient=void 0;var wA=$r(),ll=Ut(),EA=Eg(),AA=Ag(),kg=Sg(),SA=Li(),Dg=Ve(),fl=class t extends wA.BaseExternalAccountClient{subjectTokenSupplier;constructor(e){super(e);let r=(0,ll.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,ll.originalOrCamelOptions)(n),u=(0,ll.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 EA.FileSubjectTokenSupplier({filePath:h,formatType:c,subjectTokenFieldName:l});else if(d)this.credentialSourceType="url",this.subjectTokenSupplier=new AA.UrlSubjectTokenSupplier({url:d,formatType:c,subjectTokenFieldName:l,headers:A,additionalGaxiosOptions:t.RETRY_CONFIG});else if(p){this.credentialSourceType="certificate";let R=new kg.CertificateSubjectTokenSupplier({useDefaultCertificateConfig:p.use_default_certificate_config,certificateConfigLocation:p.certificate_config_location,trustChainPath:p.trust_chain_path});this.subjectTokenSupplier=R}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 SA.StsCredentials({tokenExchangeEndpoint:this.getTokenUrl(),clientAuthentication:this.clientAuth,transporter:new Dg.Gaxios({agent:r})}),this.transporter=new Dg.Gaxios({...this.transporter.defaults||{},agent:r})}return e}};Wi.IdentityPoolClient=fl});var pl=J(Ji=>{"use strict";Object.defineProperty(Ji,"__esModule",{value:!0});Ji.AwsRequestSigner=void 0;var Gi=Ve(),vg=Os(),Tg="AWS4-HMAC-SHA256",kA="aws4_request",hl=class{getCredentials;region;crypto;constructor(e,r){this.getCredentials=e,this.region=r,this.crypto=(0,vg.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 TA({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=Gi.Gaxios.mergeHeaders(h.amzDate?{"x-amz-date":h.amzDate}:{},{authorization:h.authorizationHeader,host:l.host},u||{});c.token&&Gi.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}};Ji.AwsRequestSigner=hl;async function Ms(t,e,r){return await t.signWithHmacSha256(e,r)}async function DA(t,e,r,n,s){let i=await Ms(t,`AWS4${e}`,r),u=await Ms(t,i,n),c=await Ms(t,u,s);return await Ms(t,c,"aws4_request")}async function TA(t){let e=Gi.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=Gi.Gaxios.mergeHeaders({host:t.host},e.has("date")?{}:{"x-amz-date":i},e),l="",h=[...c.keys()].sort();h.forEach(D=>{l+=`${D}:${c.get(D)}
52
+ "HS256", "HS384", "HS512", "RS256", "RS384", "RS512", "PS256", "PS384", "PS512", "ES256", "ES384", "ES512" and "none".`,Is="secret must be a string or buffer",Hn="key must be a string or a buffer",iE="key must be a string, a buffer or an object",Ic=typeof Dt.createPublicKey=="function";Ic&&(Hn+=" or a KeyObject",Is+="or a KeyObject");function xm(t){if(!Wn.isBuffer(t)&&typeof t!="string"&&(!Ic||typeof t!="object"||typeof t.type!="string"||typeof t.asymmetricKeyType!="string"||typeof t.export!="function"))throw $t(Hn)}function Pm(t){if(!Wn.isBuffer(t)&&typeof t!="string"&&typeof t!="object")throw $t(iE)}function aE(t){if(!Wn.isBuffer(t)){if(typeof t=="string")return t;if(!Ic||typeof t!="object"||t.type!=="secret"||typeof t.export!="function")throw $t(Is)}}function Nc(t){return t.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function Im(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=Om.format.bind(Om,t).apply(null,e);return new TypeError(r)}function uE(t){return Wn.isBuffer(t)||typeof t=="string"}function Ns(t){return uE(t)||(t=JSON.stringify(t)),t}function Nm(t){return function(r,n){aE(n),r=Ns(r);var s=Dt.createHmac("sha"+t,n),i=(s.update(r),s.digest("base64"));return Nc(i)}}var Pc,cE="timingSafeEqual"in Dt?function(e,r){return e.byteLength!==r.byteLength?!1:Dt.timingSafeEqual(e,r)}:function(e,r){return Pc||(Pc=Rm()),Pc(e,r)};function lE(t){return function(r,n,s){var i=Nm(t)(r,s);return cE(Wn.from(n),Wn.from(i))}}function Bm(t){return function(r,n){Pm(n),r=Ns(r);var s=Dt.createSign("RSA-SHA"+t),i=(s.update(r),s.sign(n,"base64"));return Nc(i)}}function jm(t){return function(r,n,s){xm(s),r=Ns(r),n=Im(n);var i=Dt.createVerify("RSA-SHA"+t);return i.update(r),i.verify(s,n,"base64")}}function fE(t){return function(r,n){Pm(n),r=Ns(r);var s=Dt.createSign("RSA-SHA"+t),i=(s.update(r),s.sign({key:n,padding:Dt.constants.RSA_PKCS1_PSS_PADDING,saltLength:Dt.constants.RSA_PSS_SALTLEN_DIGEST},"base64"));return Nc(i)}}function dE(t){return function(r,n,s){xm(s),r=Ns(r),n=Im(n);var i=Dt.createVerify("RSA-SHA"+t);return i.update(r),i.verify({key:s,padding:Dt.constants.RSA_PKCS1_PSS_PADDING,saltLength:Dt.constants.RSA_PSS_SALTLEN_DIGEST},n,"base64")}}function hE(t){var e=Bm(t);return function(){var n=e.apply(null,arguments);return n=Fm.derToJose(n,"ES"+t),n}}function pE(t){var e=jm(t);return function(n,s,i){s=Fm.joseToDer(s,"ES"+t).toString("base64");var u=e(n,s,i);return u}}function mE(){return function(){return""}}function gE(){return function(e,r){return r===""}}qm.exports=function(e){var r={hs:Nm,rs:Bm,ps:fE,es:hE,none:mE},n={hs:lE,rs:jm,ps:dE,es:pE,none:gE},s=e.match(/^(RS|PS|ES|HS)(256|384|512)$|^(none)$/);if(!s)throw $t(oE,e);var i=(s[1]||s[3]).toLowerCase(),u=s[2];return{sign:r[i](u),verify:n[i](u)}}});var jc=J((e1,Lm)=>{var yE=X("buffer").Buffer;Lm.exports=function(e){return typeof e=="string"?e:typeof e=="number"||yE.isBuffer(e)?e.toString():JSON.stringify(e)}});var Wm=J((t1,Hm)=>{var _E=Mn().Buffer,Um=Fc(),bE=Bc(),CE=X("stream"),Mm=jc(),qc=X("util");function $m(t,e){return _E.from(t,e).toString("base64").replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function wE(t,e,r){r=r||"utf8";var n=$m(Mm(t),"binary"),s=$m(Mm(e),r);return qc.format("%s.%s",n,s)}function zm(t){var e=t.header,r=t.payload,n=t.secret||t.privateKey,s=t.encoding,i=bE(e.alg),u=wE(e,r,s),c=i.sign(u,n);return qc.format("%s.%s",u,c)}function Fi(t){var e=t.secret||t.privateKey||t.key,r=new Um(e);this.readable=!0,this.header=t.header,this.encoding=t.encoding,this.secret=this.privateKey=this.key=r,this.payload=new Um(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))}qc.inherits(Fi,CE);Fi.prototype.sign=function(){try{var e=zm({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")}};Fi.sign=zm;Hm.exports=Fi});var tg=J((r1,eg)=>{var Jm=Mn().Buffer,Gm=Fc(),EE=Bc(),AE=X("stream"),Vm=jc(),SE=X("util"),kE=/^[a-zA-Z0-9\-_]+?\.[a-zA-Z0-9\-_]+?\.([a-zA-Z0-9\-_]+)?$/;function DE(t){return Object.prototype.toString.call(t)==="[object Object]"}function TE(t){if(DE(t))return t;try{return JSON.parse(t)}catch{return}}function Km(t){var e=t.split(".",1)[0];return TE(Jm.from(e,"base64").toString("binary"))}function vE(t){return t.split(".",2).join(".")}function Ym(t){return t.split(".")[2]}function RE(t,e){e=e||"utf8";var r=t.split(".")[1];return Jm.from(r,"base64").toString(e)}function Xm(t){return kE.test(t)&&!!Km(t)}function Qm(t,e,r){if(!e){var n=new Error("Missing algorithm parameter for jws.verify");throw n.code="MISSING_ALGORITHM",n}t=Vm(t);var s=Ym(t),i=vE(t),u=EE(e);return u.verify(i,s,r)}function Zm(t,e){if(e=e||{},t=Vm(t),!Xm(t))return null;var r=Km(t);if(!r)return null;var n=RE(t);return(r.typ==="JWT"||e.json)&&(n=JSON.parse(n,e.encoding)),{header:r,payload:n,signature:Ym(t)}}function Gn(t){t=t||{};var e=t.secret||t.publicKey||t.key,r=new Gm(e);this.readable=!0,this.algorithm=t.algorithm,this.encoding=t.encoding,this.secret=this.publicKey=this.key=r,this.signature=new Gm(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))}SE.inherits(Gn,AE);Gn.prototype.verify=function(){try{var e=Qm(this.signature.buffer,this.algorithm,this.key.buffer),r=Zm(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")}};Gn.decode=Zm;Gn.isValid=Xm;Gn.verify=Qm;eg.exports=Gn});var Lc=J(Mr=>{var rg=Wm(),xi=tg(),OE=["HS256","HS384","HS512","RS256","RS384","RS512","PS256","PS384","PS512","ES256","ES384","ES512"];Mr.ALGORITHMS=OE;Mr.sign=rg.sign;Mr.verify=xi.verify;Mr.decode=xi.decode;Mr.isValid=xi.isValid;Mr.createSign=function(e){return new rg(e)};Mr.createVerify=function(e){return new xi(e)}});var yg=J(Ii=>{"use strict";Object.defineProperty(Ii,"__esModule",{value:!0});Ii.GoogleToken=void 0;var ng=Pi(X("fs")),FE=Ve(),xE=Pi(Lc()),PE=Pi(X("path")),IE=X("util");function Pi(t,e){if(typeof WeakMap=="function")var r=new WeakMap,n=new WeakMap;return(Pi=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 NE(t,e){dg(t,e),e.add(t)}function BE(t,e,r){dg(t,e),e.set(t,r)}function dg(t,e){if(e.has(t))throw new TypeError("Cannot initialize the same private elements twice on an object")}function sg(t,e,r){return t.set(zt(t,e),r),r}function og(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 ig(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,mg(n.key),n)}}function hg(t,e,r){return e&&ig(t.prototype,e),r&&ig(t,r),Object.defineProperty(t,"prototype",{writable:!1}),t}function pg(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function jE(t,e,r){return e=Ls(e),qE(t,Wc()?Reflect.construct(e,r||[],Ls(t).constructor):e.apply(t,r))}function qE(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 LE(t)}function LE(t){if(t===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}function UE(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 Uc(t){var e=typeof Map=="function"?new Map:void 0;return Uc=function(n){if(n===null||!$E(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 ME(n,arguments,Ls(this).constructor)}return s.prototype=Object.create(n.prototype,{constructor:{value:s,enumerable:!1,writable:!0,configurable:!0}}),qs(s,n)},Uc(t)}function ME(t,e,r){if(Wc())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 Wc(){try{var t=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(Wc=function(){return!!t})()}function $E(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 Ls(t){return Ls=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},Ls(t)}function mt(t,e,r){return(e=mg(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function mg(t){var e=zE(t,"string");return Cr(e)=="symbol"?e:e+""}function zE(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(R,S,_,y){var m=S&&S.prototype instanceof c?S:c,D=Object.create(m.prototype);return gt(D,"_invoke",(function(C,E,v){var x,$,V,U=0,Q=v||[],ne=!1,ae={p:0,n:0,v:t,a:fe,f:fe.bind(t,4),d:function(Ae,oe){return x=Ae,$=0,V=t,ae.n=oe,u}};function fe(ye,Ae){for($=ye,V=Ae,e=0;!ne&&U&&!oe&&e<Q.length;e++){var oe,pe=Q[e],G=ae.p,K=pe[2];ye>3?(oe=K===Ae)&&(V=pe[($=pe[4])?5:($=3,3)],pe[4]=pe[5]=t):pe[0]<=G&&((oe=ye<2&&G<pe[1])?($=0,ae.v=Ae,ae.n=pe[1]):G<K&&(oe=ye<3||pe[0]>Ae||Ae>K)&&(pe[4]=ye,pe[5]=Ae,ae.n=K,$=0))}if(oe||ye>1)return u;throw ne=!0,Ae}return function(ye,Ae,oe){if(U>1)throw TypeError("Generator is already running");for(ne&&Ae===1&&fe(Ae,oe),$=Ae,V=oe;(e=$<2?t:V)||!ne;){x||($?$<3?($>1&&(ae.n=-1),fe($,V)):ae.n=V:ae.v=V);try{if(U=2,x){if($||(ye="next"),e=x[ye]){if(!(e=e.call(x,V)))throw TypeError("iterator result is not an object");if(!e.done)return e;V=e.value,$<2&&($=0)}else $===1&&(e=x.return)&&e.call(x),$<2&&(V=TypeError("The iterator does not provide a '"+ye+"' method"),$=1);x=t}else if((e=(ne=ae.n<0)?V:C.call(E,ae))!==u)break}catch(pe){x=t,$=1,V=pe}finally{U=1}}return{value:e,done:ne}}})(R,_,y),!0),D}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(R){return Object.setPrototypeOf?Object.setPrototypeOf(R,h):(R.__proto__=h,gt(R,s,"GeneratorFunction")),R.prototype=Object.create(p),R}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,R){gt(u,A,function(S){return this._invoke(A,R,S)})};d("next",0),d("throw",1),d("return",2)}},gt(t,e,r,n)}function ag(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 Jn(t){return function(){var e=this,r=arguments;return new Promise(function(n,s){var i=t.apply(e,r);function u(l){ag(i,n,s,u,c,"next",l)}function c(l){ag(i,n,s,u,c,"throw",l)}u(void 0)})}}var ug=ng.readFile?(0,IE.promisify)(ng.readFile):Jn(yt().m(function t(){return yt().w(function(e){for(;;)switch(e.n){case 0:throw new js("use key rather than keyFile.","MISSING_CREDENTIALS");case 1:return e.a(2)}},t)})),cg="https://oauth2.googleapis.com/token",HE="https://oauth2.googleapis.com/revoke?token=",js=(function(t){function e(r,n){var s;return pg(this,e),s=jE(this,e,[r]),mt(s,"code",void 0),s.code=n,s}return UE(e,t),hg(e)})(Uc(Error)),Bs=new WeakMap,er=new WeakSet,s1=Ii.GoogleToken=(function(){function t(e){pg(this,t),NE(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,FE.request)(n)}}),BE(this,Bs,void 0),zt(er,this,gg).call(this,e)}return hg(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,lg).call(this,n).then(function(i){return s(null,i)},r);return}return zt(er,this,lg).call(this,n)}},{key:"getCredentials",value:(function(){var e=Jn(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=PE.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,ug(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 js("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,ug(s,"utf8");case 5:return d=A.v,A.a(2,{privateKey:d});case 6:throw new js("*.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 js("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,fg).call(this).then(function(){return r()},r);return}return zt(er,this,fg).call(this)}}])})();function lg(t){return Mc.apply(this,arguments)}function Mc(){return Mc=Jn(yt().m(function t(e){return yt().w(function(r){for(;;)switch(r.n){case 0:if(!(og(Bs,this)&&!e.forceRefresh)){r.n=1;break}return r.a(2,og(Bs,this));case 1:return r.p=1,r.n=2,sg(Bs,this,zt(er,this,WE).call(this,e));case 2:return r.a(2,r.v);case 3:return r.p=3,sg(Bs,this,void 0),r.f(3);case 4:return r.a(2)}},t,this,[[1,,3,4]])})),Mc.apply(this,arguments)}function WE(t){return $c.apply(this,arguments)}function $c(){return $c=Jn(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,GE).call(this);case 4:return n.a(2,zt(er,this,JE).call(this))}},t,this)})),$c.apply(this,arguments)}function GE(){if(!this.iss)throw new js("email is required.","MISSING_CREDENTIALS")}function fg(){return zc.apply(this,arguments)}function zc(){return zc=Jn(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=HE+this.accessToken,r.n=2,this.transporter.request({url:e,retry:!0});case 2:zt(er,this,gg).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)})),zc.apply(this,arguments)}function gg(){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 JE(){return Hc.apply(this,arguments)}function Hc(){return Hc=Jn(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:cg,exp:e+3600,iat:e,sub:this.sub},r),s=xE.sign({header:{alg:"RS256"},payload:n,secret:this.key}),p.p=1,p.n=2,this.transporter.request({method:"POST",url:cg,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]])})),Hc.apply(this,arguments)}});var Jc=J(Ni=>{"use strict";Object.defineProperty(Ni,"__esModule",{value:!0});Ni.JWTAccess=void 0;var VE=Lc(),KE=Ut(),_g={alg:"RS256",typ:"JWT"},Gc=class t{email;key;keyId;projectId;eagerRefreshThresholdMillis;cache=new KE.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?{..._g,kid:this.keyId}:_g,p=Object.assign(h,r),A=VE.sign({header:d,payload:p,secret:this.key}),R=new Headers({authorization:`Bearer ${A}`});return this.cache.set(s,{expiration:l*1e3,headers:R}),R}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)}})})}};Ni.JWTAccess=Gc});var Kc=J(ji=>{"use strict";Object.defineProperty(ji,"__esModule",{value:!0});ji.JWT=void 0;var bg=yg(),YE=Jc(),XE=cn(),Bi=pt(),Vc=class t extends XE.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!==Bi.DEFAULT_UNIVERSE;if(this.subject&&this.universeDomain!==Bi.DEFAULT_UNIVERSE)throw new RangeError(`Service Account user is configured for the credential. Domain-wide delegation is not supported in universes other than ${Bi.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 YE.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!==Bi.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 bg.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 bg.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.")}};ji.JWT=Vc});var Xc=J(Vn=>{"use strict";Object.defineProperty(Vn,"__esModule",{value:!0});Vn.UserRefreshClient=Vn.USER_REFRESH_ACCOUNT_TYPE=void 0;var QE=cn(),ZE=pt();Vn.USER_REFRESH_ACCOUNT_TYPE="authorized_user";var Yc=class t extends QE.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 ZE.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}};Vn.UserRefreshClient=Yc});var Zc=J(Kn=>{"use strict";Object.defineProperty(Kn,"__esModule",{value:!0});Kn.Impersonated=Kn.IMPERSONATED_ACCOUNT_TYPE=void 0;var Cg=cn(),eA=Ve(),tA=Ut();Kn.IMPERSONATED_ACCOUNT_TYPE="impersonated_service_account";var Qc=class t extends Cg.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 Cg.OAuth2Client,this.targetPrincipal=e.targetPrincipal??"",this.delegates=e.delegates??[],this.targetScopes=e.targetScopes??[],this.lifetime=e.lifetime??3600,!!!(0,tA.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 eA.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}};Kn.Impersonated=Qc});var tl=J(Us=>{"use strict";Object.defineProperty(Us,"__esModule",{value:!0});Us.OAuthClientAuthHandler=void 0;Us.getErrorFromOAuthErrorResponse=sA;var Yn=Ve(),rA=Os(),nA=["PUT","POST","PATCH"],el=class{#e=(0,rA.createCrypto)();#t;transporter;constructor(e){e&&"clientId"in e?(this.#t=e,this.transporter=new Yn.Gaxios):(this.#t=e?.clientAuthentication,this.transporter=e?.transporter||new Yn.Gaxios)}applyClientAuthenticationOptions(e,r){e.headers=Yn.Gaxios.mergeHeaders(e.headers),this.injectAuthenticatedHeaders(e,r),r||this.injectAuthenticatedRequestBody(e)}injectAuthenticatedHeaders(e,r){if(r)e.headers=Yn.Gaxios.mergeHeaders(e.headers,{authorization:`Bearer ${r}`});else if(this.#t?.confidentialClientType==="basic"){e.headers=Yn.Gaxios.mergeHeaders(e.headers);let n=this.#t.clientId,s=this.#t.clientSecret||"",i=this.#e.encodeBase64StringUtf8(`${n}:${s}`);Yn.Gaxios.mergeHeaders(e.headers,{authorization:`Basic ${i}`})}}injectAuthenticatedRequestBody(e){if(this.#t?.confidentialClientType==="request-body"){let r=(e.method||"GET").toUpperCase();if(!nA.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"]}}}};Us.OAuthClientAuthHandler=el;function sA(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 Li=J(qi=>{"use strict";Object.defineProperty(qi,"__esModule",{value:!0});qi.StsCredentials=void 0;var oA=Ve(),iA=pt(),wg=tl(),aA=Ut(),rl=class t extends wg.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))};iA.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 oA.GaxiosError&&u.response?(0,wg.getErrorFromOAuthErrorResponse)(u.response.data,u):u}}};qi.StsCredentials=rl});var $r=J(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 uA=Ve(),cA=X("stream"),nl=pt(),lA=Li(),Eg=Ut(),fA=_c(),dA="urn:ietf:params:oauth:grant-type:token-exchange",hA="urn:ietf:params:oauth:token-type:access_token",sl="https://www.googleapis.com/auth/cloud-platform",pA=3600;Tt.EXPIRATION_TIME_OFFSET=300*1e3;Tt.EXTERNAL_ACCOUNT_TYPE="external_account";Tt.CLOUD_RESOURCE_MANAGER="https://cloudresourcemanager.googleapis.com/v1/projects/";var mA="//iam\\.googleapis\\.com/locations/[^/]+/workforcePools/[^/]+/providers/.+",gA="https://sts.{universeDomain}/v1/token",ol=class t extends nl.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,Eg.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")??gA.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,Eg.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 lA.StsCredentials({tokenExchangeEndpoint:this.tokenUrl,clientAuthentication:this.clientAuth}),this.scopes=r.get("scopes")||[sl],this.cachedAccessToken=null,this.audience=r.get("audience"),this.subjectTokenType=u,this.workforcePoolUserProject=c;let p=new RegExp(mA);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=pA),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}`};nl.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=uA.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 cA.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:dA,audience:this.audience,requestedTokenType:hA,subjectToken:e,subjectTokenType:this.subjectTokenType,scope:this.serviceAccountImpersonationUrl?[sl]: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"}};nl.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||[sl]}getMetricsHeaderValue(){let e=process.version.replace(/^v/,""),r=this.serviceAccountImpersonationUrl!==void 0,n=this.credentialSourceType?this.credentialSourceType:"unknown";return`gl-node/${e} auth/${fA.pkg.version} google-byoid-sdk source/${n} sa-impersonation/${r} config-lifetime/${this.configLifetimeRequested}`}getTokenUrl(){return this.tokenUrl}};Tt.BaseExternalAccountClient=ol});var Ag=J(Ui=>{"use strict";Object.defineProperty(Ui,"__esModule",{value:!0});Ui.FileSubjectTokenSupplier=void 0;var al=X("util"),ul=X("fs"),yA=(0,al.promisify)(ul.readFile??(()=>{})),_A=(0,al.promisify)(ul.realpath??(()=>{})),bA=(0,al.promisify)(ul.lstat??(()=>{})),il=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 _A(e),!(await bA(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 yA(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}};Ui.FileSubjectTokenSupplier=il});var Sg=J(Mi=>{"use strict";Object.defineProperty(Mi,"__esModule",{value:!0});Mi.UrlSubjectTokenSupplier=void 0;var CA=pt(),cl=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};CA.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}};Mi.UrlSubjectTokenSupplier=cl});var kg=J(_t=>{"use strict";Object.defineProperty(_t,"__esModule",{value:!0});_t.CertificateSubjectTokenSupplier=_t.InvalidConfigurationError=_t.CertificateSourceUnavailableError=_t.CERTIFICATE_CONFIGURATION_ENV_VARIABLE=void 0;var $i=Ut(),zi=X("fs"),Hi=X("crypto"),wA=X("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 ll=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 wA.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,$i.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,$i.isValidFile)(r))return r;throw new tr(`Path from environment variable "${_t.CERTIFICATE_CONFIGURATION_ENV_VARIABLE}" is invalid: ${r}`)}let n=(0,$i.getWellKnownCertificateConfigFileLocation)();if(await(0,$i.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 zi.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 zi.promises.readFile(e),new Hi.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 zi.promises.readFile(r),(0,Hi.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 Hi.X509Certificate(e);if(!this.trustChainPath)return JSON.stringify([r.raw.toString("base64")]);try{let i=((await zi.promises.readFile(this.trustChainPath,"utf8")).match(/-----BEGIN CERTIFICATE-----[^-]+-----END CERTIFICATE-----/g)??[]).map((l,h)=>{try{return new Hi.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=ll});var hl=J(Wi=>{"use strict";Object.defineProperty(Wi,"__esModule",{value:!0});Wi.IdentityPoolClient=void 0;var EA=$r(),fl=Ut(),AA=Ag(),SA=Sg(),Dg=kg(),kA=Li(),Tg=Ve(),dl=class t extends EA.BaseExternalAccountClient{subjectTokenSupplier;constructor(e){super(e);let r=(0,fl.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,fl.originalOrCamelOptions)(n),u=(0,fl.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 AA.FileSubjectTokenSupplier({filePath:h,formatType:c,subjectTokenFieldName:l});else if(d)this.credentialSourceType="url",this.subjectTokenSupplier=new SA.UrlSubjectTokenSupplier({url:d,formatType:c,subjectTokenFieldName:l,headers:A,additionalGaxiosOptions:t.RETRY_CONFIG});else if(p){this.credentialSourceType="certificate";let R=new Dg.CertificateSubjectTokenSupplier({useDefaultCertificateConfig:p.use_default_certificate_config,certificateConfigLocation:p.certificate_config_location,trustChainPath:p.trust_chain_path});this.subjectTokenSupplier=R}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 Dg.CertificateSubjectTokenSupplier){let r=await this.subjectTokenSupplier.createMtlsHttpsAgent();this.stsCredential=new kA.StsCredentials({tokenExchangeEndpoint:this.getTokenUrl(),clientAuthentication:this.clientAuth,transporter:new Tg.Gaxios({agent:r})}),this.transporter=new Tg.Gaxios({...this.transporter.defaults||{},agent:r})}return e}};Wi.IdentityPoolClient=dl});var ml=J(Ji=>{"use strict";Object.defineProperty(Ji,"__esModule",{value:!0});Ji.AwsRequestSigner=void 0;var Gi=Ve(),Rg=Os(),vg="AWS4-HMAC-SHA256",DA="aws4_request",pl=class{getCredentials;region;crypto;constructor(e,r){this.getCredentials=e,this.region=r,this.crypto=(0,Rg.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 vA({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=Gi.Gaxios.mergeHeaders(h.amzDate?{"x-amz-date":h.amzDate}:{},{authorization:h.authorizationHeader,host:l.host},u||{});c.token&&Gi.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}};Ji.AwsRequestSigner=pl;async function Ms(t,e,r){return await t.signWithHmacSha256(e,r)}async function TA(t,e,r,n,s){let i=await Ms(t,`AWS4${e}`,r),u=await Ms(t,i,n),c=await Ms(t,u,s);return await Ms(t,c,"aws4_request")}async function vA(t){let e=Gi.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=Gi.Gaxios.mergeHeaders({host:t.host},e.has("date")?{}:{"x-amz-date":i},e),l="",h=[...c.keys()].sort();h.forEach(D=>{l+=`${D}:${c.get(D)}
53
53
  `});let d=h.join(";"),p=await t.crypto.sha256DigestHex(r),A=`${t.method.toUpperCase()}
54
54
  ${t.canonicalUri}
55
55
  ${t.canonicalQuerystring}
56
56
  ${l}
57
57
  ${d}
58
- ${p}`,R=`${u}/${t.region}/${n}/${kA}`,S=`${Tg}
58
+ ${p}`,R=`${u}/${t.region}/${n}/${DA}`,S=`${vg}
59
59
  ${i}
60
60
  ${R}
61
- `+await t.crypto.sha256DigestHex(A),_=await DA(t.crypto,t.securityCredentials.secretAccessKey,u,t.region,n),y=await Ms(t.crypto,_,S),m=`${Tg} Credential=${t.securityCredentials.accessKeyId}/${R}, SignedHeaders=${d}, Signature=${(0,vg.fromArrayBufferToHex)(y)}`;return{amzDate:e.has("date")?void 0:i,authorizationHeader:m,canonicalQuerystring:t.canonicalQuerystring}}});var Rg=J(Ki=>{"use strict";Object.defineProperty(Ki,"__esModule",{value:!0});Ki.DefaultAwsSecurityCredentialsSupplier=void 0;var Vi=pt(),ml=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};Vi.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 Vi.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 Vi.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 Vi.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}};Ki.DefaultAwsSecurityCredentialsSupplier=ml});var yl=J(Yi=>{"use strict";Object.defineProperty(Yi,"__esModule",{value:!0});Yi.AwsClient=void 0;var vA=pl(),RA=$r(),OA=Rg(),Og=Ut(),FA=Ve(),gl=class t extends RA.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,Og.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,Og.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 OA.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 vA.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 FA.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}))}};Yi.AwsClient=gl});var El=J(qe=>{"use strict";Object.defineProperty(qe,"__esModule",{value:!0});qe.InvalidSubjectTokenError=qe.InvalidMessageFieldError=qe.InvalidCodeFieldError=qe.InvalidTokenTypeFieldError=qe.InvalidExpirationTimeFieldError=qe.InvalidSuccessFieldError=qe.InvalidVersionFieldError=qe.ExecutableResponseError=qe.ExecutableResponse=void 0;var Xi="urn:ietf:params:oauth:token-type:saml2",_l="urn:ietf:params:oauth:token-type:id_token",bl="urn:ietf:params:oauth:token-type:jwt",Cl=class{version;success;expirationTime;tokenType;errorCode;errorMessage;subjectToken;constructor(e){if(!e.version)throw new Qi("Executable response must contain a 'version' field.");if(e.success===void 0)throw new Zi("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!==Xi&&this.tokenType!==_l&&this.tokenType!==bl)throw new ea(`Executable response must contain a 'token_type' field when successful and it must be one of ${_l}, ${bl}, or ${Xi}.`);if(this.tokenType===Xi){if(!e.saml_response)throw new $s(`Executable response must contain a 'saml_response' field when token_type=${Xi}.`);this.subjectToken=e.saml_response}else{if(!e.id_token)throw new $s(`Executable response must contain a 'id_token' field when token_type=${_l} or ${bl}.`);this.subjectToken=e.id_token}}else{if(!e.code)throw new ta("Executable response must contain a 'code' field when unsuccessful.");if(!e.message)throw new ra("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)}};qe.ExecutableResponse=Cl;var rr=class extends Error{constructor(e){super(e),Object.setPrototypeOf(this,new.target.prototype)}};qe.ExecutableResponseError=rr;var Qi=class extends rr{};qe.InvalidVersionFieldError=Qi;var Zi=class extends rr{};qe.InvalidSuccessFieldError=Zi;var wl=class extends rr{};qe.InvalidExpirationTimeFieldError=wl;var ea=class extends rr{};qe.InvalidTokenTypeFieldError=ea;var ta=class extends rr{};qe.InvalidCodeFieldError=ta;var ra=class extends rr{};qe.InvalidMessageFieldError=ra;var $s=class extends rr{};qe.InvalidSubjectTokenError=$s});var kl=J(Xn=>{"use strict";Object.defineProperty(Xn,"__esModule",{value:!0});Xn.PluggableAuthHandler=Xn.ExecutableError=void 0;var ln=El(),xA=X("child_process"),Al=X("fs"),na=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)}};Xn.ExecutableError=na;var Sl=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=xA.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 ln.ExecutableResponse(l);return r(h)}catch(l){return l instanceof ln.ExecutableResponseError?n(l):n(new ln.ExecutableResponseError(`The executable returned an invalid response: ${i}`))}else return n(new na(i,c.toString()))})})}async retrieveCachedResponse(){if(!this.outputFile||this.outputFile.length===0)return;let e;try{e=await Al.promises.realpath(this.outputFile)}catch{return}if(!(await Al.promises.lstat(e)).isFile())return;let r=await Al.promises.readFile(e,{encoding:"utf8"});if(r!=="")try{let n=JSON.parse(r);return new ln.ExecutableResponse(n).isValid()?new ln.ExecutableResponse(n):void 0}catch(n){throw n instanceof ln.ExecutableResponseError?n:new ln.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}};Xn.PluggableAuthHandler=Sl});var Tl=J(Qn=>{"use strict";Object.defineProperty(Qn,"__esModule",{value:!0});Qn.PluggableAuthClient=Qn.ExecutableError=void 0;var PA=$r(),IA=El(),Fg=kl(),NA=kl();Object.defineProperty(Qn,"ExecutableError",{enumerable:!0,get:function(){return NA.ExecutableError}});var BA=30*1e3,xg=5*1e3,Pg=120*1e3,jA="GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES",Ig=1,Dl=class extends PA.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=BA;else if(this.timeoutMillis=e.credential_source.executable.timeout_millis,this.timeoutMillis<xg||this.timeoutMillis>Pg)throw new Error(`Timeout must be between ${xg} and ${Pg} milliseconds.`);this.outputFile=e.credential_source.executable.output_file,this.handler=new Fg.PluggableAuthHandler({command:this.command,timeoutMillis:this.timeoutMillis,outputFile:this.outputFile}),this.credentialSourceType="executable"}async retrieveSubjectToken(){if(process.env[jA]!=="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>Ig)throw new Error(`Version of executable is not currently supported, maximum supported version is ${Ig}.`);if(!e.success)throw new Fg.ExecutableError(e.errorMessage,e.errorCode);if(this.outputFile&&!e.expirationTime)throw new IA.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}};Qn.PluggableAuthClient=Dl});var Rl=J(sa=>{"use strict";Object.defineProperty(sa,"__esModule",{value:!0});sa.ExternalAccountClient=void 0;var qA=$r(),LA=dl(),UA=yl(),MA=Tl(),vl=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===qA.EXTERNAL_ACCOUNT_TYPE?e.credential_source?.environment_id?new UA.AwsClient(e):e.credential_source?.executable?new MA.PluggableAuthClient(e):new LA.IdentityPoolClient(e):null}};sa.ExternalAccountClient=vl});var qg=J(Zn=>{"use strict";Object.defineProperty(Zn,"__esModule",{value:!0});Zn.ExternalAccountAuthorizedUserClient=Zn.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE=void 0;var Bg=pt(),Ng=el(),jg=Ve(),$A=X("stream"),zA=$r();Zn.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE="external_account_authorized_user";var HA="https://sts.{universeDomain}/v1/oauthtoken",Ol=class t extends Ng.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})};Bg.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 jg.GaxiosError&&s.response?(0,Ng.getErrorFromOAuthErrorResponse)(s.response.data,s):s}}},Fl=class extends Bg.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 Ol({tokenRefreshEndpoint:e.token_url??HA.replace("{universeDomain}",this.universeDomain),transporter:this.transporter,clientAuthentication:r}),this.cachedAccessToken=null,this.quotaProjectId=e.quota_project_id,typeof e?.eagerRefreshThresholdMillis!="number"?this.eagerRefreshThresholdMillis=zA.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=jg.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 $A.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}};Zn.ExternalAccountAuthorizedUserClient=Fl});var $g=J(Ht=>{"use strict";Object.defineProperty(Ht,"__esModule",{value:!0});Ht.GoogleAuth=Ht.GoogleAuthExceptionMessages=void 0;var WA=X("child_process"),zs=X("fs"),GA=Ve(),Hs=Rs(),JA=X("os"),xl=X("path"),VA=Os(),KA=Dc(),YA=vc(),XA=Rc(),es=Vc(),Lg=Yc(),ts=Qc(),QA=Rl(),Ws=$r(),Pl=pt(),Ug=qg(),Mg=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.
61
+ `+await t.crypto.sha256DigestHex(A),_=await TA(t.crypto,t.securityCredentials.secretAccessKey,u,t.region,n),y=await Ms(t.crypto,_,S),m=`${vg} Credential=${t.securityCredentials.accessKeyId}/${R}, SignedHeaders=${d}, Signature=${(0,Rg.fromArrayBufferToHex)(y)}`;return{amzDate:e.has("date")?void 0:i,authorizationHeader:m,canonicalQuerystring:t.canonicalQuerystring}}});var Og=J(Ki=>{"use strict";Object.defineProperty(Ki,"__esModule",{value:!0});Ki.DefaultAwsSecurityCredentialsSupplier=void 0;var Vi=pt(),gl=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};Vi.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 Vi.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 Vi.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 Vi.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}};Ki.DefaultAwsSecurityCredentialsSupplier=gl});var _l=J(Yi=>{"use strict";Object.defineProperty(Yi,"__esModule",{value:!0});Yi.AwsClient=void 0;var RA=ml(),OA=$r(),FA=Og(),Fg=Ut(),xA=Ve(),yl=class t extends OA.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,Fg.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,Fg.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 FA.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 RA.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 xA.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}))}};Yi.AwsClient=yl});var Al=J(qe=>{"use strict";Object.defineProperty(qe,"__esModule",{value:!0});qe.InvalidSubjectTokenError=qe.InvalidMessageFieldError=qe.InvalidCodeFieldError=qe.InvalidTokenTypeFieldError=qe.InvalidExpirationTimeFieldError=qe.InvalidSuccessFieldError=qe.InvalidVersionFieldError=qe.ExecutableResponseError=qe.ExecutableResponse=void 0;var Xi="urn:ietf:params:oauth:token-type:saml2",bl="urn:ietf:params:oauth:token-type:id_token",Cl="urn:ietf:params:oauth:token-type:jwt",wl=class{version;success;expirationTime;tokenType;errorCode;errorMessage;subjectToken;constructor(e){if(!e.version)throw new Qi("Executable response must contain a 'version' field.");if(e.success===void 0)throw new Zi("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!==Xi&&this.tokenType!==bl&&this.tokenType!==Cl)throw new ea(`Executable response must contain a 'token_type' field when successful and it must be one of ${bl}, ${Cl}, or ${Xi}.`);if(this.tokenType===Xi){if(!e.saml_response)throw new $s(`Executable response must contain a 'saml_response' field when token_type=${Xi}.`);this.subjectToken=e.saml_response}else{if(!e.id_token)throw new $s(`Executable response must contain a 'id_token' field when token_type=${bl} or ${Cl}.`);this.subjectToken=e.id_token}}else{if(!e.code)throw new ta("Executable response must contain a 'code' field when unsuccessful.");if(!e.message)throw new ra("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)}};qe.ExecutableResponse=wl;var rr=class extends Error{constructor(e){super(e),Object.setPrototypeOf(this,new.target.prototype)}};qe.ExecutableResponseError=rr;var Qi=class extends rr{};qe.InvalidVersionFieldError=Qi;var Zi=class extends rr{};qe.InvalidSuccessFieldError=Zi;var El=class extends rr{};qe.InvalidExpirationTimeFieldError=El;var ea=class extends rr{};qe.InvalidTokenTypeFieldError=ea;var ta=class extends rr{};qe.InvalidCodeFieldError=ta;var ra=class extends rr{};qe.InvalidMessageFieldError=ra;var $s=class extends rr{};qe.InvalidSubjectTokenError=$s});var Dl=J(Xn=>{"use strict";Object.defineProperty(Xn,"__esModule",{value:!0});Xn.PluggableAuthHandler=Xn.ExecutableError=void 0;var ln=Al(),PA=X("child_process"),Sl=X("fs"),na=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)}};Xn.ExecutableError=na;var kl=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=PA.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 ln.ExecutableResponse(l);return r(h)}catch(l){return l instanceof ln.ExecutableResponseError?n(l):n(new ln.ExecutableResponseError(`The executable returned an invalid response: ${i}`))}else return n(new na(i,c.toString()))})})}async retrieveCachedResponse(){if(!this.outputFile||this.outputFile.length===0)return;let e;try{e=await Sl.promises.realpath(this.outputFile)}catch{return}if(!(await Sl.promises.lstat(e)).isFile())return;let r=await Sl.promises.readFile(e,{encoding:"utf8"});if(r!=="")try{let n=JSON.parse(r);return new ln.ExecutableResponse(n).isValid()?new ln.ExecutableResponse(n):void 0}catch(n){throw n instanceof ln.ExecutableResponseError?n:new ln.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}};Xn.PluggableAuthHandler=kl});var vl=J(Qn=>{"use strict";Object.defineProperty(Qn,"__esModule",{value:!0});Qn.PluggableAuthClient=Qn.ExecutableError=void 0;var IA=$r(),NA=Al(),xg=Dl(),BA=Dl();Object.defineProperty(Qn,"ExecutableError",{enumerable:!0,get:function(){return BA.ExecutableError}});var jA=30*1e3,Pg=5*1e3,Ig=120*1e3,qA="GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES",Ng=1,Tl=class extends IA.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=jA;else if(this.timeoutMillis=e.credential_source.executable.timeout_millis,this.timeoutMillis<Pg||this.timeoutMillis>Ig)throw new Error(`Timeout must be between ${Pg} and ${Ig} milliseconds.`);this.outputFile=e.credential_source.executable.output_file,this.handler=new xg.PluggableAuthHandler({command:this.command,timeoutMillis:this.timeoutMillis,outputFile:this.outputFile}),this.credentialSourceType="executable"}async retrieveSubjectToken(){if(process.env[qA]!=="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>Ng)throw new Error(`Version of executable is not currently supported, maximum supported version is ${Ng}.`);if(!e.success)throw new xg.ExecutableError(e.errorMessage,e.errorCode);if(this.outputFile&&!e.expirationTime)throw new NA.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}};Qn.PluggableAuthClient=Tl});var Ol=J(sa=>{"use strict";Object.defineProperty(sa,"__esModule",{value:!0});sa.ExternalAccountClient=void 0;var LA=$r(),UA=hl(),MA=_l(),$A=vl(),Rl=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===LA.EXTERNAL_ACCOUNT_TYPE?e.credential_source?.environment_id?new MA.AwsClient(e):e.credential_source?.executable?new $A.PluggableAuthClient(e):new UA.IdentityPoolClient(e):null}};sa.ExternalAccountClient=Rl});var Lg=J(Zn=>{"use strict";Object.defineProperty(Zn,"__esModule",{value:!0});Zn.ExternalAccountAuthorizedUserClient=Zn.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE=void 0;var jg=pt(),Bg=tl(),qg=Ve(),zA=X("stream"),HA=$r();Zn.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE="external_account_authorized_user";var WA="https://sts.{universeDomain}/v1/oauthtoken",Fl=class t extends Bg.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})};jg.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 qg.GaxiosError&&s.response?(0,Bg.getErrorFromOAuthErrorResponse)(s.response.data,s):s}}},xl=class extends jg.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 Fl({tokenRefreshEndpoint:e.token_url??WA.replace("{universeDomain}",this.universeDomain),transporter:this.transporter,clientAuthentication:r}),this.cachedAccessToken=null,this.quotaProjectId=e.quota_project_id,typeof e?.eagerRefreshThresholdMillis!="number"?this.eagerRefreshThresholdMillis=HA.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=qg.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 zA.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}};Zn.ExternalAccountAuthorizedUserClient=xl});var zg=J(Ht=>{"use strict";Object.defineProperty(Ht,"__esModule",{value:!0});Ht.GoogleAuth=Ht.GoogleAuthExceptionMessages=void 0;var GA=X("child_process"),zs=X("fs"),JA=Ve(),Hs=Rs(),VA=X("os"),Pl=X("path"),KA=Os(),YA=Tc(),XA=Rc(),QA=Oc(),es=Kc(),Ug=Xc(),ts=Zc(),ZA=Ol(),Ws=$r(),Il=pt(),Mg=Lg(),$g=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 Il=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 Hs.universe("universe-domain"),e||=Pl.DEFAULT_UNIVERSE}catch(r){if(r&&r?.response?.status===404)e=Pl.DEFAULT_UNIVERSE;else throw r}return e}async getUniverseDomain(){let e=(0,Mg.originalOrCamelOptions)(this.clientOptions).get("universe_domain");try{e??=(await this.getClient()).universeDomain}catch{e??=Pl.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 es.JWT?r.scopes=this.scopes:r instanceof Ws.BaseExternalAccountClient&&(r.scopes=this.getAnyScopes()),await this.#t(r);if(r=await this._tryGetApplicationCredentialsFromWellKnownFile(e),r)return r instanceof es.JWT?r.scopes=this.scopes:r instanceof Ws.BaseExternalAccountClient&&(r.scopes=this.getAnyScopes()),await this.#t(r);if(await this._checkIsGCE())return e.scopes=this.getAnyScopes(),await this.#t(new KA.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=Hs.getGCPResidency()||await Hs.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=xl.join(s,".config"))}return r&&(r=xl.join(r,"gcloud","application_default_credentials.json"),zs.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=zs.realpathSync(e),!zs.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=zs.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!==ts.IMPERSONATED_ACCOUNT_TYPE)throw new Error(`The incoming JSON object does not have the "${ts.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 ts.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,Mg.originalOrCamelOptions)(r).get("universe_domain");return e.type===Lg.USER_REFRESH_ACCOUNT_TYPE?(n=new Lg.UserRefreshClient(r),n.fromJSON(e)):e.type===ts.IMPERSONATED_ACCOUNT_TYPE?n=this.fromImpersonatedJSON(e):e.type===Ws.EXTERNAL_ACCOUNT_TYPE?(n=QA.ExternalAccountClient.fromJSON({...e,...r}),n.scopes=this.getAnyScopes()):e.type===Ug.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE?n=new Ug.ExternalAccountAuthorizedUserClient({...e,...r}):(r.scopes=this.scopes,n=new es.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 es.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 es.JWT({...r,apiKey:e})}_isWindows(){let e=JA.platform();return!!(e&&e.length>=3&&e.substring(0,3).toLowerCase()==="win")}async getDefaultServiceProjectId(){return new Promise(e=>{(0,WA.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!==Ws.EXTERNAL_ACCOUNT_TYPE?null:await(await this.getClient()).getProjectId()}async getGCEProjectId(){try{return await Hs.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 ts.Impersonated)return{client_email:e.getTargetPrincipal()};if(e instanceof Ws.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([Hs.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=xl.resolve(this.keyFilename),r=zs.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 YA.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=GA.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,XA.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 ts.Impersonated)return(await n.sign(e)).signedBlob;let i=(0,VA.createCrypto)();if(n instanceof es.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=Il});var zg=J(oa=>{"use strict";Object.defineProperty(oa,"__esModule",{value:!0});oa.IAMAuth=void 0;var Nl=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}}};oa.IAMAuth=Nl});var Hg=J(nr=>{"use strict";Object.defineProperty(nr,"__esModule",{value:!0});nr.DownscopedClient=nr.EXPIRATION_TIME_OFFSET=nr.MAX_ACCESS_BOUNDARY_RULES_COUNT=void 0;var ZA=Ve(),eS=X("stream"),Bl=pt(),tS=Li(),rS="urn:ietf:params:oauth:grant-type:token-exchange",nS="urn:ietf:params:oauth:token-type:access_token",sS="urn:ietf:params:oauth:token-type:access_token";nr.MAX_ACCESS_BOUNDARY_RULES_COUNT=10;nr.EXPIRATION_TIME_OFFSET=300*1e3;var jl=class extends Bl.AuthClient{authClient;credentialAccessBoundary;cachedDownscopedAccessToken;stsCredential;constructor(e,r={accessBoundary:{accessBoundaryRules:[]}}){if(super(e instanceof Bl.AuthClient?{}:e),e instanceof Bl.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 tS.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=ZA.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 eS.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:rS,requestedTokenType:nS,subjectToken:e,subjectTokenType:sS},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=jl});var Wg=J(ia=>{"use strict";Object.defineProperty(ia,"__esModule",{value:!0});ia.PassThroughClient=void 0;var oS=pt(),ql=class extends oS.AuthClient{async request(e){return this.transporter.request(e)}async getAccessToken(){return{}}async getRequestHeaders(){return new Headers}};ia.PassThroughClient=ql});var Ul=J(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 Gg=$g();Object.defineProperty(te,"GoogleAuth",{enumerable:!0,get:function(){return Gg.GoogleAuth}});te.gcpMetadata=Rs();te.gaxios=Ve();var Jg=pt();Object.defineProperty(te,"AuthClient",{enumerable:!0,get:function(){return Jg.AuthClient}});Object.defineProperty(te,"DEFAULT_UNIVERSE",{enumerable:!0,get:function(){return Jg.DEFAULT_UNIVERSE}});var iS=Dc();Object.defineProperty(te,"Compute",{enumerable:!0,get:function(){return iS.Compute}});var aS=Rc();Object.defineProperty(te,"GCPEnv",{enumerable:!0,get:function(){return aS.GCPEnv}});var uS=zg();Object.defineProperty(te,"IAMAuth",{enumerable:!0,get:function(){return uS.IAMAuth}});var cS=vc();Object.defineProperty(te,"IdTokenClient",{enumerable:!0,get:function(){return cS.IdTokenClient}});var lS=Gc();Object.defineProperty(te,"JWTAccess",{enumerable:!0,get:function(){return lS.JWTAccess}});var fS=Vc();Object.defineProperty(te,"JWT",{enumerable:!0,get:function(){return fS.JWT}});var dS=Qc();Object.defineProperty(te,"Impersonated",{enumerable:!0,get:function(){return dS.Impersonated}});var Ll=cn();Object.defineProperty(te,"CodeChallengeMethod",{enumerable:!0,get:function(){return Ll.CodeChallengeMethod}});Object.defineProperty(te,"OAuth2Client",{enumerable:!0,get:function(){return Ll.OAuth2Client}});Object.defineProperty(te,"ClientAuthentication",{enumerable:!0,get:function(){return Ll.ClientAuthentication}});var hS=Ec();Object.defineProperty(te,"LoginTicket",{enumerable:!0,get:function(){return hS.LoginTicket}});var pS=Yc();Object.defineProperty(te,"UserRefreshClient",{enumerable:!0,get:function(){return pS.UserRefreshClient}});var mS=yl();Object.defineProperty(te,"AwsClient",{enumerable:!0,get:function(){return mS.AwsClient}});var gS=pl();Object.defineProperty(te,"AwsRequestSigner",{enumerable:!0,get:function(){return gS.AwsRequestSigner}});var yS=dl();Object.defineProperty(te,"IdentityPoolClient",{enumerable:!0,get:function(){return yS.IdentityPoolClient}});var _S=Rl();Object.defineProperty(te,"ExternalAccountClient",{enumerable:!0,get:function(){return _S.ExternalAccountClient}});var bS=$r();Object.defineProperty(te,"BaseExternalAccountClient",{enumerable:!0,get:function(){return bS.BaseExternalAccountClient}});var CS=Hg();Object.defineProperty(te,"DownscopedClient",{enumerable:!0,get:function(){return CS.DownscopedClient}});var Vg=Tl();Object.defineProperty(te,"PluggableAuthClient",{enumerable:!0,get:function(){return Vg.PluggableAuthClient}});Object.defineProperty(te,"ExecutableError",{enumerable:!0,get:function(){return Vg.ExecutableError}});var wS=Wg();Object.defineProperty(te,"PassThroughClient",{enumerable:!0,get:function(){return wS.PassThroughClient}});var ES=new Gg.GoogleAuth;te.auth=ES});var vy=J((fx,lf)=>{"use strict";var VD=/at\s(?:.*\.)?plugin\s.*\n\s*(.*)/,KD=/(\w*(\.\w*)*)\..*/;lf.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,Ty(n.stack)}};function Ty(t){let e=t.match(VD);return e?e[1].split(/[/\\]/).slice(-1)[0].match(KD)[1]:"anonymous"}lf.exports.extractPluginName=Ty});var Oy=J((dx,Ry)=>{"use strict";Ry.exports=function(e){return e[0]==="@"&&(e=e.slice(1).replace("/","-")),e.replace(/-(.)/g,function(r,n){return n.toUpperCase()})}});var Fy=J((hx,Ia)=>{"use strict";var YD=vy(),XD=Oy(),QD=0;function ff(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=YD(t)+"-auto-"+QD++),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=XD(e.name);return!r&&!t[n]&&(t[n]=t),t}Ia.exports=ff;Ia.exports.default=ff;Ia.exports.fastifyPlugin=ff});var Zs,df=je(()=>{"use strict";Zs=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 Nl=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 Hs.universe("universe-domain"),e||=Il.DEFAULT_UNIVERSE}catch(r){if(r&&r?.response?.status===404)e=Il.DEFAULT_UNIVERSE;else throw r}return e}async getUniverseDomain(){let e=(0,$g.originalOrCamelOptions)(this.clientOptions).get("universe_domain");try{e??=(await this.getClient()).universeDomain}catch{e??=Il.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 es.JWT?r.scopes=this.scopes:r instanceof Ws.BaseExternalAccountClient&&(r.scopes=this.getAnyScopes()),await this.#t(r);if(r=await this._tryGetApplicationCredentialsFromWellKnownFile(e),r)return r instanceof es.JWT?r.scopes=this.scopes:r instanceof Ws.BaseExternalAccountClient&&(r.scopes=this.getAnyScopes()),await this.#t(r);if(await this._checkIsGCE())return e.scopes=this.getAnyScopes(),await this.#t(new YA.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=Hs.getGCPResidency()||await Hs.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=Pl.join(s,".config"))}return r&&(r=Pl.join(r,"gcloud","application_default_credentials.json"),zs.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=zs.realpathSync(e),!zs.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=zs.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!==ts.IMPERSONATED_ACCOUNT_TYPE)throw new Error(`The incoming JSON object does not have the "${ts.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 ts.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,$g.originalOrCamelOptions)(r).get("universe_domain");return e.type===Ug.USER_REFRESH_ACCOUNT_TYPE?(n=new Ug.UserRefreshClient(r),n.fromJSON(e)):e.type===ts.IMPERSONATED_ACCOUNT_TYPE?n=this.fromImpersonatedJSON(e):e.type===Ws.EXTERNAL_ACCOUNT_TYPE?(n=ZA.ExternalAccountClient.fromJSON({...e,...r}),n.scopes=this.getAnyScopes()):e.type===Mg.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE?n=new Mg.ExternalAccountAuthorizedUserClient({...e,...r}):(r.scopes=this.scopes,n=new es.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 es.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 es.JWT({...r,apiKey:e})}_isWindows(){let e=VA.platform();return!!(e&&e.length>=3&&e.substring(0,3).toLowerCase()==="win")}async getDefaultServiceProjectId(){return new Promise(e=>{(0,GA.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!==Ws.EXTERNAL_ACCOUNT_TYPE?null:await(await this.getClient()).getProjectId()}async getGCEProjectId(){try{return await Hs.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 ts.Impersonated)return{client_email:e.getTargetPrincipal()};if(e instanceof Ws.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([Hs.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=Pl.resolve(this.keyFilename),r=zs.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 XA.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=JA.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,QA.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 ts.Impersonated)return(await n.sign(e)).signedBlob;let i=(0,KA.createCrypto)();if(n instanceof es.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=Nl});var Hg=J(oa=>{"use strict";Object.defineProperty(oa,"__esModule",{value:!0});oa.IAMAuth=void 0;var Bl=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}}};oa.IAMAuth=Bl});var Wg=J(nr=>{"use strict";Object.defineProperty(nr,"__esModule",{value:!0});nr.DownscopedClient=nr.EXPIRATION_TIME_OFFSET=nr.MAX_ACCESS_BOUNDARY_RULES_COUNT=void 0;var eS=Ve(),tS=X("stream"),jl=pt(),rS=Li(),nS="urn:ietf:params:oauth:grant-type:token-exchange",sS="urn:ietf:params:oauth:token-type:access_token",oS="urn:ietf:params:oauth:token-type:access_token";nr.MAX_ACCESS_BOUNDARY_RULES_COUNT=10;nr.EXPIRATION_TIME_OFFSET=300*1e3;var ql=class extends jl.AuthClient{authClient;credentialAccessBoundary;cachedDownscopedAccessToken;stsCredential;constructor(e,r={accessBoundary:{accessBoundaryRules:[]}}){if(super(e instanceof jl.AuthClient?{}:e),e instanceof jl.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 rS.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=eS.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 tS.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:nS,requestedTokenType:sS,subjectToken:e,subjectTokenType:oS},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=ql});var Gg=J(ia=>{"use strict";Object.defineProperty(ia,"__esModule",{value:!0});ia.PassThroughClient=void 0;var iS=pt(),Ll=class extends iS.AuthClient{async request(e){return this.transporter.request(e)}async getAccessToken(){return{}}async getRequestHeaders(){return new Headers}};ia.PassThroughClient=Ll});var Ml=J(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 Jg=zg();Object.defineProperty(te,"GoogleAuth",{enumerable:!0,get:function(){return Jg.GoogleAuth}});te.gcpMetadata=Rs();te.gaxios=Ve();var Vg=pt();Object.defineProperty(te,"AuthClient",{enumerable:!0,get:function(){return Vg.AuthClient}});Object.defineProperty(te,"DEFAULT_UNIVERSE",{enumerable:!0,get:function(){return Vg.DEFAULT_UNIVERSE}});var aS=Tc();Object.defineProperty(te,"Compute",{enumerable:!0,get:function(){return aS.Compute}});var uS=Oc();Object.defineProperty(te,"GCPEnv",{enumerable:!0,get:function(){return uS.GCPEnv}});var cS=Hg();Object.defineProperty(te,"IAMAuth",{enumerable:!0,get:function(){return cS.IAMAuth}});var lS=Rc();Object.defineProperty(te,"IdTokenClient",{enumerable:!0,get:function(){return lS.IdTokenClient}});var fS=Jc();Object.defineProperty(te,"JWTAccess",{enumerable:!0,get:function(){return fS.JWTAccess}});var dS=Kc();Object.defineProperty(te,"JWT",{enumerable:!0,get:function(){return dS.JWT}});var hS=Zc();Object.defineProperty(te,"Impersonated",{enumerable:!0,get:function(){return hS.Impersonated}});var Ul=cn();Object.defineProperty(te,"CodeChallengeMethod",{enumerable:!0,get:function(){return Ul.CodeChallengeMethod}});Object.defineProperty(te,"OAuth2Client",{enumerable:!0,get:function(){return Ul.OAuth2Client}});Object.defineProperty(te,"ClientAuthentication",{enumerable:!0,get:function(){return Ul.ClientAuthentication}});var pS=Ac();Object.defineProperty(te,"LoginTicket",{enumerable:!0,get:function(){return pS.LoginTicket}});var mS=Xc();Object.defineProperty(te,"UserRefreshClient",{enumerable:!0,get:function(){return mS.UserRefreshClient}});var gS=_l();Object.defineProperty(te,"AwsClient",{enumerable:!0,get:function(){return gS.AwsClient}});var yS=ml();Object.defineProperty(te,"AwsRequestSigner",{enumerable:!0,get:function(){return yS.AwsRequestSigner}});var _S=hl();Object.defineProperty(te,"IdentityPoolClient",{enumerable:!0,get:function(){return _S.IdentityPoolClient}});var bS=Ol();Object.defineProperty(te,"ExternalAccountClient",{enumerable:!0,get:function(){return bS.ExternalAccountClient}});var CS=$r();Object.defineProperty(te,"BaseExternalAccountClient",{enumerable:!0,get:function(){return CS.BaseExternalAccountClient}});var wS=Wg();Object.defineProperty(te,"DownscopedClient",{enumerable:!0,get:function(){return wS.DownscopedClient}});var Kg=vl();Object.defineProperty(te,"PluggableAuthClient",{enumerable:!0,get:function(){return Kg.PluggableAuthClient}});Object.defineProperty(te,"ExecutableError",{enumerable:!0,get:function(){return Kg.ExecutableError}});var ES=Gg();Object.defineProperty(te,"PassThroughClient",{enumerable:!0,get:function(){return ES.PassThroughClient}});var AS=new Jg.GoogleAuth;te.auth=AS});var Ry=J((px,ff)=>{"use strict";var KD=/at\s(?:.*\.)?plugin\s.*\n\s*(.*)/,YD=/(\w*(\.\w*)*)\..*/;ff.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,vy(n.stack)}};function vy(t){let e=t.match(KD);return e?e[1].split(/[/\\]/).slice(-1)[0].match(YD)[1]:"anonymous"}ff.exports.extractPluginName=vy});var Fy=J((mx,Oy)=>{"use strict";Oy.exports=function(e){return e[0]==="@"&&(e=e.slice(1).replace("/","-")),e.replace(/-(.)/g,function(r,n){return n.toUpperCase()})}});var xy=J((gx,Na)=>{"use strict";var XD=Ry(),QD=Fy(),ZD=0;function df(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=XD(t)+"-auto-"+ZD++),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=QD(e.name);return!r&&!t[n]&&(t[n]=t),t}Na.exports=df;Na.exports.default=df;Na.exports.fastifyPlugin=df});var Zs,hf=je(()=>{"use strict";Zs=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 eo,hf=je(()=>{"use strict";eo=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 ZD,existsSync as eT,mkdirSync as tT}from"fs";import{join as Py}from"path";import{tmpdir as rT}from"os";var to,pf=je(()=>{"use strict";to=class{type="temp-file";config;baseDir;constructor(e={}){this.config={subdirectory:"claude-code-router",extension:"json",includeTimestamp:!1,prefix:"session",...e};let r=rT();this.baseDir=Py(r,this.config.subdirectory),this.ensureDir()}ensureDir(){try{eT(this.baseDir)||tT(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 Py(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 ZD(i,JSON.stringify(s,null,2),"utf-8"),!0}catch{return!1}}getBaseDir(){return this.baseDir}}});var mf,is,Iy=je(()=>{"use strict";df();hf();pf();mf=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 Zs(e.config);case"webhook":return new eo(e.config);case"temp-file":return new to(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)}},is=new mf});import nT from"fastify";import sT from"@fastify/cors";var Pd=xr(_u(),1);import{readFileSync as P_,existsSync as Fd}from"fs";import{join as xd}from"path";import{config as I_}from"dotenv";var kn=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:xd(process.cwd(),this.options.jsonPath);if(Fd(e))try{let r=P_(e,"utf-8"),n=Pd.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:xd(process.cwd(),this.options.envPath);if(Fd(e))try{let r=I_({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 Id(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 N_}from"undici";function Nd(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 N_(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 Bd="1.0.51";async function j_(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 jd(s,u,n,t.headers,{req:t}),d=await qd(c,l,u,r,h,n,{req:t}),p=await Ld(c,d,u,n,h,{req:t});return Ud(p,e,s)}catch(c){if(c.code==="provider_response_error"){let l=await q_(t,e,r,n,c);if(l)return l}throw c}}async function q_(t,e,r,n,s){let i=t.scenarioType||"default",u=r.configService.get("fallback");if(!u||!u[i])return null;let c=u[i];if(!Array.isArray(c)||c.length===0)return null;t.log.warn(`Request failed for ${t.scenarioType}, trying ${c.length} fallback models`);for(let l of c)try{t.log.info(`Trying fallback model: ${l}`);let h={...t.body},[d,...p]=l.split(",");h.model=p.join(",");let A={...t,provider:d,body:h},R=r.providerService.getProvider(d);if(!R){t.log.warn(`Fallback provider '${d}' not found, skipping`);continue}let{requestBody:S,config:_,bypass:y}=await jd(h,R,n,t.headers,{req:A}),m=await qd(S,_,R,r,y,n,{req:A}),D=await Ld(S,m,R,n,y,{req:A});return t.log.info(`Fallback model ${l} succeeded`),Ud(D,e,h)}catch(h){t.log.warn(`Fallback model ${l} failed: ${h.message}`);continue}return t.log.error(`All fallback models failed for yichu ${i}`),null}async function jd(t,e,r,n,s){let i=t,u={},c=!1;if(c=L_(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 L_(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 qd(t,e,r,n,s,i,u){let c=e.url||new URL(r.baseUrl);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 Nd(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 Ld(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 Ud(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 bu=async t=>{t.get("/",async()=>({message:"LLMs API",version:Bd})),t.get("/health",async()=>({status:"ok",timestamp:new Date().toISOString()}));let e=t.transformerService.getTransformersWithEndpoint();for(let{transformer:r}of e)r.endPoint&&t.post(r.endPoint,async(n,s)=>j_(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||!U_(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 U_(t){try{return new URL(t),!0}catch{return!1}}var Dn=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 Md(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 M_}from"crypto";var jo=new Uint8Array(256),Bo=jo.length;function Cu(){return Bo>jo.length-16&&(M_(jo),Bo=0),jo.slice(Bo,Bo+=16)}import{randomUUID as $_}from"crypto";var wu={randomUUID:$_};function z_(t,e,r){if(wu.randomUUID&&!e&&!t)return wu.randomUUID();t=t||{};let n=t.random??t.rng?.()??Cu();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 Md(n)}var Gt=z_;var $d=t=>t<=0?"none":t<=1024?"low":t<=8192?"medium":"high";var zd=(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"?zd(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:$d(e.thinking.budget_tokens),enabled:e.thinking.type==="enabled"},s.thinking={type:e.thinking.type,budget_tokens:e.thinking.budget_tokens}):e.reasoning&&(s.reasoning=e.reasoning,s.thinking={type:e.reasoning.enabled?"enabled":"disabled",budget_tokens:e.reasoning.max_tokens||1e4}),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,A=new Map,R=new Map,S=0,_=0,y=0,m=!1,D=!1,C=0,E=-1,v=()=>{let U=C;return C++,U},x=U=>{if(!m)try{s.enqueue(U);let Q=new TextDecoder().decode(U);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(E>=0){let Q={type:"content_block_stop",index:E};x(i.encode(`event: content_block_stop
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 eo,pf=je(()=>{"use strict";eo=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 eT,existsSync as tT,mkdirSync as rT}from"fs";import{join as Iy}from"path";import{tmpdir as nT}from"os";var to,mf=je(()=>{"use strict";to=class{type="temp-file";config;baseDir;constructor(e={}){this.config={subdirectory:"claude-code-router",extension:"json",includeTimestamp:!1,prefix:"session",...e};let r=nT();this.baseDir=Iy(r,this.config.subdirectory),this.ensureDir()}ensureDir(){try{tT(this.baseDir)||rT(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 Iy(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 eT(i,JSON.stringify(s,null,2),"utf-8"),!0}catch{return!1}}getBaseDir(){return this.baseDir}}});var gf,is,Ny=je(()=>{"use strict";hf();pf();mf();gf=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 Zs(e.config);case"webhook":return new eo(e.config);case"temp-file":return new to(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)}},is=new gf});import sT from"fastify";import oT from"@fastify/cors";var Id=xr(bu(),1);import{readFileSync as I_,existsSync as xd}from"fs";import{join as Pd}from"path";import{config as N_}from"dotenv";var kn=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:Pd(process.cwd(),this.options.jsonPath);if(xd(e))try{let r=I_(e,"utf-8"),n=Id.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:Pd(process.cwd(),this.options.envPath);if(xd(e))try{let r=N_({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 Nd(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 B_}from"undici";function Bd(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 B_(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 jd="1.0.52";async function q_(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 qd(s,u,n,t.headers,{req:t}),d=await Ld(c,l,u,r,h,n,{req:t}),p=await Ud(c,d,u,n,h,{req:t});return Md(p,e,s)}catch(c){if(c.code==="provider_response_error"){let l=await L_(t,e,r,n,c);if(l)return l}throw c}}async function L_(t,e,r,n,s){let i=t.scenarioType||"default",u=r.configService.get("fallback");if(!u||!u[i])return null;let c=u[i];if(!Array.isArray(c)||c.length===0)return null;t.log.warn(`Request failed for ${t.scenarioType}, trying ${c.length} fallback models`);for(let l of c)try{t.log.info(`Trying fallback model: ${l}`);let h={...t.body},[d,...p]=l.split(",");h.model=p.join(",");let A={...t,provider:d,body:h},R=r.providerService.getProvider(d);if(!R){t.log.warn(`Fallback provider '${d}' not found, skipping`);continue}let{requestBody:S,config:_,bypass:y}=await qd(h,R,n,t.headers,{req:A}),m=await Ld(S,_,R,r,y,n,{req:A}),D=await Ud(S,m,R,n,y,{req:A});return t.log.info(`Fallback model ${l} succeeded`),Md(D,e,h)}catch(h){t.log.warn(`Fallback model ${l} failed: ${h.message}`);continue}return t.log.error(`All fallback models failed for yichu ${i}`),null}async function qd(t,e,r,n,s){let i=t,u={},c=!1;if(c=U_(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 U_(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 Ld(t,e,r,n,s,i,u){let c=e.url||new URL(r.baseUrl);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 Bd(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 Ud(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 Md(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 Cu=async t=>{t.get("/",async()=>({message:"LLMs API",version:jd})),t.get("/health",async()=>({status:"ok",timestamp:new Date().toISOString()}));let e=t.transformerService.getTransformersWithEndpoint();for(let{transformer:r}of e)r.endPoint&&t.post(r.endPoint,async(n,s)=>q_(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||!M_(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 M_(t){try{return new URL(t),!0}catch{return!1}}var Dn=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 $d(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 $_}from"crypto";var jo=new Uint8Array(256),Bo=jo.length;function wu(){return Bo>jo.length-16&&($_(jo),Bo=0),jo.slice(Bo,Bo+=16)}import{randomUUID as z_}from"crypto";var Eu={randomUUID:z_};function H_(t,e,r){if(Eu.randomUUID&&!e&&!t)return Eu.randomUUID();t=t||{};let n=t.random??t.rng?.()??wu();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 $d(n)}var Gt=H_;var zd=t=>t<=0?"none":t<=1024?"low":t<=8192?"medium":"high";var Hd=(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"?Hd(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:zd(e.thinking.budget_tokens),enabled:e.thinking.type==="enabled"},s.thinking={type:e.thinking.type,budget_tokens:e.thinking.budget_tokens}):e.reasoning&&(s.reasoning=e.reasoning,s.thinking={type:e.reasoning.enabled?"enabled":"disabled",budget_tokens:e.reasoning.max_tokens||1e4}),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,A=new Map,R=new Map,S=0,_=0,y=0,m=!1,D=!1,C=0,E=-1,v=()=>{let U=C;return C++,U},x=U=>{if(!m)try{s.enqueue(U);let Q=new TextDecoder().decode(U);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(E>=0){let Q={type:"content_block_stop",index:E};x(i.encode(`event: content_block_stop
74
74
  data: ${JSON.stringify(Q)}
75
75
 
76
76
  `)),E=-1}c?(x(i.encode(`event: message_delta
@@ -134,7 +134,7 @@ data: ${JSON.stringify(_e)}
134
134
  `))}catch(le){console.error(le)}}}}}if(pe?.finish_reason&&!m&&!p){if(_===0&&y===0&&console.error("Warning: No content in the stream response!"),E>=0){let G={type:"content_block_stop",index:E};x(i.encode(`event: content_block_stop
135
135
  data: ${JSON.stringify(G)}
136
136
 
137
- `)),E=-1}m||(c={type:"message_delta",delta:{stop_reason:{stop:"end_turn",length:"max_tokens",tool_calls:"tool_use",content_filter:"stop_sequence"}[pe.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(U){if(!m)try{s.error(U)}catch(Q){console.error(Q)}}finally{if(V)try{V.releaseLock()}catch(U){console.error(U)}}},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_${Gt()}`;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}):n.message?.reasoning_content&&s.push({type:"thinking",thinking:n.message.reasoning_content,signature:void 0});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 Tn={TYPE_UNSPECIFIED:"TYPE_UNSPECIFIED",STRING:"STRING",NUMBER:"NUMBER",INTEGER:"INTEGER",BOOLEAN:"BOOLEAN",ARRAY:"ARRAY",OBJECT:"OBJECT",NULL:"NULL"};function H_(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(Tn).includes(n)?n:Tn.TYPE_UNSPECIFIED}else{e.anyOf=[];for(let n of r){let s=n.toUpperCase();e.anyOf.push({type:Object.values(Tn).includes(s)?s:Tn.TYPE_UNSPECIFIED})}}}function ys(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)&&H_(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(Tn).includes(l)?l:Tn.TYPE_UNSPECIFIED}else if(r.includes(u))e[u]=ys(c);else if(n.includes(u)){let l=[];for(let h of c){if(h.type=="null"){e.nullable=!0;continue}l.push(ys(h))}e[u]=l}else if(s.includes(u)){let l={};for(let[h,d]of Object.entries(c))l[h]=ys(d);e[u]=l}else{if(u==="additionalProperties")continue;e[u]=c}return e}function W_(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=ys(e.parameters)),e.response&&(Object.keys(e.response).includes("$schema")?e.responseJsonSchema||(e.responseJsonSchema=e.response,delete e.response):e.response=ys(e.response));return t}function Lo(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(W_({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,A)=>({functionCall:{id:p.id||`tool_${Math.random().toString(36).substring(2,15)}`,name:p.function.name,args:JSON.parse(p.function.arguments||"{}")},thoughtSignature:A===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(A=>{let R=i.find(S=>S.tool_call_id===A.id);return{functionResponse:{name:A?.function?.name,response:{result:R?.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 Uo(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 Mo(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(`
137
+ `)),E=-1}m||(c={type:"message_delta",delta:{stop_reason:{stop:"end_turn",length:"max_tokens",tool_calls:"tool_use",content_filter:"stop_sequence"}[pe.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(U){if(!m)try{s.error(U)}catch(Q){console.error(Q)}}finally{if(V)try{V.releaseLock()}catch(U){console.error(U)}}},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_${Gt()}`;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}):n.message?.reasoning_content&&s.push({type:"thinking",thinking:n.message.reasoning_content,signature:void 0});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 Tn={TYPE_UNSPECIFIED:"TYPE_UNSPECIFIED",STRING:"STRING",NUMBER:"NUMBER",INTEGER:"INTEGER",BOOLEAN:"BOOLEAN",ARRAY:"ARRAY",OBJECT:"OBJECT",NULL:"NULL"};function W_(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(Tn).includes(n)?n:Tn.TYPE_UNSPECIFIED}else{e.anyOf=[];for(let n of r){let s=n.toUpperCase();e.anyOf.push({type:Object.values(Tn).includes(s)?s:Tn.TYPE_UNSPECIFIED})}}}function ys(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)&&W_(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(Tn).includes(l)?l:Tn.TYPE_UNSPECIFIED}else if(r.includes(u))e[u]=ys(c);else if(n.includes(u)){let l=[];for(let h of c){if(h.type=="null"){e.nullable=!0;continue}l.push(ys(h))}e[u]=l}else if(s.includes(u)){let l={};for(let[h,d]of Object.entries(c))l[h]=ys(d);e[u]=l}else{if(u==="additionalProperties")continue;e[u]=c}return e}function G_(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=ys(e.parameters)),e.response&&(Object.keys(e.response).includes("$schema")?e.responseJsonSchema||(e.responseJsonSchema=e.response,delete e.response):e.response=ys(e.response));return t}function Lo(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(G_({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,A)=>({functionCall:{id:p.id||`tool_${Math.random().toString(36).substring(2,15)}`,name:p.function.name,args:JSON.parse(p.function.arguments||"{}")},thoughtSignature:A===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(A=>{let R=i.find(S=>S.tool_call_id===A.id);return{functionResponse:{name:A?.function?.name,response:{result:R?.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 Uo(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 Mo(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
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(A){let R=async(y,m)=>{if(y.startsWith("data: ")){let D=y.slice(6).trim();if(D){r?.debug({chunkStr:D},`${e} chunk:`);try{let C=JSON.parse(D);if(!C.candidates||!C.candidates[0]){r?.debug({chunkStr:D},"Invalid chunk structure");return}let E=C.candidates[0],v=E.content?.parts||[];v.filter(U=>U.text&&U.thought===!0).forEach(U=>{c||(c=!0);let Q={choices:[{delta:{role:"assistant",content:null,thinking:{content:U.text}},finish_reason:null,index:h,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:C.responseId||"",model:C.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};m.enqueue(s.encode(`data: ${JSON.stringify(Q)}
139
139
 
140
140
  `))});let x=v.find(U=>U.thoughtSignature)?.thoughtSignature;if(x&&!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:C.responseId||"",model:C.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};m.enqueue(s.encode(`data: ${JSON.stringify(Q)}
@@ -153,10 +153,10 @@ data: ${JSON.stringify(G)}
153
153
  `)),!u&&V&&(u=!0)}$.length>0&&($.forEach(U=>{h++,d++;let Q={choices:[{delta:{role:"assistant",tool_calls:[{...U,index:d}]},finish_reason:E.finishReason?.toLowerCase()||null,index:h,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:C.responseId||"",model:C.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:{completion_tokens:C.usageMetadata?.candidatesTokenCount||0,prompt_tokens:C.usageMetadata?.promptTokenCount||0,prompt_tokens_details:{cached_tokens:C.usageMetadata?.cachedContentTokenCount||0},total_tokens:C.usageMetadata?.totalTokenCount||0,output_tokens_details:{reasoning_tokens:C.usageMetadata?.thoughtsTokenCount||0}}};E?.groundingMetadata?.groundingChunks?.length&&(Q.choices[0].delta.annotations=E.groundingMetadata.groundingChunks.map((ne,ae)=>{let fe=E?.groundingMetadata?.groundingSupports?.filter(ye=>ye.groundingChunkIndices?.includes(ae));return{type:"url_citation",url_citation:{url:ne?.web?.uri||"",title:ne?.web?.title||"",content:fe?.[0]?.segment?.text||"",start_index:fe?.[0]?.segment?.startIndex||0,end_index:fe?.[0]?.segment?.endIndex||0}}})),m.enqueue(s.encode(`data: ${JSON.stringify(Q)}
154
154
 
155
155
  `))}),!u&&V&&(u=!0))}catch(C){r?.error(`Error parsing ${e} stream chunk`,D,C.message)}}}},S=t.body.getReader(),_="";try{for(;;){let{done:y,value:m}=await S.read();if(y){_&&await R(_,A);break}_+=n.decode(m,{stream:!0});let D=_.split(`
156
- `);_=D.pop()||"";for(let C of D)await R(C,A)}}catch(y){A.error(y)}finally{A.close()}}});return new Response(p,{status:t.status,statusText:t.statusText,headers:t.headers})}}var $o=class{name="gemini";endPoint="/v1beta/models/:modelAndAction";async transformRequestIn(e,r){return{body:Lo(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=Uo;async transformResponseOut(e){return Mo(e,this.name,this.logger)}};async function AS(){try{let{GoogleAuth:t}=await Promise.resolve().then(()=>xr(Ul(),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:
156
+ `);_=D.pop()||"";for(let C of D)await R(C,A)}}catch(y){A.error(y)}finally{A.close()}}});return new Response(p,{status:t.status,statusText:t.statusText,headers:t.headers})}}var $o=class{name="gemini";endPoint="/v1beta/models/:modelAndAction";async transformRequestIn(e,r){return{body:Lo(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=Uo;async transformResponseOut(e){return Mo(e,this.name,this.logger)}};async function SS(){try{let{GoogleAuth:t}=await Promise.resolve().then(()=>xr(Ml(),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 aa=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 AS();return{body:Lo(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 Uo(e)}async transformResponseOut(e){return Mo(e,this.name)}};var ua=class{name="deepseek";async transformRequestIn(e){return e.max_tokens&&e.max_tokens>8192&&(e.max_tokens=8192),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=(A,R,S)=>{let _=A.split(`
159
+ 3. Use Google Cloud environment with default service account`)}}var aa=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 SS();return{body:Lo(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 Uo(e)}async transformResponseOut(e){return Mo(e,this.name)}};var ua=class{name="deepseek";async transformRequestIn(e){return e.max_tokens&&e.max_tokens>8192&&(e.max_tokens=8192),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=(A,R,S)=>{let _=A.split(`
160
160
  `);for(let y of _)y.trim()&&R.enqueue(S.encode(y+`
161
161
  `))},p=(A,R)=>{let{controller:S,encoder:_}=R;if(A.startsWith("data: ")&&A.trim()!=="data: [DONE]")try{let y=JSON.parse(A.slice(6));if(y.choices?.[0]?.delta?.reasoning_content){R.appendReasoningContent(y.choices[0].delta.reasoning_content);let m={...y,choices:[{...y.choices[0],delta:{...y.choices[0].delta,thinking:{content:y.choices[0].delta.reasoning_content}}}]};delete m.choices[0].delta.reasoning_content;let D=`data: ${JSON.stringify(m)}
162
162
 
@@ -208,16 +208,16 @@ Examples:
208
208
  `);c=m.pop()||"";for(let D of m)if(D.trim())try{A(D,{controller:h,encoder:n,hasTextContent:()=>s,setHasTextContent:C=>s=C,reasoningContent:()=>i,appendReasoningContent:C=>i+=C,isReasoningComplete:()=>u,setReasoningComplete:C=>u=C})}catch(C){console.error("Error processing line:",D,C),h.enqueue(n.encode(D+`
209
209
  `))}continue}let y=c.split(`
210
210
  `);c=y.pop()||"";for(let m of y)if(m.trim())try{A(m,{controller:h,encoder:n,hasTextContent:()=>s,setHasTextContent:D=>s=D,reasoningContent:()=>i,appendReasoningContent:D=>i+=D,isReasoningComplete:()=>u,setReasoningComplete:D=>u=D})}catch(D){console.error("Error processing line:",m,D),h.enqueue(n.encode(m+`
211
- `))}}}catch(R){console.error("Stream error:",R),h.error(R)}finally{try{d.releaseLock()}catch(R){console.error("Error releasing reader lock:",R)}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 ha=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 ry=xr(_u());var wr=class extends Error{constructor(e,r){super(`${e} at position ${r}`),this.position=r}};function Kg(t){return/^[0-9A-Fa-f]$/.test(t)}function Hr(t){return t>="0"&&t<="9"}function Yg(t){return t>=" "}function Gs(t){return`,:[]/{}()
212
- +`.includes(t)}function Ml(t){return t>="a"&&t<="z"||t>="A"&&t<="Z"||t==="_"||t==="$"}function $l(t){return t>="a"&&t<="z"||t>="A"&&t<="Z"||t==="_"||t==="$"||t>="0"&&t<="9"}var zl=/^(http|https|ftp|mailto|file|data|irc):\/\/$/,Hl=/^[A-Za-z0-9-._~:/?#@!$&'()*+;=]$/;function Wl(t){return`,[]/{}
213
- +`.includes(t)}function Gl(t){return Js(t)||SS.test(t)}var SS=/^[[{\w-]$/;function Xg(t){return t===`
214
- `||t==="\r"||t===" "||t==="\b"||t==="\f"}function zr(t,e){let r=t.charCodeAt(e);return r===32||r===10||r===9||r===13}function Qg(t,e){let r=t.charCodeAt(e);return r===32||r===9||r===13}function Zg(t,e){let r=t.charCodeAt(e);return r===160||r>=8192&&r<=8202||r===8239||r===8287||r===12288}function Js(t){return Jl(t)||pa(t)}function Jl(t){return t==='"'||t==="\u201C"||t==="\u201D"}function Vl(t){return t==='"'}function pa(t){return t==="'"||t==="\u2018"||t==="\u2019"||t==="`"||t==="\xB4"}function Kl(t){return t==="'"}function rs(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(!zr(t,r-1))return t+e;for(;zr(t,r-1);)r--;return t.substring(0,r)+e+t.substring(r)}function ey(t,e,r){return t.substring(0,e)+t.substring(e+r)}function ty(t){return/[,\n][ \t\r]*$/.test(t)}var kS={"\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r"," ":"\\t"},DS={'"':'"',"\\":"\\","/":"/",b:"\b",f:"\f",n:`
215
- `,r:"\r",t:" "};function Yl(t){let e=0,r="";h(["```","[```","{```"]),i()||ye(),h(["```","```]","```}"]);let s=p(",");for(s&&u(),Gl(t[e])&&ty(r)?(s||(r=Rt(r,",")),m()):s&&(r=rs(r,","));t[e]==="}"||t[e]==="]";)e++,u();if(e>=t.length)return r;fe();function i(){u();let G=_()||y()||D()||E()||v()||$(!1)||V();return u(),G}function u(){let G=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,K=e,ue=c(G);do ue=l(),ue&&(ue=c(G));while(ue);return e>K}function c(G){let K=G?zr:Qg,ue="";for(;;)if(K(t,e))ue+=t[e],e++;else if(Zg(t,e))ue+=" ",e++;else break;return ue.length>0?(r+=ue,!0):!1}function l(){if(t[e]==="/"&&t[e+1]==="*"){for(;e<t.length&&!TS(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(Ml(t[e]))for(;e<t.length&&$l(t[e]);)e++;return u(),!0}return!1}function d(G){c(!0);for(let K of G){let ue=e+K.length;if(t.slice(e,ue)===K)return e=ue,!0}return!1}function p(G){return t[e]===G?(r+=t[e],e++,!0):!1}function A(G){return t[e]===G?(e++,!0):!1}function R(){return A("\\")}function S(){return u(),t[e]==="."&&t[e+1]==="."&&t[e+2]==="."?(e+=3,u(),A(","),!0):!1}function _(){if(t[e]==="{"){r+="{",e++,u(),A(",")&&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(),!(D()||$(!0))){t[e]==="}"||t[e]==="{"||t[e]==="]"||t[e]==="["||t[e]===void 0?r=rs(r,","):Ae();break}u();let Me=p(":"),Te=e>=t.length;Me||(Gl(t[e])||Te?r=Rt(r,":"):oe()),i()||(Me||Te?r+="null":oe())}return t[e]==="}"?(r+="}",e++):r=Rt(r,"}"),!0}return!1}function y(){if(t[e]==="["){r+="[",e++,u(),A(",")&&u();let G=!0;for(;e<t.length&&t[e]!=="]";)if(G?G=!1:p(",")||(r=Rt(r,",")),S(),!i()){r=rs(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=rs(r,",")),r=`[
211
+ `))}}}catch(R){console.error("Stream error:",R),h.error(R)}finally{try{d.releaseLock()}catch(R){console.error("Error releasing reader lock:",R)}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 ha=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 ny=xr(bu());var wr=class extends Error{constructor(e,r){super(`${e} at position ${r}`),this.position=r}};function Yg(t){return/^[0-9A-Fa-f]$/.test(t)}function Hr(t){return t>="0"&&t<="9"}function Xg(t){return t>=" "}function Gs(t){return`,:[]/{}()
212
+ +`.includes(t)}function $l(t){return t>="a"&&t<="z"||t>="A"&&t<="Z"||t==="_"||t==="$"}function zl(t){return t>="a"&&t<="z"||t>="A"&&t<="Z"||t==="_"||t==="$"||t>="0"&&t<="9"}var Hl=/^(http|https|ftp|mailto|file|data|irc):\/\/$/,Wl=/^[A-Za-z0-9-._~:/?#@!$&'()*+;=]$/;function Gl(t){return`,[]/{}
213
+ +`.includes(t)}function Jl(t){return Js(t)||kS.test(t)}var kS=/^[[{\w-]$/;function Qg(t){return t===`
214
+ `||t==="\r"||t===" "||t==="\b"||t==="\f"}function zr(t,e){let r=t.charCodeAt(e);return r===32||r===10||r===9||r===13}function Zg(t,e){let r=t.charCodeAt(e);return r===32||r===9||r===13}function ey(t,e){let r=t.charCodeAt(e);return r===160||r>=8192&&r<=8202||r===8239||r===8287||r===12288}function Js(t){return Vl(t)||pa(t)}function Vl(t){return t==='"'||t==="\u201C"||t==="\u201D"}function Kl(t){return t==='"'}function pa(t){return t==="'"||t==="\u2018"||t==="\u2019"||t==="`"||t==="\xB4"}function Yl(t){return t==="'"}function rs(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(!zr(t,r-1))return t+e;for(;zr(t,r-1);)r--;return t.substring(0,r)+e+t.substring(r)}function ty(t,e,r){return t.substring(0,e)+t.substring(e+r)}function ry(t){return/[,\n][ \t\r]*$/.test(t)}var DS={"\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r"," ":"\\t"},TS={'"':'"',"\\":"\\","/":"/",b:"\b",f:"\f",n:`
215
+ `,r:"\r",t:" "};function Xl(t){let e=0,r="";h(["```","[```","{```"]),i()||ye(),h(["```","```]","```}"]);let s=p(",");for(s&&u(),Jl(t[e])&&ry(r)?(s||(r=Rt(r,",")),m()):s&&(r=rs(r,","));t[e]==="}"||t[e]==="]";)e++,u();if(e>=t.length)return r;fe();function i(){u();let G=_()||y()||D()||E()||v()||$(!1)||V();return u(),G}function u(){let G=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,K=e,ue=c(G);do ue=l(),ue&&(ue=c(G));while(ue);return e>K}function c(G){let K=G?zr:Zg,ue="";for(;;)if(K(t,e))ue+=t[e],e++;else if(ey(t,e))ue+=" ",e++;else break;return ue.length>0?(r+=ue,!0):!1}function l(){if(t[e]==="/"&&t[e+1]==="*"){for(;e<t.length&&!vS(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($l(t[e]))for(;e<t.length&&zl(t[e]);)e++;return u(),!0}return!1}function d(G){c(!0);for(let K of G){let ue=e+K.length;if(t.slice(e,ue)===K)return e=ue,!0}return!1}function p(G){return t[e]===G?(r+=t[e],e++,!0):!1}function A(G){return t[e]===G?(e++,!0):!1}function R(){return A("\\")}function S(){return u(),t[e]==="."&&t[e+1]==="."&&t[e+2]==="."?(e+=3,u(),A(","),!0):!1}function _(){if(t[e]==="{"){r+="{",e++,u(),A(",")&&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(),!(D()||$(!0))){t[e]==="}"||t[e]==="{"||t[e]==="]"||t[e]==="["||t[e]===void 0?r=rs(r,","):Ae();break}u();let Me=p(":"),Te=e>=t.length;Me||(Jl(t[e])||Te?r=Rt(r,":"):oe()),i()||(Me||Te?r+="null":oe())}return t[e]==="}"?(r+="}",e++):r=Rt(r,"}"),!0}return!1}function y(){if(t[e]==="["){r+="[",e++,u(),A(",")&&u();let G=!0;for(;e<t.length&&t[e]!=="]";)if(G?G=!1:p(",")||(r=Rt(r,",")),S(),!i()){r=rs(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=rs(r,",")),r=`[
217
217
  ${r}
218
- ]`}function D(){let G=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1,K=arguments.length>1&&arguments[1]!==void 0?arguments[1]:-1,ue=t[e]==="\\";if(ue&&(e++,ue=!0),Js(t[e])){let Me=Vl(t[e])?Vl:Kl(t[e])?Kl:pa(t[e])?pa:Jl,Te=e,W=r.length,le='"';for(e++;;){if(e>=t.length){let _e=U(e-1);return!G&&Gs(t.charAt(_e))?(e=Te,r=r.substring(0,W),D(!0)):(le=Rt(le,'"'),r+=le,!0)}if(e===K)return le=Rt(le,'"'),r+=le,!0;if(Me(t[e])){let _e=e,Ft=le.length;if(le+='"',e++,r+=le,u(!1),G||e>=t.length||Gs(t[e])||Js(t[e])||Hr(t[e]))return C(),!0;let Re=U(_e-1),Be=t.charAt(Re);if(Be===",")return e=Te,r=r.substring(0,W),D(!1,Re);if(Gs(Be))return e=Te,r=r.substring(0,W),D(!0);r=r.substring(0,W),e=_e+1,le=`${le.substring(0,Ft)}\\${le.substring(Ft)}`}else if(G&&Wl(t[e])){if(t[e-1]===":"&&zl.test(t.substring(Te+1,e+2)))for(;e<t.length&&Hl.test(t[e]);)le+=t[e],e++;return le=Rt(le,'"'),r+=le,C(),!0}else if(t[e]==="\\"){let _e=t.charAt(e+1);if(DS[_e]!==void 0)le+=t.slice(e,e+2),e+=2;else if(_e==="u"){let Re=2;for(;Re<6&&Kg(t[e+Re]);)Re++;Re===6?(le+=t.slice(e,e+6),e+=6):e+Re>=t.length?e=t.length:pe()}else le+=_e,e+=2}else{let _e=t.charAt(e);_e==='"'&&t[e-1]!=="\\"?(le+=`\\${_e}`,e++):Xg(_e)?(le+=kS[_e],e++):(Yg(_e)||ae(_e),le+=_e,e++)}ue&&R()}}return!1}function C(){let G=!1;for(u();t[e]==="+";){G=!0,e++,u(),r=rs(r,'"',!0);let K=r.length;D()?r=ey(r,K,1):r=Rt(r,'"')}return G}function E(){let G=e;if(t[e]==="-"){if(e++,Q())return ne(G),!0;if(!Hr(t[e]))return e=G,!1}for(;Hr(t[e]);)e++;if(t[e]==="."){if(e++,Q())return ne(G),!0;if(!Hr(t[e]))return e=G,!1;for(;Hr(t[e]);)e++}if(t[e]==="e"||t[e]==="E"){if(e++,(t[e]==="-"||t[e]==="+")&&e++,Q())return ne(G),!0;if(!Hr(t[e]))return e=G,!1;for(;Hr(t[e]);)e++}if(!Q())return e=G,!1;if(e>G){let K=t.slice(G,e),ue=/^0\d/.test(K);return r+=ue?`"${K}"`:K,!0}return!1}function v(){return x("true","true")||x("false","false")||x("null","null")||x("True","true")||x("False","false")||x("None","null")}function x(G,K){return t.slice(e,e+G.length)===G?(r+=K,e+=G.length,!0):!1}function $(G){let K=e;if(Ml(t[e])){for(;e<t.length&&$l(t[e]);)e++;let ue=e;for(;zr(t,ue);)ue++;if(t[ue]==="(")return e=ue+1,i(),t[e]===")"&&(e++,t[e]===";"&&e++),!0}for(;e<t.length&&!Wl(t[e])&&!Js(t[e])&&(!G||t[e]!==":");)e++;if(t[e-1]===":"&&zl.test(t.substring(K,e+2)))for(;e<t.length&&Hl.test(t[e]);)e++;if(e>K){for(;zr(t,e-1)&&e>0;)e--;let ue=t.slice(K,e);return r+=ue==="undefined"?"null":JSON.stringify(ue),t[e]==='"'&&e++,!0}}function V(){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 U(G){let K=G;for(;K>0&&zr(t,K);)K--;return K}function Q(){return e>=t.length||Gs(t[e])||zr(t,e)}function ne(G){r+=`${t.slice(G,e)}0`}function ae(G){throw new wr(`Invalid character ${JSON.stringify(G)}`,e)}function fe(){throw new wr(`Unexpected character ${JSON.stringify(t[e])}`,e)}function ye(){throw new wr("Unexpected end of json string",t.length)}function Ae(){throw new wr("Object key expected",e)}function oe(){throw new wr("Colon expected",e)}function pe(){let G=t.slice(e,e+6);throw new wr(`Invalid unicode character "${G}"`,e)}}function TS(t,e){return t[e]==="*"&&t[e+1]==="/"}function Xl(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=ry.default.parse(t);return e?.debug("Tool arguments JSON5 parsing successful"),JSON.stringify(n)}catch(n){try{let s=Yl(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 ma=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=Xl(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 A=e.body.getReader(),R=(y,m,D)=>{let C=y.split(`
218
+ ]`}function D(){let G=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1,K=arguments.length>1&&arguments[1]!==void 0?arguments[1]:-1,ue=t[e]==="\\";if(ue&&(e++,ue=!0),Js(t[e])){let Me=Kl(t[e])?Kl:Yl(t[e])?Yl:pa(t[e])?pa:Vl,Te=e,W=r.length,le='"';for(e++;;){if(e>=t.length){let _e=U(e-1);return!G&&Gs(t.charAt(_e))?(e=Te,r=r.substring(0,W),D(!0)):(le=Rt(le,'"'),r+=le,!0)}if(e===K)return le=Rt(le,'"'),r+=le,!0;if(Me(t[e])){let _e=e,Ft=le.length;if(le+='"',e++,r+=le,u(!1),G||e>=t.length||Gs(t[e])||Js(t[e])||Hr(t[e]))return C(),!0;let Re=U(_e-1),Be=t.charAt(Re);if(Be===",")return e=Te,r=r.substring(0,W),D(!1,Re);if(Gs(Be))return e=Te,r=r.substring(0,W),D(!0);r=r.substring(0,W),e=_e+1,le=`${le.substring(0,Ft)}\\${le.substring(Ft)}`}else if(G&&Gl(t[e])){if(t[e-1]===":"&&Hl.test(t.substring(Te+1,e+2)))for(;e<t.length&&Wl.test(t[e]);)le+=t[e],e++;return le=Rt(le,'"'),r+=le,C(),!0}else if(t[e]==="\\"){let _e=t.charAt(e+1);if(TS[_e]!==void 0)le+=t.slice(e,e+2),e+=2;else if(_e==="u"){let Re=2;for(;Re<6&&Yg(t[e+Re]);)Re++;Re===6?(le+=t.slice(e,e+6),e+=6):e+Re>=t.length?e=t.length:pe()}else le+=_e,e+=2}else{let _e=t.charAt(e);_e==='"'&&t[e-1]!=="\\"?(le+=`\\${_e}`,e++):Qg(_e)?(le+=DS[_e],e++):(Xg(_e)||ae(_e),le+=_e,e++)}ue&&R()}}return!1}function C(){let G=!1;for(u();t[e]==="+";){G=!0,e++,u(),r=rs(r,'"',!0);let K=r.length;D()?r=ty(r,K,1):r=Rt(r,'"')}return G}function E(){let G=e;if(t[e]==="-"){if(e++,Q())return ne(G),!0;if(!Hr(t[e]))return e=G,!1}for(;Hr(t[e]);)e++;if(t[e]==="."){if(e++,Q())return ne(G),!0;if(!Hr(t[e]))return e=G,!1;for(;Hr(t[e]);)e++}if(t[e]==="e"||t[e]==="E"){if(e++,(t[e]==="-"||t[e]==="+")&&e++,Q())return ne(G),!0;if(!Hr(t[e]))return e=G,!1;for(;Hr(t[e]);)e++}if(!Q())return e=G,!1;if(e>G){let K=t.slice(G,e),ue=/^0\d/.test(K);return r+=ue?`"${K}"`:K,!0}return!1}function v(){return x("true","true")||x("false","false")||x("null","null")||x("True","true")||x("False","false")||x("None","null")}function x(G,K){return t.slice(e,e+G.length)===G?(r+=K,e+=G.length,!0):!1}function $(G){let K=e;if($l(t[e])){for(;e<t.length&&zl(t[e]);)e++;let ue=e;for(;zr(t,ue);)ue++;if(t[ue]==="(")return e=ue+1,i(),t[e]===")"&&(e++,t[e]===";"&&e++),!0}for(;e<t.length&&!Gl(t[e])&&!Js(t[e])&&(!G||t[e]!==":");)e++;if(t[e-1]===":"&&Hl.test(t.substring(K,e+2)))for(;e<t.length&&Wl.test(t[e]);)e++;if(e>K){for(;zr(t,e-1)&&e>0;)e--;let ue=t.slice(K,e);return r+=ue==="undefined"?"null":JSON.stringify(ue),t[e]==='"'&&e++,!0}}function V(){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 U(G){let K=G;for(;K>0&&zr(t,K);)K--;return K}function Q(){return e>=t.length||Gs(t[e])||zr(t,e)}function ne(G){r+=`${t.slice(G,e)}0`}function ae(G){throw new wr(`Invalid character ${JSON.stringify(G)}`,e)}function fe(){throw new wr(`Unexpected character ${JSON.stringify(t[e])}`,e)}function ye(){throw new wr("Unexpected end of json string",t.length)}function Ae(){throw new wr("Object key expected",e)}function oe(){throw new wr("Colon expected",e)}function pe(){let G=t.slice(e,e+6);throw new wr(`Invalid unicode character "${G}"`,e)}}function vS(t,e){return t[e]==="*"&&t[e+1]==="/"}function Ql(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=ny.default.parse(t);return e?.debug("Tool arguments JSON5 parsing successful"),JSON.stringify(n)}catch(n){try{let s=Xl(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 ma=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=Ql(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 A=e.body.getReader(),R=(y,m,D)=>{let C=y.split(`
219
219
  `);for(let E of C)E.trim()&&m.enqueue(D.encode(E+`
220
- `))},S=(y,m,D)=>{let C="";try{C=Xl(s.arguments||"",this.logger)}catch($){console.error(`${$.message} ${$.stack} \u5DE5\u5177\u8C03\u7528\u53C2\u6570\u89E3\u6790\u5931\u8D25: ${JSON.stringify(s)}`),C=s.arguments||""}let E={role:"assistant",tool_calls:[{function:{name:s.name,arguments:C},id:s.id,index:s.index,type:"function"}]},v={...y,choices:[{...y.choices[0],delta:E}]};v.choices[0].delta.content!==void 0&&delete v.choices[0].delta.content;let x=`data: ${JSON.stringify(v)}
220
+ `))},S=(y,m,D)=>{let C="";try{C=Ql(s.arguments||"",this.logger)}catch($){console.error(`${$.message} ${$.stack} \u5DE5\u5177\u8C03\u7528\u53C2\u6570\u89E3\u6790\u5931\u8D25: ${JSON.stringify(s)}`),C=s.arguments||""}let E={role:"assistant",tool_calls:[{function:{name:s.name,arguments:C},id:s.id,index:s.index,type:"function"}]},v={...y,choices:[{...y.choices[0],delta:E}]};v.choices[0].delta.content!==void 0&&delete v.choices[0].delta.content;let x=`data: ${JSON.stringify(v)}
221
221
 
222
222
  `;m.enqueue(D.encode(x))},_=(y,m)=>{let{controller:D,encoder:C}=m;if(y.startsWith("data: ")&&y.trim()!=="data: [DONE]"){let E=y.slice(6);try{let v=JSON.parse(E);if(v.choices?.[0]?.delta?.tool_calls?.length){let $=v.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 V=`data: ${JSON.stringify(v)}
223
223
 
@@ -241,7 +241,7 @@ ${r}
241
241
  `))}else S.enqueue(_.encode(A+`
242
242
  `))};try{for(;;){let{done:A,value:R}=await h.read();if(A){u.trim()&&d(u,l,n);break}let S=r.decode(R,{stream:!0});u+=S;let _=u.split(`
243
243
  `);u=_.pop()||"";for(let y of _)if(y.trim())try{p(y,{controller:l,encoder:n,reasoningContent:()=>s,appendReasoningContent:m=>s+=m,isReasoningComplete:()=>i,setReasoningComplete:m=>i=m})}catch(m){console.error("Error processing line:",y,m),l.enqueue(n.encode(y+`
244
- `))}}}catch(A){console.error("Stream error:",A),l.error(A)}finally{try{h.releaseLock()}catch(A){console.error("Error releasing reader lock:",A)}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;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 _a=class{static TransformerName="maxcompletiontokens";async transformRequestIn(e){return e.max_tokens&&(e.max_completion_tokens=e.max_tokens,delete e.max_tokens),e}};function ny(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 sy(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 oy(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)}
244
+ `))}}}catch(A){console.error("Stream error:",A),l.error(A)}finally{try{h.releaseLock()}catch(A){console.error("Error releasing reader lock:",A)}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;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 _a=class{static TransformerName="maxcompletiontokens";async transformRequestIn(e){return e.max_tokens&&(e.max_completion_tokens=e.max_tokens,delete e.max_tokens),e}};function sy(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 oy(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 iy(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
 
@@ -254,10 +254,10 @@ ${r}
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
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 A=h.split(`
257
- `);h=A.pop()||"";for(let R of A)i(R,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 vS(){try{let{GoogleAuth:t}=await Promise.resolve().then(()=>xr(Ul(),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:
257
+ `);h=A.pop()||"";for(let R of A)i(R,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 RS(){try{let{GoogleAuth:t}=await Promise.resolve().then(()=>xr(Ml(),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 ba=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 vS();return{body:ny(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 sy(e)}async transformResponseOut(e){return oy(e,this.name,this.logger)}};var Ca=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 wa=class{name="streamoptions";async transformRequestIn(e){return e.stream&&(e.stream_options={include_usage:!0}),e}};var Ea=class{name="OpenAI";endPoint="/v1/chat/completions";async transformRequestIn(e){return e.thinking?.type==="enabled"?e.enable_thinking=!0:e.enable_thinking===void 0&&!e.thinking&&(e.enable_thinking=!1),e}};var Aa=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 Sa=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(),A=(S,_,y)=>{let m=S.split(`
260
+ 3. Use Google Cloud environment with default service account`)}}var ba=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 RS();return{body:sy(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 oy(e)}async transformResponseOut(e){return iy(e,this.name,this.logger)}};var Ca=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 wa=class{name="streamoptions";async transformRequestIn(e){return e.stream&&(e.stream_options={include_usage:!0}),e}};var Ea=class{name="OpenAI";endPoint="/v1/chat/completions";async transformRequestIn(e){return e.thinking?.type==="enabled"?e.enable_thinking=!0:e.enable_thinking===void 0&&!e.thinking&&(e.enable_thinking=!1),e}};var Aa=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 Sa=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(),A=(S,_,y)=>{let m=S.split(`
261
261
  `);for(let D of m)D.trim()&&_.enqueue(y.encode(D+`
262
262
  `))},R=(S,_)=>{let{controller:y,encoder:m}=_;if(S.startsWith("data: ")&&S.trim()!=="data: [DONE]"){let D=S.slice(6);try{let C=JSON.parse(D);if(C.usage&&(this.logger?.debug({usage:C.usage,hasToolCall:c},"usage"),C.choices[0].finish_reason=c?"tool_calls":"stop"),C.choices?.[0]?.finish_reason==="error"&&y.enqueue(m.encode(`data: ${JSON.stringify({error:C.choices?.[0].error})}
263
263
 
@@ -299,14 +299,14 @@ ${r}
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 A=this.buildImageContent({url:p.image_url,mime_type:p.mime_type});A&&d.push(A)}else if(p.type==="output_image_base64"){let A=this.buildImageContent({b64_json:p.image_base64,mime_type:p.mime_type});A&&d.push(A)}}),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 Ql=`Always think before answering. Even if the problem seems simple, always write down your reasoning process explicitly.
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 A=this.buildImageContent({url:p.image_url,mime_type:p.mime_type});A&&d.push(A)}else if(p.type==="output_image_base64"){let A=this.buildImageContent({b64_json:p.image_base64,mime_type:p.mime_type});A&&d.push(A)}}),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 Zl=`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.`,RS=10,Da=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<RS)&&(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:Ql}):n.content=[{type:"text",text:Ql},{type:"text",text:n.content||""}]),n.role==="tool"&&e.messages.push({role:"user",content:[{type:"text",text:Ql}]}),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",A="",R="",S=(_,y)=>{if(typeof y!="string"){_.choices?.[0]?.delta&&Object.keys(_.choices[0].delta).length>0&&!_.choices[0].delta.content&&(_.choices[0].index=s,l.enqueue(u.encode(`data: ${JSON.stringify(_)}
308
+ Your final answer must follow after the closing tag above.`,OS=10,Da=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<OS)&&(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:Zl}):n.content=[{type:"text",text:Zl},{type:"text",text:n.content||""}]),n.role==="tool"&&e.messages.push({role:"user",content:[{type:"text",text:Zl}]}),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",A="",R="",S=(_,y)=>{if(typeof y!="string"){_.choices?.[0]?.delta&&Object.keys(_.choices[0].delta).length>0&&!_.choices[0].delta.content&&(_.choices[0].index=s,l.enqueue(u.encode(`data: ${JSON.stringify(_)}
310
310
 
311
311
  `)));return}let m=A+y;for(A="";m.length>0;)if(p==="SEARCHING"){let D=m.indexOf(r);if(D!==-1)m=m.substring(D+r.length),p="REASONING";else{for(let C=r.length-1;C>0;C--)if(m.endsWith(r.substring(0,C))){A=m.substring(m.length-C);break}m=""}}else if(p==="REASONING"){let D=m.indexOf(n);if(D!==-1){let C=m.substring(0,D);if(C.length>0){let x={..._.choices[0].delta,thinking:{content:C}};delete x.content;let $={..._,choices:[{..._.choices[0],delta:x,index:s}]};l.enqueue(u.encode(`data: ${JSON.stringify($)}
312
312
 
@@ -323,18 +323,19 @@ ${s.content}`),delete s.thinking)});let n=e.messages[e.messages.length-1];return
323
323
  `))}else l.enqueue(u.encode(C+`
324
324
  `))}}}catch(_){console.error("Stream error:",_),l.error(_)}finally{try{h.releaseLock()}catch(_){console.error("Error releasing reader lock:",_)}if(p==="REASONING"){let y={choices:[{delta:{thinking:{signature:new Date().getTime().toString()}}}]};l.enqueue(u.encode(`data: ${JSON.stringify(y)}
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 iy={AnthropicTransformer:qo,GeminiTransformer:$o,VertexGeminiTransformer:aa,VertexClaudeTransformer:ba,DeepseekTransformer:ua,TooluseTransformer:ca,OpenrouterTransformer:la,OpenAITransformer:Ea,MaxTokenTransformer:fa,GroqTransformer:da,CleancacheTransformer:ha,EnhanceToolTransformer:ma,ReasoningTransformer:ga,SamplingTransformer:ya,MaxCompletionTokens:_a,CerebrasTransformer:Ca,StreamOptionsTransformer:wa,CustomParamsTransformer:Aa,VercelTransformer:Sa,OpenAIResponsesTransformer:ka,ForceReasoningTransformer:Da};var ns=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})
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 Ta=class{static TransformerName="flattenMessage";name="flattenMessage";async transformRequestIn(e){return!e.messages||!Array.isArray(e.messages)||(e.messages=e.messages.map(r=>{if(typeof r.content=="string")return r;if(Array.isArray(r.content)){let n=[];r.content.forEach(i=>{i.type==="text"&&i.text?n.push(i.text):i.type==="image_url"&&i.image_url?.url?n.push(`[Image: ${i.image_url.url}]`):i.type==="image"&&i.source?i.source.type==="base64"?n.push(`[Image: ${i.source.media_type}]`):i.source.type==="url"&&n.push(`[Image: ${i.source.url}]`):i.type==="tool_result"&&(typeof i.content=="string"?n.push(i.content):i.content&&n.push(JSON.stringify(i.content)))});let s=n.join(`
327
+ `);return{...r,content:s||r.content}}return r})),e}};var ay={AnthropicTransformer:qo,GeminiTransformer:$o,VertexGeminiTransformer:aa,VertexClaudeTransformer:ba,DeepseekTransformer:ua,TooluseTransformer:ca,OpenrouterTransformer:la,OpenAITransformer:Ea,MaxTokenTransformer:fa,GroqTransformer:da,CleancacheTransformer:ha,EnhanceToolTransformer:ma,ReasoningTransformer:ga,SamplingTransformer:ya,MaxCompletionTokens:_a,CerebrasTransformer:Ca,StreamOptionsTransformer:wa,CustomParamsTransformer:Aa,VercelTransformer:Sa,OpenAIResponsesTransformer:ka,ForceReasoningTransformer:Da,FlattenMessageTransformer:Ta};var ns=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})
327
328
  error: ${r.message}
328
329
  stack: ${r.stack}`),!1}}async initialize(){try{await this.registerDefaultTransformersInternal(),await this.loadFromConfig()}catch(e){this.logger.error(`TransformerService init error: ${e.message}
329
- Stack: ${e.stack}`)}}async registerDefaultTransformersInternal(){try{Object.values(iy).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 OS}from"tiktoken";var Vs=class{type="tiktoken";name;encoding;constructor(e="cl100k_base"){this.name=`tiktoken-${e}`;try{this.encoding=OS(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 Oa}from"path";import{homedir as UD}from"os";import{existsSync as rf,mkdirSync as MD}from"fs";import{promises as Fa}from"fs";var FS=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}},xS=FS,PS=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}},IS=PS,hy=(()=>{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]]))})(),NS=t=>Object.fromEntries(Object.entries(t).map(([e,r])=>[r,e])),BS=NS(hy),ay=".,!?\u2026\u3002\uFF0C\u3001\u0964\u06D4\u060C",jS=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|[${ay}])]+`,` ?[^\\s${ay}]+`]]),Ks="\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E",LO=new RegExp(`^[${Ks}]+$`,"gu"),ef=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"),Ta=(t,e=!0)=>{if(t.Regex!==void 0){let r=t.Regex.replace(/\\([#&~])/g,"$1");for(let[n,s]of jS)r=r.replaceAll(n,s);return new RegExp(r,"gu")}else if(t.String!==void 0){let r=qS(t.String);return new RegExp(e?r:`(${r})`,"gu")}else return console.warn("Unknown pattern type:",t),null},qS=t=>t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),LS=(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},US=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,MS=t=>Number.isInteger(t)||typeof t=="bigint",$S=t=>{let e=0;for(let r of t)++e;return e},zS=t=>py(t.toLowerCase()),Ot=(...t)=>Array.prototype.concat.apply([],t),tf=t=>new Map(Object.entries(t)),HS=(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},py=t=>t.replace(new RegExp("\\p{M}","gu"),""),uy=(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},WS=t=>t.match(/\S+/g)||[],GS=class{constructor(){let t=function(...e){return t._call(...e)};return Object.setPrototypeOf(t,new.target.prototype)}},Ys=GS,JS=class extends Ys{constructor(t){super(),this.config=t}_call(t){return this.normalize(t)}},Er=JS,VS=class extends Er{tokenize_chinese_chars(t){let e=[];for(let r=0;r<t.length;++r){let n=t[r],s=n.charCodeAt(0);US(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`
330
- `: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}},KS=VS,YS=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}},XS=YS,QS=class extends Er{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)}},ZS=QS,ek=class extends Er{normalize(t){let e=Ta(this.config.pattern??{});return e===null?t:t.replaceAll(e,this.config.content??"")}},tk=ek,rk=class extends Er{constructor(){super(...arguments),this.form="NFC"}normalize(t){return t=t.normalize(this.form),t}},va=rk,nk=class extends va{constructor(){super(...arguments),this.form="NFC"}},sk=nk,ok=class extends va{constructor(){super(...arguments),this.form="NFD"}},ik=ok,ak=class extends va{constructor(){super(...arguments),this.form="NFKC"}},uk=ak,ck=class extends va{constructor(){super(...arguments),this.form="NFKD"}},lk=ck,fk=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}},dk=fk,hk=class extends Er{normalize(t){return py(t)}},pk=hk,mk=class extends Er{normalize(t){return t.toLowerCase()}},gk=mk,yk=class extends Er{normalize(t){return t=this.config.prepend+t,t}},_k=yk;function bk(t){if(t===null)return null;switch(t.type){case"BertNormalizer":return new KS(t);case"Precompiled":return new XS(t);case"Sequence":return new ZS(t);case"Replace":return new tk(t);case"NFC":return new sk(t);case"NFD":return new ik(t);case"NFKC":return new uk(t);case"NFKD":return new lk(t);case"Strip":return new dk(t);case"StripAccents":return new pk(t);case"Lowercase":return new gk(t);case"Prepend":return new _k(t);default:throw new Error(`Unknown Normalizer type: ${t.type}`)}}var my=bk,Ck=class extends Ys{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=Ck,wk=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=hy,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(""))}},Ek=wk,Ak=class extends sr{pre_tokenize_text(t,e){return t.match(/\w+|[^\w\s]+/g)||[]}},Sk=Ak,kk=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]}},Dk=kk,Tk=class extends sr{constructor(t){super(),this.config=t,this.pattern=Ta(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):HS(t,this.pattern)}},vk=Tk,Rk=class extends sr{constructor(t){super(),this.config=t,this.pattern=new RegExp(`[^${Ks}]+|[${Ks}]+`,"gu")}pre_tokenize_text(t){return t.match(this.pattern)||[]}},Ok=Rk,Fk=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)||[]}},xk=Fk,Pk=class extends sr{constructor(){super(),this.pattern=new RegExp(`[^\\s${Ks}]+|[${Ks}]`,"gu")}pre_tokenize_text(t,e){return t.trim().match(this.pattern)||[]}},Ik=Pk,Nk=class extends sr{constructor(t){super(),this.config=t,this.pattern=Ta(this.config.pattern??{}),this.content=this.config.content??""}pre_tokenize_text(t){return this.pattern===null?[t]:[t.replaceAll(this.pattern,this.config.content??"")]}},Bk=Nk,jk=class extends sr{constructor(t){super(),this.tokenizers=(t.pretokenizers??[]).map(e=>gy(e))}pre_tokenize_text(t,e){return this.tokenizers.reduce((r,n)=>n?n.pre_tokenize(r,e):r,[t])}},qk=jk,Lk=class extends sr{pre_tokenize_text(t){return WS(t)}},Uk=Lk;function Mk(t){if(t===null)return null;switch(t.type){case"BertPreTokenizer":return new Ik;case"Sequence":return new qk(t);case"Whitespace":return new Sk;case"WhitespaceSplit":return new Uk;case"Metaspace":return new Dk(t);case"ByteLevel":return new Ek(t);case"Split":return new vk(t);case"Punctuation":return new Ok(t);case"Digits":return new xk(t);case"Replace":return new Bk(t);default:throw new Error(`Unknown PreTokenizer type: ${t.type}`)}}var gy=Mk,$k=class extends Ys{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=LS(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)}},Ra=$k,zk=class extends Ra{constructor(t){super(t),this.max_input_chars_per_word=100,this.tokens_to_ids=tf(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}},cy=zk,ly=class yy{constructor(e,r){this.is_leaf=e,this.children=r}static default(){return new yy(!1,new Map)}},Hk=class{constructor(){this.root=ly.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=ly.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)}}},Wk=Hk,Zl=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}},Gk=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 Zl(this.bos_token_id??0,0,0,0,0),s=new Zl(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 Zl(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)}},Jk=Gk;function Vk(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 Kk=class extends Ra{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=Vk(this.scores)[0],this.unk_score=this.min_score-10,this.scores[this.unk_token_id]=this.unk_score,this.trie=new Wk,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=$S(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 Jk(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}},fy=Kk,Yk=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}},Xk=Yk,Qk=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()}},Zk=Qk,eD=class extends Ra{constructor(t){super(t),this.tokens_to_ids=tf(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 Zk(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 Xk((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}},dy=eD,tD=class extends Ra{constructor(t,e){super(t);let r=t.vocab;this.tokens_to_ids=tf(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}},rD=tD;function nD(t,e){switch(t.type){case"WordPiece":return new cy(t);case"Unigram":return new fy(t,e.eos_token);case"BPE":return new dy(t);default:if(t.vocab)return Array.isArray(t.vocab)?new fy(t,e.eos_token):Object.hasOwn(t,"continuing_subword_prefix")&&Object.hasOwn(t,"unk_token")?Object.hasOwn(t,"merges")?new dy(t):new cy(t):new rD(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 sD=nD,oD=class extends Ys{constructor(t){super(),this.config=t}_call(t,...e){return this.post_process(t,...e)}},Xs=oD,iD=class extends Xs{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}}},aD=iD,uD=class extends Xs{post_process(t,e=null){return{tokens:e?Ot(t,e):t}}},cD=uD,lD=class extends Xs{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}}},fD=lD,dD=class extends Xs{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}}},hD=dD,pD=class extends Xs{constructor(t){super(t),this.processors=(t.processors??[]).map(e=>by(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}},mD=pD;function gD(t){if(t===null)return null;switch(t.type){case"TemplateProcessing":return new aD(t);case"ByteLevel":return new cD(t);case"BertProcessing":return new fD(t);case"RobertaProcessing":return new hD(t);case"Sequence":return new mD(t);default:throw new Error(`Unknown PostProcessor type: ${t.type}`)}}var by=gD,yD=class extends Ys{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=yD,_D=class extends or{constructor(t){super(t),this.byte_decoder=BS,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}},bD=_D,CD=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=ef(e)),e})}},wD=CD,ED=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}},AD=ED,SD=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?"":" "))}},kD=SD,DD=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=ef(r).replaceAll(this.word_delimiter_token," ").trim()),r}decode_chain(t){return[this.convert_tokens_to_string(t)]}},TD=DD,vD=class extends or{constructor(t){super(t),this.decoders=(t.decoders??[]).map(e=>Cy(e))}decode_chain(t){return this.decoders.reduce((e,r)=>r.decode_chain(e),t)}},RD=vD,OD=class extends or{decode_chain(t){let e=Ta(this.config.pattern),r=this.config.content??"";return e===null?t:t.map(n=>n.replaceAll(e,r))}},FD=OD,xD=class extends or{decode_chain(t){return[t.join("")]}},PD=xD,ID=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)})}},ND=ID,BD=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}},jD=BD;function qD(t){if(t===null)return null;switch(t.type){case"ByteLevel":return new bD(t);case"WordPiece":return new wD(t);case"Metaspace":return new AD(t);case"BPEDecoder":return new kD(t);case"CTC":return new TD(t);case"Sequence":return new RD(t);case"Replace":return new FD(t);case"Fuse":return new PD(t);case"Strip":return new ND(t);case"ByteFallback":return new jD(t);default:throw new Error(`Unknown Decoder type: ${t.type}`)}}var Cy=qD,LD=class{constructor(t,e){let r=uy(t,"Tokenizer",["model","decoder","post_processor","pre_tokenizer","normalizer"]);if(r)throw new Error(r);let n=uy(e,"Config");if(n)throw new Error(n);this.tokenizer=t,this.config=e,this.normalizer=my(this.tokenizer.normalizer),this.pre_tokenizer=gy(this.tokenizer.pre_tokenizer),this.model=sD(this.tokenizer.model,this.config),this.post_processor=by(this.tokenizer.post_processor),this.decoder=Cy(this.tokenizer.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[],this.tokenizer.added_tokens.forEach(s=>{let i=new IS(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 xS(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||!MS(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=ef(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=zS(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}},wy=LD;var xa=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||Oa(UD(),".claude-code-router",".huggingface"),this.safeModelName=e.replace(/\//g,"_").replace(/[^a-zA-Z0-9_-]/g,"_"),this.name=`huggingface-${e.split("/").pop()}`}getCachePaths(){let e=Oa(this.cacheDir,this.safeModelName);return{modelDir:e,tokenizerJson:Oa(e,"tokenizer.json"),tokenizerConfig:Oa(e,"tokenizer_config.json")}}ensureDir(e){rf(e)||MD(e,{recursive:!0})}async loadFromCache(){try{let e=this.getCachePaths();if(!rf(e.tokenizerJson)||!rf(e.tokenizerConfig))return null;let[r,n]=await Promise.all([Fa.readFile(e.tokenizerJson,"utf-8"),Fa.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([Fa.writeFile(e.tokenizerJson,JSON.stringify(c,null,2)),Fa.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 Pa=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 ss=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 Vs("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 Vs(e.encoding||"cl100k_base");break;case"huggingface":this.logger?.info(`Initializing HuggingFace tokenizer for model: ${e.model}`),n=new xa(e.model,this.logger,{timeout:this.options.timeout});break;case"api":n=new Pa(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 $D}from"tiktoken";var nf=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())}},sf=new nf(100);import{readFile as of}from"fs/promises";import{opendir as zD,stat as HD}from"fs/promises";import{join as af}from"path";import{CLAUDE_PROJECTS_DIR as Ey,HOME_DIR as Ay}from"@CCR/shared";import{LRUCache as WD}from"lru-cache";var Ar=$D("cl100k_base"),Sy=(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},GD=async(t,e)=>{if(t.sessionId){let r=await ky(t.sessionId);if(r){let n=af(Ay,r,"config.json"),s=af(Ay,r,`${t.sessionId}.json`);try{let i=JSON.parse(await of(s,"utf8"));if(i&&i.Router)return i.Router}catch{}try{let i=JSON.parse(await of(n,"utf8"));if(i&&i.Router)return i.Router}catch{}}}},JD=async(t,e,r,n)=>{let s=await GD(t,r),i=r.get("providers")||[],u=s||r.get("Router");if(t.body.model.includes(",")){let[p,A]=t.body.model.split(","),R=i.find(_=>_.name.toLowerCase()===p),S=R?.models?.find(_=>_.toLowerCase()===A);return R&&S?{model:`${R.name},${S}`,scenarioType:"default"}:{model:t.body.model,scenarioType:"default"}}let c=u?.longContextThreshold||6e4,l=n&&n.input_tokens>c&&e>2e4,h=e>c;if((l||h)&&u?.longContext)return t.log.info(`Using long context model due to token count: ${e}, threshold: ${c}`),{model:u.longContext,scenarioType:"longContext"};if(t.body?.system?.length>1&&t.body?.system[1]?.text?.startsWith("<CCR-SUBAGENT-MODEL>")){let p=t.body?.system[1].text.match(/<CCR-SUBAGENT-MODEL>(.*?)<\/CCR-SUBAGENT-MODEL>/s);if(p)return t.body.system[1].text=t.body.system[1].text.replace(`<CCR-SUBAGENT-MODEL>${p[1]}</CCR-SUBAGENT-MODEL>`,""),{model:p[1],scenarioType:"default"}}let d=r.get("Router");return t.body.model?.includes("claude")&&t.body.model?.includes("haiku")&&d?.background?(t.log.info(`Using background model for ${t.body.model}`),{model:d.background,scenarioType:"background"}):Array.isArray(t.body.tools)&&t.body.tools.some(p=>p.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"}},uf=async(t,e,r)=>{let{configService:n,event:s}=r;if(t.body.metadata?.user_id){let d=t.body.metadata.user_id.split("_session_");d.length>1&&(t.sessionId=d[1])}let i=sf.get(t.sessionId),{messages:u,system:c=[],tools:l}=t.body,h=n.get("REWRITE_SYSTEM_PROMPT");if(h&&c.length>1&&c[1]?.text?.includes("<env>")){let d=await of(h,"utf-8");c[1].text=`${d}<env>${c[1].text.split("<env>").pop()}`}try{let[d,p]=t.body.model.split(","),A=r.tokenizerService?.getTokenizerConfigForModel(d,p),R;r.tokenizerService?R=(await r.tokenizerService.countTokens({messages:u,system:c,tools:l},A)).tokenCount:R=Sy(u,c,l);let S,_=n.get("CUSTOM_ROUTER_PATH");if(_)try{let y=X(_);t.tokenCount=R,S=await y(t,n.getAll(),{event:s})}catch(y){t.log.error(`failed to load custom router: ${y.message}`)}if(S)t.scenarioType="default";else{let y=await JD(t,R,n,i);S=y.model,t.scenarioType=y.scenarioType}t.body.model=S}catch(d){t.log.error(`Error in router middleware: ${d.message}`);let p=n.get("Router");t.body.model=p?.default,t.scenarioType="default"}},Qs=new WD({max:1e3}),ky=async t=>{if(Qs.has(t)){let e=Qs.get(t);return!e||e===""?null:e}try{let e=await zD(Ey),r=[];for await(let i of e)i.isDirectory()&&r.push(i.name);let n=r.map(async i=>{let u=af(Ey,i,`${t}.jsonl`);try{return(await HD(u)).isFile()?i:null}catch{return null}}),s=await Promise.all(n);for(let i of s)if(i)return Qs.set(t,i),i;return Qs.set(t,""),null}catch(e){return console.error("Error searching for project by session:",e),Qs.set(t,""),null}};var cf=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()}},Dy=new cf;var By=xr(Fy(),1);var os=class extends TransformStream{buffer="";currentEvent={};constructor(){super({transform:(e,r)=>{this.buffer+=e;let n=this.buffer.split(`
331
- `);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 Na=class extends TransformStream{constructor(){super({transform:(e,r)=>{let n="";e.event&&(n+=`event: ${e.event}
330
+ Stack: ${e.stack}`)}}async registerDefaultTransformersInternal(){try{Object.values(ay).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 FS}from"tiktoken";var Vs=class{type="tiktoken";name;encoding;constructor(e="cl100k_base"){this.name=`tiktoken-${e}`;try{this.encoding=FS(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 Fa}from"path";import{homedir as MD}from"os";import{existsSync as nf,mkdirSync as $D}from"fs";import{promises as xa}from"fs";var xS=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}},PS=xS,IS=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}},NS=IS,py=(()=>{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]]))})(),BS=t=>Object.fromEntries(Object.entries(t).map(([e,r])=>[r,e])),jS=BS(py),uy=".,!?\u2026\u3002\uFF0C\u3001\u0964\u06D4\u060C",qS=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|[${uy}])]+`,` ?[^\\s${uy}]+`]]),Ks="\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E",$O=new RegExp(`^[${Ks}]+$`,"gu"),tf=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"),va=(t,e=!0)=>{if(t.Regex!==void 0){let r=t.Regex.replace(/\\([#&~])/g,"$1");for(let[n,s]of qS)r=r.replaceAll(n,s);return new RegExp(r,"gu")}else if(t.String!==void 0){let r=LS(t.String);return new RegExp(e?r:`(${r})`,"gu")}else return console.warn("Unknown pattern type:",t),null},LS=t=>t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),US=(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},MS=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,$S=t=>Number.isInteger(t)||typeof t=="bigint",zS=t=>{let e=0;for(let r of t)++e;return e},HS=t=>my(t.toLowerCase()),Ot=(...t)=>Array.prototype.concat.apply([],t),rf=t=>new Map(Object.entries(t)),WS=(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},my=t=>t.replace(new RegExp("\\p{M}","gu"),""),cy=(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},GS=t=>t.match(/\S+/g)||[],JS=class{constructor(){let t=function(...e){return t._call(...e)};return Object.setPrototypeOf(t,new.target.prototype)}},Ys=JS,VS=class extends Ys{constructor(t){super(),this.config=t}_call(t){return this.normalize(t)}},Er=VS,KS=class extends Er{tokenize_chinese_chars(t){let e=[];for(let r=0;r<t.length;++r){let n=t[r],s=n.charCodeAt(0);MS(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`
331
+ `: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}},YS=KS,XS=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}},QS=XS,ZS=class extends Er{constructor(t){super(t),this.normalizers=(t.normalizers??[]).map(e=>gy(e))}normalize(t){return this.normalizers.reduce((e,r)=>r?r.normalize(e):e,t)}},ek=ZS,tk=class extends Er{normalize(t){let e=va(this.config.pattern??{});return e===null?t:t.replaceAll(e,this.config.content??"")}},rk=tk,nk=class extends Er{constructor(){super(...arguments),this.form="NFC"}normalize(t){return t=t.normalize(this.form),t}},Ra=nk,sk=class extends Ra{constructor(){super(...arguments),this.form="NFC"}},ok=sk,ik=class extends Ra{constructor(){super(...arguments),this.form="NFD"}},ak=ik,uk=class extends Ra{constructor(){super(...arguments),this.form="NFKC"}},ck=uk,lk=class extends Ra{constructor(){super(...arguments),this.form="NFKD"}},fk=lk,dk=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}},hk=dk,pk=class extends Er{normalize(t){return my(t)}},mk=pk,gk=class extends Er{normalize(t){return t.toLowerCase()}},yk=gk,_k=class extends Er{normalize(t){return t=this.config.prepend+t,t}},bk=_k;function Ck(t){if(t===null)return null;switch(t.type){case"BertNormalizer":return new YS(t);case"Precompiled":return new QS(t);case"Sequence":return new ek(t);case"Replace":return new rk(t);case"NFC":return new ok(t);case"NFD":return new ak(t);case"NFKC":return new ck(t);case"NFKD":return new fk(t);case"Strip":return new hk(t);case"StripAccents":return new mk(t);case"Lowercase":return new yk(t);case"Prepend":return new bk(t);default:throw new Error(`Unknown Normalizer type: ${t.type}`)}}var gy=Ck,wk=class extends Ys{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=wk,Ek=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=py,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(""))}},Ak=Ek,Sk=class extends sr{pre_tokenize_text(t,e){return t.match(/\w+|[^\w\s]+/g)||[]}},kk=Sk,Dk=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]}},Tk=Dk,vk=class extends sr{constructor(t){super(),this.config=t,this.pattern=va(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):WS(t,this.pattern)}},Rk=vk,Ok=class extends sr{constructor(t){super(),this.config=t,this.pattern=new RegExp(`[^${Ks}]+|[${Ks}]+`,"gu")}pre_tokenize_text(t){return t.match(this.pattern)||[]}},Fk=Ok,xk=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)||[]}},Pk=xk,Ik=class extends sr{constructor(){super(),this.pattern=new RegExp(`[^\\s${Ks}]+|[${Ks}]`,"gu")}pre_tokenize_text(t,e){return t.trim().match(this.pattern)||[]}},Nk=Ik,Bk=class extends sr{constructor(t){super(),this.config=t,this.pattern=va(this.config.pattern??{}),this.content=this.config.content??""}pre_tokenize_text(t){return this.pattern===null?[t]:[t.replaceAll(this.pattern,this.config.content??"")]}},jk=Bk,qk=class extends sr{constructor(t){super(),this.tokenizers=(t.pretokenizers??[]).map(e=>yy(e))}pre_tokenize_text(t,e){return this.tokenizers.reduce((r,n)=>n?n.pre_tokenize(r,e):r,[t])}},Lk=qk,Uk=class extends sr{pre_tokenize_text(t){return GS(t)}},Mk=Uk;function $k(t){if(t===null)return null;switch(t.type){case"BertPreTokenizer":return new Nk;case"Sequence":return new Lk(t);case"Whitespace":return new kk;case"WhitespaceSplit":return new Mk;case"Metaspace":return new Tk(t);case"ByteLevel":return new Ak(t);case"Split":return new Rk(t);case"Punctuation":return new Fk(t);case"Digits":return new Pk(t);case"Replace":return new jk(t);default:throw new Error(`Unknown PreTokenizer type: ${t.type}`)}}var yy=$k,zk=class extends Ys{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=US(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)}},Oa=zk,Hk=class extends Oa{constructor(t){super(t),this.max_input_chars_per_word=100,this.tokens_to_ids=rf(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}},ly=Hk,fy=class _y{constructor(e,r){this.is_leaf=e,this.children=r}static default(){return new _y(!1,new Map)}},Wk=class{constructor(){this.root=fy.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=fy.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)}}},Gk=Wk,ef=class by{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 by(this.token_id,this.node_id,this.pos,this.length,this.score);return e.prev=this.prev,e.backtrace_score=this.backtrace_score,e}},Jk=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 ef(this.bos_token_id??0,0,0,0,0),s=new ef(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 ef(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)}},Vk=Jk;function Kk(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 Yk=class extends Oa{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=Kk(this.scores)[0],this.unk_score=this.min_score-10,this.scores[this.unk_token_id]=this.unk_score,this.trie=new Gk,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=zS(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 Vk(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}},dy=Yk,Xk=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}},Qk=Xk,Zk=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()}},eD=Zk,tD=class extends Oa{constructor(t){super(t),this.tokens_to_ids=rf(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 eD(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 Qk((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}},hy=tD,rD=class extends Oa{constructor(t,e){super(t);let r=t.vocab;this.tokens_to_ids=rf(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}},nD=rD;function sD(t,e){switch(t.type){case"WordPiece":return new ly(t);case"Unigram":return new dy(t,e.eos_token);case"BPE":return new hy(t);default:if(t.vocab)return Array.isArray(t.vocab)?new dy(t,e.eos_token):Object.hasOwn(t,"continuing_subword_prefix")&&Object.hasOwn(t,"unk_token")?Object.hasOwn(t,"merges")?new hy(t):new ly(t):new nD(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 oD=sD,iD=class extends Ys{constructor(t){super(),this.config=t}_call(t,...e){return this.post_process(t,...e)}},Xs=iD,aD=class extends Xs{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}}},uD=aD,cD=class extends Xs{post_process(t,e=null){return{tokens:e?Ot(t,e):t}}},lD=cD,fD=class extends Xs{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}}},dD=fD,hD=class extends Xs{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}}},pD=hD,mD=class extends Xs{constructor(t){super(t),this.processors=(t.processors??[]).map(e=>Cy(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}},gD=mD;function yD(t){if(t===null)return null;switch(t.type){case"TemplateProcessing":return new uD(t);case"ByteLevel":return new lD(t);case"BertProcessing":return new dD(t);case"RobertaProcessing":return new pD(t);case"Sequence":return new gD(t);default:throw new Error(`Unknown PostProcessor type: ${t.type}`)}}var Cy=yD,_D=class extends Ys{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=_D,bD=class extends or{constructor(t){super(t),this.byte_decoder=jS,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}},CD=bD,wD=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=tf(e)),e})}},ED=wD,AD=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}},SD=AD,kD=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?"":" "))}},DD=kD,TD=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=tf(r).replaceAll(this.word_delimiter_token," ").trim()),r}decode_chain(t){return[this.convert_tokens_to_string(t)]}},vD=TD,RD=class extends or{constructor(t){super(t),this.decoders=(t.decoders??[]).map(e=>wy(e))}decode_chain(t){return this.decoders.reduce((e,r)=>r.decode_chain(e),t)}},OD=RD,FD=class extends or{decode_chain(t){let e=va(this.config.pattern),r=this.config.content??"";return e===null?t:t.map(n=>n.replaceAll(e,r))}},xD=FD,PD=class extends or{decode_chain(t){return[t.join("")]}},ID=PD,ND=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)})}},BD=ND,jD=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}},qD=jD;function LD(t){if(t===null)return null;switch(t.type){case"ByteLevel":return new CD(t);case"WordPiece":return new ED(t);case"Metaspace":return new SD(t);case"BPEDecoder":return new DD(t);case"CTC":return new vD(t);case"Sequence":return new OD(t);case"Replace":return new xD(t);case"Fuse":return new ID(t);case"Strip":return new BD(t);case"ByteFallback":return new qD(t);default:throw new Error(`Unknown Decoder type: ${t.type}`)}}var wy=LD,UD=class{constructor(t,e){let r=cy(t,"Tokenizer",["model","decoder","post_processor","pre_tokenizer","normalizer"]);if(r)throw new Error(r);let n=cy(e,"Config");if(n)throw new Error(n);this.tokenizer=t,this.config=e,this.normalizer=gy(this.tokenizer.normalizer),this.pre_tokenizer=yy(this.tokenizer.pre_tokenizer),this.model=oD(this.tokenizer.model,this.config),this.post_processor=Cy(this.tokenizer.post_processor),this.decoder=wy(this.tokenizer.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[],this.tokenizer.added_tokens.forEach(s=>{let i=new NS(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 PS(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||!$S(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=tf(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=HS(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}},Ey=UD;var Pa=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||Fa(MD(),".claude-code-router",".huggingface"),this.safeModelName=e.replace(/\//g,"_").replace(/[^a-zA-Z0-9_-]/g,"_"),this.name=`huggingface-${e.split("/").pop()}`}getCachePaths(){let e=Fa(this.cacheDir,this.safeModelName);return{modelDir:e,tokenizerJson:Fa(e,"tokenizer.json"),tokenizerConfig:Fa(e,"tokenizer_config.json")}}ensureDir(e){nf(e)||$D(e,{recursive:!0})}async loadFromCache(){try{let e=this.getCachePaths();if(!nf(e.tokenizerJson)||!nf(e.tokenizerConfig))return null;let[r,n]=await Promise.all([xa.readFile(e.tokenizerJson,"utf-8"),xa.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([xa.writeFile(e.tokenizerJson,JSON.stringify(c,null,2)),xa.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 Ey(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 Ia=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 ss=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 Vs("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 Vs(e.encoding||"cl100k_base");break;case"huggingface":this.logger?.info(`Initializing HuggingFace tokenizer for model: ${e.model}`),n=new Pa(e.model,this.logger,{timeout:this.options.timeout});break;case"api":n=new Ia(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 zD}from"tiktoken";var sf=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())}},of=new sf(100);import{readFile as af}from"fs/promises";import{opendir as HD,stat as WD}from"fs/promises";import{join as uf}from"path";import{CLAUDE_PROJECTS_DIR as Ay,HOME_DIR as Sy}from"@CCR/shared";import{LRUCache as GD}from"lru-cache";var Ar=zD("cl100k_base"),ky=(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},JD=async(t,e)=>{if(t.sessionId){let r=await Dy(t.sessionId);if(r){let n=uf(Sy,r,"config.json"),s=uf(Sy,r,`${t.sessionId}.json`);try{let i=JSON.parse(await af(s,"utf8"));if(i&&i.Router)return i.Router}catch{}try{let i=JSON.parse(await af(n,"utf8"));if(i&&i.Router)return i.Router}catch{}}}},VD=async(t,e,r,n)=>{let s=await JD(t,r),i=r.get("providers")||[],u=s||r.get("Router");if(t.body.model.includes(",")){let[p,A]=t.body.model.split(","),R=i.find(_=>_.name.toLowerCase()===p),S=R?.models?.find(_=>_.toLowerCase()===A);return R&&S?{model:`${R.name},${S}`,scenarioType:"default"}:{model:t.body.model,scenarioType:"default"}}let c=u?.longContextThreshold||6e4,l=n&&n.input_tokens>c&&e>2e4,h=e>c;if((l||h)&&u?.longContext)return t.log.info(`Using long context model due to token count: ${e}, threshold: ${c}`),{model:u.longContext,scenarioType:"longContext"};if(t.body?.system?.length>1&&t.body?.system[1]?.text?.startsWith("<CCR-SUBAGENT-MODEL>")){let p=t.body?.system[1].text.match(/<CCR-SUBAGENT-MODEL>(.*?)<\/CCR-SUBAGENT-MODEL>/s);if(p)return t.body.system[1].text=t.body.system[1].text.replace(`<CCR-SUBAGENT-MODEL>${p[1]}</CCR-SUBAGENT-MODEL>`,""),{model:p[1],scenarioType:"default"}}let d=r.get("Router");return t.body.model?.includes("claude")&&t.body.model?.includes("haiku")&&d?.background?(t.log.info(`Using background model for ${t.body.model}`),{model:d.background,scenarioType:"background"}):Array.isArray(t.body.tools)&&t.body.tools.some(p=>p.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"}},cf=async(t,e,r)=>{let{configService:n,event:s}=r;if(t.body.metadata?.user_id){let d=t.body.metadata.user_id.split("_session_");d.length>1&&(t.sessionId=d[1])}let i=of.get(t.sessionId),{messages:u,system:c=[],tools:l}=t.body,h=n.get("REWRITE_SYSTEM_PROMPT");if(h&&c.length>1&&c[1]?.text?.includes("<env>")){let d=await af(h,"utf-8");c[1].text=`${d}<env>${c[1].text.split("<env>").pop()}`}try{let[d,p]=t.body.model.split(","),A=r.tokenizerService?.getTokenizerConfigForModel(d,p),R;r.tokenizerService?R=(await r.tokenizerService.countTokens({messages:u,system:c,tools:l},A)).tokenCount:R=ky(u,c,l);let S,_=n.get("CUSTOM_ROUTER_PATH");if(_)try{let y=X(_);t.tokenCount=R,S=await y(t,n.getAll(),{event:s})}catch(y){t.log.error(`failed to load custom router: ${y.message}`)}if(S)t.scenarioType="default";else{let y=await VD(t,R,n,i);S=y.model,t.scenarioType=y.scenarioType}t.body.model=S}catch(d){t.log.error(`Error in router middleware: ${d.message}`);let p=n.get("Router");t.body.model=p?.default,t.scenarioType="default"}},Qs=new GD({max:1e3}),Dy=async t=>{if(Qs.has(t)){let e=Qs.get(t);return!e||e===""?null:e}try{let e=await HD(Ay),r=[];for await(let i of e)i.isDirectory()&&r.push(i.name);let n=r.map(async i=>{let u=uf(Ay,i,`${t}.jsonl`);try{return(await WD(u)).isFile()?i:null}catch{return null}}),s=await Promise.all(n);for(let i of s)if(i)return Qs.set(t,i),i;return Qs.set(t,""),null}catch(e){return console.error("Error searching for project by session:",e),Qs.set(t,""),null}};var lf=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()}},Ty=new lf;var jy=xr(xy(),1);var os=class extends TransformStream{buffer="";currentEvent={};constructor(){super({transform:(e,r)=>{this.buffer+=e;let n=this.buffer.split(`
332
+ `);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 Ba=class extends TransformStream{constructor(){super({transform:(e,r)=>{let n="";e.event&&(n+=`event: ${e.event}
332
333
  `),e.id&&(n+=`id: ${e.id}
333
334
  `),e.retry&&(n+=`retry: ${e.retry}
334
335
  `),e.data&&(e.data.type==="done"?n+=`data: [DONE]
335
336
  `:n+=`data: ${JSON.stringify(e.data)}
336
337
  `),n+=`
337
- `,r.enqueue(n)}})}};var xy=(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()}}})};df();hf();pf();Iy();var ro=new Map,gf=new Map,jy={name:"token-speed",version:"1.0.0",description:"Statistics for streaming response token generation speed",register:(0,By.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)is.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&&is.registerHandlers(i)}r.outputOptions&&is.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(gf.has(h))return gf.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 gf.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 S=i.body?.metadata?.user_id;if(S&&typeof S=="string"){let _=S.match(/_session_([a-f0-9-]+)/i);d=_?_[1]:void 0}}catch{}if(!d)return;let p=await s(i);if(c instanceof ReadableStream){ro.set(h,{requestId:h,sessionId:d,startTime:l,lastTokenTime:l,tokenCount:0,tokensPerSecond:0,tokenTimestamps:[],stream:!0});let[S,_]=c.tee();return(async()=>{let m=null,D=async C=>{let E=ro.get(h);if(!E)return;let v=performance.now();if(C){let x=(E.lastTokenTime-E.startTime)/1e3;x>0&&(E.tokensPerSecond=Math.round(E.tokenCount/x))}else{let x=v-1e3;E.tokenTimestamps=E.tokenTimestamps.filter($=>$>x),E.tokensPerSecond=E.tokenTimestamps.length}await Ny(E,n,r.outputOptions,C).catch(x=>{t.log?.warn(`Failed to output streaming stats: ${x.message}`)})};try{let E=_.pipeThrough(new TextDecoderStream).pipeThrough(new os).getReader();for(m=setInterval(async()=>{ro.get(h)&&await D(!1)},1e3);;){let{done:v,value:x}=await E.read();if(v)break;let $=x,V=ro.get(h);if(!V)continue;let U=performance.now();if(!V.firstTokenTime&&($.event==="content_block_start"||$.event==="content_block_delta"||$.event==="text_block"||$.event==="content_block")&&(V.firstTokenTime=U,V.timeToFirstToken=Math.round(U-V.startTime)),$.event==="content_block_delta"&&$.data?.delta){let Q=$.data.delta.type,ne="";if(Q==="text_delta"?ne=$.data.delta.text||"":Q==="input_json_delta"?ne=$.data.delta.partial_json||"":Q==="thinking_delta"&&(ne=$.data.delta.thinking||""),ne){let ae=p&&p.encodeText?p.encodeText(ne).length:no(ne);V.tokenCount+=ae,V.lastTokenTime=U;for(let fe=0;fe<ae;fe++)V.tokenTimestamps.push(U)}}$.event==="message_stop"&&(m&&(clearInterval(m),m=null),await D(!0),ro.delete(h))}}catch(C){m&&clearInterval(m),C.name!=="AbortError"&&C.code!=="ERR_STREAM_PREMATURE_CLOSE"&&t.log?.warn(`Error processing token stats: ${C.message}`)}})().catch(m=>{console.log(m),t.log?.warn(`Background stats processing failed: ${m.message}`)}),S}let A=performance.now(),R=0;if(c&&typeof c=="string")try{let S=JSON.parse(c);if(S.usage?.output_tokens)R=S.usage.output_tokens;else{let _=S.content||S.message?.content||"";if(p)Array.isArray(_)?R=_.reduce((y,m)=>{if(m.type==="text"){let D=m.text||"";return y+(p.encodeText?p.encodeText(D).length:no(D))}return y},0):typeof _=="string"&&(R=p.encodeText?p.encodeText(_).length:no(_));else{let y=Array.isArray(_)?_.map(m=>m.text).join(""):_;R=no(y)}}}catch{}if(R>0){let S=(A-l)/1e3,_={requestId:h,sessionId:d,startTime:l,lastTokenTime:A,tokenCount:R,tokensPerSecond:S>0?Math.round(R/S):0,timeToFirstToken:Math.round(A-l),stream:!1,tokenTimestamps:[]};await Ny(_,n,r.outputOptions,!0)}return c})})};function no(t){let e=(t.match(/[\u4e00-\u9fa5]/g)||[]).length,r=t.length-e;return Math.ceil(e/1.5+r/4)}async function Ny(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 is.outputToType(c,i,u)}catch(l){console.error(`[TokenSpeedPlugin] Failed to output to ${c}:`,l)}}function oT(t={}){let e=nT({bodyLimit:52428800,...t});return e.setErrorHandler(Id),e.register(sT),e}var yf=class{app;configService;providerService;transformerService;tokenizerService;constructor(e={}){let{initialConfig:r,...n}=e;this.app=oT({...n,logger:n.logger??!0}),this.configService=new kn(e),this.transformerService=new ns(this.configService,this.app.log),this.tokenizerService=new ss(this.configService,this.app.log),this.transformerService.initialize().finally(()=>{this.providerService=new Dn(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 uf(l,h,{configService:this.configService,tokenizerService:this.tokenizerService})}),await bu(c)});return}if(!r)throw new Error("options is required");let n=new kn({initialConfig:{providers:r.Providers,Router:r.Router}}),s=new ns(n,this.app.log);await s.initialize();let i=new Dn(n,s,this.app.log),u=new ss(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 uf(l,h,{configService:n,tokenizerService:u})}),await bu(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}`);let r=async n=>{this.app.log.info(`Received ${n}, shutting down gracefully...`),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)}}},xP=yf;export{kn as ConfigService,Dn as ProviderService,os as SSEParserTransform,Na as SSESerializerTransform,ss as TokenizerService,ns as TransformerService,Sy as calculateTokenCount,xP as default,Dy as pluginManager,xy as rewriteStream,uf as router,ky as searchProjectBySession,sf as sessionUsageCache,jy as tokenSpeedPlugin};
338
+ `,r.enqueue(n)}})}};var Py=(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()}}})};hf();pf();mf();Ny();var ro=new Map,yf=new Map,qy={name:"token-speed",version:"1.0.0",description:"Statistics for streaming response token generation speed",register:(0,jy.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)is.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&&is.registerHandlers(i)}r.outputOptions&&is.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(yf.has(h))return yf.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 yf.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 S=i.body?.metadata?.user_id;if(S&&typeof S=="string"){let _=S.match(/_session_([a-f0-9-]+)/i);d=_?_[1]:void 0}}catch{}if(!d)return;let p=await s(i);if(c instanceof ReadableStream){ro.set(h,{requestId:h,sessionId:d,startTime:l,lastTokenTime:l,tokenCount:0,tokensPerSecond:0,tokenTimestamps:[],stream:!0});let[S,_]=c.tee();return(async()=>{let m=null,D=async C=>{let E=ro.get(h);if(!E)return;let v=performance.now();if(C){let x=(E.lastTokenTime-E.startTime)/1e3;x>0&&(E.tokensPerSecond=Math.round(E.tokenCount/x))}else{let x=v-1e3;E.tokenTimestamps=E.tokenTimestamps.filter($=>$>x),E.tokensPerSecond=E.tokenTimestamps.length}await By(E,n,r.outputOptions,C).catch(x=>{t.log?.warn(`Failed to output streaming stats: ${x.message}`)})};try{let E=_.pipeThrough(new TextDecoderStream).pipeThrough(new os).getReader();for(m=setInterval(async()=>{ro.get(h)&&await D(!1)},1e3);;){let{done:v,value:x}=await E.read();if(v)break;let $=x,V=ro.get(h);if(!V)continue;let U=performance.now();if(!V.firstTokenTime&&($.event==="content_block_start"||$.event==="content_block_delta"||$.event==="text_block"||$.event==="content_block")&&(V.firstTokenTime=U,V.timeToFirstToken=Math.round(U-V.startTime)),$.event==="content_block_delta"&&$.data?.delta){let Q=$.data.delta.type,ne="";if(Q==="text_delta"?ne=$.data.delta.text||"":Q==="input_json_delta"?ne=$.data.delta.partial_json||"":Q==="thinking_delta"&&(ne=$.data.delta.thinking||""),ne){let ae=p&&p.encodeText?p.encodeText(ne).length:no(ne);V.tokenCount+=ae,V.lastTokenTime=U;for(let fe=0;fe<ae;fe++)V.tokenTimestamps.push(U)}}$.event==="message_stop"&&(m&&(clearInterval(m),m=null),await D(!0),ro.delete(h))}}catch(C){m&&clearInterval(m),C.name!=="AbortError"&&C.code!=="ERR_STREAM_PREMATURE_CLOSE"&&t.log?.warn(`Error processing token stats: ${C.message}`)}})().catch(m=>{console.log(m),t.log?.warn(`Background stats processing failed: ${m.message}`)}),S}let A=performance.now(),R=0;if(c&&typeof c=="string")try{let S=JSON.parse(c);if(S.usage?.output_tokens)R=S.usage.output_tokens;else{let _=S.content||S.message?.content||"";if(p)Array.isArray(_)?R=_.reduce((y,m)=>{if(m.type==="text"){let D=m.text||"";return y+(p.encodeText?p.encodeText(D).length:no(D))}return y},0):typeof _=="string"&&(R=p.encodeText?p.encodeText(_).length:no(_));else{let y=Array.isArray(_)?_.map(m=>m.text).join(""):_;R=no(y)}}}catch{}if(R>0){let S=(A-l)/1e3,_={requestId:h,sessionId:d,startTime:l,lastTokenTime:A,tokenCount:R,tokensPerSecond:S>0?Math.round(R/S):0,timeToFirstToken:Math.round(A-l),stream:!1,tokenTimestamps:[]};await By(_,n,r.outputOptions,!0)}return c})})};function no(t){let e=(t.match(/[\u4e00-\u9fa5]/g)||[]).length,r=t.length-e;return Math.ceil(e/1.5+r/4)}async function By(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 is.outputToType(c,i,u)}catch(l){console.error(`[TokenSpeedPlugin] Failed to output to ${c}:`,l)}}function iT(t={}){let e=sT({bodyLimit:52428800,...t});return e.setErrorHandler(Nd),e.register(oT),e}var _f=class{app;configService;providerService;transformerService;tokenizerService;constructor(e={}){let{initialConfig:r,...n}=e;this.app=iT({...n,logger:n.logger??!0}),this.configService=new kn(e),this.transformerService=new ns(this.configService,this.app.log),this.tokenizerService=new ss(this.configService,this.app.log),this.transformerService.initialize().finally(()=>{this.providerService=new Dn(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 cf(l,h,{configService:this.configService,tokenizerService:this.tokenizerService})}),await Cu(c)});return}if(!r)throw new Error("options is required");let n=new kn({initialConfig:{providers:r.Providers,Router:r.Router}}),s=new ns(n,this.app.log);await s.initialize();let i=new Dn(n,s,this.app.log),u=new ss(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 cf(l,h,{configService:n,tokenizerService:u})}),await Cu(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}`);let r=async n=>{this.app.log.info(`Received ${n}, shutting down gracefully...`),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)}}},NP=_f;export{kn as ConfigService,Dn as ProviderService,os as SSEParserTransform,Ba as SSESerializerTransform,ss as TokenizerService,ns as TransformerService,ky as calculateTokenCount,NP as default,Ty as pluginManager,Py as rewriteStream,cf as router,Dy as searchProjectBySession,of as sessionUsageCache,qy as tokenSpeedPlugin};
338
339
  /*! Bundled license information:
339
340
 
340
341
  web-streams-polyfill/dist/ponyfill.es2018.js: